Question

I would like my users to be able to choose that an alarm-sound plays at the highest possible volume.

For this I need to set media volume to max, play the alarm and set the volume back to the original state.

For testing I have a button with this onClick-event:

public void playAlarm(View view) {
  AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
  audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

  MediaPlayer mediaPlayer = MediaPlayer.create(view.getContext(), R.raw.alarm);
  mediaPlayer.start();

  audio.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND);
}

The alarm-sound is playing at the original volume, and not at max volume.

What am I doing wrong?

Was it helpful?

Solution

mediaPlayer.start()

does not actually play the sound. It schedules it for playing asap and returns immediately. Therefore, by the time the sound is played, the volume is back to normal. You need to set the volume back once the sound is done playing, using an http://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top