You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用ESC键停止playsound播放?

实现ESC键停止闹钟音频的方案

关键要点

  • ESC键的ASCII码确实是27,但用键盘库的'esc'字符串更直观,无需记忆数字
  • 由于playsound播放音频时会阻塞主线程,必须用线程分离播放逻辑和按键监听逻辑

实现步骤

  1. 安装跨平台键盘监听库:pip install keyboard
  2. 修改代码,将音频播放放到子线程中
  3. 在主线程中监听ESC按键,触发后终止音频线程

修改后的完整代码

from playsound import playsound
import time
import threading
import keyboard

CLEAR = "\033[2J"
CLEAR_AND_RETURN = "\033[H"

# 全局变量标记是否停止音频
stop_audio = False

def play_alarm_sound():
    global stop_audio
    try:
        # 循环播放直到收到停止信号
        while not stop_audio:
            playsound("alarm.mp3")
            if stop_audio:
                break
    except Exception as e:
        print(f"播放出错: {e}")

def alarm(seconds): 
    global stop_audio
    stop_audio = False  # 重置停止标记
    time_elapsed = 0

    print(CLEAR)
    while time_elapsed < seconds: 
        # 倒计时过程中也监听ESC键,支持提前取消
        if keyboard.is_pressed('esc'):
            print(f"{CLEAR_AND_RETURN}闹钟已取消")
            return
        time.sleep(1)
        time_elapsed += 1

        time_left = seconds - time_elapsed
        minutes_left = time_left // 60 
        seconds_left = time_left % 60 

        print(f"{CLEAR_AND_RETURN}Alarm will sound in: {minutes_left:02d}:{seconds_left:02d}")

    # 启动音频播放线程
    audio_thread = threading.Thread(target=play_alarm_sound)
    audio_thread.start()
    
    # 主线程监听ESC键,按下后停止音频
    print("闹钟已启动,按ESC键停止播放")
    while audio_thread.is_alive():
        if keyboard.is_pressed('esc'):
            stop_audio = True
            print(f"{CLEAR_AND_RETURN}音频已停止")
            break
        time.sleep(0.1)  # 降低CPU占用

minutes = int(input("How many minutes to wait until alarm sounds?:"))
seconds = int(input("How many seconds to wait until alarm sounds?:"))
total_seconds = minutes * 60 + seconds
alarm(total_seconds)
# alarm(2)  # 测试用的可注释或保留

代码说明

  • stop_audio全局变量用于传递停止信号
  • play_alarm_sound函数在子线程中执行,循环播放音频直到收到停止指令
  • 倒计时阶段加入ESC监听,支持提前终止闹钟
  • 音频播放时,主线程实时检测ESC按键,触发后标记停止信号并终止音频线程

内容的提问来源于stack exchange,提问作者FreshPrincess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 17:03:28