android-How to play local wav file with MediaPlayer ?
1. The purpose of this post
This post would demo how to use android MediaPlayer to play local wav file in the raw directory.
2. Environments
- android 4.0+
3. The solution
3.1 Add wav file to your res/raw directory
Add your ring.wav file to your res/raw directory, it the directory does not exist, just create a new one.
3.2 The code(The basic one)
The most easiest code to play local wav file is as follows:
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.ring);//define a new mediaplayer with your local wav file
mediaPlayer.start(); // no need to call prepare(); create() does that for you
Increase your phone’s volume now, you should hear the sound.
3.3 The production code
Because the MediaPlayer initialization process is expensive , you should not call it on your main UI thread, and in order to avoid the memory leak problem, you should release the MediaPlayer once you have completed the play.
The demo code:
try {
if(mediaPlayer==null) {//check if it's been already initialized.
mediaPlayer = MediaPlayer.create(context, R.raw.ring); // this method is expensive on cpu and memory
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
Log.debug("TestRing",play wav finished"); //when the play completes, print a log
}
});
mediaPlayer.start(); //start play the wav!
}catch (Exception ex) {
LogUtils.error("",ex);
if(mediaPlayer!=null) {
mediaPlayer.release();// if error occurs, reinitialize the MediaPlayer
mediaPlayer = null; // ready to be garbage collected.
}
}
4. Conclusion
You can get more information from google official documents on MediaPlayer.