廣告位招商中 歡迎洽談

串接 Speechify 語音合成 API:低延遲串流傳輸、Simba 模型與詞級時間戳記實戰

蔡伯威 · 365Finds Editorial
已收錄 88,650 篇 Wiki 文章

讓你的 AI 用上 365 Wiki

複製下方的提示詞,貼給你常用的 AI,然後直接提問。

下載完整版 Skill

先用提示詞體驗;經常使用時,安裝完整版 365Wiki Skill,以後無需重複複製。沒有常用 AI?Gemini、Microsoft Copilot 等網頁版也可以。

365Wiki Skill

在現代 Web 應用中,讓使用者等待三到五秒鐘只為生成一段音訊播放,是完全無法接受的互動體驗。長期以來,打造音訊閱讀器、線上教育平台與輔助閱讀工具的全端工程師們不得不忍受傳統文字轉語音(TTS)架構的硬傷:向 REST 接口提交大段文本,HTTP 連線長時間掛起等待伺服器端全量推論完成,最後下載一個靜態 MP3 檔案交由 HTML5 <audio> 播放。

這種傳統模式帶來了兩大致命痛點:首先是首包延遲(TTFB)與發音等待時間極高,破壞了即時互動感;其次,靜態音訊檔案缺乏高精度的詞級時間對齊資訊,前端介面根本無法原生實現類似「卡拉 OK 式」精準流暢的逐詞同步高亮閱讀。

在 365Finds 看來,這個工程瓶頸的分水嶺已經確立:如果你正在打造互動式閱讀或語言學習產品,傳統的整段靜態 TTS 接口已經被淘汰。Speechify 官方推出的開發者接口(Speechify Developer API)正是為打破這道限制而生。透過原生串流架構的 Simba 系列語音模型(如 Simba 3.2 與 Simba 3.5),結合 Server-Sent Events(SSE)長連線與即時詞級時間標記(Speech Marks),Speechify 能將首字發音等待時間壓低至毫秒級,並在同一個通道中即時輸出精確的詞級時間戳記。

本文將深入剖析 Speechify 開發者接口的串接架構、鑑權安全規範,並提供從後端串流轉發到前端 JavaScript 驅動 60 FPS 逐詞高亮渲染的完整落地實戰。


一、架構解析:Speechify 如何實現音訊與時間戳記並發串流傳輸

與傳統的整批推論生成不同,Speechify 的 Simba 模型採用增量式合成邏輯,利用 HTTP 串流通道(Server-Sent Events)持續向用戶端推送音訊區塊與中繼資料:

+-----------------------------------------------------------------------+
| 瀏覽器前端                                                            |
|  [正文 DOM 節點] <--- requestAnimationFrame 逐詞高亮同步循環          |
|         ^                                                             |
|         | SSE 資料流 (Base64 音訊塊 + speech_marks 陣列)              |
|  [Next.js / Node.js 鑑權代理服務]                                     |
|         ^ (持有官方私有金鑰:SPEECHIFY_API_KEY)                       |
+---------|-------------------------------------------------------------+
          | POST /v1/audio/stream/with-timestamps
+---------v-------------------------------------------------------------+
| Speechify 官方雲端接口 (api.speechify.ai)                             |
|  [Simba 3.2 / 3.5 語音大模型]                                         |
|   -> 分塊輸出 Base64 音訊資料 (MP3 / PCM)                             |
|   -> 同步計算詞級絕對毫秒標記 (start_time / end_time)                 |
+-----------------------------------------------------------------------+

Simba 系列模型選型建議

在串接時,模型參數的選型直接決定了首字延遲與語系支援:

接口鑑權與安全架構邊界

串流詞級時間戳記接口的官方網址為:POST https://api.speechify.ai/v1/audio/stream/with-timestamps(亦可透過 https://api.speechify.com 發起請求)。鑑權採用標準的 Authorization: Bearer <SPEECHIFY_API_KEY>。

安全風險警告:前端工程師絕對不能在用戶端瀏覽器 JavaScript 程式碼中直接暴露主 SPEECHIFY_API_KEY。任何封包攔截工具都能輕易取得明文憑證,造成 API 配額被盜刷。365Finds 明確建議:必須在業務後端(如 Next.js Route Handler 或 Node.js/Express 服務)搭建一層輕量級代理,完成使用者工作階段驗證後,以不緩衝的方式將 SSE 串流直接轉發給瀏覽器前端。


二、封包協定深度拆解:解析 SSE 與 Speech Marks 資料結構

向 /v1/audio/stream/with-timestamps 發起 POST 請求時,回應標頭將被設為 Content-Type: text/event-stream。回傳資料由多個以 event: speech.chunk 命名的事件區塊組成,最終以 event: speech.done 正式結束(請注意:Speechify 不採用 OpenAI 風格的 [DONE] 字串標記,而是使用標準的具名事件)。

單一 Chunk 載荷範例

每個 speech.chunk 攜帶一段 JSON 資料:

