MediaPlayer 暂停再播放的 IllegalStateException 问题

前两天写项目的时候有一个播放背景音乐的功能,使用 MediaPlayer 的时候,进行 暂停-> 重置-> 播放 流程时总是莫名其妙的抛出异常。

这里记录一下解决问题的代码:

private var mediaPlayer: MediaPlayer? = null

    /**
     * 开始播放
     */
    private fun playMedia() {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(this, R.raw.catch_bg)
        }
        // 为解决第二次播放时抛出的IllegalStateException,这里做了try-catch处理
        var isPlaying = false
        try {
            isPlaying = mediaPlayer!!.isPlaying();
        } catch (e: IllegalStateException) {
            mediaPlayer = null;
            mediaPlayer = MediaPlayer.create(this, R.raw.catch_bg)
        }

        if (isPlaying) {
            mediaPlayer!!.stop()
            mediaPlayer!!.release()
            mediaPlayer = null
            mediaPlayer = MediaPlayer.create(this, R.raw.catch_bg)
        }
        try {
            // Prepare to async playing
            mediaPlayer?.setOnPreparedListener {
                mediaPlayer?.start()
            }
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } catch (e: SecurityException) {
            e.printStackTrace()
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

最终在界面销毁时,进行资源释放:

private fun resetMedia() {
        try {
            if (mediaPlayer != null && mediaPlayer!!.isPlaying) {
                mediaPlayer!!.stop()
                mediaPlayer!!.release()
                mediaPlayer == null
            }
        } catch (e: Exception) {
        }
    }

解决方式来源于:http://lovelease.iteye.com/blog/2105616 (文中后续更新的方式测试不成功。)

你可能感兴趣的:(Android,mediaplayer,异常)