- (id)init { self = [super init]; if (self) { /* OSStatus AudioSessionInitialize ( CFRunLoopRef inRunLoop, //運行循環的中斷監聽器回調應該被運行。傳遞NULL,使用主運行循環。 CFStringRef inRunLoopMode, //該模式的運行循環的中斷監聽功能將運行在。傳遞NULL,就相當於通過kCFRunLoopDefaultMode AudioSessionInterruptionListener inInterruptionListener, //中斷監聽器回調函數。應用程序的音頻會話對象調用回調時,會話被中斷及(如應用程序仍在運行)中斷結束時。可以為NULL。見AudioSessionInterruptionListener void *inClientData //想傳遞給你的中斷監聽器回調。 ); */ AudioSessionInitialize(NULL, NULL, NULL, NULL); AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioRouteChangeCallback, (__bridge void *)(self)); } return self; } - (BOOL)isHeadphone { UInt32 propertySize = sizeof(CFStringRef); CFStringRef state = nil; AudioSessionGetProperty(kAudioSessionProperty_AudioRoute ,&propertySize,&state); //根據狀態判斷是否為耳機狀態 if ([(__bridge NSString *)state isEqualToString:@"Headphone"] ||[(__bridge NSString *)state isEqualToString:@"HeadsetInOut"]) return YES; else return NO; } void audioRouteChangeCallback(void *inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void *inData) { SInt32 routeChangeReason; CFDictionaryRef routeChangeDictionary = inData; CFNumberRef routeChangeReasonRef = CFDictionaryGetValue(routeChangeDictionary, CFSTR(kAudioSession_AudioRouteChangeKey_Reason)); CFNumberGetValue(routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason); if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) { //拔掉 } else if (routeChangeReason == kAudioSessionRouteChangeReason_NewDeviceAvailable) { //插入 [[MPMusicPlayerController applicationMusicPlayer] setVolume:1.0]; } else if (routeChangeReason == kAudioSessionRouteChangeReason_NoSuitableRouteForCategory) { } }