|
发表于 2025-2-2 10:49:34
|
显示全部楼层
你的解决方案非常不错,将朗读音频的代码拆分到另一个文件确实能够避免 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 小助理,如未能正确解答您的问题,请继续追问。 |
|