Skip to content Skip to sidebar Skip to footer

How Do I Make A Mediaplayer Stop When Another Mediaplayer Starts So That They Dont Play On Top Of Each Other?

I have 2 buttons that both play an mp3. When the first song is playing I want a click of the second song to stop the first song, and start the song that was clicked. also if the fi

Solution 1:

Seems like you need to implement a state machine to manage your player (start-stop-restart) instead of creating a new player every time a button is pressed

Solution 2:

Here is a sample sound helper class I use for simple apps. I use it to play at most one resource at a time within my app, but you could modify it to play audio from some url instead.

publicclassSound
{
privatestatic MediaPlayer mp = null;

/** Stop old sound and start new one */publicstaticvoidplay(Context context, int resource)
{
    stop(context);

    mp = MediaPlayer.create(context, resource);
    mp.setLooping(false);
    mp.start();
}

/** Stop the music */publicstaticvoidstop(Context context)
{
    if (mp != null)
    {
        mp.stop();
        mp.release();
        mp = null;
    }
}
}

Solution 3:

Whoooaaaaa, losing handles on MediaPlayers left and right.

First of all, for this particular activity, you should only put

mp = new MediaPlayer();

in the onCreate() method of your activity. Delete the two you call in the onClick() method and move it to the onCreate() method.

From there, all you have to do is include a call to mp.reset() right before you call mp.setDataSource() and it should work just like you want it to!

Cheers

Post a Comment for "How Do I Make A Mediaplayer Stop When Another Mediaplayer Starts So That They Dont Play On Top Of Each Other?"