Python execute playsound in separate thread
Asked Answered
T

4

8

I need to play a sound in my Python program so I used playsound module for that:

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

How can I modify this to run inside main method as a new thread? I need to run this method inside the main method if a condition is true. When it is false the thread needs to stop.

Teofilateosinte answered 11/11, 2018 at 8:13 Comment(0)
N
5

Use threading library :

from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
Newberry answered 11/11, 2018 at 8:19 Comment(0)
I
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.

Iconostasis answered 20/6, 2019 at 3:31 Comment(1)
Not supported yet on all platforms, e.g. not supported on LinuxPamphylia
N
5

Use threading library :

from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
Newberry answered 11/11, 2018 at 8:19 Comment(0)
S
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()

Sweetener answered 11/11, 2018 at 8:23 Comment(4)
You don't want to call the run() method directly. That gets called by the start(). For example see here.Curnin
Your right. it was not in my original answer, it was edited in there. removed it.Sweetener
I think it depends on the version of python you have and the operating system used. When I use start(), the function is initialized, but not executed.Newberry
for me terminate doesn't stop it from running, I have to end it from system monitorBrick
C
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.

Checked answered 20/4 at 0:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.