Communitygithub.com

Cetc2211/AcTR-app

Implementa capacidades de texto a voz (TTS) usando el z-ai-web-dev-sdk. Usa esta skill cuando el usuario necesite convertir texto en voz natural, crear contenido de audio, construir aplicaciones activadas por voz o generar archivos de audio hablado. Soporta múltiples voces, velocidad ajustable y varios formatos de audio.

¿Qué es AcTR-app?

Esta skill proporciona una guía completa para implementar funcionalidad de texto a voz (TTS) utilizando el paquete z-ai-web-dev-sdk, permitiendo convertir texto en audio de voz de sonido natural. Es útil para desarrolladores que construyen aplicaciones que requieren generación de audio a partir de texto, como audiolibros, narraciones de e-learning, asistentes de voz y sistemas de notificación automatizada. La skill soporta múltiples plataformas incluyendo aplicaciones Node.js, API REST con Express.js y Next.js. Incluye instrucciones detalladas para uso básico y avanzado, manejo de múltiples voces, velocidades ajustables (0.5-2.0), control de volumen y formatos de salida como WAV, MP3 y PCM. También cubre limitaciones importantes de la API como el límite de 1024 caracteres por solicitud y restricciones de streaming. Proporciona ejemplos de código para implementación directa, procesamiento por lotes, generación de contenido dinámico y mejores prácticas como manejo de errores, preparación de texto y reutilización de instancias SDK.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Cetc2211/AcTR-app/tree/HEAD/skills/TTS

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Skill de TTS (Texto a Voz)

Esta skill guía la implementación de funcionalidad de texto a voz (TTS) usando el paquete z-ai-web-dev-sdk, permitiendo convertir texto en audio de voz de sonido natural.

Ruta de la Skill

Ubicación de la Skill: {project_path}/skills/TTS

Esta skill se encuentra en la ruta anterior dentro de tu proyecto.

Scripts de Referencia: Hay scripts de prueba de ejemplo disponibles en el directorio {Skill Location}/scripts/ para pruebas rápidas y referencia. Consulta {Skill Location}/scripts/tts.ts para un ejemplo funcional.

Resumen

El texto a voz te permite construir aplicaciones que generan audio hablado a partir de entrada de texto, soportando varias voces, velocidades y formatos de salida para diversos casos de uso.

IMPORTANTE: z-ai-web-dev-sdk DEBE usarse solo en código de backend. Nunca lo uses en código del lado del cliente.

Limitaciones y Restricciones de la API

Antes de implementar la funcionalidad TTS, ten en cuenta estas limitaciones importantes:

Restricciones del Texto de Entrada

  • Longitud máxima: 1024 caracteres por solicitud
  • El texto que exceda este límite debe dividirse en fragmentos más pequeños

Parámetros de Audio

  • Rango de velocidad: 0.5 a 2.0
    • 0.5 = mitad de velocidad (más lento)
    • 1.0 = velocidad normal (predeterminado)
    • 2.0 = doble velocidad (más rápido)
  • Rango de volumen: Mayor que 0, hasta 10
    • Predeterminado: 1.0
    • Los valores deben ser mayores que 0 (exclusivo) y hasta 10 (inclusive)

Formato y Streaming

  • Limitación de streaming: Cuando stream: true está habilitado, solo se admite el formato pcm
  • Sin streaming: Soporta formatos wav, pcm y mp3
  • Frecuencia de muestreo: 24000 Hz (recomendado)

Mejor Práctica para Texto Largo

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

Prerrequisitos

El paquete z-ai-web-dev-sdk ya está instalado. Impórtalo como se muestra en los ejemplos a continuación.

Uso de CLI (Para Tareas Simples)

Para conversiones simples de texto a voz, puedes usar la CLI de z-ai en lugar de escribir código. Esto es ideal para generación rápida de audio, prueba de voces o automatización simple.

TTS Básico

# Convertir texto a voz (formato WAV predeterminado)
z-ai tts --input "Hola, mundo" --output ./hola.wav

# Usando opciones cortas
z-ai tts -i "Hola, mundo" -o ./hola.wav

Diferentes Voces y Velocidades

# Usar una voz específica
z-ai tts -i "Bienvenido a nuestro servicio" -o ./bienvenido.wav --voice tongtong

