匯入蘋果的兩個架構是必不可少的環節。。。
代碼部分+小解:
- (void)viewDidLoad{ [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib. AudioSessionInitialize (NULL, NULL, NULL, NULL); /* OSStatus AudioSessionInitialize ( CFRunLoopRef inRunLoop, CFStringRef inRunLoopMode, AudioSessionInterruptionListener inInterruptionListener, void *inClientData ); 這個函數,必須在調用其他AudioSession functions之前調用 inRunLoop The run loop that the interruption listener callback should be run on. Pass NULL to use the main run loop. 置 NULL ,是使用預設的the main run loop;(當在監聽器回調的時候停止迴圈) inRunLoopMode The mode for the run loop that the interruption listener function will run on. Passing NULL is equivalent to passing kCFRunLoopDefaultMode(kCFRunLoopDefaultMode來持有對象,在應用或線程閑置的時候這些對象被監控). (當監聽器將要回調的時候運行迴圈中斷) NULL == kCFRunLoopDefaultMode, inInterruptionListener The interruption listener callback function. The application’s audio session object invokes the callback when the session is interrupted and (if the application is still running) when the interruption ends. Can be NULL. See AudioSessionInterruptionListener. 用 NULL 來代替 AudioSessionInterruptionListener(音頻會話被打斷),當我們拔下耳機的時候,音頻會話被打斷,從而使得應用程式的音頻對象引起了回調。 inClientData Data that you would like to be passed to your interruption listener callback. */ [self addHeadPhoneListener];}
添加監聽事件和回呼函數:
//監聽耳機插入和拔出- (BOOL)addHeadPhoneListener{ OSStatus status = AudioSessionAddPropertyListener( kAudioSessionProperty_AudioRouteChange, audioRouteChangeListenerCallback,self); /* AudioSessionAddPropertyListener( AudioSessionPropertyID inID, AudioSessionPropertyListener inProc, void *inClientData ) 註冊一個監聽:audioRouteChangeListenerCallback,當音頻會話傳遞的方式(耳機/喇叭)發生改變的時候,會觸發這個監聽 kAudioSessionProperty_AudioRouteChange :就是檢測音頻路線是否改變 */}void audioRouteChangeListenerCallback ( void *inUserData, AudioSessionPropertyID inPropertyID, UInt32 inPropertyValueS, const void *inPropertyValue ) { UInt32 propertySize = sizeof(CFStringRef); AudioSessionInitialize(NULL, NULL, NULL, NULL); CFStringRef state = nil; //擷取音頻路線 AudioSessionGetProperty(kAudioSessionProperty_AudioRoute ,&propertySize,&state);//kAudioSessionProperty_AudioRoute:音頻路線 NSLog(@"%@",(NSString *)state);//Headphone 耳機 Speaker 喇叭.}
理解的不透徹,望各位大神指教。