How to Use TTS API with Python 3 for Radio Ads?

By Route 168 editorial team · Updated 2026-11-19

This guide shows advertising agencies and radio producers how to automate voiceover generation using Python 3. Instead of manually uploading scripts or managing complex tools, you can send text directly from your code and receive audio files instantly. This approach lets you integrate TTS into your existing content creation pipelines, ensuring consistent quality for radio spots and ads.

You will learn to set up your environment, write scripts using the standard OpenAI-compatible SDK, and handle responses efficiently. We cover practical details like splitting long texts, optimizing for ad formats, and managing rate limits. By the end, you will have a reliable script that generates high-quality synthetic voiceovers ready for broadcast.

How to Use TTS API with Python 3 for Radio Ads?

Frequently asked questions

What is Python 3?

Python 3 is a modern, high-level programming language widely used for scripting and automation. It provides clear syntax and robust libraries, making it ideal for developers who need to integrate APIs like ours into their advertising workflows efficiently and reliably.

How does the API work?

You send a POST request to https://api.route168.cc/v1/audio/speech with your text and parameters. The API processes the request and returns an audio file directly in the response. You can use standard HTTP libraries or the OpenAI SDK by adjusting the base URL.

Is Python 3 required?

No, Python 3 is not strictly required. You can use any language that supports HTTP requests. However, Python is recommended for its simplicity in handling JSON payloads and binary audio data, making integration straightforward for radio production scripts.

Can I use other languages?

Yes, any language capable of making HTTP POST requests works. Since our endpoint matches the OpenAI speech format, you can use JavaScript, Go, Ruby, or C#. Just update the base URL to https://api.route168.cc/v1 and use your API key.

How do I install the SDK?

We recommend using the official OpenAI Python SDK. Install it via pip: pip install openai. Then, initialize the client by setting the base_url to https://api.route168.cc/v1 and providing your tts-... API key in the authorization header.

What libraries do I need?

You primarily need the openai library for easy SDK integration. For direct HTTP requests, use standard libraries like requests or urllib. No additional specialized libraries are required, as the API returns standard audio formats like MP3, WAV, or FLAC.

How do I send a request?

Create a JSON body with model, input, voice, and response_format. Include your API key in the Authorization header. Send a POST request to https://api.route168.cc/v1/audio/speech. Ensure your text does not exceed 4096 characters per request.

How do I receive audio?

The API returns the audio file directly in the response body as binary data. The format depends on your response_format parameter (mp3, wav, opus, flac, or pcm). Check the response status code to ensure success before processing the binary content.

How do I save the audio?

Write the binary response content to a file using your programming language’s file I/O functions. For example, in Python, open a file in binary write mode (wb) and save the response data to create the final audio asset for your radio ad.

How do I split long texts?

Split your script into chunks of up to 4096 characters. Each chunk becomes a separate API request. You can split by sentences or words, ensuring no single request exceeds the character limit to avoid errors and maintain synthesis quality.

How do I join audio files?

After generating audio for each text chunk, concatenate the resulting files. Use libraries like pydub or ffmpeg to merge the individual audio segments into a single continuous file, preserving the flow of your radio advertisement or content piece.

How do I handle errors?

Check the HTTP status code. If synthesis fails, the charge is returned in full. Handle network errors and rate limits (60 requests/minute) by implementing retry logic with exponential backoff. Always validate your input text length and voice availability before sending.

How do I optimize for ads?

Use voices like felix for energetic promos or sage for instructional content. Adjust the speed parameter between 0.25 and 4.0 to fit time slots. Keep texts concise under 4096 characters to ensure quick generation and consistent audio quality for your spots.

How do I deploy the script?

Run your Python script on any server or local machine with internet access. Ensure your API key is secure. For automated workflows, schedule the script using cron jobs or integrate it into your CI/CD pipeline for on-demand ad generation.

Why Python for Radio Ads?

Sound wave illustration for: Why Python for Radio Ads?

Python allows radio producers to automate voice generation directly from scripts, eliminating manual uploads and complex toolchains. By treating text-to-speech as a programmatic step, agencies can dynamically generate ad copies and radio spots at scale without human intervention for each file.

This approach ensures consistency across campaigns and reduces production time significantly. With simple code, you can loop through multiple scripts, adjust parameters like speed and voice, and manage large volumes of audio files efficiently.

Automation benefits

Automating TTS with Python removes the bottleneck of manual audio file creation. You can trigger synthesis for hundreds of ad variations instantly, ensuring rapid turnaround for time-sensitive radio spots.

The API processes requests sequentially, handling the queue logic so you can focus on content strategy rather than file management.

  • Generate multiple ad variations automatically
  • Reduce manual file creation time
  • Scale production without hiring more staff

Script flexibility

Python scripts allow precise control over each TTS request. You can easily modify parameters such as voice selection, speed (0.25–4.0), and response format (mp3, wav, opus, flac, pcm) within your code.

This flexibility enables dynamic content insertion, allowing you to personalize ads based on real-time data or campaign requirements without changing the underlying workflow.

Integration ease

The API follows the OpenAI SDK shape, making it straightforward to integrate into existing Python projects. Simply change the base URL and use your API key to start sending requests.

This compatibility means you can leverage existing libraries and tools, reducing the learning curve for developers and producers already familiar with standard Python ecosystems.

Setting Up the Environment

Sound wave illustration for: Setting Up the Environment

Python 3 provides a stable foundation for automating voiceover generation in advertising workflows. Using the official OpenAI SDK simplifies communication with our API, allowing you to focus on script logic rather than HTTP details.

We recommend using virtual environments to keep dependencies clean. This ensures that your TTS integration remains isolated and reproducible across different development or production servers.

Install Python 3

Ensure you have Python 3.8 or higher installed on your system. Most modern Linux distributions and macOS come with Python pre-installed, but Windows users may need to download the installer from python.org. Verify the installation by running python --version in your terminal.

  • Download the latest stable release from python.org
  • Add Python to your system PATH during installation
  • Verify installation with python --version

Install required libraries

Install the openai Python package using pip. This library handles the JSON serialization and HTTP requests to our API endpoint. You may also want pydub or ffmpeg if you need to merge the audio parts later.

  • Run pip install openai
  • Optionally install pydub for audio manipulation
  • Ensure requests is available as a dependency

Configure API key

Retrieve your API key from the /get-api-key/ dashboard. Set it as an environment variable named OPENAI_API_KEY for security. The SDK automatically detects this variable, so you do not need to hardcode credentials in your script. Remember that each account has one active key; issuing a new one invalidates the previous one immediately.

  • Set export OPENAI_API_KEY='tts-your-key-here'
  • Use environment variables for secure access
  • Regenerate keys via the dashboard if needed

Writing the Script

Sound wave illustration for: Writing the Script

Using Python makes generating radio spots straightforward because the official OpenAI SDK works with our API by simply changing the base URL. This allows you to leverage familiar libraries like requests or openai without learning a new protocol.

You start by importing the necessary modules and initializing the client with your API key. This setup ensures that every request is authenticated and routed correctly to our speech endpoint.

Import the SDK

Import the requests library or the openai package. If using openai, set the base_url to https://api.route168.cc/v1. This ensures compatibility with standard TTS workflows.

Ensure your Python environment is version 3.6 or higher. Install the package using pip install openai or pip install requests.

  • import requests or from openai import OpenAI
  • base_url = 'https://api.route168.cc/v1'

Define the request

Construct a JSON payload containing the model, input, voice, and response_format. The model should be tts-1 or tts-1-hd. The input field holds your radio script text, limited to 4096 characters.

Specify the voice (e.g., aria, felix) and response_format (e.g., mp3). You can also set speed between 0.25 and 4.0 to adjust the pacing of the voiceover.

  • model: 'tts-1' or 'tts-1-hd'
  • voice: 'aria', 'nova', etc.
  • response_format: 'mp3' or 'wav'

Send the payload

Send a POST request to /v1/audio/speech with your JSON body and the Authorization: Bearer header. The API returns the audio file directly in the response body.

Check the status code. A 200 OK response means the audio was generated successfully. You can then save the binary data to a file for your radio production workflow.

  • POST https://api.route168.cc/v1/audio/speech
  • Authorization: Bearer tts-...

Handling the Response

Sound wave illustration for: Handling the Response

Once the API returns a successful response, you receive the raw audio binary data. This payload contains the synthesized speech in your requested format, ready for immediate use in your radio ad production pipeline without needing intermediate storage steps.

You can save this binary stream directly to disk. This allows you to quickly generate individual voiceovers for multiple ad scripts and assemble them later in your audio editing software, ensuring your automation workflow remains efficient and error-free.

Receive audio data

The response body contains the raw audio bytes. Ensure your Python script handles binary data correctly to avoid corruption.

Check the response headers to confirm the content type matches your selected format (mp3, wav, etc.).

  • Use response.content to access raw binary data.
  • Verify Content-Type header matches audio/mp3 or similar.

Save to file

Write the binary content to a local file using standard Python file I/O operations. This creates a standalone audio asset you can upload to your radio station's playlist or editing suite.

This step is crucial for batch processing multiple ad spots simultaneously.

  • Open file in binary write mode ('wb').
  • Ensure the filename extension matches the format.

Check status codes

Verify the HTTP status code is 200 OK. Any other code indicates a problem with the request or your API key.

Failed requests are free, so check the status before assuming a charge occurred.

  • 200: Success.
  • 4xx/5xx: Check error message in response body for details.

Processing Long Texts

Sound wave illustration for: Processing Long Texts

Radio scripts often exceed the 4,096-character limit per request. To handle longer ad spots, you must split the input text into smaller segments before sending them to the API.

Split into chunks

Divide your script into parts of up to 4,096 characters each. Ensure boundaries preserve natural pauses to avoid awkward audio cuts.

Generate each part

Send each chunk as a separate POST request. Since requests are processed sequentially, longer scripts may queue briefly under load.

Join audio files

Combine the returned audio files in order. Use your preferred audio library to merge the segments into a single broadcast-ready file.

Optimizing for Ads

Sound wave illustration for: Optimizing for Ads

Selecting the correct voice and speed ensures your radio spot sounds professional and fits the ad duration. Our eight presets cover everything from warm narration to energetic promos, allowing you to match the tone of your brand without manual editing.

Adjusting the speed parameter lets you compress or expand the audio to fit exact time slots. You can fine-tune the delivery between 0.25x and 4.0x speed, ensuring the voiceover aligns perfectly with your visual or audio cues.

Choose the right voice

Each voice has a distinct character. Use 'felix' for energetic promo spots or 'aria' for clear, warm narration. You can also choose 'atlas' for neutral news-style delivery or 'nova' for upbeat content. All voices support all 23 languages, so you can mix languages if needed.

  • Use 'felix' for high-energy advertisements
  • Use 'aria' for clear, warm narration
  • Use 'atlas' for neutral news-style delivery
  • Use 'nova' for upbeat content
  • Use 'luna' for soft storytelling
  • Use 'milo' for friendly conversation

Adjust speed

Speed affects how fast the text is read. You can set the speed between 0.25 and 4.0. This helps you fit the audio into a specific time slot, such as a 30-second radio spot.

  • Speed range: 0.25 to 4.0
  • Adjust to fit time slots
  • Test different speeds for best fit

Select format

Choose the audio format that works best for your radio station. MP3 is small and easy to share, while WAV is uncompressed and high quality. FLAC and OPUS offer lossless or efficient compression. PCM is raw audio for further processing.

  • MP3: Small, easy to share
  • WAV: Uncompressed, high quality
  • FLAC: Lossless compression
  • OPUS: Efficient compression
  • PCM: Raw audio for processing

