繁体   English   中英

声音不会持续播放! -Pygame,Python

[英]Sound won't be played consistently! - Pygame, 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)

pygame.mixer.Sound.play()文档中

在可用频道上开始播放声音(即在计算机的扬声器上)。 这将强制选择一个频道,因此如果有必要,播放可能会切断当前播放的声音。

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

也许像:

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()是不理想的,因为它会减慢/中断事件处理。 因此,在实践中,将需要使用其他一些等待延迟计时方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM