iOS小視頻錄制(類似微信)

前言:前一段時(shí)間產(chǎn)品新需求,說是要做微信的小時(shí)頻功能.
功能需求:360x640 or 640x360的分辨率,大小在2MB 之內(nèi)的 MP4格式
短視頻 demo 地址
思路:使用 AVFoundtion框架提供的 AVCaptureSession進(jìn)行錄制,
大致如下:
攝像頭,麥克風(fēng)(input)->AVCapture Session->AVCaptureVideoDataOutpu(僅視頻數(shù)據(jù),無音頻數(shù)據(jù))t,AVCaptureAudioDataOutput(音頻數(shù)據(jù)),AVCaptureStillImageOutput(照片),AVCaptureMovieFileOutput(有視頻,也有音頻)->AVAssetWriter封裝視頻和音頻格式,寫入磁盤,完成錄制

關(guān)系圖.jpg

1.AVCaptureDeviceInput(輸入設(shè)備):包括攝像頭(前置,后置),麥克風(fēng),負(fù)責(zé)采集視頻和音頻數(shù)據(jù)
2.AVCaptureVideoDataOutpu:輸出視頻數(shù)據(jù),僅僅只是視頻,沒有聲音,可以對視頻格式和參數(shù)進(jìn)行自定義封裝和添加濾鏡處理
3.AVCaptureAudioDataOutput:輸出音頻數(shù)據(jù),可以對格式和參數(shù)進(jìn)行自定義封裝
4.AVCaptureStillImageOutput:照片數(shù)據(jù),用戶獲取靜態(tài)圖像(拍照)
5.AVCaptureMovieFileOutput:輸出完整視頻(包括音頻),優(yōu)點(diǎn):錄制簡單,缺點(diǎn):可定制性差,短視頻不適用(體積太大)
6.AVCapture Session:用于處理輸入與輸出之間的數(shù)據(jù)流
7.AVCaptureVideoPreviewLayer:攝像頭實(shí)時(shí)預(yù)覽 layer, 可以預(yù)覽攝像頭采集的實(shí)時(shí)視頻信息
8.AVAssetWriter:封裝音視頻格式,寫入磁盤

代碼示例:

1.錄制:

- (AVCaptureSession *)recordSession {
    if (_recordSession == nil) {
        _recordSession = [[AVCaptureSession alloc] init];
        _recordSession.sessionPreset = AVCaptureSessionPresetHigh;
        //添加后置攝像頭的輸出
        if ([_recordSession canAddInput:self.backCameraInput]) {
            [_recordSession addInput:self.backCameraInput];
        }
        //添加后置麥克風(fēng)的輸出
        if ([_recordSession canAddInput:self.audioMicInput]) {
            [_recordSession addInput:self.audioMicInput];
        }
        //添加視頻輸出
        if ([_recordSession canAddOutput:self.videoOutput]) {
            [_recordSession addOutput:self.videoOutput];
            _cx = VIDEO_WIDTH;
            _cy = VIDEO_HEIGHT;
        }
        //添加音頻輸出
        if ([_recordSession canAddOutput:self.audioOutput]) {
            [_recordSession addOutput:self.audioOutput];
        }
        // 靜態(tài)圖像輸出
        if ([_recordSession canAddOutput:self.stillImageOutput]) {
            [_recordSession addOutput:self.stillImageOutput];
        }
        //設(shè)置視頻錄制的方向
        self.videoConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
    }
    return _recordSession;
}

//后置攝像頭輸入
- (AVCaptureDeviceInput *)backCameraInput {
    if (_backCameraInput == nil) {
        NSError *error;
        _backCameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamara] error:&error];
        if (error) {
            NSLog(@"獲取后置攝像頭失敗~");
        }
    }
    return _backCameraInput;
}

//前置攝像頭輸入
- (AVCaptureDeviceInput *)frontCameraInput {
    if (_frontCameraInput == nil) {
        NSError *error;
        _frontCameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamara] error:&error];
        if (error) {
            NSLog(@"獲取前置攝像頭失敗~");
        }
    }
    return _frontCameraInput;
}

//麥克風(fēng)輸入
- (AVCaptureDeviceInput *)audioMicInput {
    if (_audioMicInput == nil) {
        AVCaptureDevice *mic = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
        NSError *error;
        _audioMicInput = [AVCaptureDeviceInput deviceInputWithDevice:mic error:&error];
        if (error) {
            NSLog(@"獲取麥克風(fēng)失敗~");
        }
    }
    return _audioMicInput;
}

//視頻輸出
- (AVCaptureVideoDataOutput *)videoOutput {
    if (_videoOutput == nil) {
        _videoOutput = [[AVCaptureVideoDataOutput alloc] init];
        [_videoOutput setSampleBufferDelegate:self queue:self.captureQueue];
        NSDictionary* setcapSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange], kCVPixelBufferPixelFormatTypeKey,
                                        nil];
        _videoOutput.videoSettings = setcapSettings;
    }
    return _videoOutput;
}

//音頻輸出
- (AVCaptureAudioDataOutput *)audioOutput {
    if (_audioOutput == nil) {
        _audioOutput = [[AVCaptureAudioDataOutput alloc] init];
        [_audioOutput setSampleBufferDelegate:self queue:self.captureQueue];
    }
    return _audioOutput;
}

//靜態(tài)圖像輸出
- (AVCaptureStillImageOutput *)stillImageOutput{
    if (_stillImageOutput == nil) {
        _stillImageOutput = [[AVCaptureStillImageOutput alloc]init];
        _stillImageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
    }
    return _stillImageOutput;
}
//視頻連接
- (AVCaptureConnection *)videoConnection {
    _videoConnection = [self.videoOutput connectionWithMediaType:AVMediaTypeVideo];
    return _videoConnection;
}

//音頻連接
- (AVCaptureConnection *)audioConnection {
    if (_audioConnection == nil) {
        _audioConnection = [self.audioOutput connectionWithMediaType:AVMediaTypeAudio];
    }
    return _audioConnection;
}

//捕獲到的視頻呈現(xiàn)的layer
- (AVCaptureVideoPreviewLayer *)previewLayer {
    if (_previewLayer == nil) {
        //通過AVCaptureSession初始化
        AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.recordSession];
        //設(shè)置比例為鋪滿全屏
        preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewLayer = preview;
    }
    return _previewLayer;
}

//錄制的隊(duì)列
- (dispatch_queue_t)captureQueue {
    if (_captureQueue == nil) {
        _captureQueue = dispatch_queue_create("cn.qiuyouqun.im.wclrecordengine.capture", DISPATCH_QUEUE_SERIAL);
    }
    return _captureQueue;
}

</pre>

2.格式封裝和配置參數(shù)
<pre>
//初始化視頻輸入
- (void)initVideoInputHeight:(NSInteger)cy width:(NSInteger)cx {
    //錄制視頻的一些配置勺择,分辨率领铐,編碼方式等等
    NSInteger numPixels = cx * cy;
    //每像素比特
    CGFloat bitsPerPixel = 6.0;
    NSInteger bitsPerSecond = numPixels * bitsPerPixel;
    
    // 碼率和幀率設(shè)置
    NSDictionary *compressionProperties = @{ AVVideoAverageBitRateKey:@(bitsPerSecond),
                                             AVVideoExpectedSourceFrameRateKey:@(30),
                                             AVVideoMaxKeyFrameIntervalKey:@(30),
                                             AVVideoProfileLevelKey:AVVideoProfileLevelH264BaselineAutoLevel };
    NSDictionary* settings = @{AVVideoCodecKey:AVVideoCodecH264,
                               AVVideoScalingModeKey:AVVideoScalingModeResizeAspectFill,
                               AVVideoWidthKey:@(cx),
                               AVVideoHeightKey:@(cy),
                               AVVideoCompressionPropertiesKey:compressionProperties };
    
    //初始化視頻寫入類
    _videoInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
    _videoInput.transform = [self transformFromCurrentVideoOrientationToOrientation:AVCaptureVideoOrientationPortrait];
    //表明輸入是否應(yīng)該調(diào)整其處理為實(shí)時(shí)數(shù)據(jù)源的數(shù)據(jù)
    _videoInput.expectsMediaDataInRealTime = YES;
    //將視頻輸入源加入
    if ([_writer canAddInput:_videoInput]) {
        [_writer addInput:_videoInput];
    }
}

//初始化音頻輸入
- (void)initAudioInputChannels:(int)ch samples:(Float64)rate {
    //音頻的一些配置包括音頻各種這里為AAC,音頻通道软瞎、采樣率和音頻的比特率
    NSDictionary *settings = @{AVEncoderBitRatePerChannelKey:@(28000),
                               AVFormatIDKey:@(kAudioFormatMPEG4AAC),
                               AVNumberOfChannelsKey:@(1),
                               AVSampleRateKey:@(22050) };
    //初始化音頻寫入類
    _audioInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:settings];
    //表明輸入是否應(yīng)該調(diào)整其處理為實(shí)時(shí)數(shù)據(jù)源的數(shù)據(jù)
    _audioInput.expectsMediaDataInRealTime = YES;
    //將音頻輸入源加入
    [_writer addInput:_audioInput];
}
</pre>

