How to Generate Audio from Python for News Content?

By NewsBrio editorial team · Updated 2026-11-19

This guide shows news product teams how to automate audio generation using Python and the NewsBrio API. We cover integrating with your CMS, handling long articles, and managing formats. You will learn to configure the API, split text into chunks, and concatenate audio files efficiently.

Ideal for teams building daily audio briefings or archiving editorial content, this page provides concrete Python examples. We explain voice selection, error handling, and deployment considerations. Get practical steps to turn text into audio reliably, without complex setup or extra dependencies.

How to Generate Audio from Python for News Content?

Frequently asked questions

Is Python the best language for this API?

Python is not the best; it is simply convenient. The API follows the OpenAI speech endpoint shape, so any language with an HTTP client works. We recommend Python for news teams because it integrates easily with CMS workflows and allows quick scripting for editorial text processing.

Can I use this API with other programming languages?

Yes. Any language that can send a POST request with JSON works. You can use the official OpenAI SDKs by changing the base_url to https://api.innwa.info/v1. Plain HTTP requests with the correct Authorization header also work perfectly across JavaScript, Ruby, or Go.

How do I handle special characters in my text?

Send the text as a standard JSON string in the input field. The API handles standard Unicode characters automatically. Just ensure your JSON is valid. Special punctuation and symbols count toward the 4096 character limit, so ensure your payload fits within that constraint.

What is the maximum text length per request?

The maximum input length is 4096 characters per request. If your editorial content exceeds this, split the text into smaller parts. Generate audio for each part separately, then join the resulting audio files to create a complete broadcast segment or news update.

Can I generate audio while editing my script?

You can generate audio while editing, but requests are processed sequentially. Longer texts take roughly real-time to generate. During editing, you may experience queue delays if other requests are processing. Plan your generation steps to avoid blocking your editorial workflow during peak usage.

Do I need to install additional libraries?

No. You can use the official OpenAI Python SDK or plain HTTP libraries like requests. Change the base_url to https://api.innwa.info/v1. No custom SDK is required. Standard JSON parsing and HTTP client tools are sufficient for integration.

How do I debug a failed API request?

Check the HTTP status code and response body for error details. Failed requests are free, so no charge is applied. Ensure your text is under 4096 characters and your API key is valid. If issues persist, verify your JSON structure and speed limits within the 0.25–4.0 range.

Can I use this API in a serverless environment?

Yes. The API is stateless and works well with serverless functions. Each request is independent. Just ensure you handle the 60 requests per minute rate limit per key. Serverless environments are ideal for triggering audio generation from CMS events or editorial workflows efficiently.

Is the API suitable for real-time news updates?

It is suitable for near-real-time updates, but not instantaneous. Requests are processed sequentially, so under load, you may experience queue delays. Short phrases take a few seconds. For breaking news, plan for a slight delay between text submission and audio availability in your broadcast workflow.

How do I store the generated audio files?

The API returns the audio file in the response but does not store it. You must save the file to your own infrastructure. Generated audio is not retained by our service. Store the files in your CMS or media library as needed for your news product.

Can I change the voice after generating audio?

No. Once audio is generated, the voice is fixed. You must regenerate the audio if you want a different voice. The API does not support post-generation voice modification. Select your desired voice from the 8 presets before sending the request to ensure the correct output.

Do I need to pay for each generation separately?

No. You pay based on total characters processed, not per request. The rate is $10 per 1 million characters. Failed requests are free. You top up your balance once, and charges are deducted automatically as you generate audio, regardless of how many requests you make.

How do I handle large-scale generation?

Split long texts into chunks of 4096 characters. Generate audio for each chunk and join the files. Monitor your rate limit of 60 requests per minute. For large volumes, space out requests to avoid queue delays. Use the balance dashboard to track character usage efficiently.

Can I use the API for podcast production?

