How do i play a sound in terminal while being able to stop it while playing in Python?

Viewed 306

I want to be able to play a sound in python by running my code in the terminal (i'm on MacOS if that's relevant), and be able to type something in terminal to stop it midway. Right now this is what i have:

import os
import sys

if __name__ == '__main__':
    os.system("afplay " + "/path/to/sound.mp3")
    if input("type 'halt' to stop music") == "halt":
        sys.exit()

The problem is that if i play the sound first then ask for the input, it won't show the input until it's done playing the sound. If i ask for the input then play the sound, it won't play the sound until it got the input. Is there a way around this?

1 Answers

You could use the playsound package, which has built-in asynchronous audio playing, along with other utilities.

Install the playsound package (and PyObjC if you're on a Mac). After you do that, you could try this:

import os
import playsound
import sys

if __name__ == '__main__':
    playsound.playsound("music.mp3", False)
    if input("type 'halt' to stop music") == "halt":
        sys.exit()
Related