Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notification if System Preferences Default Sound changed

This is fairly simple (I think). I'm simply wanting to get a notification in my application whenever a user changes the default sound input or sound output device in System Preferences - Sound. I'll be darned if I'm able to dig it out of the Apple docs, however.

As a side note, this is for OSX, not IOS.

Thanks guys!

like image 389
Chuck D Avatar asked Sep 27 '14 00:09

Chuck D


1 Answers

Set up an AudioObjectPropertyAddress for the default output device:

AudioObjectPropertyAddress outputDeviceAddress = {
    kAudioHardwarePropertyDefaultOutputDevice,
    kAudioObjectPropertyScopeGlobal,
    kAudioObjectPropertyElementMaster
};

Then, use AudioObjectAddPropertyListener to register a listener for changes in the default device:

AudioObjectAddPropertyListener(kAudioObjectSystemObject, 
                                 &outputDeviceAddress,
                                 &callbackFunction, nil);

The callback function looks like this:

OSStatus callbackFunction(AudioObjectID inObjectID, 
                            UInt32 inNumberAddresses,
                            const AudioObjectPropertyAddress inAddresses[],             
                            void *inClientData)

As a side note, you should also use AudioObjectPropertyAddress to tell the HAL to manage its own thread for notifications. You do this by setting the run loop selector to NULL. I actually perform this step before setting up the output device listener.

AudioObjectPropertyAddress runLoopAddress = {
    kAudioHardwarePropertyRunLoop, 
    kAudioObjectPropertyScopeGlobal,
    kAudioObjectPropertyElementMaster
};

CFRunLoopRef runLoop = NULL;
UInt32 size = sizeof(CFRunLoopRef);
AudioObjectSetPropertyData(kAudioObjectSystemObject, 
                            &runLoopAddress, 0, NULL, size, &runLoop);
like image 55
joelperry Avatar answered Sep 22 '22 21:09

joelperry