在 Windows 平台上,可利用 Microsoft Speech API (SAPI 5) 實現文字轉語音。本文介紹 pyTTS 封裝庫的使用方法,涵蓋語速、音量、語音選擇、語音輸出檔案與發音校正。
SAPI5SpeechInstaller.msi)。pywin32:pip install pywin32pyTTS:需從 SourceForge 下載 pyTTS-3.0.win32-py2.4.exe(較舊,Python 2 專用)。注意:pyTTS 早已停止維護,現代專案建議使用跨平台的 pyttsx3、gTTS (Google) 或 edge-tts (Microsoft Edge)。
import pyTTS
import time
tts = pyTTS.Create()
# 設定語速 (-10 到 10)
tts.Rate = 1
print("語速:", tts.Rate)
# 設定音量 (0-100%)
tts.Volume = 90
print("音量:", tts.Volume)
# 列出可用語音
print("語音列表:", tts.GetVoiceNames())
# 選擇語音
tts.SetVoiceByName('MSMary') # 英文女聲
# 中文系統可能有 'Microsoft Huihui' 等
# 直接朗讀
tts.Speak("Hello, this is a test.")
# 朗讀並存成 WAV 檔
tts.SpeakToWave('output.wav', "This will be saved to file.")
# 從 WAV 檔播放
tts.SpeakFromWave('output.wav')
# 建立發音校正器
p = pyTTS.Pronounce()
# 註冊難發音詞彙對照
p.AddMisspelled('Ctrl', 'Control')
p.AddMisspelled(' * ', ' times ') # 需含空格避免誤替換
# 校正並朗讀
text = "Please press the Ctrl key! 2 * 3 = 6"
corrected = p.Correct(text)
print("校正後:", corrected)
# Please press the Control key! 2 times 3 = 6
tts.Speak(corrected)
# -*- coding: utf-8 -*-
import pyTTS
import time
tts = pyTTS.Create()
tts.Rate = 1
tts.Volume = 90
tts.SetVoiceByName('MSMary')
# 1. 朗讀日期時間
time_str = "The date and time is " + time.asctime()
tts.Speak(time_str)
# 2. 朗讀長段落
story = """A young executive was leaving the office at 6 pm when he found the CEO
standing in front of a shredder..."""
tts.Speak(story)
tts.Speak('Haah haa haah haa') # 笑聲
# 3. 發音替換示範
p = pyTTS.Pronounce()
p.AddMisspelled('Ctrl', 'Control')
p.AddMisspelled(' * ', 'times')
tts.Speak(p.Correct('Please press the Ctrl key!'))
tts.Speak(p.Correct('2 * 3 = 6'))
# 4. 語速變化
tts.Rate = 3
for i in range(7):
tts.Speak("The sinking steamer sunk!")
time.sleep(0.3)
tts.Rate = 0
tts.Speak("Wow, not one mispronounced word!")
import pyttsx3
engine = pyttsx3.init()
engine.setProperty('rate', 150)
engine.setProperty('volume', 0.9)
voices = engine.getProperty('voices')
for v in voices:
print(v.id, v.name)
engine.say("Hello World")
engine.runAndWait()
from gtts import gTTS
tts = gTTS(text="你好,世界", lang='zh-tw')
tts.save('hello.mp3')
# 播放需外部播放器
# pip install edge-tts
import asyncio
import edge_tts
async def main():
communicate = edge_tts.Communicate("你好,世界", "zh-TW-HsiaoChenNeural")
await communicate.save("hello.mp3")
asyncio.run(main())
| 方案 | 平台 | 離線 | 中文支援 | 語音品質 | 維護狀態 |
|---|---|---|---|---|---|
| pyTTS (SAPI) | Windows | 是 | 視系統語音包 | 一般 | 停止維護 |
| pyttsx3 | 跨平台 | 是 | 視系統語音包 | 一般 | 活躍 |
| gTTS | 跨平台 | 否 | 優秀 | 優秀 | 活躍 |
| edge-tts | 跨平台 | 否 | 優秀 | 優秀 | 活躍 |