Communitygithub.com

ARYAN2302/liquid_researcher

使用 z-ai-web-dev-sdk 實作文字轉語音 (TTS) 功能。當使用者需要將文字轉換為自然語音、建立音訊內容、建置語音驅動應用程式或產生語音音訊檔案時,使用此技能。支援多種語音、可調整速度及各種音訊格式。

liquid_researcher 是什麼?

此技能提供使用 z-ai-web-dev-sdk 套件實作文字轉語音 (TTS) 功能的完整指南。它涵蓋了從基本命令列用法到進階 SDK 整合的所有內容,讓開發者能夠建立動態語音應用程式。此技能明確規定 API 限制,例如每請求最多 1024 個字元、速度範圍 0.5 至 2.0,以及音量範圍 0 至 10。它也詳細說明了輸出格式支援:非串流輸出支援 wav、pcm 和 mp3 格式,而串流模式則限制為僅支援 pcm 格式。此技能支援多種語音選項,包括 'tongtong'、'chuichui' 和 'xiaochen' 等,並為批次處理、動態內容產生以及 Next.js 和 Express.js 等框架的整合提供了實用的 JavaScript 範例。最佳實務部分涵蓋了文字準備、錯誤處理和 SDK 實例重複使用,使其成為在各種平台(包括 CLI、Node.js 和 Web 應用程式)上實作可靠 TTS 功能的完整解決方案。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ARYAN2302/liquid_researcher/tree/HEAD/skills/TTS

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

TTS(文字轉語音)技能

此技能引導使用 z-ai-web-dev-sdk 套件實作文字轉語音 (TTS) 功能,讓能將文字轉換為自然的語音音訊。

技能路徑

技能位置:{project_path}/skills/TTS

此技能位於專案中的上述路徑。

參考腳本:可在 {Skill Location}/scripts/ 目錄中找到範例測試腳本,用於快速測試和參考。請參閱 {Skill Location}/scripts/tts.ts 以取得可運作的範例。

概述

文字轉語音可讓您建置能從文字輸入產生語音音訊的應用程式,支援多種語音、速度和輸出格式,以滿足各種使用案例。

重要:z-ai-web-dev-sdk 必須僅在後端程式碼中使用。切勿在客戶端程式碼中使用。

API 限制與限制

在實作 TTS 功能之前,請注意這些重要的限制:

輸入文字限制

  • 最大長度:每個請求 1024 個字元
  • 超出此限制的文字必須分割成較小的區塊

音訊參數

  • 速度範圍:0.5 到 2.0
    • 0.5 = 半速(較慢)
    • 1.0 = 正常速度(預設)
    • 2.0 = 雙倍速度(較快)
  • 音量範圍:大於 0,最大可達 10
    • 預設值:1.0
    • 值必須大於 0(不含)且最大可達 10(含)

格式與串流

  • 串流限制:啟用 stream: true 時,僅支援 pcm 格式
  • 非串流:支援 wav、pcm 和 mp3 格式
  • 取樣率:24000 Hz(建議)

長文字的建議做法

function splitTextIntoChunks(text, maxLength = 1000) {
  const chunks = [];
  const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];
  
  let currentChunk = '';
  for (const sentence of sentences) {
    if ((currentChunk + sentence).length <= maxLength) {
      currentChunk += sentence;
    } else {
      if (currentChunk) chunks.push(currentChunk.trim());
      currentChunk = sentence;
    }
  }
  if (currentChunk) chunks.push(currentChunk.trim());
  
  return chunks;
}

先決條件

z-ai-web-dev-sdk 套件已安裝。如下列範例所示將其匯入。

CLI 用法(適用於簡單任務)

對於簡單的文字轉語音轉換,您可以使用 z-ai CLI 而非編寫程式碼。這非常適合快速音訊產生、測試語音或簡單的自動化。

基本 TTS

# 將文字轉換為語音(預設 WAV 格式)
z-ai tts --input "Hello, world" --output ./hello.wav

# 使用簡短選項
z-ai tts -i "Hello, world" -o ./hello.wav

不同的語音和速度

# 使用特定語音
z-ai tts -i "Welcome to our service" -o ./welcome.wav --voice tongtong

# 調整語速 (0.5-2.0)
z-ai tts -i "This is faster speech" -o ./fast.wav --speed 1.5

