Communitygithub.com

AcTR-app TTS (텍스트 음성 변환)

z-ai-web-dev-sdk를 사용하여 텍스트를 자연스러운 음성으로 변환(TTS)하는 기능을 구현합니다. 사용자가 텍스트를 음성으로 변환하거나, 오디오 콘텐츠를 만들고, 음성 기반 애플리케이션을 구축하거나, 음성 오디오 파일을 생성해야 할 때 이 기술을 사용하세요. 여러 음성, 조절 가능한 속도 및 다양한 오디오 형식을 지원합니다.

AcTR-app TTS (텍스트 음성 변환)란 무엇인가요?

이 기술은 z-ai-web-dev-sdk 패키지를 활용하여 텍스트를 자연스러운 음성 오디오로 변환하는 텍스트 음성 변환(TTS) 기능을 구현하는 방법을 안내합니다. 개발자는 제공되는 SDK를 통해 몇 줄의 코드로 강력한 TTS 기능을 애플리케이션에 통합할 수 있습니다. 이 기술은 CLI(명령줄 인터페이스)를 통한 빠른 변환과 SDK를 통한 심층적인 프로그래매틱 제어를 모두 지원합니다. 입력 텍스트는 최대 1024자로 제한되며, 긴 텍스트는 분할 처리가 권장됩니다. 음성 속도는 0.5~2.0 사이, 볼륨은 0 초과 10 이하로 조절 가능하며, wav, mp3, pcm 형식을 지원합니다. 특히 스트리밍 모드에서는 pcm 형식만 지원된다는 점을 유의해야 합니다. 이 기술은 Express.js, Next.js 등 다양한 백엔드 프레임워크와 통합하기 위한 예제 코드를 제공하며, 오디오북, 전자 학습, 음성 비서, 알림 시스템 등 다양한 사용 사례에 활용될 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Cetc2211/AcTR-app/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 형식을 지원합니다.
  • 샘플레이트: 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 패키지는 이미 설치되어 있습니다. 아래 예제와 같이 가져오기(import)하여 사용하십시오.

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 객체에서 arrayBuffer 가져오기
  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 객체에서 arrayBuffer 가져오기
  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 객체에서 arrayBuffer 가져오기
  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 객체에서 arrayBuffer 가져오기
  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 객체에서 arrayBuffer 가져오기
      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 객체에서 arrayBuffer 가져오기
    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 객체에서 arrayBuffer 가져오기
    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 객체에서 arrayBuffer 가져오기
    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. 전자 학습: 교육 콘텐츠 내레이션 생성
  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));

    const outputPath = path.join(outputDir, `tts-${Date.now()}.wav`);
    fs.writeFileSync(outputPath, buffer);

    res.json({ success: true, path: outputPath, size: buffer.length });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

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

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.

관련 스킬