Sterisk Sterisk - 2 months ago 22
Android Question

How to return state of media player?

I'm trying to return the current state of the media player because I want to check that the media player has not loaded a song yet so I can provide a popup to choose an audio file.

Code in other class

public Sound(int buttonID, Activity _activity) {
super();
this.activity = _activity;
button = (Button) activity.findViewById(buttonID);
mp = new MediaPlayer();
}


Code to check if an audio file is loaded

sound.button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(//no audio file loaded){
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivityForResult(intent, PICK_AUDIO_REQUEST);
}
else if(sound.mp.isPlaying()) {
sound.mp.pause();
}
else{
sound.mp.seekTo(0);
sound.mp.start();
}
}


});


Using the answer, this is the code I came up with:

sound.button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sound.mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
isPrepared = true;
}
});

if(!isPrepared){
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivityForResult(intent, PICK_AUDIO_REQUEST);
}
else if(sound.mp.isPlaying()) {
sound.mp.pause();
}
else{
sound.mp.seekTo(0);
sound.mp.start();
}
}


});

Answer

I'm afraid that there is no such method. You have to check it yourself. It's not too hard to follow MeidaManager state with the MediaPlayer's StateDiagram. The easiest way is to declare a boolean flag isPrepared / isReadyToPlay and set it to true in onPrepared() callback of the OnPreparedListener.

Comments