VoIP 场景下,如何切换蓝牙耳机的输入/输出通道而不重建设备?

解读

国内 iOS 音视频面试常把“蓝牙耳机切换”作为“音频路由”问题的典型场景。
面试官真正想确认的是:

  1. 你是否知道 iOS 音频路由由系统 Audio Session 统一管理,而不是由 App 直接操作硬件;
  2. 你是否能在不破坏现有 AVAudioSession 实例、不重新实例化任何 AUGraph/IOUnit 的前提下,用官方 API 完成输入/输出方向的切换;
  3. 你是否了解 VoIP 对通话质量、回声抑制、采样率对齐的附加要求;
  4. 你是否能在用户点击“切换到耳机麦克风”或“仅听不响”时,给出 200 ms 内完成的稳定方案,而不是 teardown 重建。

知识点

  1. AVAudioSession:唯一入口,单例生命周期随进程,不需要也不允许重建。
  2. Category:VoIP 必须设为 AVAudioSessionCategoryPlayAndRecord,Mode 设为 VoiceChat,才能激活系统回声消除(AEC)与自动增益(AGC)。
  3. 路由选项:
    • AVAudioSessionPortBluetoothHFP 含双向声道;
    • AVAudioSessionPortBluetoothA2DP 仅输出,高音质但无麦克风;
    • 耳机插孔、听筒、扬声器属于其他 port。
  4. 切换策略:
    • 只改 setPreferredInput 可切换麦克风,不改输出;
    • 改 overrideOutputAudioPort 只能扬声器/听筒之间切,无法指定蓝牙;
    • 真正“同时指定输入+输出”靠 setPreferredInput:error: 结合 categoryOptions 为 0(默认)即可,系统会把输出自动同步到同一蓝牙设备。
  5. 通知:
    • AVAudioSessionRouteChangeNotification 告知路由已变,但不要在回调里再设一次,避免循环。
  6. 线程与错误:
    • 所有 session 调用必须在活跃 session 上、主线程或专用串行队列,错误码要转成中文提示(国内产品规范)。
  7. 权限:
    • iOS 14+ 需在 Info.plist 声明 NSBluetoothAlwaysUsageDescription,否则系统拒绝切换。
  8. 性能:
    • 切换过程约 80~150 ms,若此时正在使用 VoiceProcessingIO 应保持 kAudioUnitProperty_EnableIO 不变,仅监听采样率变化并重新配置 AUBuffer。

答案

步骤代码(Objective-C,ARC,兼容 iOS 12-17):

// 1. 配置一次即可,通常在 didFinishLaunching 或房间创建时
- (void)setupAudioSession {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord
                    mode:AVAudioSessionModeVoiceChat
                 options:AVAudioSessionCategoryOptionAllowBluetooth
                   error:&err];
    if (err) { NSLog(@"设置 category 失败: %@", err.localizedDescription); }
}

// 2. 用户点击“切换到蓝牙耳机”时调用
- (BOOL)routeToBluetoothHeadset {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    // 2.1 找到蓝牙 HFP 端口
    AVAudioSessionPortDescription *bluetoothInput = nil;
    for (AVAudioSessionPortDescription *port in session.availableInputs) {
        if ([port.portType isEqualToString:AVAudioSessionPortBluetoothHFP]) {
            bluetoothInput = port;
            break;
        }
    }
    if (!bluetoothInput) {
        NSLog(@"未检测到蓝牙 HFP 设备");
        return NO;
    }
    
    // 2.2 激活 session(若未激活)
    NSError *actErr = nil;
    if (!session.isOtherAudioPlaying) {
        [session setActive:YES error:&actErr];
        if (actErr) { NSLog(@"激活 session 失败: %@", actErr.localizedDescription); }
    }
    
    // 2.3 只改输入,输出由系统自动跟随同一设备
    NSError *setErr = nil;
    BOOL success = [session setPreferredInput:bluetoothInput error:&setErr];
    if (!success) {
        NSLog(@"切换蓝牙失败: %@", setErr.localizedDescription);
    }
    return success;
}

// 3. 如需“只监听、不用蓝牙耳机麦克风”,则把输入切回手机麦克风
- (BOOL)useBuiltInMicAndBluetoothEarphone {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    AVAudioSessionPortDescription *builtInMic = nil;
    for (AVAudioSessionPortDescription *port in session.availableInputs) {
        if ([port.portType isEqualToString:AVAudioSessionPortBuiltInMic]) {
            builtInMic = port;
            break;
        }
    }
    if (!builtInMic) return NO;
    
    NSError *err = nil;
    return [session setPreferredInput:builtInMic error:&err];
}

// 4. 监听路由变化,仅做 UI 刷新,不再调用 setPreferredInput
- (void)routeChanged:(NSNotification *)note {
    AVAudioSessionRouteChangeReason reason = [note.userInfo[AVAudioSessionRouteChangeReasonKey] intValue];
    if (reason == AVAudioSessionRouteChangeReasonOverride || 
        reason == AVAudioSessionRouteChangeReasonCategoryChange) {
        // 更新 UI 即可
    }
}

关键结论:
• 全程只操作 AVAudioSession,不释放任何 AudioUnit、不重建播放器;
• 输入与输出同步由系统保证,App 无需也不允许直接指定输出端口;
• 切换耗时 < 200 ms,VoIP 通话不会中断。

拓展思考

  1. 双蓝牙设备场景:iOS 只允许同时连接 1 个 HFP 与 1 个 A2DP,若用户已连蓝牙音箱(A2DP)再连耳机(HFP),系统会优先把 HFP 作为输入,此时 App 需提示“已自动切换至耳机麦克风”。
  2. 低电量蓝牙手环:部分手环广播 HFP 但无麦克风,调用 setPreferredInput 后录音会失败,需 fallback 到内置麦克风并弹 Toast 提示。
  3. 采样率漂移:蓝牙耳机常 16 kHz,而 VoIP 服务器要求 48 kHz,需在 AUGraph 里加入采样率转换单元,避免重采样导致 CPU 占用飙升。
  4. 后台模式:VoIP 需打开 audio Background Mode,否则锁屏 30 s 后系统会强制把路由切回听筒,导致用户以为“切换失败”。
  5. 合规:国内应用市场审核要求“用户主动触发才允许切换麦克风”,不可在后台静默调用 setPreferredInput,否则可能被拒。