Difference between revisions of "Minimalist Sound Manager"

(Created page with "A minimalist sound manager to make playing sounds easier without adding a whole library: <source lang='lua'> do -- will hold the currently playing sources local sources ...")
 
 
(2 intermediate revisions by 2 users not shown)
Line 67: Line 67:
 
end
 
end
 
</source>
 
</source>
 
+
== Other languages ==
 +
{{i18n|Minimalist Sound Manager}}
 
[[Category:Snippets]]
 
[[Category:Snippets]]
 +
{{#set:LOVE Version=any}}
 +
{{#set:Description=Code that manages your audio Source objects for you.}}

Latest revision as of 21:04, 23 May 2024

A minimalist sound manager to make playing sounds easier without adding a whole library:

do
    -- will hold the currently playing sources
    local sources = {}

    -- check for sources that finished playing and remove them
    -- add to love.update
    function love.audio.update()
        local remove = {}
        for _,s in pairs(sources) do
            if s:isStopped() then
                remove[#remove + 1] = s
            end
        end

        for i,s in ipairs(remove) do
            sources[s] = nil
        end
    end

    -- overwrite love.audio.play to create and register source if needed
    local play = love.audio.play
    function love.audio.play(what, how, loop)
        local src = what
        if type(what) ~= "userdata" or not what:typeOf("Source") then
            src = love.audio.newSource(what, how)
            src:setLooping(loop or false)
        end

        play(src)
        sources[src] = src
        return src
    end

    -- stops a source
    local stop = love.audio.stop
    function love.audio.stop(src)
        if not src then return end
        stop(src)
        sources[src] = nil
    end
end

Now you can play sound effects and background music without worrying about the actual source objects:

function love.load()
    -- you will still get a source handle if you need it
    bgm = love.audio.play("background-music.ogg", "stream", true) -- stream and loop background music
end

function love.update(dt)
    love.audio.update()
end

function love.keypressed(key)
    if key == 's' then
        love.audio.stop(bgm)
    elseif key == 'p' then
        love.audio.play(bgm) -- still streaming and looping
    else
        love.audio.play("explosion.ogg") -- play explosion sound once
    end
end

Other languages