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

Python语音识别遇无法识别声音报错终止问题解决咨询

解决语音识别程序遇无法识别声音时崩溃的问题

核心解决方案是添加异常捕获机制处理识别失败的情况,并让程序进入循环持续运行,避免单次错误导致终止。

关键修改点:

  • 捕获speech_recognition库抛出的UnknownValueError(无法识别语音)和RequestError(Google API请求失败)
  • 将主逻辑放入无限循环,确保程序持续监听
  • 处理识别失败的场景,提示用户并回到监听状态

修改后的完整代码:

import speech_recognition as sr
import pyttsx3
import wikipedia  # 修正原代码的大小写错误
import pywhatkit

listener = sr.Recognizer()
player = pyttsx3.init()


def listen():
    with sr.Microphone() as input_device:
        print("100% booted waiting for commands.")
        # 可选:调整识别器的噪声阈值,提升抗干扰能力
        listener.adjust_for_ambient_noise(input_device, duration=0.5)
        voice_content = listener.listen(input_device)
        try:
            text_command = listener.recognize_google(voice_content)
            text_command = text_command.lower()
            print(text_command)
            return text_command
        except sr.UnknownValueError:
            print("无法识别输入的声音,请重新尝试")
            talk("无法识别输入的声音,请重新尝试")
            return None
        except sr.RequestError:
            print("语音识别服务不可用,请检查网络连接")
            talk("语音识别服务不可用,请检查网络连接")
            return None


def talk(text):
    player.say(text)
    player.runAndWait()


def run_voice_bot():
    while True:  # 无限循环持续监听
        command = listen()
        if not command:
            continue  # 识别失败时跳过后续逻辑,回到监听状态
        if "what is" in command:
            command = command.replace("what is", "")
            try:
                info = wikipedia.summary(command, 5)
                talk(info)
                print(info)
            except wikipedia.exceptions.DisambiguationError:
                talk("这个关键词有多个结果,请更具体一点")
                print("这个关键词有多个结果,请更具体一点")
            except wikipedia.exceptions.PageError:
                talk("找不到相关信息")
                print("找不到相关信息")
        elif "who is" in command:
            command = command.replace("who is", "")
            try:
                info = wikipedia.summary(command, 5)
                talk(info)
                print(info)
            except wikipedia.exceptions.DisambiguationError:
                talk("这个关键词有多个结果,请更具体一点")
                print("这个关键词有多个结果,请更具体一点")
            except wikipedia.exceptions.PageError:
                talk("找不到相关信息")
                print("找不到相关信息")
        elif "play" in command:
            command = command.replace("play", "")
            pywhatkit.playonyt(command)
            talk("ok here you go.")
        else:
            talk("Sorry, I am unable to find what you looking for")
            print("Sorry, I am unable to find what you looking for")


run_voice_bot()

额外优化说明:

  • 添加了adjust_for_ambient_noise方法,帮助识别器适应环境噪声,提升识别准确率
  • 针对wikipedia库也添加了异常捕获,处理歧义页面和无结果的情况,进一步增强程序稳定性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:32:55