萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 文本轉語音 (TTS) 實戰:從 pyTTS/SAPI 到現代跨平台方案 (pyttsx3/gTTS/Edge-TTS)

文本轉語音 (TTS) 是賦予應用「聲音」的關鍵技術。早期 Windows 平台依賴 pyTTS 封裝 Microsoft SAPI 5,但該庫已停維、不支援 Python 3、跨平台困難。本文回顧經典 pyTTS 用法,重點推薦現代跨平台、支援 Python 3、語音質量高的三大主流方案:pyttsx3 (離線)、gTTS (Google 雲端)、edge-tts (微軟 Edge 級神經網絡語音),並提供統一介面封裝。

一、 歷史回顧:pyTTS + SAPI 5 (僅限 Windows, Python 2.x)


# 經典代碼 (需安裝 pyTTS-3.0.win32-py2.4.exe, SAPI5SpeechInstaller.msi, pywin32)
import pyTTS
import time

tts = pyTTS.Create()
tts.Rate = 1          # 語速 -10~10
tts.Volume = 90       # 音量 0-100
print("Voices:", tts.GetVoiceNames())
tts.SetVoiceByName('MSMary')  # 設置語音角色

tts.Speak("The date and time is " + time.asctime())
tts.SpeakToWave('output.wav', "Save to file")
tts.SpeakFromWave('output.wav')

# 發音修正器
p = pyTTS.Pronounce()
p.AddMisspelled('Ctrl', 'Control')
tts.Speak(p.Correct('Press Ctrl key'))

局限:僅 Windows、Python 2、語音機械感強、依賴系統安裝語音包、無異步支援。

二、 現代方案一:pyttsx3 —— 跨平台離線 TTS 引擎

繼承 pyttsx,支援 Windows (SAPI5), macOS (NSSpeechSynthesizer), Linux (espeak/Festival)。純 Python,無外部雲端依賴。

安裝與基礎用法


pip install pyttsx3

import pyttsx3

engine = pyttsx3.init()  # 自動選擇平台後端
engine.setProperty('rate', 180)      # 語速 (詞/分)
engine.setProperty('volume', 0.9)    # 音量 0.0-1.0

# 列舉並選擇語音
voices = engine.getProperty('voices')
for v in voices:
    print(v.id, v.name, v.languages, v.gender)
# 選擇中文語音 (Windows: Microsoft Huihui, macOS: Tingting, Linux: zh)
chinese_voice = next((v for v in voices if 'zh' in str(v.languages)), None)
if chinese_voice:
    engine.setProperty('voice', chinese_voice.id)

engine.say("你好,世界!這是 pyttsx3 離線語音合成。")
engine.runAndWait()

# 保存到文件
engine.save_to_file("離線保存測試", "output_pyttsx3.wav")
engine.runAndWait()

進階:事件回調、異步非阻塞


def on_start(name): print(f"開始: {name}")
def on_end(name, completed): print(f"結束: {name}, completed={completed}")

engine.connect('started-utterance', on_start)
engine.connect('finished-utterance', on_end)

# 非阻塞:startLoop + endLoop (需自行管理線程)
engine.startLoop(False)
engine.say("後台播放中...")
# 主線程可做其他事
import time
time.sleep(2)
engine.endLoop()

三、 現代方案二:gTTS (Google Text-to-Speech) —— 雲端高質量、需網絡

調用 Google Translate TTS API,語音自然度極高,支援 100+ 語言,但需穩定訪問 Google 服務,有單次字符數限制 (~5000 字)。


pip install gtts

from gtts import gTTS
import os

tts = gTTS(text="你好,這是 Google 雲端語音合成,音質非常自然。", lang='zh-cn', slow=False)
tts.save("output_gtts.mp3")

# 播放 (跨平台簡易)
import platform, subprocess
if platform.system() == 'Darwin': subprocess.call(['afplay', 'output_gtts.mp3'])
elif platform.system() == 'Windows': os.startfile('output_gtts.mp3')
else: subprocess.call(['xdg-open', 'output_gtts.mp3'])

適用場景:離線部署不可行、追求最高自然度、文本較短、有穩定外網連接。

四、 現代方案三:edge-tts —— 微軟 Edge 級神經網絡語音,免費、高質量、支援 SSML

逆向工程 Microsoft Edge 瀏覽器「朗讀」功能調用的內部 API,提供超過 400 種神經網絡語音 (含多種中文語音:zh-CN-XiaoxiaoNeural, zh-CN-YunxiNeural 等),支援 SSML (語音合成標記語言) 精細控制語速、音高、停頓、情感風格,完全免費、無需 API Key、跨平台、異步原生。

