Change media player volume on seekbar

2020-02-16 01:28发布

问题:

I am working on a game application. But there is a problem on volume control. I want to change media player volume using a seekBar, and not system media volume. Is there any solution for change media player volume via seekBar.

Thanks in advance.

回答1:

First, get a reference from AudioManager;

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

To raise the volume:

 audioMan.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_VIBRATE | AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);

To low the volume:

audioMan.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_VIBRATE | AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);

To get the max volume:

int maxVolume = audioMan.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

To get the current volume:

int currVolume = audioMan.getStreamVolume(AudioManager.STREAM_MUSIC);

You can remove any of the flags that I've included



回答2:

May be this help...

protected static void setVolume(int volume) {
        currentVolume = volume;
        {
            if (volume == 1) {
                volume = 2;
            }
            try {
                float vol = ((float) volume / CONSTANT.SYSTEM_MAX_VOLUME);
                mediaPlayer.setVolume(vol, vol);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }