iOS AVFoundation框架捕獲功能

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


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末笋妥,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子窄潭,更是在濱河造成了極大的恐慌挽鞠,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件狈孔,死亡現(xiàn)場(chǎng)離奇詭異信认,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)均抽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門嫁赏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人油挥,你說(shuō)我怎么就攤上這事潦蝇。” “怎么了深寥?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵攘乒,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我惋鹅,道長(zhǎng)则酝,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任闰集,我火速辦了婚禮沽讹,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘武鲁。我一直安慰自己爽雄,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布沐鼠。 她就那樣靜靜地躺著挚瘟,像睡著了一般。 火紅的嫁衣襯著肌膚如雪饲梭。 梳的紋絲不亂的頭發(fā)上乘盖,一...
    開(kāi)封第一講書(shū)人閱讀 51,443評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音排拷,去河邊找鬼侧漓。 笑死,一個(gè)胖子當(dāng)著我的面吹牛监氢,可吹牛的內(nèi)容都是我干的布蔗。 我是一名探鬼主播藤违,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼纵揍!你這毒婦竟也來(lái)了顿乒?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤泽谨,失蹤者是張志新(化名)和其女友劉穎璧榄,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體吧雹,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡骨杂,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了雄卷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片搓蚪。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖丁鹉,靈堂內(nèi)的尸體忽然破棺而出妒潭,到底是詐尸還是另有隱情,我是刑警寧澤揣钦,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布雳灾,位于F島的核電站,受9級(jí)特大地震影響冯凹,放射性物質(zhì)發(fā)生泄漏谎亩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一谈竿、第九天 我趴在偏房一處隱蔽的房頂上張望团驱。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至啼止,卻和暖如春道逗,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背献烦。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工滓窍, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人巩那。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓吏夯,卻偏偏與公主長(zhǎng)得像此蜈,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子噪生,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354