首页 > 解决方案 > 使用工作表对话框时 AVCaptureSession 不可见

问题描述

我在带有 ViewController 的情节提要中有一个自定义视图,可以向我展示 AVCaptureSessionPreviewLayer 的输出(在本例中为网络摄像头镜头)。在我的普通窗口中使用自定义视图时,一切都很好,我看到了视频输出。

但是,当我想在工作表对话框中使用自定义视图时,即使网络摄像头指示正在运行,视频也不可见。

这是 ViewController 代码:

import Cocoa
import AVKit

class RecordViewController: NSViewController {

    let captureSession = AVCaptureSession()
     var captureDevice : AVCaptureDevice?
     var previewLayer : AVCaptureVideoPreviewLayer?
    @IBOutlet weak var camera: NSView!

override func viewDidLoad() {
    super.viewDidLoad()

    camera.wantsLayer = true;
            camera.layer = CALayer()


            // Do any additional setup after loading the view, typically from a nib.
            captureSession.sessionPreset = AVCaptureSession.Preset.medium

            // Get all audio and video devices on this machine
            let devices = AVCaptureDevice.devices()

            // Find the FaceTime HD camera object
            for device in devices {
                print(device)

                // Camera object found and assign it to captureDevice
                if ((device as AnyObject).hasMediaType(AVMediaType.video)) {
                    print(device)
                    captureDevice = device as? AVCaptureDevice
                }
            }


            if captureDevice != nil {

                do {

                    try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice!))
                    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                    previewLayer?.frame = (self.camera.layer?.frame)!

                    // Add previewLayer into custom view
                    self.camera.layer?.addSublayer(previewLayer!)

                    // Start camera
                    captureSession.startRunning()

                } catch {
                    print(AVCaptureSessionErrorKey.description)
                }
            }    }

}

标签: swiftavcapturesession

解决方案


换行:

previewLayer?.frame = (self.camera.layer?.frame)!

至:

previewLayer?.frame = self.camera.bounds

如果你想让你的相机填满你的 customView,也可以使用这一行:

previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill


推荐阅读