Wednesday, May 20, 2015

Playing Raw WAV File in Android - Eclipse

In this post I'm gonna show you a simple steps on how to play a raw wav file in android. First let's make a new project in eclipse :
Then put one button to the main GUI :
Next.. Right click on "res" folder, choose "New" then "Folder" as shown below :
Name the new folder as "raw" :
Then put your wav file to that raw folder :
Next,.. Let's make a handler program for our button :
After that, making a handler for mediaplayer :
Let's initialize our mp in onCreate method :
From line 23 we can see that mp player will be playing our footballcrowd.wap that we have included before. On line 24 we set the mp player to loop forever... Ok... Let's put that mp player to our button click listener :
Rightnow if you are going to run this code on real device then press the play button. We can see that our wap file can be played already. But there is one problem here, If wav file is playing, we don't know how to stop it except for using force stop. So we need to add another handler for stopping the mp player. Ok... ummm.... add following code to the button click listener :
In above code, we were helped by "status" variabel to stop the mp player. If status equals true, it means that our mp player is being played now so when clicking play button again it will execute mp.stop() as seen in line 36. After executing that code we can see that mp player is stopped. The next code is in line 39, we see that code is similar initialization from onCreate() method, but why we have to do initializing again...?? Well... After executing mp.stop(), it seems that our mp player is empty, so we need to initialize it again hehehe... :D *simple explanation...

Ummm... The last code piece is to put mp.stop() inside onPause method. So right click anywhere in main activity, choose "Source" then "Override/Implements Methods..." as shown below :
Then choose "onPause" :
Put this code inside onPause code block :
We have to stop mp player in onPause because there might be a chance that user leave the application accidently without stopping it first by clicking the play button. When this event happens, our mp player will continue to run in background event if application already closed. So that's why we have to stop it in onPause when our application become unavailable in the main screen....




Aaaandd... oooh... I forgot to put mp.release() after mp.stop(). Please do it by yourself....hehehe... :-)

No comments:

Post a Comment