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.
}
}
}
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.
In your code the
self.view.layer?.addSublayer(previewLayer)
will not be executed since self.view.layer
is nil
so that won't be executed.
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
Working code in 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With