I am developing a simple game in Android. I want to add sound effects for each of the touch events. However I have add background sound effect that runs throughout the game
For short sound effect like explosions, coin collections etc, it is better to use SoundPool
.
You just need to create a sound pool :
SoundPool sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
In Lollipop and later:
AudioAttributes attrs = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
SoundPool sp = new SoundPool.Builder()
.setMaxStreams(10)
.setAudioAttributes(attrs)
.build();
This creates sound pool for max. of 10 sound streams (i.e. how many simultaneous sound effects can be played at any one time) and uses AudioManager.STREAM_MUSIC
as sounds stream.
Be sure to also set the volume control in your Activity
, so the user is able to change the volume of the proper stream:
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Than, you need to load sound effects into pool and give them their identifiers:
int soundIds[] = new int[10];
soundIds[0] = sp.load(context, R.raw.your_sound, 1);
//rest of sounds goes here
You need to pass a context to load method, so either you do this inside your activity, or get is from somwhere else.
And final step to play sound is to call play
method:
sp.play(soundIds[0], 1, 1, 1, 0, 1.0);
parameters are:
soundID a soundID returned by the load() function
leftVolume left volume value (range = 0.0 to 1.0)
rightVolume right volume value (range = 0.0 to 1.0)
priority stream priority (0 = lowest priority)
loop loop mode (0 = no loop, -1 = loop forever)
rate playback rate (1.0 = normal playback, range 0.5 to 2.0)
You need to remember, that SoundPool
should not use media files over 1MB, the smaller the files, the better effect and performance you have.
Be sure to release the SoundPool
when you are done, or in Activity.onDestroy
.
sp.release();
Hope this helps
GameView is not a subclass of Context. Pass the Activity or the ApplicationContext to the Mediaplayer
Just do the following ...
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.combo);
mp.start();
I found it at How to play a Sound Effect in Android