How do you get/set media volume (not ringtone volume) in Android?

Buda Gavril picture Buda Gavril · Jan 4, 2011 · Viewed 107.8k times · Source

Is there a way to get/set media volume? I have tried the following:

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);

but it returns the ringtone volume.

Answer

trgraglia picture trgraglia · Mar 27, 2011
private AudioManager audio;

Inside onCreate:

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

Override onKeyDown:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        return false;
    }
}