處理音頻中斷


//接受來電和來電結束調用的方法

//當播放器遇到中斷的時候(如來電),調用該方法

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player

{

    //中斷播放

}

 //中斷事件結束後調用下面的方法

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)options

{

   //恢復播放

}

 //添加系統通知 當按下鎖屏鍵時將發送通知 接受通知

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

        

- (void)handleInterruption:(NSNotification *)not

{

    NSDictionary *info = not.userInfo;

    

    //拿到系統的通知的key

    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];

    

    //AVAudioSessionInterruptionTypeEnd //系統中斷停止音頻

    if (type == AVAudioSessionInterruptionTypeBegan) {//系統中斷音頻

        

       //中斷播放

        

    }else{

        

        

        AVAudioSessionInterruptionOptions options= [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];

       //中斷被另一個音頻會話已經結束,這個應用程序可以恢復音頻會議。

        if (options == AVAudioSessionInterruptionOptionShouldResume) {//可以恢復播放

            

           //恢復播放

        }

    }

}


        //更換線路播放響應

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


- (void)handleRouteChange:(NSNotification *)not

{

    NSDictionary *info = not.userInfo;

    

    AVAudioSessionRouteChangeReason key = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];

    

    if (key == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) { //前一個的音頻輸出路徑不再可用

       //判斷是否是耳機 如果是拔出斷開時停止播放

        

        /* 

         系統知道設備斷開連接後,需要向userInfo字典提出要求,以獲取其中用於描述前一個線路的AVAudioSessionRouteDescription.線路描述整合在一個輸入數組和輸出數組裏面

         數組中保存的都是AVAudioSessionPortDescription實例用於描述不同的I/O接口屬性 ,

            */

        

        AVAudioSessionRouteDescription *desc = info[AVAudioSessionRouteChangePreviousRouteKey];

        

        AVAudioSessionPortDescription *prodesc = [desc.outputs firstObject];

        

        //prodesc是拿出的I/O接口屬性描述

        

        NSString *porType = prodesc.portType;

       

        //判斷是否爲耳機接口

        if ([porType isEqualToString:AVAudioSessionPortHeadphones]) {

            

           //停止播放

        }

    }

    

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章