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

如何使代码中的engine.say()生效?语音转文字转语音功能异常排查

解决Vosk+pyttsx3语音转文字再转语音的engine.say()失效问题

你遇到的核心问题有两个:一是pyttsx3的engine.say()仅将语音任务加入队列,必须调用engine.runAndWait()才会触发播放;二是你直接使用recognizer.Result()返回的完整JSON字符串朗读,内容包含多余格式字符,且可能为空文本时无效触发。

修复步骤

  1. 解析识别结果的JSON字符串,提取纯文本内容
  2. 在engine.say()后添加engine.runAndWait()执行语音播放
  3. 增加空文本判断,避免无效朗读
  4. 可选:添加engine.stop()清空任务队列,防止重复播放

修改后的完整代码

from vosk import Model, KaldiRecognizer
import pyaudio
import pyttsx3
import json

model = Model(r"C:\Users\user\PycharmProjects\SpeechRecog\vosk-model-tl-ph-generic-0.6")
recognizer = KaldiRecognizer(model, 16000)

engine = pyttsx3.init()
# 可选:自定义语音属性
# engine.setProperty('rate', 150)  # 调整语速(默认200)
# engine.setProperty('volume', 0.8)  # 调整音量(范围0-1)

mic = pyaudio.PyAudio()
stream = mic.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=8192)
stream.start_stream()

while True:
    data = stream.read(4096)

    if recognizer.AcceptWaveform(data):
        result_json = recognizer.Result()
        # 解析JSON提取纯文本
        result_dict = json.loads(result_json)
        text = result_dict.get('text', '')
        
        if text:
            engine.say(text)
            engine.runAndWait()  # 触发语音播放
            engine.stop()  # 清空任务队列
        
        print(result_json)
        print(text)

额外排查点

  • 若仍无声音,可指定Windows驱动初始化:engine = pyttsx3.init(driverName='sapi5')
  • 检查系统默认音频输出设备是否正常、音量未静音
  • 更新pyttsx3到最新版本:pip install --upgrade pyttsx3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:45:21