title: Play Audio Through Speakers with Headphones Plugged In
body: <p>I want to play an audio file through speakers with plugged-in headset.</p>
  
  <p>I tried the following:
  MainActivity.java:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>Manifest:</p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /&gt;
  </code></pre>
  
  <p>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?</p>
  
  <p><strong>EDIT 1:</strong></p>
  
  <p>I tried the following code from the post <a href="https://stackoverflow.com/questions/33429701/android-how-to-route-the-audio-to-speakers-when-headphones-inserted">Android, how to route the audio to speakers when headphones inserted?</a>:</p>
  
  <pre><code>   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();
  </code></pre>
  
  <p>But I am getting </p>
  
  <blockquote>
    <p>java.lang.IllegalStateException</p>
  </blockquote>
  
  <p>Any ideas how to solve this?</p>