在 PyQt 中使用 pyttsx

Use pyttsx in PyQt

我正在用 pyqt 为我的聊天机器人制作 Gui,但我在这部分代码中遇到了一些问题。

def __init__(self):
    super(Window, self).__init__()
    self.setGeometry(50, 50, 500, 300)
    self.setWindowTitle("Chatbot 0.3")


def offline_speak(chat_speech):
    engine = pyttsx.init()
    engine.say(chat_speech)
    engine.runAndWait()

很少有事情会像 def offline_speak(self) 那样改变然后在上面提到它 init 比如 self.offline_speak() 但我不知道引擎代码。

谁能给我一些建议?

没有必要让offline_speak()成为class的一个方法,但是这个任务可能非常耗时,所以它会阻塞Qt生成的主循环,所以建议执行正如我在 QRunnableQThreadPool

的帮助下展示的那样,它在第二个线程中
import pyttsx

from PyQt4.QtGui import *
from PyQt4.QtCore import *


class SpeechRunnable(QRunnable):
    def __init__(self):
        QRunnable.__init__(self)
    def run(self):
        self.engine = pyttsx.init()
        self.engine.say(self.chat_speech)
        self.engine.runAndWait()

    def say(self, text):
        self.chat_speech = text
        QThreadPool.globalInstance().start(self)

    def stop(self):
        self.engine.stop()


class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.runnable = None
        self.setWindowTitle("Chatbot 0.3")
        lay = QVBoxLayout(self)
        self.le = QLineEdit(text, self)
        self.btnStart = QPushButton("start", self)
        self.btnStop = QPushButton("stop", self)
        self.btnStart.clicked.connect(self.onClickedStart)
        lay.addWidget(self.le)
        lay.addWidget(self.btnStart)
        lay.addWidget(self.btnStop)


    def onClickedStart(self):
        self.runnable = SpeechRunnable()
        self.runnable.say(self.le.text())
        self.btnStop.clicked.connect(self.runnable.stop)

    def closeEvent(self, event):
        if self.runnable is not None:
            self.runnable.stop()
            QThread.msleep(100) #delay
        super(Window, self).closeEvent(event)
text = """

What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
It has survived not only five centuries, but also the leap into electronic typesetting, 
remaining essentially unchanged. 
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, 
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
"""


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())