You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.7 KiB
Kotlin
63 lines
1.7 KiB
Kotlin
package com.last.commit.audio
|
|
|
|
import com.badlogic.gdx.Gdx
|
|
import com.badlogic.gdx.audio.Music
|
|
import com.badlogic.gdx.audio.Sound
|
|
|
|
public class SoundEngine {
|
|
|
|
private val sounds: ThreadLocal<HashMap<String, Sound>> =
|
|
ThreadLocal.withInitial() { HashMap() }
|
|
private val musicTracks: ThreadLocal<HashMap<String, Music>> =
|
|
ThreadLocal.withInitial() { HashMap() }
|
|
|
|
lateinit var backgroundMusic: Music
|
|
|
|
fun play(gameSound: GameSound, volume: Float = 1f) {
|
|
if (gameSound is GameSoundEffect) {
|
|
val sound = loadEffect(gameSound.name)
|
|
sound.play(volume)
|
|
} else if (gameSound is GameMusic) {
|
|
backgroundMusic = loadMusic(gameSound.name)
|
|
backgroundMusic.volume = volume
|
|
backgroundMusic.setLooping(true)
|
|
backgroundMusic.play()
|
|
}
|
|
}
|
|
|
|
fun stop() {
|
|
backgroundMusic.pause()
|
|
}
|
|
|
|
fun resume() {
|
|
backgroundMusic.play()
|
|
}
|
|
|
|
private fun loadEffect(name: String): Sound {
|
|
return loadSound("effects/$name")
|
|
}
|
|
|
|
private fun loadMusic(name: String): Music {
|
|
var music = musicTracks.get().get(name)
|
|
|
|
if (music == null) {
|
|
println("Loading sound $name")
|
|
music = Gdx.audio.newMusic(Gdx.files.internal("sounds/music/$name"))
|
|
musicTracks.get()[name] = music
|
|
}
|
|
return music!!
|
|
}
|
|
|
|
private fun loadSound(name: String): Sound {
|
|
var sound = sounds.get().get(name)
|
|
|
|
if (sound == null) {
|
|
println("Loading sound $name")
|
|
sound = Gdx.audio.newSound(Gdx.files.internal("sounds/$name"))
|
|
sounds.get()[name] = sound
|
|
}
|
|
|
|
return sound!!
|
|
}
|
|
}
|