Communitygithub.com

AiCurv/ADBCommander

Implementa funcionalidad de texto a voz (TTS) usando el z-ai-web-dev-sdk. Utiliza 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. Soporta múltiples voces, velocidad ajustable y varios formatos de audio.

¿Qué es ADBCommander?

Esta skill implementa funcionalidad de texto a voz (TTS) mediante el paquete z-ai-web-dev-sdk, permitiendo la conversión de texto en audio de voz con sonido natural. Es ideal para desarrolladores que buscan añadir capacidades de voz a aplicaciones web backend, Next.js, Express.js o scripts de automatización. La herramienta soporta múltiples voces (como tongtong, chuichui, xiaochen), rango de velocidad de 0.5 a 2.0, control de volumen de 0 a 10 y formatos de salida WAV, MP3 y PCM. Incluye advertencias importantes como el límite de 1024 caracteres por solicitud y la restricción de que solo el formato PCM es soportado cuando se usa streaming. Proporciona ejemplos de uso mediante CLI para tareas rápidas y SDK para integración profunda, así como fragmentos de código para procesamiento por lotes, generación dinámica y rutas API.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/AiCurv/ADBCommander/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 la conversión de texto en audio de voz con sonido natural.

Ruta de la Skill

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

Esta skill se encuentra en la ruta anterior 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.

Descripción General

Texto a Voz te permite construir aplicaciones que generan audio hablado a partir de texto de entrada, 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 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 = velocidad doble (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 soporta 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 desde CLI (Para Tareas Simples)

Para conversiones de texto a voz simples, puedes usar la CLI de z-ai en lugar de escribir código. Esto es ideal para generación rápida de audio, probar 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 Velocidad

# Usar 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á en streaming" -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 soporta 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 en línea de comandos

Usa SDK para:

  • Generación dinámica de audio en aplicaciones
  • Integración con servicios web
  • Tuberías personalizadas de procesamiento de audio
  • 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!', './salida.wav');

Múltiples Opciones de Voz

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 la API)
  // 0.5 = mitad de velocidad (más lento)
  // 1.0 = velocidad normal (predeterminado)
  // 2.0 = velocidad doble (más rápido)
  // Valores fuera de este rango causarán errores en la 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 la 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 suave
await generateWithVolume('Mensaje susurrado', 0.5, './suave.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 = [];

  // Asegurarse de 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, './salida-audio');
console.log('Generados:', results.length, 'archivos de audio');

Generación Dinámica de Contenido

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',
  './salida.wav',
  { speed: 1.2 }
);

Ejemplo de Ruta API de 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 en 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 }
    );
  }
}

Prácticas Recomendadas

1. Preparación del Texto

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

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

  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 excede 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 de texto
  4. Asistentes de Voz: Generar respuestas dinámicas
  5. Anuncios: Crear notificaciones de audio automatizadas
  6. Sistemas IVR: Generar mensajes de sistemas telefónicos
  7. Localización de Contenido: Crear audio en diferentes idiomas

Ejemplos de Integración

Endpoint API de 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 = './salida-audio';

async function initZAI() {
  zaiInstance = await ZAI.create();
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
}

app.post('/tts', async (req, res) => {
  try {
    const { text, voice, speed } = req.body;
    
    if (!text) {
      return res.status(400).json({ error: 'El texto es requerido' });
    }

    const zai = zaiInstance || await initZAI();
    
    const response = await zaiInstance.audio.tts.create({
      input: text.trim(),
      voice: voice || 'tongtong',
      speed: speed || 1.0,
      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.download(outputPath);
  } catch (error) {
    console.error('Error en TTS:', error);
    res.status(500).json({ error: 'Error generando audio' });
  }
});

app.listen(3000, () => {
  initZAI();
  console.log('Servidor escuchando en el puerto 3000');
});

Resolución de Problemas

Errores Comunes

  1. Límite de caracteres excedido

    • Asegúrate de que el texto de entrada no supere los 1024 caracteres
    • Usa la función splitTextIntoChunks para textos más largos
  2. Errores de velocidad fuera de rango

    • Asegúrate de que la velocidad esté entre 0.5 y 2.0
  3. Errores de formato de streaming

    • Cuando uses stream: true, usa solo formato pcm
  4. Errores de volumen

    • Asegúrate de que el volumen sea > 0 y <= 10

Problemas de Red

  • Asegúrate de la conexión a internet
  • Verifica que la API de z-ai esté accesible
  • Implementa reintentos para fallos transitorios

Referencia de la API

Parámetros de Entrada

ParámetroTipoPredeterminadoDescripción
inputstring-Texto a convertir (obligatorio, máx. 1024 caracteres)
voicestringtongtongVoz a usar: tongtong, chuichui, xiaochen, jam, kazi, douji, luodo
speednumber1.0Velocidad del habla (0.5-2.0)
volumenumber1.0Volumen del audio (>0 a 10)
response_formatstringwavFormato de salida: wav, mp3, pcm
streambooleanfalseHabilitar salida en streaming

Formato de Salida

  • Formato WAV: Calidad completa, compatible con la mayoría de reproductores
  • Formato MP3: Tamaño de archivo comprimido, ideal para almacenamiento
  • Formato PCM: Audio sin procesar, adecuado para streaming y procesamiento personalizado

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.

Skills relacionados