# Ajustar velocidad del habla (0.5-2.0)
z-ai tts -i "Este es un habla más rápida" -o ./rapido.wav --speed 1.5

# Habla más lenta
z-ai tts -i "Este es un habla más lenta" -o ./lento.wav --speed 0.8

Diferentes Formatos de Salida

# Formato MP3
z-ai tts -i "Hola Mundo" -o ./hola.mp3 --format mp3

# Formato WAV (predeterminado)
z-ai tts -i "Hola Mundo" -o ./hola.wav --format wav

# Formato PCM
z-ai tts -i "Hola Mundo" -o ./hola.pcm --format pcm

Salida en Streaming

# Generación de audio en streaming
z-ai tts -i "Este es un texto más largo que se transmitirá" -o ./stream.wav --stream

Parámetros de CLI

  • --input, -i <texto>: Requerido - Texto a convertir en voz (máx. 1024 caracteres)
  • --output, -o <ruta>: Requerido - Ruta del archivo de audio de salida
  • --voice, -v <voz>: Opcional - Tipo de voz (predeterminado: tongtong)
  • --speed, -s <número>: Opcional - Velocidad del habla, 0.5-2.0 (predeterminado: 1.0)
  • --format, -f <formato>: Opcional - Formato de salida: wav, mp3, pcm (predeterminado: wav)
  • --stream: Opcional - Habilitar salida en streaming (solo admite formato pcm)

Cuándo Usar CLI vs SDK

Usa CLI para:

  • Conversiones rápidas de texto a voz
  • Probar diferentes voces y velocidades
  • Generación simple de audio por lotes
  • Scripts de automatización de línea de comandos

Usa SDK para:

  • Generación dinámica de audio en aplicaciones
  • Integración con servicios web
  • Procesamiento de audio personalizado
  • Aplicaciones de producción con requisitos complejos

Implementación Básica de TTS

Texto a Voz Simple

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
  });

  // Obtener array buffer del objeto Response
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

  fs.writeFileSync(outputPath, buffer);
  console.log(`Audio guardado en ${outputPath}`);
  return outputPath;
}

// Uso
await textToSpeech('¡Hola, mundo!', './output.wav');

Opciones de Múltiples Voces

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, // Voces disponibles: tongtong, chuichui, xiaochen, jam, kazi, douji, luodo
    speed: 1.0,
    response_format: 'wav',
    stream: false
  });

  // Obtener array buffer del objeto Response
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

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

// Uso
await generateWithVoice('Bienvenido a nuestro servicio', 'tongtong', './bienvenido.wav');

Velocidad Ajustable

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function generateWithSpeed(text, speed, outputPath) {
  const zai = await ZAI.create();

  // Rango de velocidad: 0.5 a 2.0 (restricción de API)
  // 0.5 = mitad de velocidad (más lento)
  // 1.0 = velocidad normal (predeterminado)
  // 2.0 = doble velocidad (más rápido)
  // Los valores fuera de este rango causarán errores de API

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

  // Obtener array buffer del objeto Response
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

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

// Uso - narración más lenta
await generateWithSpeed('Este es un anuncio importante', 0.8, './lento.wav');

// Uso - narración más rápida
await generateWithSpeed('Actualización rápida', 1.3, './rapido.wav');

Volumen Ajustable

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function generateWithVolume(text, volume, outputPath) {
  const zai = await ZAI.create();

  // Rango de volumen: mayor que 0, hasta 10 (restricción de API)
  // Los valores deben ser > 0 (exclusivo) y <= 10 (inclusive)
  // Predeterminado: 1.0 (volumen normal)

  const response = await zai.audio.tts.create({
    input: text,
    voice: 'tongtong',
    speed: 1.0,
    volume: volume, // Parámetro opcional
    response_format: 'wav',
    stream: false
  });

  // Obtener array buffer del objeto Response
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(new Uint8Array(arrayBuffer));

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

// Uso - audio más fuerte
await generateWithVolume('Este es un anuncio', 5.0, './fuerte.wav');

// Uso - audio más bajo
await generateWithVolume('Mensaje susurrado', 0.5, './bajo.wav');

Casos de Uso Avanzados

Procesamiento por Lotes

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 = [];

  // Asegurar que el directorio de salida exista
  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
      });

      // Obtener array buffer del objeto 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;
}

