蓝牙耳机(Airpods)和AVAudioSession覆盖

时间:2017-12-18 14:59:30

标签: swift avaudiosession ios-bluetooth

我希望能够在我的应用程序中使用Airpods,并且我有一些解决方案(几乎)。

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")
        }
    }
}

问题是它只在我(或之后)切换到其他有声音的应用程序(即YouTube应用程序)并返回时才有效。之后它就像一个魅力,但我相信它应该从一开始就有用。

0 个答案:

没有答案