为什么我的AVCaptureVideoPreviewLayer出现了?

时间:2016-07-27 12:02:50

标签: swift xcode macos

我试图制作一个Swift OsX应用程序,打开相机并显示正在录制的内容。

现在它只是一个ViewController,绿灯亮起让我觉得录音正在开始,但屏幕保持灰色并且没有任何显示。

这是ViewController的代码:

class ViewController: NSViewController, AVCaptureVideoDataOutputSampleBufferDelegate {

    let session = AVCaptureSession()
    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    @IBOutlet weak var imgView: NSImageView!

    func setUpSession() {
        self.session.sessionPreset = AVCaptureSessionPresetLow

        // Add the default input camera
        do {
            let input = try AVCaptureDeviceInput(device: device)
            self.session.addInput(input)
            print("Input added.")
        } catch let error as NSError {
            print(error)
        }

        var previewLayer = AVCaptureVideoPreviewLayer(session: session)
        previewLayer.frame = self.view.bounds
        previewLayer.position = CGPointMake(0, 0)
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

        self.view.layer = previewLayer
        self.session.startRunning()
        print("Session running.")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUpSession()
    }

    override var representedObject: AnyObject? {
        didSet {
            // Update the view, if already loaded.
        }
    }
}

1 个答案:

答案 0 :(得分:1)

尝试view.layer.addSublayer(previewLayer)