1

在这里提出并回答了这个问题:停止在 pydub 中播放音频

但是,一个答案对我不起作用。我在 Ubuntu 18.04 上使用 pydub,Python 3.6。

我尝试了以下代码的多种变体,包括上述代码:

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

我得到以下信息:

sound_alarm is True
^Csound_alarm is True
^Csound_alarm is True
sound_alarm is True

我让它循环一次,尝试杀死它两次,显然,它一直在循环。

我尝试过使用 playsound,但这种行为绝对不是我喜欢的。它不会立即终止播放。它确实会停止播放,但会给出非常难看的堆栈跟踪(见下文)。但是,除非我现在可以杀死它,否则似乎不是一个好的解决方案。

(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.
4

1 回答 1

0

我建议simpleaudio用于播放(如果安装了 pydub,默认情况下会使用它)。它应该立即响应键盘中断,因为它在单独的线程中播放。

于 2019-10-25T13:33:17.873 回答