如何在python线程中使用pyttsx

f45qwnt8  于 2023-01-18  发布在  Python
关注(0)|答案(2)|浏览(150)

我正在使用pyttsx3进行文本到语音转换。我意识到我可以在线程中使用它(或者我做错了什么)。你知道为什么吗?
代码示例:

from threading import Thread
import pyttsx3

def myfunc():
  engine = pyttsx3.init()
  engine.say("ok")
  engine.runAndWait()

t = Thread(target=myfunc)
t.start()

错误:

File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "test.py", line 9, in myfunc
    engine.runAndWait() #blocks
  File "/usr/local/lib/python3.6/site-packages/pyttsx3/engine.py", line 188, in runAndWait
    self.proxy.runAndWait()
  File "/usr/local/lib/python3.6/site-packages/pyttsx3/driver.py", line 204, in runAndWait
    self._driver.startLoop()
  File "/usr/local/lib/python3.6/site-packages/pyttsx3/drivers/nsss.py", line 33, in startLoop
    AppHelper.runConsoleEventLoop()
  File "/usr/local/lib/python3.6/site-packages/PyObjCTools/AppHelper.py", line 241, in runConsoleEventLoop
    nextfire = nextfire.earlierDate_(soon)
AttributeError: 'NoneType' object has no attribute 'earlierDate_'
bqujaahr

bqujaahr1#

错误似乎是它不能在osx上的线程中运行。下面是一些可能运行良好的示例:
如果您只需要将文本转换为语音,可以使用os.system('say %s')

import os
def myfunc():
  os.system('say ok')

gTTS或Google的TextToSpeech引擎,支持64种语言,包括意大利语。

from gtts import gTTS
import os
tts = gTTS(text='Good morning', lang='it')
tts.save("good.mp3")
os.system("mpg321 good.mp3")
ogsagwnx

ogsagwnx2#

我觉得pyttsx3不能在多个线程中发声(只发声一次就可以了),如果想在多个线程中发声,Macos系统应该使用say命令。
其他操作系统也应该有相应的命令

import sys
import os
import threading

print('threading1:',threading.activeCount())
text = 'Please start'

def myfunc():
    while True:
        # os.system('say another')
        # os.system('say -v Daniel "another"')
        # os.system('say -v Daniel "[[rate 160]] another"')  # 速度默认200
        os.system('say -v Daniel -r 140 "{}"'.format(text))
        os.system('say -v Samantha -r 140 "{}"'.format(text))
        # print(111)

loopThread = threading.Thread(target=myfunc, name='backgroundMusicThread')
loopThread.daemon = True
loopThread.start()

print('threading2:',threading.activeCount())

while True:
    text = input('input:\n')
    if text == 'end':
        sys.exit()

相关问题