AVAudioSession setCategory .allowBluetooth 导致崩溃

AVAudioSession setCategory .allowBluetooth causes crash

我正在编写一个使用 AVAudioSession 录制用户音频的应用程序。当我没有在选项中添加蓝牙时一切正常,但我也希望能够使用 AirPods 进行录制。当我添加 .allowBluetooth 选项时,它会产生崩溃并且不再有效。

        do {
            let session = AVAudioSession.sharedInstance()
            try session.setCategory(.record, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
            try session.setActive(true)
        } catch let error as NSError {
            print(error.localizedDescription)
            return
        }

对此有什么建议吗?我浏览了许多与该主题相关的 SO 帖子,但没有发现似乎可以解决我的问题。

您收到错误代码 -50,表示参数无效。

这是因为 .defaultToSpeaker 选项只能与 playAndRecord 类别一起使用:

You can set this option can only when using the playAndRecord category. It’s used to modify the category’s routing behavior so that audio is always routed to the speaker rather than the receiver if no other accessories, such as headphones, are in use.

因此要么删除此选项,要么使用 playAndRecord 类别。