pythonpython-playsound

Cannot terminate `playsound`-process in python, sound keeps playing


I want to play a sound file for a certain period of time and stop playing it after this time period. I used the playsound function of the playsound python module. I created a process with playsound as target (module multiprocessing) in order to be able to terminate this process. Starting the process works fine, sound begins to play. But if I wait e.g. 5 seconds with time.sleep(5) and terminate the process, the sound keeps playing. Here is my code:

import multiprocessing
from playsound import playsound
import time


if __name__ == "__main__":
    p = multiprocessing.Process(target=playsound, args=('my_soundfile.mp3',))
    p.start()
    time.sleep(5)
    p.terminate()

So if I run this code, the sound file starts to play, but it does not stop playing after 5 seconds. The sleep time period does not matter, same problem with other values. If I terminate the process immediately after starting it

p.start()
p.terminate()

the sound file does not start playing, I assume because terminating the process works as intended. But if I do something (e.g. waiting a period of time with time.sleep()) in between, the sound file keeps playing.

I have the idea of using multiprocessing in order to stop the sound file from playing from this post: How to stop audio with playsound module? (I wanted to ask my question as a comment in this post, but I need a reputation of 50 for that...)

I know there are other ways to play a sound file in python, but I want to know why terminating this process does not stop the sound file from playing.

I'm using Ubuntu 22.04 and Python 3.10.6


Solution

  • As I want to mark this question as solved, here is the summary so far: