Search code examples
androidaudiomedia-player

Issues with volume using MediaPlayer on Android


I'm having problems playing sounds with MediaPlayer. If the sound starts when the volume of the device is 0, then it won't play. I'll explain: if in the moment of start playing a sound, the device has volume = 0, and afterwards I increase the volume, it still doesn't sound. However, if it has volume != 0 when the sound starts, I can lower it to mute, and then increase it again and it's still playing.

Here is the code:

mpMusic = MediaPlayer.create(context, R.raw.musicmenu_overcast);
float streamVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mpMusic.setVolume(streamVolume, streamVolume);
mpMusic.start();
mpMusic.setLooping(true);

What am I doing wrong? Thank you all!


Solution

  • Note that here, there are 2 kinds of sound level :

    • The STREAM volume
    • The PLAYER volume

    If you set the PLAYER volume to "0", whatever the value of the STREAM volume is, you will never hear anything... If you set the PLAYER volume to "10" for example, you will hear your music with a level that is 10% of the STREAM volume.

    In your case, you are setting the volume player to "0" when the STREAM volume is 0... that is why you don't hear anything.

    Are you sure that you need to adjust the volume of the PLAYER ?