How to play media?
Hi How to play media file in an application.I am trying it with the following code but do not know why it is not working for me
player= new MediaPlayer().create(cont开发者_开发知识库ext, R.raw.lonely);
player.start();
player.release();
Help me. Thanks in advance.
I haven't played with MediaPlayer
, but I would try without the release()
call. This example doesn't use it. And the docs say it's a cleanup method to be called after the playback:
Releases resources associated with this MediaPlayer object. It is considered good practice to call this method when you're done using the MediaPlayer.
I think you're messing up the with constructors. You can instantiate the MediaPlayer statically: MediaPlayer.create(Context context, int resid)
, which is the easiest way, cause you just need to call play()
. Also you need a valid context, it's to say, if you're creating rhe MediaPlayer within an Activity or a Service, just pass "this" as a context.
You can also use the "normal" constructor MediaPlayer()
, but then you would have to explicity call to setDataSource()
and prepare()
before play()
.
Besides, as Grzegorz wrote, calling release()
just after play()
is not a good idea.
you can folow this sample :
public void audioPlayer(String path, String fileName){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(path+"/"+fileName);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
精彩评论