Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App unable to find AVAudio BluetoothHFP Handsfree port Swift

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)
}
like image 334
richc Avatar asked Mar 08 '17 19:03

richc


1 Answers

I needed to add setActive after setCategory.

 do { try AVAudioSession.sharedInstance().setActive(true)
        print("setActive")
    } catch {
        print(error)
    }
like image 197
richc Avatar answered Sep 23 '22 04:09

richc