Python - Pygame - Get if specific sound is playing

2019-02-25 19:28发布

问题:

Pygame's mixer module has pygame.mixer.get_busy which returns a simple boolean.
My problem is that I have sound playing constantly, like explosions and gunshots, and need to know when a specific sound is playing to prevent game dialogue from overlapping.

I considered making a list of currently playing dialogue, creating a timer that counts down as each sound is triggered,but that would require me to add an sound Effects (my module that handles sounds) update in the main game loop.
This seems messy, and like a giant slowdown.

Is there a cleaner way to do this?

回答1:

You can use the channel object.

Play a specific type of audio in a channel and check to see if the sound is playing.

import pygame

def main(filepath):
    pygame.mixer.init()

    # If you want more channels, change 8 to a desired number. 8 is the default number of channel

    pygame.mixer.set_num_channels(8)

    # This is the sound channel
    voice = pygame.mixer.Channel(5)

    sound = pygame.mixer.Sound(filepath)

    voice.play(sound)

    if voice.get_busy():
        #Do Something