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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
pdm LVW
  • 149
  • 1
  • 11

3 Answers3

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.

Forlanda
  • 81
  • 1
  • 3
5

Use threading library :

from threading import Thread
T = Thread(target=playy) # create thread
T.start() # Launch created thread
Calvin-Ruiz
  • 173
  • 1
  • 1
  • 9
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()

Dinari
  • 2,487
  • 13
  • 28
  • 1
    You don't want to call the `run()` method directly. That gets called by the `start()`. For example see [here](https://docs.python.org/3.5/library/multiprocessing.html#the-process-class). – Paul Nov 20 '18 at 13:56
  • Your right. it was not in my original answer, it was edited in there. removed it. – Dinari Nov 20 '18 at 14:07
  • 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. – Calvin-Ruiz May 17 '20 at 09:38
  • for me terminate doesn't stop it from running, I have to end it from system monitor – Yuval Harpaz Jan 08 '23 at 10:11