How to Generate TTS Audio with Python Using Our API?

By LectioLab editorial team · Updated 2026-11-19

This guide shows educators and methodologists how to convert course materials into audio using Python and the LectioLab API. You will learn to send text via a standard endpoint and receive MP3 or WAV files, integrating seamlessly into your existing LMS workflows. The process uses the official OpenAI Python client, requiring only a base URL change and an API key. The client is not an official OpenAI product.

By following these steps, you can generate clear narration for lectures or study guides. We cover simple requests, handling long texts by splitting them into chunks, and managing errors in production. The guide is designed for technical users who need a reliable, lightweight solution for text-to-speech without complex integrations.

How to Generate TTS Audio with Python Using Our API?

Frequently asked questions

What Python version is required?

The API uses standard HTTP requests, so any Python version capable of making POST requests works. No specific version is mandated. We recommend using the official OpenAI Python SDK or the requests library, both of which are widely supported across modern Python environments for reliable integration.

Do I need to install a specific library?

No proprietary library is required. You can use the official OpenAI Python SDK or plain HTTP libraries like requests. Simply install the chosen library via pip. The API endpoint shape matches the OpenAI speech endpoint, ensuring compatibility with existing SDK implementations without custom code.

How do I set the base_url?

Configure your SDK or HTTP client to use https://api.788t.info/v1 as the base URL. This directs requests to our TTS endpoint. Ensure your Authorization header includes your Bearer token. This standard configuration allows you to use familiar SDK methods while routing traffic to our infrastructure.

Can I use async requests?

Yes. Since the API uses standard HTTP, you can utilize any async HTTP client like aiohttp or the async features of the OpenAI SDK. This allows efficient handling of multiple text-to-speech conversions in parallel, which is useful for processing large course materials without blocking your application.

How do I save the audio file?

The API returns the audio file directly in the response body. Save this binary data to a file with the appropriate extension, such as .mp3 or .wav, based on your selected response_format. The file contains the synthesized speech ready for playback or distribution in your LMS.

What if the text is too long?

Each request supports up to 4096 characters. For longer texts, split your content into chunks of this size. Generate audio for each chunk separately and then join the resulting audio files. This ensures consistent quality and avoids exceeding the input limit per single API call.

How do I change the voice?

Include the voice parameter in your JSON body with one of the eight presets: aria, nova, luna, sage, felix, milo, atlas, or orion. Select the voice that best fits your educational content style. Each voice offers a distinct tone suitable for different types of instructional material.

Can I adjust the speed?

Yes, set the speed parameter between 0.25 and 4.0. This allows you to slow down complex explanations or speed up simple reviews. Adjusting speed helps tailor the audio to your students' listening preferences and learning pace without requiring manual editing of the generated audio files.

How do I handle errors?

The API returns standard HTTP status codes. Check for errors like 400 or 500 and handle them in your code. Failed requests are free, so you can retry without incurring extra costs. Implement retry logic to handle transient network issues or temporary service unavailability gracefully.

Is there a limit to file size?

File size depends on text length and speed. Typical generation is roughly real time, producing about 25 characters per second of audio. There is no explicit file size limit, but larger texts require splitting. Ensure your storage can handle the resulting MP3 or WAV files.

Can I use this in a web app?

Yes. The API is designed for integration into web applications and LMS workflows. You can generate audio on demand or pre-generate files for static content. Use the standard HTTP endpoint to integrate seamlessly with your existing backend infrastructure, serving audio files directly to your students.

How do I test my code?

Use the free trial credit of $0.50 provided upon Google sign-in. This covers about 50,000 characters. Test with short texts first to verify voice selection, format, and speed settings. Monitor your usage dashboard to ensure you stay within limits while refining your integration logic.

What if the API is down?

We do not provide an SLA or uptime guarantee. If the API is unavailable, requests may fail or queue. Implement retry logic in your application to handle temporary outages. Since failed requests are free, you can retry without cost once the service is restored.

How do I upgrade the library?

