Posts tagged ‘sound’

Android play instant sound from resource

I wanted to play short sound bites in a Android application, when playing sounds on the Media player there is a lag as the Media player needs to allocate memory, load the resource etc. If you need to play short sounds in response to button click or when shooting a gun in your game you need it to play instantly in response to what the user just did. In that respect SoundPool is the way to go, it allows preloading the soundbites and gives instant access to the sounds as needed. I created a simple convenience class for it as seen below.

//
package us.kristjansson.android.util;
//
import android.media.AudioManager;
import android.media.SoundPool;
import android.app.Activity;
//
import java.util.HashMap;
//
import us.kristjansson.android.R;

public class CxMediaPlayer
{
private SoundPool mShortPlayer= null;
private HashMap mSounds = new HashMap();

// Constructor
public CxMediaPlayer( Activity pContext )
{
// setup Soundpool
this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);

// 0-9 Buttons
mSounds.put( R.raw.button_1, this.mShortPlayer.load(pContext, R.raw.button_1, 1) );
mSounds.put( R.raw.button_2, this.mShortPlayer.load(pContext, R.raw.button_2, 1) );
mSounds.put( R.raw.button_3, this.mShortPlayer.load(pContext, R.raw.button_3, 1) );
mSounds.put( R.raw.button_4, this.mShortPlayer.load(pContext, R.raw.button_4, 1) );
mSounds.put( R.raw.button_5, this.mShortPlayer.load(pContext, R.raw.button_5, 1) );
mSounds.put( R.raw.button_6, this.mShortPlayer.load(pContext, R.raw.button_6, 1) );
mSounds.put( R.raw.button_7, this.mShortPlayer.load(pContext, R.raw.button_7, 1) );

// Others
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.correct_answer, 1) );
mSounds.put( R.raw.delete_5, this.mShortPlayer.load(pContext, R.raw.wrong_answer, 1) );
}

// Plays the passed preloaded resource
public void playShortResource( int piResource )
{
int iSoundId = mSounds.get( piResource );
this.mShortPlayer.play( iSoundId, 0.99f, 0.99f, 0, 0, 1 );
}

// Cleanup
public void Release()
{
// Cleanup
this.mShortPlayer.release();
this.mShortPlayer = null;
}
}

Then all you need in your Activity is to initiate the player class and call playShortResource when you need a sound played. Your resources should be available in the res/raw directory.

// The media player – OnCreate
  mxMediaPlayer = new CxMediaPlayer( this );
// Play the desired sound – OnClick
  mxMediaPlayer.playShortResource(  R.raw.button_1 );
// Make sure to release resources when done – OnDestroy
  mxMediaPlayer.Release();