21

I'd like to play audio from a file into the phone's earpiece (or headset of that is connected) using the android MediaPlayer. I tried using the MODE_IN_CALL hack as suggested in this thread - Android - Getting audio to play through earpiece but that did not help. The app also has the android.permission.MODIFY_AUDIO_SETTINGS permission, but any call to m_amAudioManager.setSpeakerphoneOn(false); is ignored.

private AudioManager m_amAudioManager;  
m_amAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);  
m_amAudioManager.setMode(AudioManager.MODE_IN_CALL); 
m_amAudioManager.setSpeakerphoneOn(false); 

A call to setMode(AudioManager.STREAM_VOICE_CALL); on the MediaPlayer did not help either.

mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();

Has something changed since android 2.3 to break this code ? I tried the code on Android ICS without any success. Can someone point me in the right direction ? The audio always plays from the speaker phone so far.

Community
  • 1
  • 1
Deepak Bala
  • 11,095
  • 2
  • 38
  • 49

8 Answers8

40

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.

Community
  • 1
  • 1
Deepak Bala
  • 11,095
  • 2
  • 38
  • 49
  • I'll have to try that out. I've been using the solution from the post you referenced for years without real issue. I have had a few random complaints of weird changes to audio in other apps, but they could never be confirmed. I will check this out, it certainly sounds like a better solution. I never liked how my solution looked, even through it worked. – Piwaf Sep 11 '13 at 18:45
  • Specifically, some versions of firmware running on Samsung Galaxy S2 and Micromax run into trouble with the solution in the other post. If you're still using it, I'd suggest moving to this code fragment. It has not failed me thus far. – Deepak Bala Sep 12 '13 at 11:35
  • It appears with this approach you need to re-"prepare" the MedialPlayer when switching modes. Is that your experience as well? – Piwaf Nov 11 '13 at 21:07
  • Yes I had to reset and re-prepare the media player. Thanks for pointing that out. I will update the answer to reflect this. – Deepak Bala Nov 12 '13 at 12:47
  • Deepak Bala> Please see a related issue: http://stackoverflow.com/questions/33062660/android-what-audio-mode-should-be-set-to-send-receive-voice-between-devices , now i need to play the audio received and record audio from microphone at the same time. If i set MODE_IN_CALL audio is recorded clearly, but speaker goes off. What now (Micromax tablet)? – Jasper Oct 11 '15 at 14:38
  • @DeepakBala Do you know how to adjust the volume through the hardware keys when `AudioManager.STREAM_VOICE_CALL` is used? I can't seem to control the volume when this stream type is set. – Robert Nov 10 '15 at 21:54
5

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();
    }
wutzebaer
  • 14,365
  • 19
  • 99
  • 170
4

The following code works fine for me and I have tested in on multiple devices:

1- creating instances:

MediaPlayer mPlayer = MediaPlayer.create(MainActivity.this, R.raw.skype_call_dialing);
AudioManager mAudioManager = ((AudioManager).getSystemService(Context.AUDIO_SERVICE));

2- if you want to set volume to max (optional)

 int maxVolumeMusic = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
 mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolumeMusic, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
 mAudioManager.setMode(AudioManager.STREAM_MUSIC);

3- set audio to play from earpiece:

mAudioManager.setSpeakerphoneOn(false);

4- play:

mPlayer.setLooping(true);
mPlayer.start();

Done!!!! But there is some tips I am going to share with you:

1- in step 2, if you set Audiomanager.setMode() before AudioManager.setStreamVolume() then the volume would not set to max!

2- if you add mPlayer.prepare() before mPlayer.setLooping(true); it would lead to crash!, you should not use mPlayer.prepare() while mPlayer is initializing like this:

MediaPlayer mPlayer = MediaPlayer.create(MainActivity.this, R.raw.skype_call_dialing);

3- in step 2, mAudioManager.setMode() I used AudioManager.STREAM_MUSIC, when I try other modes, in many cases I was not able to switch on and off speaker!

farhad.kargaran
  • 2,233
  • 1
  • 24
  • 30
  • The line **mAudioManager.setMode()** has a wrong enum as input. It does work though, because the enum-value is the same as the correct enum. As the documentation states: [link](https://developer.android.com/reference/android/media/AudioManager.html?#setMode(int)) The SetMode method has 5 possible enumvalues: MODE_NORMAL, MODE_RINGTONE, MODE_IN_CALL, MODE_IN_COMMUNICATION The correct one here should be MODE_IN_CALL which is the same enumvalue as AudioManager.STREAM_MUSIC ;) – ThijsM Apr 04 '18 at 12:56
  • Can you tell what `R.raw.skype_call_dialing` reffer too in the above example ? I guess it is audio file in raw folder of project. What format should be for the file like mp3, aac? – Vikrant Aug 23 '18 at 08:42
4

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);
Vivek
  • 566
  • 5
  • 6
1

This method is working fine for me.

You need to set audio manager mode too. and then using audiomgr.setSpeakerphoneOn(false) api you can toggle.

AudioManager audiomgr = (AudioManager) 
    context.getSystemService(Context.AUDIO_SERVICE);
audiomgr.setMode(AudioManager.MODE_IN_COMMUNICATION);
audiomgr.setSpeakerphoneOn(false);
Da2da2
  • 57
  • 2
  • 3
  • 13
0

How about this then:

// Make sure that streams following the PHONE routing strategy aren't forced
// to play in the speaker.
Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse",
    int.class,
    int.class);
// First 0 == FOR_COMMUNICATION, second 0 == FORCE_NONE.
setForceUse.invoke(null, 0, 0);

Then use STREAM_VOICE_CALL for your MediaPlayer.

If the setForceUse call succeeds and the audio from your MediaPlayer still plays in the loudspeaker, then I'd say something is messed up in the AudioPolicyManager implementation on the phone/tablet that you're testing this on.

Michael
  • 57,169
  • 9
  • 80
  • 125
  • The phone is able to play from the earpiece on other apps. I'm not able to get it work on my app alone. – Deepak Bala Dec 24 '12 at 08:58
  • @Gaffi: Sounds like you're getting compile time errors rather than runtime errors. Maybe you haven't imported the reflection package? If you use Eclipse it should automatically offer suggestions on how to resolve those issues. – Michael Apr 23 '13 at 13:30
0

I found i needed to set both the mediaplayer and Audiomanager

private MediaPlayer mp = new MediaPlayer();
AudioManager mAudioManager = (AudioManager) v.getContext()
                                .getSystemService(Context.AUDIO_SERVICE);
                        mAudioManager.setSpeakerphoneOn(false);
                        mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
Mark Sheekey
  • 608
  • 7
  • 23
0

Audio Manager speaker phone issue is resolved by this way only :

AudioManager audiomgr = (AudioManager) 
    context.getSystemService(Context.AUDIO_SERVICE);
audiomgr.setMode(AudioManager.MODE_IN_COMMUNICATION);
audiomgr.setSpeakerphoneOn(false);