Like2D Logo Like2D
← Back to Docs

Audio

Full audio playback system using a key-based approach. Load sounds once, then play/stop/pause them using their key. Supported formats: WAV, MP3, OGG. Multiple sounds can play simultaneously.

Loading & Unloading

loadSound(key, filename)

Loads a sound file into memory. The key is a unique string identifier used for all subsequent operations.

Parameters:

Returns: success (boolean)

loadSound("jump", "assets/jump.wav")
loadSound("bgm", "assets/theme.mp3")
loadSound("explosion", "assets/boom.ogg")

unloadSound(key)

Frees the sound from memory. Always call this in onCleanup() or when a sound is no longer needed to prevent memory leaks.

Playback Control

playSound(key, loop)

Plays a previously loaded sound. Set loop to true for infinite looping (background music) or false for one-shot playback (sound effects).

Parameters:

playSound("bgm", true)    -- Looping background music
playSound("jump", false)  -- One-shot jump SFX

stopSound(key)

Stops playback and resets the sound position to the beginning.

pauseSound(key)

Pauses the sound at its current position. Use resumeSound() to continue.

resumeSound(key)

Resumes a paused sound from where it was paused.

isSoundPlaying(key)

Returns true if the sound is currently playing (not paused or stopped).

Returns: playing (boolean)

Volume & Pitch

setSoundVolume(key, volume)

Sets the volume for a specific sound.

Parameters:

setMasterVolume(volume)

Sets the global volume for all sounds simultaneously.

Parameters:

setSoundPitch(key, pitch)

Changes playback speed and pitch. 1.0 = normal, 2.0 = double speed/pitch, 0.5 = half speed/pitch.

Complete Example

-- Complete audio management example
function onInit()
    loadSound("bgm", "assets/music.mp3")
    loadSound("coin", "assets/coin.wav")
    loadSound("hurt", "assets/hurt.wav")
    playSound("bgm", true)
end

function onUpdate(dt)
    -- Toggle music with M key
    if isKeyJustPressed("m") then
        if isSoundPlaying("bgm") then
            pauseSound("bgm")
        else
            resumeSound("bgm")
        end
    end
    -- Volume controls
    if isKeyDown("Up") then
        setMasterVolume(math.min(1.0, currentVol + dt))
    end
    -- Play SFX
    if isKeyJustPressed("Space") then
        playSound("coin", false)
    end
end

function onCleanup()
    stopSound("bgm")
    unloadSound("bgm")
    unloadSound("coin")
    unloadSound("hurt")
end