How to get notification if System Preferences Default Sound changed

后端 未结 2 404
鱼传尺愫
鱼传尺愫 2021-02-06 16:15

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 Pr

2条回答
  •  终归单人心
    2021-02-06 16:47

    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);
    

提交回复
热议问题