Python Integration Guide for Text-to-Speech API

By LMS Voice Lab editorial team · Updated 2026-11-19

This guide shows edtech teams how to integrate our text-to-speech API into their LMS workflows using Python. We provide a simple, programmatic solution that replaces expensive voice-over production with scalable audio generation. By using the OpenAI SDK with a modified base_url, you can generate synthetic speech for courses and training materials with minimal code changes.

You will learn to authenticate with a Bearer token, configure voice presets like Aria or Atlas, and handle responses efficiently. The documentation covers parameter tuning, rate limits, and error handling, ensuring reliable delivery of audio files directly into your educational content pipeline.

Python Integration Guide for Text-to-Speech API

Frequently asked questions

How do I set the base_url?

Set the base_url to https://api.t46.net/v1. This allows you to use the official OpenAI SDKs by simply changing the endpoint. Your API key remains valid for this base URL, ensuring seamless integration with your existing Python code without requiring custom HTTP clients or complex configuration changes.

What models are available?

Two models are available: tts-1 and tts-1-hd. Both use the same engine and have identical pricing. You can choose either based on your preference, as they use the same engine and pricing. The model parameter accepts these exact string values in your JSON request body.

Which voices can I use?

Eight presets are available: aria, nova, luna, sage, felix, milo, atlas, and orion. These cover female and male tones, ranging from warm narrators to deep documentary styles. All voices can speak any of the 23 supported languages, allowing you to mix voices and languages freely in your application.

What is the max input length?

The maximum input length is 4096 characters per request. This limit applies to the text you send in the input field. If your content exceeds this, you must split the text into smaller chunks, generate audio for each, and join the resulting files programmatically to create a continuous audio file.

How do I set the speed?

Use the speed parameter with a value between 0.25 and 4.0. The default speed is 1.0. You can adjust this value to make the speech faster or slower. This parameter accepts floating-point numbers, allowing for fine-grained control over the playback rate of the generated audio file.

How do I specify a language?

Pass the ISO language code in the language field. If omitted, the system guesses the language from the script, defaulting to English for Latin text. For non-English Latin-script text, explicitly setting the language ensures accurate pronunciation and prevents the system from misinterpreting the intended language during synthesis.

What happens if I exceed rate limits?

You are limited to 60 requests per minute per key. Before your first top-up, the limit is 10 requests per minute. If you exceed this, requests may queue or fail. Requests are processed sequentially, so under load, you might experience delays. Monitor your usage to stay within these bounds.

Are failed requests free?

Yes, failed requests are free. If synthesis fails, the charge is returned in full. You only pay for successful audio generations. This ensures you are not charged for errors or issues that prevent the API from producing the requested audio file, protecting your balance during development and testing phases.

How do I rotate my API key?

Issue a new key at any time via your account dashboard. The new key becomes active immediately, and the old one stops working at once. This allows for seamless rotation without downtime. You can manage your active key directly from the /get-api-key/ page on the site.

Is the OpenAI SDK required?

No, the OpenAI SDK is not required. You can use any HTTP client to send POST requests to the endpoint. The OpenAI SDK is recommended for convenience because the request shape is identical. You can also use plain HTTP libraries like requests in Python if you prefer simpler dependencies.

Can I use other languages?

Yes, 23 languages are supported, including Arabic, Chinese, French, German, Japanese, Spanish, and more. Any voice can speak any of these languages. If a language is not listed, it is not supported. Ensure you set the language parameter for non-English texts to guarantee accurate pronunciation and voice selection.

What formats are supported?

Five formats are supported: mp3, wav, opus, flac, and pcm. Specify your preferred format in the response_format field. This allows you to choose between compressed audio for smaller file sizes or uncompressed formats for higher quality, depending on your LMS platform requirements and storage constraints.

How do I handle long texts?

Split your text into parts of up to 4096 characters. Generate audio for each part individually. Then, join the resulting audio files programmatically. This approach ensures you stay within the input limit while creating continuous audio content.

Is authentication required?

Yes, authentication is required. Include your API key in the Authorization header as Bearer tts-... . One active key is issued per account. Ensure your key is valid and has sufficient balance. Requests without proper authentication will be rejected by the API endpoint before processing begins.

First request

curl

curl https://api.t46.net/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.t46.net/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.t46.net/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

Get your API Key

Sound wave illustration for: Get your API Key