If using the OpenAI SDK or requests, upgrade via pip install --upgrade library_name. Since the API endpoint remains consistent, no code changes are usually needed. Check the library documentation for any breaking changes in newer versions that might affect how you send requests or parse responses.

Prerequisites

Sound wave illustration for: Prerequisites

To integrate LectioLab’s text-to-speech API into your LMS workflow, ensure your environment meets the baseline technical requirements. The solution relies on standard Python libraries, making it easy to embed in existing educational scripts without heavy dependencies.

Python 3.7+

The API client requires Python 3.7 or higher. This version ensures compatibility with the asynchronous features and type hints used in modern TTS integration scripts. The API itself processes requests sequentially. Verify your version with python --version before proceeding with the installation.

  • Supported on Windows, macOS, and Linux
  • No special compiler flags needed
  • Compatible with standard virtual environments

OpenAI Python package

Install the official openai package via pip. Although this is not the OpenAI speech service, the request shape is identical. Using this package allows you to simply change the base_url to point to https://api.788t.info/v1 and use the standard SDK methods.

  • Command: pip install openai
  • Uses standard HTTP client under the hood
  • Compatible with OpenAI SDK v1.0.0+

API key

Generate a Bearer token from the /get-api-key/ page. This key authenticates your requests and tracks usage against your balance. Keep the key secure in environment variables, as it grants full access to your account’s character quota.

  • Format: tts-...
  • One active key per account
  • Regenerate to invalidate old keys instantly

Installation

Sound wave illustration for: Installation

The primary requirement is the official openai Python package, which provides the HTTP client used to communicate with the LectioLab API. This library handles authentication headers and JSON serialization, allowing you to send synthesis requests using a familiar interface.

Before writing code, ensure your development environment has Python 3.7 or higher. You will need to install the package and import the necessary classes to initialize the client and generate audio files from your course materials.

pip install openai

Install the library using your standard Python package manager. This command fetches the latest stable version compatible with your environment.

Ensure the package is installed in the same virtual environment where your LMS integration scripts will run to avoid dependency conflicts.

  • Run: pip install openai

Import modules

Import the OpenAI client class from the openai package. You will also need standard library modules like os to manage environment variables and pathlib for file handling.

These imports provide the foundation for creating the client instance and saving the resulting audio bytes to disk.

Set environment variables

Store your API key in an environment variable named OPENAI_API_KEY. This keeps your credentials out of your source code, which is essential for secure deployment in your teaching workflows.

Use the os module to retrieve this key when initializing the client. This approach allows you to update credentials without changing code.

Configuration

Sound wave illustration for: Configuration

Configuration initializes the connection between your Python script and the LectioLab API. You must define the base URL and provide your authentication key to enable audio synthesis requests.

Set base_url

Set the base URL to https://api.788t.info/v1. This directs requests to the correct endpoint while keeping the standard request shape compatible with existing OpenAI SDKs.

Set API key

Assign your API key to the OPENAI_API_KEY environment variable or pass it directly. The key format is tts-.... Ensure you retrieve this from your dashboard at /get-api-key/.

Verify connection

Send a simple test request to generate a short audio clip. Successful response confirms the base URL and authentication are correct. Check for a 200 status code and valid audio data in the response body.

  • Use a short test string like "Hello".
  • Check for HTTP 200 response.
  • Verify audio file content type.

Simple request

Sound wave illustration for: Simple request

The core API call requires sending a POST request to the speech endpoint. You provide the text, select a voice, and choose the output format. The API returns the audio data directly, ready for immediate use in your LMS workflows.

This minimal example demonstrates a synchronous request. It handles the basic flow from sending text to receiving the binary audio stream, ensuring your Python script can generate MP3 or WAV files with minimal code overhead.

Code example

Here is a basic Python script using the OpenAI SDK. It sends a short text string to the API and waits for the response. The base_url points to our endpoint, and the key authenticates the request.

