Skip to content

Instantly share code, notes, and snippets.

@banjun
Created April 18, 2020 17:50
Show Gist options
  • Save banjun/f3722bb047dad775e62450ee8fb3efdd to your computer and use it in GitHub Desktop.
Save banjun/f3722bb047dad775e62450ee8fb3efdd to your computer and use it in GitHub Desktop.
Set AVCaptureSession output to BlackHole or another arbitrary device by an output device name
private let audioOutput: AVCaptureAudioPreviewOutput = {
let audioOutput = AVCaptureAudioPreviewOutput()
audioOutput.volume = UserDefaults.standard.volume
struct Device {
var name: String?
var uid: String?
}
var devicesProperty = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDevices, mScope: kAudioDevicePropertyScopeOutput, mElement: kAudioObjectPropertyElementWildcard)
var devicesSize: UInt32 = 0
AudioObjectGetPropertyDataSize(AudioObjectID(kAudioObjectSystemObject), &devicesProperty, 0, nil, &devicesSize)
let devicesResult = UnsafeMutablePointer<AudioDeviceID>.allocate(capacity: Int(devicesSize))
AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &devicesProperty, 0, nil, &devicesSize, devicesResult)
let deviceIDs = UnsafeBufferPointer(start: devicesResult, count: Int(devicesSize))
let devices = deviceIDs.map { deviceID -> Device in
var nameProperty = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceNameCFString, mScope: kAudioDevicePropertyScopeOutput, mElement: kAudioObjectPropertyElementWildcard)
var uidProperty = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyDeviceUID, mScope: kAudioDevicePropertyScopeOutput, mElement: kAudioObjectPropertyElementWildcard)
var size: UInt32 = UInt32(MemoryLayout<CFString>.size)
var name: CFString?
var uid: CFString?
AudioObjectGetPropertyData(deviceID, &nameProperty, 0, nil, &size, &name)
AudioObjectGetPropertyData(deviceID, &uidProperty, 0, nil, &size, &uid)
return Device(name: name as String?, uid: uid as String?)
}
NSLog("%@", "\(devices)")
audioOutput.outputDeviceUniqueID = devices.first {$0.name == "BlackHole 16ch"}?.uid
return audioOutput
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment