Search code examples
androidaudiowebviewwebrtcpeerjs

android WebView play audio through earpiece or Bluetooth


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)?


Solution

  • 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
    }