由於攝像和拍照使用的是同一變數.所以這裡就不再重新定義了.可以參考拍照篇 首先定義幾個變數
GPUImageMovieWriter * movieWriter; //寫入磁碟的
NSMutableDictionary * videoSettings; //字面意思.視訊設定
NSDictionary * audioSettings; //聲音設定
NSString * moviePath; //視訊儲存路徑
複製程式碼
//視訊設定
videoSettings = [[NSMutableDictionary alloc] init];
[videoSettings setObject:AVVideoCodecH264 forKey:AVVideoCodecKey];
[videoSettings setObject:[NSNumber numberWithInteger:1080] forKey:AVVideoWidthKey]; //視訊的寬度,這裡最好是定義imageCamera時候的寬度
[videoSettings setObject:[NSNumber numberWithInteger:1920] forKey:AVVideoHeightKey]; //視訊的高度.同上
//音訊設定
AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[ 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];
//臨時儲存路徑
moviePath= [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Movie.mov"];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
//視訊寫入磁碟初始化.
/*
我這裡使用了AVFileTypeQuickTimeMovie 因為我上文使用了mov.
還支援其他,比如AVFileTypeMPEG4 格式為.MP4
AVFileTypeAppleM4V 格式m4v
AVFileTypeAppleM4A 格式m4a
AVFileType3GPP 格式3gp 等..自己可以在AVFoundation/AVMediaFormat中看到
*/
movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(1080, 1920) fileType:AVFileTypeQuickTimeMovie outputSettings:videoSettings];
[movieWriter setHasAudioTrack:YES audioSettings:audioSettings];
unlink([moviePath UTF8String]); //如果這個路徑有檔案,刪除.也可以使用NSFileManager來進行操作
imageCamera.audioEncodingTarget = movieWriter; //設定聲音
複製程式碼
開始錄影
[filter addTarget:movieWriter];
[movieWriter startRecording];
複製程式碼
停止錄影
[filter removeTarget:movieWriter];
//儲存到圖片庫,並且設定回撥.
[movieWriter finishRecordingWithCompletionHandler:^{
UISaveVideoAtPathToSavedPhotosAlbum(pathToMovie, self, @selector(videoWithPatch:didFinishSavingWithError:contextInfo:), nil);
}];
複製程式碼
回撥程式碼
- (void)videoWithPatch:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
//使用NSFileManager來進行刪除,如果不刪除的話,第二次點選會出現崩潰錯誤.提示AVAssetWriter status為2,或者3.(已完成狀態).
NSFileManager* fileManager=[NSFileManager defaultManager];
if([fileManager removeItemAtPath:pathToMovie error:nil]){
NSLog(@"REMOVE");
}else{
NSLog(@"error");
}
}
複製程式碼
至此 攝像和拍照 應該已經完結了.恩.如果有問題可以隨時聯絡我,一起研究. 下一篇是裁剪.