Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if MediaPlayer is released()?

Tags:

android

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();
        }
    });
like image 690
Chameleon Avatar asked Feb 05 '13 14:02

Chameleon


1 Answers

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.

like image 163
DeeV Avatar answered Sep 25 '22 14:09

DeeV