美文网首页AVFoundation 拍片专用视频音频处理音视频
关于AVAudioSession通知的处理,拔出耳机暂停播放,系

关于AVAudioSession通知的处理,拔出耳机暂停播放,系

作者: 骆小喵 | 来源:发表于2016-08-10 18:42 被阅读771次

    1.拔出耳机暂停播放

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

    拔出耳机暂停播放通知回调处理

    AVAudioSessionRouteChangeNotification通知的userinfo中会带有通知发送的原因信息及前一个线路的描述. 线路变更的原因保存在userinfo的AVAudioSessionRouteChangeReasonKey值中,通过返回值可以推断出不同的事件,对于旧音频设备中断对应的reason为AVAudioSessionRouteChangeReasonOldDeviceUnavailable.但光凭这个reason并不能断定是耳机断开,所以还需要使用通过AVAudioSessionRouteChangePreviousRouteKey获得上一线路的描述信息,注意线路的描述信息整合在一个输入NSArray和一个输出NSArray中,数组中的元素都是AVAudioSessionPortDescription对象.我们需要从线路描述中找到第一个输出接口并判断其是否为耳机接口,如果为耳机,则停止播放.

    - (void)handleRouteChange:(NSNotification *)noti {
      
        NSDictionary *info = noti.userInfo;
        AVAudioSessionRouteChangeReason reason = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
        
        //旧音频设备断开
        if (reason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
            
            //获取上一线路描述信息并获取上一线路的输出设备类型
            AVAudioSessionRouteDescription *previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey];
            AVAudioSessionPortDescription *previousOutput = previousRoute.outputs[0];
            NSString *portType = previousOutput.portType;
            
            if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {
            
               //在这里暂停播放
            }
        }
    }
    

    2.监听系统中断音频播放
    来电暂停
    QQ 微信语音暂停
    其他音乐软件占用

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

    接收音频中断操作回调通知

    在接收到通知的userInfo中,会包含一个AVAudioSessionInterruptionTypeKey,用来标识中断开始和中断结束.
    当中断类型为AVAudioSessionInterruptionTypeKeyEnded时,userInfo中还会包含一个AVAudioSessionInterruptionOptions来表明音频会话是否已经重新激活以及是否可以再次播放

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

    相关文章

      网友评论

        本文标题:关于AVAudioSession通知的处理,拔出耳机暂停播放,系

        本文链接:https://www.haomeiwen.com/subject/cpejsttx.html