The Python Oracle

Python execute playsound in separate thread

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle

--

Chapters
00:00 Question
00:32 Accepted answer (Score 4)
00:46 Answer 2 (Score 6)
01:08 Answer 3 (Score 2)
01:33 Thank you

--

Full question
https://stackoverflow.com/questions/5324...

Answer 2 links:
[more on this here]: https://realpython.com/python-gil/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #multithreading #pythonplaysound

#avk47



ANSWER 1

Score 8


You may not have to worry about using a thread. You can simply call playsound as follows:

def playy():  
    playsound('beep.mp3', block = False)

This will allow the program to keep running without waiting for the sound play to finish.




ACCEPTED ANSWER

Score 5


Use threading library :

from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread



ANSWER 3

Score 2


As python multi-threading is not really multi-threading (more on this here), I would suggest using a multi-process for it:

from multiprocessing import Process

def playy():
    playsound('beep.mp3')


P = Process(name="playsound",target=playy)
P.start() # Inititialize Process

can be terminated at will with P.terminate()




ANSWER 4

Score 0


If you don't want to get confused by threading stuff Nava could be a better option for you. You can just do

from nava import play
play("beep.wav", async_mode=True)

Up until now it supports mp3 only for MacOS (but supports wav for other OSs). You can always convert your mp3 to wav.