I want to check if MediaPlayer is released - how to check it? I found that isPlaying generate exception instead of false - it is complicated how to do it in simple way.
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
}
});
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 mIsPlayerRelease = true;
mediaPlayer = MediaPlayer.create(myContext, soundId); // ready to play
mIsPlayerRelease = false;
....
mediaPlayer.reset(); // ready to play again
mIsPlayerRelease = false;
....
mediaPlayer.release(); // can't be played until release.
mIsPlayerRelease = true;
EDIT:
You can fix the blocking issue by placing the creation in an AsyncTask
and setting the variable on completion.
private class MediaCreator extends AsyncTask<Integer, Void, Boolean> {
WeakReference<Context> mCtx;
public MediaCreator(Context ctx) {
mCtx = new WeakReference(ctx);
}
@Override
protected Boolean doInBackgroind(Integer.... params) {
final Context ctx = mCtx.get();
if(ctx == null || params == null || params.length == 0) {
return false;
}
mediaPlayer = MediaPlayer.create(ctx, params[0];
}
@Override
protected void onPostExecute(Boolean success) {
if(success) {
mIsPlayerRelease = false;
} else {
mIsPlayerRelease = true;
}
}
}
You can put this class in whatever class is handling mediaPlayer
. Start it with
MediaCreator creator = new MediaCreator(myContext);
creator.execute(R.id.mySoundId);
The method doInBackground
will create and buffer the media player on a separate thread. It will return once created and onPostExecute()
will be called on the main thread setting the boolean to false
if the player was created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With