IOS切换AVFoundation相机

时间:2013-05-16 15:43:39

标签: ios camera avfoundation avcapturesession

在我的应用程序中,我使用AVFoundation

捕获图像

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

这是我使用的代码:

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。

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:2)

如果没有在主线程上运行,我看到切换代码无效的问题。您可以尝试使用以下块包装代码:

dispatch_async(dispatch_get_main_queue(), ^{
   // Your camera toggle code goes here
});