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?