Created
January 1, 2019 03:12
-
-
Save knoguchi/9c7cd044f5cfcea112e0aa634d9f4e04 to your computer and use it in GitHub Desktop.
Built-in webcam access in macOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Tested in macOS Mojave (Dec 31, 2018) using Xcode 10.1 | |
* 1. Create a new Xcode project | |
* 2. Select macOS | |
* 3. Pick Cocoa App, give it a name, create | |
* 4. Open the project setting, click "Capabilities", goto "App Sandbox" -> "Hardware" -> check "Camera" | |
* 5. Open Info.plist of the project, and add row "Privacy - Camera Usage Description", give it some description | |
* 6. Open ViewController, and paste the code below | |
* 7. Click Play icon, give Cam access permissson "OK" | |
* 8. Voila! Preview screen! | |
*/ | |
import Cocoa | |
import AVFoundation | |
class ViewController: NSViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.wantsLayer = true | |
let session:AVCaptureSession = AVCaptureSession() | |
session.sessionPreset = AVCaptureSession.Preset.low | |
let device = AVCaptureDevice.default(for: .video) | |
print("device found = ", device) | |
let device_input : AVCaptureDeviceInput = try! AVCaptureDeviceInput(device: device!) | |
let previewLayer:AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session) | |
previewLayer.frame = view.bounds | |
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill | |
self.view.layer?.addSublayer(previewLayer) | |
if session.canAddInput(device_input) | |
{ | |
session.addInput(device_input) | |
} | |
session.startRunning() | |
} | |
override var representedObject: Any? { | |
didSet { | |
// Update the view, if already loaded. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment