iOS 使用AVAudio播放音乐中断处理

在使用AVFoundation框架中的AVAudioPlayer播放音乐时,会出现中断的情况,比如接听电话,或者接听FaceTime,这就要通过注册通知来处理,

[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(handleInterruption:) name :AVAudioSessionInterruptionNotifacation object:[AVAudioSession shareInstance]];

- (void)dealloc{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)handleInterruption:(NSNotification *)notification{
  NSDictionary *info = notification.userInfo;
  AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
  if(type == AVAudioSessionInterruptionTypeBegan)  //中断开始(比如有电话打入时,播放音乐就这这个时间停止了)
  {
  
    //停止播放
     [self.player stop];

      if(self.delegate)
      {
        [self.delegate playbackStopped];//通过代理更改音乐暂停时的样式
      }
  }else{
    // 当中断音乐结束时,会有一个 AVAudioSessionInterruptionOptions 这样的值来表明音频会话是否已经重新激活,是否可以再次播放
    AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionKey] unsignedIntergerValue];
    
    if(options == AVAudioSessionInterruptionOptionShouldResume)
    {
      //音乐恢复播放
      [self.player play];
  
      if(self.delegate)
      {
        [self.delegate playbackBegan]; //通过代理更改音乐播放时的样式
      }
    }
  }
}
当接收到中断通知时,音频会话就已经被终止,且 AVAudioPlayer已经处于暂停的状态,调用[self.player stop]方法,也只能更新内部状态,并不能停止音乐。


 

  

原文地址:https://www.cnblogs.com/poky/p/5842175.html