Pr.Pg Next Pg

Adding Music using SoundPool tutorials


Adding Music using SoundPool

  • MediaPlayer is used when we want to add long music to our application.

  • But when we want to add short sounds we add it using SoundPool.

  • We now add a short sound clip in our raw folder which we had created and make sure the name of the file is in lower case.

  • To illustrate how to add music using sound pool we make a class which will have the following code.


package com.example.helloandroid;





import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;


public class ShortSounds extends Activity implements OnClickListener {

SoundPool sp;

int firework=0;


protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub


View view = new View(this);



sp = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);

firework = sp.load(this, R.raw.firework_rocket_launch, 1);



public void onClick(View arg0) {

// TODO Auto-generated method stub

if(firework!=0){,1,1, 0, 0, 1);







  • In this Example what we do is that whenever we will click on the screen, a sound will play.

  • So set up a View object and then we set our ContentView to this object.

  • Then we create a SoundPool object and initialize the constructor as shown.

  • The parameter 3 is basically the number of simultaneous streams that can play.

  • Next parameter is the audio stream as described by the audio manager.

  • The third quality has currently no effect. We just use it as 0 for now.

  • Then we make our SoundPool object load our clip and this method returns an int value which is the sound ID which can be used to play or unload the sound.

  • The load() method takes the application context , the resource ID of the sound and the priority of the sound.

  • This priority has no effect right now.However we use 1 for future compatibility.

  • We then play the sound in our onClick() method.

  • We initialize our firework variable to 0 so that the SoundPool object may take sometime to load the file and we don’t want to play the sound before it finished loading, just to prevent any error.

  • So this was a simple application in which we add a short sound.

Difference between SoundPool and Media Player


  • SoundPool is designed for short clips which can be kept in memory decompressed for quick access, this is best suited for sound effects in apps or games.

  • Using this method with soundboards is a bad idea as you will be loading lots of “medium” sized sounds into the memory and you may exceed your limit (16Mb) and get an OutOfMemoryException.


  • MediaPlayer is designed for longer sound files or streams, this is best suited for music files or larger files.

  • The files will be loaded from disk each time create is called, this will save on memory space but introduce a small delay (not really noticeable).


Pr.Pg border                                              Next Pg