Yes. The API supports 23 languages and 8 voice presets. Generate audio for your script, split if necessary, and join the files. The synthetic watermark is inaudible. Since audio is not stored, you manage your podcast assets directly in your production workflow.

Why Use Python for News Audio?

Sound wave illustration for: Why Use Python for News Audio?

Python offers a straightforward way to integrate text-to-speech directly into your newsroom’s existing content management systems. By using a standard REST API, you can programmatically convert editorial drafts into audio files without building complex custom pipelines or relying on heavy desktop applications.

Direct integration with content management systems

News product teams can embed audio generation directly into their editorial workflows. When an article is published, a simple script can trigger the API to produce an audio version, ensuring that audio assets are available immediately alongside the text.

Automation of daily audio briefings

You can automate the creation of daily news briefings by feeding curated headlines into the API. This allows you to deliver consistent audio updates to subscribers without manual recording, saving editorial time while maintaining a reliable publishing schedule.

Scalable batch processing for archives

Python’s ability to handle loops and asynchronous requests makes it ideal for processing large backlogs. You can systematically convert entire archives of articles into audio, creating a searchable audio library that grows automatically as your content library expands.

Setting Up the API Key

Sound wave illustration for: Setting Up the API Key

To begin your integration, visit https://innwa.info/get-api-key/ and create an account using either Google or your email and password. This step establishes your unique identity on the NewsBrio platform, allowing you to manage your API access and billing preferences securely.

Create an account on the platform

Signing up is quick and requires no credit card. Once registered, you can immediately access your dashboard to view your API key and initial balance.

Retrieve your Bearer token

Your API key appears on the dashboard as a string starting with 'tts-'. Copy this value precisely; it serves as your Bearer token for authenticating every request to https://api.innwa.info/v1. Note that generating a new key instantly invalidates the previous one.

Securely store the key in environment variables

For production stability, do not hardcode your key in source files. Instead, store it in environment variables (e.g., using the python-dotenv library) so it remains secure across deployments and version control systems.

  • Use single quotes to prevent shell expansion issues.
  • Ensure your .env file is listed in .gitignore.
  • Rotate keys regularly via the dashboard if needed.

Making the First API Call

Sound wave illustration for: Making the First API Call

Generating audio from Python is straightforward because our API mirrors the OpenAI speech endpoint structure. You do not need a custom library; the standard OpenAI SDK handles the heavy lifting by simply pointing to our base URL.

This approach lets you use familiar code patterns while benefiting from our specific voice models and pricing. It ensures compatibility with existing workflows without requiring complex new integrations for news product teams.

Install the OpenAI Python package

Run pip install openai in your terminal to add the package to your project dependencies. The API uses the same request shape as the OpenAI speech endpoint, so the official OpenAI SDKs work by changing the base_url.

Configure the base_url for our API

Initialize the client by setting the base_url to https://api.innwa.info/v1. Authenticate using your Bearer token obtained from the dashboard. This redirects all standard TTS requests to our infrastructure while keeping your code compatible with OpenAI-style libraries.

Ensure your API key is stored securely in environment variables to prevent accidental exposure in your code repository or logs.

  • Set base_url to https://api.innwa.info/v1
  • Use Authorization: Bearer <your-key> header
  • Store keys in environment variables

Send a simple text-to-speech request

Construct a request using the Audio.speech method. Pass your news text, select a voice like 'atlas' for neutral news delivery, and specify the model 'tts-1'. The SDK handles the JSON serialization and HTTP POST to v1/audio/speech.

The response contains the audio binary data. Save this directly to an MP3 or WAV file for immediate use in your CMS or broadcast workflow.

  • Use Audio.speech method
  • Set model to 'tts-1' or 'tts-1-hd'
  • Specify voice (e.g., 'atlas')
  • Handle binary response data

Handling Long Articles

Sound wave illustration for: Handling Long Articles

When your news article exceeds the API’s 4,096-character limit, you must split the input text into smaller segments. Each segment is processed independently, ensuring that no single request violates the input constraint while maintaining the narrative flow of your editorial content.

Split text into 4096-character chunks

Divide your article string at natural boundaries, such as sentence ends or paragraph breaks, rather than arbitrary character cuts. This preserves readability when the audio segments are joined later. Ensure that punctuation and spaces are counted toward the character limit, as they contribute to the 4,096-character budget per request.

  • Identify sentence boundaries using simple regex or NLP libraries like nltk or spacy.
  • Ensure each chunk stays strictly under 4,096 characters, including spaces and punctuation.
  • Avoid splitting mid-sentence to prevent disjointed audio playback.

Generate audio for each chunk

Send each text chunk as a separate POST request to the v1/audio/speech endpoint. The API processes requests sequentially, so under heavy load, you may experience queue wait times. Use the speed parameter to adjust generation time if needed, but note that typical processing is roughly real-time (25 characters per second).

  • Use the tts-1 or tts-1-hd model for consistent engine quality.
  • Specify the voice (e.g., atlas for news) and response_format in each request.
  • Handle rate limits (60 requests/minute) by implementing retry logic with exponential backoff.

Concatenate audio files programmatically

Once all audio files are generated, concatenate them in the original order of the text chunks. For formats like MP3 or WAV, use libraries such as pydub or ffmpeg to merge the files. This creates a single audio file that plays continuously, mimicking a complete read of the original article.

  • Use pydub to load and concatenate audio segments in Python.
  • Ensure consistent sample rates and formats across all chunks before merging.
  • Test the final output for audio gaps or clicks between segments.

Choosing the Right Voice

Sound wave illustration for: Choosing the Right Voice

Selecting the correct voice preset ensures your news audio matches the editorial tone. Our eight voices cover distinct styles, from neutral reporting to deep documentary narration, allowing you to tailor the listening experience for different content types.

Atlas for straightforward news delivery

Atlas offers a neutral, professional tone ideal for standard news updates. Its clear, balanced delivery ensures listeners focus on the information rather than the narrator’s personality, making it perfect for daily briefings or breaking news segments.

  • Neutral and professional tone
  • Ideal for standard news updates
  • Ensures focus on information

Milo for engaging reader segments

Milo provides a friendly, conversational voice suited for engaging reader segments or lighter editorial content. His approachable style helps humanize the news, making complex stories feel more accessible and inviting to a broader audience.

  • Friendly and conversational style
  • Humanizes editorial content
  • Approachable for broader audiences

Orion for in-depth documentary features

Orion delivers a deep, authoritative voice perfect for in-depth documentary features or long-form journalism. His rich tone adds gravity and seriousness to detailed reports, enhancing the listener’s immersion in serious, investigative storytelling.

Use Orion when the content requires a sense of weight and historical context, distinguishing it from standard news delivery.

  • Deep, authoritative tone
  • Perfect for long-form journalism
  • Adds gravity to serious stories

Managing Audio Formats

Sound wave illustration for: Managing Audio Formats

Choosing the right audio format balances quality, file size, and compatibility. Our API supports multiple output types, allowing you to optimize storage and playback performance based on your specific news delivery needs.

Selecting the appropriate format ensures your audio integrates smoothly into existing CMS workflows without unnecessary bloat or quality loss.

Use MP3 for web players

MP3 is the standard for web audio players. It offers a good balance between file size and sound quality, making it ideal for quick-loading news segments on mobile and desktop sites.

Use WAV for high-fidelity needs

WAV provides uncompressed audio suitable for professional broadcast workflows or archival purposes. Use this format when preserving the exact nuance of the synthesized voice is critical for editorial standards.

Use OPUS for efficient storage

OPUS offers efficient compression, making it suitable for long-form content or large archives. It reduces storage costs while keeping files accessible for future use.

Error Handling in Python

Sound wave illustration for: Error Handling in Python

