Steve Steve - 15 days ago 8
Android Question

Change volume of an alarm

I want to set volume for an alarm. I use this code but nothing seems to happen with the volume, only logs show value of volume that I'd set. What should I do to actually change volume?

My code:

final MediaPlayer mediaPlayer = MediaPlayer.create(this, RingtoneManager.getActualDefaultRingtoneUri(this,RingtoneManager.TYPE_ALARM));

final AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
final int currentVolume = audio.getStreamVolume(AudioManager.STREAM_ALARM);
Log.e("Point_1", "Volume " + currentVolume);
audio.setStreamVolume(AudioManager.STREAM_ALARM,0,0);
mediaPlayer.start();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
mediaPlayer.stop();
Log.e("Point_1", "Volume_after " + audio.getStreamVolume(AudioManager.STREAM_ALARM));
}

}, 5000);


Thanks.

Answer

use this code

AudioManager audioManager = 
    (AudioManager)getSystemService(Context.AUDIO_SERVICE);

audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                             [int value],
                             [if desired a flag]);

you should use AudioManager.STREAM_MUSIC instead of AudioManager.STREAM_ALARM

and see How to correctly set MediaPlayer audio stream type too

Comments