因此,我有一个问题,我试图创建一个自定义相机的Xcode,但是,由于某种原因,我无法得到它,以便它是设置为使用前面的相机。不管我在代码中做了什么修改,它似乎只使用后面的摄像头,我希望有人能慷慨地看一下下面的代码,看看我是不是遗漏了什么东西,或者哪里出了问题。任何帮助都将是非常感谢的,谢谢您的时间。
func SelectInputDevice() {
let devices = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera,
mediaType: AVMediaTypeVideo, position: .front)
if devices?.position == AVCaptureDevicePosition.front {
print(devices?.position)
frontCamera = devices
}
currentCameraDevice = frontCamera
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: currentCameraDevice)
captureSession.addInput(captureDeviceInput)
} catch {
print(error.localizedDescription)
}
}这就是frontCamera和currentCameraDevice是AVCaptureDevice的地方。
发布于 2017-09-23 18:16:39
似乎您的代码中缺少了一些东西:
1)为了更改输入设备,需要在添加新设备并以session.beginConfiguration()结束之前通过调用session.commitConfiguration()重新配置会话。此外,应该对后台队列进行所有更改(希望您已经为会话创建了该队列),以便在配置会话时不会阻止UI。
2)在使用session.canAddInput(captureDeviceInput) +删除以前的设备(后摄像头)添加新设备之前,使用front+back配置是不允许的,因此与会话检查比较安全。
3)还会更干净地检查你的设备是否有一个工作前摄像头(可能是坏的)之前,以防止任何碰撞。
将捕获设备改为前置摄像机的完整代码如下:
func switchCameraToFront() {
//session & sessionQueue are references to the capture session and its dispatch queue
sessionQueue.async { [unowned self] in
let currentVideoInput = self.videoDeviceInput //ref to current videoInput as setup in initial session config
let preferredPosition: AVCaptureDevicePosition = .front
let preferredDeviceType: AVCaptureDeviceType = .builtInWideAngleCamera
let devices = self.videoDeviceDiscoverySession.devices!
var newVideoDevice: AVCaptureDevice? = nil
// First, look for a device with both the preferred position and device type. Otherwise, look for a device with only the preferred position.
if let device = devices.filter({ $0.position == preferredPosition && $0.deviceType == preferredDeviceType }).first {
newVideoDevice = device
}
else if let device = devices.filter({ $0.position == preferredPosition }).first {
newVideoDevice = device
}
if let videoDevice = newVideoDevice {
do {
let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
self.session.beginConfiguration()
// Remove the existing device input first, since using the front and back camera simultaneously is not supported.
self.session.removeInput(currentVideoInput)
if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
}
else {
//fallback to current device
self.session.addInput(self.videoDeviceInput);
}
self.session.commitConfiguration()
}
catch {
}
}
}
}https://stackoverflow.com/questions/46375271
复制相似问题