处理音频中断


//接受来电和来电结束调用的方法

//当播放器遇到中断的时候(如来电),调用该方法

- (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]) {

            

           //停止播放

        }

    }

    

}



你可能感兴趣的:(ios,AVAudio)