每当我使用“ playsound”在后台播放声音时,游戏的其余部分均不会加载

时间:2019-01-05 16:33:39

标签: python playsound

所以我决定实现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?")

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

1 个答案:

答案 0 :(得分:0)

摘自the playsound module的文档:

  

第二个可选参数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.")