Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I release or reset the MediaPlayer?

Tags:

android

I haave my own Custom Adapter Class called WordAdapter, and I am using a Media Player(named pronounce-global variable in the WordAdapter class). I have different activities in which each list item has a linear layout(named as linearLayout). I am setting onClickListener to it so that when the Linear Layout is clicked, a sound file is played. On completion of playing that sound, I want to free off any unwanted memory. But I do not know if I should use release() or reset(). I have checked previous questions asked on SO before, but I don't think it provides precise explanation for my situation so as to use which method.

NOTE: I should be able to play other audio files after this one too (After completing playing this audio file, when I click on other items in the same activity, I should be able to get the sound.)

    linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pronounce = MediaPlayer.create(context, currentWord.getPronounceResourceID());
            pronounce.start();
            pronounce.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer player) {
                    //pronounce.release();
                    //pronounce.reset();
                }
            });
        }
    });
like image 885
Siddharth Venu Avatar asked Aug 07 '16 07:08

Siddharth Venu


1 Answers

Do a reset before a release, but I suspect that only release is needed.

This might be easier to manage:

    public void onClick(View view) {
        if (pronounce != null) {
            pronounce.reset();
            pronounce.release();
            pronounce = null;
        }
        pronounce = MediaPlayer.create(context, currentWord.getPronounceResourceID());
        pronounce.start();
   }

The reset method will simply stop any media and send the MediaPlayer instance back to the idle state. Exactly in the same state when it was created.

The release method destroys the media player and frees the majority of the unmanaged resources. When you call release, you should set the instance variable to null so that the remainder of the object is a candidate for garbage collection.

You might have some better performance if you just use reset and then reuse the existing mediaplayer instance on subsequent clicks.

like image 177
selbie Avatar answered Nov 03 '22 23:11

selbie