我正在以自定义视图(cameraView)打开相机,并且对于后置相机也可以正常工作,但是当我使用自定义转弯button(TurnCamera)
将其切换到前端时,出现了以下问题:>
输入“ AVCaptureFigVideoDevice:0x1035c9e80 [Front 摄影机] [com.apple.avfoundation.avcapturedevice.built-in_video:1]“
但是我的自定义摄像头视图仍在显示后置摄像头,并且得到captureSession.canAddInput(input) = false
,我应该对前摄像头的info.plist进行任何访问吗?
我打开相机的代码是:-
func camera(){
let devices = AVCaptureDevice.devices(for: AVMediaType.video)
currentCaptureDevice = (usingFrontCamera ? getFrontCamera() : getBackCamera())
print(currentCaptureDevice)
for device in devices{
do{
let input = try AVCaptureDeviceInput(device: currentCaptureDevice!)
if captureSession.canAddInput(input){
captureSession.addInput(input)
sessionOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if captureSession.canAddOutput(sessionOutput){
captureSession.startRunning()
captureSession.addOutput(sessionOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
previewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
cameraView.layer.addSublayer(previewLayer)
previewLayer.position = CGPoint(x: self.cameraView.frame.width/2, y: self.cameraView.frame.height/2)
cameraView.contentMode = .scaleToFill
previewLayer.bounds = cameraView.frame
}
}
}
catch{
print("error")
}
}
}
“取回相机”功能是:-
func getBackCamera() -> AVCaptureDevice{
return AVCaptureDevice.default(for: AVMediaType.video)!
}
获取前置摄像头的功能是:-
func getFrontCamera() -> AVCaptureDevice?{
let videoDevices = AVCaptureDevice.devices(for: AVMediaType.video)
for device in videoDevices{
let device = device as! AVCaptureDevice
if device.position == AVCaptureDevice.Position.front {
return device
}
}
return nil
}
切换摄像机的按钮动作:-
@IBAction func TurnCamera(_ sender: UIButton) {
usingFrontCamera = !usingFrontCamera
camera()
}
在以下位置找到演示项目:-https://www.dropbox.com/s/6cfmbh3tnw5y4f7/SwitchingCamera.zip?dl=0
预先感谢
答案 0 :(得分:3)
我得到了答案,当从后退切换到前端时,我没有删除捕获会话输入。
我仅在两个功能中进行过更改 1:-较早
func getBackCamera() -> AVCaptureDevice{
return AVCaptureDevice.default(for: AVMediaType.video)!
}
现在,
func getBackCamera() -> AVCaptureDevice{
for i in captureSession.inputs {
captureSession.removeInput(i as! AVCaptureInput)
}
return AVCaptureDevice.default(for: AVMediaType.video)!
}
2:-较早
func getFrontCamera() -> AVCaptureDevice?{
let videoDevices = AVCaptureDevice.devices(for: AVMediaType.video)
for device in videoDevices{
let device = device as! AVCaptureDevice
if device.position == AVCaptureDevice.Position.front {
return device
}
}
return nil
}
现在,
func getFrontCamera() -> AVCaptureDevice?{
for i in captureSession.inputs {
captureSession.removeInput(i as! AVCaptureInput)
}
let videoDevices = AVCaptureDevice.devices(for: AVMediaType.video)
for device in videoDevices{
let device = device
if device.position == AVCaptureDevice.Position.front {
return device
}
}
return nil
}
获取演示:-https://www.dropbox.com/s/p6opina5gtg8nvd/Updated%20Switching%20Camera%202.zip?dl=0