Playing sound on Andorid, no worries!

Was looking into making a funny little app that plays a noise when you press a button.

As I was packaging the sound files with my application there was no need to watch out for IO Exceptions or file paths. This meant that code to do this was hilariously simple.

MediaPlayer mp = MediaPlayer.create(thisContext, R.raw.giggity);
mp.start();

Sweet ey? Basically becuase my sound (Family Guy's Quagmire's "Giggity") was packaged with the app, then i simply pass it the int resource ID "R.raw.giggity" and my application's context (as its an activity, this is itself).

Then you just start().... Giggity! haha.

HOWEVER... When i started "Giggity Spamming" myself with lots of giggitys, i soon ran out of memory! I tried calling a garbage collection manually, and then I tried moving the MediaPlayer object declaration to be a global class variable. This then gave me problems when I tried to call another sound with the same class, because the MediaPlayer was in the wrong state.

The solution is to call a reset() on the media player, so that it is ready to play another sound. (apart from when mp is null, as it would be on the first call)

MediaPlayer mp;
playSound() {
  if (mp != null) mp.reset();
  mp = MediaPlayer.create(thisContext, R.raw.Giggity);
  mp.start();
}

That's it, noises with no memory leaks. Giggity!