Android MediaPlayer Usage Difference of "stop()" vs "release()"

148 Views Asked by At

I am learning how to play audio using MediaPlayer from this tutorial, which suggests using release() instead of stop() to STOP the audio. His explanation makes sense to me (free up the system resource as soon as you don't need it) and from a user perspective it works as expected, but I still feel like a bit weird that what's the point of using stop()? (https://stackoverflow.com/a/20580149/3466808)

fun stopPlayer1() = mediaPlayer?.stop()

fun stopPlayer2() {
    mediaPlayer?.release()

    mediaPlayer = null
}

So, which approach is better? Release as soon as user stops the audio? Or release only when the screen is no longer visible (onStop() called)?

1

There are 1 best solutions below

3
snachmsm On

take a look at the diagram in DOCS

MediaPlayer after release() is not "usable" anymore, you can nullify it safely. after onStop you still can call e.g. prepareAsync() and start playing again using single instance

edit: to comment

if (mMediaPlayer != null) {
        try {
            mMediaPlayer.stop();
        } catch (Exception ignored) {
        }

        try {
            mMediaPlayer.reset();
        } catch (Exception ignored) {
        }

        try {
            mMediaPlayer.release();
        } catch (Exception ignored) {
        }

        mMediaPlayer = null;
    }