twilio / audioswitch

An Android audio management library for real-time communication apps.
Apache License 2.0
160 stars 49 forks source link

Bluetooth is connected, but userSelectedDevice is still the one I set before, so the sound is always playing from the previously selected route. #156

Closed LxzBUG closed 5 months ago

LxzBUG commented 7 months ago

This sentence means that I previously selected the speaker, so userSelectedDevice is the speaker. Then when I connect Bluetooth, selectedDevice keeps returning my previous setting, which prevents me from connecting Bluetooth.

` private fun enumerateDevices(bluetoothHeadsetName: String? = null) { // save off the old state and 'semi'-deep copy the list of audio devices val oldAudioDeviceState = AudioDeviceState(mutableAudioDevices.map { it }, selectedDevice) // update audio device list and selected device addAvailableAudioDevices(bluetoothHeadsetName)

    if (!userSelectedDevicePresent(mutableAudioDevices)) {
        userSelectedDevice = null
    }

    // Select the audio device
    logger.d(TAG, "Current user selected AudioDevice = $userSelectedDevice")
    selectedDevice = if (userSelectedDevice != null) {//always not null。。。。
        userSelectedDevice
    } else if (mutableAudioDevices.size > 0) {
        val firstAudioDevice = mutableAudioDevices[0]
        /*
         * If there was an error starting bluetooth sco, then the selected AudioDevice should
         * be the next valid device in the list.
         */
        if (firstAudioDevice is BluetoothHeadset &&
                bluetoothHeadsetManager?.hasActivationError() == true) {
            mutableAudioDevices[1]
        } else {
            firstAudioDevice
        }
    } else {
        null
    }

    // Activate the device if in the active state
    if (state == ACTIVATED) {
        activate()
    }
    // trigger audio device change listener if there has been a change
    val newAudioDeviceState = AudioDeviceState(mutableAudioDevices, selectedDevice)
    if (newAudioDeviceState != oldAudioDeviceState) {
        audioDeviceChangeListener?.invoke(mutableAudioDevices, selectedDevice)
    }
}

`

ocarevs commented 6 months ago

@LxzBUG This is correct behaviour. If user has selected the device, in your case speakerphone, when bluetooth device is connected it should not automatically change selected device to bluetooth. You should be able to change to bluetooth after receiving a callback in AudioDeviceChangeListener and/or getting AudioSwitch.availableAudioDevices list which should include now newly added bluetooth device and then setting it to route audio through bluetooth device AudioSwitch.selectDevice