Add Sound Effects to Your Android Game
Join the DZone community and get the full member experience.
Join For Free
Every game has sound and music. In this short post I will teach you
how to add sound to your own Android game. Lets start off with the base
sprite example from last post.
After downloading, import the project into your workspace and build it to
your device. When done correctly, you will be able to add a sprite of an
explosion by touching the screen.
Now we have a working sprite example!
Next we need the sound of an explosion:
More code after the break:
Go to your Eclipse project and make a new folder under res named raw. Put the explosion.wav into that folder (see image).
Now let's set up the code.
Open the AnimationView.java file and add the following variables to the AnimationThread:
/** Sound variables */ private SoundPool sounds; private int sExplosion;
Now scroll down into the constructor so we can initialize them (above the run method). Add these lines just above the closing bracket of the constructor:
sounds = new SoundPool(10, AudioManager.STREAM_MUSIC,0); sExplosion = sounds.load(context, R.raw.explosion, 1);
Now the SoundPool is set up
and can play 10 streams at a time. Now we just need to tell the
SoundPool when to start playing, so scroll down again and find the following
inside the doTouch event:
a.setXPos((int)x); a.setYPos((int)y);
add these lines below:
sounds.play(sExplosion, 1.0f, 1.0f, 0, 0, 1.5f);
Thats it! Just run and add sprites by touching the screen. We now have a sound effect! ( Be sure to enable your sound )
Here is a dump of the finished Eclipse project:
Source: http://p-xr.com/android-tutorial-add-sound-effects-to-your-game/
Opinions expressed by DZone contributors are their own.
Comments