Search code examples
androidandroid-mediaplayerringtone

How to set android MediaPlayer volume according to ringtone volume?


How can I set the MediaPlayer sound volume according to ringtone volume?

I did this method, but doesn't work:

        MediaPlayer player = MediaPlayer.create(MyActivity.this, R.raw.sound);
        AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = audio.getStreamVolume(AudioManager.RINGER_MODE_NORMAL);

        player.setVolume(currentVolume, currentVolume);

Solution

  • Instead of adjusting the volume, you should use setAudioStreamType() to set which audio stream you want to play your audio over - this automatically uses the volume of the selected stream. For example, if you want your audio to play at the same volume as a notification would, you could use AudioManager.STREAM_NOTIFICATION:

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);