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

2024-07-05 14:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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)

Tags: httpsioimport声音playpygamea4笔记
1条回答
网友
1楼 · 发布于 2024-07-05 14:31:43

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.

因此,您需要等待声音播放完毕(或使用多个频道同时播放声音)

可能是这样的:

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 )

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

相关问题 更多 >