3.視頻方向控制
<pre>
- (CMMotionManager *)motionManager{
    if (!_motionManager) {
        _motionManager = [[CMMotionManager alloc]init];
        _motionManager.deviceMotionUpdateInterval = MOTION_UPDATE_INTERVAL;
    }
    return _motionManager;
}
// 開始
- (void)startDeviceMotionUpdates{
    if (_motionManager.deviceMotionAvailable) {
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
            [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
        }];
    }
}
// 結(jié)束
- (void)stopDeviceMotionUpdates{
    [_motionManager stopDeviceMotionUpdates];
}
- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x))
    {
        if (y >= 0){
            _deviceOrientation = UIDeviceOrientationPortraitUpsideDown;
            _videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            //NSLog(@"UIDeviceOrientationPortraitUpsideDown--AVCaptureVideoOrientationPortraitUpsideDown");
        }
        else{
            _deviceOrientation = UIDeviceOrientationPortrait;
            _videoOrientation = AVCaptureVideoOrientationPortrait;
            //NSLog(@"UIDeviceOrientationPortrait--AVCaptureVideoOrientationPortrait");
        }
    }
    else{
        if (x >= 0){
            _deviceOrientation = UIDeviceOrientationLandscapeRight;
            _videoOrientation = AVCaptureVideoOrientationLandscapeRight;
            //NSLog(@"UIDeviceOrientationLandscapeRight--AVCaptureVideoOrientationLandscapeRight");
        }
        else{
            _deviceOrientation = UIDeviceOrientationLandscapeLeft;
            _videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
           // NSLog(@"UIDeviceOrientationLandscapeLeft--AVCaptureVideoOrientationLandscapeLeft");
        }
    }
    ;
    if (_delegate && [_delegate respondsToSelector:@selector(motionManagerDeviceOrientation:)]) {
        [_delegate motionManagerDeviceOrientation:_deviceOrientation];
    }
}
// 調(diào)整設(shè)備取向
- (AVCaptureVideoOrientation)currentVideoOrientation{
    AVCaptureVideoOrientation orientation;
    switch ([SGMotionManager sharedManager].deviceOrientation) {
        case UIDeviceOrientationPortrait:
            orientation = AVCaptureVideoOrientationPortrait;
            break;
        case UIDeviceOrientationLandscapeRight:
            orientation = AVCaptureVideoOrientationLandscapeLeft;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            orientation = AVCaptureVideoOrientationPortraitUpsideDown;
            break;
        default:
            orientation = AVCaptureVideoOrientationLandscapeRight;
            break;
    }
    return orientation;
}

PS: 以上只是貼出了部分代碼片段,完整代碼請看 demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市迈着,隨后出現(xiàn)的幾起案子去枷,更是在濱河造成了極大的恐慌,老刑警劉巖是复,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件删顶,死亡現(xiàn)場離奇詭異,居然都是意外死亡淑廊,警方通過查閱死者的電腦和手機(jī)逗余,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來季惩,“玉大人录粱,你說我怎么就攤上這事』埃” “怎么了啥繁?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長青抛。 經(jīng)常有香客問我旗闽,道長,這世上最難降的妖魔是什么蜜另? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任适室,我火速辦了婚禮,結(jié)果婚禮上举瑰,老公的妹妹穿的比我還像新娘捣辆。我一直安慰自己,他們只是感情好此迅,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布汽畴。 她就那樣靜靜地躺著旧巾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪菠齿。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天绳匀,我揣著相機(jī)與錄音炸客,去河邊找鬼疾棵。 笑死,一個(gè)胖子當(dāng)著我的面吹牛痹仙,可吹牛的內(nèi)容都是我干的是尔。 我是一名探鬼主播开仰,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼众弓!你這毒婦竟也來了恩溅?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤谓娃,失蹤者是張志新(化名)和其女友劉穎脚乡,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體滨达,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年锌订,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瀑志。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡污秆,死狀恐怖劈猪,靈堂內(nèi)的尸體忽然破棺而出良拼,到底是詐尸還是另有隱情,我是刑警寧澤庸推,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布浇冰,位于F島的核電站聋亡,受9級特大地震影響肘习,放射性物質(zhì)發(fā)生泄漏坡倔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一罪塔、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧征堪,春花似錦、人聲如沸佃蚜。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至氯夷,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間靶擦,已是汗流浹背腮考。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工玄捕, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留踩蔚,地道東北人枚粘。 一個(gè)月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像福也,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子暴凑,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容