At Apple Developer documentation, https://developer.apple.com/documentation/avfoundation/avcapturedevice/discoverysession you can find the sentence
You can also key-value observe this property to monitor changes to the list of available devices.
But how to use it?
I tried it with the code above and tested on my MacBook with EarPods.
When I disconnect the EarPods, nothing was happened.
MacBook Air M2
macOS Sequoia 15.0.1
Xcode 16.0
import Foundation
import AVFoundation
let discovery_session = AVCaptureDevice.DiscoverySession.init(deviceTypes: [.microphone], mediaType: .audio, position: .unspecified)
let devices = discovery_session.devices
for device in devices {
print(device.localizedName)
}
let device = devices[0]
let observer = Observer()
discovery_session.addObserver(observer, forKeyPath: "devices", options: [.new, .old], context: nil)
let input = try! AVCaptureDeviceInput(device: device)
let queue = DispatchQueue(label: "queue")
var output = AVCaptureAudioDataOutput()
let delegate = OutputDelegate()
output.setSampleBufferDelegate(delegate, queue: queue)
var session = AVCaptureSession()
session.beginConfiguration()
session.addInput(input)
session.addOutput(output)
session.commitConfiguration()
session.startRunning()
let group = DispatchGroup()
let q = DispatchQueue(label: "", attributes: .concurrent)
q.async(group: group, execute: DispatchWorkItem() {
sleep(10)
session.stopRunning()
})
_ = group.wait(timeout: .distantFuture)
class Observer: NSObject {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("Change")
if keyPath == "devices" {
if let newDevices = change?[.newKey] as? [AVCaptureDevice] {
print("New devices: \(newDevices.map { $0.localizedName })")
}
if let oldDevices = change?[.oldKey] as? [AVCaptureDevice] {
print("Old devices: \(oldDevices.map { $0.localizedName })")
}
}
}
}
class OutputDelegate : NSObject, AVCaptureAudioDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
print("Output")
}
}