之前已經有一篇博客講過怎么開啟攝像頭並完成對攝像頭的圖像的濾鏡化了,現在就說說怎么錄像,並把這個添加濾鏡的錄像文件寫到Path
原理是GPUImage給出了GPUImageMovieWriter這么個類,專門用於記錄攝像頭的錄像。設定了路徑和聲音視頻參數以后,把GPUImageMovieWriter的對象委托給濾鏡對象,再把濾鏡對象委托給VideoCamera就可以開始錄制了。
首先定義:
GPUImageMovieWriter * movieWriter;
GPUImageVideoCamera * videoCamera;
NSMutableDictionary * videoSettings;
NSDictionary * audioSettings;
NSString * pathToMovie;
這些都是錄像必備的屬性
接下來是初始化的工作
首先初始化聲音和視頻參數:
//init Video Setting
videoSettings = [[NSMutableDictionaryalloc] init];;
[videoSettingssetObject:AVVideoCodecH264forKey:AVVideoCodecKey];
[videoSettingssetObject:[NSNumbernumberWithInteger:200] forKey:AVVideoWidthKey];
[videoSettingssetObject:[NSNumbernumberWithInteger:200] forKey:AVVideoHeightKey];
//init audio setting
AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
audioSettings = [NSDictionarydictionaryWithObjectsAndKeys:
[ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[ NSNumber numberWithInt: 2 ], AVNumberOfChannelsKey,
[ NSNumber numberWithFloat: 16000.0 ], AVSampleRateKey,
[ NSData dataWithBytes:&channelLayout length: sizeof( AudioChannelLayout ) ], AVChannelLayoutKey,
[ NSNumber numberWithInt: 32000 ], AVEncoderBitRateKey,
nil];
然后是初始化文件路徑和視頻寫入對象
//init Movie path
pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:thePath];
unlink([pathToMovieUTF8String]); // If a file already exists, AVAssetWriter won't let you record new frames, so delete the old movie
NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
//init movieWriter
movieWriter = [[GPUImageMovieWriteralloc] initWithMovieURL:movieURL size:CGSizeMake(480.0, 640.0) fileType:AVFileTypeMPEG4outputSettings:videoSettings];
[movieWritersetHasAudioTrack:YESaudioSettings:audioSettings];
接下來是GPUImageVideoCamera和濾鏡效果的初始化,我就不寫了,看我另外一篇博客
初始化的最后動作就是賦予委托:
//把濾鏡效果加給攝像頭
[videoCameraaddTarget:testFilter];
//把攝像頭上的圖像給GPUImageView顯示出來
[testFilteraddTarget:imageView];
[testFilteraddTarget:movieWriter];
這樣初始化的工作就全部做完了,要開始錄制只要開啟以下代碼:
videoCamera.audioEncodingTarget = movieWriter;
[movieWriterstartRecording];
就可以開始錄制了,結束錄制也很簡單:
//stop recording
[testFilterremoveTarget:movieWriter];
[movieWriterfinishRecording];
錄制完的視頻將會保存在路徑里
還有兩個小設置:
開啟和關閉閃光燈:
[videoCamera.inputCamerasetTorchMode:AVCaptureTorchModeOn];
[videoCamera.inputCameraunlockForConfiguration];
[videoCamera.inputCameralockForConfiguration:nil];
[videoCamera.inputCamerasetTorchMode:AVCaptureTorchModeOff];
[videoCamera.inputCameraunlockForConfiguration];