gpt4 book ai didi

swift - 在 xcode、Swift 3 中自定义相机

转载 作者:行者123 更新时间:2023-11-28 15:18:51 24 4
gpt4 key购买 nike

所以我遇到了这个问题,我试图在 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 的地方。

最佳答案

您的代码中似乎缺少一些东西:

1) 为了更改输入设备,您需要在添加新设备并以 session.commitConfiguration() 结束之前调用 session.beginConfiguration() 来重新配置 session >。此外,所有更改都应在后台队列(希望您已为 session 创建)上进行,以便在配置 session 时不会阻塞 UI。

2) 在使用 session.canAddInput(captureDeviceInput) 添加新设备之前,检查它允许新设备的 session 会更安全 + 删除以前的设备(后置摄像头)作为前+后不允许配置。

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 {

}
}
}
}

关于swift - 在 xcode、Swift 3 中自定义相机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46375271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com