How to Generate Audiobooks from Text Using Python?

By NarrativeNode editorial team · Updated 2026-11-19

This guide shows self-publishing freelancers how to use the NarrativeNode Python API to turn manuscripts into audiobooks. You will learn to split long chapters into 4,096-character chunks, loop through paragraphs, and concatenate audio files using FFmpeg or a library like pydub. We cover configuring your script with the correct base URL, handling rate limits, and selecting voices like Aria for clear narration.

Discover how to manage language codes, debug common API errors, and optimize your generation speed. You will also see how to validate output quality, verify the synthetic watermark, and prepare your final files for platforms like ACX. This practical workflow helps you produce clear, character-based audio books efficiently without needing complex infrastructure or expensive subscriptions.

How to Generate Audiobooks from Text Using Python?

Frequently asked questions

What is the best way to split text for TTS?

Split your text into parts of up to 4096 characters per request. Generate audio for each chunk individually, then join the resulting audio files together. This ensures you stay within the character limit while maintaining a coherent narrative flow for your audiobook production.

Does Python handle audio merging automatically?

No, the API returns individual audio files for each request. You must handle the merging process in your Python script using libraries like pydub or simple file concatenation. The API does not provide a built-in endpoint for merging multiple audio segments into a single file.

How do I handle special characters in text?

Standard special characters and punctuation are processed normally and count toward your character limit. Ensure your text encoding is UTF-8 compatible when sending the JSON body. There are no specific restrictions on common symbols, so you can include standard narrative punctuation without issue.

Can I use the same voice for multiple books?

Yes, you can reuse any of the eight preset voices across unlimited books. The voice selection is independent per request, so you can assign Aria to one novel and Felix to another. There is no limit on how many times a voice preset can be utilized.

What is the maximum file size for audio?

The API does not specify a maximum audio file size, but limits input text to 4096 characters per request. Generated audio size depends on the format and duration. You receive the file directly in the response, so your local storage handles the final file size constraints.

Do I need to pay for each chapter separately?

No, you pay based on the total characters processed across all requests. Each chapter is just a series of API calls. You are charged $0.01 per 1,000 characters regardless of how many separate requests you make to generate the final audiobook chapters.

How do I detect the language of my text?

If you do not set the language field, the API guesses it from the script, defaulting to English for Latin text. For non-English Latin-script text, you should explicitly set the language parameter to ensure accurate pronunciation. Supported languages include English, Spanish, French, and German.

Can I change the voice mid-story?

Yes, you can change the voice for each individual request. Simply specify a different voice preset in the JSON body for subsequent requests. This allows you to assign unique voices to different characters or narrators within the same audiobook project seamlessly.

What is the difference between tts-1 and tts-1-hd?

Both models use the same engine and price. The only difference is the model identifier in your request; they use the same engine and price. You can choose either 'tts-1' or 'tts-1-hd' without any change in cost or processing speed, as they are functionally identical for your billing and generation needs.

Is the API suitable for children's books?

Yes, the clear narration voices like Aria and Luna work well for children's content. You can use any of the eight presets to match the tone. You can generate audio for any text up to 4096 characters per request.

How do I handle pauses in narration?

The API does not support SSML or explicit pause tags. You must insert punctuation like ellipses (...) or commas in your text to influence pacing. The TTS engine interprets these standard punctuation marks to create natural breaks in the generated audio speech flow.

Can I generate audio while reading?

You can generate audio for short phrases quickly, but requests are processed sequentially, so long texts may queue. Requests are processed sequentially, so long texts may queue. Short phrases generate quickly, but complex sequences might wait in the queue under load.

What happens if the server is down?

If synthesis fails, the charge is returned in full. You can retry the request later. There is no uptime guarantee, so plan for potential delays. Failed requests do not consume your character balance, ensuring you only pay for successfully generated audio files.

Do I need a library like pydub to merge files?

Yes, you need a library like pydub or similar tools to merge the individual audio files returned by the API. The API returns separate files for each text chunk. You must handle the concatenation logic in your Python script to create the final audiobook file.

Prepare Your Manuscript

Sound wave illustration for: Prepare Your Manuscript

Converting a manuscript into an audiobook begins with preparing your source text. Since the API charges per character and limits requests to 4,096 characters, your manuscript must be clean, plain text without complex formatting that could break the synthesis pipeline.

