2

在我的应用程序中,我正在使用 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;
            }
        }
    }

谢谢。

4

2 回答 2

7

如果您的 captureSessionsessionPreset与您要切换到的相机不兼容,则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];
} 
于 2013-05-16T15:50:08.810 回答
2

如果切换代码不在主线程上运行,我已经看到切换代码不起作用的问题。您可以尝试使用以下块包装您的代码:

dispatch_async(dispatch_get_main_queue(), ^{
   // Your camera toggle code goes here
});
于 2013-05-17T00:33:06.473 回答