Mac开发监听默认音频设备的变化

公司项目使用的音视频库需要在用户切换麦克风时收到通知,在网上找了很久半天,最后在苹果的官方示例代码中发现了解决方案

1
2
3
4
5
AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyDefaultInputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster };

AudioObjectAddPropertyListener(kAudioObjectSystemObject, &theAddress, AOPropertyListenerProc, (__bridge void * _Nullable)(self));

使用设备属性设置一个监听器,这里我需要监听麦克风设备的切换,所以选择了kAudioHardwarePropertyDefaultInputDeviceAOPropertyListenerProc为一个函数指针,作为通知后的回调
之后再实现AOPropertyListenerProc函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
OSStatus AOPropertyListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void* inClientData)
{

for (UInt32 x=0; x<inNumberAddresses; x++) {

switch (inAddresses[x].mSelector)
{
/*
* These are the other types of notifications we might receive, however, they are beyond
* the scope of this sample and we ignore them.
*
case kAudioHardwarePropertyDefaultInputDevice:
fprintf(stderr, "AOPropertyListenerProc: default input device changed\n");
break;

case kAudioHardwarePropertyDefaultOutputDevice:
fprintf(stderr, "AOPropertyListenerProc: default output device changed\n");
break;

case kAudioHardwarePropertyDefaultSystemOutputDevice:
fprintf(stderr, "AOPropertyListenerProc: default system output device changed\n");
break;
*/
case kAudioHardwarePropertyDefaultInputDevice:{
fprintf(stderr, "AOPropertyListenerProc: default input device changed\n");
}
break;
// case kAudioHardwarePropertyDevices:
// {
// fprintf(stderr, "AOPropertyListenerProc: kAudioHardwarePropertyDevices\n");
// }
// break;

default:
fprintf(stderr, "AOPropertyListenerProc: unknown message\n");
break;
}
}

return noErr;
}