๐ Supernal TTS API Documentation
:::caution Under Development The Supernal TTS API is currently in active development. Some features may be incomplete, unstable, or subject to breaking changes. Please use with caution in production environments. :::
Base URLโ
https://tts.supernal.ai/api/v1
Authenticationโ
Currently, the API is open for development. In production, add authentication headers:
Authorization: Bearer YOUR_API_KEY
Endpointsโ
1. Generate Audioโ
Generate TTS audio from text, with automatic caching.
Endpoint: POST /generate
Request Body:
{
"text": "The text to convert to speech",
"options": {
"provider": "openai", // optional: openai, cartesia, azure, mock
"voice": "fable", // optional: provider-specific voice
"speed": 1.0, // optional: 0.25 to 4.0
"format": "mp3", // optional: mp3, wav, ogg
"quality": "medium", // optional: low, medium, high
"language": "en-US", // optional: language code
"cache": true, // optional: enable caching (default: true)
"ttl": 86400, // optional: cache TTL in seconds
"private": false // optional: owner-only audio, see "Private audio" below
},
"metadata": {
"contentId": "blog-post-123",
"userId": "user-456",
"tags": ["blog", "tech"],
"priority": 1
}
}
Response:
{
"hash": "a1b2c3d4e5f6...",
"audioUrl": "/api/v1/audio/a1b2c3d4e5f6",
"cached": false,
"duration": 12.5,
"cost": 0.0045,
"metadata": {
"provider": "openai",
"voice": "fable",
"generatedAt": "2024-01-20T10:30:00Z",
"fileSize": 245760
}
}
Status Codes:
200- Success400- Invalid request429- Rate limit exceeded500- Server error
Example:
curl -X POST https://tts.supernal.ai/api/v1/generate \
-H "Content-Type: application/json" \
-d '{
"text": "Hello world!",
"options": {
"provider": "openai",
"voice": "nova"
}
}'
Private audioโ
Set "private": true in options when the narration must not be shared, for example a story a buyer paid for. A private result behaves differently from normal cached audio:
- It is stored under a random id that starts with
prv_, not under a hash of the text. Nobody can work the id out from the text. /hash-lookupand/hash-existsnever find it, and it never fills the shared cache. A later public request for the same text generates fresh audio.- The server keeps no copy of the text with it. Its metadata returns an empty
originalText. - Only the key or user token that generated it can read it. A request without credentials gets
401. Any other key gets404. - It is always sent with
Cache-Control: private, no-store. - It expires 90 days after generation (operators can change this with
TTS_PRIVATE_AUDIO_TTL_DAYS). The response carriesexpiresAt, and after that time the audio answers404, even to its owner. - Each owner can make 50 private generations per day (
TTS_PRIVATE_DAILY_CAP). Past that the API answers429 PRIVATE_DAILY_CAP_EXCEEDED. A generation that fails still counts. - The text may be at most 20,000 characters (
TTS_PRIVATE_MAX_CHARS). A request whose audio could exceed 50 MB (TTS_PRIVATE_MAX_BYTES) is refused before any provider is called, with400 PRIVATE_TEXT_TOO_LONGor400 PRIVATE_AUDIO_TOO_LARGE. Uncompressed formats reach that limit sooner. - The owner can delete it with
DELETE /audio/{id}. Any other caller gets404, and the route does not delete public audio.
On deployed storage (Supabase or Redis+S3) only a user (JWT) token can own private audio. sk-tts- API keys are kept in server memory and get new ids when the server restarts, so they are refused there. On local disk storage, which private mode allows only when NODE_ENV is development or test, a sk-tts- key used from a server (no Origin header) can own it. Browser keys paired to a website origin are shared by every visitor of that site and can never own private audio. Every refusal answers 403 PRIVATE_REQUIRES_OWNER. Because an <audio> tag cannot send an Authorization header, play private audio through your own backend, which fetches it with the owner's token and passes it to the buyer.
The response looks like a normal generate response, with "private": true, the prv_ id in hash and audioUrl, and no hashes field. Private mode works on POST /generate only. POST /generate-progressive answers 400 PRIVATE_NOT_SUPPORTED.
If the server has no private storage set up, private requests get 503 PRIVATE_MODE_NOT_CONFIGURED before any provider is called. The operator must set TTS_PRIVATE_AUDIO_SECRET (32 or more random characters, different from JWT_SECRET; the server refuses to start with a weak one) and, with Supabase storage, SUPABASE_PRIVATE_BUCKET. That bucket must exist and be non-public; the server checks it at startup and leaves private mode off if it is public or missing. Private metadata goes to the service-role-only table private_audio_metadata, never to audio_metadata. On deployed storage the server also needs REDIS_URL, so the daily cap is shared across instances and survives restarts; without it private requests get 503. The server checks the private bucket once, at startup; if it is missing or public, private mode stays off (503) until the process restarts. After changing bucket settings an operator must restart the server. That check only reads the bucket's public flag, so the operator must also keep storage.objects policies closed for that bucket: no policy may let anon or authenticated read it.
Rotating TTS_PRIVATE_AUDIO_SECRET cuts every owner off from their existing private audio, because each id is signed with the secret in force when it was made. After a rotation the old ids answer 404 to everyone, including their owners, and the files stay in storage until an operator deletes them.
Expired audio stops being served at once but stays stored until an operator purges it. Run node scripts/purge-expired-private-audio.mjs with SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY and TTS_SUPABASE_PROJECT_REF (the project ref in that URL; the script refuses to run if they differ) set, on any schedule. It is safe to re-run, works oldest first, and logs and skips any item it cannot remove so the next run retries it. It does the same as these two steps by hand: first remove the files listed by SELECT s3_bucket, s3_key FROM public.private_audio_metadata WHERE expires_at < now(); from their bucket (Storage API remove, or the dashboard), then run DELETE FROM public.private_audio_metadata WHERE expires_at < now();. Remove the files first: a row deleted before its file leaves a file nothing points to.
2. Retrieve Audioโ
Get the generated audio file by hash or private id.
Endpoint: GET /audio/{hash}
Public audio needs no credentials and is sent with Cache-Control: public, max-age=31536000. A prv_ id needs the owning key, as described under "Private audio".
The endpoint honours a single byte range, so players can seek. Range: bytes=0-1023 returns 206 Partial Content with Content-Range: bytes 0-1023/<size>. Open-ended (bytes=1024-) and suffix (bytes=-500) ranges work too. A well-formed range that starts past the end of the file returns 416 with Content-Range: bytes */<size>. A malformed Range header is ignored and the whole file comes back with 200. A request for several separate ranges gets the whole file with 200.
Response: Audio file (binary)
Headers:
Content-Type: audio/mpeg
Content-Length: 245760
Cache-Control: public, max-age=31536000
ETag: "a1b2c3d4e5f6"
X-Provider: openai
X-Cached-Tier: disk
Example:
curl https://tts.supernal.ai/api/v1/audio/a1b2c3d4e5f6 -o output.mp3
3. Get Audio Metadataโ
Retrieve metadata about a cached audio file.
Endpoint: GET /audio/{hash}/metadata
Response:
{
"hash": "a1b2c3d4e5f6",
"originalText": "Hello world!",
"normalizedText": "hello world",
"provider": "openai",
"voice": "nova",
"language": "en-US",
"format": "mp3",
"duration": 1.2,
"fileSize": 24576,
"sampleRate": 24000,
"bitrate": 128000,
"generatedAt": "2024-01-20T10:30:00Z",
"lastAccessedAt": "2024-01-20T11:00:00Z",
"accessCount": 5,
"cost": {
"amount": 0.00015,
"currency": "USD",
"charactersCharged": 12
}
}
4. Check Audio Existsโ
Check if audio exists without downloading it.
Endpoint: HEAD /audio/{hash}
Returns the same headers as GET, including Content-Length, and no body. A Range header gives the 206 headers for that range. Private ids follow the same access rules as GET.
Response:
200- Audio exists404- Audio not found
5. Delete Cached Audioโ
Remove audio from cache.
Endpoint: DELETE /cache/{hash}
Response:
{
"deleted": true
}
6. Get Cache Statisticsโ
Get overall cache statistics.
Endpoint: GET /cache/stats
Response:
{
"totalEntries": 1234,
"totalSize": 1073741824,
"oldestEntry": "2024-01-01T00:00:00Z",
"newestEntry": "2024-01-20T15:30:00Z"
}
7. Clear Cacheโ
Clear all cached audio files (admin only).
Endpoint: DELETE /cache
Response:
{
"message": "Cache cleared"
}
8. List Supported Voicesโ
Get available voices for a provider.
Endpoint: GET /voices?provider={provider}
Query Parameters:
provider(optional) - Filter by provider
Response:
{
"voices": [
"alloy",
"echo",
"fable",
"onyx",
"nova",
"shimmer"
]
}
9. List Supported Languagesโ
Get supported languages for a provider.
Endpoint: GET /languages?provider={provider}
Response:
{
"languages": [
"en", "es", "fr", "de", "it", "pt", "ru", "zh", "ja", "ko"
]
}
10. Estimate Costโ
Estimate the cost of generating audio without actually generating it.
Endpoint: POST /estimate
Request Body:
{
"text": "Your text here",
"options": {
"provider": "openai",
"quality": "high"
}
}
Response:
{
"cost": 0.0045,
"characterCount": 150,
"currency": "USD"
}
11. Get Available Providersโ
List all configured providers with their capabilities.
Endpoint: GET /providers
Response:
{
"providers": [
{
"name": "openai",
"voices": ["alloy", "echo", "fable", "onyx", "nova", "shimmer"],
"languages": ["en", "es", "fr", "de", "it", "pt", "ru", "zh", "ja", "ko"]
},
{
"name": "cartesia",
"voices": ["barbershop-man", "broadway-diva", "confident-british-man"],
"languages": ["en", "es", "fr", "de", "pt", "zh", "ja", "hi"]
},
{
"name": "azure",
"voices": ["en-US-JennyNeural", "en-US-GuyNeural", "en-GB-SoniaNeural"],
"languages": ["en-US", "en-GB"]
},
{
"name": "mock",
"voices": ["mock-voice-1", "mock-voice-2", "mock-voice-3"],
"languages": ["en", "es", "fr", "de", "it", "pt", "ru", "zh", "ja", "ko"]
}
]
}
12. Get Provider Statisticsโ
Get usage statistics for each provider.
Endpoint: GET /stats/providers
Response:
{
"stats": {
"openai": {
"requests": 1523,
"charactersProcessed": 4567890,
"totalCost": 68.52,
"avgLatency": 198,
"errors": 3
},
"cartesia": {
"requests": 892,
"charactersProcessed": 2345678,
"totalCost": 18.76,
"avgLatency": 42,
"errors": 1
}
}
}
13. Health Checkโ
Check API health status.
Endpoint: GET /health
Response:
{
"status": "ok",
"service": "supernal-tts-api",
"timestamp": "2024-01-20T10:30:00Z",
"uptime": 3600
}
14. Readiness Checkโ
Check if the service is ready to handle requests.
Endpoint: GET /health/ready
Response:
{
"ready": true,
"timestamp": "2024-01-20T10:30:00Z"
}
15. Liveness Checkโ
Check if the service is alive.
Endpoint: GET /health/live
Response:
{
"live": true,
"timestamp": "2024-01-20T10:30:00Z"
}
Upgradingโ
POST /hash-lookupandPOST /hash-existsnow require an API key. They were anonymous before.GETandHEAD /audio/{hash}now honour theRangeheader (single byte ranges,206and416).- A failed cache lookup now returns
500before any provider call.
Error Responsesโ
All errors follow this format:
{
"error": {
"message": "Human-readable error message",
"code": "ERROR_CODE",
"provider": "openai",
"details": {
// Additional error details
}
}
}
Error Codesโ
| Code | Description | HTTP Status |
|---|---|---|
INVALID_VOICE | Voice not supported by provider | 400 |
INVALID_SPEED | Speed out of valid range | 400 |
INVALID_FORMAT | Audio format not supported | 400 |
PROVIDER_NOT_CONFIGURED | Provider not set up | 500 |
OPENAI_GENERATION_ERROR | OpenAI API error | 502 |
CARTESIA_GENERATION_ERROR | Cartesia API error | 502 |
AZURE_GENERATION_ERROR | Azure API error | 502 |
RATE_LIMIT_EXCEEDED | Too many requests | 429 |
Rate Limitingโ
Default rate limits:
- 100 requests per minute per IP
- Configurable via
API_RATE_LIMITenvironment variable
Rate limit headers:
RateLimit-Limit: 100
RateLimit-Remaining: 95
RateLimit-Reset: 1642680000
Provider-Specific Optionsโ
OpenAI Optionsโ
{
"provider": "openai",
"voice": "fable", // alloy, echo, fable, onyx, nova, shimmer
"quality": "high", // standard or high (HD)
"speed": 1.0 // 0.25 to 4.0
}
Cartesia Optionsโ
{
"provider": "cartesia",
"voice": "confident-british-man",
"speed": 1.0, // 0.5 to 2.0
"emotion": {
"positivity": 0.8, // -1 to 1
"energy": 0.6 // -1 to 1
}
}
Azure Optionsโ
{
"provider": "azure",
"voice": "en-US-JennyNeural",
"speed": 1.0, // 0.5 to 2.0
"pitch": 0 // -50 to 50 (semitones)
}
Mock Optionsโ
{
"provider": "mock",
"voice": "mock-voice-1"
}
Webhooks (Future)โ
Configure webhooks for async generation:
{
"text": "Long text content...",
"options": { "provider": "openai" },
"webhook": {
"url": "https://yourapp.com/tts-webhook",
"headers": {
"X-Auth-Token": "your-token"
}
}
}
Client SDKsโ
JavaScript/TypeScriptโ
npm install @supernal-tts/client
import { TTSClient } from '@supernal-tts/client';
const client = new TTSClient({
apiUrl: 'https://tts.supernal.ai'
});
const { audioUrl } = await client.generate({
text: "Hello world!"
});
Python (Coming Soon)โ
from supernal_tts import TTSClient
client = TTSClient(api_url="https://tts.supernal.ai")
response = client.generate("Hello world!")
Postman Collectionโ
Import the Postman collection for easy API testing.
OpenAPI Specificationโ
View the OpenAPI spec for detailed schema information.
๐ง Try the API Liveโ
:::info Development Demo This is a development preview using our mock provider. The actual API may behave differently and is subject to changes as we continue development. :::
This is a live demonstration of the Supernal TTS API. Click the button to hear this text converted to speech using our mock provider.
For more examples and integration guides, see the Examples section.