Python scripts must handle the 60 requests-per-minute limit gracefully to avoid interrupting news workflows. Catching RateLimitError allows your application to pause and retry without crashing during peak editorial bursts.

Catch API rate limit errors

Implement retry logic with exponential backoff when receiving a 429 status code. This ensures your batch processing pipeline remains stable even when sending multiple article segments.

  • Check for RateLimitError in your exception handler.
  • Implement exponential backoff to avoid immediate re-failure.
  • Log the retry attempt for auditing purposes.

Handle network timeouts gracefully

Network hiccups can occur during high-traffic news cycles. Set a reasonable timeout (e.g., 30 seconds) to prevent your script from hanging indefinitely while waiting for audio synthesis.

  • Set a connection timeout of 10 seconds.
  • Set a read timeout of 30 seconds.
  • Retry once on timeout before failing.

Log failures for debugging

Record the specific input text, voice, and error code when a request fails. This metadata helps you identify if a specific article format or voice preset causes consistent errors.

  • Log the request ID and timestamp.
  • Store the input text snippet (first 100 chars).
  • Record the HTTP status code and error message.
Error Handling in Python

Optimizing for Speed

Sound wave illustration for: Optimizing for Speed

Optimizing your Python integration for speed ensures timely audio delivery, especially during breaking news cycles. Since requests are processed sequentially under load, minimizing latency becomes critical for maintaining a smooth user experience.

Pre-fetch voices and models

Cache the available voices and models locally using the GET /v1/voices and GET /v1/models endpoints. This reduces initial API calls and ensures you have immediate access to configuration details without waiting for network responses during generation.

  • Cache voice lists locally to avoid repeated API calls.
  • Store model metadata (tts-1, tts-1-hd) for quick selection.

Use async requests for parallel generation

While the API processes requests sequentially, you can optimize your client-side code by using asynchronous Python libraries like aiohttp or asyncio. This allows your application to handle multiple pending requests efficiently without blocking the main thread.

  • Use aiohttp for non-blocking HTTP requests.
  • Implement asyncio to manage concurrent tasks smoothly.

Monitor queue wait times

Requests are processed one after another, so under load, a request may wait in a queue. Monitor your response headers or timing data to detect delays. If wait times increase, consider staggering batch jobs or splitting longer texts into smaller chunks to reduce queue congestion.

  • Track request duration to identify queue delays.
  • Stagger batch jobs during high-traffic periods.

Testing Your Integration

Sound wave illustration for: Testing Your Integration

Testing ensures your news audio pipeline works before going live. Use the $0.50 free trial credit to generate about 50,000 characters without spending your own balance. This allows you to verify the integration logic, check voice selection, and confirm that audio files are correctly saved or streamed to your CMS.

The trial is valid for 7 days, giving you ample time to run batch tests and edge-case scenarios. Once confirmed, you can proceed with confidence to real-world usage.

Use the free trial credit

Sign in with Google to receive $0.50 in credit immediately. This covers roughly 50,000 characters, enough for several short briefings or a full article test. It is the safest way to validate your Python script before incurring charges.

The credit expires after 7 days, so prioritize testing your core workflows first. Email and password accounts do not receive this trial credit, so use Google sign-in for testing.

  • No credit card required
  • Covers ~50,000 characters
  • Expires in 7 days

Verify audio quality and clarity

Listen to generated clips using the 'atlas' voice for standard news delivery. Check for clear pronunciation and appropriate pacing. Ensure the speed parameter (0.25–4.0) suits your editorial style.

Verify that the output format (mp3, wav, etc.) plays correctly in your web player or broadcast software. Check that the audio does not cut off prematurely at the 4096-character limit.

  • Test 'atlas' for news
  • Check mp3/wav playback
  • Verify speed settings

Test edge cases like special characters

Send text containing punctuation, numbers, URLs, and special characters to ensure they are handled correctly. Verify that the API does not crash or produce garbled audio on unexpected input.

