Reputation: 69
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(context, R.raw.lonely);
player.start();
player.release();
Help me. Thanks in advance.
Upvotes: 0
Views: 580
Reputation: 298
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();
}
Upvotes: 0
Reputation: 6447
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.
Upvotes: 1
Reputation: 24251
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.
Upvotes: 2