Android: Adding Sound Effects with SoundPool

Here is another beginner Android development tutorial.

For some time now, I want to add sound effects to my Android quiz game Quizzly, so now as I learn how to do it, I will make a small tutorial.

To start off, l would like to point out that there are two built in classes in Android for playing sound. MediaPlayer and SoundPool. The first one should be used for longer sounds like music and the second one is for shorter sounds like sound effects. I will be adding a small sound effect to the game, so I will use SoundPool.

The first thing we are going to do is actually add the sound files to the project, so in the resources folder make a folder named “raw” and add the sound files(use lowercase characters for naming the files)

 

 

 

 

 

 

 

 

The next thing that we are going to do is import the classes that we will need in the activity where the sounds will be played

import android.media.AudioManager;

import android.media.SoundPool;

Next, we will create out SoundPool object, that we will use for playing the sounds as well as a HashMap object where we will put the sounds for easy access:

SoundPool quizzlySoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

soundsMap = new HashMap<Integer, Integer>();

 After that, we need to load the sounds and add them to the Hash Map. a good place to do that is inside the onCreate() method of the activity

soundsMap.put(1, quizzlySoundPool.load(this, R.raw.ding, 1));

soundsMap.put(2, quizzlySoundPool.load(this, R.raw.buzz, 1));

 Now we are all set to play the sound. We can do so, by calling the play() method

quizzlySoundPool.play(soundsMap.get(1), 1f, 1f, 1, 0, 1f);

Well that is it. Fell free to try it out and leave a comment.

Check out Quizzly on the Google Play Store.

Tagged with: , , ,
Posted in Android, Tutorials
3 comments on “Android: Adding Sound Effects with SoundPool
  1. erdani says:

    Hello there, You’ve done a great job. I will definitely digg it and in my opinion recommend to my friends. I am confident they’ll be benefited from this web site.

    • Nikola Kirev says:

      Thanks for the comment!

      • Cyrille says:

        Hello Nikola!
        Thanks for your great tutorial!
        I wish I could adapt it so that a sound would be played when hitting an OTG USB keyboard key… Which part of your code should be modifyed and how?
        Thanks a lot!

Leave a Reply

Check out my apps: