Saturday, November 16, 2013

Simple usage of MediaPlayer on Android

In the side project, I wanted to play a sound that I have embedded as part of the resources. After a short research, Android provides MediaPlayer to help you play sounds and videos. I am only going to use it playback some sounds.

Before I started, I browse over to the MediaPlayer docs on Google. The most important is the state diagram that it is displaying. From here, it is required for states of your implementation of the player to follow.

To start with, you will need to create your instance of MediaPlayer.

try {
    mp = MediaPlayer.create(getApplicationContext(), R.raw.whitenoise_30s);
} catch (IllegalStateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
mp.setLooping(true);
mp.start(); 

When create() is called, the MediaPlayer enters into Prepared state. This means that we can immediately call the start()  and the MediaPlayer transitioned into the Started state. The audio will start to play on  the speaker.

To stop the playing, stop() can be called. When stop() is called, the MediaPlayer transitioned into Stopped. The audio will stop to play and be silent on the speaker.

To playback, instead of calling create() again, it is better to call prepare(). From the state diagram, the MediaPlayer will transition from Stopped to Prepared. A boolean could be used to track if the MediaPlayer has been created or not. This is to indicate whether create() or prepare() should be called. 

No comments: