<1> AVCapture
前面我们已经分析了Camera的UIImageViewController使用,这个部分我们再来看下AVCapture怎么使用的。
(1)输入源设置:相机、照片库
(2)设置前后摄像头
(3)设置视频质量
(4)设置照片、视频模式
(5)设置闪光灯打开方式
(6)视频编辑
(7)自定义摄像界面
(8)视频缩略图、视频关键帧
拍照:我们同样从这几个分部分析下AVCapture的使用:
(1)设备输入源设置:
AVCaptureDevice *device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
self.videoInput = [AVCaptureDeviceInputdeviceInputWithDevice:device error:&error];
(2)相机预览层设置
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
[self.view.layer addSublayer:previewLayer];
(3)静态图片抓取
利用AVCaptureSession建立媒体流与Image:JPEG的联系。
self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *stillImageOutputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey, nil];
[self.stillImageOutput setOutputSettings:stillImageOutputSettings];
[self.captureSession addOutput:self.stillImageOutput];
(4)点击拍照时,调用如下方法:[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:stillImageConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
if (imageDataSampleBuffer != NULL)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:^(NSURL *assetURL, NSError *error)
{}];
}
}];
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
self.audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioDevice error:nil];
self.movieOutput = [[AVCaptureMovieFileOutput alloc] init];
[self.captureSession addInput:self.videoInput];
[self.captureSession addOutput:self.stillImageOutput];
(2)点击录制之后调用方法:[self.movieOutput startRecordingToOutputFileURL:视频文件路径 recordingDelegate:self];
视频缩略图、视频关键帧:AVURLAsset *myAsset = [[AVURLAsset alloc] initWithURL:视频文件路径 options:[NSDictionary dictionaryWithObject:@"YES" forKey:AVURLAssetPreferPreciseDurationAndTimingKey]];
AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:myAsset];
imageGenerator.appliesPreferredTrackTransform = YES;
// 获取视频拍摄的关键帧。
[imageGenerator generateCGImagesAsynchronouslyForTimes:times
completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error)
{
image即为关键帧图片
}];