Android mediaPlayer - is there an "isPrepared()" or "getStatus()" method?

Viewed 17219

I'm having issues with Android's MediaPlayer. It seems like it's missing important functionality, mainly a way to get the current status of MediaPlayer or to find out if it's prepared. I know there's the on prepared listener, but the MediaPlayer lasts longer than the Activity, so when the Playing Activity is resumed, it would be nice to get current player state, whether or not it's trying to load media, whether media is loaded, etc. Am I missing something, or do I have to keep track of the player states myself?

Other functionality that would be nice would be onPlayStateChanged() - I currently have to keep track play state manually. Am I doing it wrong?

6 Answers

I have found something which might be helpful for you and others. There is a setOnPreparedListener() function in MediaPlayer class which makes you able to run a piece of code when the MediaPlayer is prepared.

Also, if you want to be sure your media has been loaded, you can use the getDuration() function. This code returns the duration in milliseconds, if no duration is available it returns -1. Here below is the code:

yourMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        if(yourMediaPlayer.getDuration() != -1){
            //your code when when something is loading
        }
    }
}

There is no getState of MediaPlayer class, but internally it has a state, as explained by alex.magellan. Calling methods at "not allowed states" results in Exception.

To avoid these, i have created a StateMachine with MediaPlayerWrapper class. So instead of calling MediaPlayer directly, MediaPlayerWrapper is used, which internally updates StateMachine and exposes getState() method.

StateMachine and Wrapper class implementations can be found here.

I don't think there's a way to do it through the MediaPlayer class itself.

Easiest thing to do is global variable that gets set to true upon creation and reset. It get set to false on release.

boolean playerAvailable = true;

mediaPlayer = MediaPlayer.create(myContext, soundId); // ready to play

playerAvailable = true;

....

mediaPlayer.reset();   // ready to play again

playerAvailable = true;

....

mediaPlayer.release(); // can't be played until release.

playerAvailable = false;

you could make a workaround for this by having a predefined boolean variable and setting it to true when the onPrepared() callback is called and set it to false when the MediaPlayer starts. for example:

public boolean mpPrepared = false;

mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
        mpPrepared = true;
    }
});

mp.start();
mpPrepared = false;
Related