AVAudioSession音频会话中断监听配置

工作之余打个笔记。音频后台播放时需要做响应监听配置,比如电话,微信语音等  原理是,在音乐播放被中断时,暂停播放,在中断结束后,开始播放。具体做法是:

首先在AppDelegate内注册音频中断状态监听的通知以及定义一个BOOL类型值记录播放状态

@property (nonatomic, assign) BOOL isPlaying; // 是否是播放状态

//注册音频中断时的通知
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleInterruption:)
                                                 name:AVAudioSessionInterruptionNotification
                                               object:[AVAudioSession sharedInstance]];

下面所述的[KPAudioPlayerTool sharePlayerTool]代表的是我项目内自己写的音频管理类。
然后通知监听内的处理:

#pragma mark - 实现接收到中断通知时的方法
- (void)handleInterruption:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    //一个中断状态类型
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] integerValue];
    NSLog(@"中断时的通知 ---->>> %@",type == 0? @"结束中断":@"开始中断");
    //判断开始中断还是中断已经结束
    BOOL isSuspended = NO;
    if (@available(iOS 10.3, *)) {
        isSuspended = [info[AVAudioSessionInterruptionWasSuspendedKey] boolValue];
    }
    NSLog(@"isSuspended = %d",isSuspended)
    if (isSuspended) {
        [self resumePlayWithInfo:info];
    }else{
        if (type == AVAudioSessionInterruptionTypeBegan) {
            //停止音频播放
            //处理业务逻辑
            if([[KPAudioPlayerTool sharePlayerTool] isPlaying]) { // 正在播放
                self.isPlaying = YES;
                [[KPAudioPlayerTool sharePlayerTool] pause];
            } else {
                self.isPlaying = NO;
            }
            NSLog(@"isPlaying = %d",self.isPlaying)
            NSLog(@"--------------------:%@", [AVAudioSession sharedInstance].category);
        }else {
            [self resumePlayWithInfo:info];
        }
    }
}
- (void)resumePlayWithInfo:(NSDictionary *)info{
    //如果中断结束会附带一个KEY值,表明是否应该恢复音频
    AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] integerValue];
    if (options == AVAudioSessionInterruptionOptionShouldResume) { // 表明音频会话是否已经重新激活,以及是否可以再次播放。
        //恢复播放
        //处理业务逻辑
        NSLog(@"<<<<<<<<<<<<<<<<恢复播放");
        if ([KPAudioPlayerTool sharePlayerTool] && ![[KPAudioPlayerTool sharePlayerTool] isPlaying] && self.isPlaying) {
            // 如果再次恢复Session播放失败就不进行播放
            BOOL isError = NO;
            NSError * error;
            //开启后台处理多媒体事件
            [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
            AVAudioSession *session = [AVAudioSession sharedInstance];
            //设置会话的场景、选项、模式
            if(![session setCategory:AVAudioSessionCategoryPlayback error:&error]) {
                isError = YES;
                NSLog(@"音频会话分类设置出错:%@",[error localizedDescription]);
            }
            //激活会话
            if(![session setActive:YES error:&error]) {
                isError = YES;
                NSLog(@"音频会话分类设置出错:%@",[error localizedDescription]);
            }
            if (!isError) { // 设置不出错则继续播放
                [[KPAudioPlayerTool sharePlayerTool] start];
            }
        }
    }
}

/// APP进入后台,记录当前播放状态
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    if ([[KPAudioPlayerTool sharePlayerTool] isPlaying]) {
        self.isPlaying = YES;
    } else {
        self.isPlaying = NO;
    }
    //开启后台处理多媒体事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

若要采用后台播放音频,最基础配置如下

    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
    [session setActive:YES error:nil];

如果需要在采用控制栏及通知栏控制音频的播放状态,可以在进入后台以及恢复Session的时候开启后台处理多媒体事件: [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

你可能感兴趣的:(AVAudioSession音频会话中断监听配置)