简体   繁体   中英

Whenever I use the "playsound" to play sound in the background the rest of my game does not load

I decided to use playsound() to add a background sound in my program. However when I run the program with playsound, the actual game does not load until the song is finished:

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?")

Usually I would expect the sound to play in the background while the dice game is loaded and being played, however it does not work like this.

From the documentation for the playsound module :

There's an optional second argument, block , which is set to True by default. Setting it to False makes the function run asynchronously.

Thus, if you want it to run once in the background, you need to use:

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

...or, if you want it to run repeatedly in the background, waiting until one instance finishes before starting the next, you might launch a thread for the purpose:

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.")

Hello I tried this but when I put block=False it just wouldnt play sound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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