Forgiven1
Forgiven1

Reputation: 21

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.

Upvotes: 2

Views: 7999

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

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

Upvotes: 5

Related Questions