Python Documentation for Text-to-Speech API

By SonicLesson editorial team · Updated 2026-11-19

This guide explains how to integrate the SonicLesson text-to-speech API into Python applications. You will find concrete examples for authentication, request formatting, and error handling. The documentation covers every parameter, from voice selection to language codes, ensuring you generate audio files that match your classroom materials or edtech tools precisely.

Designed for teachers and indie developers, this reference uses the standard OpenAI-compatible endpoint structure. You can quickly adapt existing code by changing the base URL. We provide clear explanations of rate limits, pricing, and long-text splitting, so you can deploy reliable synthetic voice generation without enterprise overhead or complex SDK dependencies.

Python Documentation for Text-to-Speech API

Frequently asked questions

How do I get an API key?

Sign up on /get-api-key/ using Google or email. Google sign-ins receive a $0.50 trial valid for 7 days. Email accounts start without credit. The dashboard displays your active key, balance, and usage statistics immediately after registration.

Can I use the OpenAI SDK?

Yes. The API matches the OpenAI speech endpoint shape. Change the base URL to https://api.999sl.top/v1 and use your SonicLesson key. The official OpenAI SDKs work directly without modification for integration.

What is the base URL?

The base URL is https://api.999sl.top/v1. Use POST https://api.999sl.top/v1/audio/speech for synthesis. GET /v1/voices lists available options, and GET /v1/models returns model details. Authentication requires a Bearer token.

How do I split long texts?

Split input text into parts of up to 4096 characters. Send each part as a separate request. Join the resulting audio files programmatically. This ensures compliance with the character limit per request.

What are the rate limits?

Limits are 60 requests per minute per key. New accounts without top-ups are limited to 10 requests per minute. Requests process sequentially, so high load may cause queuing delays during synthesis.

How do I handle errors?

Failed requests are free, with charges returned in full. Monitor response status codes. If synthesis fails, the API returns an error object. Retry logic should account for potential queueing delays under load.

What formats are supported?

Supported formats are mp3, wav, opus, flac, and pcm. Set the response_format field in your JSON body. Choose based on your storage needs or playback requirements. All formats include inaudible synthetic watermarks.

How do I set the language?

Set the optional language field to an ISO code. If omitted, the system guesses from the script, defaulting Latin text to English. Explicitly set it for non-English Latin scripts to ensure accuracy.

Can I change my API key?

Yes. Issue a new key from your dashboard at any time. The old key stops working immediately upon generating the new one. Only one active key exists per account at any time.

What is the response format?

The response contains the generated audio file directly. It is not stored on our servers. Input text is used only for generation and not for training. Metadata like time and status is kept for billing.

Is there a Python SDK?

No official SDK of our own. Use the standard OpenAI Python SDK or plain HTTP requests. Configure the base URL to point to our API endpoint for seamless integration with your codebase.

How do I calculate costs in code?

Cost is $0.01 per 1,000 characters, including spaces and punctuation. Count characters in your input text before sending. Multiply by the rate to estimate costs. Failed requests incur no charge.

What happens if I exceed limits?

Requests are processed sequentially. Exceeding limits may cause requests to wait in a queue. Ensure your code handles potential delays. The system does not drop requests but may increase latency during high load.

Can I use async requests?

Requests are processed one after another. However, requests are processed one after another. Under load, each request may wait in a queue, affecting total generation time for long texts.

First request

curl

curl https://api.999sl.top/v1/audio/speech \
  -H "Authorization: Bearer $TTS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"tts-1","voice":"aria","input":"Hello from the API.","response_format":"mp3"}' \
  --output hello.mp3

Python (openai)

from openai import OpenAI

client = OpenAI(base_url="https://api.999sl.top/v1", api_key="tts-...")

with client.audio.speech.with_streaming_response.create(
    model="tts-1", voice="nova", input="Hello from Python.", response_format="mp3"
) as response:
    response.stream_to_file("hello.mp3")

