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

PyCharm语音助手出现speech_recognition模块AssertionError求助

问题

在PyCharm开发的语音助手一周前运行正常,现在进入语音识别环节时触发speech_recognition模块__init__.py中的AssertionError,未自行使用assert关键字。已尝试新建项目、重新安装所有模块,问题仍存在。程序能正常完成问候,执行到语音识别步骤时报错。

代码

import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()


def wishMe():
    hour = int(datetime.datetime.now().hour)
    if 0 <= hour < 12:
        speak("Good Morning")
    elif hour >= 12 and hour < 18:
        speak("Good Afternoon")
    else:
        speak("Good Evening")
    speak("I am Edith. How can I help you sir?")


def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 0.4
        audio = r.listen(source)
        r.energy_threshold = 270

    try:
        print("Recognizing")
        query = r.recognize_google(audio, language='en-us')
        print(f"User said: {query}\n")
    except Exception as e:
        print("Say that again please...")
        return "none"
    return query


if __name__ == "__main__":
    wishMe()
    while True:
        query = takeCommand().lower()
        if 'wikipedia' in query:
            speak('Searching on wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=3)
            speak("According to wikipedia")
            print(results)
            speak(results)
        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

报错信息

C:\Users\hp1\PycharmProjects\pythonvoiceassistant\venv\Scripts\python.exe C:/Users/hp1/PycharmProjects/pythonvoiceassistant/main.py
Listening...
Traceback (most recent call last):
  File "C:\Users\hp1\PycharmProjects\pythonvoiceassistant\main.py", line 50, in <module>
    query = takeCommand().lower()
  File "C:\Users\hp1\PycharmProjects\pythonvoiceassistant\main.py", line 34, in takeCommand
    audio = r.listen(source)
  File "C:\Users\hp1\PycharmProjects\pythonvoiceassistant\venv\lib\site-packages\speech_recognition\__init__.py", line 595, in listen
    assert self.pause_threshold >= self.non_speaking_duration >= 0
AssertionError

Process finished with exit code 1

解决方案

报错核心原因是speech_recognition库的listen方法有断言校验:要求pause_threshold必须大于等于non_speaking_duration且两者都不小于0。你手动设置了r.pause_threshold = 0.4,但库默认的non_speaking_duration是0.5,导致0.4 < 0.5,触发断言失败。

修复步骤:

  1. 调整参数关系:在设置pause_threshold后,同步设置non_speaking_duration为小于等于前者的值,比如:
    r.pause_threshold = 0.4
    r.non_speaking_duration = 0.3
    
  2. 修正代码顺序:你把r.energy_threshold = 270写在了r.listen(source)之后,这行代码不会对当前监听生效,需要移到listen调用前。

调整后的takeCommand函数示例:

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 0.4
        r.non_speaking_duration = 0.3
        r.energy_threshold = 270
        audio = r.listen(source)

    try:
        print("Recognizing")
        query = r.recognize_google(audio, language='en-us')
        print(f"User said: {query}\n")
    except Exception as e:
        print("Say that again please...")
        return "none"
    return query

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:24:37