检测Mac是否在使用耳机 发表于 2013-08-27 | 分类于 pieces 前两天有朋友在我博客留言问如何检测Mac是否在使用耳机,今天抽时间去查了一下API,检测方法应该不只一种,我暂且贴出这一段代码吧: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#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