How to Play Music in Python without Blocking the Main Thread

One of my students today at theCoderSchool was interested in writing a Python program that featured music. However, we quickly ran into a problem of blocking the main thread. But thanks to the threading library, we were easily able to play the music on it’s own thread and get back to coding her program:


from playsound import playsound
from threading import Thread

def play_music():
    playsound('wooboost.mp3')

# Play Music on Separate Thread (in background)
music_thread = Thread(target=play_music)
music_thread.start()

print("Does playsound block the main thread?")
user_input = input("What is your guess?: ")
print("You guessed: " + user_input)

 

topherPedersen