简体   繁体   English

Android “stop()”与“release()”的 MediaPlayer 使用差异

[英]Android MediaPlayer Usage Difference of "stop()" vs "release()"

I am learning how to play audio using MediaPlayer from this tutorial , which suggests using release() instead of stop() to STOP the audio.我正在学习如何使用本教程中的MediaPlayer播放音频,它建议使用release()而不是stop()停止音频。 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() ?他的解释对我来说很有意义( free up the system resource as soon as you don't need it )并且从用户的角度来看它按预期工作,但我仍然觉得使用stop()有什么意义有点奇怪? ( https://stackoverflow.com/a/20580149/3466808 ) 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)?还是仅在屏幕不再可见时才释放(调用onStop() )?

take a look at the diagram in DOCS看一下DOCS中的图表

MediaPlayer after release() is not "usable" anymore, you can null ify it safely. release()后的MediaPlayer不再“可用”,您可以null安全地确认它。 after onStop you still can call eg prepareAsync() and start playing again using single instanceonStop之后,您仍然可以调用例如prepareAsync()并使用单个实例再次开始播放

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM