2024-06-22|閱讀時間 ‧ 約 27 分鐘

[Python]使用pyttsx3將文字轉語音

本文利用pyqt5,使用pyttsx3將QLineEdit(單行輸入框)的字串,轉成語音呈現出來。



程式範例

import sys
import pyttsx3
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QVBoxLayout

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

self.initUI()
self.engine = pyttsx3.init()

def initUI(self):
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle('Text to Speech')

layout = QVBoxLayout()

self.text_input = QLineEdit(self)
layout.addWidget(self.text_input)

self.play_button = QPushButton('Play', self)
self.play_button.clicked.connect(self.play_text)
layout.addWidget(self.play_button)

self.setLayout(layout)

def play_text(self):
text = self.text_input.text()
self.engine.say(text)
self.engine.runAndWait()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = TextToSpeech()
ex.show()
sys.exit(app.exec_())

程式碼重點說明

play_text :讀取輸入框中的文字並使用 pyttsx3 讀出來。

    def play_text(self):
text = self.text_input.text()
self.engine.say(text)
self.engine.runAndWait()

pyttsx3 用於將文字轉換為語音。與其他語音合成庫不同,pyttsx3 支持多平台,包括 Windows、macOS 和 Linux,並且不需要依賴於線上服務,這意味著它可以在沒有網絡連接的情況下工作。

以下是 pyttsx3 模組的說明,包括安裝、基本使用和常用功能:


基本使用

以下是一個簡單的範例,展示如何使用 pyttsx3 將文字轉換為語音:

import pyttsx3

# 初始化引擎
engine = pyttsx3.init()

# 設置文字
text = "Hello, how are you today?"

# 說出文字
engine.say(text)

# 等待完成
engine.runAndWait()

常用功能

調整語速

可以調整語音播放的速度:

import pyttsx3

engine = pyttsx3.init()

# 設置語速
rate = engine.getProperty('rate') # 獲取當前語速
print(f"Current speaking rate: {rate}")

engine.setProperty('rate', 150) # 設置語速為150字/分鐘

engine.say("This is the new speaking rate.")
engine.runAndWait()

調整音量

可以調整語音的音量:

import pyttsx3

engine = pyttsx3.init()

# 設置音量
volume = engine.getProperty('volume') # 獲取當前音量
print(f"Current volume level: {volume}")

engine.setProperty('volume', 0.9) # 設置音量(範圍在0.0到1.0之間)

engine.say("This is the new volume level.")
engine.runAndWait()

更改語音

可以更改語音引擎使用的語音(例如男聲或女聲):

import pyttsx3

engine = pyttsx3.init()

# 獲取所有可用語音
voices = engine.getProperty('voices')
for index, voice in enumerate(voices):
print(f"Voice {index}:")
print(f" - ID: {voice.id}")
print(f" - Name: {voice.name}")
print(f" - Languages: {voice.languages}")
print(f" - Gender: {voice.gender}")
print(f" - Age: {voice.age}")

# 設置使用的語音(例如,選擇第二個語音)
engine.setProperty('voice', voices[1].id)

engine.say("This is a different voice.")
engine.runAndWait()








分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.