由于摄像和拍照使用的是同一变量.所以这里就不再重新定义了.可以参考拍照篇 首先定义几个变量
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");
}
}
复制代码
至此 摄像和拍照 应该已经完结了.恩.如果有问题可以随时联系我,一起研究. 下一篇是裁剪.