AVFoundation可以用來(lái)干嘛呢?當(dāng)前比較火的小視頻/直播離不開(kāi)照片/視頻的捕捉功能,使用iOS 原生框架AVFoundation便可以完成這些功能,當(dāng)然還可以實(shí)現(xiàn)簡(jiǎn)單的人臉識(shí)別和二維碼功能,將在下一章中講到.
AVFoundation
???????? ◆捕捉會(huì)話: AVCaptureSession.
◆捕捉設(shè)備: AVCaptureDevice.
◆捕捉設(shè)備輸入: AVCaptureDeviceInput.
◆捕捉設(shè)備輸出: AVCaptureOutput ??????抽象類.
◆AVCaptureStillImageOutput
◆AVCaputureMovieFileOutput
◆AVCaputureAudioDataOutput
◆AVCaputureVideoDataOutput
◆捕捉連接:AVCaptureConnection
◆捕捉預(yù)覽:AVCaptureVideoPreviewLayer
#import "THCameraController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "NSFileManager+THAdditions.h"
NSString *const THThumbnailCreatedNotification = @"THThumbnailCreated";
@interface THCameraController () <AVCaptureFileOutputRecordingDelegate>
@property (strong, nonatomic) dispatch_queue_t videoQueue; //視頻隊(duì)列
@property (strong, nonatomic) AVCaptureSession *captureSession;// 捕捉會(huì)話
@property (weak, nonatomic) AVCaptureDeviceInput *activeVideoInput;//輸入
@property (strong, nonatomic) AVCaptureStillImageOutput *imageOutput;
@property (strong, nonatomic) AVCaptureMovieFileOutput *movieOutput;
@property (strong, nonatomic) NSURL *outputURL;
@end
@implementation THCameraController
- (BOOL)setupSession:(NSError **)error {
//創(chuàng)建捕捉會(huì)話。AVCaptureSession 是捕捉場(chǎng)景的中心樞紐
self.captureSession = [[AVCaptureSession alloc]init];
/*
AVCaptureSessionPresetHigh
AVCaptureSessionPresetMedium
AVCaptureSessionPresetLow
AVCaptureSessionPreset640x480
AVCaptureSessionPreset1280x720
AVCaptureSessionPresetPhoto
*/
//設(shè)置圖像的分辨率
self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
//拿到默認(rèn)視頻捕捉設(shè)備 iOS系統(tǒng)返回后置攝像頭
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//將捕捉設(shè)備封裝成AVCaptureDeviceInput
//注意:為會(huì)話添加捕捉設(shè)備崇众,必須將設(shè)備封裝成AVCaptureDeviceInput對(duì)象
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:error];
//判斷videoInput是否有效
if (videoInput)
{
//canAddInput:測(cè)試是否能被添加到會(huì)話中
if ([self.captureSession canAddInput:videoInput])
{
//將videoInput 添加到 captureSession中
[self.captureSession addInput:videoInput];
self.activeVideoInput = videoInput;
}
}else
{
return NO;
}
//選擇默認(rèn)音頻捕捉設(shè)備 即返回一個(gè)內(nèi)置麥克風(fēng)
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
//為這個(gè)設(shè)備創(chuàng)建一個(gè)捕捉設(shè)備輸入
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:error];
//判斷audioInput是否有效
if (audioInput) {
//canAddInput:測(cè)試是否能被添加到會(huì)話中
if ([self.captureSession canAddInput:audioInput])
{
//將audioInput 添加到 captureSession中
[self.captureSession addInput:audioInput];
}
}else
{
return NO;
}
//AVCaptureStillImageOutput 實(shí)例 從攝像頭捕捉靜態(tài)圖片
self.imageOutput = [[AVCaptureStillImageOutput alloc]init];
//配置字典:希望捕捉到JPEG格式的圖片
self.imageOutput.outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
//輸出連接 判斷是否可用掂僵,可用則添加到輸出連接中去
if ([self.captureSession canAddOutput:self.imageOutput])
{
[self.captureSession addOutput:self.imageOutput];
}
//創(chuàng)建一個(gè)AVCaptureMovieFileOutput 實(shí)例,用于將Quick Time 電影錄制到文件系統(tǒng)
self.movieOutput = [[AVCaptureMovieFileOutput alloc]init];
//輸出連接 判斷是否可用顷歌,可用則添加到輸出連接中去
if ([self.captureSession canAddOutput:self.movieOutput])
{
[self.captureSession addOutput:self.movieOutput];
}
self.videoQueue = dispatch_queue_create("cc.VideoQueue", NULL);
return YES;
}
- (void)startSession {
//檢查是否處于運(yùn)行狀態(tài)
if (![self.captureSession isRunning])
{
//使用同步調(diào)用會(huì)損耗一定的時(shí)間锰蓬,則用異步的方式處理
dispatch_async(self.videoQueue, ^{
[self.captureSession startRunning];
});
}
}
- (void)stopSession {
//檢查是否處于運(yùn)行狀態(tài)
if ([self.captureSession isRunning])
{
//使用異步方式,停止運(yùn)行
dispatch_async(self.videoQueue, ^{
[self.captureSession stopRunning];
});
}
}
//- (dispatch_queue_t)globalQueue {
//
// return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//}
#pragma mark - Device Configuration 配置攝像頭支持的方法
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position {
//獲取可用視頻設(shè)備
NSArray *devicess = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
//遍歷可用的視頻設(shè)備 并返回position 參數(shù)值
for (AVCaptureDevice *device in devicess)
{
if (device.position == position) {
return device;
}
}
return nil;
}
- (AVCaptureDevice *)activeCamera {
//返回當(dāng)前捕捉會(huì)話對(duì)應(yīng)的攝像頭的device 屬性
return self.activeVideoInput.device;
}
//返回當(dāng)前未激活的攝像頭
- (AVCaptureDevice *)inactiveCamera {
//通過(guò)查找當(dāng)前激活攝像頭的反向攝像頭獲得眯漩,如果設(shè)備只有1個(gè)攝像頭芹扭,則返回nil
AVCaptureDevice *device = nil;
if (self.cameraCount > 1)
{
if ([self activeCamera].position == AVCaptureDevicePositionBack) {
device = [self cameraWithPosition:AVCaptureDevicePositionFront];
}else
{
device = [self cameraWithPosition:AVCaptureDevicePositionBack];
}
}
return device;
}
//判斷是否有超過(guò)1個(gè)攝像頭可用
- (BOOL)canSwitchCameras {
return self.cameraCount > 1;
}
//可用視頻捕捉設(shè)備的數(shù)量
- (NSUInteger)cameraCount {
return [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
}
//切換攝像頭
- (BOOL)switchCameras {
//判斷是否有多個(gè)攝像頭
if (![self canSwitchCameras])
{
return NO;
}
//獲取當(dāng)前設(shè)備的反向設(shè)備
NSError *error;
AVCaptureDevice *videoDevice = [self inactiveCamera];
//將輸入設(shè)備封裝成AVCaptureDeviceInput
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
//判斷videoInput 是否為nil
if (videoInput)
{
//標(biāo)注原配置變化開(kāi)始
[self.captureSession beginConfiguration];
//將捕捉會(huì)話中,原本的捕捉輸入設(shè)備移除
[self.captureSession removeInput:self.activeVideoInput];
//判斷新的設(shè)備是否能加入
if ([self.captureSession canAddInput:videoInput])
{
//能加入成功赦抖,則將videoInput 作為新的視頻捕捉設(shè)備
[self.captureSession addInput:videoInput];
//將獲得設(shè)備 改為 videoInput
self.activeVideoInput = videoInput;
}else
{
//如果新設(shè)備舱卡,無(wú)法加入。則將原本的視頻捕捉設(shè)備重新加入到捕捉會(huì)話中
[self.captureSession addInput:self.activeVideoInput];
}
//配置完成后队萤, AVCaptureSession commitConfiguration 會(huì)分批的將所有變更整合在一起轮锥。
[self.captureSession commitConfiguration];
}else
{
//創(chuàng)建AVCaptureDeviceInput 出現(xiàn)錯(cuò)誤,則通知委托來(lái)處理該錯(cuò)誤
[self.delegate deviceConfigurationFailedWithError:error];
return NO;
}
return YES;
}
/*
AVCapture Device 定義了很多方法要尔,讓開(kāi)發(fā)者控制ios設(shè)備上的攝像頭舍杜。可以獨(dú)立調(diào)整和鎖定攝像頭的焦距赵辕、曝光既绩、白平衡。對(duì)焦和曝光可以基于特定的興趣點(diǎn)進(jìn)行設(shè)置匆帚,使其在應(yīng)用中實(shí)現(xiàn)點(diǎn)擊對(duì)焦熬词、點(diǎn)擊曝光的功能。
還可以讓你控制設(shè)備的LED作為拍照的閃光燈或手電筒的使用
每當(dāng)修改攝像頭設(shè)備時(shí)吸重,一定要先測(cè)試修改動(dòng)作是否能被設(shè)備支持互拾。并不是所有的攝像頭都支持所有功能,例如牽制攝像頭就不支持對(duì)焦操作嚎幸,因?yàn)樗湍繕?biāo)距離一般在一臂之長(zhǎng)的距離颜矿。但大部分后置攝像頭是可以支持全尺寸對(duì)焦。嘗試應(yīng)用一個(gè)不被支持的動(dòng)作嫉晶,會(huì)導(dǎo)致異常崩潰骑疆。所以修改攝像頭設(shè)備前田篇,需要判斷是否支持
*/
#pragma mark - Focus Methods 點(diǎn)擊聚焦方法的實(shí)現(xiàn)
- (BOOL)cameraSupportsTapToFocus {
//詢問(wèn)激活中的攝像頭是否支持興趣點(diǎn)對(duì)焦
return [[self activeCamera]isFocusPointOfInterestSupported];
}
- (void)focusAtPoint:(CGPoint)point {
AVCaptureDevice *device = [self activeCamera];
//是否支持興趣點(diǎn)對(duì)焦 & 是否自動(dòng)對(duì)焦模式
if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
NSError *error;
//鎖定設(shè)備準(zhǔn)備配置,如果獲得了鎖
if ([device lockForConfiguration:&error]) {
//將focusPointOfInterest屬性設(shè)置CGPoint
device.focusPointOfInterest = point;
//focusMode 設(shè)置為AVCaptureFocusModeAutoFocus
device.focusMode = AVCaptureFocusModeAutoFocus;
//釋放該鎖定
[device unlockForConfiguration];
}else{
//錯(cuò)誤時(shí)箍铭,則返回給錯(cuò)誤處理代理
[self.delegate deviceConfigurationFailedWithError:error];
}
}
}
#pragma mark - Exposure Methods 點(diǎn)擊曝光的方法實(shí)現(xiàn)
- (BOOL)cameraSupportsTapToExpose {
//詢問(wèn)設(shè)備是否支持對(duì)一個(gè)興趣點(diǎn)進(jìn)行曝光
return [[self activeCamera] isExposurePointOfInterestSupported];
}
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;
//鎖定設(shè)備準(zhǔn)備配置
if ([device lockForConfiguration:&error])
{
//配置期望值
device.exposurePointOfInterest = point;
device.exposureMode = exposureMode;
//判斷設(shè)備是否支持鎖定曝光的模式泊柬。
if ([device isExposureModeSupported:AVCaptureExposureModeLocked]) {
//支持,則使用kvo確定設(shè)備的adjustingExposure屬性的狀態(tài)诈火。
[device addObserver:self forKeyPath:@"adjustingExposure" options:NSKeyValueObservingOptionNew context:&THCameraAdjustingExposureContext];
}
//釋放該鎖定
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
//判斷context(上下文)是否為THCameraAdjustingExposureContext
if (context == &THCameraAdjustingExposureContext) {
//獲取device
AVCaptureDevice *device = (AVCaptureDevice *)object;
//判斷設(shè)備是否不再調(diào)整曝光等級(jí)兽赁,確認(rèn)設(shè)備的exposureMode是否可以設(shè)置為AVCaptureExposureModeLocked
if(!device.isAdjustingExposure && [device isExposureModeSupported:AVCaptureExposureModeLocked])
{
//移除作為adjustingExposure 的self,就不會(huì)得到后續(xù)變更的通知
[object removeObserver:self forKeyPath:@"adjustingExposure" context:&THCameraAdjustingExposureContext];
//異步方式調(diào)回主隊(duì)列冷守,
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];
}
}
//重新設(shè)置對(duì)焦&曝光
- (void)resetFocusAndExposureModes {
AVCaptureDevice *device = [self activeCamera];
AVCaptureFocusMode focusMode = AVCaptureFocusModeContinuousAutoFocus;
//獲取對(duì)焦興趣點(diǎn) 和 連續(xù)自動(dòng)對(duì)焦模式 是否被支持
BOOL canResetFocus = [device isFocusPointOfInterestSupported]&& [device isFocusModeSupported:focusMode];
AVCaptureExposureMode exposureMode = AVCaptureExposureModeContinuousAutoExposure;
//確認(rèn)曝光度可以被重設(shè)
BOOL canResetExposure = [device isFocusPointOfInterestSupported] && [device isExposureModeSupported:exposureMode];
//回顧一下刀崖,捕捉設(shè)備空間左上角(0,0)拍摇,右下角(1亮钦,1) 中心點(diǎn)則(0.5,0.5)
CGPoint centPoint = CGPointMake(0.5f, 0.5f);
NSError *error;
//鎖定設(shè)備充活,準(zhǔn)備配置
if ([device lockForConfiguration:&error]) {
//焦點(diǎn)可設(shè)蜂莉,則修改
if (canResetFocus) {
device.focusMode = focusMode;
device.focusPointOfInterest = centPoint;
}
//曝光度可設(shè),則設(shè)置為期望的曝光模式
if (canResetExposure) {
device.exposureMode = exposureMode;
device.exposurePointOfInterest = centPoint;
}
//釋放鎖定
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
#pragma mark - Flash and Torch Modes 閃光燈 & 手電筒
//判斷是否有閃光燈
- (BOOL)cameraHasFlash {
return [[self activeCamera]hasFlash];
}
//閃光燈模式
- (AVCaptureFlashMode)flashMode {
return [[self activeCamera]flashMode];
}
//設(shè)置閃光燈
- (void)setFlashMode:(AVCaptureFlashMode)flashMode {
//獲取會(huì)話
AVCaptureDevice *device = [self activeCamera];
//判斷是否支持閃光燈模式
if ([device isFlashModeSupported:flashMode]) {
//如果支持堪唐,則鎖定設(shè)備
NSError *error;
if ([device lockForConfiguration:&error]) {
//修改閃光燈模式
device.flashMode = flashMode;
//修改完成巡语,解鎖釋放設(shè)備
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
}
//是否支持手電筒
- (BOOL)cameraHasTorch {
return [[self activeCamera]hasTorch];
}
//手電筒模式
- (AVCaptureTorchMode)torchMode {
return [[self activeCamera]torchMode];
}
//設(shè)置是否打開(kāi)手電筒
- (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];
}
}
}
#pragma mark - Image Capture Methods 拍攝靜態(tài)圖片
/*
AVCaptureStillImageOutput 是AVCaptureOutput的子類翎蹈。用于捕捉圖片
*/
- (void)captureStillImage {
//獲取連接
AVCaptureConnection *connection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
//程序只支持縱向淮菠,但是如果用戶橫向拍照時(shí),需要調(diào)整結(jié)果照片的方向
//判斷是否支持設(shè)置視頻方向
if (connection.isVideoOrientationSupported) {
//獲取方向值
connection.videoOrientation = [self currentVideoOrientation];
}
//定義一個(gè)handler 塊荤堪,會(huì)返回1個(gè)圖片的NSData數(shù)據(jù)
id handler = ^(CMSampleBufferRef sampleBuffer,NSError *error)
{
if (sampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:sampleBuffer];
UIImage *image = [[UIImage alloc]initWithData:imageData];
//重點(diǎn):捕捉圖片成功后合陵,將圖片傳遞出去
[self writeImageToAssetsLibrary:image];
}else
{
NSLog(@"NULL sampleBuffer:%@",[error localizedDescription]);
}
};
//捕捉靜態(tài)圖片
[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 框架
用來(lái)讓開(kāi)發(fā)者通過(guò)代碼方式訪問(wèn)iOS photo
注意:會(huì)訪問(wèn)到相冊(cè),需要修改plist 權(quán)限澄阳。否則會(huì)導(dǎo)致項(xiàng)目崩潰
*/
- (void)writeImageToAssetsLibrary:(UIImage *)image {
//創(chuàng)建ALAssetsLibrary 實(shí)例
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
//參數(shù)1:圖片(參數(shù)為CGImageRef 所以image.CGImage)
//參數(shù)2:方向參數(shù) 轉(zhuǎn)為NSUInteger
//參數(shù)3:寫入成功拥知、失敗處理
[library writeImageToSavedPhotosAlbum:image.CGImage
orientation:(NSUInteger)image.imageOrientation
completionBlock:^(NSURL *assetURL, NSError *error) {
//成功后,發(fā)送捕捉圖片通知碎赢。用于繪制程序的左下角的縮略圖
if (!error)
{
[self postThumbnailNotifification:image];
}else
{
//失敗打印錯(cuò)誤信息
id message = [error localizedDescription];
NSLog(@"%@",message);
}
}];
}
//發(fā)送縮略圖通知
- (void)postThumbnailNotifification:(UIImage *)image {
//回到主隊(duì)列
dispatch_async(dispatch_get_main_queue(), ^{
//發(fā)送請(qǐng)求
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:THThumbnailCreatedNotification object:image];
});
}
#pragma mark - Video Capture Methods 捕捉視頻
//判斷是否錄制狀態(tài)
- (BOOL)isRecording {
return self.movieOutput.isRecording;
}
//開(kāi)始錄制
- (void)startRecording {
if (![self isRecording]) {
//獲取當(dāng)前視頻捕捉連接信息低剔,用于捕捉視頻數(shù)據(jù)配置一些核心屬性
AVCaptureConnection * videoConnection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];
//判斷是否支持設(shè)置videoOrientation 屬性。
if([videoConnection isVideoOrientationSupported])
{
//支持則修改當(dāng)前視頻的方向
videoConnection.videoOrientation = [self currentVideoOrientation];
}
//判斷是否支持視頻穩(wěn)定 可以顯著提高視頻的質(zhì)量肮塞。只會(huì)在錄制視頻文件涉及
if([videoConnection isVideoStabilizationSupported])
{
videoConnection.enablesVideoStabilizationWhenAvailable = YES;
}
AVCaptureDevice *device = [self activeCamera];
//攝像頭可以進(jìn)行平滑對(duì)焦模式操作襟齿。即減慢攝像頭鏡頭對(duì)焦速度。當(dāng)用戶移動(dòng)拍攝時(shí)攝像頭會(huì)嘗試快速自動(dòng)對(duì)焦枕赵。
if (device.isSmoothAutoFocusEnabled) {
NSError *error;
if ([device lockForConfiguration:&error]) {
device.smoothAutoFocusEnabled = YES;
[device unlockForConfiguration];
}else
{
[self.delegate deviceConfigurationFailedWithError:error];
}
}
//查找寫入捕捉視頻的唯一文件系統(tǒng)URL.
self.outputURL = [self uniqueURL];
//在捕捉輸出上調(diào)用方法 參數(shù)1:錄制保存路徑 參數(shù)2:代理
[self.movieOutput startRecordingToOutputFileURL:self.outputURL recordingDelegate:self];
}
}
- (CMTime)recordedDuration {
return self.movieOutput.recordedDuration;
}
//寫入視頻唯一文件系統(tǒng)URL
- (NSURL *)uniqueURL {
NSFileManager *fileManager = [NSFileManager defaultManager];
//temporaryDirectoryWithTemplateString 可以將文件寫入的目的創(chuàng)建一個(gè)唯一命名的目錄猜欺;
NSString *dirPath = [fileManager temporaryDirectoryWithTemplateString:@"kamera.XXXXXX"];
if (dirPath) {
NSString *filePath = [dirPath stringByAppendingPathComponent:@"kamera_movie.mov"];
return [NSURL fileURLWithPath:filePath];
}
return nil;
}
//停止錄制
- (void)stopRecording {
//是否正在錄制
if ([self isRecording]) {
[self.movieOutput stopRecording];
}
}
#pragma mark - AVCaptureFileOutputRecordingDelegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error {
//錯(cuò)誤
if (error) {
[self.delegate mediaCaptureFailedWithError:error];
}else
{
//寫入
[self writeVideoToAssetsLibrary:[self.outputURL copy]];
}
self.outputURL = nil;
}
//寫入捕捉到的視頻
- (void)writeVideoToAssetsLibrary:(NSURL *)videoURL {
//ALAssetsLibrary 實(shí)例 提供寫入視頻的接口
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
//寫資源庫(kù)寫入前,檢查視頻是否可被寫入 (寫入前盡量養(yǎng)成判斷的習(xí)慣)
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:videoURL]) {
//創(chuàng)建block塊
ALAssetsLibraryWriteVideoCompletionBlock completionBlock;
completionBlock = ^(NSURL *assetURL,NSError *error)
{
if (error) {
[self.delegate assetLibraryWriteFailedWithError:error];
}else
{
//用于界面展示視頻縮略圖
[self generateThumbnailForVideoAtURL:videoURL];
}
};
//執(zhí)行實(shí)際寫入資源庫(kù)的動(dòng)作
[library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:completionBlock];
}
}
//獲取視頻左下角縮略圖
- (void)generateThumbnailForVideoAtURL:(NSURL *)videoURL {
//在videoQueue 上拷窜,
dispatch_async(self.videoQueue, ^{
//建立新的AVAsset & AVAssetImageGenerator
AVAsset *asset = [AVAsset assetWithURL:videoURL];
AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
//設(shè)置maximumSize 寬為100开皿,高為0 根據(jù)視頻的寬高比來(lái)計(jì)算圖片的高度
imageGenerator.maximumSize = CGSizeMake(100.0f, 0.0f);
//捕捉視頻縮略圖會(huì)考慮視頻的變化(如視頻的方向變化)涧黄,如果不設(shè)置,縮略圖的方向可能出錯(cuò)
imageGenerator.appliesPreferredTrackTransform = YES;
//獲取CGImageRef圖片 注意需要自己管理它的創(chuàng)建和釋放
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:kCMTimeZero actualTime:NULL error:nil];
//將圖片轉(zhuǎn)化為UIImage
UIImage *image = [UIImage imageWithCGImage:imageRef];
//釋放CGImageRef imageRef 防止內(nèi)存泄漏
CGImageRelease(imageRef);
//回到主線程
dispatch_async(dispatch_get_main_queue(), ^{
//發(fā)送通知赋荆,傳遞最新的image
[self postThumbnailNotifification:image];
});
});
}
@end