I have an android app with a button that plays a sound. the code for playing the sound:
if (mp != null)
{
mp.release();
}
mp = MediaPlayer.create(this, R.raw.match);
mp.start();
mp is a field in the activity:
public class Game extends Activity implements OnClickListener {
/** Called when the activity is first created. */
//variables:
MediaPlayer mp;
//...
The app runs ok, but after clicking the button about 200 times on the emulator, app crashed and gave me this error https://dl.dropbox.com/u/5488790/error.txt (couldn’t figure how to post it here so it will appear decently)
i am assuming this is because the MediaPlayer object is consuming up too much memory, but isn’t mp.release() supposed to take care of this? What am i doing wrong here?
It looks like your code should work, but obviously
release()isn’t really releasing everything.Maybe it’s because you have to reload
R.raw.matchevery time you want to play the sound. IfR.raw.matchis just a short sound effect, then you might want to consider usingSoundPoolinstead.If you use
SoundPoolyou only have to loadR.raw.matchonce which may prevent the memory issues.This tutorial has a good example on how to use it: http://www.vogella.com/articles/AndroidMedia/article.html#tutorial_soundpool
You pretty much just make one instance of SoundPool then load the sound once and play it when you need it.
Hope this helps!
Edit
If you want to use MediaPlayer…
This way you only create one instance and whenever you want to play it, you just rewind it to the beginning then play.