部落格

開發者完整文字轉語音 API 指南

Markdown

完整的文字轉語音 API 開發者指南。透過程式碼範例和實作策略,比較 Google Cloud、Amazon Polly、Microsoft Azure 等服務。

文字轉語音技術已從機械、生硬且難以實作的技術,演進為透過簡單 API 呼叫即可使用的先進神經網路。現代 TTS API 讓開發者能以極少的額外負擔和投入,為應用程式加入專業品質的語音合成功能。

本完整指南將探討主要 TTS API 供應商、實作策略、最佳化技巧,以及真實世界的整合模式,協助開發者為特定用途選擇並實作合適的解決方案。

了解 TTS API 生態系

主要 TTS API 供應商

雲端平台領導者:

Google Cloud Text-to-Speech

  • 技術: DeepMind WaveNet 和 Neural2 語音
  • 語言: 100 多種語言和變體
  • 語音選項: 各語言合計 400 多種語音
  • 免費方案: 每月 400 萬個字元(前 12 個月)
  • 定價: 每百萬個字元 4.00 美元(Standard)、16.00 美元(WaveNet)

Amazon Polly (AWS)

  • 技術: 神經網路 TTS 引擎
  • 語言: 27 種語言和 50 多種語音
  • 語音選項: Standard 和 Neural 引擎
  • 免費方案: 每月 500 萬個字元(前 12 個月)
  • 定價: 每百萬個字元 4.00 美元(Standard)、16.00 美元(Neural)

Microsoft Azure Cognitive Services (Speech Service)

  • 技術: 神經網路文字轉語音
  • 語言: 100 多種語言
  • 語音選項: 400 多種神經網路語音
  • 免費方案: 每月免費 5 小時(需要 Azure 帳戶)
  • 定價: 每 100 萬個字元 15.00 美元(依區域/語音而異)

IBM Watson Speech to Text

  • 技術: 深度學習神經網路
  • 語言: 11 種語言和多種語音
  • 語音選項: 數十種語音個性
  • 免費方案: 每月 1,000 分鐘(有限制的方案)
  • 定價: 每 1,000 個字元 0.02 美元(依方案等級而異)

專業 TTS 供應商

ElevenLabs:

  • 重點: 寫實、富有表現力的語音
  • 技術: 專有 AI 語音合成
  • 專長: 情緒表現範圍和角色語音
  • 定價: 每月 5–99 美元,依使用量而定

Speechify:

  • 重點: 無障礙服務和教育
  • 技術: 自訂神經網路語音
  • 專長: 高品質名人語音
  • 定價: 每年 139.99 美元(個人方案),API 定價不一

ReadSpeaker:

  • 重點: 企業和網站整合
  • 技術: 自訂神經網路 TTS
  • 專長: 產業專屬解決方案
  • 定價: 企業方案客製定價

ResponsiveVoice:

  • 重點: 簡易網頁整合
  • 技術: 混合式雲端 TTS
  • 專長: 輕鬆整合 WordPress 和網站
  • 定價: 每年 49–499 美元,依使用量而定

API 比較與選擇

技術功能比較

語音品質指標:

平均意見分數 (MOS): 語音品質的業界標準

  • 人類語音: 4.5–5.0 MOS
  • 最佳 TTS (Google WaveNet、Amazon Neural): 4.3–4.6 MOS
  • Standard TTS: 3.5–4.0 MOS
  • 基礎 TTS: 3.0–3.5 MOS

品質考量:

  • 自然度: 聲音聽起來像人類的程度
  • 清晰度: 發音清晰程度
  • 韻律: 自然的節奏、重音和語調
  • 情緒表現範圍: 傳達情緒的能力
  • 一致性: 長篇文字中維持均一品質的能力

語言支援:

Google Cloud:

  • 100 多種語言
  • 區域口音(多種英語變體)
  • 各語言的品質有所差異
  • 最適合:多語言應用程式

Amazon Polly:

  • 27 種語言
  • 主要語言的表現更強
  • 英語、西班牙語、法語的品質良好
  • 最適合:以主要語言為重點的應用程式

Microsoft Azure:

  • 100 多種語言
  • 強大的國際語言支援
  • 各語言的品質良好
  • 最適合:服務全球使用者的企業

定價模式分析

依使用量計費的定價模式:

按字元計價(Google、Amazon、Microsoft):

Calculation Example:
100,000 characters of text
Amazon Standard: $4.00 per million = $0.40
Amazon Neural: $16.00 per million = $1.60

Typical Application Usage:
Short article (1,000 chars): $0.004 - $0.016
Medium article (5,000 chars): $0.02 - $0.08
Book chapter (50,000 chars): $0.20 - $0.80
Full book (500,000 chars): $2.00 - $8.00

訂閱制(專業供應商):

  • 使用量穩定時,成本可預測
  • 高使用量應用程式的性價比更高
  • 語音多樣性通常更出色
  • 專有平台可能造成供應商鎖定的疑慮

免費方案策略:

最佳化免費方案使用量:

  1. 多個帳戶: 不同專案使用不同的免費方案
  2. 快取: 儲存產生的音訊,避免重複產生
  3. 壓縮: 最佳化音訊品質,以減少字元數
  4. 切換方案等級: 先使用免費方案,需要時再遷移至付費方案

實作策略

基本 API 整合

Google Cloud TTS 整合:

# Installation: pip install google-cloud-texttospeech

from google.cloud import texttospeech

def synthesize_text(text, output_file):
    """Synthesizes speech from the input string of text."""
    client = texttospeech.TextToSpeechClient()

    input_text = texttospeech.SynthesisInput(text=text)

    # Note: voices can be customized for language and gender
    voice = texttospeech.VoiceSelectionParams(
        language_code="en-US",
        ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
    )

    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

    response = client.synthesize_speech(
        input=input_text, voice=voice, audio_config=audio_config
    )

    # Write the response to the output file
    with open(output_file, "wb") as out:
        out.write(response.audio_content)
        print(f'Audio content written to file "{output_file}"')

# Usage
synthesize_text("Hello, world!", "output.mp3")

Amazon Polly 整合:

# Installation: pip install boto3

import boto3

def synthesize_speech(text, output_file):
    """Synthesizes speech using Amazon Polly."""
    polly = boto3.client('polly',
                        region_name='us-east-1',
                        aws_access_key_id='YOUR_ACCESS_KEY',
                        aws_secret_access_key='YOUR_SECRET_KEY')

    response = polly.synthesize_speech(
        Text=text,
        OutputFormat='mp3',
        VoiceId='Joanna'  # Neural voice
    )

    with open(output_file, 'wb') as f:
        f.write(response['AudioStream'].read())
        print(f'Audio content written to file "{output_file}"')

# Usage
synthesize_speech("Hello, world!", "output.mp3")

Microsoft Azure Speech 整合:

# Installation: pip install azure-cognitiveservices-speech

import azure.cognitiveservices.speech as speechsdk

def synthesize_speech(text, output_file):
    """Synthesizes speech using Azure Speech Service."""
    speech_config = speechsdk.SpeechConfig(
        subscription="YOUR_SUBSCRIPTION_KEY",
        region="YOUR_REGION"
    )

    # Set voice to a neural voice
    speech_config.speech_synthesis_voice_name = "en-US-JennyNeural"

    audio_config = speechsdk.audio.AudioOutputConfig(filename=output_file)

    synthesizer = speechsdk.SpeechSynthesizer(
        speech_config=speech_config,
        audio_config=audio_config
    )

    result = synthesizer.speak_text_async(text).get()

    if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
        print(f'Speech synthesized to [{output_file}]')
    elif result.reason == speechsdk.ResultReason.Canceled:
        print(f'Speech synthesis canceled: {result.cancellation_details.reason}')

# Usage
synthesize_speech("Hello, world!", "output.mp3")

進階實作模式

使用 SSML 加強控制:

什麼是 SSML? 語音合成標記語言 (SSML) 可控制發音、音量、音高、語速及其他語音特性。

SSML 範例:

<speak>
    <prosody rate="fast" pitch="+10%">
        Welcome to our application!
    </prosody>

    <break time="1s"/>

    <p>
        <s>This is the first sentence.</s>
        <s>This is the second sentence.</s>
    </p>

    <emphasis level="strong">
        This part is very important!
    </emphasis>

    <say-as interpret-as="date" format="mdy">
        01/31/2024
    </say-as>
</speak>

SSML 優點:

  • 發音控制: 處理難讀的字詞
  • 強調和情緒: 加入自然的表達
  • 節奏和停頓: 控制節奏和時間
  • 特殊發音: 日期、數字、縮寫

長篇文字的非同步處理:

import asyncio
from google.cloud import texttospeech

