Search code examples
androidaudioandroid-mediaplayermedia-playervolume

How to Change Sound Programmatically on Android


I have a media player which plays song files. However, no matter how I try to initialize its volume, the only way to change it is manually with the volume buttons. I've tried

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
    mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, 0); // Sets volume to max

and even

mMediaPlayer.setVolume(1, 1);

but none work. I've used this code in the past without problem. I've tried my app on both 5.1.1 and 7.1.1 and no luck. It doesn't matter whether the phone's volume starts in a muted state or not. I checked and maxVolume is non-zero (I've tried just hardcoding numbers too). How can I set the initial volume programmatically? The media player starts playing automatically. (I've tried calling this within the media player's onPrepared listener too in case it made a difference. It doesn't.) I also checked whether the phone volume is "fixed". It's not.

How can I get my player to start playing at max volume (no matter what the phone was set for)?


Solution

  • I found the problem. I had the stream wrong. Instead of STREAM_ALARM it should have been STREAM_MUSIC. The list of streams can be found here:

    https://developer.android.com/reference/android/media/AudioManager.html