> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-es/audio-y-voz/melotts.md).

# MeloTTS

Ejecuta TTS multilingüe de alta calidad MeloTTS con inferencia rápida en GPUs de Clore.ai

MeloTTS es una biblioteca multilingüe de texto a voz de alta calidad desarrollada por **MyShell AI**. Ofrece síntesis de voz rápida y de sonido natural en varios idiomas y acentos del inglés, diseñada tanto para investigación como para despliegue en producción. MeloTTS está optimizado para la velocidad — puede generar voz significativamente más rápido que en tiempo real incluso en CPU — manteniendo una alta calidad de audio adecuada para uso comercial.

MeloTTS actualmente admite:

* **Inglés** (estadounidense, británico, indio, australiano, predeterminado)
* **Chino (simplificado y chino-inglés mixto)**
* **Japonés**
* **Coreano**
* **Español**
* **Francés**

Puntos destacados clave:

* ⚡ **Inferencia rápida** — más rápida que el tiempo real en CPU, rapidísima en GPU
* 🌍 **Multilingüe** — 6 idiomas con variantes de acento para inglés
* 🐳 **Listo para Docker** — imagen oficial de Docker disponible
* 🔌 **API REST** — API HTTP para integración en cualquier aplicación
* 📱 **De nivel de producción** — usado en los productos de consumo de MyShell

{% hint style="success" %}
Todos los ejemplos se pueden ejecutar en servidores GPU alquilados a través de [Marketplace de CLORE.AI](https://clore.ai/marketplace).
{% endhint %}

***

## Requisitos del servidor

| Parámetro | Mínimo                 | Recomendado             |
| --------- | ---------------------- | ----------------------- |
| GPU       | NVIDIA GTX 1080 (8 GB) | NVIDIA RTX 3090 (24 GB) |
| VRAM      | 4 GB                   | 8–16 GB                 |
| RAM       | 8 GB                   | 16 GB                   |
| CPU       | 4 núcleos              | 8 núcleos               |
| Disco     | 10 GB                  | 20 GB                   |
| SO        | Ubuntu 20.04+          | Ubuntu 22.04            |
| CUDA      | 11.7+ (opcional)       | 12.1+                   |
| Python    | 3.8+                   | 3.10                    |
| Puertos   | 22, 8888               | 22, 8888                |

{% hint style="info" %}
MeloTTS es excepcionalmente eficiente: funciona bien en CPU para solicitudes individuales y se beneficia enormemente de la GPU para el procesamiento por lotes. Incluso una GPU económica duplica drásticamente el rendimiento.
{% endhint %}

***

## Despliegue rápido en CLORE.AI

{% hint style="warning" %}
**Nota:** MeloTTS no tiene una imagen oficial preconstruida de Docker en Docker Hub (`myshell-ai/melotts` no existe). El enfoque recomendado es usar una imagen base de NVIDIA CUDA e instalar MeloTTS mediante pip desde el repositorio oficial de GitHub.
{% endhint %}

### 1. Encuentra un servidor adecuado

Ve a [Marketplace de CLORE.AI](https://clore.ai/marketplace) y filtra por:

* **VRAM**: ≥ 4 GB (o solo CPU para bajo volumen)
* **GPU**: Cualquier GPU NVIDIA (GTX 1080+, serie RTX, A100)
* **Disco**: ≥ 10 GB

### 2. Configura tu despliegue

**Imagen de Docker:**

```
nvidia/cuda:12.8.1-devel-ubuntu22.04
```

**Mapeos de puertos:**

```
22   → Acceso SSH
8888 → servidor API de MeloTTS
```

**Variables de entorno:**

```
NVIDIA_VISIBLE_DEVICES=all
```

**Comando de inicio** (ejecutar después de conectarse por SSH al servidor):

```bash
apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git && \
git clone https://github.com/myshell-ai/MeloTTS.git && \
cd MeloTTS && pip install -e . && \
python -m unidic download && \
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')" && \
python -m melo.api_server --host 0.0.0.0 --port 8888
```

### 3. Acceder a la API

```
http://<your-clore-server-ip>:8888
```

Prueba con:

```bash
curl -X POST http://<server-ip>:8888/synthesize \
  -H "Content-Type: application/json" \\
  -d '{"text": "¡Hola desde Clore.ai!", "language": "EN", "speaker_id": "EN-Default"}'
```

***

## Configuración paso a paso

### Paso 1: conéctate por SSH a tu servidor

```bash
ssh root@<la-ip-de-tu-servidor-clore> -p <puerto-ssh>
```

### Paso 2: Construir y ejecutar el contenedor

Dado que MeloTTS no tiene una imagen de Docker Hub preconstruida, usa una base NVIDIA CUDA e instala MeloTTS desde el código fuente:

```bash
# Ejecuta un contenedor CUDA e instala MeloTTS dentro de él
docker run -d \\
  --name melotts \
  --gpus all \\
  -p 8888:8888 \
  -v /workspace/melotts/outputs:/app/outputs \
  -e NVIDIA_VISIBLE_DEVICES=all \
  nvidia/cuda:12.8.1-devel-ubuntu22.04 \
  bash -c "apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git && \
    git clone https://github.com/myshell-ai/MeloTTS.git /app/MeloTTS && \
    cd /app/MeloTTS && pip install -e . && \
    python -m unidic download && \
    python3 -c \"import nltk; nltk.download('averaged_perceptron_tagger_eng')\" && \
    python -m melo.api_server --host 0.0.0.0 --port 8888"
```

Alternativamente, construye una imagen Docker personalizada desde el código fuente:

```bash
git clone https://github.com/myshell-ai/MeloTTS.git
cd MeloTTS
docker build -t melotts:local .
docker run -d \\
  --name melotts \
  --gpus all \\
  -p 8888:8888 \
  melotts:local
```

### Paso 3: Verificar que el servicio se está ejecutando

```bash
# Compruebe los registros del contenedor
docker logs -f melotts

# Espera a que arranque y luego prueba
curl http://localhost:8888/health
```

### Paso 4: Alternativa — interfaz de Jupyter Notebook

```bash
docker run -d \\
  --name melotts-jupyter \
  --gpus all \\
  -p 8888:8888 \
  nvidia/cuda:12.8.1-devel-ubuntu22.04 \
  bash -c "pip install jupyter melo-tts && \
    jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root"
```

Accede en: `http://<server-ip>:8888`

### Paso 5: Instalar desde pip (sin Docker)

```bash
# Instala las dependencias del sistema
apt-get install -y python3-pip ffmpeg espeak-ng

# Instala MeloTTS
pip install melo-tts

# Descarga los datos de NLTK requeridos
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')"
```

***

## Ejemplos de uso

### Ejemplo 1: TTS básico en inglés (Python)

```python
from melo.api import TTS

# Inicializar TTS en inglés
speed = 1.0  # Ajustar la velocidad del habla (0.5 = lento, 2.0 = rápido)
device = 'cuda'  # Usa 'cpu' si no hay GPU disponible

tts = TTS(language='EN', device=device)

# Obtener los IDs de altavoz disponibles
speakers = tts.hps.data.spk2id
print("Altavoces disponibles:", list(speakers.keys()))
# Salida: ['EN-Default', 'EN-US', 'EN-GB', 'EN-India', 'EN-Australia', 'EN-Brazil']

# Generar voz
speaker_ids = tts.hps.data.spk2id
output_path = "output_english.wav"

tts.tts_to_file(
    text="Bienvenido a Clore.ai, tu mercado en la nube de GPU para cargas de trabajo de IA. Alquila potentes GPU en minutos.",
    speaker_id=speaker_ids['EN-Default'],
    output_path=output_path,
    speed=speed
)

print(f"Guardado en: {output_path}")
```

***

### Ejemplo 2: TTS multilingüe

```python
from melo.api import TTS

device = 'cuda'

# Definir pares idioma-texto
language_texts = [
    ('EN', 'EN-US', "La computación en GPU ha transformado la investigación y el desarrollo de la inteligencia artificial."),
    ('EN', 'EN-GB', "El Reino Unido lidera Europa en inversión e innovación en IA."),
    ('ZH', 'ZH', "Clore.ai es un mercado de computación en la nube con GPU descentralizado que ofrece potencia de cálculo a los desarrolladores de IA."),
    ('JP', 'JP', "El desarrollo de la inteligencia artificial requiere recursos de cálculo a gran escala."),
    ('KR', 'KR', "Clore.ai es un mercado de nube GPU para investigadores de IA."),
    ('SP', 'SP', "La inteligencia artificial está transformando todas las industrias del mundo."),
    ('FR', 'FR', "La inteligencia artificial está revolucionando la forma en que trabajamos y vivimos."),
]

for lang, speaker, text in language_texts:
    try:
        tts = TTS(language=lang, device=device)
        speaker_id = tts.hps.data.spk2id[speaker]

        output_file = f"output_{lang}_{speaker}.wav"
        tts.tts_to_file(text=text, speaker_id=speaker_id, output_path=output_file)
        print(f"✓ Generado [{lang}]: {output_file}")
    except Exception as e:
        print(f"✗ Error [{lang}]: {e}")
```

***

### Ejemplo 3: Uso de la API REST

```python
import requests
import json

API_BASE = "http://<your-clore-server-ip>:8888"

# Comprobar las voces disponibles
response = requests.get(f"{API_BASE}/voices")
print("Voces disponibles:", json.dumps(response.json(), indent=2))

# Sintetizar voz
def synthesize(text, language="EN", speaker="EN-Default", speed=1.0):
    payload = {
        "text": text,
        "language": language,
        "speaker_id": speaker,
        "speed": speed,
        "format": "wav"
    }

    response = requests.post(
        f"{API_BASE}/synthesize",
        json=payload,
        timeout=30
    )

    if response.status_code == 200:
        return response.content
    else:
        raise Exception(f"Error de la API: {response.status_code} - {response.text}")

# Generar muestras
samples = [
    ("Hola, esto es MeloTTS ejecutándose en los servidores GPU de Clore.ai.", "EN", "EN-US"),
    ("Esta es la variante de acento del inglés británico.", "EN", "EN-GB"),
    ("Déjame demostrar el acento del inglés indio.", "EN", "EN-India"),
]

for text, lang, speaker in samples:
    audio_bytes = synthesize(text, lang, speaker)
    filename = f"api_output_{speaker.replace('-', '_')}.wav"
    with open(filename, "wb") as f:
        f.write(audio_bytes)
    print(f"Guardado: {filename}")
```

***

### Ejemplo 4: Procesamiento por lotes de alta velocidad

```python
from melo.api import TTS
from concurrent.futures import ThreadPoolExecutor
import soundfile as sf
import time
import numpy as np
from pathlib import Path

device = 'cuda'
tts = TTS(language='EN', device=device)
speaker_id = tts.hps.data.spk2id['EN-US']

# Lote grande de textos
texts = [
    f"Esta es la oración número {i}. Demuestra el procesamiento por lotes rápido con MeloTTS en la infraestructura GPU de Clore.ai."
    for i in range(1, 51)  # 50 oraciones
]

output_dir = Path("batch_output")
output_dir.mkdir(exist_ok=True)

start_time = time.time()

# Procesar el lote
for i, text in enumerate(texts):
    output_path = str(output_dir / f"batch_{i+1:03d}.wav")
    tts.tts_to_file(
        text=text,
        speaker_id=speaker_id,
        output_path=output_path,
        speed=1.0,
        quiet=True
    )
    if (i + 1) % 10 == 0:
        elapsed = time.time() - start_time
        print(f"Progreso: {i+1}/50 | Tiempo: {elapsed:.1f}s | Velocidad: {(i+1)/elapsed:.1f} oraciones/seg")

total_time = time.time() - start_time
print(f"\nLote completo: {len(texts)} oraciones en {total_time:.1f}s")
print(f"Promedio: {total_time/len(texts)*1000:.0f}ms por oración")
```

***

### Ejemplo 5: TTS mixto chino-inglés

```python
from melo.api import TTS

device = 'cuda'
tts = TTS(language='ZH', device=device)
speaker_id = tts.hps.data.spk2id['ZH']

# Texto en idioma mixto (chino + inglés)
mixed_texts = [
    "Usamos los servidores GPU de Clore.ai para ejecutar cargas de trabajo de aprendizaje automático.",
    "La conferencia de IA de hoy discutió los modelos de lenguaje de gran tamaño y la tecnología de síntesis de voz.",
    "Mi startup necesita recursos de GPU para entrenar nuestro modelo de aprendizaje profundo.",
    "Clore.ai ofrece precios muy competitivos, mucho más baratos que AWS y GCP.",
]

for i, text in enumerate(mixed_texts):
    output_file = f"mixed_zh_en_{i+1}.wav"
    tts.tts_to_file(
        text=text,
        speaker_id=speaker_id,
        output_path=output_file,
        speed=0.9  # Un poco más lento para mayor claridad
    )
    print(f"Generado: {output_file}")
    print(f"  Texto: {text[:60]}...")
```

***

## Configuración

### Configuración con Docker Compose

Dado que MeloTTS no tiene una imagen oficial de Docker Hub, usa la imagen base de NVIDIA CUDA e instala MeloTTS desde el código fuente al iniciar:

```yaml
version: '3.8'

services:
  melotts:
    image: nvidia/cuda:12.8.1-devel-ubuntu22.04
    container_name: melotts
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
      - PYTHONDONTWRITEBYTECODE=1
    ports:
      - "8888:8888"
    volumes:
      - ./outputs:/app/outputs
      - ./cache:/root/.cache
    command: >
      bash -c "apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git &&
      git clone https://github.com/myshell-ai/MeloTTS.git /app/MeloTTS &&
      cd /app/MeloTTS && pip install -e . &&
      python -m unidic download &&
      python3 -c 'import nltk; nltk.download(\"averaged_perceptron_tagger_eng\")' &&
      python -m melo.api_server --host 0.0.0.0 --port 8888"
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8888/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
```

### Opciones de configuración de la API

| Parámetro   | Valor predeterminado | Descripción                                       |
| ----------- | -------------------- | ------------------------------------------------- |
| `--host`    | `127.0.0.1`          | Dirección de enlace (usar `0.0.0.0` para público) |
| `--port`    | `8888`               | Puerto del servidor API                           |
| `--workers` | `1`                  | Número de procesos de trabajo                     |
| `--device`  | `auto`               | `cuda`, `cpu`, o `auto`                           |

### Idiomas y altavoces compatibles

| Idioma  | Código | IDs de altavoz                                                          |
| ------- | ------ | ----------------------------------------------------------------------- |
| Inglés  | `EN`   | `EN-Default`, `EN-US`, `EN-GB`, `EN-India`, `EN-Australia`, `EN-Brazil` |
| Chino   | `ZH`   | `ZH`                                                                    |
| Japonés | `JP`   | `JP`                                                                    |
| Coreano | `KR`   | `KR`                                                                    |
| Español | `SP`   | `SP`                                                                    |
| Francés | `FR`   | `FR`                                                                    |

***

## Consejos de rendimiento

### 1. Benchmark GPU vs CPU

Rendimiento de MeloTTS (RTF = factor de tiempo real, más bajo es mejor):

| Dispositivo     | RTF     | Notas                                   |
| --------------- | ------- | --------------------------------------- |
| CPU (8 núcleos) | \~0.3x  | Rápido, ideal para poca carga           |
| RTX 3080        | \~0.05x | 20 veces más rápido que el tiempo real  |
| RTX 4090        | \~0.02x | 50 veces más rápido que el tiempo real  |
| A100            | \~0.01x | 100 veces más rápido que el tiempo real |

### 2. Optimizar para rendimiento

```python
# Desactivar el cálculo de gradientes para la inferencia
import torch

with torch.no_grad():
    tts.tts_to_file(text, speaker_id, output_path)
```

### 3. Precalentar el modelo

```python
# Ejecutar una inferencia de calentamiento para cargar los kernels de CUDA
tts.tts_to_file(
    text="warmup",
    speaker_id=speaker_id,
    output_path="/dev/null"
)
print("Modelo precalentado, listo para inferencia rápida")
```

### 4. Ajustar la calidad de audio frente a la velocidad

```python
# Más rápido (calidad ligeramente inferior)
tts.tts_to_file(text, speaker_id, output_path, speed=1.2)

# Habla más lenta (mejor articulación)
tts.tts_to_file(text, speaker_id, output_path, speed=0.8)
```

### 5. Eficiencia de memoria

```python
# Liberar memoria de la GPU entre lotes grandes
import gc
import torch

gc.collect()
torch.cuda.empty_cache()
```

***

## Solución de problemas

### Problema: `espeak-ng` no encontrado

```bash
apt-get install -y espeak-ng
python3 -c "import phonemizer; print('phonemizer OK')"
```

### Problema: faltan datos de NLTK

```bash
python3 -c "
import nltk
nltk.download('averaged_perceptron_tagger_eng')
nltk.download('punkt')
"
```

### Problema: el puerto 8888 entra en conflicto con Jupyter

MeloTTS usa el puerto 8888 de forma predeterminada, lo que choca con Jupyter Notebook. Soluciones:

```bash
# Opción 1: Ejecutar MeloTTS en un puerto diferente
python -m melo.api_server --host 0.0.0.0 --port 8889

# Opción 2: Ejecutar Jupyter en un puerto diferente
jupyter notebook --port 8890
```

### Problema: el texto chino no se representa correctamente

```bash
# Instalar soporte para chino
pip install jieba
apt-get install -y python3-opencc

# Prueba
python3 -c "from melo.api import TTS; t = TTS('ZH'); print('ZH OK')"
```

### Problema: falla la descarga de la imagen de Docker

```bash
# Compila desde el código fuente en su lugar
git clone https://github.com/myshell-ai/MeloTTS.git
cd MeloTTS
pip install -e .
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')"
```

### Problema: inferencia lenta en GPU

```bash
# Verificar que se esté usando la GPU
python3 -c "
import torch
from melo.api import TTS
tts = TTS('EN', device='cuda')
print(f'Dispositivo: {next(tts.model.parameters()).device}')
print(f'CUDA disponible: {torch.cuda.is_available()}')
"
```

***

## Recomendaciones de GPU para Clore.ai

MeloTTS es ligero — funciona bien en CPU para bajo volumen y escala linealmente con el cómputo de GPU. No necesitas hardware caro.

| GPU       | VRAM  | Precio de Clore.ai                        | RTF (factor de tiempo real) | Capacidad             |
| --------- | ----- | ----------------------------------------- | --------------------------- | --------------------- |
| Solo CPU  | —     | \~$0.02/h                                 | \~0.3×                      | \~3 solicitudes/min   |
| RTX 3090  | 24 GB | $0.07–0.21/h                              | \~0.02× (50× tiempo real)   | \~100 solicitudes/min |
| RTX 4090  | 24 GB | $0.14–0.42/h                              | \~0.01× (100× tiempo real)  | \~200 solicitudes/min |
| A100 40GB | 40 GB | [bare metal](https://clore.ai/bare-metal) | \~0.005× (200× tiempo real) | \~400 solicitudes/min |

{% hint style="info" %}
**La mejor relación calidad-precio para cargas de trabajo TTS:** La RTX 3090 a 0,07–0,21 $/h ofrece velocidad TTS 50 veces superior al tiempo real. Para una API de producción que atiende a cientos de usuarios, esto es más que suficiente. Las instancias solo CPU (0,07–0,21 $/h) funcionan bien para desarrollo y despliegues con poco tráfico.
{% endhint %}

**Recomendación para producción:** Para una API TTS multilingüe que atiende a 10–50 usuarios concurrentes, la RTX 3090 es el punto ideal. Escala horizontalmente (múltiples instancias) en lugar de actualizar a una costosa A100 — MeloTTS no se beneficia de forma proporcional de GPUs de gama alta.

***

## Enlaces

* **GitHub**: <https://github.com/myshell-ai/MeloTTS>
* **Docker**: No hay imagen oficial en Docker Hub — instalar desde [código fuente de GitHub](https://github.com/myshell-ai/MeloTTS) usando `nvidia/cuda:12.8.1-devel-ubuntu22.04` imagen base
* **Artículo**: <https://arxiv.org/abs/2406.06753>
* **Hugging Face**: <https://huggingface.co/myshell-ai/MeloTTS-English>
* **MyShell AI**: <https://myshell.ai>
* **Marketplace de CLORE.AI**: <https://clore.ai/marketplace>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-es/audio-y-voz/melotts.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