# 較慢的語音
z-ai tts -i "This is slower speech" -o ./slow.wav --speed 0.8

不同的輸出格式

# MP3 格式
z-ai tts -i "Hello World" -o ./hello.mp3 --format mp3

# WAV 格式(預設)
z-ai tts -i "Hello World" -o ./hello.wav --format wav

# PCM 格式
z-ai tts -i "Hello World" -o ./hello.pcm --format pcm

串流輸出

# 串流音訊產生
z-ai tts -i "This is a longer text that will be streamed" -o ./stream.wav --stream

CLI 參數

  • --input, -i <text>:必要 - 要轉換為語音的文字(最多 1024 個字元)
  • --output, -o <path>:必要 - 輸出音訊檔案路徑
  • --voice, -v <voice>:選用 - 語音類型(預設:tongtong)
  • --speed, -s <number>:選用 - 語速,0.5-2.0(預設:1.0)
  • --format, -f <format>:選用 - 輸出格式:wav, mp3, pcm(預設:wav)
  • --stream:選用 - 啟用串流輸出(僅支援 pcm 格式)

何時使用 CLI 與 SDK

在以下情況使用 CLI:

  • 快速文字轉語音轉換
  • 測試不同的語音和速度
  • 簡單的批次音訊產生
  • 命令列自動化腳本

在以下情況使用 SDK:

  • 應用程式中的動態音訊產生
  • 與 Web 服務整合
  • 自訂音訊處理管線
  • 具有複雜需求的生產應用程式

基本 TTS 實作

簡單的文字轉語音

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function textToSpeech(text, outputPath) {
  const zai = await ZAI.create();

  const response = await zai.audio.tts.create({
    input: text,
    voice: 'tongtong',
    speed: 1.0,
    response_format: 'wav',
    stream: false
  });

  // 從 Response 物件取得陣列緩衝區
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

  fs.writeFileSync(outputPath, buffer);
  console.log(`音訊已儲存至 ${outputPath}`);
  return outputPath;
}

// 用法
await textToSpeech('Hello, world!', './output.wav');

多種語音選項

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function generateWithVoice(text, voice, outputPath) {
  const zai = await ZAI.create();

  const response = await zai.audio.tts.create({
    input: text,
    voice: voice, // 可用的語音:tongtong, chuichui, xiaochen, jam, kazi, douji, luodo
    speed: 1.0,
    response_format: 'wav',
    stream: false
  });

  // 從 Response 物件取得陣列緩衝區
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

  fs.writeFileSync(outputPath, buffer);
  return outputPath;
}

// 用法
await generateWithVoice('Welcome to our service', 'tongtong', './welcome.wav');

可調整速度

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function generateWithSpeed(text, speed, outputPath) {
  const zai = await ZAI.create();

  // 速度範圍:0.5 到 2.0 (API 限制)
  // 0.5 = 半速(較慢)
  // 1.0 = 正常速度(預設)
  // 2.0 = 雙倍速度(較快)
  // 超出此範圍的值會導致 API 錯誤

  const response = await zai.audio.tts.create({
    input: text,
    voice: 'tongtong',
    speed: speed,
    response_format: 'wav',
    stream: false
  });

  // 從 Response 物件取得陣列緩衝區
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

  fs.writeFileSync(outputPath, buffer);
  return outputPath;
}

// 用法 - 較慢的旁白
await generateWithSpeed('This is an important announcement', 0.8, './slow.wav');

// 用法 - 較快的旁白
await generateWithSpeed('Quick update', 1.3, './fast.wav');

可調整音量

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function generateWithVolume(text, volume, outputPath) {
  const zai = await ZAI.create();

  // 音量範圍:大於 0,最大可達 10 (API 限制)
  // 值必須 > 0(不含)且 <= 10(含)
  // 預設值:1.0(正常音量)

  const response = await zai.audio.tts.create({
    input: text,
    voice: 'tongtong',
    speed: 1.0,
    volume: volume, // 選用參數
    response_format: 'wav',
    stream: false
  });

  // 從 Response 物件取得陣列緩衝區
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

  fs.writeFileSync(outputPath, buffer);
  return outputPath;
}

// 用法 - 較大聲的音訊
await generateWithVolume('This is an announcement', 5.0, './loud.wav');

// 用法 - 較小聲的音訊
await generateWithVolume('Whispered message', 0.5, './quiet.wav');

進階使用案例

