Skip to content

Instantly share code, notes, and snippets.

@christiangenco
Created December 30, 2020 02:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiangenco/e975b8166599025aebe5909ff9ce57ad to your computer and use it in GitHub Desktop.
Save christiangenco/e975b8166599025aebe5909ff9ce57ad to your computer and use it in GitHub Desktop.
Minimal macOS Swift app to show webcam video in a custom NSView
import Cocoa
import AVFoundation
// inspiration: https://www.youtube.com/watch?v=1_PUdhLQsZQ
class ViewController: NSViewController {
@IBOutlet weak var videoView: NSView!
private var cameraSession = AVCaptureSession()
private var camera: AVCaptureDevice!
func videoDevices() -> [AVCaptureDevice]{
let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera, .externalUnknown], mediaType: .video, position: .unspecified)
return discoverySession.devices
}
override func viewDidLoad() {
super.viewDidLoad()
print("view did load")
let devices = videoDevices()
let cameraName = "FaceTime HD Camera"
for device in devices{
// print(device.localizedName)
if(device.localizedName == cameraName) {
camera = device
}
}
do{
try cameraSession.addInput(AVCaptureDeviceInput(device: camera))
} catch let error{
print("uh-oh spaghet")
print(error.localizedDescription)
}
let preview = AVCaptureVideoPreviewLayer(session: cameraSession)
preview.videoGravity = .resizeAspectFill
videoView.layer = preview
cameraSession.sessionPreset = .high
cameraSession.startRunning()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment