Views
Minimalist Sound Manager
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
-- 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
-- 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