event: speech.chunk
data: {
  "audio": "SUQzBAAAAAAAI1RTU0UAAAA...",
  "speech_marks": [
    {
      "type": "word",
      "start": 0,
      "end": 5,
      "start_time": 0,
      "end_time": 469,
      "value": "Hello"
    },
    {
      "type": "word",
      "start": 6,
      "end": 11,
      "start_time": 470,
      "end_time": 820,
      "value": "world"
    }
  ]
}

重要欄位屬性剖析:

由於 start_time 與 end_time 是相對於整段語音起點的全局時間,前端不需要依據每個音訊切片的播放時間進行痛苦的動態累加計算,大幅降低了時脈漂移風險。


三、後端實戰:建置安全無緩衝的 SSE 轉發代理

以下是一個基於 Node.js / Express 的生產級轉發代理範例。它負責妥善保護主 API Key,並以管線方式即時透傳資料串流:

// server.js (Node.js / Express)
import express from "express";

const app = express();
app.use(express.json());

app.post("/api/tts/stream", async (req, res) => {
  const { text, voiceId = "geffen_32", model = "simba-3.5" } = req.body;

  if (!text || typeof text !== "string") {
    return res.status(400).json({ error: "缺少必需的文本輸入。" });
  }

  const speechifyApiKey = process.env.SPEECHIFY_API_KEY;
  if (!speechifyApiKey) {
    return res.status(500).json({ error: "伺服端未配置 API Key。" });
  }

  try {
    const upstreamResponse = await fetch("https://api.speechify.ai/v1/audio/stream/with-timestamps", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${speechifyApiKey}`,
        "Content-Type": "application/json",
        "Accept": "text/event-stream"
      },
      body: JSON.stringify({
        input: text,
        voice_id: voiceId,
        model: model,
        output_format: "mp3_24000_64"
      })
    });

    if (!upstreamResponse.ok) {
      const errText = await upstreamResponse.text();
      return res.status(upstreamResponse.status).send(errText);
    }

    // 設定下游瀏覽器的串流回應標頭
    res.setHeader("Content-Type", "text/event-stream");
    res.setHeader("Cache-Control", "no-cache");
    res.setHeader("Connection", "keep-alive");
    res.flushHeaders?.();

    // 持續將上游串流直接傳遞給前端,避免記憶體快取延遲
    const reader = upstreamResponse.body.getReader();
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      res.write(value);
    }
    res.end();
  } catch (err) {
    console.error("Speechify 代理請求異常:", err);
    if (!res.headersSent) {
      res.status(500).json({ error: "語音串流轉發失敗。" });
    } else {
      res.end();
    }
  }
});

app.listen(3000, () => console.log("Proxy running on http://localhost:3000"));

四、前端核心:Web Audio 無縫拼接與 60 FPS 逐詞同步引擎

在前端實作中,365Finds 發現最容易踩的坑就是監聽 HTML5 <audio> 標籤的 timeupdate 事件來更新文字高亮。timeupdate 的觸發頻率通常每秒只有 3 到 4 次(間隔長達 250 至 300 毫秒),而一個英語或多語單字的朗讀時間通常落在 150 到 350 毫秒之間,這會導致文字高亮出現嚴重脫節與遲滯感。

專業級的解決方案由三項瀏覽器技術組成:

  1. ReadableStream 讀取器:以文本串流方式即時解析 SSE 區塊;
  2. Web Audio API (AudioContext):基於微秒級系統音訊時間軸無縫排程音訊切片播放;
  3. requestAnimationFrame 渲染迴圈:以每秒 60 到 120 幀的極致流暢度輪詢當前播放毫秒,瞬間點亮對應單字。

前端 DOM 結構與樣式配置

<div id="reader-container" class="reader-text"></div>
<button id="play-btn">立即開始朗讀</button>

<style>
  .reader-text span.word {
    display: inline-block;
    padding: 0 2px;
    transition: background-color 0.1s ease, color 0.1s ease;
  }
  .reader-text span.word.highlight {
    background-color: #fef08a;
    color: #854d0e;
    border-radius: 3px;
    font-weight: 600;
  }
</style>

前端 JavaScript 控制器完整程式碼

class SpeechifyKaraokePlayer {
  constructor(containerElement) {
    this.container = containerElement;
    this.audioContext = null;
    this.speechMarks = [];
    this.nextScheduleTime = 0;
    this.playbackStartTime = 0;
    this.isPlaying = false;
    this.activeWordElement = null;
  }

  // 將純文字預先渲染為帶有字元偏移屬性的 span 節點
  prepareText(rawText) {
    this.container.innerHTML = "";
    const tokens = rawText.match(/\S+|\s+/g) || [];
    let charCounter = 0;

    tokens.forEach((token) => {
      if (/\S/.test(token)) {
        const span = document.createElement("span");
        span.className = "word";
        span.textContent = token;
        span.dataset.start = charCounter;
        span.dataset.end = charCounter + token.length;
        this.container.appendChild(span);
      } else {
        this.container.appendChild(document.createTextNode(token));
      }
      charCounter += token.length;
    });
  }

  async startStream(text) {
    this.prepareText(text);
    this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
    await this.audioContext.resume();

    this.speechMarks = [];
    this.nextScheduleTime = this.audioContext.currentTime + 0.05; // 預留 50ms 緩衝
    this.playbackStartTime = this.nextScheduleTime;
    this.isPlaying = true;

    // 啟動 60 FPS 渲染迴圈
    requestAnimationFrame(() => this.renderHighlightLoop());

    const response = await fetch("/api/tts/stream", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text, model: "simba-3.5", voiceId: "geffen_32" })
    });

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let sseBuffer = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      sseBuffer += decoder.decode(value, { stream: true });
      const events = sseBuffer.split("\n\n");
      sseBuffer = events.pop(); // 保留尚未結尾的殘缺資料

      for (const rawEvent of events) {
        this.parseSseEvent(rawEvent);
      }
    }
  }

  parseSseEvent(rawEvent) {
    const lines = rawEvent.split("\n");
    let eventName = "";
    let dataStr = "";

    for (const line of lines) {
      if (line.startsWith("event:")) {
        eventName = line.replace("event:", "").trim();
      } else if (line.startsWith("data:")) {
        dataStr = line.replace("data:", "").trim();
      }
    }

    if (eventName === "speech.chunk" && dataStr) {
      try {
        const payload = JSON.parse(dataStr);
        if (payload.speech_marks && Array.isArray(payload.speech_marks)) {
          this.speechMarks.push(...payload.speech_marks);
        }
        if (payload.audio) {
          this.queueAudioChunk(payload.audio);
        }
      } catch (err) {
        console.error("解析 chunk 資料失敗:", err);
      }
    } else if (eventName === "speech.done") {
      console.log("Speechify 音訊串流接收完成。");
    }
  }

  async queueAudioChunk(base64Audio) {
    const binary = atob(base64Audio);
    const len = binary.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binary.charCodeAt(i);
    }

    try {
      const audioBuffer = await this.audioContext.decodeAudioData(bytes.buffer.slice(0));
      const source = this.audioContext.createBufferSource();
      source.buffer = audioBuffer;
      source.connect(this.audioContext.destination);

      // 無縫時間排程
      const scheduleAt = Math.max(this.audioContext.currentTime, this.nextScheduleTime);
      source.start(scheduleAt);
      this.nextScheduleTime = scheduleAt + audioBuffer.duration;
    } catch (e) {
      console.warn("音訊切片解碼警告(常見於 MP3 框架邊界跨封包截斷):", e);
    }
  }

  renderHighlightLoop() {
    if (!this.isPlaying) return;

    // 計算當前音訊時間線所處的絕對毫秒數
    const currentMs = (this.audioContext.currentTime - this.playbackStartTime) * 1000;

    // 匹配落在此毫秒區間內的詞級標記
    const currentMark = this.speechMarks.find(
      (mark) => currentMs >= mark.start_time && currentMs < mark.end_time
    );

    if (currentMark) {
      const wordSpan = this.container.querySelector(
        `span.word[data-start="${currentMark.start}"]`
      );

      if (wordSpan && wordSpan !== this.activeWordElement) {
        if (this.activeWordElement) {
          this.activeWordElement.classList.remove("highlight");
        }
        wordSpan.classList.add("highlight");
        wordSpan.scrollIntoView({ behavior: "smooth", block: "nearest" });
        this.activeWordElement = wordSpan;
      }
    }

    requestAnimationFrame(() => this.renderHighlightLoop());
  }
}

五、工程取捨與 365Finds 實務建議

在正式上線部署時,有三個關鍵設計架構需要團隊特別權衡:

  1. PCM 與 MP3 格式取捨:雖然 mp3_24000_64 能節省約 70% 的網路傳輸頻寬,但瀏覽器原生 decodeAudioData 對跨封包截斷的 MP3 訊框邊界容錯率有限。若使用者網路環境極度惡劣或要求極限低延遲,建議評估請求 pcm_24000 並採用 AudioWorklet 進行串流式線性渲染。
  2. 初始緩衝門檻:不要在第一個 SSE 位元組剛剛到達瀏覽器的瞬間立即播放。預留 50 至 100 毫秒的安全緩衝區,能有效吸收弱網環境下的封包抖動,避免首包播完後因第二包延遲而發生音訊中斷或爆音。
  3. 平台對比與選型依據:AWS Polly 雖具備 Speech Marks,但首包延遲普遍落在 1500 毫秒以上,無法滿足現代互動式閱讀的即時感;ElevenLabs 聲音擬真度高,但在複雜文字情境下前端逐詞對齊開發成本高昂。365Finds 推薦 Speechify 的核心原因在於:Simba 模型將百毫秒級串流極低延遲與開箱即用的絕對毫秒級時間戳記完整結合,是目前構建高精讀互動產品最成熟的工程解法。

參考資料