Search code examples
androidaudioandroid-mediaplayer

Play Audio Through Speakers with Headphones Plugged In


I want to play an audio file through speakers with plugged-in headset.

I tried the following: MainActivity.java:

AudioManager audioManager = (AudioManager)mainActivity
     .getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
MediaPlayer mp = MediaPlayer.create(mainActivity, R.raw.chime);
mp.setAudioStreamType(AudioManager.STREAM_RING);
mp.start();

Manifest:

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

But the audio is still played through the plugged in headphones. How can I direct the audio output to the speakers, with plugged in headphones, correctly?

EDIT 1:

I tried the following code from the post Android, how to route the audio to speakers when headphones inserted?:

   MediaPlayer mp = MediaPlayer.create(mainActivity, R.raw.chime);
   AudioManager am = (AudioManager) mainActivity.getSystemService(mainActivity.AUDIO_SERVICE);
    try {
        mp.setAudioStreamType(AudioManager.STREAM_ALARM);
        mp.setLooping(true);
        mp.prepare();
    } catch (IllegalArgumentException | SecurityException| IllegalStateException | IOException e) {
        Log.i("TAG","Error is " + e.toString());
        e.printStackTrace();
    }
    am.requestAudioFocus(null, AudioManager.STREAM_ALARM,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    mp.start();

But I am getting

java.lang.IllegalStateException

Any ideas how to solve this?


Solution

  • I'll provide a complete code snippet (tested on Android 24), which I had to aggregate from multiple hints to solutions:

    public class AudioClass
    {
        AudioManager audioManager;
        Activity activity;
    
        public AudioClass(Activity activity)
        {
           this.activity = activity;
    
            //NEEDS TO BE DONE BEFORE PLAYING AUDIO!
            audioManager = (AudioManager)
                activity.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            audioManager.setSpeakerphoneOn(true);
        }
    
        public void playAudio() {
            //CAN BE CALLED FROM ANYWHERE AFTER AudioClass IS INSTANTIATED
            MediaPlayer mp = MediaPlayer.create(activity, R.raw.audio_file_name);
            mp.setAudioStreamType(AudioManager.MODE_IN_COMMUNICATION);
            mp.start();
        }
    }
    

    And the permissions for modifying audio settings need to be set in the manifest:

    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />