如何使用 swift xcode 访问 Mac 默认相机

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28783312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:44:42  来源:igfitidea点击:

How to access Mac default camera using swift xcode

xcodemacosswiftavcapturedevice

提问by KD.

Today i am coding for Macfirst 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

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

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.
        }
    }
}

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.

我没有看到此代码打开了我的笔记本电脑默认摄像头或在视图上显示任何内容。我在这里做错了什么?我可以寻找的任何方向或任何示例,即使它在 Obj-C 中也会非常有帮助。TIA。

采纳答案by qwerty_so

In your code the

在您的代码中

self.view.layer?.addSublayer(previewLayer)

will not be executed since self.view.layeris nilso that won't be executed.

将不执行,因为self.view.layernil这样就不会被执行。

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

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

回答by Rick

Be sure to check that your view has a Core Animation Layer in IB:

请务必检查您的视图在 IB 中是否具有核心动画层:

enter image description here

在此处输入图片说明

回答by SUMIT NIHALANI

Working code in swift 5.

Swift 5 中的工作代码

import Cocoa
import AVFoundation

class SomwViewController: NSViewController {
    @IBOutlet private var cameraView: NSView?
    let session: AVCaptureSession = AVCaptureSession()

    override func viewDidLoad() {
        super.viewDidLoad()
        cameraView?.wantsLayer = true
        cameraView?.layer?.backgroundColor = NSColor.black.cgColor
        session.sessionPreset = AVCaptureSession.Preset.low
        let input: AVCaptureInput = try! AVCaptureDeviceInput(device: AVCaptureDevice.default(for: .video)!)
        session.addInput(input)
        let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
        previewLayer.frame = cameraView!.bounds
        previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

        cameraView?.layer?.addSublayer(previewLayer)
    }

    override func viewDidAppear() {
        session.startRunning()
    }

    override func viewDidDisappear() {
        session.stopRunning()
    }
}

You should definitely not use force unwraps, it's just an example.

你绝对不应该使用强制解包,这只是一个例子。

回答by rolling Ztoned

if anyone still looking to launch webcam in Mac OS X using swift 3

如果有人仍然希望使用 swift 3 在 Mac OS X 中启动网络摄像头

here is the code

这是代码

@IBOutlet var previewCam: PreviewCam!
override func viewDidLoad()
{
    super.viewDidLoad()
    view.wantsLayer = true
    previewCam.wantsLayer = true
    let session:AVCaptureSession = AVCaptureSession()
    session.sessionPreset = AVCaptureSessionPresetLow
    let device:AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    print("device found = ",device)

    let device_input : AVCaptureDeviceInput = try! AVCaptureDeviceInput(device: device)


    let previewLayer:AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)

    previewLayer.frame = previewCam.bounds
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.previewCam.layer?.addSublayer(previewLayer)
    if session.canAddInput(device_input)
    {
        session.addInput(device_input)
    }
    session.startRunning()
}

for those who asked about preview cam

对于那些询问预览凸轮的人

#import "PreviewCam.h"

@implementation PreviewCam

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    // Drawing code here.
    CGContextRef context = [[NSGraphicsContext currentContext]graphicsPort];
    CGContextSetRGBFillColor(context, 0, 0, 0, 0.75);
    CGContextFillRect(context, NSRectToCGRect(dirtyRect));
    self.layer.borderColor = [[NSColor whiteColor]CGColor];
    self.layer.borderWidth = 2.0f;
}