完整项目下载链接:https://github.com/SSYSSK/camera2
@property (strong, nonatomic) AVCaptureMovieFileOutput *movieOutput;
[self.movieOutput startRecordingToOutputFileURL: self.outputURL recordingDelegate:self];
这句代码时开始录制,然后就会执行代理回调
#pragma AVCaptureFileOutputRecordingDelegate - 视频输出代理
//录制完成
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error {
NSLog(@"录制完成");
UISaveVideoAtPathToSavedPhotosAlbum([outputFileURL path], nil, nil, nil);
//在videoQueue 上,
dispatch_async(self.videoQueue, ^{
//建立新的AVAsset & AVAssetImageGenerator
AVAsset *asset = [AVAsset assetWithURL:outputFileURL];
AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
//设置maximumSize 宽为100,高为0 根据视频的宽高比来计算图片的高度
imageGenerator.maximumSize = CGSizeMake(100.0f, 0.0f);
//捕捉视频缩略图会考虑视频的变化(如视频的方向变化),如果不设置,缩略图的方向可能出错
imageGenerator.appliesPreferredTrackTransform = YES;
//获取CGImageRef图片 注意需要自己管理它的创建和释放
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:kCMTimeZero actualTime:NULL error:nil];
//将图片转化为UIImage
UIImage *image = [UIImage imageWithCGImage:imageRef];
//释放CGImageRef imageRef 防止内存泄漏
CGImageRelease(imageRef);
//回到主线程
dispatch_async(dispatch_get_main_queue(), ^{
//发送请求
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"showVideoImage" object:image];
});
});
}
这个是获取图片的代理回调(录制视频的可以忽略这里,纯粹记录一下而已)
#pragma mark AVCapturePhotoCaptureDelegate
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error {
if (error) {
NSLog(@"获取图片错误 --- %@",error.localizedDescription);
}
if (photo) {
if (@available(iOS 11.0, *)) {
CGImageRef cgImage = [photo CGImageRepresentation];
UIImage * image = [UIImage imageWithCGImage:cgImage];
NSLog(@"获取图片成功 --- %@",image);
//前置摄像头拍照会旋转180解决办法
if (self.activeVideoInput.device.position == AVCaptureDevicePositionFront) {
UIImageOrientation imgOrientation = UIImageOrientationLeftMirrored;
image = [[UIImage alloc]initWithCGImage:cgImage scale:1.0f orientation:imgOrientation];
}else {
UIImageOrientation imgOrientation = UIImageOrientationRight;
image = [[UIImage alloc]initWithCGImage:cgImage scale:1.0f orientation:imgOrientation];
}
//发送请求显示缩略图
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"showVideoImage" object:image];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
} else {
NSLog(@"不是走这个代理方法");
}
}
}