Python语音助手如何实现文本、语音两种输入模式选择功能
现有代码的核心问题
takecommand主输入函数没有返回值:调用子输入函数后没有将结果返回,外部逻辑无法拿到用户的输入内容- 模式选择的键盘监听逻辑存在缺陷:空循环高频调用
keyboard.is_pressed既会占用过高CPU,也容易错过用户的按键触发,同时没有按键消抖逻辑,容易出现单次按键被识别为多次的问题 - 语音识别函数的递归调用存在安全隐患:识别失败时直接递归调用自身,连续多次识别失败会触发栈溢出
- 逻辑判断冗余:用于存储模式的变量本身就是布尔值,不需要额外和
True/False做等值比较
修正后的完整代码
import keyboard import speech_recognition as sr import time # 文本输入实现 def takecommandti(): print(" ") rt = input(">>") return rt.lower() # 语音输入实现 def takeCommandsi(): r = sr.Recognizer() r.dynamic_energy_threshold = False r.energy_threshold = 4000 r.pause_threshold = 1 # 替换递归为循环,避免栈溢出 while True: print("Listening....") with sr.Microphone() as source: r.adjust_for_ambient_noise(source) audio = r.listen(source) try: print("Recognizing....") said = r.recognize_google(audio, language='en-in') print(f"You Said : {said}\n") return said.lower() except sr.UnknownValueError : print("could not understand audio \n ~Trying Again~") except sr.RequestError as e: print(f"Could not request results, check your internet connection; {e}") return "None" # 输入模式选择 input_mode_is_speech = False print("Please Select in which input Mode you want to Use :) ") print("1.Press 't' for Text Input Mode \n2.Press 's' for Speech Input Mode ") while True: if keyboard.is_pressed('t'): print('You have successfully Selected : Text Input Mode') input_mode_is_speech = False # 按键消抖,避免按键残留触发后续输入 time.sleep(0.2) break elif keyboard.is_pressed('s'): print('You have successfully Selected : Speech Input Mode') input_mode_is_speech = True time.sleep(0.2) break # 降低循环频率减少CPU占用 time.sleep(0.1) # 统一输入入口 def takecommand(): if input_mode_is_speech: return takeCommandsi() else: return takecommandti() # 测试代码,可替换为你的语音助手业务逻辑 if __name__ == "__main__": while True: user_input = takecommand() if user_input == "quit": print("退出程序") break print(f"处理输入:{user_input}")
注意事项
- keyboard库需要系统级的键盘监听权限,Windows下需要用管理员身份运行IDE/终端,Linux/macOS下需要加sudo执行脚本
- 如果你需要切换输入模式,可以自行在业务逻辑中加触发重新执行模式选择的代码
内容的提问来源于stack exchange,提问作者iamDyeus
相关产品推荐
相关产品推荐

