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コマンドから、Next.js APIルート、Express.jsエンドポイント、バッチ処理用の高度なSDK実装まで、複数の実装オプションをカバーしています。重要な制約事項として、1リクエストあたりの最大入力テキスト長は1024文字、ストリーミングモードではpcm形式のみサポート、サンプルレートは24000Hz推奨などが含まれます。また、テキストの前処理、堅牢なエラーハンドリング、インスタンスの再利用といったベストプラクティスも強調されており、プロダクション品質のTTSアプリケーションの構築に適しています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/AiCurv/ADBCommander/tree/HEAD/skills/TTS

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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 = 2倍の速度(速い)
  • 音量範囲: 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 オブジェクトから array buffer を取得
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

  fs.writeFileSync(outputPath, buffer);
  console.log(`Audio saved to ${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 オブジェクトから array buffer を取得
  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 = 2倍の速度(速い)
  // この範囲外の値は API エラーを引き起こします

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

  // Response オブジェクトから array buffer を取得
  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 オブジェクトから array buffer を取得
  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 オブジェクトから array buffer を取得
      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('Generated:', results.length, 'audio files');

動的コンテンツ生成

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 オブジェクトから array buffer を取得
    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 オブジェクトから array buffer を取得
    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('Text input cannot be empty');
    }

    if (text.length > 1024) {
      throw new Error('Text input exceeds maximum length of 1024 characters');
    }

    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 オブジェクトから array buffer を取得
    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. Eラーニング: 教育コンテンツのナレーションを作成
  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().catch(console.error);

app.post('/api/tts', async (req, res) => {
  try {
    const {
      text,
      voice = 'tongtong',
      speed = 1.0,
      format = 'wav'
    } = req.body;

    if (!text) {
      return res.status(400).json({ error: 'Text フィールドは必須です' });
    }

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

    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(arrayBuffer));

    const contentType = format === 'mp3' ? 'audio/mpeg' :
                       format === 'pcm' ? 'audio/l16' : 'audio/wav';

    res.setHeader('Content-Type', contentType);
    res.setHeader('Content-Length', buffer.length);
    res.send(buffer);
  } catch (error) {
    console.error('TTS Route Error:', error);
    res.status(500).json({ error: '音声生成に失敗しました' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`TTS サーバーがポート ${PORT} で起動しました`);
});

トラブルシューティング

よくある問題

  1. 応答がない

    • テキスト入力が空でないことを確認
    • テキスト長が1024文字を超えていないか確認
    • ネットワーク接続をチェック
  2. 音質が悪い

    • テキストに特殊文字や記号がないか確認
    • 適切な音声モデルを使用しているか確認
    • 速度設定を調整(1.0~1.5推奨)
  3. ファイル形式の問題

    • ストリーミングを使用する場合は pcm 形式のみサポートされることに注意
    • 適切なファイル拡張子を使用(.wav、.mp3、.pcm)
  4. 音量の問題

    • 音量値が0より大きく10以下であることを確認
    • 値が範囲外の場合、APIはエラーを返す

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.

関連スキル