Pygame's sound handling is kinda minimalist, so figuring out how to organize them can be a bit of a chore.
You should be able to write a small number of functions to simplify most of the work. For example, instead of having to create a sound, get the channel from playing it, and adjust the left and right levels every time, you might try something like:
(It gets a little weird toward the end; I'll explain afterward)
def play2d(filename, listenerX=0, listenerY=0, soundX=0, soundY=0) :
toplay=pygame.mixer.Sound(filename)
channel=toplay.play()
position_sound2d(channel, listenerX, listenerY, soundX, soundY)
return channel
def position_sound2d(channel, listenerX, listenerY, soundX, soundY) :
x=soundX-listenerX
y=soundY-listenerY
volume=-abs(y)-abs(x)
vl, vr=convert(x, volume)
channel.set_volume(vl, vr)
def convert(pan=0.0, volume=0.0):
v = ((volume+50.0)/50.0)
if v<0.0 :
v=0.0
elif v>1.0 :
v=1.0
pan/=10.0
if pan<-1.0 :
pan=-1.0
elif pan>1.0 :
pan=1.0
vl = v if pan<=0.0 else v*(1.0-pan)
vr = v if pan>=0.0 else v*(1.0+pan)
return (vl, vr)
The first function plays the sound, positions it, and returns the channel that it's playing on, in case you want to move it later. If you don't specify the position, the sound will be centered.
The second function handles positioning. You shouldn't need to call it unless you're moving a sound, since play2d already handles that part.
The third function converts the more (x, y)-style positioning into percentages for the left and right channels. You shouldn't need to use this directly; I included it because it made things easier for me. (The indentation is a bit shallow; if that needs to be fixed, I'll change it here).
There are a couple syntactical things in there that might be hard to follow, particularly that part at the end that sets vl and vr. It's not something you will necessarily need, but it's a convenient way to choose one of two values for a variable in one line. (It might be easier to follow were there a comma before the else part, but I don't think that would be legal.)
Also, while I copied convert from another project, I wrote play2d and position_sound2d just now. Hopefully, there aren't any errors, but I hope they're easy enough to understand regardless.
If you're wondering if there's a way to attach sounds to specific events, the answer is "Yes, but the best way would depend on how the rest of your game is organized".
看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
George... Don't do that.