In my app I need to be able to listen for system volume changes in OS X. Looking through the AudioToolbox library it seems like what I want is AudioHardwareServiceAddPropertyListener. I tried setting up the listener with the following code:
// Volume changed callback
static OSStatus onVolumeChange(AudioObjectID inObjectID,
UInt32 inNumberAddresses,
const AudioObjectPropertyAddress* inAddresses,
void* inClientData)
{
NSLog(@"Volume changed");
return noErr;
}
- (void) registerVolumeListener
{
// Get default output device id
AudioObjectPropertyAddress defaultOutputDevicePropertyAddress = {
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = kAudioObjectPropertyElementMaster,
.mSelector = kAudioHardwarePropertyDefaultOutputDevice
};
AudioDeviceID outputDeviceID = kAudioObjectUnknown;
UInt32 propertySize = sizeof(AudioDeviceID);
OSStatus status = AudioHardwareServiceGetPropertyData(kAudioObjectSystemObject,
&defaultOutputDevicePropertyAddress,
0,
NULL,
&propertySize,
&outputDeviceID);
// Set up listener for master volume property on default device
AudioObjectPropertyAddress virtualMasterVolumePropertyAddress = {
.mScope = kAudioDevicePropertyScopeOutput,
.mElement = kAudioObjectPropertyElementMaster,
.mSelector = kAudioHardwareServiceDeviceProperty_VirtualMasterVolume
};
status = AudioHardwareServiceAddPropertyListener(outputDeviceID,
&virtualMasterVolumePropertyAddress,
onVolumeChange,
(__bridge void*)self);
// Change default device volume to trigger callback
Float32 volumeToSet = .2;
propertySize = sizeof(Float32);
status = AudioHardwareServiceSetPropertyData(outputDeviceID,
&virtualMasterVolumePropertyAddress,
0,
NULL,
propertySize,
&volumeToSet);
}
but when I call registerVolumeListener from elsewhere in the code it doesn't trigger the onVolumeChange callback. When I change the system volume normally it doesn't trigger the callback either. Anyone have an idea of what might be going wrong?