Page 1 of 1

Newbie question: Audio

Posted: Thu Mar 20, 2014 4:10 pm
by orangeroo
Hi,

I'm new to love and lua and am trying to create a simple program that registers a key press and plays a sound immediately when a key is pressed. However, I've noticed that after the first time I press a key and the sound plays, I have to wait a short duration before pressing again and hearing the sound. If I press the key too early after the first time, the sound will only play once and not twice. Any input/suggestions would be helpful. Cheers!

My Code:

Code: Select all

function love.load()
	kicksrc = love.audio.newSource("kick.wav", "static")
	kicksrc:setLooping(false) 
end

function love.update()
	--onKeyPressPlayAudio("d", kicksrc)
end


function love.draw()
	onKeyDraw( "d", "d", "D", 50, 50 )

end

function onKeyDraw(keypress, textDefault, textPressed, x, y)
	if love.keyboard.isDown(keypress) then
		love.graphics.print(textPressed, x, y) 
	else
		love.graphics.print(textDefault, x, y) 
	end

end


function love.keypressed(key)
	if key == "escape" then
		love.event.quit()		
	end
	if key == 'd' then
		love.audio.play(kicksrc)    
	end	
end

Re: Newbie question: Audio

Posted: Thu Mar 20, 2014 4:53 pm
by Robin
Welcome!

A Source isn't so much a "sound" object as it is a "sound production" object. A musical instrument, sort of. If you have a trumpet and I ask you to play a melody, you can play it. But if I ask you to start playing that melody at the same time, you can't do that. So I'd need another person with a trumpet, and ask them to play the melody.

With Sources you need a similar approach.

You could use a user library that handles that automatically, but I'm not very familiar with those.

Another thing you can do is keep track of them yourself:

Code: Select all

function newkicksource()
	local kicksrc = love.audio.newSource("kick.wav", "static")
	kicksrc:setLooping(false) 
	return kicksrc
end

function love.load()
	paused_sources = {}
	playing_sources = {}
end

function love.update()
	for i = #playing_sources, 1, -1 do
		if playing_sources[i]:isStopped() then
			table.insert(paused_sources, table.remove(playing_sources, i))
		end
	end
end

function love.keypressed(key)
	if key == "escape" then
		love.event.quit()		
	end
	if key == 'd' then
		local kicksrc
		if #paused_sources == 0 then
			kicksrc = newkicksource()
		else
			kicksrc = table.remove(paused_sources)
		end
		love.audio.play(kicksrc)    
		table.insert(playing_sources, kicksrc)
	end	
end
Warning: untested.

Re: Newbie question: Audio

Posted: Thu Mar 20, 2014 6:39 pm
by orangeroo
Hi Robin,

Thanks for the really quick reply, that works! I'm still a little slow in understanding how it works though, but I'll take a closer look at it later when it's not an unearthly hour in the day (it's 2am woots). Thanks again!

Re: Newbie question: Audio

Posted: Sat Mar 22, 2014 7:42 am
by shatterblast
You might consider Slam:

http://www.love2d.org/wiki/SLAM