1

我决定使用playsound()在我的程序中添加背景声音。但是,当我使用 playsound 运行程序时,实际游戏在歌曲完成之前不会加载:

from playsound import playsound
#type 'pip install playsound' in command prompt to install library
import random

playsound('audio.mp3')

while True:
    min = 1
    max = 6
    roll_again = "yes"
    while roll_again == "yes" or roll_again == "y":
        print("Rolling the dices...")
        print("The values are....")
        print(random.randint(min, max))
        print(random.randint(min, max))
        roll_again = raw_input("Roll the dices again?")

通常我希望在加载和播放骰子游戏时在后台播放声音,但它不是这样工作的。

4

1 回答 1

1

从模块的文档playsound

有一个可选的第二个参数,默认block设置为True。将其设置为False使函数异步运行。

因此,如果您希望它在后台运行一次,您需要使用:

playsound('audio.mp3', block=False)

...或者,如果您希望它在后台重复运行,等到一个实例完成后再开始下一个实例,您可以为此目的启动一个线程:

import threading
from playsound import playsound

def loopSound():
    while True:
        playsound('audio.mp3', block=True)

# providing a name for the thread improves usefulness of error messages.
loopThread = threading.Thread(target=loopSound, name='backgroundMusicThread')
loopThread.daemon = True # shut down music thread when the rest of the program exits
loopThread.start()

while True:
    raw_input("Put your gameplay loop here.")
于 2019-01-05T18:45:15.783 回答