關(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值中,通過(guò)返回值可以推斷出不同的事件,對(duì)于舊音頻設(shè)備中斷對(duì)應(yīng)的reason為AVAudioSessionRouteChangeReasonOldDeviceUnavailable.但光憑這個(gè)reason并不能斷定是耳機(jī)斷開(kāi),所以還需要使用通過(guò)AVAudioSessionRouteChangePreviousRouteKey獲得上一線路的描述信息,注意線路的描述信息整合在一個(gè)輸入NSArray和一個(gè)輸出NSArray中,數(shù)組中的元素都是AVAudioSessionPortDescription對(duì)象.我們需要從線路描述中找到第一個(gè)輸出接口并判斷其是否為耳機(jī)接口,如果為耳機(jī),則停止播放.

- (void)handleRouteChange:(NSNotification *)noti {
  
    NSDictionary *info = noti.userInfo;
    AVAudioSessionRouteChangeReason reason = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
    
    //舊音頻設(shè)備斷開(kāi)
    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)系統(tǒng)中斷音頻播放
來(lái)電暫停
QQ 微信語(yǔ)音暫停
其他音樂(lè)軟件占用

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

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

在接收到通知的userInfo中,會(huì)包含一個(gè)AVAudioSessionInterruptionTypeKey,用來(lái)標(biāo)識(shí)中斷開(kāi)始和中斷結(jié)束.
當(dāng)中斷類型為AVAudioSessionInterruptionTypeKeyEnded時(shí),userInfo中還會(huì)包含一個(gè)AVAudioSessionInterruptionOptions來(lái)表明音頻會(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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容