```python import os from openai import OpenAI client = OpenAI( base_url="https://api.788t.info/v1", api_key=os.environ["LECTIO_API_KEY"] ) audio = client.audio.speech.create( model="tts-1", voice="nova", input="Hello, this is a test sentence.", response_format="mp3" ) ```

  • Set base_url to https://api.788t.info/v1
  • Use model tts-1 or tts-1-hd
  • Specify response_format as mp3 or wav
  • Limit text to 4096 characters

Response handling

The API returns the audio data directly in the response body. If the request succeeds, you receive the file content directly. The SDK handles the HTTP connection, so you do not need to manage headers manually.

If the input text exceeds 4096 characters, the request will fail. Ensure your text is within limits before sending. The response time varies based on server load; typical generation is roughly real time (about 25 characters per second), but short phrases take a few seconds and requests may wait in a queue under load.

  • Check status code 200 for success
  • Handle 400 errors for invalid input
  • Catch network errors with try/except
  • Verify API key is valid

Save to file

To save the audio, write the binary response to a local file. This is essential for integrating with course materials or LMS platforms that require static audio files. Use audio.stream_to_file() for simplicity.

``python audio.stream_to_file("output.mp3") `` This saves the MP3 file to your current directory. You can now upload it to your learning management system or distribute it to students.

  • Use stream_to_file() method
  • Specify filename with extension .mp3 or .wav
  • Ensure write permissions in directory
  • Verify file size matches expected duration

Advanced usage

Sound wave illustration for: Advanced usage

Beyond basic synthesis, you can customize output by selecting specific voices, adjusting playback speed, or forcing a language. This allows precise alignment with course material style and learner needs.

Each adjustment modifies the generation parameters sent to the API, ensuring the audio matches pedagogical requirements without manual post-processing.

Change voice

Select from eight presets to match content tone. Use 'sage' for instructional modules or 'nova' for upbeat quizzes.

Voices are consistent across requests, ensuring uniform audio quality for entire courses.

  • Use voice='sage' for calm, instructional content.
  • Use voice='nova' for bright, upbeat announcements.
  • Choose voice='atlas' for neutral, news-style readings.

Adjust speed

Set speed between 0.25 and 4.0 to control playback rate. Faster speeds suit review sessions; slower speeds aid comprehension.

Default speed is 1.0. Adjustments do not affect character count billing; billing is based on the input text length.

  • Set speed=1.5 for quick reviews.
  • Set speed=0.8 for complex explanations.
  • Keep speed=1.0 for standard narration.

Select language

Specify language with an ISO code (e.g., 'de', 'fr') to ensure correct pronunciation. Omit it to let the API guess from the script.

Explicitly setting the language prevents mispronunciation in mixed-script texts.

Supported languages include German, French, Spanish, and others listed in our docs.

  • Set language='de' for German text.
  • Set language='fr' for French content.
  • Omit language for auto-detection from Latin script.

image

Handling long texts

Sound wave illustration for: Handling long texts

The API limits each request to 4,096 characters. For longer course materials, split the input text into smaller segments before sending them to the endpoint. This ensures compliance with the single-request constraint and prevents truncation.

Split into chunks

Divide your text into parts of up to 4,096 characters each. Process each chunk independently via a POST request. This approach respects the API’s input limit while maintaining audio continuity.

  • Maximum 4,096 characters per request
  • Split at sentence boundaries where possible
  • Maintain consistent voice and speed settings

Join audio files

Receive audio files for each chunk sequentially. Concatenate the resulting audio files in the correct order to reconstruct the full narration. This method preserves the narrative flow of your educational content.

  • Merge MP3 or WAV files in order
  • Ensure consistent sample rates across chunks
  • Verify audio continuity after merging

Manage memory

Process chunks iteratively rather than loading all responses into memory simultaneously. This is crucial for long texts, as holding multiple audio blobs can consume significant RAM. Stream or write files directly to disk when possible.

  • Use iterative processing for large texts
  • Write audio to disk instead of storing in memory
  • Monitor memory usage during batch generation

Error handling

