Play sound in Android tutorial

6 10 2012

To play sounds in android you can use SoundPool. My solution is based on a SoundUtils class having two methods (in simpliest scenario). Audio files has to be in /res/raw/

  • initTiltSounds(Context context) loads sounds from resources and sets boolean flag after it has finished loading. If flag is false it means that sounds can’t be played yet, so in my case I call it in OnCreate method
  • playSound(AudioManager audioManager) plays sounds loaded in previous method

My SoundUtils looks as follows:

public class SoundUtils {

	private static final String LOG_TAG = SoundUtils.class.getSimpleName();

	private SoundPool soundPool;
	private boolean soundsLoaded = false;
	private int soundID;

	public void initTiltSounds(Context context) {
		soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

		soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
		public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
				soundsLoaded = true;
		soundID = soundPool.load(context, R.raw.swosh_sound_effect, 1);

	public void playSound(AudioManager audioManager) {
		float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		if (soundsLoaded), actualVolume, actualVolume, 1, 0, 1f);
			Log.e(LOG_TAG, "Tilt Sound not loaded");

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!




Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: