BackgroundMusicPlayer.kt 1.15 KB
Newer Older
楊慶堂's avatar
楊慶堂 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
package io.github.apollozhu.lottery.utils

import io.github.apollozhu.lottery.settings.LotteryPreferences
import javafx.application.Platform
import javafx.embed.swing.JFXPanel
import javafx.scene.media.Media
import javafx.scene.media.MediaPlayer
import java.io.File

object BackgroundMusicPlayer {
    // IMPORTANT: Magic, Do NOT Touch
    val panel = JFXPanel()
    // END-IMPORTANT

    init {
        LotteryPreferences.addListener { play() }
        play()
    }

    var currentPlayer: MediaPlayer? = null

    fun stop() {
        currentPlayer?.stop()
    }

    private var currentPath = ""

    fun play(path: String = LotteryPreferences.backgroundMusicPath) {
        Platform.runLater {
            if (path != currentPath) {
                currentPath = path
                try {
                    val media = Media(File(path).toURI().toString())
                    val player = MediaPlayer(media)
                    player.cycleCount = MediaPlayer.INDEFINITE
                    player.play()
                    stop()
                    currentPlayer = player
                } catch (_: Exception) {
                }
            }
        }

    }
}