切换
前置和后置摄像头需要重新配置捕捉会话。幸运的是,可以动态重新配置AVCaptureSession, 所以不必担心停止会话和重启会话带来的开销。不过我们对会话进行的任何改变,都要通过beginConfiguration和commitConfiguration方法进行单独的、原子性的变化。
- (BOOL)switchCameras {
if (![self canSwitchCameras]) { // 1
return NO;
}
NSError *error;
AVCaptureDevice *videoDevice = [self inactiveCamera]; // 2
AVCaptureDeviceInput *videoInput =
[AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if (videoInput) {
[self.captureSession beginConfiguration]; // 3
[self.captureSession removeInput:self.activeVideoInput]; // 4
if ([self.captureSession canAddInput:videoInput]) { // 5
[self.captureSession addInput:videoInput];
self.activeVideoInput = videoInput;
} else {
[self.captureSession addInput:self.activeVideoInput];
}
[self.captureSession commitConfiguration]; // 6
} else {
[self.delegate deviceConfigurationFailedWithError:error]; // 7
return NO;
}
return YES;
}
(1)首先要确认是否可以切换摄像头。如果不可以,则返回
NO,并退出方法。
(2)接下来,获取指向未激活摄像头的指针并为它创建一个新的AVCaptureDeviceInput.
(3)在会话中调用beginConiguration,并标注原子配置变化的开始。
(4)移除当前激活的AVCaptureDeviceInput.该当前视频捕捉设备输入信息必须在新的对象添加前移除。
(5) 执行标准测试来检查是否可以添加新的AVCaptureDevicelnput,如果可以,将它添加到会话并设置为activeVideolnput.为确保安全,如果新的输入不能被添加,需要重新添加之前的输入。
(6)配置完成后,对AVCaptureSession调用commitConfiguration,会分批将所有变更整合在一起,得出一个有关会话的单独的、原子性的修改。
(7)当创建新的AVCaptureDevicelnput时如果出现错误,需要通知委托来处理该错误。再次运行该应用程序。假设iOS设备具有两个摄像头,点击屏幕右上角的摄像头图标就可以切换前置和后置摄像头了。










网友评论