【问题标题】:Playing sound using pygame (python)使用 pygame (python) 播放声音
【发布时间】:2020-08-18 04:16:49
【问题描述】:

截至目前,我有一个程序可以根据特定按键播放单个声音。每次按键都会根据按下的键成功播放正确的声音,但是当来自不同键的下一个声音开始播放时,声音会被切断。我想知道如何让我的程序完整地播放每个键的声音,即使按下另一个键并开始播放新的声音(我希望这些声音同时播放)。我正在使用 pygame 和键盘库。

这是我用来播放按键声音的功能:

# 'keys' refers to a dictionary that has the key press strings and sound file names stored as key-value pairs.
key = keyboard.read_key() 
def sound(key):
    play = keys.get(key, 'sounds/c2.mp3')
    pygame.mixer.init()
    pygame.mixer.music.load(play)
    pygame.mixer.music.play()

如果您需要更多上下文,请告诉我,我会更新我的问题。

【问题讨论】:

    标签: python pygame playback


    【解决方案1】:

    在 pygame 中,您可以使用通道同时播放多个音轨。请注意,频道仅支持 wav 或 ogg 文件。

    这里是一些示例代码。按 1-3 键开始曲目。您也可以多次启动同一曲目。

    import pygame
    
    lst = [
    'Before The Brave - Free.wav',   # key 1
    'Imagine Dragons - Demons.wav',  # key 2
    'Shinedown-How Did You Love.wav' # key 3
    ]
    
    pygame.init()
    size = (250, 250)
    screen = pygame.display.set_mode(size)
    
    pygame.mixer.init()
    print("channel cnt",pygame.mixer.get_num_channels()) # max track count (8 on my machine)
    
    while True: 
        pygame.time.Clock().tick(10) 
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                exit()
        idx = 0
        keys = pygame.key.get_pressed()
        if keys[pygame.K_1]: idx = 1
        if keys[pygame.K_2]: idx = 2
        if keys[pygame.K_3]: idx = 3
        if (idx):
           ch = pygame.mixer.find_channel() # find open channel, returns None if all channels used
           snd = pygame.mixer.Sound(lst[idx-1])  # create sound object, must be wav or ogg
           if (ch): ch.play(snd)  # play on channel if available
    

    【讨论】:

    • 我使用了你的一些代码,效果很好。唯一的问题是我需要八个以上的频道。我将如何增加可用频道的数量?如果我不能,有什么方法可以让程序在返回“none”后保持运行,还是我必须找到一种方法来清除频道以便始终有 1 个可用频道?
    • 答案已更新以检查无。如果通道已满,而您想要另一种声音,则需要停止其中一个通道并替换声音文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多