關(guān)于AVAudioSession通知的處理,拔出耳機(jī)暫停播放,系統(tǒng)中斷音頻播放

1.拔出耳機(jī)暫停播放

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];

拔出耳機(jī)暫停播放通知回調(diào)處理

AVAudioSessionRouteChangeNotification通知的userinfo中會(huì)帶有通知發(fā)送的原因信息及前一個(gè)線路的描述. 線路變更的原因保存在userinfo的AVAudioSessionRouteChangeReasonKey值中,通過返回值可以推斷出不同的事件,對于舊音頻設(shè)備中斷對應(yīng)的reason為AVAudioSessionRouteChangeReasonOldDeviceUnavailable.但光憑這個(gè)reason并不能斷定是耳機(jī)斷開,所以還需要使用通過AVAudioSessionRouteChangePreviousRouteKey獲得上一線路的描述信息,注意線路的描述信息整合在一個(gè)輸入NSArray和一個(gè)輸出NSArray中,數(shù)組中的元素都是AVAudioSessionPortDescription對象.我們需要從線路描述中找到第一個(gè)輸出接口并判斷其是否為耳機(jī)接口,如果為耳機(jī),則停止播放.

- (void)handleRouteChange:(NSNotification *)noti {
  
    NSDictionary *info = noti.userInfo;
    AVAudioSessionRouteChangeReason reason = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
    
    //舊音頻設(shè)備斷開
    if (reason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        
        //獲取上一線路描述信息并獲取上一線路的輸出設(shè)備類型
        AVAudioSessionRouteDescription *previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey];
        AVAudioSessionPortDescription *previousOutput = previousRoute.outputs[0];
        NSString *portType = previousOutput.portType;
        
        if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {
        
           //在這里暫停播放
        }
    }
}

2.監(jiān)聽系統(tǒng)中斷音頻播放
來電暫停
QQ 微信語音暫停
其他音樂軟件占用

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

接收音頻中斷操作回調(diào)通知

在接收到通知的userInfo中,會(huì)包含一個(gè)AVAudioSessionInterruptionTypeKey,用來標(biāo)識中斷開始和中斷結(jié)束.
當(dāng)中斷類型為AVAudioSessionInterruptionTypeKeyEnded時(shí),userInfo中還會(huì)包含一個(gè)AVAudioSessionInterruptionOptions來表明音頻會(huì)話是否已經(jīng)重新激活以及是否可以再次播放

- (void)audioInterruption:(NSNotification *)noti {

    NSDictionary *info = noti.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    
    if (type == AVAudioSessionInterruptionTypeBegan) {
        
    } else {
        
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            
        }
    }
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容