gpt4 book ai didi

python - 声音不会一直播放! - Pygame,Python

转载 作者:行者123 更新时间:2023-12-03 01:31:07 25 4
gpt4 key购买 nike

我正在尝试在 Python 中使用 Pygame 库来播放一些钢琴声音。我有 .wav 格式的音符,我想使用 while 循环持续播放一些音符,但结果与我不同。

我真的尝试了一些其他可能的解决方案,但我没有找到任何解决我的问题的方法。我希望这三个音符(声音)同时播放并每 0.4 秒重复一次。

c4.wav : https://gofile.io/?c=F3U1LG

e4.wav : https://gofile.io/?c=4KflZ9

a4.wav : https://gofile.io/?c=mtNXWd

import pygame
import time
pygame.init()

c4 = pygame.mixer.Sound("c4.wav")
e4 = pygame.mixer.Sound("e4.wav")
a4 = pygame.mixer.Sound("a4.wav")

while True:
c4.play()
e4.play()
a4.play()
time.sleep(0.4)

最佳答案

来自 pygame.mixer.Sound.play() documentation :

Begin playback of the Sound (i.e., on the computer's speakers) on an available Channel. This will forcibly select a Channel, so playback may cut off a currently playing sound if necessary.



所以你需要等待声音完成播放(或使用多个 channel 同时发出声音)

也许是这样的:
def playAndWait( sound ):
""" Play a sound, wait for it to finish """
sound.play() # play the sound
time.sleep( sound.get_length() ) # wait for sound to end

# Quickly confirm sound has stopped, should not loop (much).
# (This is probably unnecessary)
while ( pygame.mixer.get_busy() ):
time.sleep( 0.1 )

while True:
playAndWait( c4 )
playAndWait( e4 )
playAndWait( a4 )
time.sleep( 0.4 )

不理想使用 time.sleep()在 pygame 中,因为它减慢/破坏了事件处理。所以在实践中,需要使用其他一些等待延迟计时的方法。

关于python - 声音不会一直播放! - Pygame,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57898529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com