批次處理

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
import path from 'path';

async function batchTextToSpeech(textArray, outputDir) {
  const zai = await ZAI.create();
  const results = [];

  // 確保輸出目錄存在
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  for (let i = 0; i < textArray.length; i++) {
    try {
      const text = textArray[i];
      const outputPath = path.join(outputDir, `audio_${i + 1}.wav`);

      const response = await zai.audio.tts.create({
        input: text,
        voice: 'tongtong',
        speed: 1.0,
        response_format: 'wav',
        stream: false
      });

      // 從 Response 物件取得陣列緩衝區
      const arrayBuffer = await response.arrayBuffer();
      const buffer = Buffer.from(new Uint8Array(arrayBuffer));

      fs.writeFileSync(outputPath, buffer);
      results.push({
        success: true,
        text,
        path: outputPath
      });
    } catch (error) {
      results.push({
        success: false,
        text: textArray[i],
        error: error.message
      });
    }
  }

  return results;
}

// 用法
const texts = [
  'Welcome to chapter one',
  'Welcome to chapter two',
  'Welcome to chapter three'
];

const results = await batchTextToSpeech(texts, './audio-output');
console.log('已產生:', results.length, '個音訊檔案');

動態內容產生

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

class TTSGenerator {
  constructor() {
    this.zai = null;
  }

  async initialize() {
    this.zai = await ZAI.create();
  }

  async generateAudio(text, options = {}) {
    const {
      voice = 'tongtong',
      speed = 1.0,
      format = 'wav'
    } = options;

    const response = await this.zai.audio.tts.create({
      input: text,
      voice: voice,
      speed: speed,
      response_format: format,
      stream: false
    });

    // 從 Response 物件取得陣列緩衝區
    const arrayBuffer = await response.arrayBuffer();
    return Buffer.from(new Uint8Array(arrayBuffer));
  }

  async saveAudio(text, outputPath, options = {}) {
    const buffer = await this.generateAudio(text, options);
    if (buffer) {
      fs.writeFileSync(outputPath, buffer);
      return outputPath;
    }
    return null;
  }
}

// 用法
const generator = new TTSGenerator();
await generator.initialize();

await generator.saveAudio(
  'Hello, this is a test',
  './output.wav',
  { speed: 1.2 }
);

Next.js API 路由範例

import { NextRequest, NextResponse } from 'next/server';

export async function POST(req: NextRequest) {
  try {
    const { text, voice = 'tongtong', speed = 1.0 } = await req.json();

    // 匯入 ZAI SDK
    const ZAI = (await import('z-ai-web-dev-sdk')).default;

    // 建立 SDK 實例
    const zai = await ZAI.create();

    // 產生 TTS 音訊
    const response = await zai.audio.tts.create({
      input: text.trim(),
      voice: voice,
      speed: speed,
      response_format: 'wav',
      stream: false,
    });

    // 從 Response 物件取得陣列緩衝區
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(arrayBuffer));

    // 以回應形式傳回音訊
    return new NextResponse(buffer, {
      status: 200,
      headers: {
        'Content-Type': 'audio/wav',
        'Content-Length': buffer.length.toString(),
        'Cache-Control': 'no-cache',
      },
    });
  } catch (error) {
    console.error('TTS API 錯誤:', error);

    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : '產生語音失敗,請稍後重試',
      },
      { status: 500 }
    );
  }
}

最佳實務

1. 文字準備

function prepareTextForTTS(text) {
  // 移除過多的空白
  text = text.replace(/\s+/g, ' ').trim();

  // 展開常見縮寫以獲得更好的發音
  const abbreviations = {
    'Dr.': 'Doctor',
    'Mr.': 'Mister',
    'Mrs.': 'Misses',
    'etc.': 'et cetera'
  };

  for (const [abbr, full] of Object.entries(abbreviations)) {
    text = text.replace(new RegExp(abbr, 'g'), full);
  }

  return text;
}

