处理音频中断


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

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

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

            

           //停止播放

        }

    }

    

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值