Python - Pygame - Get if specific sound is playing

一世执手 提交于 2019-12-20 03:56:07

问题


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


来源:https://stackoverflow.com/questions/14432851/python-pygame-get-if-specific-sound-is-playing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!