使用pygame播放声音python

问题描述

截至目前,我有一个程序可以根据某些按键来播放各个声音。每次按键成功都会根据所按下的按键播放正确的声音,但是当另一个按键发出的下一个声音开始播放时,声音会被切断。我想知道如何让我的程序完整地播放每个键的声音,即使按下另一个键并开始播放新声音时(我希望声音同时播放)。我正在使用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()

如果您需要更多背景信息,请告诉我,我会更新我的问题。

解决方法

在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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...