Communitygithub.com

Cetc2211/AcTR-app

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

AcTR-app 是什麼?

此技能引導使用者利用 z-ai-web-dev-sdk 套件實作文字轉語音 (TTS) 功能,能夠將文字轉換為自然流暢的語音音訊。它支援多種語音選項(如 tongtong、chuichui、xiaochen 等)、可調整的語速(0.5 至 2.0)與音量(大於 0 至 10),以及 wav、mp3、pcm 等輸出格式。此技能可應用於許多平台,包括 Node.js 後端環境、Express.js、Next.js API 路由以及命令列(CLI)。透過 z-ai CLI,使用者可以快速進行語音轉換;而 SDK 則適用於需要動態生成、批次處理或整合至網頁服務的進階情境。文件中詳細說明了 API 限制(例如每則請求文字上限 1024 字元、串流時僅支援 pcm 格式),並提供了錯誤處理、文字預處理與 SDK 實例重複使用等最佳實務,是開發語音應用程式的實用工具。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Cetc2211/AcTR-app/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(不包含 0)且小於等於 10(包含 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 時機:

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

基本 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(不包含 0)且 <= 10(包含 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:', 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:', 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. 電子學習:為教育內容建立旁白
  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(o

…

[已截斷以進行翻譯]

Individual skills in this repo

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

Cetc2211/AcTR-app

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.

Cetc2211/AcTR-app

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.

Cetc2211/AcTR-app

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.

Cetc2211/AcTR-app

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.

Cetc2211/AcTR-app

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

Cetc2211/AcTR-app

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.

Cetc2211/AcTR-app

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.

相關技能