[英]why isn't pygame playing the audio files the correct amount of times?
对不起,如果我只是做了一些愚蠢的事情,我以前从未使用过 pygame。 我试图让 pygame 通过查看字符串并相应地播放声音来播放莫尔斯电码,尽管当我运行它时,它只播放短哔声 3 次和长哔声一次。 这是因为同时播放多个哔声吗? 有人可以帮忙,因为我对 pygame 没有任何经验。 这是我的代码:
from pygame import mixer
import os
import time
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
mixer.init()
l = ".... . .-.. ---"
h = list(l)
print(h)
def play(CURR_DIR, l):
for i in l:
if i == ".":
mixer.music.load(CURR_DIR + "\short beep.mp3")
mixer.music.set_volume(0.7)
mixer.music.play()
print(".")
elif i == "-":
mixer.music.load(CURR_DIR + "\long beep.mp3")
mixer.music.set_volume(0.7)
mixer.music.play()
print("-")
elif i == " ":
time.sleep(1)
print(" ")
play(CURR_DIR, l)
您必须等到音乐播放完pygame.mixer.music.get_busy()
。 例如:
import os
import pygame
CURR_DIR = os.path.dirname(os.path.realpath(__file__))
pygame.mixer.init()
clock = pygame.time.Clock()
l = ".... . .-.. ---"
i = 0
pause = False
pause_end = 0
run = True
while run:
clock.tick(100)
if pause:
if pygame.time.get_ticks() > pause_end:
pause = False
elif not pygame.mixer.music.get_busy():
if i < len(l):
if l[i] == ".":
pygame.mixer.music.load(CURR_DIR + "/short beep.mp3")
pygame.mixer.music.play(0)
print(".")
elif l[i] == "-":
pygame.mixer.music.load(CURR_DIR + "/long beep.mp3")
pygame.mixer.music.play(0)
print("_")
elif l[i] == " ":
pause_end = pygame.time.get_ticks() + 1000
pause = True
print(" ")
i += 1
else:
run = False
pygame.quit()
exit()
我想我找到了一个解决方案,可以解决您在另一个 SO 问题中尝试做的事情。 它需要 pygame.mixer.Channel 及其 set_endevent() function。
https://stackoverflow.com/a/61068408/11620108
在他们的例子中:
horn = pygame.mixer.Sound( 'car-horn2.ogg' ) # converted from MP3 to OGG
quack = pygame.mixer.Sound( 'duck-quack.ogg' )
ca_ching = pygame.mixer.Sound( 'cash-register.ogg' )
bark = pygame.mixer.Sound( 'dog-bark.ogg' )
ding = pygame.mixer.Sound( 'single-ding.ogg' )
gobble = pygame.mixer.Sound( 'turkey-gobble.ogg' )
您可以为每个声音分配一个变量。 对于暂停,您可以使用音量设置为 0 的长哔声。
例子:
morse_dot = pygame.mixer.Sound('short_beep.mp3')
morse_dash = pygame.mixer.Sound('long_beep.mp3')
morse_pause = pygame.mixer.Sound('long_beep.mp3')
morse_pause.set_volume(0)
然后,您可以通过变量名将莫尔斯电码字符串转换为相应声音的列表:
sound_list =[]
for c in morse_code:
if c == ".":
sound_list.append(morse_dot)
elif c == "-":
sound_list.append(morse_dash)
elif c == " ":
sound_list.append(morse_pause)
并使用其他 SO 答案中的建议进行播放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.