Communitygithub.com

AiCurv/ADBCommander

z-ai-web-dev-sdk를 사용하여 텍스트를 자연스러운 음성으로 변환하는 TTS(텍스트 음성 변환) 기능을 구현합니다. 음성 지원 앱 구축, 오디오 콘텐츠 제작, 다양한 음성과 속도 조절이 필요한 경우에 사용하세요.

ADBCommander란 무엇인가요?

이 스킬은 z-ai-web-dev-sdk 패키지를 활용하여 텍스트를 자연스러운 음성 오디오로 변환하는 TTS(Text-to-Speech) 기능을 구현하는 방법을 안내합니다. 다양한 음성, 조절 가능한 속도(0.5~2.0), 볼륨(0~10), 출력 형식(wav, mp3, pcm)을 지원하며, 최대 1024자 입력 제한이 있습니다. 스트리밍 모드에서는 pcm 형식만 지원합니다. CLI를 통한 간단한 변환부터 SDK를 활용한 동적 오디오 생성, Next.js API 라우트, Express.js 엔드포인트 통합까지 다양한 사용 사례를 다룹니다. 또한 입력 텍스트 전처리, 오류 처리, SDK 인스턴스 재사용과 같은 모범 사례를 제공합니다. 배치 처리, 다이내믹 콘텐츠 생성, 오디오북, 전자 학습, 음성 비서 등에 활용할 수 있습니다.

지원 대상~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 = 두 배 속도(빠르게)
  • 볼륨 범위: 0보다 크고 최대 10
    • 기본값: 1.0
    • 값은 0보다 크고(배타적) 10 이하(포함)여야 합니다.

형식 및 스트리밍

  • 스트리밍 제한: stream: true가 활성화되면 pcm 형식만 지원됩니다.
  • 비스트리밍: wav, pcm, mp3 형식을 지원합니다.
  • 샘플 레이트: 24000Hz(권장)

긴 텍스트 처리를 위한 모범 사례

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 객체에서 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;
}

// Usage
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;
}

// Usage
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 객체에서 array buffer 가져오기
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

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

// Usage - 느린 내레이션
await generateWithSpeed('This is an important announcement', 0.8, './slow.wav');

// Usage - 빠른 내레이션
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;
}

// Usage - 더 큰 소리
await generateWithVolume('This is an announcement', 5.0, './loud.wav');

// Usage - 더 작은 소리
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;
}

// Usage
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;
  }
}

// Usage
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();

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

    // Create SDK instance
    const zai = await ZAI.create();

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

    // Get array buffer from Response object
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(arrayBuffer));

    // Return audio as response
    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 객체에서 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;
}

// Usage
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(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
}

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

    if (!text || text.length > 1024) {
      return res.status(400).json({
        error: '텍스트는 필수이며 최대 1024자까지 가능합니다.'
      });
    }

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

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

    res.set({
      'Content-Type': 'audio/wav',
      'Content-Length': buffer.length.toString()
    });
    res.send(buffer);
  } catch (error) {
    console.error('TTS Error:', error);
    res.status(500).json({ error: '음성 생성 실패' });
  }
});

app.listen(3001, () => {
  console.log('TTS 서버가 포트 3001에서 실행 중입니다.');
});

오류 처리 예제

async function robustTTSGeneration(text, options = {}) {
  try {
    // 텍스트 준비
    const preparedText = prepareTextForTTS(text);

    // 긴 텍스트에 대한 청크 분할
    if (preparedText.length > 1000) {
      const chunks = splitTextIntoChunks(preparedText);
      const audioBuffers = [];

      for (const chunk of chunks) {
        const buffer = await generateAudio(chunk, options);
        audioBuffers.push(buffer);
      }

      // 청크 병합 로직
      return Buffer.concat(audioBuffers);
    }

    return await generateAudio(preparedText, options);
  } catch (error) {
    console.error('TTS 생성 실패:', error);
    throw error;
  }
}

문제 해결

일반적인 문제

  1. 입력 텍스트가 너무 김: 텍스트가 1024자를 초과하는 경우 splitTextIntoChunks 함수를 사용하여 분할하세요.

  2. 지원되지 않는 형식: 스트리밍 모드에서는 pcm 형식만 지원됩니다. 비스트리밍 모드에서는 wav, mp3, pcm을 사용하세요.

  3. 잘못된 속도 값: 속도가 0.5에서 2.0 사이인지 확인하세요.

  4. 잘못된 볼륨 값: 볼륨이 0보다 크고 10보다 작거나 같은지 확인하세요.

  5. SDK 인스턴스: 성능 향상을 위해 getZAIInstance()를 사용하여 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.

관련 스킬