IOS切换AVFoundation相机

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

谢谢。

如果您的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]; } 

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

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