Capture video input on Mac

Generated on 7/31/2024

1 search

To capture video input on a Mac, you can use the AV Foundation framework. Here's a basic outline of the steps involved:

  1. Create an AV capture session: This session coordinates the data flow between the input (camera) and the output (file).

  2. Create an AV capture device: Set it to the default system preferred camera.

  3. Add an input to the session: This represents the input from the capture device.

  4. Add an output to the session: This manages the output and writes it to disk.

  5. Commit the configuration and start running the session.

Here's a snippet of code to illustrate this process:

import AVFoundation

let captureSession = AVCaptureSession()

guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(input)

let output = AVCaptureMovieFileOutput()
captureSession.addOutput(output)

captureSession.startRunning()

let outputURL = URL(fileURLWithPath: "path/to/output.mov")
output.startRecording(to: outputURL, recordingDelegate: self)

To extend this code to record spatial video, you need to:

  1. Change the AV capture device: Use the built-in dual wide camera for spatial video.

  2. Pick a supported video format: Iterate through the formats in the video device and check if spatial video capture is supported.

  3. Enable spatial video recording on the output.

Here's an example of how to modify the code for spatial video:

// Change the AV capture device
let captureDevice = AVCaptureDevice.default(.builtInDualWideCamera, for: .video, position: .back)

// Pick a supported video format
for format in captureDevice.formats {
    if format.isSpatialVideoCaptureSupported {
        try captureDevice.lockForConfiguration()
        captureDevice.activeFormat = format
        captureDevice.unlockForConfiguration()
        break
    }
}

// Enable spatial video recording
output.isSpatialVideoCaptureEnabled = true

For more detailed information, you can refer to the session Build compelling spatial photo and video experiences from WWDC 2024.

Relevant Sessions

  1. Build compelling spatial photo and video experiences
  2. Capture HDR content with ScreenCaptureKit
  3. Introducing enterprise APIs for visionOS