Node.js (openai)

import OpenAI from "openai";
import fs from "node:fs";

const client = new OpenAI({ baseURL: "https://api.999sl.top/v1", apiKey: process.env.TTS_API_KEY });
const res = await client.audio.speech.create({ model: "tts-1", voice: "milo", input: "Hello from Node.js." });
fs.writeFileSync("hello.mp3", Buffer.from(await res.arrayBuffer()));
voice
ariafemale
novafemale
lunafemale
sagefemale
felixmale
milomale
atlasmale
orionmale
language
arالعربية
zh中文
daDansk
nlNederlands
enEnglish
fiSuomi
frFrançais
deDeutsch
elΕλληνικά
heעברית
hiहिन्दी
itItaliano
ja日本語
ko한국어
msBahasa Melayu
noNorsk
plPolski
ptPortuguês
ruРусский
esEspañol
swKiswahili
svSvenska
trTürkçe

Authentication

Sound wave illustration for: Authentication

Authentication for the SonicLesson TTS API relies on a single active bearer token per account. This key authorizes all requests to the API base URL and is managed directly through the account dashboard. You can view your current key, usage statistics, and balance in one place, ensuring simple oversight without enterprise-grade complexity.

API Key Management

Keys are generated upon account creation and are tied to your specific site account. The dashboard displays the active key alongside your current balance and character usage. Keep this key secure, as it provides direct access to your billing and audio generation capabilities.

  • One active key per account
  • Viewable in the dashboard alongside usage stats
  • Included in the Authorization: Bearer header

Key Rotation Policy

You can issue a new key at any time via the dashboard. Upon generation, the previous key stops working immediately, ensuring no overlap or delayed revocation. This allows for quick response to potential exposure without waiting for a daily cycle.

  • Old key invalidates instantly
  • No grace period
  • Generate new key from dashboard

Quickstart with cURL

Sound wave illustration for: Quickstart with cURL

To verify your API key, send a simple POST request to the speech endpoint. This confirms connectivity and returns an audio file without consuming significant credits, serving as a quick sanity check before full integration.

Use the generated audio to test playback in your classroom materials or edtech tools. The response delivers the synthesized voice directly, allowing you to validate format and quality immediately.

First Request

Send a POST request to https://api.999sl.top/v1/audio/speech with your bearer token. Include the model "tts-1", a short input text, and your chosen voice. This minimal payload proves your key works and returns the audio stream.

  • Endpoint: POST /v1/audio/speech
  • Auth: Bearer your_api_key
  • Model: tts-1 or tts-1-hd

Response Format

The API returns the audio file directly in the response body, with the content type matching your requested format (e.g., audio/mpeg for mp3). Headers include standard HTTP status codes to indicate success or failure.

  • Content-Type matches response_format
  • Body contains raw audio bytes
  • No JSON wrapper for audio data

Error Handling

Handle standard HTTP errors gracefully. A 401 indicates an invalid or expired key, while a 429 means you exceeded 60 requests per minute. Check the response body for a JSON object describing the error for debugging.

  • 401: Invalid API key
  • 429: Rate limit exceeded (60 req/min)
  • 500: Internal server error

Python SDK Setup

Sound wave illustration for: Python SDK Setup

The SonicLesson API is compatible with the official OpenAI Python SDK. You do not need a custom library to integrate synthetic voice generation into your edtech tools or classroom materials. Simply install the standard package and configure the client to point to our infrastructure.

Code Example

Initialize the client with your API key and the specific base URL. Pass the text, voice, and format parameters directly to the speech endpoint. The SDK handles the JSON serialization and file download automatically, returning the audio bytes for immediate playback or saving.

  • Install the library via pip install openai
  • Import the OpenAI client class
  • Pass your Bearer token in the api_key argument

Base URL Configuration

Point the SDK to https://api.999sl.top/v1 instead of the default OpenAI endpoint. This ensures your requests route through the correct gateway for character billing and voice synthesis. All other parameters remain identical to the standard OpenAI speech schema.

Request Parameters

Sound wave illustration for: Request Parameters

The API accepts eight distinct voice presets, ranging from warm narrators to deep documentary styles. Each voice supports all 23 listed languages, allowing consistent tone across diverse classroom materials or edtech applications without needing separate voice models.

Voice Selection

Select voices like aria for clear narration or atlas for neutral news-style delivery. The voice parameter expects one of the eight preset names. All voices handle multiple languages natively, ensuring uniform audio quality regardless of the source text's origin.

  • Use aria for warm, clear narration.
  • Choose atlas for neutral, news-style delivery.
  • Any voice can speak any of the 23 supported languages.

Speed Control

Adjust speech rate between 0.25 and 4.0 to match educational pacing needs. Slower speeds aid comprehension for language learners, while faster rates suit quick reviews. The API processes requests sequentially, so extreme speeds may slightly affect queue time under load.

Language Settings

Provide an optional ISO language code to ensure accurate pronunciation. Without it, the system guesses from the script, defaulting to English for Latin text. Explicitly setting language prevents errors with non-English Latin-script inputs like Dutch or Swedish.

Audio Formats

Sound wave illustration for: Audio Formats

For classroom recordings or archival storage, FLAC offers lossless compression without quality loss, while PCM provides raw, uncompressed audio data. Both formats are ideal when your edtech tool requires pristine audio fidelity or simple parsing without decoding overhead.

FLAC and PCM

FLAC compresses audio to roughly half the size of WAV while remaining fully lossless. PCM delivers raw byte streams, which are useful for real-time processing pipelines that handle their own encoding.

  • FLAC: Lossless compression
  • PCM: Raw, uncompressed audio data
  • Both support any voice and speed setting

MP3 and WAV Options

  • MP3: Optimized for web and LMS integration
  • WAV: Uncompressed, high quality, larger files
  • Select based on your delivery channel needs

Rate Limits

Sound wave illustration for: Rate Limits

The API enforces a strict limit of 60 requests per minute per key. Before your first top-up, this limit drops to 10 requests per minute, which helps manage initial usage during the trial period.

Concurrency Limits

Requests are processed sequentially, meaning they run one after another rather than in parallel. This single-threaded processing ensures stability but means that under heavy load, your requests may wait in a queue before synthesis begins. For classroom materials or bulk lesson generation, plan your batch sizes accordingly to avoid unnecessary delays.

Burst Handling

If you send more requests than the allowed limit within a minute, you will receive a 429 Too Many Requests error. To handle bursts effectively, implement exponential backoff in your Python script. This allows your application to wait briefly and retry automatically, ensuring that all your text-to-speech jobs eventually complete without manual intervention.

  • Limit: 60 requests/minute (standard)
  • Trial Limit: 10 requests/minute
  • Processing: Sequential (queue-based)
  • Error: 429 if exceeded
Rate Limits

Error Codes

Sound wave illustration for: Error Codes

The API returns standard HTTP status codes to indicate request outcomes. Understanding these codes helps you implement robust retry logic in your classroom or edtech applications without unnecessary overhead.

500 Server Error

A 500 status indicates the synthesis engine encountered an unexpected issue. This is rare but may occur during high load. Failed requests are free, so you can safely retry or split your text further.

429 Too Many Requests

You receive this code when exceeding 60 requests per minute per key (10 before first top-up). Implement exponential backoff to handle bursts gracefully. This ensures your lesson materials generate smoothly without manual intervention.

  • Rate limit resets every minute.
  • Check the Retry-After header if present.

Voice List Endpoint

Sound wave illustration for: Voice List Endpoint

The /v1/models endpoint provides metadata about the available synthesis engines. Currently, the API supports two models: tts-1 and tts-1-hd. Both utilize the same underlying engine and pricing structure, allowing you to switch between them without changing your billing expectations.

Model Info

Selecting tts-1 or tts-1-hd does not alter the voice characteristics or the output quality significantly, as they share the same engine. The primary difference lies in the internal processing, but for most educational and indie dev use cases, either model performs identically regarding voice tone and language support.

Available Voices

The /v1/voices endpoint returns the full list of eight available presets. Each voice is a preset with a specific tone, ranging from warm narrators to neutral news readers. All eight voices support all 23 listed languages, though proper language codes should be set for non-English Latin-script text to ensure accuracy.

  • aria: warm, clear narrator
  • nova: bright, upbeat
  • luna: soft, storytelling
  • sage: calm, instructional
  • felix: energetic, promo
  • milo: friendly, conversational
  • atlas: neutral, news
  • orion: deep, documentary

Pricing and Billing

Sound wave illustration for: Pricing and Billing

Pricing is straightforward: $10 per 1 million characters, equating to $0.01 per 1,000 characters. Spaces and punctuation count toward the total. Failed requests are free, with any charge returned in full if synthesis fails. This structure avoids hidden fees for classroom materials or batch-generated audio files.

Character Counting

Each request supports up to 4096 characters. For longer texts, split the input into parts, generate audio for each, and join the files. This ensures consistent quality and predictable billing based on exact character volume.

  • Spaces and punctuation count as characters.
  • Failed requests incur no charge.
  • Maximum 4096 characters per request.

Payment Methods

We accept USDT on the TRON network (TRC-20) only. The minimum top-up is $5, and credits are added automatically within minutes of transfer. There are no monthly plans, no seats, and no VAT invoices. Balance does not expire.

  • USDT (TRC-20) only.
  • Minimum top-up: $5.
  • No cards or PayPal.

Long Text Handling

Sound wave illustration for: Long Text Handling

For classroom materials or educational podcasts, texts often exceed the 4,096-character limit per request. The API does not handle long-form synthesis internally; instead, your implementation must split the input text into chunks of up to 4,096 characters before sending individual requests.

Splitting Logic

Split your text carefully to avoid cutting mid-sentence if possible, though the API accepts any character sequence. Each chunk triggers a separate synthesis job. Since requests are processed sequentially, under load a request may wait in a queue.

  • Maximum 4,096 characters per request
  • Spaces and punctuation count toward the limit
  • Send one request per chunk

Audio Joining

Once you receive the audio file for each chunk, you must join them in your application. The API returns raw audio data or files depending on your chosen response_format. Concatenate these files in order to create the final continuous audio file for your students or app users.

Data Privacy

Sound wave illustration for: Data Privacy

Input text is used solely to produce the audio and is not retained for training models. Generated audio files are returned in the response and are not stored on our servers, ensuring your lesson content remains transient during processing.

Input Usage

The API processes your submitted text strictly for synthesis purposes. Once the audio is generated and delivered, the original text input is not archived for model improvement or secondary analysis.

Audio Storage

Generated audio files are not stored persistently after delivery. We retain only request metadata—such as timestamp, character count, and status—for billing and usage verification purposes.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. The language’s dominance in data and education tools means libraries handle text splitting and format conversion natively.

Avatar of the voice aria
ariafemale
Avatar of the voice nova
novafemale
Avatar of the voice luna
lunafemale
Avatar of the voice sage
sagefemale
Avatar of the voice felix
felixmale
Avatar of the voice milo
milomale
Avatar of the voice atlas
atlasmale
Avatar of the voice orion
orionmale

23 languages

Any voice speaks any of these languages.

Sources and further reading

  1. Wikipedia
  2. LibriTTS-R corpus (OpenSLR 141)
  3. LibriVox public-domain audiobooks
  4. TRON developer hub: TRC-20
  5. ISO 639 language codes
  6. curl documentation
  7. Creative Commons Attribution 4.0
  8. OpenAI API reference: create speech
  9. Python documentation
  10. Node.js documentation
  11. openai-node on GitHub
  12. openai-python on GitHub

More on this site