gpt4 book ai didi

ios - 切换到前置摄像头时 AVFoundation 摄像头崩溃(刷新摄像头)

转载 作者:行者123 更新时间:2023-11-30 12:14:35 25 4
gpt4 key购买 nike

我是 iOS 的新手,正在使用 swift 开发简单的应用程序,因为我需要一个自定义相机。我正在使用 AVFoundation,但该应用程序长时间显示黑屏,然后正在加载相机。这是我的代码

 func prepareCamera() {
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
if frontCam{
if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .front).devices {
captureDevice = availableDevices.first
DispatchQueue(label: "prepare").async {
self.beginSession()
}
}
}else{
if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .back).devices {
captureDevice = availableDevices.first
beginSession()
}
}
}
@IBAction func switchCameraBtnClicked(_ sender: Any) {
frontCam = !frontCam
prepareCamera()
}
func beginSession () {

do {
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
captureSession.removeInput(input)
}
}
if captureSession.inputs.isEmpty {
captureSession.addInput(captureDeviceInput)
}

}catch {
print(error.localizedDescription)
}


if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
self.previewLayer = previewLayer
// self.view.layer.addSublayer(self.previewLayer)
self.view.layer.insertSublayer(self.previewLayer, at: 0)
self.previewLayer.frame = self.view.layer.frame

captureSession.startRunning()

let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)]

dataOutput.alwaysDiscardsLateVideoFrames = true

if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
}

captureSession.commitConfiguration()


let queue = DispatchQueue(label: "com.graymatics.customcamera")
dataOutput.setSampleBufferDelegate(self, queue: queue)



}

}

如果代码不正确,请纠正。

最佳答案

终于找到解决办法了

这是我的代码:

override func viewDidDisappear(_ animated: Bool) {
self.stopCaptureSession()
}


func stopCaptureSession () {
self.captureSession.stopRunning()

if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
self.captureSession.removeInput(input)
}
}
}

从当前 View Controller 继续移动时需要停止 session 。

关于ios - 切换到前置摄像头时 AVFoundation 摄像头崩溃(刷新摄像头),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45589395/

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