iosswiftavaudiosession

AVAudioSession setCategory .allowBluetooth causes crash


I'm writing an app that records user audio with AVAudioSession. All works well when I'm not adding bluetooth to the options, but I'd like to be able to record with AirPods as well. When I add the .allowBluetooth option, it produces a crash and no longer works.

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
}

Any suggestions on this? I've looked through numerous SO posts related to the subject and found nothing that seems to solve my issue.


Solution

  • You are getting error code -50, which indicates invalid parameters.

    This is because the .defaultToSpeaker option can only be used with the playAndRecord category:

    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.

    So either remove this option or use a playAndRecord category.