Preparing the text ensures smooth processing. You will need to split long chapters into manageable chunks and handle special characters to avoid errors during generation.

Clean Text Format

Remove headers, footers, and page numbers. Convert all text to a simple UTF-8 encoded file. This ensures that spaces and punctuation count accurately toward your character limit, which is critical for budgeting your $0.01 per 1,000 characters cost.

  • Use plain .txt or .json files
  • Remove markdown symbols
  • Ensure UTF-8 encoding

Split Long Chapters

The API accepts a maximum of 4,096 characters per request. You must split longer chapters into smaller segments before sending them to the endpoint. Each segment generates a separate audio file, which you will later concatenate.

Splitting at natural breaks, such as paragraph ends, helps maintain narrative flow. Keep segments slightly under the limit to avoid truncation issues.

  • Max 4096 characters per request
  • Split at paragraph boundaries
  • Keep segments under the limit

Handle Special Characters

Ensure your text is free of unusual Unicode characters that might confuse the TTS engine. Accents and punctuation are supported, but remove any non-standard symbols.

Special characters can cause request failures or silent errors. Cleaning your text beforehand prevents unnecessary retries and wasted API calls.

  • Remove non-UTF8 symbols
  • Check for stray characters
  • Validate text encoding

Configure Python Script

Sound wave illustration for: Configure Python Script

Setting up your Python environment is the first step toward automating your manuscript’s conversion. You need the OpenAI library (or plain HTTP), which works seamlessly with our API by simply adjusting the connection endpoint. This approach ensures you can use standard, well-documented code without learning a new proprietary SDK.

Once the library is installed, you will configure your authentication and server details. This setup allows your script to communicate directly with NarrativeNode’s TTS engine, ensuring your code is ready to process text chapters as soon as you define your API key and base URL.

Import OpenAI Library

Start by installing the openai package via pip. This library provides the Audio class (or client.audio.speech.create), which handles the HTTP requests to generate audio. Since our API mimics the OpenAI speech endpoint structure, you can rely on familiar methods like client.audio.speech.create without needing a custom wrapper.

This standard library approach means you benefit from existing community examples and reliable error handling. You do not need to manage raw JSON serialization manually, as the SDK handles the conversion of your text input into the required request body format automatically.

  • Install via pip install openai
  • Use version 1.0 or higher for stability
  • No custom SDK required for basic usage

Set API Key

Retrieve your unique API key from the /get-api-key/ dashboard. It starts with tts- and is the only credential needed for authentication. Store this securely in an environment variable or a .env file to prevent accidental exposure in your version control system.

Pass the key to the OpenAI client configuration. This key identifies your account for billing purposes, tracking character usage against your balance. If you issue a new key, the old one stops immediately, so ensure your scripts are updated if you rotate credentials.

  • Key format: tts-...
  • One active key per account
  • New keys invalidate old ones instantly

Define Base URL

By default, the OpenAI client points to api.openai.com. You must override this to point to our infrastructure. Set the base_url parameter to https://api.rx115.cc/v1 in your client initialization. This redirects all speech generation requests to NarrativeNode’s servers.

This single line of configuration is all that is needed to switch providers. Your existing code logic remains unchanged, allowing you to test with free trial credits or paid balances without rewriting your entire script. The endpoint structure matches the standard speech API exactly.

  • Base URL: https://api.rx115.cc/v1
  • Overrides default OpenAI endpoint
  • Maintains standard request shape

Process Text in Batches

Sound wave illustration for: Process Text in Batches

Processing long manuscripts requires splitting text into manageable segments, as the API accepts a maximum of 4096 characters per request. This limit ensures stable generation and prevents timeouts during synthesis of longer chapters.

By looping through your text paragraph by paragraph, you can chunk the content efficiently. Each chunk triggers a separate API call, generating distinct audio files that must be stitched together later to form a continuous narration.

4096 Character Chunks

Split your manuscript into segments of up to 4096 characters, counting spaces and punctuation. This ensures each request fits within the single-request limit while maintaining coherent sentence structures for natural speech synthesis.

  • Count all characters, including spaces and punctuation.
  • Ensure each chunk stays under the 4096-character limit.
  • Preserve paragraph breaks to maintain narrative flow.

Loop Through Paragraphs

Use a Python loop to iterate through your cleaned text. For each chunk, send a POST request to the speech endpoint. This method allows you to process large files without overwhelming the rate limit of 60 requests per minute.

Implement a small delay between requests if you approach the limit. This prevents throttling and ensures each segment is processed sequentially, which is crucial for maintaining the correct order of audio files.

  • Send one POST request per chunk.
  • Monitor the 60 requests per minute limit.
  • Add delays if nearing the threshold.

Concatenate Audio Files

After receiving the audio files for each chunk, you need to merge them. Use a library like pydub or FFmpeg to concatenate the MP3 files in the exact order they were generated. This creates a single, continuous audio file.

Verify the output by listening to the transition points. Ensure there are no gaps or overlaps that disrupt the listening experience. This step transforms fragmented segments into a cohesive audiobook chapter ready for publishing.

  • Use FFmpeg or pydub for merging.
  • Maintain the original chunk order.
  • Verify audio continuity at merge points.

Select Appropriate Voice

Sound wave illustration for: Select Appropriate Voice

Selecting the right voice is critical for audiobook immersion. NarrativeNode offers eight distinct presets, but two stand out for long-form narration: Aria for clear, warm storytelling and Orion for deep, documentary-style tones.

Choose Aria for Narration

Aria delivers a warm, clear narrator voice ideal for fiction and memoirs. Her tone keeps listeners engaged without sounding robotic, making her perfect for character-driven stories.

  • Aria: Warm, clear narrator

Use Orion for Deep Tone

For non-fiction, history, or dramatic readings, Orion provides a deep, documentary-style voice. His authoritative tone adds weight to serious content without requiring additional production effort.

  • Orion: Deep, documentary style

Match Genre to Voice

Match your voice to the manuscript’s genre. Use Luna for soft storytelling or Felix for energetic promos. Ensure the voice aligns with the emotional arc of your book to maintain consistency across chapters.

  • Felix: Energetic, promo
  • Luna: Soft, storytelling
  • Sage: Calm, instructional
  • Milo: Friendly, conversational
  • Atlas: Neutral, news
  • Nova: Bright, upbeat

Handle Rate Limits

Sound wave illustration for: Handle Rate Limits

Managing rate limits is essential for processing long manuscripts efficiently. Our API allows 60 requests per minute per key, but new accounts start with only 10 requests per minute until the first top-up is processed. Understanding these constraints prevents bottlenecks during bulk audiobook generation.

Implement Sleep Functions

Insert a time.sleep() call between requests to stay within the 60 requests per minute limit. This simple throttle ensures you do not exceed the quota, avoiding unnecessary errors while your Python script processes chapter by chapter.

Monitor Request Counts

Track your usage via the dashboard to ensure you remain within the 10 requests per minute limit for new accounts. Once you add funds via USDT (TRC-20), the limit increases to 60 requests per minute, allowing faster processing of longer texts.

Retry Logic

Implement exponential backoff in your code to handle temporary rate limit errors. If a request fails, wait briefly and retry. This ensures your script gracefully handles quota limits without manual intervention, keeping your audiobook production pipeline running smoothly.

Save and Merge Audio

Sound wave illustration for: Save and Merge Audio

Once your script receives the audio bytes, save each chunk as a separate MP3 file. This ensures that if a request fails mid-batch, you only lose the last segment rather than the entire chapter. Storing intermediate files allows you to pause and resume processing without re-generating previously completed text.

Download MP3 Files

Write the binary response directly to disk using a unique filename that includes the chunk index. This prevents overwriting previous segments and makes it easy to track which part of the manuscript corresponds to each audio file.

  • Use a sequential naming convention like chapter1_part_001.mp3
  • Save files in a dedicated temporary directory
  • Ensure the file size is greater than zero before proceeding

Use FFmpeg to Join

Use FFmpeg to concatenate the individual MP3 files into a single audiobook chapter. This tool is efficient and preserves the audio quality without re-encoding, ensuring seamless transitions between chunks. The command simply lists all input files in order and outputs a final master file.

  • Use ffmpeg -f concat -safe 0 -i filelist.txt -c copy output.mp3
  • Generate a filelist.txt containing all chunk paths
  • Verify the output file duration matches the sum of input durations

