This question was asked and answered here: Stop the audio from playing in pydub
However, the one answer does not work for me. I am using pydub, Python 3.6 on Ubuntu 18.04.
I have tried a number of variations of the following code, including the above:
def ring():
sound_alarm = True
while True:
try:
print(f'sound_alarm is {sound_alarm}')
if sound_alarm == False:
return
play(sound)
except KeyboardInterrupt:
sound_alarm = False
print('done playing sound.')
break
I get the following:
sound_alarm is True
^Csound_alarm is True
^Csound_alarm is True
sound_alarm is True
I let it loop once, tried killing it twice and, obviously, it kept looping.
I have tried using playsound instead, but the behavior is definitely not to my liking. It does not kill the playback immediately. It does stop playback, but gives a very ugly stacktrace (see below). However, unless I can kill it NOW, it seems this is not a good solution.
(python3.6:16669): GStreamer-CRITICAL **: 11:18:46.456:
Trying to dispose element playbin, but it is in PLAYING instead of the NULL state.
You need to explicitly set elements to the NULL state before
dropping the final reference, to allow them to clean up.
This problem may also be caused by a refcounting bug in the
application or some element.