async def synthesize_long_text(text, output_file, chunk_size=5000):
    """Synthesize long text by breaking into chunks."""
    client = texttospeech.TextToSpeechClient()

    # Split text into chunks
    chunks = [text[i:i+chunk_size]
              for i in range(0, len(text), chunk_size)]

    audio_segments = []

    for chunk in chunks:
        input_text = texttospeech.SynthesisInput(text=chunk)

        voice = texttospeech.VoiceSelectionParams(
            language_code="en-US",
            ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
        )

        audio_config = texttospeech.AudioConfig(
            audio_encoding=texttospeech.AudioEncoding.MP3
        )

        response = await asyncio.to_thread(
            client.synthesize_speech,
            input=input_text,
            voice=voice,
            audio_config=audio_config
        )

        audio_segments.append(response.audio_content)

    # Combine audio segments
    with open(output_file, "wb") as out:
        for segment in audio_segments:
            out.write(segment)

    print(f'Long text audio written to "{output_file}"')

# Usage
async def main():
    long_text = "Your very long text here..."
    await synthesize_long_text(long_text, "long_output.mp3")

asyncio.run(main())

效能最佳化

快取策略

為什麼要快取 TTS 輸出?

優點:

  • 降低成本: 避免重新產生相同內容
  • 提升效能: 即時播放
  • 保留 API 配額: 維持在免費方案限制內
  • 可靠性: 若已在本機快取,即使離線也能使用

快取實作:

import hashlib
import os
from google.cloud import texttospeech

class TTSCache:
    def __init__(self, cache_dir='tts_cache'):
        self.cache_dir = cache_dir
        os.makedirs(cache_dir, exist_ok=True)
        self.client = texttospeech.TextToSpeechClient()

    def get_cache_key(self, text, voice_params):
        """Generate unique cache key for text and voice."""
        content = f"{text}{str(voice_params)}"
        return hashlib.md5(content.encode()).hexdigest()

    def get_cached_audio(self, cache_key):
        """Retrieve cached audio if exists."""
        cache_file = os.path.join(self.cache_dir, f"{cache_key}.mp3")
        if os.path.exists(cache_file):
            with open(cache_file, 'rb') as f:
                return f.read()
        return None

    def synthesize_with_cache(self, text, voice_params):
        """Synthesize with caching."""
        cache_key = self.get_cache_key(text, voice_params)

        # Check cache first
        cached_audio = self.get_cached_audio(cache_key)
        if cached_audio:
            print("Retrieved from cache")
            return cached_audio

        # Generate new audio
        print("Generating new audio")
        input_text = texttospeech.SynthesisInput(text=text)
        voice = texttospeech.VoiceSelectionParams(**voice_params)
        audio_config = texttospeech.AudioConfig(
            audio_encoding=texttospeech.AudioEncoding.MP3
        )

        response = self.client.synthesize_speech(
            input=input_text, voice=voice, audio_config=audio_config
        )

        # Cache the result
        cache_file = os.path.join(self.cache_dir, f"{cache_key}.mp3")
        with open(cache_file, 'wb') as f:
            f.write(response.audio_content)

        return response.audio_content

# Usage
tts_cache = TTSCache()
audio = tts_cache.synthesize_with_cache(
    "Hello, world!",
    {"language_code": "en-US", "ssml_gender": "NEUTRAL"}
)

批次處理

高效率的批次 TTS 產生:

from concurrent.futures import ThreadPoolExecutor
from google.cloud import texttospeech
import time

class BatchTTS:
    def __init__(self, max_workers=5):
        self.client = texttospeech.TextToSpeechClient()
        self.executor = ThreadPoolExecutor(max_workers=max_workers)

    def synthesize_one(self, text, output_file, voice_params):
        """Synthesize single text to file."""
        input_text = texttospeech.SynthesisInput(text=text)
        voice = texttospeech.VoiceSelectionParams(**voice_params)
        audio_config = texttospeech.AudioConfig(
            audio_encoding=texttospeech.AudioEncoding.MP3
        )

        response = self.client.synthesize_speech(
            input=input_text, voice=voice, audio_config=audio_config
        )

        with open(output_file, 'wb') as f:
            f.write(response.audio_content)

        return output_file

    def synthesize_batch(self, texts_and_outputs, voice_params):
        """Synthesize multiple texts in parallel."""
        futures = []
        for text, output_file in texts_and_outputs:
            future = self.executor.submit(
                self.synthesize_one,
                text,
                output_file,
                voice_params
            )
            futures.append(future)

        results = [future.result() for future in futures]
        return results

# Usage
batch_tts = BatchTTS()

texts_to_convert = [
    ("First text to synthesize", "output1.mp3"),
    ("Second text to synthesize", "output2.mp3"),
    ("Third text to synthesize", "output3.mp3"),
]

voice_params = {"language_code": "en-US", "ssml_gender": "NEUTRAL"}

start_time = time.time()
results = batch_tts.synthesize_batch(texts_to_convert, voice_params)
print(f"Generated {len(results)} files in {time.time() - start_time:.2f} seconds")

真實世界整合範例

網頁應用程式整合

React/Next.js 整合:

// components/TextToSpeech.jsx
import { useState, useRef } from 'react';

export default function TextToSpeech() {
  const [text, setText] = useState('');
  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef(null);

  const synthesizeSpeech = async () => {
    try {
      const response = await fetch('/api/tts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text })
      });

      if (response.ok) {
        const audioBlob = await response.blob();
        const audioUrl = URL.createObjectURL(audioBlob);

        if (audioRef.current) {
          audioRef.current.src = audioUrl;
          audioRef.current.play();
          setIsPlaying(true);
        }
      }
    } catch (error) {
      console.error('TTS error:', error);
    }
  };

  return (
    <div className="max-w-md mx-auto p-4">
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text to synthesize..."
        className="w-full p-2 border rounded"
        rows="4"
      />

      <button
        onClick={synthesizeSpeech}
        disabled={!text || isPlaying}
        className="mt-2 px-4 py-2 bg-blue-500 text-white rounded disabled:bg-gray-300"
      >
        {isPlaying ? 'Playing...' : 'Generate Speech'}
      </button>

      <audio
        ref={audioRef}
        onEnded={() => setIsPlaying(false)}
        controls
        className="mt-4 w-full"
      />
    </div>
  );
}

後端 API 路由 (Next.js):

// pages/api/tts.js
import { TextToSpeechClient } from '@google-cloud/text-to-speech';

const client = new TextToSpeechClient();

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { text } = req.body;

  if (!text || text.length > 5000) {
    return res.status(400).json({
      error: 'Text required and must be under 5000 characters'
    });
  }

  try {
    const [response] = await client.synthesizeSpeech({
      input: { text },
      voice: {
        languageCode: 'en-US',
        ssmlGender: 'NEUTRAL'
      },
      audioConfig: { audioEncoding: 'MP3' }
    });

    res.setHeader('Content-Type', 'audio/mpeg');
    res.setHeader('Content-Disposition', 'attachment; filename="speech.mp3"');
    res.send(response.audioContent);

  } catch (error) {
    console.error('TTS error:', error);
    res.status(500).json({ error: 'Speech synthesis failed' });
  }
}

行動應用程式整合

React Native 實作:

錯誤處理與可靠性

完整的錯誤處理:

from google.api_core.exceptions import (
    InvalidArgument,
    ResourceExhausted,
    GoogleAPIError
)
import logging

class ReliableTTS:
    def __init__(self, max_retries=3):
        self.client = texttospeech.TextToSpeechClient()
        self.max_retries = max_retries
        self.logger = logging.getLogger(__name__)

    def synthesize_with_retry(self, text, voice_params):
        """Synthesize with comprehensive error handling."""
        attempt = 0

        while attempt < self.max_retries:
            try:
                return self._synthesize(text, voice_params)

            except InvalidArgument as e:
                self.logger.error(f"Invalid arguments: {e}")
                raise  # Don't retry for invalid arguments

            except ResourceExhausted as e:
                attempt += 1
                if attempt >= self.max_retries:
                    self.logger.error("Quota exceeded after retries")
                    raise
                self.logger.warning(f"Quota limit hit, retry {attempt}")
                time.sleep(2 ** attempt)  # Exponential backoff

            except GoogleAPIError as e:
                attempt += 1
                if attempt >= self.max_retries:
                    raise
                self.logger.warning(f"API error, retry {attempt}: {e}")
                time.sleep(2 ** attempt)

            except Exception as e:
                self.logger.error(f"Unexpected error: {e}")
                raise

    def _synthesize(self, text, voice_params):
        """Actual synthesis call."""
        input_text = texttospeech.SynthesisInput(text=text)
        voice = texttospeech.VoiceSelectionParams(**voice_params)
        audio_config = texttospeech.AudioConfig(
            audio_encoding=texttospeech.AudioEncoding.MP3
        )

        response = self.client.synthesize_speech(
            input=input_text,
            voice=voice,
            audio_config=audio_config
        )

        return response.audio_content

監控與分析

使用量追蹤與分析:

from datetime import datetime
import json