Error Handling

Sound wave illustration for: Error Handling

Robust error handling ensures your radio ad campaigns run smoothly without manual intervention. By catching exceptions and managing retries, you prevent single API failures from halting the entire voiceover production pipeline, keeping your content delivery on schedule.

Catch exceptions

Wrap your API calls in try-except blocks to handle network issues or invalid responses gracefully. This prevents your script from crashing when the service is temporarily unavailable or returns an unexpected status code.

  • Catch requests.exceptions.ConnectionError for network drops
  • Handle HTTPError for 4xx/5xx status codes
  • Validate JSON responses before processing audio data

Retry on failure

Implement a retry logic for transient errors like 429 (rate limit) or 503 (service unavailable). Since requests are processed sequentially, brief pauses between retries help avoid overwhelming the queue during high load.

  • Exponential backoff for rate limits
  • Retry up to 3 times for server errors
  • Abort after max retries to avoid infinite loops

Log errors

Log error details including the timestamp, request ID, and error message. This helps diagnose issues later and ensures you can quickly identify if a specific voice or model caused a failure.

  • Log error type and message
  • Record request parameters for debugging
  • Track retry attempts and final status
Error Handling

Testing Your Script

Sound wave illustration for: Testing Your Script

Testing ensures your automation pipeline works before you commit budget to a full radio spot campaign. A quick validation step prevents wasted credits on malformed requests or unexpected audio artifacts.

By verifying the output against your script’s logic, you confirm that the API correctly handles your specific voice and format preferences, ensuring consistency across all generated assets.

Use sample text

Start with a short, representative phrase from your ad script, such as a call-to-action or brand slogan. This keeps the test fast and inexpensive.

Send the text through your Python script using the tts-1 model. This confirms that your API key and base URL configuration are correct.

  • Use a phrase under 50 characters to minimize cost.
  • Verify the request returns a 200 status code.

Verify output

Download the returned audio file and play it to check for clarity and correct pacing. Ensure the voice matches your selected preset, such as 'sage' for instructional tones.

Confirm the file format matches your response_format setting, whether MP3 for web use or WAV for broadcast editing.

  • Listen for unnatural pauses or clipped words.
  • Check file integrity using a media player.

Check timing

Note how long the request takes. Short phrases may take a few seconds, while longer texts process at roughly real-time speed (25 characters per second).

If your script sends multiple requests, remember they are processed sequentially. Monitor the queue time to ensure your automation doesn’t stall under load.

  • Expect a few seconds for short phrases.
  • Long texts generate at ~25 chars/second.

Deployment

Sound wave illustration for: Deployment

Once your script works locally, move it to a reliable environment. Cron jobs or task schedulers can trigger synthesis at specific times, ensuring radio spots are ready before airtime. This removes manual bottlenecks from your production workflow.

For production, run the script as a background service. Since requests are processed sequentially, avoid overlapping calls that might queue up. Keep the API key secure in your environment variables to prevent unauthorized usage.

Schedule tasks

Use system cron jobs or cloud schedulers to automate generation. This ensures ads are synthesized on a fixed schedule, such as nightly updates for daily rotations.

Set up recurring jobs to regenerate spots if voice models update or if you need fresh variations for A/B testing campaigns.

  • Use cron for daily ad rotations
  • Schedule bulk generation during off-peak hours
  • Automate weekly ad refreshes

Run in production

Deploy the script on a stable server or container. Ensure the environment has consistent network access to api.route168.cc.

Monitor the queue behavior; since requests are processed one after another, long texts may take time. Plan your deployment window accordingly to avoid blocking other tasks.

  • Use environment variables for keys
  • Ensure stable network connectivity
  • Handle sequential processing delays

Monitor usage

