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
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.