我正在使用AV基金会,我设置了一个按钮,我想在点按时在前置摄像头和后置摄像头之间切换。
如果我运行应用程序,然后点击按钮,控制台会告诉我我已成功将设备更改为前置摄像头,但屏幕仍显示后置摄像头正在看到的内容。
我需要更新屏幕,以便它真正显示前置摄像头看到的内容,并且真正捕获前置摄像头看到的内容。
这是我的IBAction代码,它连接到我的切换按钮:
-(IBAction)toggleCamera {
_inputDevice = [self frontCamera];
}
这是为“frontCamera”提供动力的方法实现:
- (AVCaptureDevice *)frontCamera {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if ([device position] == AVCaptureDevicePositionFront) {
NSLog(@"Device position during frontCamera method: %d", [device position]);
return device;
}
}
return nil;
}
答案 0 :(得分:1)
您需要做的不仅仅是设置输入设备。你有AVCaptureSession吗?如果是这样,每次交换相机时,您需要(1)重新配置会话,(2)删除当前输入,(3)添加新输入和(4)提交会话配置:
// Define a flag in your header file to keep track of the current camera input
BOOL isUsingFrontFacingCamera;
-(IBAction)toggleCamera
{
// determine the mode to switch to
AVCaptureDevicePosition desiredPosition;
if (isUsingFrontFacingCamera)
{
desiredPosition = AVCaptureDevicePositionBack;
}
else
desiredPosition = AVCaptureDevicePositionFront;
}
for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType: AVMediaTypeVideo])
{
if ([d position] == desiredPosition)
{
// configure the session
[session beginConfiguration];
// find and clear all the existing inputs
for (AVCaptureInput *oldInput in [session inputs])
{
[session removeInput:oldInput];
}
// add the new input to session
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
[session addInput:input];
// commit the configuration
[session commitConfiguration];
break;
}
}
// update the flag to reflect the current mode
isUsingFrontFacingCamera = !isUsingFrontFacingCamera;
}
根据此post
改编的答案