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

Question:

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

Asked By: DerGrillerich

||

Answers:

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

  • As @jasonharper suggested, the problem here is that playsound() launches another program that plays the sound, terminating the original process won’t have any effect on this new process.
  • Possible solutions for this problem are (from the comments of @nigh_anxiety and @jasonharper):
    • use something else like pyaudio (which I did, works fine) or pygame
    • Shorten the original soundfile to the length I want it to play (that would work, but too much effort…)
Answered By: DerGrillerich
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.