How can stop mediaPlayer which is already running ,and create new mediaPlayer?
I am working in android. I am creating a mediaPlayer which is running audio files. i have 10 buttons. i have assigned different url to each button. So when i press button1 then song of url with respect to button 1 is playing. and then i click on 2nd button then song of button 2 is also playing with song 1. but i want to stop song of button 1 when i press button 2.
this is the code i am using for this functionality:-
public void onClick(View v)
{
MediaPlayer mediaPlayer=new MediaPlayer();
if (mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
int i = Integer.parseInt((v.getTag()).toString());
String str=urls[i];
try {
mediaPlayer.setDataSource(str);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e)
{
e.printStackTrace();
}
}
please check my code and let me know what is mistake done by m开发者_Go百科e.
you have construct a new MediaPlayer object each time the user click you view
how could it be in the running state !!!
calling release()
method on a MediaPlayer object it is in thre End state
Once the MediaPlayer object is in the End state, it can no longer be used and there is no way to bring it back to any other state.
but in case you want to reuse a MediaPlayer object you should call the call the following method in the same order
reset() make the mediaPlayer enter the Idle state
setDataSource() set your data source note : the mediaplayer shoud be in the idle state
prepare()
start()
精彩评论