0

I am facing an issue with the audio output device in swift. In my app, connected to Bluetooth audio device. It has a voice call feature using agora. When a call is completed the output audio device is changed to the phone speaker, but Bluetooth is still connected. I want to set my audio in Bluetooth. How can I solve this issue? ie. now the audioSession output AVAudioSession.Port.builtInReceiver , I want to change it to AVAudioSession.Port.bluetoothHFP

1 Answers1

1

You do this by setting appropriate audio category, mode and options.

The option .allowBluetooth essentially means "prefer Bluetooth HFP". This option allows for simultaneous output & input with a bluetooth device (e.g. headset/headphones). However, the audio output is low quality.

The alternative option .allowBluetoothA2DP enables high quality audio output in the connected bluetooth device. But it doesn't support simultaneous audio input.

// After agora call is completed:

let audioSession = AVAudioSession.sharedInstance()

// The category depends on usage.
// For playback only, use .playback
// For playback and recording, use .playAndRecord
// See official docs for more info.
let category: AVAudioSession.Category = .playback

// Generally the default mode is fine.
let mode: AVAudioSession.Mode = .default

// Options tailor your session, and must be compatible with the category specified.
let options: AVAudioSession.CategoryOptions = [
  .allowBluetooth, // Enable Bluetooth HFP, supporting input & output
  // .mixWithOthers, // Allow background audio (OS/other app) to play
  // .duckOthers, // Allow background audio to play at a quieter ("ducked") volume
]

do {
  try audioSession.setCategory(category, mode: mode, options: options)
  try audioSession.setActive(true) // activate your audio session
} catch {
  print("Something went wrong: \(String(describing: error))")
}

In your case, you may be able to set the session options before a call starts instead, and have them persist satisfactorily after a call ends. It depends on your exact behavioural spec.

kwiknik
  • 570
  • 3
  • 7