使用AudioHardwareServiceAddPropertyListener监听OS X系统卷更改

时间:2015-07-09 21:43:56

标签: objective-c macos audiotoolbox

在我的应用程序中,我需要能够监听OS X中的系统卷更改。通过AudioToolbox库查看我想要的是AudioHardwareServiceAddPropertyListener。我尝试使用以下代码设置监听器:

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

但是当我从代码中的其他地方调用registerVolumeListener时,它不会触发onVolumeChange回调。当我正常更改系统音量时,它也不会触发回调。任何人都知道可能出现的问题?

0 个答案:

没有答案