音频会话的中断处理

音频会话中断

  • 当有人打来电话时, 音频会话会中断播放音频
  • 当电话挂断后, 音频是不会重新开始播放的
  • 为了处理这种情况, 可以使用下面的代码

音频会话通知

// 会话中断通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  • 我们使用AVAudioSessionInterruptionType来判断会话的状态
    • AVAudioSessionInterruptionTypeBegan: 中断开始
    • AVAudioSessionInterruptionTypeEnded: 中断结束
/**
 会话中断通知
 */
- (void)handleInterruption:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        // 音频会话中断开始, 处理音频中断
    }else if (type == AVAudioSessionInterruptionTypeEnded) {
        // 音频会话中断结束
    }
}
/**
 会话中断通知
 */
- (void)handleInterruption:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        // 音频会话中断开始, 处理音频中断
    }else if (type == AVAudioSessionInterruptionTypeEnded) {
        // 音频会话中断结束, 处理重新播放音频
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            // 可以重新播放音频
        }
    }
}
  • 注意: 当音频会话中断并结束中断后, 之前播放的音频是不会自动播放的, 我们需要再次启动播放

你可能感兴趣的:(音频会话的中断处理)