How to stop mediaplayer while playing on background?

Viewed 366

I am developing a music player on android and the app has two activities (MainActivity and PlayActivity). In the MainActivity I have a listview with a list of songs and in the PlayActivity I have a button to listen and pause the music. The problem is that when go back to MainActivity and I select a new song from the listview, the first one keeps playing on background while the second one also starts playing. How can I stop the first song when I select a new one? (I don't want to stop mediaplayer onBackPressed, I just want to stop the music when another song it's selected from listview and play a fresh song in PlayActivity)

EDIT: I'm using AsyncTask to start mediaplayer on PlayActivity: mp.prepareAsync();

3 Answers

You could try to stop MediaPlayer when onBackPressed()

MediaPlayer  mp ; // mp is your MediaPlayer

@Override
public void onBackPressed() {
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }
    super.onBackPressed();
}
private void playMusic() {
    if (mp != null) {
        if (mp.isPlaying()) {
            mp.stop();
            mp.release();

            MediaPlayer copyMp = new MediaPlayer();

            try {
                copyMp.setDataSource("/path");
                mp = copyMp;
                mp.prepare();
                mp.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From here

MediaPlayer is not thread-safe. Creation of and all access to player instances should be on the same thread.

That means you have to maintain one media player instance throughout your whole application(As per your requirement). I don't know how you implemented the media player(Service/AsyncTask etc.). When you select a new song, you need to access that instance and replace the existing song with the selected one.

Related