我正在尝试建立一个简单的视图,以便用户可以在前后摄像头之间切换。我有一个完美的工作视图,该视图可以显示我的后置摄像头正在使用的一切。
我正在使用此行来设置设备:
guard let captureDevice = AVCaptureDevice.default(for: .video) else {return}
在玩AVCaptureDevice时,我尝试使用此调用:
guard let captureDevice = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) else {
print("unable to get capture device")
return
}
当我改变了设置捕获设备的方式时,我的视图从显示任何摄像机图像(按预期)变为仅显示视图的背景图像。
当我仍然在两种情况下仍将设备设置为使用后置摄像头时,我更想知道为什么会这样。在下面,我注释了使我的代码正常工作的那一行,然后保留了破坏它的代码。
fileprivate func setupCaptureSession() {
let captureSession = AVCaptureSession()
//1. Setup inputs
//THIS LINE WORKS
//guard let captureDevice = AVCaptureDevice.default(for: .video) else {return}
//THIS LINE DOES NOT
guard let captureDevice = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) else {
print("unable to get capture device")
return
}
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
//Required as a safeguard to see if input can actually be used.
if captureSession.canAddInput(input) {
captureSession.addInput(input)
}
} catch let err {
print("Could not setup camera input: ", err)
}
//2. Setup outputs
if captureSession.canAddOutput(output){
captureSession.addOutput(output)
}
//3. Setup output preview
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.frame
view.layer.addSublayer(previewLayer)
captureSession.startRunning()
}