一、应用场景

笔者最近在做一个AI项目,需要文字转语音功能。

二、原理概述

使用python语言,PyQt窗口,以及谷歌翻译插件(gtts)实现,具有可视化的图窗、按钮。

三、完整代码

"""
_gtts_ui.py
初始选择页面,运行该文件以启动应用
"""

# Main entry point of the application
import sys

from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton, QVBoxLayout, QLabel, QInputDialog, \
    QLineEdit
from gtts import gTTS


class NewWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("New Window")
        self.setGeometry(100, 100, 200, 100)

        layout = QVBoxLayout()
        label = QLabel("This is a new window!")
        layout.addWidget(label)
        self.setLayout(layout)


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Main Window 【主窗口】")

        # Create a grid layout for buttons
        grid_layout = QGridLayout()

        button_labels = \
            [
                "【开始转换】"
            ]
        for i, label in enumerate(button_labels):
            button = QPushButton(label)
            font = QtGui.QFont()
            font.setFamily("Arial")  # 括号里可以设置成自己想要的其它字体
            font.setPointSize(18)  # 括号里的数字可以设置成自己想要的字体大小
            button.setFont(font)
            row = i // 3  # Row index (0, 1, or 2)
            col = i % 3  # Column index (0, 1, or 2)

            # Connect each button to a unique function
            button.clicked.connect(self.create_button_handler(label))

            # Add the button to the grid layout
            grid_layout.addWidget(button, row, col)

        # Add a button to close the window
        close_button = QPushButton("【Close Window】\n【关闭窗口】")
        close_button.clicked.connect(self.close_window)
        font = QtGui.QFont()
        font.setFamily("Arial")  # 括号里可以设置成自己想要的其它字体
        font.setPointSize(18)  # 括号里的数字可以设置成自己想要的字体大小
        close_button.setFont(font)
        grid_layout.addWidget(close_button, 3, 0, 1, 3)  # Place it at the bottom

        # Set the layout for the main window
        self.setLayout(grid_layout)

    def create_button_handler(self, label):
        """Create a function that handles the button click."""

        def button_handler():
            print(f"{label} clicked!")
            # For demonstration, open a new window when Button 1 is clicked
            if label == "【开始转换】":
                text, okPressed = QInputDialog.getText(self, "Get text", "转换文本:", QLineEdit.Normal, "")
                if okPressed and text != '':  // 非空文本,点击ok按钮
                    print(text)
                    tts = gTTS(text=text, lang='zh')
                    tts.save("test.mp3")  // 自定义保存的语音文件名

        return button_handler

    def close_window(self):
        """Close the main window."""
        self.close()  # This will trigger closeEvent


if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = MyWindow()
    window.resize(900, 600)  # Resize the window to make it fit nicely
    window.show()

    # Only call exec_() once in the main entry point
    sys.exit(app.exec_())

四、运行示例

(需要vpn访问谷歌)

在这里插入图片描述

转换成功:

在这里插入图片描述

【2025.4.14更新】
增加保存文件功能:

更新后的代码

"""
_gtts_ui.py
带有图形界面的实时文字转语音程序

"""

# Main entry point of the application
import sys

from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton, QVBoxLayout, QLabel, QInputDialog, \
    QLineEdit
from gtts import gTTS


class NewWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("New Window")
        self.setGeometry(100, 100, 200, 100)

        layout = QVBoxLayout()
        label = QLabel("This is a new window!")
        layout.addWidget(label)
        self.setLayout(layout)


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Main Window 【主窗口】")

        # Create a grid layout for buttons
        grid_layout = QGridLayout()

        button_labels = \
            [
                "【开始转换】"
            ]
        for i, label in enumerate(button_labels):
            button = QPushButton(label)
            font = QtGui.QFont()
            font.setFamily("Arial")  # 括号里可以设置成自己想要的其它字体
            font.setPointSize(18)  # 括号里的数字可以设置成自己想要的字体大小
            button.setFont(font)
            row = i // 3  # Row index (0, 1, or 2)
            col = i % 3  # Column index (0, 1, or 2)

            # Connect each button to a unique function
            button.clicked.connect(self.create_button_handler(label))

            # Add the button to the grid layout
            grid_layout.addWidget(button, row, col)

        # Add a button to close the window
        close_button = QPushButton("【Close Window】\n【关闭窗口】")
        close_button.clicked.connect(self.close_window)
        font = QtGui.QFont()
        font.setFamily("Arial")  # 括号里可以设置成自己想要的其它字体
        font.setPointSize(18)  # 括号里的数字可以设置成自己想要的字体大小
        close_button.setFont(font)
        grid_layout.addWidget(close_button, 3, 0, 1, 3)  # Place it at the bottom

        # Set the layout for the main window
        self.setLayout(grid_layout)

    def create_button_handler(self, label):
        """Create a function that handles the button click."""

        def button_handler():
            print(f"{label} clicked!")
            # For demonstration, open a new window when Button 1 is clicked
            if label == "【开始转换】":
                text, okPressed = QInputDialog.getText(self, "Get text", "转换文本:", QLineEdit.Normal, "")
                tts = gTTS(text=text, lang='zh')
                if okPressed and text != '':
                    print(text)
                    text, okPressed = QInputDialog.getText(self, "Get text", "存储文件名:", QLineEdit.Normal, "chat_.mp3")

                    tts.save(text)

        return button_handler

    def close_window(self):
        """Close the main window."""
        self.close()  # This will trigger closeEvent


if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = MyWindow()
    window.resize(900, 600)  # Resize the window to make it fit nicely
    window.show()

    # Only call exec_() once in the main entry point
    sys.exit(app.exec_())

运行示例:

在这里插入图片描述

在这里插入图片描述

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