【问题标题】:cannot stop audio playback gracefully using pydub or playsound in python无法在 python 中使用 pydub 或 playsound 优雅地停止音频播放
【发布时间】:2025-12-09 20:10:01
【问题描述】:

这个问题在这里被问及回答:Stop the audio from playing in 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.

【问题讨论】:

    标签: python python-3.x ubuntu-18.04 pydub python-playsound


    【解决方案1】:

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

    【讨论】: