Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when an Audio Device is disconnected in CoreAudio?

Is there a way to set up a listener for any Audio Device to detect if it's been removed or unplugged? I found this post which helps if you only care about built-in audio related devices:

How to get notifications when the headphones are plugged in/out? Mac

But I'm looking for a more universal solution (i.e. all devices, USB, HDMI, etc.). And it's OSX specific.

Any ideas on how to do this?

like image 783
bhawley Avatar asked Apr 28 '14 20:04

bhawley


1 Answers

I figured it out! One just needs to add a listener to the appropriate AudioDeviceID (the device you wish to monitor):

// add listener for detecting when a device is removed
const AudioObjectPropertyAddress alive_address =
{
  kAudioDevicePropertyDeviceIsAlive,
  kAudioObjectPropertyScopeGlobal,
  kAudioObjectPropertyElementMaster
};

AudioObjectAddPropertyListener(current_device_id_, &alive_address, deviceIsAliveCallback, &player_);

And then write the corresponding callback:

OSStatus deviceIsAliveCallback(AudioObjectID                       inObjectID,
                           UInt32                              inNumberAddresses,
                           const AudioObjectPropertyAddress    inAddresses[],
                           void*                               inClientData)
{
  // your code here
}

Hope this helps someone!

like image 182
bhawley Avatar answered Oct 17 '22 23:10

bhawley