GPUImage學習日記(2)之視訊錄製

GPUImage學習日記(2)之視訊錄製

簡介:GPUImage 關於視訊錄製主要類就是GPUImageVideoCamera,本文就視訊錄製新增濾鏡儲存等都做一個簡單說明.

大致思路:
  • 初始化GPUImageVideoCamera並新增音訊輸入輸入設定
  • 新增展示ImageView 和 濾鏡設定(如:GPUImageVignetteFilter)
  • 初始化GPUImageMovieWriter資料寫入方法
  • 錄製結束移除GPUImageMovieWriter並呼叫其finishRecording
  • 儲存視訊
對應簡易流程圖如下
具體實現如下
1.和照片新增濾鏡類似,videoCamera新增濾鏡,濾鏡新增展示檢視imageView.
_videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
_videoCamera.outputImageOrientation = [UIApplication sharedApplication].statusBarOrientation;
_filter = [[GPUImageSepiaFilter alloc] init];
_filterView = [[GPUImageView alloc] initWithFrame:self.view.bounds];
self.view = _filterView;
[_videoCamera addTarget:_filter];
[_filter addTarget:_filterView];
[_videoCamera startCameraCapture];
注:addAudioInputsAndOutputs方法可消除第一幀黑屏問題.

2.開始錄製

        unlink([pathToMovie UTF8String]); //刪除已存在檔案
_movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(480.0, 640.0)];
_movieWriter.encodingLiveVideo = YES;
[_filter addTarget:_movieWriter];
_videoCamera.audioEncodingTarget = _movieWriter;
[_movieWriter startRecording];

3.結束錄製

        [_filter removeTarget:_movieWriter];
_videoCamera.audioEncodingTarget = nil;
[_movieWriter finishRecording];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(pathToMovie))
{
[library writeVideoAtPathToSavedPhotosAlbum:movieURL completionBlock:^(NSURL *assetURL, NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"儲存失敗");
} else {
NSLog(@"儲存成功");
}
});
}];
}

注:其中儲存視訊到相簿中在IOS10以上PHAssetChangeRequest相關方法.