鱼C论坛

 找回密码
 立即注册
查看: 24|回复: 1

[技术交流] Pyttsx3 RuntimeError: run loop already started 解决方案

[复制链接]
发表于 昨天 10:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
(代码很多,不展示)

问题疑似是同一个程序里只能有一个 pyttsx3 在朗读它生成的音频。

解决方案也很简单,把朗读音频的代码拆开到另一个文件,并使用 sys.argv 接收朗读的文本:

speak.py
import sys
from pyttsx3 import speak
text = sys.argv[1]
speak(text)

然后,使用 subprocess.call(['python', 'speak.py', 'Hello world']) 代替原来的 speak(text)。

还可以使用 sys.argv 接收 pyttsx3 Engine 的各种参数,如 rate、volume:
import sys
from pyttsx3 import init
rate, volume, voice, text = sys.argv
rate, volume, voice = int(rate), float(volume), int(voice)
engine = init()
engine.setProperty('rate', rate)
engine.setProperty('volume', volume)
engine.setProperty('voice', engine.getProperty('voices')[voice].id)
engine.say(text)
engine.runAndWait()
engine.stop()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 昨天 10:49 | 显示全部楼层
你的解决方案非常不错,将朗读音频的代码拆分到另一个文件确实能够避免 RuntimeError。我注意到你的代码有一些小问题,以下是经过修正的版本:

speak.py
import sys
from pyttsx3 import init

text = sys.argv[1:]
engine = init()
engine.say(' '.join(text))
engine.runAndWait()
engine.stop()

主程序中的调用方法示例
import subprocess

text = "Hello, this is a test."
subprocess.call(['python', 'speak.py', text])

这样做可以有效地解决 pyttsx3 RuntimeError: run loop already started 的问题。如果需要接收更多参数,请参考以下扩展示例。

speak.py 扩展版
import sys
from pyttsx3 import init

rate = int(sys.argv[1])
volume = float(sys.argv[2])
voice = int(sys.argv[3])
text = ' '.join(sys.argv[4:])

engine = init()
engine.setProperty('rate', rate)
engine.setProperty('volume', volume)
engine.setProperty('voice', engine.getProperty('voices')[voice].id)
engine.say(text)
engine.runAndWait()
engine.stop()

主程序中调用示例
import subprocess

rate = 150
volume = 0.9
voice = 0  # 使用第一个语音
text = "Hello, this is an extended test."
subprocess.call(['python', 'speak.py', str(rate), str(volume), str(voice), text])

这样,你可以灵活地调整 pyttsx3 引擎的参数和传递文本内容。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-2-3 07:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表