AVFoundation

一压状、視頻采集(也可以稱為捕捉)

AV Foundation 照片和視頻捕捉功能是從框架搭建之初就是它的強(qiáng)項(xiàng)。 從iOS 4.0 我們就可以直接訪問iOS的攝像頭和攝像頭生成的數(shù)據(jù)(照片凝危、視頻)搂鲫。目前捕捉功能仍然是蘋果公司多媒體工程師最關(guān)注的領(lǐng)域。 核心的捕捉類在iOS 和 OS X上是一致的。除了Mac OSX 為截屏功能定義了AVCaptureScreenInput 類模暗。但iOS上由于沙盒的限制不提供該類。我們討論的大部分功能都適應(yīng)于OS X開發(fā)的念祭。想嘗試Mac開發(fā)的同學(xué),可以挑戰(zhàn)一下哦碍侦!
思維導(dǎo)圖:https://zhimap.com/medit/95df35a2c8e44e2c83a8e05d7be37e62

捕捉會(huì)話(AVCaptureSession)

AV Foundation 捕捉棧核心類是AVCaptureSession粱坤。一個(gè)捕捉會(huì)話相當(dāng)于一個(gè)虛擬的“插線板”。用于連接輸入和輸出的資源瓷产。

捕捉設(shè)備(AVCaptureDevice)

AVCaptureDevice為攝像頭站玄、麥克風(fēng)等物理設(shè)備提供接口。大部分我們使用的設(shè)備都是內(nèi)置于MAC或者iPhone濒旦、iPad上的株旷。當(dāng)然也可能出現(xiàn)外部設(shè)備。但是AVCaptureDevice 針對(duì)物理設(shè)備提供了大量的控制方法。比如控制攝像頭聚焦晾剖、曝光锉矢、白平衡、閃光燈等齿尽。

捕捉設(shè)備的輸入(AVCaptureDeviceInput)

注意:為捕捉設(shè)備添加輸入沽损,不能添加到AVCaptureSession 中,必須通過將它封裝到一個(gè)AVCaptureDeviceInput實(shí)例中循头。這個(gè)對(duì)象在設(shè)備輸入數(shù)據(jù)和捕捉會(huì)話間扮演插頭的作用绵估。

捕捉的輸出(AVCaptureOutput)

AVCaptureOutput 是一個(gè)抽象類。用于為捕捉會(huì)話得到的數(shù)據(jù)尋找輸出的目的地卡骂」眩框架定義了一些抽象類的高級(jí)擴(kuò)展類。例如 AVCaptureStillImageOutput 和 AVCaptureMovieFileOutput類全跨。使用它們來捕捉靜態(tài)照片缝左、視頻。例如 AVCaptureAudioDataOutput 和 AVCaptureVideoDataOutput ,使用它們來直接訪問硬件捕捉到的數(shù)字樣本螟蒸。

捕捉連接(AVCaptureConnection)

AVCaptureConnection類.捕捉會(huì)話先確定由給定捕捉設(shè)備輸入渲染的媒體類型盒使,并自動(dòng)建立其到能夠接收該媒體類型的捕捉輸出端的連接。

捕捉預(yù)覽(AVCaptureVideoPreviewLayer)

如果不能在影像捕捉中看到正在捕捉的場(chǎng)景七嫌,那么應(yīng)用程序用戶體驗(yàn)就會(huì)很差少办。幸運(yùn)的是框架定義了AVCaptureVideoPreviewLayer 類來滿足該需求。這樣就可以對(duì)捕捉的數(shù)據(jù)進(jìn)行實(shí)時(shí)預(yù)覽诵原。
1.捕捉會(huì)話的相關(guān)設(shè)置

- (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;
        }
    }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;
        }
    }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("videoQueue", NULL);
    
    return YES;
}

2.開始采集

- (void)startSession {

    //檢查是否處于運(yùn)行狀態(tài)
    if (![self.captureSession isRunning])
    {
        //使用同步調(diào)用會(huì)損耗一定的時(shí)間吗蚌,則用異步的方式處理
        dispatch_async(self.videoQueue, ^{
            [self.captureSession startRunning];
        });
        
    }
}

3.停止采集

- (void)stopSession {
    
    //檢查是否處于運(yùn)行狀態(tài)
    if ([self.captureSession isRunning])
    {
        //使用異步方式腿倚,停止運(yùn)行
        dispatch_async(self.videoQueue, ^{
            [self.captureSession stopRunning];
        });
    }
    
}

4.根據(jù)攝像頭方向找到AVCaptureDevice

- (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;    
}

5.獲取當(dāng)前捕捉會(huì)話對(duì)應(yīng)的攝像頭的device

