Reputation: 21
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.
Upvotes: 2
Views: 7999
Reputation: 295403
From the documentation for the playsound
module:
There’s an optional second argument,
block
, which is set toTrue
by default. Setting it toFalse
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.")
Upvotes: 5