美文网首页
AVFoundation - 捕捉设备: AVCaptureDe

AVFoundation - 捕捉设备: AVCaptureDe

作者: jinlei_123 | 来源:发表于2020-03-08 19:14 被阅读0次

    AVCaptureDevice是相机硬件的接口,用于配置底层硬件的属性,这些底层硬件包括前后置摄像头、麦克风、闪光灯等。

    验证授权

    1. 请求用户授权指定的媒体类型

    为保护用户隐私,应用在使用相机或者麦克风时,总是需要用户授权才能正常使用。当应用第一次需要权限的媒体类型创建任何AVCaptureDeviceInput对象时,系统会自动显示一个alert以请求用户授权。在被授予任何访问权限之前,任何AVMediaType类型的AVCaptureDevice都将关闭静默音频样本或黑色视频帧。
    调用下面方法,可以让应用直接获取用户授权,而不是需要等到创建AVCaptureDeviceInput对象时,系统自动显示一个alert以请求用户授权。

    + (void)requestAccessForMediaType:(AVMediaType)mediaType completionHandler:(void (^)(BOOL granted))handler
    

    该方法有两个参数:

    • 第一个参数mediaType: 媒体类型常量,可以是AVMediaTypeVideo和AVMediaTypeAudio,如果没有提供媒体类型或提供其他的媒体类型,都将抛出异常
    • 第二个参数(void (^)(BOOL granted))handler: 获得用户相应后调用的块,如果用户授予使用硬件的权限,则granted返回YES,否则返回NO.注意块回调可能在任意线程,如果需要处理UI,需要切回主线程。
      如果调用该方法之前,已经显示alert以请求用户授权,不管用户同意或者拒绝授权,该方法的回调都会立即放回用户曾经的授权结果,而不会再次显示一个alert请求用户授权。

    应用程序必须在配置信息info.plist中提供使用NSCameraUsageDescription或NSMicrophoneUsageDescription信息的解释。iOS在最初请求用户许可时显示了这个解释,然后在设置应用程序中显示。在没有使用说明的情况下启动AVCaptureSession会引发异常。

    2. 获取制定媒体类型的授权状态

    为了获悉应用程序是否获取指定媒体类型的权限,应用可以调用下面的类方法获取授权状态:

    + (AVAuthorizationStatus)authorizationStatusForMediaType:(AVMediaType)mediaType;
    

    该方法同步调用,会立即返回授权状态。如果此方法返回AVAuthorizationStatusNotDetermined,则可以调用+requestAccessForMediaType:completionHandler:以提示用户记录权限

    授权状态AVAuthorizationStatus

    • AVAuthorizationStatusNotDetermined: 用户尚未授权
    • AVAuthorizationStatusRestricted:不允许用户访问媒体捕获设备,用户不能改变客户机的状态,可能由于活跃的限制,如家长控制,这个状态通常是看不到的,用于发现设备的类方法不会返回用户被限制访问的设备。
    • AVAuthorizationStatusDenied:用户已经明确拒绝了应用访问捕获设备
    • AVAuthorizationStatusAuthorized: 用户授予应用访问捕获设备的权限

    媒体类型AVMediaType

    • AVMediaTypeVideo: 指定视频
    • AVMediaTypeAudio: 指定音频
    • AVMediaTypeText: 指定文本
    • AVMediaTypeClosedCaption: 指定闭路内容
    • AVMediaTypeSubtitle: 指定字幕
    • AVMediaTypeTimecode: 指定一个时间代码
    • AVMediaTypeMetadata: 指定元数据
    • AVMediaTypeMuxed: 指定混合媒体
    • AVMediaTypeMetadataObject
    • AVMediaTypeDepthData

    通知

    • AVCaptureDeviceWasConnectedNotification
      当新设备可用时发送一个通知,通知对象是AVCaptureDevice实例,表示已可用的设备。
    • AVCaptureDeviceWasDisconnectedNotification
      当现有设备不可用时发送一个通知,通知对象是AVCaptureDevice实例,表示不可用的设备。

    闪光灯

    在光线不足的情况下,需要开启屏幕的闪光灯来进行补光,便于镜头可以捕捉更好的场景,拍摄出好的照片和视频

    • iOS 10之前闪光灯设置
       AVCaptureDevice *device = nil;
       NSArray *inputs = self.session.inputs;
       for (AVCaptureDeviceInput *input in inputs) {
           if ([device.deviceType isEqual:AVMediaTypeVideo]) {
               device = input.device;
           }
       }
       NSError *errorProperty = nil;
       if ([device hasFlash]) {
           if ([device isFlashAvailable]) {
               if ([device isFlashModeSupported:AVCaptureFlashModeOn]) {
                   BOOL result = NO;
                   result = [device lockForConfiguration:&errorProperty];
                   if (result) {
                       [device setFlashMode:AVCaptureFlashModeOn];
                   }else {
                       NSLog(@"ERROR : CONFIGURATION CAPTURE DEVICE FLASH FAILURE, ERROR CODE:%ld", (long)errorProperty.code);
                   }
                   [device unlockForConfiguration];
               }else{
                   NSLog(@"ERROR : FLASH IS UNAVAILABLE BECAUSE THE DEVCICE OVERHEATS");
               }
           }else {
               NSLog(@"ERROR : SOFTWARE DEVICE HAVE NO FLASH");
           }
       }
    
    • iOS 10之后闪光灯设置
        NSArray *outputs = self.session.outputs;
        for (AVCaptureOutput *output in outputs) {
            if ([output isMemberOfClass:[AVCapturePhotoOutput class]]) {
                AVCapturePhotoOutput *photoOutput = (AVCapturePhotoOutput *)output;
                BOOL flashSupported = [[photoOutput supportedFlashModes] containsObject:@(AVCaptureFlashModeAuto)];
                if (flashSupported) {
                    AVCapturePhotoSettings *photoSettings = photoOutput.photoSettingsForSceneMonitoring;
                    photoSettings.flashMode = AVCaptureFlashModeAuto;
                }else {
                    NSLog(@"ERROR : PHOTOOUTPUT CAN NOT SUPPORT AVCAPTUREMODE TYPE");
                }
            }
        }
    
    • 闪光灯类型
        AVCaptureFlashModeOff  = 0,//闪光灯关闭
        AVCaptureFlashModeOn   = 1,//闪光灯开启
        AVCaptureFlashModeAuto = 2,//闪光灯自动
    

    手电筒

    在光线不是很暗的情况下我们可以用手机的LED灯当作手电筒使用。

        AVCaptureDevice *device = nil;
        NSArray *inputs = self.session.inputs;
        for (AVCaptureDeviceInput *input in inputs) {
            if ([device.deviceType isEqual:AVMediaTypeVideo]) {
                device = input.device;
            }
        }
        NSError *error = nil;
        if ([device hasTorch]) {
            if ([device isTorchAvailable]) {
                if ([device isTorchModeSupported:AVCaptureTorchModeOn]) {
                    BOOL result = NO;
                    result = [device lockForConfiguration:&error];
                    if (result) {
                        [device setTorchMode:AVCaptureTorchModeOn];
                    }else {
                        NSLog(@"ERROR : CONFIGURATION DEVICE TORCH FAIL AND ERROR CODE %ld", (long)error.code);
                    }
                    error = nil;
                    // Torch light
                    result = [device setTorchModeOnWithLevel:0.5 error:&error];
                    if (!result) {
                        NSLog(@"ERROR : DEVICE SET TORCH FAILURE AND ERROR CODE %ld", error.code);
                    }
                    [device unlockForConfiguration];
                }else {
                    NSLog(@"ERROR : DEVICE CAN NO SUPPORT TORCH");
                }
            }else {
                NSLog(@"ERROR : SOFTHARE DEVICE TORCH IS UNAVAILABLE BECAUSE OVERHEATS");
            }
        }else {
            NSLog(@"ERROR : SOFFHARE DEVICE HAS NO TORCH");
        }
    

    手电筒模式类型

       AVCaptureTorchModeOff  = 0,//关闭
       AVCaptureTorchModeOn   = 1,//打开
       AVCaptureTorchModeAuto = 2,//自动
    

    聚焦

    - (void)focusAtPoint:(CGPoint)point {
        AVCaptureDevice *device = [self activeCamera];
        
        if (device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            NSError *error;
            // 锁定设备准备配置,如果获得了锁
            if ([device lockForConfiguration:&error]) {
                // 将focusPointOfInterest属性设置CGPoint
                device.focusPointOfInterest = point;
                
                device.focusMode = AVCaptureFocusModeAutoFocus;
                
                // 释放该锁定
                [device unlockForConfiguration];
            } else {
                if ([self.delegate respondsToSelector:@selector(deviceConfigurationFailedWithError:)]) {
                    [self.delegate deviceConfigurationFailedWithError:error];
                }
            }
        }
    }
    
    • 聚焦类型
       AVCaptureFocusModeLocked              = 0,//锁定当前镜头位置
       AVCaptureFocusModeAutoFocus           = 1,//镜头自动调焦
       AVCaptureFocusModeContinuousAutoFocus = 2,//镜头连续自动调焦
    

    曝光

    - (void)exposeAtPoint:(CGPoint)point {
        AVCaptureDevice *device = [self activeCamera];
        
        if (device.isExposurePointOfInterestSupported && [device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
            NSError *error;
            
            if ([device lockForConfiguration:&error]) {
                device.exposurePointOfInterest = point;
                device.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
                
                [device unlockForConfiguration];
            } else {
                if ([self.delegate respondsToSelector:@selector(deviceConfigurationFailedWithError:)]) {
                    [self.delegate deviceConfigurationFailedWithError:error];
                }
            }
        }
    }
    
    • 曝光设置类型
        AVCaptureExposureModeLocked                            = 0,//锁定
        AVCaptureExposureModeAutoExpose                        = 1,//自动对焦
        AVCaptureExposureModeContinuousAutoExposure            = 2,//实现连续自动对焦
    

    白平衡

    • 类型设置白平衡
        AVCaptureDevice *device = nil;
        NSArray *inputs = self.session.inputs;
        for (AVCaptureDeviceInput *input in inputs) {
            if ([device.deviceType isEqual:AVMediaTypeVideo]) {
                device = input.device;
            }
        }
        if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            NSError *error;
            if ([device lockForConfiguration:&error]) {
                [device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
            }
            [device unlockForConfiguration];
        }
    

    白平衡类型

        AVCaptureWhiteBalanceModeLocked                     = 0,
        AVCaptureWhiteBalanceModeAutoWhiteBalance           = 1,
        AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance = 2,
    
    • RGB设置白平衡
        AVCaptureDevice *device = nil;
        NSArray *inputs = self.session.inputs;
        for (AVCaptureDeviceInput *input in inputs) {
            if ([device.deviceType isEqual:AVMediaTypeVideo]) {
                device = input.device;
            }
        }
        float maxWhiteBalance = device.maxWhiteBalanceGain;
        float redGain =  MIN(2.0, maxWhiteBalance);
        float greenGain = MIN(2.0, maxWhiteBalance);
        float blueGain = MIN(2.0, maxWhiteBalance);
        AVCaptureWhiteBalanceGains whiteBalanceGains = {
            redGain,
            greenGain,
            blueGain
        };
        
        [device setWhiteBalanceModeLockedWithDeviceWhiteBalanceGains:whiteBalanceGains completionHandler:nil];
    

    相关文章

      网友评论

          本文标题:AVFoundation - 捕捉设备: AVCaptureDe

          本文链接:https://www.haomeiwen.com/subject/ovskkhtx.html