//添加链接库
LIBS += -framework CoreAudio
//添加头文件
#include <CoreAudio/CoreAudio.h>
/*
* 设备监听回调函数
*/
OSStatus AOPropertyListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void* inClientData)
{
for (UInt32 x=0; x<inNumberAddresses; x++)
{
switch (inAddresses[x].mSelector)
{
case kAudioHardwarePropertyDefaultInputDevice://default input device changed
{
break;
}
case kAudioHardwarePropertyDefaultOutputDevice://default output device changed
{
break;
}
case kAudioHardwarePropertyDefaultSystemOutputDevice://default system output device changed
{
break;
}
default://unknown message
break;
}
}
return noErr;
}
/*
* 监听系统扬声器变化
* isListen:true 监听,false 取消监听
* return:成功/失败
*/
bool listenSystemSpeaker(const bool isListen)
{
AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster };
//AOPropertyListenerProc 为回调函数
OSStatus status = noErr;
if (isListen)
{
status = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &theAddress, AOPropertyListenerProc, nil);
}
else
{
status = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &theAddress, AOPropertyListenerProc, nil);
}
return noErr==status ? true : false;
}