Skip to content

Music and sound

Perses Games edited this page Apr 26, 2017 · 1 revision

Music

To play music simple do:

  var audio: HTMLAudioElement = Music.play("music/<music file>.mp3", volume, looping = true)

To stop the music playing use the pause method:

  audio.pause()

To remove the audio element use dispose:

  audio.dispose()

Sound

To load a sound:

  Sounds.load("FIRE", "sounds/fire.mp3", volume, channels)

The number of channels is the number of times this sound can be played simultaneously.

To play a sound:

  Sounds.play("FIRE", <optional>volume)

Usage example with an enum:

enum class GameSounds(val file: String, val defaultVolume: Double, val channels: Int) {
    LASER1("sounds/sfx_laser1.mp3", 1.0, 1),
    LASER2("sounds/sfx_laser2.mp3", 1.0, 1),
    ;

    fun play(volume: Double? = null) {
        Sounds.play(name, volume)
    }

    fun pause() {
        Sounds.pause(name)
    }

    companion object {
        fun loadAll() {
            for (sound in GameSounds.values()) {
                Sounds.load(sound.name, sound.file, sound.defaultVolume, sound.channels)
            }
        }

        fun disposeAll() {
            for (sound in GameSounds.values()) {
                Sounds.dispose(sound.name)
            }
        }
    }

}

Then to use it (make sure the sounds are loaded with GameSounds.loadAll()) you can simply do:

  GameSounds.LASER1.play()
Clone this wiki locally