iOS精品文章iOS高阶UI相关音、視頻編解碼

iOS-镜头采集(AVCaptureDevice)

2017-08-16  本文已影响532人  JackJin

承接上一篇博文小编讲述在镜头采集过程所需知识点和 AVCaptureSession 基本使用方法,本篇博文将要讲述 AVCaptureDevice 相关使用方法。

下图为本博文写作思路:

AVCaptureDevice博文写作思维导图.png

AVCaptureDevice

AVCaptureDevice 在这个采集过程中相当于在发电过程中“发电设备”,提供实现摄像头和麦克风相关初始化。而且可以对摄像头进行一些基本设置,例如:闪光灯、手电筒、聚焦、曝光、白平衡等一些基本设置。

AVCaptureDevice 初始化前需要对镜头申请权限,具体实现如下:

switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) {
        case AVAuthorizationStatusAuthorized:
        {
            //获取授权成功
            break;
        }
        case AVAuthorizationStatusNotDetermined:
        {
            //目前用户为选择
            dispatch_suspend(self.sessionQueue);//self.seaaionQueue 是串行线程
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (!granted) {
                    self.setupResult = FYCameraCaptureSetupResultNotAuthorized;
                }
                dispatch_resume(self.sessionQueue);
            }];
            break;
        }
        default:
        {
          //处理其余情况
            break;
        }
    }

请求硬件的获取状态,如下:

    AVAuthorizationStatusNotDetermined = 0,//用户暂时没有做相关选着
    AVAuthorizationStatusRestricted    = 1,//没有改媒体类型
    AVAuthorizationStatusDenied        = 2,//用户拒绝
    AVAuthorizationStatusAuthorized    = 3,//用户允许

在获取对 AVCaptureDevice 使用允许的情况中,可以获取上面四中情况。可以依次对上面三种情况进行处理。下面👇列出初始方法。

1) AVCaptureDevice基本初始方法

//方法(1)
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

//方法(2)
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInDuoCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];

2)AVCaptureDevice 实现镜头自动变焦

NSArray<AVCaptureDeviceType> *deviceType = @[AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInDualCamera];
AVCaptureDeviceDiscoverySession *videoDeviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:deviceType mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];

//获取 devices 
NSArray<AVCaptureDevice *> *devices = videoDeviceDiscoverySession.devices;

在使用 AVCaptureDeviceDiscoverySession 获取 AVCaptureDevice 过程中,使用 AVCaptureDeviceType
下面列出 AVCaptureDeviceType 种类:

//AVCaptureDeviceType 种类
AVCaptureDeviceTypeBuiltInMicrophone //创建麦克风
AVCaptureDeviceTypeBuiltInWideAngleCamera //创建广角相机
AVCaptureDeviceTypeBuiltInTelephotoCamera //创建比广角相机更长的焦距。只有使用 AVCaptureDeviceDiscoverySession 可以使用
AVCaptureDeviceTypeBuiltInDualCamera //创建变焦的相机,可以实现广角和变焦的自动切换。使用同AVCaptureDeviceTypeBuiltInTelephotoCamera 一样。
AVCaptureDeviceTypeBuiltInDuoCamera //iOS 10.2 被 AVCaptureDeviceTypeBuiltInDualCamera 替换

注释:iOS 10.2 之后添加自动变焦功能, 而且在查找自动变焦镜头时需要采用 AVCaptureDeviceDiscoverySession 进行查找。

下面👇列出通知的类型:

// Notification type 
AVCaptureDeviceWasConnectedNotification//设备被链接时发出通知
AVCaptureDeviceWasDisconnectedNotification//设备被去去除时发出通知
AVCaptureDeviceSubjectAreaDidChangeNotification//设备中场景改变时发出通知,既预览发生变化
AVCaptureDevicePositionUnspecified = 0, //不确定
AVCaptureDevicePositionBack        = 1,//后置
AVCaptureDevicePositionFront       = 2,//前置
// 如果初始的 AVMediaType 是 AVMediaTypeVideo 表示前置和后置摄像头

AVCaptureDeviceFlash(闪光灯)

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

    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");
        }
    }
    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,//闪光灯自动

太困了,晚上跑 10 公里。目前👁都睁不开。

在 iPhone 6s 开始,如果是前置摄像头并且开启闪光灯,可以实现屏幕闪光灯补光。

AVCaptureDeviceTorch(手电筒)

在光线不是很暗的情况下我们可以用手机的 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 isFlashAvailable]) {
            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");
    }

下面列出 Torch 类型,使用方法和闪关灯类型:

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

AVCaptureDeviceFocus(聚焦)

实现摄像头聚焦有两种情况:

1)镜头位置(AVCaptureFocusMode)

    AVCaptureDevice *device = nil;
    NSArray *inputs = self.session.inputs;
    for (AVCaptureDeviceInput *input in inputs) {
        if ([device.deviceType isEqual:AVMediaTypeVideo]) {
            device = input.device;
        }
    }
    if ([device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
        NSError *error;
        if ([device lockForConfiguration:&error]) {
            [device setFocusMode:AVCaptureFocusModeAutoFocus];
            //设置聚焦在设备坐标的中点
            if (device.focusPointOfInterestSupported) {
                device.focusPointOfInterest = CGPointMake(0.5, 0.5);
            }
        }
        [device unlockForConfiguration];
    }

上述代码实现聚焦在设备坐标 中心位置。

下面👇列出实现聚焦设置类型:

    AVCaptureFocusModeLocked              = 0,//锁定当前镜头位置
    AVCaptureFocusModeAutoFocus           = 1,//镜头自动调焦
    AVCaptureFocusModeContinuousAutoFocus = 2,//镜头连续自动调焦

AVCaptureDeviceExposure(曝光)

   AVCaptureDevice *device = nil;
    NSArray *inputs = self.session.inputs;
    for (AVCaptureDeviceInput *input in inputs) {
        if ([device.deviceType isEqual:AVMediaTypeVideo]) {
            device = input.device;
        }
    }
    if ([device isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
        NSError *error;
        if ([device lockForConfiguration:&error]) {
            [device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        [device unlockForConfiguration];
    }

上述代码实现自动调节曝光。

下面列出相关曝光设置类型:

    AVCaptureExposureModeLocked                            = 0,//锁定
    AVCaptureExposureModeAutoExpose                        = 1,//自动对焦
    AVCaptureExposureModeContinuousAutoExposure            = 2,//实现连续自动对焦
    AVCaptureExposureModeCustom NS_ENUM_AVAILABLE_IOS(8_0) = 3,//通过 ISO 和 曝光时间实现

AVCaptureDeviceWhiteBalance(白平衡)

1)类型设置白平衡

   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,

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

额外附加功能

附加功能:可以获取 AVCaptureDevice 一些相关的参数。

例如:

参考资料:
AVCaptureDevice
AVCaptureDevicePosition
AVCaptureTorchMode
AVCaptureFlashMode
AVCaptureFocusMode
AVCaptureExposureMode
AVCaptureWhiteBalanceMode
Advanced Camera Controls for iOS: Setting Manual White Balance

第一次发布:2017/8/15 23:16:32 星期二
第二次发布:2017/8/16 00:17:59 星期三
第三次发布:2017/8/16 20:53:56 星期三

上一篇下一篇

猜你喜欢

热点阅读