Created
December 30, 2020 02:13
-
-
Save christiangenco/e975b8166599025aebe5909ff9ce57ad to your computer and use it in GitHub Desktop.
Minimal macOS Swift app to show webcam video in a custom NSView
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
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