// Uso
const texts = [
  'Bienvenido al capítulo uno',
  'Bienvenido al capítulo dos',
  'Bienvenido al capítulo tres'
];

const results = await batchTextToSpeech(texts, './audio-output');
console.log('Generados:', results.length, 'archivos de audio');

Generación de Contenido Dinámico

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
    });

    // Obtener array buffer del objeto 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;
  }
}

// Uso
const generator = new TTSGenerator();
await generator.initialize();

await generator.saveAudio(
  'Hola, esto es una prueba',
  './output.wav',
  { speed: 1.2 }
);

Ejemplo de Ruta API en Next.js

import { NextRequest, NextResponse } from 'next/server';

export async function POST(req: NextRequest) {
  try {
    const { text, voice = 'tongtong', speed = 1.0 } = await req.json();

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

    // Crear instancia del SDK
    const zai = await ZAI.create();

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

    // Obtener array buffer del objeto Response
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(arrayBuffer));

    // Devolver audio como respuesta
    return new NextResponse(buffer, {
      status: 200,
      headers: {
        'Content-Type': 'audio/wav',
        'Content-Length': buffer.length.toString(),
        'Cache-Control': 'no-cache',
      },
    });
  } catch (error) {
    console.error('Error de API TTS:', error);

    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : 'Error al generar el audio, inténtalo de nuevo más tarde',
      },
      { status: 500 }
    );
  }
}

Mejores Prácticas

1. Preparación del Texto

function prepareTextForTTS(text) {
  // Eliminar espacios en blanco excesivos
  text = text.replace(/\s+/g, ' ').trim();

  // Expandir abreviaturas comunes para mejor pronunciación
  const abbreviations = {
    'Dr.': 'Doctor',
    'Mr.': 'Señor',
    'Mrs.': 'Señora',
    'etc.': 'etcétera'
  };

  for (const [abbr, full] of Object.entries(abbreviations)) {
    text = text.replace(new RegExp(abbr, 'g'), full);
  }

  return text;
}

2. Manejo de Errores

import ZAI from 'z-ai-web-dev-sdk';
import fs from 'fs';

async function safeTTS(text, outputPath) {
  try {
    // Validar entrada
    if (!text || text.trim().length === 0) {
      throw new Error('La entrada de texto no puede estar vacía');
    }

    if (text.length > 1024) {
      throw new Error('La entrada de texto supera la longitud máxima de 1024 caracteres');
    }

    const zai = await ZAI.create();

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

    // Obtener array buffer del objeto 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('Error TTS:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

3. Reutilización de la Instancia del SDK

import ZAI from 'z-ai-web-dev-sdk';

// Crear una instancia singleton
let zaiInstance = null;

async function getZAIInstance() {
  if (!zaiInstance) {
    zaiInstance = await ZAI.create();
  }
  return zaiInstance;
}

// Uso
const zai = await getZAIInstance();
const response = await zai.audio.tts.create({ ... });

Casos de Uso Comunes

  1. Audiolibros y Podcasts: Convertir contenido escrito a formato de audio
  2. E-learning: Crear narración para contenido educativo
  3. Accesibilidad: Proporcionar versiones de audio de contenido textual
  4. Asistentes de Voz: Generar respuestas dinámicas
  5. Anuncios: Crear notificaciones de audio automatizadas
  6. Sistemas IVR: Generar mensajes para sistemas telefónicos
  7. Localización de Contenido: Crear audio en diferentes idiomas

Ejemplos de Integración

Endpoint de API en Express.js

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, format = 'wav' } = req.body;

    // Validar longitd del texto
    if (!text || text.length > 1024) {
      return res.status(400).json({ error: 'La entrada de texto debe tener entre 1 y 1024 caracteres' });
    }

    // Generar nombre de archivo único
    const filename = `audio_${Date.now()}.${format}`;
    const outputPath = path.join(outputDir, filename);

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

    // Obtener array buffer del objeto Response
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(new Uint8Array(arrayBuffer));

    fs.writeFileSync(outputPath, buffer);

    res.json({
      success: true,
      filename,
      path: outputPath,
      size: buffer.length,
    });
  } catch (error) {
    console.error('Error de TTS:', error);
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Servidor TTS iniciado en el puerto 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.

Skills relacionados