3

I'm developing a voice call app using peer.js and WebView. My intention is to play the remote stream through the earpiece or Bluetooth headphones(If connected). And there should be an option to switch to the loudspeaker as well. I tried the following code but the audio still comes from the loudspeaker.

   private fun setupAudio() {
        val am = getSystemService(AUDIO_SERVICE) as AudioManager
        am.mode = AudioManager.MODE_IN_CALL
        am.isSpeakerphoneOn = false
    }

Is there any better way to do this? Or can I change the AudioStreamType of WebView(Like as in MediaPlayer)?

Sujith S Manjavana
  • 1,417
  • 6
  • 33
  • 60

2 Answers2

2

make sure to Add <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> in manifest permissions.

if this did not fix the issue, please try

Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
// First 1 == FOR_MEDIA, second 1 == FORCE_SPEAKER. To go back to the default
// behavior, use FORCE_NONE (0).
setForceUse.invoke(null, 1, 1);
user16930239
  • 6,319
  • 2
  • 9
  • 33
2

I got it working, the trick is to call the am.isSpeakerphoneOn = false after receiving the stream. If you are not able to get it working on android 12, try the following,

am.mode = AudioManager.MODE_NORMAL
am.setCommunicationDevice(getAudioDevice(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE));


private fun getAudioDevice(type: Int): AudioDeviceInfo? {
   val audioDevices = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
        for (deviceInfo in audioDevices) {
            if (type == deviceInfo.type) return deviceInfo
        }
    return null
}
Sujith S Manjavana
  • 1,417
  • 6
  • 33
  • 60