Sound wave illustration for: Error handling

Reliable synthesis requires robust error handling. The API returns standard HTTP status codes for failures, such as 401 for invalid keys or 429 when exceeding the 60 requests per minute limit. Catching these exceptions prevents your LMS integration from crashing during batch processing.

Try/except blocks

Wrap your API calls in try/except blocks to catch specific exceptions like OpenAIError or RateLimitError. This allows you to distinguish between authentication issues and temporary server errors. Failed requests are free, but the SDK may raise exceptions before you can check the billing status.

  • Catch AuthenticationError for invalid keys.
  • Handle RateLimitError for 429 responses.
  • Log APIError for server-side issues.

Retry logic

Implement exponential backoff for transient errors. Since requests are processed sequentially under load, a brief pause between retries helps avoid hitting the rate limit again immediately. Retrying up to three times is sufficient for most transient network issues.

Logging errors

Log error details including the request ID, timestamp, and error message. This metadata is crucial for debugging billing discrepancies or identifying which course materials failed to generate. Store logs securely, as they may contain text snippets.

Error handling

Performance tips

Sound wave illustration for: Performance tips

Optimize your TTS workflow by managing concurrency and reducing redundant API calls. Since requests are processed sequentially under load, understanding rate limits (60 req/min) helps you avoid queuing delays. Efficient Python patterns ensure steady throughput for generating course audio without unnecessary waits or wasted credits.

Leverage async I/O to handle multiple text chunks concurrently while respecting the 60 requests per minute limit. Cache responses for identical text inputs to save costs and processing time, as generated audio is not stored server-side but can be locally reused for repeated lesson deliveries.

Batch requests

Group short text segments into single API calls where possible, though the API processes one input per request. Monitor your rate limit of 60 requests per minute to avoid queuing delays, especially when generating full course chapters. Sequential processing means longer texts may take time proportional to their length.

  • Respect the 60 requests/minute limit per key.
  • Queue requests if exceeding the rate limit.
  • Monitor queue depth to prevent bottlenecks.

Async processing

Use Python’s asyncio to send multiple synthesis requests concurrently. This maximizes throughput without violating the per-key rate limit. Since synthesis takes time (roughly real-time), async handling prevents your application from blocking while waiting for audio generation to complete.

Combine async requests with a semaphore to control concurrency. This ensures you stay within the 60 requests per minute constraint while keeping your LMS integration responsive and efficient during peak usage hours.

  • Use asyncio for non-blocking I/O.
  • Implement a semaphore for concurrency control.
  • Stay within the 60 req/min limit.

Caching responses

Store generated audio files locally or in your LMS media library for identical text inputs. Since the API does not store generated audio, caching saves both generation time and character costs. Use a hash of the input text, voice, speed, and format as the cache key.

Invalidate the cache if any parameter changes, such as speed or voice selection. This approach is particularly effective for static course materials that are replayed frequently by students, ensuring consistent audio quality and reduced API dependency.

  • Cache by input text + voice + speed + format.
  • Invalidate cache on parameter change.
  • Store locally or in LMS media library.

Common issues

Sound wave illustration for: Common issues

Even with correct syntax, requests can fail due to credential or configuration issues. Understanding these common errors helps you resolve them quickly without disrupting your audio generation pipeline.

Most issues stem from simple oversights in key management, rate limits, or format selections. Addressing them ensures consistent delivery of MP3 or WAV files for your course materials.

Invalid API key

Ensure the key starts with tts- and matches the account on 788t.info. Keys are single-active; issuing a new one invalidates the old immediately.

Verify your environment variable is correctly loaded. A mismatched base URL also causes authentication failures.

  • Check for trailing spaces in the key string.
  • Confirm the key was issued for this specific site domain.

Rate limit exceeded

The API allows 60 requests per minute per key. Exceeding this triggers a 429 error. New accounts start with 10 requests per minute until the first top-up.

Implement exponential backoff in your Python script to handle temporary spikes gracefully without losing data.

  • Monitor your usage dashboard for real-time limits.
  • Split large batches if nearing the 60 req/min threshold.