Track your character count and request limits via the dashboard. With a 60 requests per minute limit, monitor usage to avoid throttling during high-volume campaigns.

Check for failed requests, which are free, but ensure your script logs them to maintain accurate billing records.

  • Watch character limits closely
  • Monitor requests per minute
  • Log failed synthesis attempts

Best Practices

Sound wave illustration for: Best Practices

Efficient API usage relies on reusing your single active key rather than generating new ones unnecessarily, as each new key instantly invalidates the previous one. This simplifies integration across your Python scripts and ensures consistent billing tracking.

Reuse API keys

Store your key securely in environment variables. Avoid generating multiple keys for different environments unless necessary, as only one key remains active at a time.

Cache results

Since generation takes time, cache audio files for static radio spots. This avoids re-processing identical text and reduces costs, as you only pay for unique character inputs.

Monitor limits

Track your 60 requests per minute limit. Implement exponential backoff in your Python script to handle rate limiting gracefully without dropping audio generation jobs.

Common Issues

Sound wave illustration for: Common Issues

Even with robust scripts, radio production workflows occasionally hit snags. Understanding these common hurdles helps you keep your voiceover pipeline running smoothly without unnecessary downtime or wasted credits.

Connection errors

Network interruptions or server load can cause request timeouts. Since requests are processed sequentially, high demand may introduce queuing delays, making short timeouts feel like failures. Ensure your script handles HTTP errors gracefully and implements exponential backoff for retries.

Character limits

Each API call accepts up to 4,096 characters. Exceeding this limit returns an error rather than truncating the text. Always split your script into chunks before sending requests to ensure complete delivery of your radio spot dialogue.

Voice selection

Mismatched language detection occurs when Latin-script text isn't explicitly tagged. If your ad is in German but uses Latin characters without the language field, the system may default to English. Always specify the ISO code for non-English languages to ensure correct pronunciation.

Next Steps

Sound wave illustration for: Next Steps

You now have a working script that generates radio spots. The next step is to refine your audio quality and expand your production capabilities. Experimenting with different voices and formats helps you find the perfect sound for each campaign.

Explore more voices

The API offers eight distinct voice presets, ranging from the warm narrator aria to the deep documentary tone of orion. Each voice can speak all 23 supported languages, allowing you to produce multilingual ads without hiring separate voice actors. Test how different tones resonate with your target audience by generating short test clips.

  • Aria for clear narration
  • Nova for upbeat spots
  • Atlas for neutral news
  • Orion for deep documentaries

Try different formats

Choose the output format that best fits your workflow. MP3 is efficient for web and mobile delivery, while WAV and FLAC provide high-quality audio for studio integration. If you need raw data for further processing, PCM is available. Selecting the right format ensures optimal balance between file size and audio fidelity.

  • MP3: Efficient for web and mobile delivery
  • WAV/FLAC: High-quality for studio integration
  • OPUS: Low bandwidth usage
  • PCM: Raw audio data

Scale your workflow

As your ad volume grows, integrate the API directly into your content management system or automation tools. You can process longer texts by splitting them into 4096-character chunks and joining the resulting audio files. Monitor your usage to stay within the 60 requests per minute limit and ensure consistent delivery for your campaigns.

  • Integrate with CMS tools
  • Split long texts for processing
  • Monitor rate limits
  • Automate batch generation

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. Its clear, upbeat delivery makes it ideal for radio spots where you need to convey enthusiasm and positivity without sounding artificial.

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. Node.js documentation
  3. FFmpeg documentation
  4. curl documentation
  5. MDN: Web Speech API
  6. W3C WAI: making audio and video accessible
  7. OpenAI API reference: create speech
  8. IETF RFC 7845: Ogg Opus
  9. openai-node on GitHub
  10. LibriTTS-R corpus (OpenSLR 141)
  11. ISO 639 language codes
  12. LibriTTS-R paper (arXiv 2305.18802)

More on this site