I want to be able to use Airpods in my app, and I have some solution that works (almost).
func playSound(soundSpeech: String) {
let audioSession = AVAudioSession.sharedInstance()
selectDevice(audioSession: audioSession)
...
}
func selectDevice(audioSession: AVAudioSession) {
print("select device")
var headphonesExist = false
var bluetoothExist = false
var speakerExist = false
let currentRoute = AVAudioSession.sharedInstance().currentRoute
for output in audioSession.currentRoute.outputs {
print(output)
if output.portType == AVAudioSessionPortHeadphones || output.portType == AVAudioSessionPortHeadsetMic {
headphonesExist = true
}
if output.portType == AVAudioSessionPortBluetoothA2DP || output.portType == AVAudioSessionPortBluetoothHFP {
bluetoothExist = true
print("bluetooth is enabled")
}
if output.portType == AVAudioSessionPortBuiltInSpeaker {
speakerExist = true
}
}
print("headphones: \(headphonesExist) bluetooth: \(bluetoothExist) speakerExist: \(speakerExist)")
if bluetoothExist == true {
do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.allowBluetoothA2DP) } catch {
print("error with audiosession: bluetooth")
}
} else {
do { try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.defaultToSpeaker) } catch {
print("error with audiosession: default speaker")
}
}
}
The problem is it does work only if (or after) I switch to other app with sound (i.e. YouTube app) and back. After that it works like a charm, but I believe it should work from the start.