gpt4 book ai didi

ios - 预览不显示(AVCaptureVideoPreviewLayer)

转载 作者:行者123 更新时间:2023-11-30 11:08:19 29 4
gpt4 key购买 nike

我试图首先让我的应用程序显示广角相机的相机预览。但我所做的只是没有显示出来。 (该应用程序具有视频和音频权限,正在 iPhone 7 Plus 上进行测试)

这是我的 session 配置代码:

func configureSession() throws {
session.beginConfiguration()

// configure inputs
let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
let audioDevice = AVCaptureDevice.default(.builtInMicrophone, for: .audio, position: .unspecified)
guard let videoInput = try? AVCaptureDeviceInput(device: videoDevice!), let audioInput = try? AVCaptureDeviceInput(device: audioDevice!), session.canAddInput(videoInput), session.canAddInput(audioInput) else {
throw CameraError.configurationFailed
}

// configure outputs
let output = AVCaptureMovieFileOutput()
let previewOutput = AVCaptureVideoDataOutput()
previewOutput.alwaysDiscardsLateVideoFrames = true
previewOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String : NSNumber(value: kCVPixelFormatType_32BGRA)]
guard session.canAddOutput(output) && session.canAddOutput(previewOutput) else {
throw CameraError.configurationFailed
}
session.sessionPreset = .high
session.addOutput(output)
session.addOutput(previewOutput)

session.commitConfiguration()
}

这是 previewLayer 的代码:

// adds given view as previewView to the session
func configureAsPreview(_ view: UIView) {
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
view.layer.addSublayer(previewLayer)
previewLayer.frame = view.layer.frame
}

它正在 viewDidLoad 中被调用:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if cameraManager.hasPermissionForVideo {
try! cameraManager.configureSession()
cameraManager.configureAsPreview(self.previewView)
cameraManager.startSession()
} else {
performSegue(withIdentifier: "presentPermissions", sender: nil)
}
}

我做错了什么?我真的无法弄清楚,这可能只是一些愚蠢的小事。

谢谢。

最佳答案

在需要时尝试更新图层框架,并使用bounds而不是frame。图层不支持自动调整大小,您需要手动管理。

private var __previewLayer = AVCaptureVideoPreviewLayer? = nil
func configureAsPreview(_ view: UIView) {
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
self.view.layer.addSublayer(previewLayer)
previewLayer.frame = self.view.bounds
self.__previewLayer = previewLayer
}

override viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.__previewLayer?.frame = self.view.bounds
}

关于ios - 预览不显示(AVCaptureVideoPreviewLayer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52461466/

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