老谭笔记

检测Mac是否在使用耳机

前两天有朋友在我博客留言问如何检测Mac是否在使用耳机,今天抽时间去查了一下API,检测方法应该不只一种,我暂且贴出这一段代码吧:

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
42
43
44
45
46
47
48
49
50
#import "AppDelegate.h"
#import <CoreAudio/CoreAudio.h>
@interface AppDelegate ()
{
AudioDeviceID defaultDevice;
}
@end
@implementation AppDelegate
- (void)checkAudioHardware:(const AudioObjectPropertyAddress *)sourceAddr
{
UInt32 dataSourceId = 0;
UInt32 dataSourceIdSize = sizeof(UInt32);
AudioObjectGetPropertyData(defaultDevice, sourceAddr, 0, NULL, &dataSourceIdSize, &dataSourceId);
if (dataSourceId == 'ispk') {
NSLog(@"没用耳机");
} else if (dataSourceId == 'hdpn') {
NSLog(@"使用耳机");
}
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
//获得内置输出设备
UInt32 defaultSize = sizeof(AudioDeviceID);
const AudioObjectPropertyAddress defaultAddr =
{
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultAddr, 0, NULL, &defaultSize, &defaultDevice);
//注册输出设备改变的通知
AudioObjectPropertyAddress sourceAddr;
sourceAddr.mSelector = kAudioDevicePropertyDataSource;
sourceAddr.mScope = kAudioDevicePropertyScopeOutput;
sourceAddr.mElement = kAudioObjectPropertyElementMaster;
AudioObjectAddPropertyListenerBlock(defaultDevice, &sourceAddr, dispatch_get_current_queue(), ^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses) {
[self checkAudioHardware:inAddresses];
});
//第一次主动检测
[self checkAudioHardware:&sourceAddr];
}
@end