Pygame mixer only plays one sound at a time

2019-05-20 18:48发布

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?

标签: python pygame
2条回答
疯言疯语
2楼-- · 2019-05-20 19:11

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)
查看更多
倾城 Initia
3楼-- · 2019-05-20 19:28

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)
查看更多
登录 后发表回答