Reputation: 600
I have a media player and everytime that this activity is called if there is a media player playing i want it to stop and the new media player start playing ... This is my audio player method
private void playAudio(String url) throws Exception{
mediaplayer.release();
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();
}
I initialize the media player at the beginning of the class
private MediaPlayer mediaplayer = new MediaPlayer();
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.songplaying);
// Getting Our Extras From Intent
Bundle names = getIntent().getExtras();
// Getting Specific Data
path = names.getString("pathkeyword");
//Start Player
try {
playAudio(path);
} catch (Exception e) {
e.printStackTrace();
}
Everytime this is class is created it creates a new media player doesn't stop the other one and just plays both at the same time.
Upvotes: 1
Views: 704
Reputation: 3440
You may wish to look into onPause
and kill the media player then. The problem is that there is no reference to the media player once it has been made a 2nd time. As a result, you start up your activity, play the music, but when you exit (e.g. press the HOME button) the media player has not been told to stop (it runs as a separate thread). When you reopen it, it will start a new media player on a new thread, producing two sounds.
To fix this, kill the media player properly when you exit. This will properly kill the media player when you quit the activity:
@Override
protected void onPause(){
super.onPause();
if(mediaplayer.isPlaying()){
try{
mediaplayer.stop();
}
catch(IllegalStateException){
Log.d("mediaplayer","Media player was stopped in an illegal state.");
}
}
}
If you wish to continue the music whilst the activity is not in the foreground, you need to use a Service
.
Upvotes: 2