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

Python新手求助:基于Hotkey调用SAPI实现音频通知功能

完善你的Python音频通知功能

Hey there! Let's get that audio notification feature polished up for you. I noticed you're already using the keyboard module for hotkeys and dipping into win32com for text-to-speech—great start! Let's fix up the gaps and add some useful tweaks.

首先,修复基础的语音通知功能

Your current Notification function cuts off at SA...—I assume you meant the Windows Speech API's SAPI.SpVoice object. Let's write a complete, robust version of this function, plus fix a few common pitfalls:

完整代码示例

import win32com.client
from keyboard import add_hotkey, wait

# 全局热键设置
HOTKEY = 'g'

# 提前初始化语音引擎(避免每次调用都创建实例,提升效率)
speaker = win32com.client.Dispatch("SAPI.SpVoice")
# 可选:调整语速(范围-10到10,0是默认)
speaker.Rate = 0
# 可选:调整音量(0到100,100是默认)
speaker.Volume = 80

def send_audio_notification(message):
    try:
        # 异步播放(避免阻塞程序,参数1代表SVSFlagsAsync)
        speaker.Speak(message, 1)
        print(f"已发送音频通知: {message}")
    except Exception as e:
        print(f"音频通知失败: {str(e)}")

# 注册热键:按下'g'时触发通知
add_hotkey(HOTKEY, lambda: send_audio_notification("Hello, this is your audio alert!"))

# 保持程序运行(keyboard模块需要主进程持续运行才能监听热键)
print(f"热键 '{HOTKEY}' 已注册!按下即可触发音频通知,按Ctrl+C退出程序...")
try:
    wait()
except KeyboardInterrupt:
    print("\n程序已退出")

扩展功能:更多音频选项

如果默认的文字转语音不够用,这里有两个实用的扩展方向:

1. 播放自定义音频文件

如果想播放自己的提示音(比如.wav格式的音效),可以用Python内置的winsound模块:

import winsound

def play_custom_audio(file_path):
    try:
        # SND_ASYNC让音频异步播放,不阻塞程序
        winsound.PlaySound(file_path, winsound.SND_FILENAME | winsound.SND_ASYNC)
        print(f"已播放自定义音频: {file_path}")
    except Exception as e:
        print(f"播放音频失败: {str(e)}")

# 修改热键调用为自定义音频
add_hotkey(HOTKEY, lambda: play_custom_audio("your_alert_sound.wav"))

2. 切换不同的语音(Windows系统)

如果你的系统安装了多个语音包,你可以枚举并选择喜欢的语音:

# 枚举所有可用语音
available_voices = speaker.GetVoices()
print("可用语音列表:")
for idx, voice in enumerate(available_voices):
    print(f"{idx+1}. {voice.GetDescription()}")

# 设置第二个语音(根据你的实际列表调整索引)
speaker.Voice = available_voices.Item(1)

重要注意事项

  • 安装依赖:如果还没装pywin32,运行pip install pywin32来获取win32com模块。
  • 权限问题:如果热键没响应,试试用管理员身份运行你的Python脚本——Windows有时会限制全局热键的权限。
  • 程序持续运行:keyboard模块的热键监听需要主程序保持运行状态,所以wait()或while True是必须的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:27:01