首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 文字轉語音 (TTS) 實作:基於 SAPI 5 與 pyTTS

     編輯:更多程式設計知識

在 Windows 平台上,可利用 Microsoft Speech API (SAPI 5) 實現文字轉語音。本文介紹 pyTTS 封裝庫的使用方法,涵蓋語速、音量、語音選擇、語音輸出檔案與發音校正。

環境準備 (Windows)

  1. 安裝 SAPI 5.1 執行環境(Windows XP 內建,較舊系統需下載 SAPI5SpeechInstaller.msi)。
  2. 安裝 pywin32:pip install pywin32
  3. 安裝 pyTTS:需從 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!")

現代替代方案推薦

1. pyttsx3 (離線、跨平台、無依賴)


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()

2. gTTS (Google 線上、自然語音、需網路)


from gtts import gTTS
tts = gTTS(text="你好,世界", lang='zh-tw')
tts.save('hello.mp3')
# 播放需外部播放器

3. edge-tts (Microsoft Edge 線上、高品質中文、免費)


# 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跨平台否優秀優秀活躍
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved