Search code examples
androidandroid-activitymp3android-mediaplayer

Android media player : How can I listen for media player events?


I am following the this explanation of the MediaPlayer and I am wondering how can I listen to the events from the player such as playing, paused, stopped etc...

The page shows how to listen only for the onPreparedListener and so I was wondering if there are events for the the other states of the player, or how would I handle the different states of the player?


Solution

  • Unfortunately you can not detect if the mediaplayer is paused or stopped, The MediaPlayer class has one function isPlaying() which will detect if it's in playing mode or not. You can do some effort for detecting pause condition as below :

    mediaplayer.pause();
    //get the length of the mediaplayer here
    length=mediaplayer.getCurrentPosition();
    //and for resume you can do the following
    mediaplayer.seekTo(length);
    mediaplayer.start();
    

    For checking stopping state of mediaplayer, you can check as above , the only change will be the time which will reach to maximum. That's all. Or, You can use setOnCompletionListener()

    Also check this answer , how mediaplayer reaches different states. Click here

    The mediaplayer contains following listener :

     1. setOnBufferingUpdateListener
     2. setOnErrorListener
     3. setOnInfoListener
     4. setOnCompletionListener
     5. setOnSeekCompleteListener
     6. setOnTimedTextListener
     7. setOnVideoSizeChangedListener
     8. setOnPreparedListener
    

    Hope this will help you . :)