使用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

最新更新