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

前言:前一段時(shí)間產(chǎn)品新需求,說(shuō)是要做微信的小時(shí)頻功能.
功能需求:360x640 or 640x360的分辨率,大小在2MB 之內(nèi)的 MP4格式
短視頻 demo 地址
思路:使用 AVFoundtion框架提供的 AVCaptureSession進(jìn)行錄制,
大致如下:
攝像頭,麥克風(fēng)(input)->AVCapture Session->AVCaptureVideoDataOutpu(僅視頻數(shù)據(jù),無(wú)音頻數(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ù),僅僅只是視頻,沒有聲音,可以對(duì)視頻格式和參數(shù)進(jìn)行自定義封裝和添加濾鏡處理
3.AVCaptureAudioDataOutput:輸出音頻數(shù)據(jù),可以對(duì)格式和參數(shù)進(jìn)行自定義封裝
4.AVCaptureStillImageOutput:照片數(shù)據(jù),用戶獲取靜態(tài)圖像(拍照)
5.AVCaptureMovieFileOutput:輸出完整視頻(包括音頻),優(yōu)點(diǎn):錄制簡(jiǎ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: 以上只是貼出了部分代碼片段,完整代碼請(qǐng)看 demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容