Untitled

mail@pastecode.io avatar
unknown
plain_text
9 days ago
1.1 kB
1
Indexable
Never
object MediaPlayerManager {
    private var mediaPlayer: MediaPlayer? = null
    private var currentResId: Int? = null

    fun playMusic(context: Context, resId: Int) {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(context, resId)
            mediaPlayer?.isLooping = true
            mediaPlayer?.start()
            currentResId = resId
        } else {
            if (currentResId != resId) {
                stopMusic()
                mediaPlayer = MediaPlayer.create(context, resId)
                mediaPlayer?.isLooping = true
                mediaPlayer?.start()
                currentResId = resId
            }
        }
    }

    fun stopMusic() {
        mediaPlayer?.let {
            if (it.isPlaying) {
                it.stop()
                it.reset()
                it.release()
                mediaPlayer = null
                currentResId = null
            }
        }
    }

    fun isPlaying(resId: Int): Boolean {
        return mediaPlayer?.isPlaying == true && currentResId == resId
    }
}
Leave a Comment