Why is there silence when using playsound in another Process in PyCharm on Windows and how can I fix it?

140 Views Asked by At

Playsound is unable to play audio in a separate process when launched from PyCharm, while being able to work properly when launched from the command line.

Trying to implement this solution leads to nothing being played despite p.is_alive() returning True.

This is the code I've tried.

import multiprocessing
from playsound import playsound

def use_playsound(audio_file):
    p = multiprocessing.Process(target=playsound, args=(audio_file,))
    p.start()
    print(p.is_alive())
    input("press ENTER to stop playback")
    p.terminate()


def main():
    use_playsound("test.mp3")


if __name__ == '__main__':
    main()

If I p.join() the process after starting it, then the sound plays successfully.

Adding block=False or block=True doesn't help.

Modifying the code so that the Process is started in main(), leaving only the playsound call in the use_playsound function does not help. Doing that then setting block=False or block=True does not help.

Raising a BaseException after p.start() makes the sound play. However when I let the program exit successfully after pressing Enter, the sound still does not play.

1

There are 1 best solutions below

7
On

When you launch from the command line compared to an editor and encounter this kind of problem, it is nearly always a path name issue.

This is because the python path may be different and the code has used a relative path, assuming that the file test.mp3 is in the same folder.

To avoid this error, use an absolute path, like so:

import multiprocessing
from playsound import playsound

def use_playsound(audio_file):
    p = multiprocessing.Process(target=playsound, args=(audio_file,))
    p.start()
    print(p.is_alive())
    input("press ENTER to stop playback")
    p.terminate()


def main():
    use_playsound("c:\\full\\path\\to\\the\\file\\test.mp3")


if __name__ == '__main__':
    main()

Another option is to use a different library that provides more control over audio playback, such as pyaudio or pyglet. These libraries allow you to play audio in the background and provide methods for controlling the playback, such as pausing and resuming.