Android - Play audio from earpiece

It turns out the right way to do this is through the following code.

Play through the ear piece

mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

Play through the speaker phone

mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

That is it. Any other solution (Including the one posted here -> Android - Getting audio to play through earpiece) does not work consistently across devices. In fact using MODE_IN_CALL ensures that your audio will never play on certain devices.

Note: You will need to re-prepare the media player to change streams.


Ok in my case the issue was solved by using the below code

    mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

    mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    mAudioManager.setSpeakerphoneOn(false);

i just wanted to add a complete example for Deepak Bala's Answer. It works when not using the MediaPlayer.create() method:

    this.player = new MediaPlayer(); 
    this.player.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

    try {
        this.player.setDataSource(getContext(), Uri.fromFile(new File(m.localFileUrl)));
        this.player.prepare();
    } catch (IllegalStateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

Tags:

Audio

Android