To begin using the LMS Voice Lab API, visit the /get-api-key/ page to create an account. You can sign in using Google or create an account with an email and password. This step establishes your unique identity for the API service, allowing you to generate and manage your authentication credentials.

Sign up on /get-api-key/

Sign up on /get-api-key/

Accounts are created per site, meaning your credentials are specific to this domain. Once registered, you will have access to a dashboard where you can view your API key, current balance, and usage statistics. This centralized management ensures you can track character consumption and billing details accurately.

Copy your Bearer token

Copy your Bearer token

After signing up, you will receive a Bearer token starting with "tts-". This token serves as your sole authentication method for all API requests. You must include it in the Authorization header of every POST request to the API endpoint. Keep this token secure, as it grants full access to your account and billing.

  • Tokens begin with "tts-"
  • One active key per account
  • Include in Authorization header

Rotate keys if needed

You can issue a new API key at any time from your dashboard. When you generate a new key, the previous one stops working immediately. This feature allows you to quickly revoke access if a key is compromised or if you need to reset credentials for different development environments without delay.

First Request with Curl

Sound wave illustration for: First Request with Curl

Begin by sending a POST request to the speech endpoint. The following command demonstrates the minimal structure required to generate audio, including the authorization header and a JSON payload specifying the model, input text, and voice preset.

Basic POST request

This command sends a short phrase to the API. `curl -X POST https://api.t46.net/v1/audio/speech -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{"model": "tts-1", "input": "Hello world", "voice": "nova"}'`

JSON body structure

The request body must include the model ("tts-1" or "tts-1-hd"), the input text (up to 4096 characters), and the voice identifier. Optional fields like response_format and speed can be added to customize the output.

Response handling

On success, the API returns an audio file in the requested format. Failed requests incur no charge, and the response indicates the status clearly. Save the binary response directly to a file for use in your LMS.

OpenAI SDK Integration

Sound wave illustration for: OpenAI SDK Integration

To integrate LMS Voice Lab with your Python applications, modify the OpenAI SDK’s base_url to point to https://api.t46.net/v1. This allows you to use the official SDK while routing requests through our TTS endpoint.

Keep your API key in an environment variable for security. The SDK handles authentication automatically when you pass your token, ensuring seamless connectivity for your course audio generation workflows.

Set base_url

Configure the SDK’s base URL to https://api.t46.net/v1. This redirects standard TTS calls to our infrastructure without requiring custom HTTP libraries.

Ensure your OPENAI_API_KEY environment variable holds your Bearer token starting with tts-. The SDK uses this for authorization.

Use tts-1 model

Select the tts-1 model for standard synthesis.

This model processes requests sequentially, so longer texts may experience slight delays during peak usage.

Use tts-1-hd model

Choose tts-1-hd for higher fidelity audio.

Both models share the same pricing of $10 per million characters, allowing you to switch based on quality needs without cost changes.

Request Parameters

Sound wave illustration for: Request Parameters

Configure your synthesis requests by defining the source text, vocal style, and output format. The API accepts a single text input up to 4096 characters, processing longer scripts by splitting and joining audio files sequentially.

Select from eight distinct voice presets tailored for educational narration or clear instructional content. You can choose between formats like MP3, WAV, FLAC, OPUS, or PCM depending on your LMS compatibility needs.

Input text (max 4096 chars)

Pass your course script as the input field. The system counts spaces and punctuation toward the character limit, so plan your splits for longer lessons to ensure seamless audio playback.

Voice selection (8 presets)

Choose a voice that matches your content tone. Options include warm narrators like Aria, calm instructional voices like Sage, or energetic promo styles like Felix. Each voice supports all 23 languages.

Voices are based on licensed recordings and carry an inaudible watermark to identify synthetic speech.

  • 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

Response format (mp3, wav, etc.)

Specify response_format to control file output. Supported formats include mp3, wav, opus, flac, and pcm. Choose based on your platform’s storage and streaming requirements.

Speed and Language

Sound wave illustration for: Speed and Language

The API adjusts vocal pacing via a speed parameter ranging from 0.25 to 4.0, allowing you to fine-tune audio for specific course segments. Slower rates aid comprehension for complex topics, while faster speeds suit quick reviews.

Speed range 0.25–4.0

Adjust the speed value to match your pedagogical needs. Values below 1.0 slow the narration, ideal for technical explanations or non-native speakers. Values above 1.0 accelerate delivery, useful for summarizing previously covered material.

Optional ISO language code

