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

AVAudioSession添加麦克风输入后Haptic Feedback及系统音效丢失问题

问题解决方法

核心原因

失效是因为 AVCaptureSession默认会自动修改AVAudioSession的配置,你之前手动设置的setAllowHapticsAndSystemSoundsDuringRecording参数会被捕获会话的默认配置覆盖,导致触感和系统音效权限被重置。

修复步骤

  • 第一步:禁用AVCaptureSession的自动音频配置
    在初始化AVCaptureSession后立刻添加以下代码,阻止它篡改你自定义的音频会话参数:
session.automaticallyConfiguresApplicationAudioSession = false
  • 第二步:补全AVAudioSession的配置校验
    封装统一的音频会话配置方法,添加系统版本兼容判断:
// 配置音频会话的统一方法
func configureAudioSession() {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(.playAndRecord, options: [.mixWithOthers])
        if #available(iOS 13.0, *) {
            try audioSession.setAllowHapticsAndSystemSoundsDuringRecording(true)
        }
        try audioSession.setActive(true)
    } catch {
        print("音频会话配置失败: \(error.localizedDescription)")
    }
}
  • 第三步:修改捕获会话后重新调用配置
    在你添加/移除麦克风输入的代码执行完成后,主动调用上面的configureAudioSession方法,保证参数不会被重置:
do {
    let microphonePermission = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
    if microphonePermission != .denied && microphonePermission != .restricted {
        let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio)
        let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice!)
        if self.session.canAddInput(audioDeviceInput) {
           self.session.addInput(audioDeviceInput)
           // 添加输入完成后重新配置音频会话
           self.configureAudioSession()
        }
        else { print("Could not add audio device input to the session.") }
    }
}
catch { print("Could not create audio device input: \(error).") }

问题定位方法

如果修改后仍然失效,可以在添加麦克风输入前后分别打印以下参数,确认配置是否被篡改:

print("是否允许触感反馈: \(audioSession.allowHapticsAndSystemSoundsDuringRecording)")
print("当前音频分类: \(audioSession.category.rawValue)")
print("当前分类选项: \(audioSession.categoryOptions.rawValue)")

如果打印结果显示allowHapticsAndSystemSoundsDuringRecording为false,说明配置还存在被覆盖的场景,需要检查所有修改AVCaptureSession的代码位置,确认都加了重新配置的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:24:00