Verify Output Quality

Listen to the merged file to check for artifacts or silence gaps between joined segments. While the API generates clean audio, checking the join points ensures that no silence was introduced during the concatenation process. Also, verify that the watermark is present, confirming the synthetic nature of the speech.

  • Play the first and last 30 seconds of the chapter
  • Check for consistent volume levels across all chunks
  • Confirm no unexpected silence exists between joined files

Check Language Settings

Sound wave illustration for: Check Language Settings

When generating audiobooks for international audiences, explicitly setting the language field prevents misinterpretation. While the API guesses from Latin script, non-English texts like French or German require a specific ISO code to ensure correct pronunciation and intonation.

Relying on auto-detection can lead to subtle errors, especially with mixed-language paragraphs. Always specify the language for consistent narration quality across your manuscript's diverse sections.

Set Language Code

Pass the language parameter (e.g., "fr", "de") in your Python request. This overrides automatic detection, ensuring the TTS engine uses the correct phonetic rules for the target language.

This is crucial for maintaining narrative consistency, especially when characters speak different languages within the same chapter.

  • Use ISO 639-1 codes like 'en', 'fr', 'de', 'es'.
  • Overrides default English assumption for Latin script text.

Auto-Detection Limits

The system defaults to English for any Latin-script text if no language is specified. This works well for standard English but fails for other European languages.

Detection is script-based, not content-aware. It cannot distinguish between English and other languages using similar alphabets without explicit instruction.

Non-English Scripts

The API supports 23 languages, including Arabic, Chinese, Japanese, Korean, and Russian. Voices can speak any of these supported languages.

Unsupported languages like Vietnamese or Thai will not render correctly. Ensure your manuscript uses one of the 23 supported languages for accurate synthesis.

Check Language Settings

Debug Common Issues

Sound wave illustration for: Debug Common Issues

Debugging your Python audiobook pipeline usually involves checking three main areas: how the API handles errors, whether your voice selection is valid, and if your authentication credentials are correct.

Audio Cutoff Errors

If the generated audio cuts off prematurely, your input text likely exceeded the 4096-character limit per request. Ensure you are splitting long chapters into smaller chunks and concatenating the results.

Voice Not Found

Verify that the voice name matches one of the eight presets exactly (e.g., 'aria', 'nova', 'luna', 'sage', 'felix', 'milo', 'atlas', 'orion'). Case sensitivity matters, and misspelled names will return a 400 error.

Invalid API Key

Ensure your key starts with 'tts-' and is sent in the Authorization header as a Bearer token. If you issued a new key, the old one stops immediately.

Optimize for Speed

Sound wave illustration for: Optimize for Speed

Speed optimization balances generation time against queue latency. Since requests are processed sequentially under load, increasing the speed parameter can significantly shorten the actual synthesis time for long manuscripts. However, extremely slow speeds may increase queue wait times if the server is busy.

Parallel Requests

While the API processes requests one after another, you can prepare multiple chunks simultaneously in your Python script. By using asyncio or threading, you keep your CPU busy calculating the next 4096-character segment while the current audio is generating. This minimizes idle time between chunks.

  • Pre-calculate text splits before sending requests.
  • Use asyncio.gather to manage concurrent tasks.
  • Maintain request order to ensure correct audio sequence.

Reduce Speed Parameter

The speed parameter accepts values from 0.25 to 4.0. Increasing the speed (e.g., to 1.5 or 2.0) reduces the duration of the audio file, which often correlates with faster generation time. For narration, speeds up to 2.0 remain clear and natural, significantly cutting down total project time.

  • Test speeds between 1.5 and 2.0 for balance.
  • Avoid speeds above 3.0 for clarity.
  • Monitor artifacts at higher speeds.

Pre-Generate Sections

Generate audio for chapters or scenes during off-peak hours or while drafting. Store these MP3 files locally. This approach decouples the generation process from your final editing workflow, ensuring that your audiobook files are ready for immediate merging and quality checks without waiting for API responses.

  • Schedule jobs during low-traffic periods.
  • Store generated MP3s in organized folders.
  • Verify character counts before generation.

Validate Output

Sound wave illustration for: Validate Output