Specify the language field using an ISO 639-1 code (e.g., es, fr, de). This ensures correct pronunciation when the voice model might otherwise guess incorrectly. Supported languages include Arabic, Chinese, Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, and Turkish.

  • Arabic, Chinese, Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, Turkish

Automatic language detection

If you omit the language field, the system infers it from the text script. Latin-script text defaults to English. For non-English Latin-script content, explicitly setting the language parameter prevents mispronunciation and ensures accurate accent handling.

Speed and Language

Rate Limits

Sound wave illustration for: Rate Limits

The API enforces a strict limit of 60 requests per minute per active key. This cap ensures stable performance for automated course production pipelines and prevents sudden spikes from overwhelming the synthesis engine.

Before your first top-up, the limit is reduced to 10 requests per minute. This allows you to verify integration stability with your Python scripts without risking quota exhaustion during initial testing.

60 requests per minute

Each API key is capped at 60 synthesis requests every 60 seconds. If your edtech platform triggers multiple simultaneous audio generations, ensure your code respects this limit to avoid HTTP 429 errors.

  • Limit applies per key, not per account.

10 requests before first top-up

New accounts start with a 10 requests per minute limit. This throttle remains active until you add USDT (TRC-20) credit to your balance. Once funded, the limit automatically increases to the standard 60 requests per minute.

Queue behavior under load

Requests are processed sequentially. If you exceed the per-minute limit, subsequent requests wait in a queue rather than failing immediately. Longer texts take more time to generate, so sustained high-volume usage may result in delayed responses as the queue fills.

  • Processing is sequential, not parallel.

Error Handling

Sound wave illustration for: Error Handling

Errors are handled with standard HTTP status codes. The API returns clear codes for client or server issues, allowing your integration to react appropriately without guesswork. Understanding these responses ensures your LMS audio generation pipeline remains robust during unexpected interruptions.

When synthesis fails, the charge is returned in full. This guarantees that you only pay for successfully generated audio files, protecting your budget during development or high-load periods.

HTTP status codes

Use standard HTTP status codes to determine the cause of failure. Common codes include 400 for bad requests, 401 for authentication errors, and 500 for server issues. Your Python script should check these codes to decide whether to retry or alert the user.

  • 400: Invalid parameters or malformed JSON
  • 401: Unauthorized or invalid API key
  • 429: Rate limit exceeded (60 req/min)

Failed request refunds

If the synthesis process fails for any reason, the cost is refunded to your account balance immediately. You do not lose credits for audio that was not delivered. This applies to both free trial credits and topped-up USDT balances.

Invalid voice IDs

Ensure the voice parameter matches one of the eight available presets. Using an invalid ID returns an error immediately, preventing wasted computation. Refer to the /v1/voices endpoint for the complete list of valid voice names.

Code Examples

Sound wave illustration for: Code Examples

Integrate the TTS API into your Python workflow using the standard requests library or the OpenAI SDK. The following examples demonstrate how to generate audio files directly from your LMS content management scripts.

These snippets cover basic generation, binary handling for file storage, and chunking logic for longer course modules that exceed the 4096-character limit.

Python script snippet

Install the OpenAI package via pip install openai. Initialize the client with your API key and the base URL https://api.t46.net/v1. Call the audio.speech.create method with your chosen model (tts-1 or tts-1-hd) and voice preset like 'aria' or 'atlas'.

The request body requires the input text, model identifier, and voice selection. The API returns a standard HTTP response containing the audio data.

Handling audio binary

The API response contains the raw audio bytes. Save this directly to a file or stream it to your LMS player. Use response.content to access the binary data.

Store the file with the appropriate extension (.mp3, .wav, etc.) based on your response_format parameter. This ensures compatibility with standard HTML5 audio tags in your course modules.

Long text splitting

Since each request supports up to 4096 characters, split longer scripts into chunks. Generate audio for each chunk individually.

Concatenate the resulting audio files or play them sequentially in your application. This ensures reliable synthesis without hitting input limits, maintaining consistent audio quality across your entire course.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. From warm narrators to energetic promotional voices, the selection covers most common eduse scenarios.

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. Python documentation
  3. Node.js documentation
  4. Creative Commons Attribution 4.0
  5. ISO 639 language codes
  6. W3C WAI: making audio and video accessible
  7. openai-python on GitHub
  8. OpenAI API reference: create speech
  9. LibriTTS-R corpus (OpenSLR 141)
  10. openai-node on GitHub
  11. curl documentation
  12. LibriVox public-domain audiobooks

More on this site