Test with non-English text to ensure the language parameter is set correctly. If omitted, Latin text defaults to English, which may cause mispronunciation for other languages.

  • Test punctuation and numbers
  • Test special characters
  • Test non-English text

Deployment Considerations

Sound wave illustration for: Deployment Considerations

Deploying NewsBrio into production requires securing your API key and tracking usage to keep costs predictable. Since accounts start with limited rate limits, monitoring ensures your newsroom audio pipeline stays reliable during high-volume days.

Secure key storage in production

Store your tts-... key in environment variables rather than hardcoding it in your source code. This prevents accidental exposure if your repository becomes public or is shared with contractors.

  • Use environment variables or a secrets manager.
  • Rotate keys immediately if a leak is suspected.

Monitor usage and costs

Track character counts closely, as billing is based on 1 million characters per $10. Since failed requests are free, you only pay for successful synthesis, but long articles can consume credit quickly.

Keep an eye on your TRON network top-ups to ensure your balance doesn’t drop below the minimum $5 top-up amount.

  • Log character usage per article for accurate cost attribution.
  • Set alerts for low balance to prevent service interruption.

Plan for scaling during breaking news

During major events, request volume may spike. Remember that requests are processed sequentially, so long texts may queue under load.

Implement retry logic with exponential backoff to handle rate limits gracefully without dropping audio generation tasks during critical news cycles.

  • Use async requests to parallelize generation where possible.
  • Pre-fetch voices to reduce latency during sudden traffic surges.

Common Pitfalls

Sound wave illustration for: Common Pitfalls

News teams often rush to generate audio for breaking stories, but overlooking language settings can result in awkward English accents on French or German copy. Explicitly passing the language parameter ensures the correct pronunciation for every script, avoiding the default English fallback.

Forgetting to set the language for non-English text

If you send Latin-script text without specifying the language, the system defaults to English. This creates unnatural audio for articles in German, Spanish, or Dutch. Always include the ISO code in your payload to guarantee accurate synthesis.

Ignoring rate limits during batch jobs

Your API key allows 60 requests per minute. During a large archive dump, you may hit this cap quickly. Implement exponential backoff in your Python script to pause and retry automatically, ensuring you do not lose credit on failed requests due to throttling.

Not handling character count limits

Each request is capped at 4096 characters. Sending a long editorial piece in one call will fail. You must split your text programmatically, generate audio for each chunk, and concatenate the files to preserve the full story structure.

Support Resources

Sound wave illustration for: Support Resources

For technical issues, our support team is available via email. We handle inquiries directly, ensuring you get specific answers without waiting in a queue. There is no phone support or live chat, so email remains our primary channel for resolving integration questions or billing discrepancies.

The documentation page provides ready-to-use Python examples for common workflows. You can copy the code directly into your CMS or broadcast tools. The examples cover authentication, text submission, and handling audio responses.

Email support for technical issues

Reach out to our support team via email for any technical difficulties. We respond directly to your inquiries, providing clear guidance on API behavior, rate limits, or character count calculations. Since we do not offer phone support or live chat, email is the most reliable way to get detailed assistance with your news audio pipeline.

  • Direct email contact for technical queries
  • No live chat or phone support available
  • Responses provided for integration and billing issues

Documentation for code snippets

Our documentation page provides ready-to-use Python examples for common workflows. You can copy the code directly into your CMS or broadcast tools. The examples cover authentication, text submission, and handling audio responses.

  • Ready-to-use Python code snippets
  • Examples for authentication and text submission
  • Guides for handling audio responses

Community examples and guides

While we do not offer a dedicated community forum, you can find practical guides and integration tips in our public documentation. These resources help you optimize your news audio generation, from splitting long articles to managing voice selections effectively.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. This variation keeps your audio feed dynamic and helps listeners distinguish between different types of content within your broadcast workflow.

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

More on this site