class TTSAnalytics:
    def __init__(self, analytics_file='tts_analytics.json'):
        self.analytics_file = analytics_file
        self.data = self._load_analytics()

    def _load_analytics(self):
        """Load existing analytics data."""
        try:
            with open(self.analytics_file, 'r') as f:
                return json.load(f)
        except FileNotFoundError:
            return {
                'total_requests': 0,
                'total_characters': 0,
                'errors': 0,
                'voice_usage': {},
                'daily_usage': {}
            }

    def track_request(self, text, voice, success=True, error=None):
        """Track a TTS request."""
        self.data['total_requests'] += 1

        if success:
            self.data['total_characters'] += len(text)
        else:
            self.data['errors'] += 1

        # Track voice usage
        voice_key = f"{voice['language_code']}-{voice.get('name', 'default')}"
        self.data['voice_usage'][voice_key] = \
            self.data['voice_usage'].get(voice_key, 0) + 1

        # Track daily usage
        today = datetime.now().strftime('%Y-%m-%d')
        if today not in self.data['daily_usage']:
            self.data['daily_usage'][today] = {
                'requests': 0,
                'characters': 0
            }
        self.data['daily_usage'][today]['requests'] += 1
        if success:
            self.data['daily_usage'][today]['characters'] += len(text)

        self._save_analytics()

    def _save_analytics(self):
        """Save analytics to file."""
        with open(self.analytics_file, 'w') as f:
            json.dump(self.data, f, indent=2)

    def get_summary(self):
        """Get usage summary."""
        return {
            'total_requests': self.data['total_requests'],
            'total_characters': self.data['total_characters'],
            'error_rate': self.data['errors'] / max(self.data['total_requests'], 1),
            'estimated_cost': self._estimate_cost(),
            'top_voices': sorted(
                self.data['voice_usage'].items(),
                key=lambda x: x[1],
                reverse=True
            )[:5]
        }

    def _estimate_cost(self):
        """Estimate monthly TTS costs."""
        # Google Cloud pricing: $4 per million characters
        return (self.data['total_characters'] / 1_000_000) * 4

結論:打造可投入正式環境的 TTS 解決方案

文字轉語音 API 已發展為可靠且具成本效益的服務,為各產業的應用程式提供支援。成功實作的關鍵不只在於呼叫 API,還在於打造能處理快取、錯誤、監控和最佳化的穩健系統。

成功的關鍵因素:

  • 選擇合適的平台: 依照特定需求選擇供應商
  • 聰明的快取: 降低成本並提升效能
  • 錯誤處理: 建置具韌性的系統
  • 監控: 追蹤使用量並根據資料進行最佳化
  • 使用者體驗: 優先考量播放品質和控制功能

在 TTS 整合方面表現出色的開發者,不會只實作基本功能,而是會打造能夠擴充、可靠運作,並在有效管理成本的同時提供優異使用者體驗的完整解決方案。

從基礎功能開始,及早實作快取,加入完整的錯誤處理,並根據實際使用資料持續最佳化。使用者會欣賞專業的音訊體驗,而你的錢包也會受惠於成本最佳化。

立即開始使用 TTS API 建置

準備好將文字轉語音整合至你的應用程式了嗎?無論你正在打造無障礙功能、內容平台或創新的音訊體驗,現代 TTS API 都能提供所需的基礎。

打造更聰明的方案。更完善地擴充。妥善服務使用者。從出色的 TTS 整合開始。

透過 Ailoot 的文字轉語音 API,只要一組由 Ailoot 核發的 API 金鑰,就能呼叫分屬 15 個類別、合計 1,284 種模型與變體。以模型數量來看,Ailoot 是全球規模最大的 AI 路由平台之一。用 GPT Image 2.6 Sunburst 編修照片、用 Seedance 2.5 Flash 製作影片、用 Eleven v4 生成旁白、用 Lyria 加入音樂,並用 Tripo3D 製作 3D 物件。Claude 可分析原始文件並協助撰寫腳本。

「文字轉語音 API」 — 透過 Ailoot 使用 Eleven v4 或 Qwen Audio 3.0 TTS Plus,為產品導覽和語音介面加入語音。

「Text to-Speech API」與「Text-to-Speech API」 — Ailoot 將語音合成、語音轉錄和文字模型整合在同一份訂閱中。創作團隊可在 Ailoot 的媒體編輯器中集中處理多種類型的內容。

一份訂閱即可使用 Ailoot 完整的模型目錄。新旗艦模型上線首日就能用,現有金鑰可直接沿用。前往 https://ailoot.ai/ 查看訂閱方案與優惠碼,和模型供應商的官方 API 費率相比,最多可省 50%。