[TOC]
AVFoundation
主要用途 : 照片视频
直播 小直播
1d92315c3d9854f980616c551d7dd84b
AVFoundation相关的类
-
AVCaptureSession 捕捉会话
-
AVCaptureDevice 捕捉设备
-
AVCaptureDeviceInput 捕捉设备输入
-
AVCaptureOutput 抽象类 捕捉设备输出
- AVCaptureStillImageOutput
摄像头捕捉静态图片 - AVCaputureMovieFileOutput
将Quick Time
电影录制到文件系统 - AVCaputureAudioDataOutput
- AVCaputureVideoDataOutput
- AVCaptureStillImageOutput
-
AVCaptureConnection 捕捉链接
-
AVCaptureVideoPreviewLayer 捕捉预览
AVCaptureSession
AVCaptureSession
是AVFoundation
的核心类,用于捕捉视频和音频,协调视频和音频的输入和输出。
实现一个视频捕捉,拍照等功能。
- (BOOL)setupSession:(NSError **)error
- 设置
Session
2. 初始化
- 设置分辨率
- 配置输入设备(音频输入,视频输入)
- 配置输出(静态图像输出,视频文件输出)
- 为
seeeion
添加输入输出时,注意一点判断能否添加,因为摄像头不隶属于任何一个APP
,它是公共设备
1.创建捕捉会话
AVCaptureSession
是捕捉场景的中心枢纽
self.captureSession = [[AVCaptureSession alloc]init];
2.设置分辨率
self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
-
AVCaptureSessionPresetHigh
适用于高质量视频和音频输出 -
AVCaptureSessionPresetMedium
适用于中等质量输出,适合通过Wifi
共享的输出视频和音频 -
AVCaptureSessionPresetLow
适用于低质量输出,适合通过3G
共享的输出视频和音频 -
AVCaptureSessionPreset320x240
适用于320x240
像素视频输出 -
AVCaptureSessionPreset352x288
适用于CIF质量(352x288
像素)视频输出 -
AVCaptureSessionPreset640x480
适用于VGA质量(640x480
像素)视频输出 -
AVCaptureSessionPreset960x540
适用于四分之一高清(960x540
像素)视频输出 -
AVCaptureSessionPreset1280x720
适用于高清720p质量(1280x720
像素)视频输出 -
AVCaptureSessionPreset1920x1080
适用于1080p质量(1920x1080
像素)视频输出 -
AVCaptureSessionPreset3840x2160
适用于2160p
质量(3840x2160
像素)视频输出,此质量也被称为UHD
或4K
。 -
AVCaptureSessionPresetiFrame960x540
可实现带有AAC
音频的960x540
像素品质的iFrame H.264
视频(约30 Mbits
/ 秒)。 以iFrame格式捕获的QuickTime电影是编辑应用程序的最佳选择 -
AVCaptureSessionPresetiFrame1280x720
使用AAC
音频以约40 Mbits / sec
的速度实现1280x720
像素品质的iFrame H.264
视频。 -
AVCaptureSessionPresetInputPriority
指定捕获会话不控制音频和视频的输出设置 -
AVCaptureSessionPresetPhoto
指定适合高分辨率照片质量的拍摄设置,不支持音视频输出
3.设置视频和音频捕捉设备
视频输入
拿到默认视频捕捉设备
iOS
系统返回后置摄像头
将捕捉设备封装成AVCaptureDeviceInput
,为会话添加捕捉设备,必须将设备封装成AVCaptureDeviceInput
对象
判断videoInput
是否有效,有可能其他设备再用摄像头
canAddInput
:测试是否能被添加到会话中
将videoInput
添加到captureSession
中
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:error];
if (videoInput)
{
if ([self.captureSession canAddInput:videoInput])
{
[self.captureSession addInput:videoInput];
self.activeVideoInput = videoInput;
}
}else
{
return NO;
}
-
音频输入
- 选择默认音频捕捉设备 即返回一个内置麦克风
- 为这个设备创建一个捕捉设备输入
- 判断
audioInput
是否有效 -
canAddInput
:测试是否能被添加到会话中 - 将
audioInput
添加到captureSession
中
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:error];
if (audioInput) {
if ([self.captureSession canAddInput:audioInput])
{
[self.captureSession addInput:audioInput];
}
}else
{
return NO;
}
4.AVCaptureStillImageOutput
从摄像头捕捉静态图片
self.imageOutput = [[AVCaptureStillImageOutput alloc]init];
//配置字典:希望捕捉到JPEG格式的图片
self.imageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
//输出连接 判断是否可用,可用则添加到输出连接中去
if ([self.captureSession canAddOutput:self.imageOutput])
{
[self.captureSession addOutput:self.imageOutput];
}
5.AVCaptureMovieFileOutput
用于将
Quick Time
电影录制到文件系统
elf.movieOutput = [[AVCaptureMovieFileOutput alloc]init];
//输出连接 判断是否可用,可用则添加到输出连接中去
if ([self.captureSession canAddOutput:self.movieOutput])
{
[self.captureSession addOutput:self.movieOutput];
}
6.创建一个串行队列
startRunning
会阻塞线程 放在子线程执行
创建FIFO
类型后台线程进行管理,包括切换前后摄像头、改变闪光灯模式、切换拍照和录像等,都可以放入子线程操作。
self.videoQueue = dispatch_queue_create("cc.VideoQueue", NULL);
startRunning
启动从输入到连接到AVCaptureSession
实例的输出的数据流
- (void)startSession {
//检查是否处于运行状态
if (![self.captureSession isRunning])
{
//使用同步调用会损耗一定的时间,则用异步的方式处理
dispatch_async(self.videoQueue, ^{
[self.captureSession startRunning];
});
}
}
stopSession
停止从输入到连接到
AVCaptureSession
实例的输出的数据流
- (void)stopSession {
//检查是否处于运行状态
if ([self.captureSession isRunning])
{
//使用异步方式,停止运行
dispatch_async(self.videoQueue, ^{
[self.captureSession stopRunning];
});
}
}
配置摄像头支持的方法
1.返回当前捕捉会话对应的摄像头的device
属性
- (AVCaptureDevice *)activeCamera {
return self.activeVideoInput.device;
}
2.返回当前未激活的摄像头
查找前置或者后置可用摄像头
- (AVCaptureDevice *)inactiveCamera {
AVCaptureDevice *device = nil;
if (self.cameraCount > 1)
{
if ([self activeCamera].position == AVCaptureDevicePositionBack) {
device = [self cameraWithPosition:AVCaptureDevicePositionFront];
}else
{
device = [self cameraWithPosition:AVCaptureDevicePositionBack];
}
}
return device;
}
返回前置或后置对应的设备
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position {
//获取可用视频设备
NSArray *devicess = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//遍历可用的视频设备 并返回position 参数值
for (AVCaptureDevice *device in devicess)
{
if (device.position == position) {
return device;
}
}
return nil;
}
3.判断是否有超过一个摄像头可用
- (BOOL)canSwitchCameras {
return self.cameraCount > 1;
}
可用视频捕捉设备的数量
- (NSUInteger)cameraCount {
return [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
}
4.切换摄像头
判断是否有多个摄像头,没有直接返回
获取当前设备的反向设备
将输入设备封装成AVCaptureDeviceInput
判断videoInput
是否为nil
- 为
nil
,创建AVCaptureDeviceInput
出现错误,则通知委托来处理该错误- 存在
标注原配置变化开始
将捕捉会话中,原本的捕捉输入设备移除 不然切换不了
判断新的设备是否能加入
能加入成功,则将 `videoInput` 作为新的视频捕捉设备
将获得设备 改为 `videoInput`
如果新设备,无法加入。则将原本的视频捕捉设备重新加入到捕捉会话中
代码示例
- (BOOL)switchCameras {
if (![self canSwitchCameras])
{
return NO;
}
NSError *error;
AVCaptureDevice *videoDevice = [self inactiveCamera];
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
//判断videoInput 是否为nil
if (videoInput)
{
//标注原配置变化开始
[self.captureSession beginConfiguration];
//将捕捉会话中,原本的捕捉输入设备移除 不然切换不了
[self.captureSession removeInput:self.activeVideoInput];
//判断新的设备是否能加入
if ([self.captureSession canAddInput:videoInput])
{
//能加入成功,则将videoInput 作为新的视频捕捉设备
[self.captureSession addInput:videoInput];
//将获得设备 改为 videoInput
self.activeVideoInput = videoInput;
}else
{
//如果新设备,无法加入。则将原本的视频捕捉设备重新加入到捕捉会话中
[self.captureSession addInput:self.activeVideoInput];
}
//配置完成后, AVCaptureSession commitConfiguration 会分批的将所有变更整合在一起。
[self.captureSession commitConfiguration];
}else
{
//创建AVCaptureDeviceInput 出现错误,则通知委托来处理该错误
[self.delegate deviceConfigurationFailedWithError:error];
return NO;
}
return YES;
}
AVCapture Device
定义了很多方法,让开发者控制ios
设备上的摄像头。可以独立调整和锁定摄像头的焦距
、曝光
、白平衡
。对焦
和曝光
可以基于特定的兴趣点进行设置,使其在应用中实现点击对焦、点击曝光的功能。还可以让你控制设备的LED
作为拍照的闪光灯
或手电筒
的使用
每当修改摄像头设备时,一定要先测试修改动作是否能被设备支持。并不是所有的摄像头都支持所有功能
,例如牵制摄像头就不支持对焦操作,因为它和目标距离一般在一臂之长的距离。但大部分后置摄像头是可以支持全尺寸对焦。尝试应用一个不被支持的动作,会导致异常崩溃。所以修改摄像头设备前,需要判断是否支持.
点击聚焦方法的实现
镜头焦点与焦距的区别:
焦点
是透镜(或曲面镜)将光线会聚后所形成的点,因光线会聚成一点可将物烧焦。
焦距
是焦点
到面镜的中心点之间的距离。镜头焦距的长短决定着拍摄的成像大小,视场角大小,景深大小和画面的透视强弱。 镜头的焦距是镜头的一个非常重要的指标。镜头焦距的长短决定了被摄物在成像介质(胶片或CCD
等)上成像的大小,也就是相当于物和象的比例尺。当对同一距离远的同一个被摄目标拍摄时,镜头焦距长的所成的象大,镜头焦距短的所成的象小。根据用途的不同,照相机镜头的焦距相差非常大,有短到几毫米,十几毫米的,也有长达几米的。
1.首先判断是否支持聚焦
- (BOOL)cameraSupportsTapToFocus {
//询问激活中的摄像头是否支持兴趣点对焦
return [[self activeCamera]isFocusPointOfInterestSupported];
}
2.对外接口,根据point
,判断聚焦的位置
是否支持兴趣点对焦 & 是否自动对焦模式
锁定设备准备配置,如果获得了锁
将focusPointOfInterest
属性设置CGPoint
focusMode
设置为AVCaptureFocusModeAutoFocus
释放该锁定
聚焦失败直接代理返回
- (void)focusAtPoint:(CGPoint)point {
AVCaptureDevice *device = [self activeCamera];
//是否支持兴趣点对焦 & 是否自动对焦模式
if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
NSError *error;
//锁定设备准备配置,如果获得了锁
if ([device lockForConfiguration:&error]) {
//将focusPointOfInterest属性设置CGPoint
device.focusPointOfInterest = point;
//focusMode 设置为AVCaptureFocusModeAutoFocus
device.focusMode = AVCaptureFocusModeAutoFocus;
//释放该锁定
[device unlockForConfiguration];
}else{
//错误时,则返回给错误处理代理
[self.delegate deviceConfigurationFailedWithError:error];
}
}
}
点击曝光的方法实现
1.是否支持曝光
- (BOOL)cameraSupportsTapToExpose {
//询问设备是否支持对一个兴趣点进行曝光
return [[self activeCamera] isExposurePointOfInterestSupported];
}
2.设置曝光
`则使用kvo确定设备的adjustingExposure属性的状态。
static const NSString *THCameraAdjustingExposureContext;
- (void)exposeAtPoint:(CGPoint)point {
AVCaptureDevice *device = [self activeCamera];
AVCaptureExposureMode exposureMode =AVCaptureExposureModeContinuousAutoExposure;
//判断是否支持 AVCaptureExposureModeContinuousAutoExposure 模式
if (device.isExposurePointOfInterestSupported && [device isExposureModeSupported:exposureMode]) {
[device isExposureModeSupported:exposureMode];
NSError *error;
//锁定设备准备配置
if ([device lockForConfiguration:&error])
{
//配置期望值
device.exposurePointOfInterest = point;
device.exposureMode = exposureMode;
//判断设备是否支持锁定曝光的模式。
if ([device isExposureModeSupported:AVCaptureExposureModeLocked]) {
//支持,则使用kvo确定设备的adjustingExposure属性的状态。
[device addObserver:self forKeyPath:@"adjustingExposure" options:NSKeyValueObservingOptionNew context:&THCameraAdjustingExposureContext];
}
//释放该锁定
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
}
observeValueForKeyPath
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
//判断context(上下文)是否为THCameraAdjustingExposureContext
if (context == &THCameraAdjustingExposureContext) {
//获取device
AVCaptureDevice *device = (AVCaptureDevice *)object;
//判断设备是否不再调整曝光等级,确认设备的exposureMode是否可以设置为AVCaptureExposureModeLocked
if(!device.isAdjustingExposure && [device isExposureModeSupported:AVCaptureExposureModeLocked])
{
//移除作为adjustingExposure 的self,就不会得到后续变更的通知
[object removeObserver:self forKeyPath:@"adjustingExposure" context:&THCameraAdjustingExposureContext];
//异步方式调回主队列,
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error;
if ([device lockForConfiguration:&error]) {
//修改exposureMode
device.exposureMode = AVCaptureExposureModeLocked;
//释放该锁定
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
});
}
}else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
3.重新设置对焦和曝光
- (void)resetFocusAndExposureModes {
AVCaptureDevice *device = [self activeCamera];
AVCaptureFocusMode focusMode = AVCaptureFocusModeContinuousAutoFocus;
//获取对焦兴趣点 和 连续自动对焦模式 是否被支持
BOOL canResetFocus = [device isFocusPointOfInterestSupported]&& [device isFocusModeSupported:focusMode];
AVCaptureExposureMode exposureMode = AVCaptureExposureModeContinuousAutoExposure;
//确认曝光度可以被重设
BOOL canResetExposure = [device isFocusPointOfInterestSupported] && [device isExposureModeSupported:exposureMode];
//回顾一下,捕捉设备空间左上角(0,0),右下角(1,1) 中心点则(0.5,0.5)
CGPoint centPoint = CGPointMake(0.5f, 0.5f);
NSError *error;
//锁定设备,准备配置
if ([device lockForConfiguration:&error]) {
//焦点可设,则修改
if (canResetFocus) {
device.focusMode = focusMode;
device.focusPointOfInterest = centPoint;
}
//曝光度可设,则设置为期望的曝光模式
if (canResetExposure) {
device.exposureMode = exposureMode;
device.exposurePointOfInterest = centPoint;
}
//释放锁定
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
闪光灯 & 手电筒
- 闪光灯
1.判断是否有闪光灯
- (BOOL)cameraHasFlash {
return [[self activeCamera]hasFlash];
}
2.闪光灯模式
- (AVCaptureFlashMode)flashMode {
return [[self activeCamera]flashMode];
}
3.设置闪光灯
- (void)setFlashMode:(AVCaptureFlashMode)flashMode {
//获取会话
AVCaptureDevice *device = [self activeCamera];
//判断是否支持闪光灯模式
if ([device isFlashModeSupported:flashMode]) {
//如果支持,则锁定设备
NSError *error;
if ([device lockForConfiguration:&error]) {
//修改闪光灯模式
device.flashMode = flashMode;
//修改完成,解锁释放设备
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
}
- 手电筒
1.是否支持手电筒
- (BOOL)cameraHasTorch {
return [[self activeCamera]hasTorch];
}
2. 手电筒模式
- (AVCaptureTorchMode)torchMode {
return [[self activeCamera]torchMode];
}
3.设置是否打开手电筒
- (void)setTorchMode:(AVCaptureTorchMode)torchMode {
AVCaptureDevice *device = [self activeCamera];
if ([device isTorchModeSupported:torchMode]) {
NSError *error;
if ([device lockForConfiguration:&error]) {
device.torchMode = torchMode;
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
}
拍摄静态图片
AVCaptureStillImageOutput
是AVCaptureOutput
的子类。用于捕捉图片
AVCaptureConnection
来获取连接
获取方向值
数据返回的block
,如果data
转image
成功,则写入相册
CMSampleBufferRef
:存放一个或多个压缩或未压缩的媒体文件
- (void)
captureStillImageAsynchronouslyFromConnection
:(AVCaptureConnection *)connectioncompletionHandler:
(void (^)(CMSampleBufferRef _Nullable imageDataSampleBuffer, NSError * _Nullable error))handler;
- (void)captureStillImage {
//获取连接
AVCaptureConnection *connection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
//程序只支持纵向,但是如果用户横向拍照时,需要调整结果照片的方向
//判断是否支持设置视频方向
if (connection.isVideoOrientationSupported) {
//获取方向值
connection.videoOrientation = [self currentVideoOrientation];
}
//定义一个handler 块,会返回1个图片的NSData数据
id handler = ^(CMSampleBufferRef sampleBuffer,NSError *error)
{
if (sampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:sampleBuffer];
UIImage *image = [[UIImage alloc]initWithData:imageData];
//重点:捕捉图片成功后,将图片传递出去
[self writeImageToAssetsLibrary:image];
}else
{
NSLog(@"NULL sampleBuffer:%@",[error localizedDescription]);
}
};
//捕捉静态图片
[self.imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:handler];
}
获取方向值
- (AVCaptureVideoOrientation)currentVideoOrientation {
AVCaptureVideoOrientation orientation;
//获取UIDevice 的 orientation
switch ([UIDevice currentDevice].orientation) {
case UIDeviceOrientationPortrait:
orientation = AVCaptureVideoOrientationPortrait;
break;
case UIDeviceOrientationLandscapeRight:
orientation = AVCaptureVideoOrientationLandscapeLeft;
break;
case UIDeviceOrientationPortraitUpsideDown:
orientation = AVCaptureVideoOrientationPortraitUpsideDown;
break;
default:
orientation = AVCaptureVideoOrientationLandscapeRight;
break;
}
return orientation;
return 0;
}
Assets Library
框架
用来让开发者通过代码方式访问iOS photo
注意:会访问到相册,需要修改plist
权限。否则会导致项目崩溃
- (void)writeImageToAssetsLibrary:(UIImage *)image {
//创建ALAssetsLibrary 实例
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
//参数1:图片(参数为CGImageRef 所以image.CGImage)
//参数2:方向参数 转为NSUInteger
//参数3:写入成功、失败处理
[library writeImageToSavedPhotosAlbum:image.CGImage
orientation:(NSUInteger)image.imageOrientation
completionBlock:^(NSURL *assetURL, NSError *error) {
//成功后,发送捕捉图片通知。用于绘制程序的左下角的缩略图
if (!error)
{
[self postThumbnailNotifification:image];
}else
{
//失败打印错误信息
id message = [error localizedDescription];
NSLog(@"%@",message);
}
}];
}
postThumbnailNotifification
通知外部,显示缩略图,一般在左下角
- (void)postThumbnailNotifification:(UIImage *)image {
//回到主队列
dispatch_async(dispatch_get_main_queue(), ^{
//发送请求
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:THThumbnailCreatedNotification object:image];
});
}
捕捉视频
1.判断录制状态
- (BOOL)isRecording {
return self.movieOutput.isRecording;
}
2.开始录制
AVCaptureConnection
获取当前视频捕捉连接信息,用于捕捉视频数据配置一些核心属性- 判断是否支持修改视频方向
- 判断是否支持视频稳定 可以显著提高视频的质量。只会在录制视频文件涉及
- 拿到当前设备,可以进行平滑对焦模式操作。即减慢摄像头镜头对焦速度。当用户移动拍摄时摄像头会尝试快速自动对焦。
5.设置视频捕捉的保存路径- 在捕捉输出上调用方法
startRecordingToOutputFileURL
参数1:录制保存路径 参数2:代理
- (void)startRecording {
if (![self isRecording]) {
//获取当前视频捕捉连接信息,用于捕捉视频数据配置一些核心属性
AVCaptureConnection * videoConnection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];
//判断是否支持设置videoOrientation 属性。
if([videoConnection isVideoOrientationSupported])
{
//支持则修改当前视频的方向
videoConnection.videoOrientation = [self currentVideoOrientation];
}
//判断是否支持视频稳定 可以显著提高视频的质量。只会在录制视频文件涉及
if([videoConnection isVideoStabilizationSupported])
{
videoConnection.enablesVideoStabilizationWhenAvailable = YES;
}
AVCaptureDevice *device = [self activeCamera];
//摄像头可以进行平滑对焦模式操作。即减慢摄像头镜头对焦速度。当用户移动拍摄时摄像头会尝试快速自动对焦。
if (device.isSmoothAutoFocusEnabled) {
NSError *error;
if ([device lockForConfiguration:&error]) {
device.smoothAutoFocusEnabled = YES;
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
//查找写入捕捉视频的唯一文件系统URL.
self.outputURL = [self uniqueURL];
//在捕捉输出上调用方法 参数1:录制保存路径 参数2:代理
[self.movieOutput startRecordingToOutputFileURL:self.outputURL recordingDelegate:self];
}
}
3.创建写入视频文件路径
- (NSURL *)uniqueURL {
NSFileManager *fileManager = [NSFileManager defaultManager];
//temporaryDirectoryWithTemplateString 可以将文件写入的目的创建一个唯一命名的目录;
NSString *dirPath = [fileManager temporaryDirectoryWithTemplateString:@"kamera.XXXXXX"];
if (dirPath) {
NSString *filePath = [dirPath stringByAppendingPathComponent:@"kamera_movie.mov"];
return [NSURL fileURLWithPath:filePath];
}
return nil;
}
4.停止录制
- (void)stopRecording {
//是否正在录制
if ([self isRecording]) {
[self.movieOutput stopRecording];
}
}
5.AVCaptureFileOutputRecordingDelegate
录制成功,将视频写入本地相册
#pragma mark - AVCaptureFileOutputRecordingDelegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error {
//错误
if (error) {
[self.delegate mediaCaptureFailedWithError:error];
}else
{
//写入
[self writeVideoToAssetsLibrary:[self.outputURL copy]];
}
self.outputURL = nil;
}
6.写入捕捉到的视频
ALAssetsLibrary
提供写入视频的接口
writeVideoAtPathToSavedPhotosAlbum
写入
- (void)writeVideoToAssetsLibrary:(NSURL *)videoURL {
//ALAssetsLibrary 实例 提供写入视频的接口
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
//写资源库写入前,检查视频是否可被写入 (写入前尽量养成判断的习惯)
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:videoURL]) {
//创建block块
ALAssetsLibraryWriteVideoCompletionBlock completionBlock;
completionBlock = ^(NSURL *assetURL,NSError *error)
{
if (error) {
[self.delegate assetLibraryWriteFailedWithError:error];
}else
{
//用于界面展示视频缩略图
[self generateThumbnailForVideoAtURL:videoURL];
}
};
//执行实际写入资源库的动作
[library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:completionBlock];
}
}
7.获取视频左下角缩略图
videoURL->AVAsset->AVAssetImageGenerator->CGImageRef->image
- (void)generateThumbnailForVideoAtURL:(NSURL *)videoURL {
//在videoQueue 上,
dispatch_async(self.videoQueue, ^{
//建立新的AVAsset & AVAssetImageGenerator
AVAsset *asset = [AVAsset assetWithURL:videoURL];
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(), ^{
//发送通知,传递最新的image
[self postThumbnailNotifification:image];
});
});
}
网友评论