- (AVCaptureDevice *)activeCamera {

    //返回當(dāng)前捕捉會(huì)話對(duì)應(yīng)的攝像頭的device 屬性
    return self.activeVideoInput.device;
}

6.獲取到當(dāng)前未激活的攝像頭

//返回當(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;
   
}

7.獲取視頻捕捉設(shè)備的數(shù)量

//可用視頻捕捉設(shè)備的數(shù)量
- (NSUInteger)cameraCount {

     return [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    
}

8.是否可以切換攝像頭

//判斷是否有超過1個(gè)攝像頭可用
- (BOOL)canSwitchCameras {

    
    return self.cameraCount > 1;
}

8.切換攝像頭

//切換攝像頭
- (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];
        
        //判斷新的設(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
    {
        //創(chuàng)建AVCaptureDeviceInput 出現(xiàn)錯(cuò)誤饭豹,則通知委托來處理該錯(cuò)誤
        [self.delegate deviceConfigurationFailedWithError:error];
        return NO;
    }
    
    
    
    return YES;
}

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í)包吝,一定要先測(cè)試修改動(dòng)作是否能被設(shè)備支持。并不是所有的攝像頭都支持所有功能源葫,例如前置攝像頭就不支持對(duì)焦操作诗越,因?yàn)樗湍繕?biāo)距離一般在一臂之長的距離。但大部分后置攝像頭是可以支持全尺寸對(duì)焦息堂。嘗試應(yīng)用一個(gè)不被支持的動(dòng)作嚷狞,會(huì)導(dǎo)致異常崩潰。所以修改攝像頭設(shè)備前荣堰,需要判斷是否支持
9.當(dāng)前攝像頭是夠支持聚焦

- (BOOL)cameraSupportsTapToFocus {
    
    //詢問激活中的攝像頭是否支持興趣點(diǎn)對(duì)焦
    return [[self activeCamera] isFocusPointOfInterestSupported];
}

10.聚焦

- (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];
        }
        
    }
    
}

11.是否支持曝光

- (BOOL)cameraSupportsTapToExpose {
    
    //詢問設(shè)備是否支持對(duì)一個(gè)興趣點(diǎn)進(jìn)行曝光
    return [[self activeCamera] isExposurePointOfInterestSupported];
}

12.曝光

static const NSString *THCameraAdjustingExposureContext;

- (void)exposeAtPoint:(CGPoint)point {

    
    AVCaptureDevice *device = [self activeCamera];
    
    AVCaptureExposureMode exposureMode =AVCaptureExposureModeContinuousAutoExposure;
    
    //判斷是否支持 AVCaptureExposureModeContinuousAutoExposure 模式
    if (device.isExposurePointOfInterestSupported && [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];
    }
    
    
}

13.重新設(shè)置對(duì)焦&曝光

// 重新設(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];
    }
     
}

14.是否有閃光燈

//判斷是否有閃光燈
- (BOOL)cameraHasFlash {

    return [[self activeCamera] hasFlash];

}

15.獲取閃光燈模式

//閃光燈模式
- (AVCaptureFlashMode)flashMode {

    
    return [[self activeCamera] flashMode];
}

16.設(shè)置閃光燈模式

//設(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];
        }
        
    }

}

17.是否支持手電筒

//是否支持手電筒
- (BOOL)cameraHasTorch {

    return [[self activeCamera] hasTorch];
}

18.獲取手電筒模式

//手電筒模式
- (AVCaptureTorchMode)torchMode {

    return [[self activeCamera] torchMode];
}

設(shè)置手電筒模式

//設(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];
        }

    }
    
}

19.拍攝靜態(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) {
                        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 框架 
    用來讓開發(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)
                             {
                                 [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];
    });
}

20.拍視頻

#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];
        
        //在捕捉輸出上調(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:@"camera.XXXXXX"];
    
    if (dirPath) {
        
        NSString *filePath = [dirPath stringByAppendingPathComponent:@"camera_movie.mov"];
        return  [NSURL fileURLWithPath:filePath];
        
    }
    
    return nil;
    
}

//停止錄制
- (void)stopRecording {

    //是否正在錄制
    if ([self isRecording]) {
        [self.movieOutput stopRecording];
    }
}

21.視頻的代理方法

#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];
    
    //寫資源庫寫入前袍嬉,檢查視頻是否可被寫入 (寫入前盡量養(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];
            
        });
        
    });
    
}

二罐监、二維碼掃描

AVFoundation掃描二維碼:http://www.reibang.com/p/c15010d58476
用Zabar掃描二維碼:http://www.reibang.com/p/5094d7963ac4

三吴藻、AVAudioRecorder錄音

http://www.reibang.com/p/fb0b351f08bb

四、音頻的播放