安裝與基礎用法


pip install edge-tts

import asyncio
import edge_tts

async def main():
    text = "你好,這是微軟 Edge 級神經網絡語音,完全免費且音質媲美商業 API。"
    voice = "zh-CN-XiaoxiaoNeural"  # 可用通用女聲
    communicate = edge_tts.Communicate(text, voice)
    await communicate.save("output_edge.mp3")
    print("Saved!")

asyncio.run(main())

# 列出所有中文語音
# edge-tts --list-voices | grep zh-CN

SSML 精細控制 (edge-tts 獨特優勢)


import asyncio, edge_tts

ssml = """

    
        
            這段話語速較快音高稍低。
        
        
            還可以切換風格,比如開心、悲傷、新聞播報、客服語氣。
        
    

"""

async def ssml_demo():
    communicate = edge_tts.Communicate(ssml=ssml)
    await communicate.save("output_ssml.mp3")

asyncio.run(ssml_demo())

五、 統一介面封裝:適配器模式屏蔽底層差異


from abc import ABC, abstractmethod
from typing import Optional
import asyncio

class TTSEngine(ABC):
    @abstractmethod
    def speak(self, text: str, voice: Optional[str] = None, **kwargs) -> None: ...
    @abstractmethod
    def save_to_file(self, text: str, filepath: str, voice: Optional[str] = None, **kwargs) -> None: ...
    @abstractmethod
    def get_voices(self) -> list: ...

class Pyttsx3Engine(TTSEngine):
    def __init__(self):
        import pyttsx3
        self.engine = pyttsx3.init()
    def speak(self, text, voice=None, **kwargs):
        if voice: self.engine.setProperty('voice', voice)
        self.engine.say(text)
        self.engine.runAndWait()
    def save_to_file(self, text, filepath, voice=None, **kwargs):
        if voice: self.engine.setProperty('voice', voice)
        self.engine.save_to_file(text, filepath)
        self.engine.runAndWait()
    def get_voices(self):
        return [{'id': v.id, 'name': v.name, 'lang': v.languages} for v in self.engine.getProperty('voices')]

class EdgeTTSEngine(TTSEngine):
    def __init__(self):
        self._voices_cache = None
    async def _async_speak(self, text, voice, filepath=None):
        comm = edge_tts.Communicate(text, voice or 'zh-CN-XiaoxiaoNeural')
        if filepath:
            await comm.save(filepath)
        else:
            # 直接播放需音頻庫支援,這裡僅演示保存
            await comm.save("/tmp/temp_edge.mp3")
            # 播放邏輯...
    def speak(self, text, voice=None, **kwargs):
        asyncio.run(self._async_speak(text, voice))
    def save_to_file(self, text, filepath, voice=None, **kwargs):
        asyncio.run(self._async_speak(text, voice, filepath))
    def get_voices(self):
        if self._voices_cache is None:
            import edge_tts
            self._voices_cache = asyncio.run(edge_tts.list_voices())
        return self._voices_cache

# 工廠函數
def create_tts_engine(engine_type: str = 'edge') -> TTSEngine:
    if engine_type == 'pyttsx3': return Pyttsx3Engine()
    if engine_type == 'edge': return EdgeTTSEngine()
    # if engine_type == 'gtts': return GTTSEngine()
    raise ValueError(f"Unknown engine: {engine_type}")

# 使用
tts = create_tts_engine('edge')
tts.save_to_file("統一介面測試", "unified.mp3", voice="zh-CN-YunxiNeural")

六、 選型決策矩陣

維度pyttsx3gTTSedge-tts
平台Win/macOS/Linux任意 (需聯網)Win/macOS/Linux
離線/雲端離線雲端雲端 (但無需 Key)
語音質量中等 (機械感)高 (自然)極高 (神經網絡/商業級)
中文支援依賴系統語音包優秀極佳 (多風格/情感)
SSML 支援無無完整支援
異步原生否 (需線程)否是 (async/await)
成本免費免費 (有配額/反爬風險)免費
推薦場景嵌入式/離線/隱私敏感/原型快速雲端演示/多語言/非中文主場景生產環境/高質量需求/SSML精細控制/中文主場景

結語

從 pyTTS/SAPI 到 edge-tts,Python TTS 生態已實現跨平台、高質量、免費、可編程的飛躍。建議:新項目首選 edge-tts(質量最佳、SSML 強大、免費);離線/隱私場景用 pyttsx3;快速多語言雲端演示用 gTTS。統一介面封裝讓你隨時無縫切換後端,專注業務邏輯而非底層適配。

copyright © 萬盛學電腦網 all rights reserved