player-none 发表于 2025-2-2 10:49:27

Pyttsx3 RuntimeError: run loop already started 解决方案

(代码很多,不展示)

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

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

speak.py
import sys
from pyttsx3 import speak
text = sys.argv
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').id)
engine.say(text)
engine.runAndWait()
engine.stop()

FishC 发表于 2025-2-2 10:49:34

你的解决方案非常不错,将朗读音频的代码拆分到另一个文件确实能够避免 RuntimeError。我注意到你的代码有一些小问题,以下是经过修正的版本:

speak.py

import sys
from pyttsx3 import init

text = sys.argv
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)
volume = float(sys.argv)
voice = int(sys.argv)
text = ' '.join(sys.argv)

engine = init()
engine.setProperty('rate', rate)
engine.setProperty('volume', volume)
engine.setProperty('voice', engine.getProperty('voices').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 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: Pyttsx3 RuntimeError: run loop already started 解决方案