http://www.reibang.com/p/fd4490cbcd22
http://www.reibang.com/p/8a003096e328

五笑诅、視頻的播放

http://www.reibang.com/p/d38dc83e3a83

六调缨、人臉識(shí)別

- (BOOL)setupSessionOutputs:(NSError **)error {

    
    self.metadataOutput = [[AVCaptureMetadataOutput alloc]init];
    
   
    
    //為捕捉會(huì)話添加設(shè)備
    if ([self.captureSession canAddOutput:self.metadataOutput]){
        [self.captureSession addOutput:self.metadataOutput];
        
        
        //獲得人臉屬性
        NSArray *metadatObjectTypes = @[AVMetadataObjectTypeFace];
        
        //設(shè)置metadataObjectTypes 指定對(duì)象輸出的元數(shù)據(jù)類型。
        /*
         限制檢查到元數(shù)據(jù)類型集合的做法是一種優(yōu)化處理方法吆你∠乙叮可以減少我們實(shí)際感興趣的對(duì)象數(shù)量
         支持多種元數(shù)據(jù)。這里只保留對(duì)人臉元數(shù)據(jù)感興趣
         */
        self.metadataOutput.metadataObjectTypes = metadatObjectTypes;
        
        //創(chuàng)建主隊(duì)列: 因?yàn)槿四槞z測(cè)用到了硬件加速妇多,而且許多重要的任務(wù)都在主線程中執(zhí)行伤哺,所以需要為這次參數(shù)指定主隊(duì)列。
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        
        
        //通過設(shè)置AVCaptureVideoDataOutput的代理者祖,就能獲取捕獲到一幀一幀數(shù)據(jù)
        [self.metadataOutput setMetadataObjectsDelegate:self queue:mainQueue];
     
        return YES;
    }else
    {
        //報(bào)錯(cuò)
        if (error) {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"Failed to still image output"};
            
            *error = [NSError errorWithDomain:THCameraErrorDomain code:THCameraErrorFailedToAddOutput userInfo:userInfo];
            
        }
        return NO;
    }

}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate

//捕捉數(shù)據(jù)
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
       fromConnection:(AVCaptureConnection *)connection {

    
    //使用循環(huán)立莉,打印人臉數(shù)據(jù)
    for (AVMetadataFaceObject *face in metadataObjects) {
        
        NSLog(@"Face detected with ID:%li",(long)face.faceID);
        NSLog(@"Face bounds:%@",NSStringFromCGRect(face.bounds));
        
    }
    
    
    //將元數(shù)據(jù) 傳遞給 THPreviewView.m   將元數(shù)據(jù)轉(zhuǎn)換為layer
    [self.faceDetectionDelegate didDetectFaces:metadataObjects];
    
}

七、三種代理總結(jié)

1.二維碼掃描七问、人臉識(shí)別
AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{}

2.錄制視頻(包括視頻和音頻)

 AVCaptureFileOutputRecordingDelegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
      fromConnections:(NSArray *)connections
                error:(NSError *)error{}

3.錄制視頻(僅包括視頻蜓耻,編碼時(shí))

AVCaptureVideoDataOutputSampleBufferDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市械巡,隨后出現(xiàn)的幾起案子刹淌,更是在濱河造成了極大的恐慌饶氏,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件有勾,死亡現(xiàn)場(chǎng)離奇詭異疹启,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)蔼卡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門喊崖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人雇逞,你說我怎么就攤上這事荤懂。” “怎么了喝峦?”我有些...
    開封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵势誊,是天一觀的道長。 經(jīng)常有香客問我谣蠢,道長粟耻,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任眉踱,我火速辦了婚禮挤忙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘谈喳。我一直安慰自己册烈,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開白布婿禽。 她就那樣靜靜地躺著赏僧,像睡著了一般。 火紅的嫁衣襯著肌膚如雪扭倾。 梳的紋絲不亂的頭發(fā)上淀零,一...
    開封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音膛壹,去河邊找鬼驾中。 笑死,一個(gè)胖子當(dāng)著我的面吹牛模聋,可吹牛的內(nèi)容都是我干的肩民。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼链方,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼持痰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起祟蚀,我...
    開封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤工窍,失蹤者是張志新(化名)和其女友劉穎占调,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體移剪,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年薪者,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了纵苛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡言津,死狀恐怖攻人,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情悬槽,我是刑警寧澤怀吻,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站初婆,受9級(jí)特大地震影響蓬坡,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜磅叛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一屑咳、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧弊琴,春花似錦兆龙、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至腋寨,卻和暖如春聪铺,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背精置。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來泰國打工计寇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人脂倦。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓番宁,卻偏偏與公主長得像,于是被迫代替她去往敵國和親赖阻。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蝶押,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355