2

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.

Steve
  • 81
  • 2
  • 10

1 Answers1

5

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

Community
  • 1
  • 1
zohreh
  • 1,055
  • 1
  • 9
  • 26
  • Hey,Thanks! Also, can you please tell me is there any way to get the max volume divide it by into 100 and then use it as a value for setStreamVolume? – Steve Nov 17 '16 at 15:44
  • see this http://stackoverflow.com/questions/15670524/how-to-turn-the-volume-to-max-programmatically-on-android – zohreh Nov 18 '16 at 06:47
  • Is there a way I can play stream even while in call and on loud speaker at max ? – Mohsin Falak Sep 14 '22 at 00:30