Unsupported format

Only mp3, wav, opus, flac, and pcm are supported. Sending an unsupported format returns an error immediately.

Ensure your LMS or audio player can decode the selected format. MP3 and WAV are universally compatible.

  • Use response_format parameter to specify output.
  • Verify client-side decoder compatibility.

Testing

Sound wave illustration for: Testing

Testing ensures your LMS integration handles synthesis reliably. Verify that character counts align with billing expectations and that audio files are generated correctly for course materials.

Use unit tests to validate input formatting and response parsing. Integration tests confirm end-to-end delivery of MP3 or WAV files to your learning platform without data loss or corruption.

Unit tests

Validate request structures before sending them to the API. Check that the input text does not exceed 4096 characters and that voice parameters are within acceptable ranges.

Test boundary conditions, such as empty strings or maximum speed limits, to ensure the library handles edge cases gracefully without crashing.

  • Verify character count limits
  • Check voice parameter validity
  • Test input text formatting

Integration tests

Send real requests to the API endpoint using a test API key. Confirm that the returned audio file is playable and matches the expected format (MP3 or WAV).

Ensure that the integration with your LMS correctly receives and stores the generated audio files for student access.

  • Verify API endpoint connectivity
  • Check audio file format
  • Test LMS file storage

Mock responses

Use mock responses for rapid testing without incurring API charges. Simulate successful synthesis and error responses to test error handling logic.

Mock rate limit responses to verify that your retry logic works correctly under load without waiting for actual rate limit thresholds.

  • Simulate success responses
  • Simulate error responses
  • Mock rate limits

Deployment

Sound wave illustration for: Deployment

Deploying the TTS integration into your LMS workflow requires separating configuration from code. Store your API key and base URL as environment variables to avoid hardcoding secrets in your repository. This ensures that credentials can be rotated or updated without modifying the application source.

Environment variables

Set OPENAI_API_KEY and OPENAI_BASE_URL in your production environment. The base URL should point to https://api.788t.info/v1. This allows the OpenAI Python SDK to route requests correctly without code changes.

  • Use .env files for local development.
  • Inject variables via your hosting provider's dashboard.
  • Verify values are loaded before making the first request.

Secret management

Since you only need one active key per account, manage it centrally. Rotate the key in the dashboard if needed; the old key stops immediately. Do not store the key in version control.

  • Use a secrets manager for production.
  • Limit key visibility to the deployment service.
  • Monitor usage via the dashboard for anomalies.

Production ready

Ensure your application handles the 60 requests per minute rate limit gracefully. Implement exponential backoff for retries. Cache generated audio for static course materials to reduce API calls and costs. Monitor character usage against your balance.

  • Implement retry logic with jitter.
  • Cache audio files for unchanging text.
  • Set up alerts for low balance.

Support

Sound wave illustration for: Support

Support is available via email for technical inquiries and billing questions. We do not offer phone support or live chat, so please allow time for a written response.

Our documentation covers all API endpoints, Python examples, and error codes. It is the primary resource for integration issues.

Documentation link

The complete API reference includes code samples for Python, request schemas, and usage limits. It is updated regularly to reflect current capabilities.

Email support

Send details to [email protected]. Include your API key, request ID, and error logs for faster resolution.

Community forums

Currently, we do not have a public community forum. For general questions, refer to the documentation or contact support directly.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. We retain only request metadata—timestamp, character count, and status—for billing and operational purposes.

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. Creative Commons Attribution 4.0
  3. LibriTTS-R paper (arXiv 2305.18802)
  4. openai-node on GitHub
  5. TRON developer hub: TRC-20
  6. IETF RFC 7845: Ogg Opus
  7. LibriTTS-R corpus (OpenSLR 141)
  8. LibriVox public-domain audiobooks
  9. openai-python on GitHub
  10. MDN: Web Speech API
  11. Node.js documentation
  12. ISO 639 language codes

More on this site