Flash Colors – Game using seperate Sound Class

fklAnother app in the Google Play Market. This time, I focussed on how to create a seperate class to handle Sounds. The app is quite simple. It shows colors. The user can choose one of 3 playing modes; simple, medium (remember growing series) or hard (remember random series). It was a challenge to work with a seperate Sounds class, that would handle sound playing.

For this app, I used SoundPool. There is one other method to play sounds, MediaPlayer. The latter is for large sounds, music and so on. For Flash Colors, a small soundbite is sufficient, so SoundPool will do.

First, we create a seperate class that we can invoke when sounds are played ;

 

import android.media.SoundPool;

public class DoSound {

	private static SoundPool soundPool;
	private static HashMap<Integer, Integer> soundsMap;
	static int SoundYeah = 1;
	static int SoundWrong = 2;

	public static void initSounds(Context context) {

	soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
	soundsMap = new HashMap<Integer, Integer>();
	soundsMap.put(SoundYeah, soundPool.load(context, R.raw.yeah, 1));
	soundsMap.put(SoundWrong, soundPool.load(context, R.raw.wrong, 1));
}
	 /** Play a given sound in the soundPool */
	 public static void playSound(Context context, int soundID) {
	if(soundPool == null || soundsMap == null){
	   initSounds(context);
	}
	    float volume = 1.0f;

	    soundPool.play(soundsMap.get(soundID), volume, volume, 1, 0, 1f);
	 }

}

Now, we can use this class in a different class. First, we instantiate the class in the OnCreate() portion of the Main class.

    private DoSound myDoSound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.series_onthouden);

        myDoSound = new DoSound();

Then, we can call the sound-module like this :

myDoSound.playSound(this, DoSound.SoundWrong);

Please note that the context (this) is being passed to the Sound handling class.

 

You can leave a response, or trackback from your own site.

Leave a Reply