How to Play Music in Python without Blocking the Main Thread

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

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