Android: Soundpool vs MediaPlayer (focus on soundboards and memory problems)
I get a fair few emails asking for help on making soundboards because I have a few out on the market currently, so this is one of a few mini-tutorials I am creating to explain some of the difficulties to overcome.
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).
So lets have a look how to use Media Player instead of SoundPool
MediaPlayer mp = MediaPlayer.create(ClassName.this, R.raw.sound); mp.start();
Where ClassName.this should be the name of your class (Hint: this should be the name of the java file you are editing)
You can pause the sound playing and then use start to start the sound playing again.
mp.pause(); // Stop mp.start(); // Start from place paused
To stop the sound playing use stop, using start now will start playing the sound again from the beginning
mp.stop(); // Stop sound mp.start(); // Start from beginning
To reset the media player so it can be reinitialised with a another sound
mp.reset(); mp = MediaPlayer.create(ClassName.this, R.raw.sound2);
To release the resources once you are finished media player (free memory)
Below are a few screenshots of my current soundboards on the market