如何使用Swift XCode访问Mac默认相机 [英] How to access Mac default camera using swift xcode

查看:158
本文介绍了如何使用Swift XCode访问Mac默认相机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我第一次为 Mac 编码。我想做的是访问默认相机并显示预览。第二步,如果需要,我将记录或快速拍摄。对于第一步,我编写了以下代码

Today i am coding for Mac first time. What I am trying to do is access the default camera and show a preview. 2nd step i will record or take a snap if i need. For the 1st step i have written the following code

import Cocoa
import AVFoundation
class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        var session:AVCaptureSession = AVCaptureSession()
        session.sessionPreset = AVCaptureSessionPresetLow
        var device:AVCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        //Preview
        var previewLayer:AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
        var myView:NSView = self.view
        previewLayer.frame = myView.bounds
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        self.view.layer?.addSublayer(previewLayer)
        session.startRunning()
    }
    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

我没看到这个代码打开了我的笔记本电脑默认相机或在视图上显示了任何内容。我在这里做错了什么?我可以寻找任何方向或任何示例,即使它在Obj-C中确实很有帮助。
TIA。

I don't see this code is turning on my laptop default camera or displaying anything on the view. What am i doing wrong here? Any direction or any example i can look for even if its in Obj-C would be really helpful. TIA.

推荐答案

在您的代码中,

self.view.layer?.addSublayer(previewLayer)

将由于 self.view.layer nil 而不会执行,因此不会执行。

will not be executed since self.view.layer is nil so that won't be executed.

A,这似乎不是唯一的问题,因为即使添加图层,相机也无法开始工作。您可能需要深入研究:

Alas, this does not seem to be only issue since even when adding a layer the camera does not start working. You will likely have to dig into this:

https://developer.apple.com/library/mac/samplecode/AVRecorder/Introduction/Intro.html

这篇关于如何使用Swift XCode访问Mac默认相机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