3

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 Answers1

3

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()
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
  • The `sys.exit()` immediately stops my program. Is it possible to stop the music with the program still running? – dominik findeisen Nov 10 '22 at 14:55
  • 1
    The playsound module doesn't support this. Look at this question: https://stackoverflow.com/questions/57158779/how-to-stop-audio-with-playsound-module – shreyasm-dev Nov 10 '22 at 18:59