导入苹果的两个框架是必不可少的环节。。。
代码部分+小解:
- (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 喇叭. }
理解的不透彻,望各位大神指教。