IOS Toggle AVFoundation相机 [英] IOS Toggle AVFoundation Camera

查看:108
本文介绍了IOS Toggle AVFoundation相机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在使用AVFoundation捕获图像

In my App I'm capturing images using AVFoundation

我按下了一个按钮,可以在前后摄像头之间切换,但是它不起作用.

I made a button to switch between front and back cameras but it won't work.

这是我使用的代码:

if (captureDevice.position == AVCaptureDevicePositionFront) {
        for ( AVCaptureDevice *device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] ) {
            if ( device.position == AVCaptureDevicePositionBack) {


                NSError * error;
                AVCaptureDeviceInput * newDeviceInput = [[AVCaptureDeviceInput alloc]initWithDevice:device error:&error];
                [captureSesion beginConfiguration];
                for (AVCaptureDeviceInput *oldInput in [captureSesion inputs]) {
                    [captureSesion removeInput:oldInput];
                }

                if ([captureSesion canAddInput:newDeviceInput]) {
                    [captureSesion addInput:newDeviceInput];
                }                
                [captureSesion commitConfiguration];
                break;
            }
        }
    }

THX.

推荐答案

如果您的captureSession的sessionPreset与要切换到的相机不兼容,则将无法通过canAddInput测试.在切换相机之前,我总是重置为AVCaptureSessionPresetHigh,然后尝试将其切换为我喜欢的任何预设.这是我使用的代码:

If your captureSession's sessionPreset is not compatible with the camera you're switching to it will fail the canAddInput test. I always reset to AVCaptureSessionPresetHigh before toggling cameras then try to switch it to whatever preset I have preferred. Here's the code I use:

- (void)toggleCamera {
  AVCaptureDevicePosition newPosition = self.currentCameraPossition == AVCaptureDevicePositionBack ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
  AVCaptureDevice *device = [self videoDeviceWithPosition:newPosition];
  AVCaptureDeviceInput *deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];

  [_captureSession beginConfiguration];
  [_captureSession removeInput:self.deviceInput];
  [_captureSession setSessionPreset:AVCaptureSessionPresetHigh]; //Always reset preset before testing canAddInput because preset will cause it to return NO

  if ([_captureSession canAddInput:deviceInput]) {
    [_captureSession addInput:deviceInput];
    self.deviceInput = deviceInput;
    self.currentCameraPossition = newPosition;
  } else {
      [_captureSession addInput:self.deviceInput];
  }

  if ([device supportsAVCaptureSessionPreset:self.sessionPreset]) {
    [_captureSession setSessionPreset:self.sessionPreset];
  }

  if ([device lockForConfiguration:nil]) {
    [device setSubjectAreaChangeMonitoringEnabled:YES];
    [device unlockForConfiguration];
  }

  [_captureSession commitConfiguration];
} 

这篇关于IOS Toggle AVFoundation相机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