You need to enable JavaScript to run this app. Python gTTS语音助手出现No text to speak断言报错求助
优惠活动
大模型
产品
解决方案
定价
更多

Python gTTS语音助手出现No text to speak断言报错求助

异常根因定位

这个AssertionError: No text to speak触发的核心原因是传入gTTS的文本参数为空字符串,顺着代码逻辑梳理共有3处逻辑漏洞直接导致空值传递:

  • 无差别调用语音播报:每轮循环不管有没有生成有效回复,都会直接执行assistantResponse(response),哪怕response是初始定义的空字符串""。常见触发空值的场景包括:麦克风识别失败返回空文本、用户未说出唤醒词、说出唤醒词但未匹配任何查询/问候逻辑,这些场景下response全程不会被赋值新内容,最终直接传给gTTS触发断言。
  • 逻辑块缩进错配:"who is"的维基查询判断没有放在唤醒词的if分支内部,哪怕用户没说唤醒词,只要识别文本包含"who is"就会触发维基查询,一旦识别的人物名匹配失败,response依然是空值。
  • 无异常兜底:维基百科查询、语音识别过程中没有加异常捕获,一旦接口请求失败,response不会被赋值有效内容,还是会走到空文本传给gTTS的分支。
修复方案

按照上述漏洞逐点修改即可,核心改动如下:

  1. 给assistantResponse加空值前置校验,空文本直接跳过播报,不触发gTTS初始化
  2. 修正逻辑缩进,把所有交互逻辑都收敛到唤醒词触发的分支内部,避免无唤醒状态下的无效执行
  3. 给维基查询加异常捕获,给response加兜底提示,保证至少有有效内容传入gTTS

修复后的核心循环&函数代码:

def assistantResponse(text):
    # 空值前置校验,直接跳过
    if not text.strip():
        return
    print(text)
    myobj = gTTS(text=text, lang="en", slow=False)
    myobj.save("assistant_response.mp3")
    os.system("start assistant_response.mp3")

a = 0
while a < 10:
    text = recordAudio()
    response = ""

    if (wakeWord(text) == True):
        response = response + greeting(text)

        if ("date" in text):
            get_date = getDate()
            response = response + "" + get_date

        if ("time" in text):
            now = datetime.datetime.now()
            meridiem = ""
            if now.hour >= 12:
                meridiem = "p.m."
                hour = now.hour - 12
            else:
                meridiem = "a.m."
                hour = now.hour

            if now.minute < 10:
                    minute = "0"+str(now.minute)
            else:
                minute = str(now.minute)
                    
            response = response + ' '+ 'It is '+ str(hour)+ ':'+minute+' '+meridiem+' .'

        # 缩进调整:将who is的判断挪入唤醒词分支内部
        if ("who is" in text):
            try:
                person = getPerson(text)
                if not person:
                    raise ValueError("No person name detected")
                wiki = wikipedia.summary(person, sentences=2)
                response = response + "" + wiki
            except Exception as e:
                response = "Sorry, I couldn't find information about that person."

    assistantResponse(response)
额外优化提示
  • 可以在循环初始加判断,如果recordAudio()返回空字符串,直接跳过本轮,减少无效计算
  • 原getPerson()函数没有做边界判断,如果用户说出的"who is"后面没有足够长度的短语,会返回空值,后续可补全空值返回的判断分支

内容的提问来源于stack exchange,提问作者Johann Flöck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 15:15:04