PyQt5系列教程(三十九)文本转语音QTextToSpeech
source link: https://xugaoxiang.com/2023/04/18/pyqt5-39-qtexttospeech/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
软硬件环境
- Windows 10 64bit
- Anaconda3 with python 3.8
- PyQt5 5.15
在这篇文章中,我们将学习如何在 PyQt5
中建立文本到语音(Text To Speech
)的应用程序,为此我们要使用 QtTextToSpeech
模块,首先让我们来谈谈这个模块,根据文档,QtTextToSpeech
模块可以让 PyQt5
的应用程序支持无障碍功能,将文字转换成语音,这对于那些有视觉障碍或由于某种原因不能访问应用程序的最终用户来讲,是非常有用的。
安装依赖库
pip install pyqt5 pyqt5-tools
使用 designer
来设计一个简单的 UI
界面,2个 label
、一个 combobox
(它会将系统中的可用声音列出来供你选择)、1个 lineedit
(这里输入文字) 和一个按钮 pushbutton
。
保存成 .ui
文件后,使用 pyuic
将 ui
转换成 py
文件
pyuic5.exe mainwindow.ui -o ui_mainwindow.py
接着看下 mainwindow.py
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtTextToSpeech import QTextToSpeech
from PyQt5.QtWidgets import QMainWindow, QApplication
from ui_mainwindow import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.play)
self.engine = None
engineNames = QTextToSpeech.availableEngines()
print('engine names: {}'.format(engineNames))
if len(engineNames) > 0:
engineName = engineNames[0]
self.engine = QTextToSpeech(engineName)
self.engine.stateChanged.connect(self.stateChanged)
self.voices = []
# 列出了系统中可用的声音
for voice in self.engine.availableVoices():
print('voice: {}'.format(voice))
self.voices.append(voice)
self.comboBox.addItem(voice.name())
else:
# 播放按钮不可用
self.pushButton.setEnabled(False)
def play(self):
self.pushButton.setEnabled(False)
# 使用选中的声音
self.engine.setVoice(self.voices[self.comboBox.currentIndex()])
# 播放
self.engine.say(self.lineEdit.text())
def stateChanged(self, state):
# 当tts结束后,将播放按钮设置为可用
if (state == QTextToSpeech.State.Ready):
self.pushButton.setEnabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
windows = MainWindow()
windows.show()
sys.exit(app.exec_())
运行上面的代码,可以看到
本机中只有一个声音,Microsoft HuiHui Desktop
,输入要转换的文本,点击 播放语音 按钮就可以听到文本对应的语音了。
https://github.com/xugaoxiang/learningPyQt5
PyQt5系列教程
更多 PyQt5
教程,请移步
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK