Over a million developers have joined DZone.

Add Sound Effects to Your Android Game

DZone's Guide to

Add Sound Effects to Your Android Game

· Mobile Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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:


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/


Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}