You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS 16后台无法设置AVAudioSession类别实现录音的问题求助

解决iOS 16后台录音时AVAudioSession设置失败问题

问题概述

需实现APP前后台均能启动录音功能,前台在所有iOS版本下运行正常,但iOS 16后台模式下设置音频会话失败,错误日志如下:

2022-10-12 18:14:08.848774+0800 Wearfit Pro[12288:2604335] [as_client] AVAudioSession_iOS.mm:2370 Failed to set category, error: '!int'
Error Domain=NSOSStatusErrorDomain Code=560557684 "(null)"

错误码解析

错误码560557684对应音频会话错误kAudioSessionErr_InappropriateCategoryForBackground,说明iOS 16后台模式下当前的音频会话类别或选项配置不符合系统新限制。

解决建议

  • 检查后台模式配置
    确保Xcode项目的Capabilities中已开启Audio, AirPlay, and Picture in Picture后台模式,这是后台录音的基础配置要求。

  • 调整音频会话设置
    iOS 16对后台录音的会话选项有更严格的约束,建议修改会话配置代码:

    NSError *error = nil;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    // 移除可能冲突的选项,保留蓝牙支持
    BOOL categorySuccess = [session setCategory:AVAudioSessionCategoryPlayAndRecord
                                     withOptions:AVAudioSessionCategoryOptionAllowBluetooth
                                           error:&error];
    if (!categorySuccess) {
        NSLog(@"cclog = AVAudioSession SetCategory失败: %@", error.localizedDescription);
        error = [NSError errorWithDomain:@"AVAudioSession SetCategory失败" code:-1 userInfo:nil];
        return;
    }
    
    // 激活会话时添加通知其他应用的选项
    BOOL activeSuccess = [session setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
    if (!activeSuccess) {
        NSLog(@"cclog = setActive失败: %@", error.localizedDescription);
        return;
    }
    

    说明:移除AVAudioSessionCategoryOptionMixWithOthers和AVAudioSessionCategoryOptionDefaultToSpeaker,这两个选项在iOS 16后台环境下会与录音权限冲突,尤其是DefaultToSpeaker在后台无法正常生效,导致会话设置失败。

  • 校验麦克风权限完整性
    在Info.plist中确保已添加NSMicrophoneUsageDescription(麦克风权限描述)和NSBackgroundAudioUsageDescription(后台音频权限描述),并在启动录音前校验权限状态:

    AVAuthorizationStatus micStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (micStatus != AVAuthorizationStatusAuthorized) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
            if (granted) {
                // 权限通过后再初始化音频会话
                [self setupAudioSession];
            } else {
                NSLog(@"用户拒绝麦克风权限,无法启动录音");
            }
        }];
        return;
    }
    
  • 规范后台录音启动时机
    iOS 16限制了后台随意触发录音的行为,建议在APP进入后台前提前激活音频会话,或通过系统允许的后台触发事件(如远程通知、蓝牙外设连接事件等)来启动录音,避免后台冷启动时直接设置音频会话。

内容的提问来源于stack exchange,提问作者Frank8888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:05:32