Search code examples
androidandroid-mediaplayer

How to stop media player properly , android


I have created a list of songs on click on the song i am able to play the song using MedaiPlayer. While one song is playing if the user clicks another song then i am stopping the media player and starting the player again. But I am getting illegalstateexception in reset(). Here is the code where I am getting the exception. How to stop a player properly? also why am i getting this exception. How to avoid it?

public void stopPlayer() {
        try {
            if (player != null) {
                // Log.e("Trying to Stop "," Player ");
                player.stop();
                player.release();

                player.reset();// causes IllegalstateException

                player = null;

            }

        } catch (Exception e) {
            player = null;
            playerStatus = false;
            e.printStackTrace();
        }
    }

Solution

  • try this :

    player.reset();
    player.release();
    

    and also have a look at media player state diagram.