David Stockdale's Scrapcode

App Music And Effect Volumes

It’s annoyingly difficult to find a clear answer on how to set the volume of background music and sound effects seperately.

This is annoying because my background music was loud enough that the player characters footsteps can’t be heard.

My first attempt to fix this was using “setVolume” on my MediaPlayer.

Example:

MenuViewModel mViewModel = ViewModelProviders.of(getActivity()).get(MenuViewModel.class);

mViewModel.setMusic(MediaPlayer.create(getActivity().getApplicationContext(), R.raw.the_villain_strikes_back));

mViewModel.play();

float currVolume = 0.5f;
float maxVolume = 0.5f;

mViewModel.music.setVolume(currVolume,maxVolume); //must be between 0.0 and 1.0!

This worked for decreasing the volume of the background music, but when I attempted to set my sound effect to 1.0f it was still just as quiet.

Another option was to use SoundPool.

Example:

SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);

int soundId = soundPool.load(context, R.raw.ringtone, 1);

soundPool.play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)

Be sure to release the SoundPool resources after use:

soundPool.release();
soundPool = null;

Last resort would of course be to change the audio files themselves to simply be louder.

Leave a Reply