AVFoundation
- 照片/視頻捕捉功能
- 小視頻/直播
- 核心類在iOS和macOS上是一致的赊舶,macOS上提供了一個(gè)截屏功能
捕捉會(huì)話
- ????????捕捉會(huì)話: AVCaptureSession
- 捕捉設(shè)備????????: AVCaptureDevice.如麥克風(fēng)跳座、攝像頭
- ????????????????????????捕捉設(shè)備輸入: AVCaptureDeviceInput
- 捕捉設(shè)備輸出:AVCaptureOutput 抽象類
- AVCaptureStillImageOutput 靜態(tài)圖片
- AVCaptureMovieFileOutput 視頻文件
- AVCaptureAudioDataOutput 音頻數(shù)據(jù)
- AVCaptureVideoDataOutput 視頻數(shù)據(jù)
- 捕捉連接:AVCaptureConnection 根據(jù)捕捉的輸出設(shè)備的渲染媒體類型自動(dòng)建立連接
- 捕捉預(yù)覽: AVCaptureVideoPreviewLayer
視頻預(yù)覽圖層
//私有方法 用于支持該類定義的不同觸摸處理方法。 將屏幕坐標(biāo)系上的觸控點(diǎn)轉(zhuǎn)換為攝像頭上的坐標(biāo)系點(diǎn)
- (CGPoint)captureDevicePointForPoint:(CGPoint)point {
AVCaptureVideoPreviewLayer *layer =
(AVCaptureVideoPreviewLayer *)self.layer;
return [layer captureDevicePointOfInterestForPoint:point];
/*
AVCaptureVideoPreviewLayer.定義了兩個(gè)方法,攝像頭/屏幕坐標(biāo)轉(zhuǎn)換躁愿;
captureDevicePointOfInterestForPoint :獲取屏幕坐標(biāo)系的CGPoint數(shù)據(jù),返回轉(zhuǎn)換得到攝像頭設(shè)備坐標(biāo)系的CGPoint數(shù)據(jù)
pointForCaptureDevicePointOfInterest : 獲取攝像頭坐標(biāo)系的CGPoint數(shù)據(jù)辫樱,返回轉(zhuǎn)換得到的屏幕坐標(biāo)系CGPoint數(shù)據(jù)
*/
}
視頻捕捉關(guān)于AVCaputureSession的配置
- ????設(shè)置Session
- 初始化
- 設(shè)置分辨率
- 配置輸入設(shè)備(注意轉(zhuǎn)換為AVCaptureDeviceInput)
- 配置輸入設(shè)備包括音頻輸入彭沼、視頻輸入
- 配置輸出(靜態(tài)圖像輸出褐奴、視頻文件輸出)
- 在為session添加輸入輸出時(shí)按脚,注意一定判斷是否能添加。(攝像頭并不隸屬于任何一個(gè)App它是公共設(shè)備)
- (BOOL)setupSession:(NSError **)error {
//創(chuàng)建捕捉會(huì)話敦冬。AVCaptureSession 是捕捉場景的中心樞紐
self.captureSession = [[AVCaptureSession alloc]init];
/*
AVCaptureSessionPresetHigh
AVCaptureSessionPresetMedium
AVCaptureSessionPresetLow
AVCaptureSessionPreset640x480
AVCaptureSessionPreset1280x720
AVCaptureSessionPresetPhoto
*/
//設(shè)置圖像的分辨率
self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
/** 添加視頻設(shè)備 */
//拿到默認(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:測試是否能被添加到會(huì)話中。攝像頭是公共設(shè)備脖旱,不隸屬于任何一個(gè)app堪遂,可能其他app也在使用
if ([self.captureSession canAddInput:videoInput])
{
//將videoInput 添加到 captureSession中
[self.captureSession addInput:videoInput];
//記錄當(dāng)前活躍設(shè)備
self.activeVideoInput = videoInput;
}
}else
{
return NO;
}
/** 添加音頻設(shè)備 */
//選擇默認(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:測試是否能被添加到會(huì)話中
if ([self.captureSession canAddInput:audioInput])
{
//將audioInput 添加到 captureSession中
[self.captureSession addInput:audioInput];
//麥克風(fēng)就一個(gè),無須記錄
}
}else
{
return NO;
}
/** 設(shè)置輸出:照片萌庆、視頻文件 */
//AVCaptureStillImageOutput 實(shí)例 從攝像頭捕捉靜態(tài)圖片
self.imageOutput = [[AVCaptureStillImageOutput alloc]init];
//配置字典:希望捕捉到JPEG格式的圖片(存儲(chǔ)格式)
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];
}
//初始化視頻隊(duì)列
self.videoQueue = dispatch_queue_create("bear.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];
});
}
}
實(shí)現(xiàn)前后攝像頭的改變
#pragma mark - Device Configuration 配置攝像頭支持的方法
//尋找指定的攝像頭設(shè)備
- (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;
}
//獲取當(dāng)前活躍設(shè)備
- (AVCaptureDevice *)activeCamera {
//返回當(dāng)前捕捉會(huì)話對(duì)應(yīng)的攝像頭的device 屬性
return self.activeVideoInput.device;
}
//返回當(dāng)前未激活的攝像頭
- (AVCaptureDevice *)inactiveCamera {
//通過查找當(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;
}
//判斷是否有超過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)注原配置變化開始
[self.captureSession beginConfiguration];
//將捕捉會(huì)話中,原本的捕捉輸入設(shè)備移除
[self.captureSession removeInput:self.activeVideoInput];
//不加上面兩句會(huì)一直加入失敗
//判斷新的設(shè)備是否能加入
if ([self.captureSession canAddInput:videoInput])
{
//能加入成功垫言,則將videoInput 作為新的視頻捕捉設(shè)備
[self.captureSession addInput:videoInput];
//將獲得設(shè)備 改為 videoInput
self.activeVideoInput = videoInput;
}else
{
//如果新設(shè)備贰剥,無法加入。則將原本的視頻捕捉設(shè)備重新加入到捕捉會(huì)話中
[self.captureSession addInput:self.activeVideoInput];
}
//配置完成后筷频,提交 AVCaptureSession commitConfiguration 會(huì)分批的將所有變更整合在一起蚌成。
[self.captureSession commitConfiguration];
}else
{
//設(shè)備添加錯(cuò)誤
//創(chuàng)建AVCaptureDeviceInput 出現(xiàn)錯(cuò)誤,則通知委托來處理該錯(cuò)誤
[self.delegate deviceConfigurationFailedWithError:error];
return NO;
}
return YES;
}
實(shí)現(xiàn)攝像頭自動(dòng)聚焦功能
捕捉設(shè)備(聚焦/曝光)
AVCapture Device 定義了很多方法凛捏,讓開發(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í)蚜点,一定要先測試修改動(dòng)作是否能被設(shè)備支持轧房。并不是所有的攝像頭都支持所有功能,例如前置攝像頭就不支持對(duì)焦操作绍绘,因?yàn)樗湍繕?biāo)距離一般在一臂之長的距離奶镶。但大部分后置攝像頭是可以支持全尺寸對(duì)焦迟赃。嘗試應(yīng)用一個(gè)不被支持的動(dòng)作,會(huì)導(dǎo)致異常崩潰厂镇。所以修改攝像頭設(shè)備前捺氢,需要判斷是否支持
#pragma mark - Focus Methods 點(diǎn)擊聚焦方法的實(shí)現(xiàn)
- (BOOL)cameraSupportsTapToFocus {
//詢問激活中的攝像頭是否支持興趣點(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)備配置,如果獲得了鎖
//因?yàn)榕渲脮r(shí)剪撬,不能讓多個(gè)對(duì)象對(duì)他進(jìn)行更改,所以要對(duì)該過程上鎖
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];
}
}
}
實(shí)現(xiàn)攝像頭自動(dòng)曝光以及鎖定曝光
#pragma mark - Exposure Methods 點(diǎn)擊曝光的方法實(shí)現(xiàn)
- (BOOL)cameraSupportsTapToExpose {
//詢問設(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];
}
}
實(shí)現(xiàn)攝像頭手電筒和閃光燈模式的開啟關(guān)閉
#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è)置是否打開手電筒
- (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];
}
}
}
靜態(tài)圖片的拍攝
#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) {
//從緩沖區(qū)身弊,將緩沖數(shù)據(jù)轉(zhuǎn)換成靜態(tài)圖片
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;
}
/*
Assets Library 框架
用來讓開發(fā)者通過代碼方式訪問iOS photo
注意:會(huì)訪問到相冊(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)
{
//拍照時(shí),左下角都有一個(gè)圖片縮略圖
[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];
});
}
視頻錄制實(shí)現(xiàn)
-
關(guān)于QuckTime
視頻內(nèi)容的捕捉:當(dāng)設(shè)置捕捉會(huì)話時(shí)填硕,添加一個(gè)名為AVCaptureMovieFileOutput的輸出麦萤。這個(gè)類定義了方法將QuckTime影片捕捉到磁盤鹿鳖。這個(gè)類大多數(shù)核心功能繼承于父類AVCaptureFileOutput。這個(gè)父類定義了許多實(shí)用功能壮莹,比如錄制到最長時(shí)限或錄制到特定文件大小時(shí)為止翅帜。還可以配置成保留最小可用的磁盤空間,這一點(diǎn)在存儲(chǔ)空間有限的移動(dòng)設(shè)備上錄制視頻時(shí)非常重要
-
通常當(dāng)QuckTime影片準(zhǔn)備發(fā)布時(shí)命满,影片頭的元數(shù)據(jù)處于文件的開始位置涝滴。這樣可以讓那個(gè)視頻播放器快速讀取頭包含信息,來確定文件的內(nèi)容胶台、結(jié)構(gòu)和其包含的多個(gè)樣本的位置歼疮。不過,當(dāng)錄制一個(gè)QuckTime影片時(shí)诈唬,直到所有的樣片都完成捕捉后才能創(chuàng)建信息頭韩脏。當(dāng)錄制結(jié)束時(shí),創(chuàng)建頭數(shù)據(jù)并將它附在文件結(jié)尾處铸磅。
-
將創(chuàng)建頭過程放在所有影片樣本完成捕捉之后存在一個(gè)問題赡矢,尤其是在移動(dòng)設(shè)備的情況下。如果遇到崩潰或者其他中斷阅仔,比如電話撥入吹散,則影片頭就不會(huì)被正確寫入,會(huì)在磁盤生成一個(gè)不可讀的影片文件霎槐。AVCaptureMovieFileOutput提供一個(gè)核心功能就是分段捕捉QuickTime影片送浊。
#pragma mark - Video Capture Methods 捕捉視頻
//判斷是否錄制狀態(tài)
- (BOOL)isRecording {
return self.movieOutput.isRecording;
}
//開始錄制
- (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];
//開始錄制。直播/小視頻 ---> 捕捉到視頻信息 ---> 壓縮(AAC/H264)
//錄制成一個(gè)QuckTime視頻文件 --> 存儲(chǔ)到相冊(cè)报辱。(也涉及到編碼--硬編碼--由于AVFoundation已經(jīng)替你完成)
//在捕捉輸出上調(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è)唯一命名的目錄与殃;
//臨時(shí)文件,沒下載完成前是沒有后綴名的碍现,下載完成后才會(huì)變成正確的后綴名
NSString *dirPath = [fileManager temporaryDirectoryWithTemplateString:@"kamera.XXXXXX"];
if (dirPath) {
//mov.視頻封裝的容器幅疼。和視頻編碼格式有區(qū)別
NSString *filePath = [dirPath stringByAppendingPathComponent:@"kamera_movie.mov"];
return [NSURL fileURLWithPath:filePath];
}
return nil;
}
//停止錄制
- (void)stopRecording {
//是否正在錄制
if ([self isRecording]) {
[self.movieOutput stopRecording];
}
}
視頻拍攝縮略圖實(shí)現(xiàn)
#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;
}
//寫入捕捉到的視頻到相冊(cè)
- (void)writeVideoToAssetsLibrary:(NSURL *)videoURL {
//ALAssetsLibrary 實(shí)例 提供寫入視頻的接口
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
//寫資源庫寫入前,檢查視頻是否可被寫入 (寫入前盡量養(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í)際寫入資源庫的動(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ù)視頻的寬高比來計(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];
});
});
}