Page 1 of 1

Can I set a different balance for each sound effect?

Posted: Sat Feb 25, 2012 10:05 am
by molul
I'd like to set the balance for my sound effects independently in real time, depending on the position of the item/character/event. For instance, if the player is closer to the left of the screen and he jumps, I'd like the sound to be hear louder on left speaker than on right speaker.

I saw the love.audio.setPosition() function, but I think it affects all the audio that is currently playing, not just one file. I wonder, can I do something like in love.graphics.setColor()? Like:

love.audio.setPosition(0, 50, 1)
playSfx (mySfx) -- mySfx plays in that position
love.audio.setPosition(<center of the screen>) -- mySfx is not affected but the rest of the sounds from now are

Re: Can I set a different balance for each sound effect?

Posted: Sat Feb 25, 2012 11:14 am
by nevon
You should be able to set the position of indivudual sources: https://love2d.org/wiki/Source:setPosition

Re: Can I set a different balance for each sound effect?

Posted: Sat Feb 25, 2012 12:34 pm
by molul
Oh, I missed that. Thanks, it works exactly as I wanted. I'll post my code, as it might be useful to other users.

First, in my "game.lua" class I wrote this function (but you can put it in your main.lua or anywhere and just call it whatever you prefer):

Code: Select all

--********************************************************
-- game:playSfx
-- "pos" is the item/character/event position
--********************************************************
function game:playSfx(sfx, pos)
	local sfxPosX = -1 + (2* (pos - camera._x) / gScreenWidth) -- calculate the sound position depending on the distance to the camera
	stopAndPlaySfx (sfx, sfxPosX)
end
Then I have this other function, called by game:playSfx():

Code: Select all

--********************************************************
-- stopAndPlaySfx
--********************************************************
function stopAndPlaySfx(sfx, sfxPos)
	if (not sfx:isStopped( )) then sfx:stop() end

	sfxPos = sfxPos or 0 -- if you call this function like "stopAndPlaySfx(mySfx), position is set to zero
	sfx:setPosition (sfxPos, 0, 0)

	love.audio.play(sfx)
end
And to use it, write a function like this in each element or character class:

Code: Select all

--********************************************************
-- player:playSfx
--********************************************************
function player:playSfx(sfx)
	game:playSfx(sfx, player.x)
end
There needs to be a few things in the game for it to work (a camera class and some global variables), but if anybody found this and had problems, I could help :)