openrouter-tts

openrouterteam/skills

Синтез речи из текста через TTS API OpenRouter.

Звёзды326
Форки62
Авторopenrouterteam
Обновлённоя 11 2026

Установка

SKILL.md

OpenRouter Text-to-Speech

Synthesize speech via POST /api/v1/audio/speech using curl. The endpoint is OpenAI-compatible, so the OpenAI SDKs work by pointing them at https://openrouter.ai/api/v1. Requires OPENROUTER_API_KEY (get one at https://openrouter.ai/keys). If unset, stop and ask.

One call, raw bytes back

The response body is the audio bytes — write them to a file with the extension matching response_format. It is not JSON; error responses are, so only try to parse JSON when the status is non-200.

Two response headers are worth keeping:

  • Content-Type — audio/mpeg for mp3; for pcm it includes the sample rate and channel count, e.g. audio/pcm;rate=24000;channels=1. Parse these parameters if you need to wrap the raw bytes into a WAV container.
  • X-Generation-Id — the generation ID (format gen-tts-<timestamp>-<suffix>), useful for tracking, debugging, and cost lookups.

Drop-in workflow

#!/usr/bin/env bash
set -euo pipefail

MODEL="openai/gpt-4o-mini-tts-2025-12-15"
VOICE="alloy"
FORMAT="mp3"                          # mp3 or pcm
INPUT="Hello! This is a text-to-speech test."
OUTPUT="speech-$(date +%Y%m%d-%H%M%S).${FORMAT}"
HEADERS=$(mktemp)

payload=$(jq -n --arg model "$MODEL" --arg input "$INPUT" \
               --arg voice "$VOICE" --arg fmt "$FORMAT" \
  '{model: $model, input: $input, voice: $voice, response_format: $fmt}')

http_code=$(curl -sS -X POST https://openrouter.ai/api/v1/audio/speech \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -D "$HEADERS" \
  --output "$OUTPUT" \
  -w '%{http_code}' \
  -d "$payload")

if [[ "$http_code" != "200" ]]; then
  echo "TTS failed (HTTP $http_code):" >&2
  cat "$OUTPUT" >&2                   # error body is JSON, not audio
  rm -f "$OUTPUT" "$HEADERS"
  exit 1
fi

gen_id=$(grep -i '^x-generation-id:' "$HEADERS" | awk '{print $2}' | tr -d '\r')
rm -f "$HEADERS"
echo "Saved $(realpath "$OUTPUT") (generation_id=${gen_id:-unknown})"

Discovering TTS models and voices

Filter the models endpoint by output modality to list speech models. Each model carries a supported_voices array with the exact voice IDs that provider accepts.

# Models + voices in one shot
curl -sS "https://openrouter.ai/api/v1/models?output_modalities=speech" \
  | jq '.data[] | {id, name, supported_voices, pricing}'

# Just the voices for a specific model
curl -sS "https://openrouter.ai/api/v1/models?output_modalities=speech" \
  | jq -r '.data[] | select(.id=="openai/gpt-4o-mini-tts-2025-12-15") | .supported_voices[]'

Voices are provider-namespaced: OpenAI uses short names (alloy, nova), Voxtral encodes language + persona + emotion (en_paul_happy), Kokoro prefixes with language/gender (af_bella = American female Bella).

Parameters

FieldRequiredNotes
modelyesTTS model slug (e.g. openai/gpt-4o-mini-tts-2025-12-15, mistralai/voxtral-mini-tts-2603).
inputyesThe text to synthesize.
voiceyesVoice identifier. Look up the exact set for your model in supported_voices on the models endpoint (see the discovery section above). Voices are provider-namespaced — e.g. alloy is an OpenAI voice and will not work on Voxtral or Kokoro.
response_formatnomp3 or pcm. Default is pcm. Set this explicitly — the default is usually not what a user wants to save.
speednoPlayback multiplier (e.g. 1.25). Honored by OpenAI TTS. Other providers may accept and ignore it, or reject unknown fields — check the provider's behavior if it matters.
providernoProvider passthrough — see below.

Picking a format

  • mp3 (audio/mpeg) — compressed, ready to play in any audio app. Default choice for files the user will listen to or share.
  • pcm (audio/pcm;rate=<rate>;channels=<n>) — uncompressed raw samples. The response Content-Type carries the sample rate and channel count (e.g. rate=24000;channels=1 for OpenAI TTS), which you'll need if you wrap the bytes into a WAV container. Lower latency for real-time streaming pipelines, but not directly playable on its own. Pick this only when the user explicitly wants raw audio or is piping into a streaming system.

Match the file extension to the format — saving pcm bytes as .mp3 produces a file no player will open, and this is the most common cause of "empty/corrupted audio" reports.

Provider-specific options

Provider passthrough goes under provider.options.<slug> and is only forwarded when that provider handles the request. The most useful one is OpenAI's instructions, which steers tone, accent, pacing, or emotion without retraining:

{
  "model": "openai/gpt-4o-mini-tts-2025-12-15",
  "input": "Welcome to the show.",
  "voice": "alloy",
  "response_format": "mp3",
  "provider": {
    "options": {
      "openai": {
        "instructions": "Speak in a warm, friendly tone with a slow pace."
      }
    }
  }
}

For other providers, check each provider's upstream docs for available passthrough keys — naming conventions vary (camelCase for OpenAI/Google, snake_case for most others).

OpenAI SDK compatibility

Because the endpoint mirrors OpenAI's /audio/speech, both OpenAI SDKs work by swapping the base URL. Prefer this when the user is already in a Python/TypeScript project and doesn't want to shell out.

# Python — streaming write to file
import os
from openai import OpenAI

client = OpenAI(base_url="https://openrouter.ai/api/v1",
                api_key=os.environ["OPENROUTER_API_KEY"])

with client.audio.speech.with_streaming_response.create(
    model="openai/gpt-4o-mini-tts-2025-12-15",
    input="The quick brown fox jumps over the lazy dog.",
    voice="nova",
    response_format="mp3",
) as response:
    response.stream_to_file("output.mp3")
// TypeScript — collect bytes, write once
import OpenAI from "openai";
import fs from "fs";

const client = new OpenAI({
  baseURL: "https://openrouter.ai/api/v1",
  apiKey: process.env.OPENROUTER_API_KEY!,
});

const response = await client.audio.speech.create({
  model: "openai/gpt-4o-mini-tts-2025-12-15",
  input: "The quick brown fox jumps over the lazy dog.",
  voice: "nova",
  response_format: "mp3",
});

await fs.promises.writeFile(
  "output.mp3",
  Buffer.from(await response.arrayBuffer()),
);

Long inputs

TTS models have per-request character limits (usually a few thousand characters) and are priced per character of input, so there's no penalty to splitting. For anything long (chapters, articles, scripts):

  1. Split the text at sentence or paragraph boundaries — never mid-word.
  2. Synthesize each chunk with the same model + voice so prosody stays consistent.
  3. Concatenate the resulting audio files. For mp3, ffmpeg -i "concat:part1.mp3|part2.mp3" -c copy out.mp3 works for simple cases; for mixed bitrates or tight seams, re-encode via ffmpeg -f concat -safe 0 -i list.txt output.mp3.

Splitting also improves time-to-first-audio if you stream chunks to a user as they're generated.

Troubleshooting

"Empty" or unplayable audio file — almost always a format/extension mismatch. Check Content-Type in the response headers: audio/pcm saved as .mp3 will not play. Either re-request with response_format: "mp3" or save with the matching extension.

400 with "Model X does not exist" — the slug is wrong. Use the full dated slug from the models endpoint (openai/gpt-4o-mini-tts-2025-12-15, not gpt-4o-mini-tts).

400 with a ZodError — a required field is missing or the wrong type. The body looks like {"success":false,"error":{"name":"ZodError","message":"[...]"}} — the nested message JSON string names the bad path (e.g. "path":["voice"]).

speed has no effect — the provider probably doesn't support it. OpenAI TTS honors it; for other providers, check upstream docs before relying on it.

References

  • TTS guide
  • Models page — filter to speech output

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: openrouter-tts](https://darkplay.ru/ai/skills/openrouterteam-skills-openrouter-tts)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

byom-reviewanthropics · Код-ревью любой моделью через OpenRouter: стандартные и состязательные проверки со…
38 комп.
consensusanthropics · Собирает разные точки зрения ИИ параллельно: Consensus опрашивает GPT-5.2, Gemini 3.1 Pro…
38 комп.
enzymeanthropics · Семантическая индексация заметок Obsidian: кластеры по концепциям и тематические вопросы.
38 комп.
octoanthropics · Мульти-LLM оркестрация для Claude Code и Cowork: 8 провайдеров, workflow Double Diamond…
38 комп.
openrouter-packjeremylongshore · Набор из 30 навыков для OpenRouter: маршрутизация LLM, выбор моделей и оптимизация затрат.
2 926 ★
openrouteropenrouterteam · Навыки для платформы OpenRouter
15 комп.
llm-routerjamesrochabrun · Маршрутизация запросов к LLM между провайдерами (OpenAI, Grok, Groq, DeepSeek) через…
46 комп.
openroutervm0-ai · OpenRouter API: маршрутизация запросов к сотням LLM через один OpenAI-совместимый…
156 комп.
Argus API Spend· Учёт расходов на API, балансов и запаса средств по OpenAI, Anthropic, OpenRouter и 25…
—
Banana Peel· OpenRouter для браузерных агентов. Один MCP для маршрутизации задач по 250+ исполнителям.
—

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для музыки, голоса и озвучки

Музыка, голос и озвучка

Подборка нейросетей для генерации музыки, голоса и озвучки. Сервисы, которые помогают создавать треки, синтезировать речь и чистить аудио без студии и дикторов. Подходит для видеом

TimbricaTimbrica
По запросу
5.0
BigspeakBigspeak
По запросу
5.0
WavToolWavtool
По запросу
5.0
LoquoraLoquora
Есть бесплатный тариф
4.9
WunjoWunjo
Есть бесплатный тариф
4.9
NexaraNexara
Есть бесплатный тариф
4.9
pitch coachApple
По запросу
4.9
audio-transcription.ruAudio-transcription
Есть бесплатный тариф
4.9
SoundfulSoundful
По запросу
4.9
TutDub
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8