Pygame mixer only plays one sound at a time

2019-05-20 19:31发布

问题:

Here is my code:

pygame.mixer.init(frequency=22050,size=-16,channels=4)
sound1 = pygame.mixer.Sound('sound1.wav')
sound2 = pygame.mixer.Sound('sound2.wav')
chan1 = pygame.mixer.find_channel()
chan2 = pygame.mixer.find_channel()
chan1.queue(sound1)
chan2.queue(sound2)
time.sleep(10)

I would think it would play sound1 and sound2 simultaneously (queue is non-blocking and the code immediately hits the sleep).
Instead, it plays sound1 and then plays sound2 when sound1 is finished.

I've confirmed both channels are distinct objects in memory so find_channel isn't returning the same channel. Is there something I'm missing or does pygame not handle this?

回答1:

The only thing i can think of is that chan1 and chan2 are same, even though they are different objects, they can be pointing to the same channel.

Try queueing right after getting a channel, that way you are sure to get a different channel with find_channel(), since find_channel() always returns a non-busy channel.

Try this:

pygame.mixer.init(frequency=22050,size=-16,channels=4)
sound1 = pygame.mixer.Sound('sound1.wav')
sound2 = pygame.mixer.Sound('sound2.wav')
chan1 = pygame.mixer.find_channel()
chan1.queue(sound1)
chan2 = pygame.mixer.find_channel()
chan2.queue(sound2)
time.sleep(10)


回答2:

See Pygame Docs, It says:

Channel.queue - queue a Sound object to follow the current

So, even though your tracks are playing on different channels, so if you force each sound to play, they will play simultaneously.

And for playing multiple sounds:

  • Open all sound files, and add the mixer.Sound object to a list.
  • The loop through the list, and start all the sounds.. using sound.play

This forces all the sounds to play simultaneously.
Also, make sure that you have enough empty channels to play all sounds, or else, some or the other sound sound will be interrupted.
So in code:

sound_files = [...] # your files
sounds = [pygame.mixer.Sound(f) for f in sound_files]
for s in sounds:
    s.play()

You could also create a new Channel or use find_channel() for each sound..

sound_files = [...] # your files
sounds = [pygame.mixer.Sound(f) for f in sound_files]
for s in sounds:
    pygame.mixer.find_channel().play(s)


标签: python pygame