2

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Forgiven1
  • 21
  • 1
  • 3
  • `playsound` isn't part of Python itself. Which library is it from? Add that library to your question's tags. And cut the code down to a [mcve] -- the *shortest possible code* that produces the problem you're asking about when run without changes. Including a MCVE that lets people reproduce the problem also ensures that folks can test their answers, and validate the correctness of answers others propose. See also the [SSCCE](http://sscce.org/) definition, which is closely related (albeit not itself part of Stack Overflow's rules). – Charles Duffy Jan 05 '19 at 17:48
  • 1
    (Right now your code doesn't run without changes *at all* -- only a single function is provided with nothing calling it, no `import`s, etc). – Charles Duffy Jan 05 '19 at 17:49
  • 1
    Okay I've done it, hope it helps with finding a solution. – Forgiven1 Jan 05 '19 at 18:41
  • Yup, that helps a great deal. – Charles Duffy Jan 05 '19 at 18:45

1 Answers1

4

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.")
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441