Before uploading, verify the generated audio meets quality standards. Listen for unnatural pauses or abrupt cuts that may result from chunking boundaries. Ensure the watermark is present, confirming the file is synthetic. This step ensures professional-grade output for your self-published audiobook.

Check that the character count matches your manuscript to avoid unexpected charges. Confirm the audio length aligns with expectations based on the 25 characters-per-second rule. This validation prevents errors in publishing platforms like ACX.

Listen for Artifacts

Play the concatenated audio file to detect any robotic tones or discontinuities at chapter boundaries. Use a media player that allows precise scrubbing to identify subtle glitches.

Ensure the voice remains consistent throughout. Listen for any sudden changes in speed or pitch that might distract listeners.

  • Use a high-quality headphone for critical listening.
  • Check the first and last 10 seconds of each chunk.
  • Verify smooth transitions between concatenated files.

Check Watermark

Confirm the inaudible watermark is embedded in every generated file. This marks the audio as synthetic speech, which is required by some platforms.

The watermark is inaudible to most listeners but can be detected by specialized tools if needed.

Verify Character Count

Count the characters in your text input, including spaces and punctuation. Ensure the total does not exceed 4096 characters per request.

Compare the billed characters with your input to ensure accuracy. This helps manage your balance and avoid overcharges.

  • Use a text editor to count characters.
  • Include spaces and punctuation in your count.
  • Keep a log of characters used per chapter.

Publish Your Audiobook

Sound wave illustration for: Publish Your Audiobook

After your Python script has merged the final audio chapters, you are ready to share your work with the world. Publishing an audiobook requires careful preparation to meet platform standards and attract listeners.

Ensure your audio files meet the required specifications before uploading. A clean, artifact-free output from your API generation ensures a professional listening experience that retains audience interest.

Upload to ACX

ACX requires high-quality audio files. Upload your concatenated MP3s via their portal, ensuring each chapter is clearly labeled. The platform checks for background noise and volume levels, so your API-generated files should pass these checks if generated correctly.

Use the official API to generate the audio, then manually upload the resulting files. ACX does not support direct API integration for self-published authors, so you must manage the file transfer yourself.

  • Ensure audio meets ACX loudness standards.
  • Label chapters sequentially.
  • Verify no background noise in API output.

Prepare Cover Art

Your cover art must be square, at least 2400x2400 pixels, and in JPEG or TIFF format. It should clearly display the title and author name, as this is the first thing listeners see.

Design a cover that reflects the genre of your manuscript. Since the API handles audio, you can focus your creative energy on visual branding that complements the narration style.

  • Minimum resolution: 2400x2400 pixels.
  • Format: JPEG or TIFF.
  • Include title and author name clearly.

Set Pricing Strategy

Determine your royalty structure. You can choose between a 40% royalty rate on sales or a 25% rate with unlimited listening on Audible. Consider your target audience and typical audiobook pricing when making this decision.

Remember that your production cost is fixed at $0.01 per 1,000 characters. Factor this into your profit margin, especially if you are pricing your audiobook competitively against traditional publishers.

  • Choose between 40% or 25% royalty rates.
  • Calculate profit margins based on character count.
  • Research competitor pricing for similar genres.

Future Enhancements

Sound wave illustration for: Future Enhancements

Current workflows rely on manual script adjustments for each new manuscript. As your library grows, automating the text-splitting and batch-voice selection process will save significant time. This allows freelancers to process entire books with fewer human interventions.

Script Automation

Integrating your Python script with version control systems can streamline updates to your narration logic. This ensures consistent character handling across multiple projects without manual code reviews.

  • Automate chapter boundary detection
  • Sync script changes via Git

Batch Processing

Instead of processing chapters sequentially, future improvements could allow parallel generation of up to 4096-character chunks. This leverages the API’s throughput more effectively, reducing total generation time for long-form content.

  • Parallel chunk generation
  • Reduce wait times

Voice Customization

While we do not offer custom voice cloning, future updates might allow selecting specific emotional tones within the existing eight presets. This would help match the genre more precisely without needing new voice models.

  • Enhanced tone selection
  • Genre-specific preset pairing

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. For English-language manuscripts, the system defaults to English if the language parameter is omitted.

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

More on this site