2. 錯誤處理

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function safeTTS(text, outputPath) {
  try {
    // 驗證輸入
    if (!text || text.trim().length === 0) {
      throw new Error('文字輸入不能為空');
    }

    if (text.length > 1024) {
      throw new Error('文字輸入超過最大長度 1024 個字元');
    }

    const zai = await ZAI.create();

    const response = await zai.audio.tts.create({
      input: text,
      voice: 'tongtong',
      speed: 1.0,
      response_format: 'wav',
      stream: false
    });

    // 從 Response 物件取得陣列緩衝區
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(arrayBuffer));

    fs.writeFileSync(outputPath, buffer);

    return {
      success: true,
      path: outputPath,
      size: buffer.length
    };
  } catch (error) {
    console.error('TTS 錯誤:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

3. SDK 實例重複使用

import ZAI from 'z-ai-web-dev-sdk';

// 建立單例實例
let zaiInstance = null;

async function getZAIInstance() {
  if (!zaiInstance) {
    zaiInstance = await ZAI.create();
  }
  return zaiInstance;
}

// 用法
const zai = await getZAIInstance();
const response = await zai.audio.tts.create({ ... });

常見使用案例

  1. 有聲書與播客:將書面內容轉換為音訊格式
  2. E-learning:為教育內容建立旁白
  3. 無障礙:提供文字內容的音訊版本
  4. 語音助理:產生動態回應
  5. 公告:建立自動化音訊通知
  6. IVR 系統:產生電話系統提示音
  7. 內容本地化:以不同語言建立音訊

整合範例

Express.js API 端點

import express from 'express';
import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';
import path from 'path';

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

let zaiInstance;
const outputDir = './audio-output';

async function initZAI() {
  zaiInstance = await ZAI.create();
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
}

// ... 其餘 Express.js 路由程式碼

Individual skills in this repo

This repo contains 8 individual skills — each has its own dedicated page.

ARYAN2302/liquid_researcher

Generate a single-file Chinese atelier-style portfolio website (horizontal-row list + hover-reveal thumb interaction, art lishu typography "Alimama DaoLiTi" via CDN, light/dark theme, hash-routed detail pages). Takes a natural-language description of the studio (name, director, discipline, works) and outputs ONE working .html file. Runs in BOTH Claude Code (writes to ~/Desktop) and GLM / online chat (outputs HTML inline). Trigger phrases include "做个中式工作室作品集", "做个隶书作品集", "lishu-portfolio-gen ...", "做个白屋风格的作品集", or when user drags this skill folder into chat asking for an atelier-style site.

ARYAN2302/liquid_researcher

Chinese-market SaaS pricing page template — soft sky-blue glass-morphism, 4-tier card grid with one elevated "recommended" tier, monthly/annual toggle, FAQ accordion, ¥ pricing with Inter numerals, careful CJK linebreaking, ICP filing footer.

ARYAN2302/liquid_researcher

Premium calm-tech SaaS landing template — bilingual (CN/EN) literary voice over a dark forest-night palette with warm gold accent, Cormorant + Noto Serif SC, Three.js procedural forest hero, station-based scrolling narrative, custom cursor. Built for ambient-AI / creative-tool / philosophical SaaS, not loud commercial launch.

ARYAN2302/liquid_researcher

Pro-camera HUD mockup template — full-viewport black canvas wrapping a real video with monospace overlays (corner brackets, top status bar, side AF/exposure columns, bottom timecode + aperture/shutter/ISO row, vertical 8-filter wheel, animated reticle). For cinematographer portfolios, camera-app demos, LUT pack previews, filter-look auditions. NOT a TikTok/Reels mockup, NOT a storyboard, NOT a shot list, NOT a script document. The chrome wraps real footage — never a div placeholder.

ARYAN2302/liquid_researcher

Premium pre-launch waitlist page template — dark charcoal canvas with subtle vignette, drifting portrait video-thumbnail cards, fade-up cascades, glass nav, live-updating join counter, single email form with success/error states. Built for creative-tool / AI / niche-SaaS invite-only launches with hushed exclusive tone, not loud growth-marketing.

ARYAN2302/liquid_researcher

Route design-related HTML artifact tasks to the right artifact skill, reference, design system generation, or export skill.

ARYAN2302/liquid_researcher

Implement AI-powered video generation capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to generate videos from text prompts or images, create video content programmatically, or build applications that produce video outputs. Supports asynchronous task management with status polling and result retrieval.

ARYAN2302/liquid_researcher

Implement specialized video understanding capabilities using the z-ai-web-dev-sdk. Use this skill when the user needs to analyze video content, understand motion and temporal sequences, extract information from video frames, describe video scenes, or perform video-based AI analysis. Optimized for MP4, AVI, MOV, and other common video formats.

相關技能