Playing sound Effect using MediaPlayer

1 vote · 3 comments

Playing from a Raw Resource Perhaps the most common thing to want to do is play back media (notably sound) within your own applications. Doing this is easy:

  1. Put the sound (or other media resource) file into the res/raw folder of your project

  2. Create an instance of MediaPlayer, referencing that resource using MediaPlayer.create, and then call start() on the instance.

  3. To stop playback, call stop(). If you wish to later replay the media, then you must reset() and prepare() the MediaPlayer object before calling start() again. (create() calls prepare() the first time.)

To pause playback, call pause(). Resume playback from where you paused with start().

raw ·
copy
· download
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); mp.start();
Add a comment

3 Comments

This method calls prepare for you, before you use it again you'll have to null the media player state by calling reset() and then after setting the new datasource call prepare().

Reply · Oct. 13, 2009, 2:27 a.m.

Simple and Great!!!!

Reply · July 17, 2013, 9:09 p.m.

I'm not able to play a tick sound (which plays perfectly in WinAmp) inside a ContdownTimer 's onTick methoc, while the explosion sound plays well in the onFinish method. Strange enough...

Reply · May 20, 2014, 2:30 p.m.