In my app I want to check for the AVAudio portTypes already connected to the phone. The code below works for BluetoothA2DP and Headphones, but not BluetoothHFP when I connect the phone to my car handsfree. Can anyone help me?! I think have been through all the SO posts on Handsfree/AV/Bluetooth, and many others, but can't work out why it is not recognising the BluetoothHFP output portType.
import AVFoundation
func startCheckAVConnection() {
// set the AVAudioSession to allow bluetooth. This do/try/catch doesn't seem to make a difference if it is here or not.
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: AVAudioSessionCategoryOptions.allowBluetooth)
} catch{
print(error)
}
// Check possible outputs for handsfree
let outputs = AVAudioSession.sharedInstance().currentRoute.outputs
if outputs.count != 0 {
for output in outputs {
if output.portType == AVAudioSessionPortBluetoothA2DP {
peripheralLabel.text = "connected to BluetoothA2DP"
} else if output.portType == AVAudioSessionPortBluetoothHFP { // NOT RECOGNISED
peripheralLabel.text = "connected to BluetoothHFP"
} else if output.portType == AVAudioSessionPortHeadphones {
peripheralLabel.text = "connected to Headphones"
}
}
} else {
peripheralLabel.text = "Please connect handsfree"
}
// Add observer for audioRouteChangeListener
NotificationCenter.default.addObserver(
self,
selector: #selector(TopVC.audioRouteChangeListener(_:)),
name: NSNotification.Name.AVAudioSessionRouteChange,
object: nil)
}
I needed to add setActive after setCategory.
do { try AVAudioSession.sharedInstance().setActive(true)
print("setActive")
} catch {
print(error)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With