Communitygithub.com

AiCurv/ADBCommander

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

ADBCommander 是什麼?

此技能提供使用 z-ai-web-dev-sdk 套件實作文字轉語音 (TTS) 功能的完整指南。它能讓開發者將文字輸入轉換為自然流暢的語音音訊,並支援多種聲音(例如 tongtong、chuichui、xiaochen 等)、可調整的語速(0.5 至 2.0)與音量(最高 10),以及多種輸出格式如 WAV、MP3 與 PCM。此技能同時涵蓋 CLI 與 SDK 兩種使用途徑,其中 CLI 適合快速測試與自動化批次處理,而 SDK 則能深入整合至網頁應用程式、Node.js 服務或 Next.js API 路由,實現動態音訊生成。此技能也講解重要限制,例如每段文字最多 1024 個字元、串流模式僅支援 PCM 格式等,並提供錯誤處理、批次處理及文字分割等最佳實務作法。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/AiCurv/ADBCommander/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 <文字>:必要 - 要轉換為語音的文字(最多 1024 個字元)
  • --output, -o <路徑>:必要 - 輸出音訊檔案路徑
  • --voice, -v <聲音>:選用 - 聲音類型(預設:tongtong)
  • --speed, -s <數字>:選用 - 語速,0.5-2.0(預設:1.0)
  • --format, -f <格式>:選用 - 輸出格式:wav、mp3、pcm(預設:wav)
  • --stream:選用 - 啟用串流輸出(僅支援 pcm 格式)

何時使用 CLI 與 SDK

使用 CLI 的時機:

  • 快速文字轉語音轉換
  • 測試不同聲音與語速
  • 簡單批次音訊生成
  • 命令列自動化腳本

使用 SDK 的時機:

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

基本 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. 有聲書與Podcast:將書面內容轉換為音訊格式
  2. 數位學習:為教育內容建立旁白
  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 });
  }
}

initZAI();

app.post('/api/tts', async (req, res) => {
  try {
    const { text, voice = 'tongtong', speed = 1.0, format = 'wav' } = req.body;
    
    // 驗證文字長度
    if (!text || text.length > 1024) {
      return res.status(400).json({ 
        error: '文字必須在 1 到 1024 個字元之間' 
      });
    }
    
    // 驗證語速
    if (speed < 0.5 || speed > 2.0) {
      return res.status(400).json({ 
        error: '語速必須在 0.5 到 2.0 之間' 
      });
    }
    
    const response = await zaiInstance.audio.tts.create({
      input: text,
      voice,
      speed,
      response_format: format,
      stream: false
    });
    
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(arrayBuffer));
    
    const outputPath = path.join(outputDir, `tts_${Date.now()}.${format}`);
    fs.writeFileSync(outputPath, buffer);
    
    res.json({
      success: true,
      path: outputPath,
      size: buffer.length,
      format
    });
  } catch (error) {
    console.error('TTS 錯誤:', error);
    res.status(500).json({ 
      success: false, 
      error: error.message 
    });
  }
});

app.listen(3000, () => {
  console.log('TTS 伺服器已在 http://localhost:3000 啟動');
});

疑難排解

常見問題

  1. API 限制錯誤:確保文字長度不超過 1024 個字元,語速在 0.5-2.0 之間,音量在 0-10 之間。
  2. 串流錯誤:串流模式僅支援 pcm 格式。串流時請勿使用 wav 或 mp3。
  3. 記憶體使用量:處理大量文字時,請分批處理並在每批次後釋放資源。
  4. 音訊品質:如果需要高品質音訊,請使用更高的取樣率(建議使用 24000 Hz)。

支援

如果您遇到任何問題或有功能請求,請參閱 z-ai-web-dev-sdk 文件或聯絡支援團隊。

Individual skills in this repo

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

AiCurv/ADBCommander

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.

AiCurv/ADBCommander

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.

AiCurv/ADBCommander

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.

AiCurv/ADBCommander

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.

AiCurv/ADBCommander

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

AiCurv/ADBCommander

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.

AiCurv/ADBCommander

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.

相關技能