audiobluetoothphone-callandroid-audiomanagerspeaker

AudiManager changing from Bluetooth to EAR_PIECE does not work


I have a button that should go from EARPIECE to SPEAKER to BLUETOOTH and so on.

This is my code:

 fun setSpeakerValue(value: SIPManager.AUDIO) {
        speaker = value
        when (value) {
            SIPManager.AUDIO.EAR_PIECE -> {
                Log.i("Speaker", "Speaker1 EARPIECE")
                binding.callItemIconSpeaker.setImageResource(R.drawable.speaker_off)
                if (SIPManager.isBluetoothConnected()) {
                    audioManager?.isBluetoothScoOn = false
                    audioManager?.stopBluetoothSco()
                }
                audioManager?.mode = AudioManager.MODE_NORMAL
                audioManager?.isSpeakerphoneOn = false
            }
            SIPManager.AUDIO.SPEAKER -> {
                Log.i("Speaker", "Speaker1 SPEAKER")
                binding.callItemIconSpeaker.setImageResource(R.drawable.speaker_on)
                if (SIPManager.isBluetoothConnected()) {
                    audioManager?.isBluetoothScoOn = false
                    audioManager?.stopBluetoothSco()
                }
                audioManager?.mode = AudioManager.MODE_IN_COMMUNICATION
                audioManager?.isSpeakerphoneOn = true
            }
            SIPManager.AUDIO.BLUETOOTH -> {
                Log.i("Speaker", "Speaker1 BLUETOOTH")
                binding.callItemIconSpeaker.setImageResource(android.R.drawable.stat_sys_data_bluetooth)
                audioManager?.mode = AudioManager.MODE_NORMAL
                audioManager?.isSpeakerphoneOn = false
                audioManager?.startBluetoothSco()
                audioManager?.isBluetoothScoOn = true
            }
        }
    }

But wheneven I ste to earpiece, I stopBluetoothSCO, I set isSpeakerOn to false, but after that, I start hearing in the blueooth instead of the earpiece of the phone. What am I doing wrong?


Solution

  • Got it to work using the answer from here: How to switch audio output from Phone, Phone Speaker, earphones or Bluetooth device

     //For BT
            mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            mAudioManager.startBluetoothSco();
            mAudioManager.setBluetoothScoOn(true);
        } else if(true) {
            //For phone ear piece
            mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            mAudioManager.stopBluetoothSco();
            mAudioManager.setBluetoothScoOn(false);
            mAudioManager.setSpeakerphoneOn(false);
        } else {
            //For phone speaker(loudspeaker)
            mAudioManager.setMode(AudioManager.MODE_NORMAL);
            mAudioManager.stopBluetoothSco();
            mAudioManager.setBluetoothScoOn(false);
            mAudioManager.setSpeakerphoneOn(true);
        }