I'm trying to play an alarm sound through the speakers via the alarm channel at max volume. For that I'm using the AudioManager and a MediaPlayer. If I plug in headphones, the alarm is still played through the speakers, however the volume of the alarm played through the speakers decreases drastically making it useless for my purpose.
Is there a way to prevent this decrease in volume?
The code I'm using is this:
public void startAlarmSound() {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(false);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
if (!alreadyPlaying)
playAlarmSound();
alreadyPlaying = true;
}
private void playAlarmSound() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
try {
mediaPlayer.setDataSource(this, Uri.parse("android.resource://com.mystuff.mine/" + R.raw.alarm_sound));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
To ensure that the volume has not been lowered, I'm calling the following every 5 seconds.
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
I'm located within the EU, so it could be caused by that regulation that deals with max volume when plugging in headphones. Since I only care about speaker output I need a workaround even if that is the case.
Edit:
This problem occurs both with my app as well as with system apps (like the alarm clock), and with both Nexus 5 and 6. As I've also read reports of that issue from other phone manufacturers, so I don't think the problem is exclusive to the nexus line of phones. I need a workaround.
I just checked the result of both getStreamMaxVolume(AudioManager.STREAM_ALARM) and getStreamVolume(AudioManager.STREAM_ALARM). Both display 7, regardless of if the headphones are plugged in or not.
I did notice that with headphones plugged in, while the volume indicator is set to max, if I reduce it and quickly increase it again, it will increase to the volume that it has without headphones. However as this requires user interaction, it's not the solution I'm looking for.