當(dāng)你的應(yīng)用程序運(yùn)行時(shí),用戶可以插入或拔出耳機(jī),在寫(xiě)音頻類APP的時(shí)候,常常會(huì)有對(duì)耳機(jī)狀態(tài)監(jiān)控的需求,在iOS6之后蘋(píng)果公司為開(kāi)發(fā)者們帶了比較友好的方法:
1.首先導(dǎo)入頭文件:
#import <AVFoundation/AVFoundation.h>
2.在該文件下存在監(jiān)聽(tīng)事件名稱,我們可以對(duì)該事件進(jìn)行監(jiān)聽(tīng):
NSString *const AVAudioSessionRouteChangeNotification
3.使用通知中心設(shè)置監(jiān)聽(tīng):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outputRouteChanged:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
4.實(shí)現(xiàn)監(jiān)聽(tīng)觸發(fā)事件:
- (void)outputRouteChanged:(NSNotification *)notification {
NSLog(@"---%@", notification.userInfo);
}
5.控制臺(tái)打印結(jié)果為:
{
AVAudioSessionRouteChangePreviousRouteKey = "<AVAudioSessionRouteDescription: 0x17420ded0, \ninputs = (null); \noutputs = (\n \"<AVAudioSessionPortDescription: 0x17420dbc0, type = Headphones; name = \\U8033\\U673a; UID = Wired Headphones; selectedDataSource = (null)>\"\n)>";
AVAudioSessionRouteChangeReasonKey = 8;
}
6:該AVAudioSessionRouteChangeNotification提供了兩個(gè)重要的對(duì)象:
// AVAudioSessionRouteDescription:前一線路的描述。
// AVAudioSessionRouteChangeReasonKey:線路改變的原因。
7:如果你只是想知道,當(dāng)耳機(jī)被拔掉,你應(yīng)該使用下面的代碼:
NSInteger routeChangeReason = [notification.userInfo [AVAudioSessionRouteChangeReasonKey] integerValue];
if (routeChangeReason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
// 舊設(shè)備失效(耳機(jī)已經(jīng)拔掉)
}
友情提示:在這里我們通常不需要檢測(cè)前一線路是否是耳機(jī),因?yàn)樵趇OS的設(shè)計(jì)邏輯中,輸出設(shè)備失效,你就應(yīng)該選擇暫停當(dāng)前的播放,而當(dāng)前正處在播放狀態(tài)你插入了耳機(jī)將會(huì)獲得的線路改變?cè)驗(yàn)椋篈VAudioSessionRouteChangeReasonNewDeviceAvailable,此時(shí)你無(wú)需暫停操作而應(yīng)該繼續(xù)播放,因?yàn)樾碌妮敵鲈O(shè)備有效,有效的話就應(yīng)該繼續(xù)播放。
詳情請(qǐng)參考蘋(píng)果官方文檔:Audio Session Programming Guide: Responding to Route Changes