Integrating Text-to-Speech with Python: A Practical Guide

By SonicPress editorial team · Updated 2026-11-19

This guide helps blog publishers and WordPress creators convert written articles into audio episodes using Python. You will learn to call our TTS API with standard libraries or the official OpenAI SDK, adapting the base URL to our endpoint. The process requires minimal infrastructure, allowing you to generate accessible audio versions of your content without managing complex backend systems.

We cover practical steps from authentication to handling long texts that exceed character limits. You will see how to split content, generate audio parts, and join them into a single file. The documentation includes concrete code examples, rate limit details, and voice selection tips to ensure your audio workflow runs smoothly during high-traffic publishing periods.

Integrating Text-to-Speech with Python: A Practical Guide

Frequently asked questions

How do I authenticate my Python requests?

Include your API key in the Authorization header as a Bearer token. Use the format Authorization: Bearer tts-.... You can find your active key on the /get-api-key/ page. Only one key is active per account; issuing a new one immediately invalidates the previous one.

Can I use the OpenAI Python SDK?

Yes. The API endpoint matches the OpenAI speech endpoint shape. Change the base_url to https://api.musang188.cc/v1 and use your SonicPress key. The official OpenAI SDKs work directly with this configuration without requiring any custom client libraries or wrappers.

What is the maximum text length?

Each request supports up to 4096 characters in the input field. Spaces and punctuation count toward this limit. For longer blog posts, split the text into chunks of 4096 characters or fewer and join the resulting audio files manually.

How do I handle rate limits?

The limit is 60 requests per minute per key. New accounts start with 10 requests per minute until the first top-up. If you exceed the limit, requests will be queued or rejected. Monitor your usage on the dashboard to stay within limits.

What happens if the API is slow?

Requests are processed sequentially, so under load a request may wait in a queue. Typical speed is roughly real-time (25 characters per second). Short phrases may take a few seconds.

Can I change the voice mid-request?

No. Each request generates audio for a single voice specified in the voice field. To change voices, you must make separate requests for each segment and join the audio files. The API does not support dynamic voice switching within a single generation.

Is the audio format changeable?

Yes. You can specify the response_format field as mp3, wav, opus, flac, or pcm. This allows you to choose the best format for your blog player or storage needs.

How do I get the list of voices?

Send a GET request to /v1/voices. This endpoint returns available voices, languages, formats, and pricing information. You can also view this data on the /get-api-key/ page alongside your API key and balance details.

Do I need to install extra libraries?

No. You can use the standard requests library or the official OpenAI Python SDK. If using the OpenAI SDK, only change the base_url. No proprietary SonicPress libraries are required to interact with the API endpoints.

How do I split long blog posts?

Split your text into parts of up to 4096 characters. Send each part as a separate POST request to /v1/audio/speech. Receive the audio files and join them using a standard audio library or tool. This ensures each request stays within limits.

What is the speed range?

The speed parameter accepts values between 0.25 and 4.0. This allows you to adjust the playback rate of the generated speech. A value of 1.0 is normal speed. Adjust this based on your audience's preference for listening pace.

Can I set a specific language?

Yes. Use the optional language field with an ISO code. If omitted, the system guesses the language, defaulting to English for Latin script. For non-English Latin text, explicitly set the language to ensure correct pronunciation and voice selection.

How do I detect encoding errors?

Check the HTTP status code of the response. A 200 OK indicates success. Errors return appropriate status codes (e.g., 400 for bad request, 429 for rate limit).

Is the API synchronous or asynchronous?

The API is synchronous. You send a POST request and wait for the audio file to be generated and returned. Requests are processed one after another. There is no WebSocket or streaming endpoint for real-time partial audio delivery.

First request

curl

curl https://api.musang188.cc/v1/audio/speech \
  -H "Authorization: Bearer $TTS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"tts-1","voice":"aria","input":"Hello from the API.","response_format":"mp3"}' \
  --output hello.mp3

Python (openai)

from openai import OpenAI

client = OpenAI(base_url="https://api.musang188.cc/v1", api_key="tts-...")

with client.audio.speech.with_streaming_response.create(
    model="tts-1", voice="nova", input="Hello from Python.", response_format="mp3"
) as response:
    response.stream_to_file("hello.mp3")

Node.js (openai)

import OpenAI from "openai";
import fs from "node:fs";

const client = new OpenAI({ baseURL: "https://api.musang188.cc/v1", apiKey: process.env.TTS_API_KEY });
const res = await client.audio.speech.create({ model: "tts-1", voice: "milo", input: "Hello from Node.js." });
fs.writeFileSync("hello.mp3", Buffer.from(await res.arrayBuffer()));
voice
ariafemale
novafemale
lunafemale
sagefemale
felixmale
milomale
atlasmale
orionmale
language
arالعربية
zh中文
daDansk
nlNederlands
enEnglish
fiSuomi
frFrançais
deDeutsch
elΕλληνικά
heעברית
hiहिन्दी
itItaliano
ja日本語
ko한국어
msBahasa Melayu
noNorsk
plPolski
ptPortuguês
ruРусский
esEspañol
swKiswahili
svSvenska
trTürkçe

Authentication Setup

Sound wave illustration for: Authentication Setup

To access the SonicPress API, you must first generate an authentication key. Navigate to the /get-api-key/ page and sign in using Google or create an account with an email and password. Your unique key will be displayed on the dashboard, ready for immediate use in your scripts.

Generate your API key

Generate your API key

Sign up on the /get-api-key/ page to receive your key. Accounts created via email start without trial credit, while Google sign-ins include $0.50. Keys are tied to your account on this specific site.

  • Supports Google sign-in or email/password registration
  • Keys are generated per site (musang188.cc)
  • Trial credit ($0.50) available for Google sign-ins

Use Bearer token in header

Use Bearer token in header

Include your key in the Authorization header as a Bearer token: Authorization: Bearer tts-.... This header authenticates every POST request to the speech endpoint. Ensure no extra spaces are included.

Rotate keys when needed

You can issue a new key at any time from your dashboard. The old key stops working immediately upon generation of the new one, ensuring secure access if a key is compromised.

  • Issue a new key instantly
  • Old key becomes inactive immediately
  • No downtime during rotation

First Request Example

Sound wave illustration for: First Request Example

Send a POST request to the API endpoint with your text and preferred voice settings. The service returns a direct audio file, allowing you to save it locally or stream it within your application.

Python requests library code

Use the standard requests library to send your payload. Ensure you include your Bearer token in the authorization header and specify the model (tts-1 or tts-1-hd).

The script below demonstrates a basic call to generate speech from a short text string.

  • Import requests and set your API key.
  • Define the JSON payload with model, voice, and input text.
  • Send the POST request and handle the binary response.

JSON body structure

The request body must contain the model, input (up to 4096 characters), voice, and response_format. The input field accepts plain text strings.

You can optionally specify a language code (e.g., en, fr) to ensure correct pronunciation, though the system guesses language by default for Latin scripts.

  • model: 'tts-1' or 'tts-1-hd'
  • input: your text content
  • voice: one of 8 presets like 'nova' or 'atlas'
  • response_format: mp3, wav, opus, flac, or pcm

Response handling

On success, the API returns the audio file directly in the response body. You can write this binary data to a file with the specified extension.

If the request fails, check the HTTP status code and error message. Failed requests are free, so no charge is applied to your balance.

  • Check for HTTP 200 status.
  • Save response content to disk.
  • Handle errors gracefully without losing credit.

Using OpenAI SDK

Sound wave illustration for: Using OpenAI SDK

The SonicPress API is compatible with the official OpenAI Python SDK because it follows the same request structure. This allows you to use familiar methods without rewriting your entire integration logic.

You only need to configure the client to point to our base URL. Once set, the SDK handles the standard TTS endpoints exactly as it would for OpenAI's services.

Change base_url parameter

Initialize the OpenAI client with base_url='https://api.musang188.cc/v1'. This redirects all requests to our infrastructure while maintaining standard compatibility.

Keep same request shape

Pass model, input, and voice exactly as defined in our spec. The API accepts tts-1 or tts-1-hd models using identical JSON structures.

Use official SDK methods

Call client.audio.speech.create() just like you would for OpenAI. The response returns the audio binary directly, ready for saving or streaming.

  • No custom parsing required
  • Uses standard audio/speech endpoint
  • Supports all formats (mp3, wav, opus, flac, pcm)

Supported Formats

Sound wave illustration for: Supported Formats

The API accepts MP3, WAV, Opus, FLAC, and PCM as valid output formats via the response_format field. MP3 is the standard choice for web playback, while WAV provides lossless quality for editing workflows.

MP3 audio output

MP3 is the default format for most integrations. It offers a balance of file size and quality, making it ideal for embedding audio players on WordPress blogs or mobile apps.

WAV format options

Choose WAV when you need uncompressed audio for high-fidelity applications. This format preserves the full audio data without lossy compression, suitable for professional editing or archival purposes.

Opus, FLAC, PCM support

Opus provides efficient compression, while FLAC offers lossless compression for storage efficiency. PCM returns raw linear audio data.

  • Opus: efficient streaming
  • FLAC: lossless storage
  • PCM: raw data

Rate Limits and Quotas

Sound wave illustration for: Rate Limits and Quotas

You can make 60 requests per minute with a single active API key. This limit applies to all synthesis endpoints, so plan your batch jobs accordingly to avoid hitting the cap during high-volume publishing cycles.

60 requests per minute

Each successful or failed request counts toward this minute-by-minute quota. If you exceed 60 requests in a 60-second window, the API returns a 429 Too Many Requests error. You must wait for the window to reset before sending more.

10 requests before top-up

New accounts start with a free trial balance of $0.50 but are restricted to 10 requests per minute. Once you top up via USDT (TRC-20), this limit increases to the standard 60 requests per minute.

Queue handling under load

Rate Limits and Quotas

Error Handling

Sound wave illustration for: Error Handling

When the synthesis engine encounters an issue, it returns standard HTTP status codes to help you diagnose the problem. Understanding these codes allows your Python script to react appropriately rather than failing silently.

Most errors are transient or related to input constraints. By checking the response status, you can distinguish between temporary load issues and permanent configuration errors, ensuring your audio generation pipeline remains robust.

Common HTTP error codes

A 400 Bad Request indicates invalid JSON or missing required fields like model or voice. A 401 Unauthorized means your API key is incorrect or expired. A 429 Too Many Requests signals you have exceeded the rate limit of 60 requests per minute.

If you receive a 500 Internal Server Error, the issue is on our side. Failed synthesis requests are free, so no charge is applied to your balance for these errors.

  • 400: Invalid request structure or parameters
  • 401: Invalid or expired API key
  • 429: Rate limit exceeded
  • 500: Internal server error (retry later)

Retry failed requests

For 429 errors, implement an exponential backoff strategy. Wait briefly before retrying, as the queue handles requests sequentially. For 500 errors, a simple retry after a short delay is often sufficient.

Since failed requests are refunded, you do not lose credit by retrying. However, avoid aggressive infinite loops; cap your retries to prevent unnecessary API calls during prolonged outages.

  • Use exponential backoff for 429 errors
  • Retry 500 errors once or twice
  • No credit loss on failed requests

Check character limits

Each request accepts up to 4096 characters. If your input text exceeds this limit, the API returns a 400 error. Ensure your Python script splits long articles into chunks before sending them.

Remember that spaces and punctuation count toward the character limit. Always validate your text length before constructing the JSON payload to avoid unnecessary network calls and delays.

  • Max 4096 characters per request
  • Spaces and punctuation count
  • Split text before sending

Voice Selection

Sound wave illustration for: Voice Selection

Selecting the right voice and language ensures your audio content matches the intended tone and audience. The API provides eight distinct voice presets, each with a specific character, and supports 23 languages. You can retrieve the full list of available voices, languages, formats, and pricing by making a GET request to /v1/voices.

List available voices

Use the /v1/voices endpoint to get a complete inventory of supported options. This includes all voice IDs, available languages, audio formats, and current pricing tiers. It is the best way to verify which voices are active before building your integration.

Choose from 8 presets

Select one of eight presets such as 'aria' for a warm narrator tone or 'atlas' for neutral news delivery. Each voice is based on licensed recordings, ensuring consistent quality. You simply pass the voice ID in your request body to generate audio with that specific character.

  • Female: aria, nova, luna, sage
  • Male: felix, milo, atlas, orion

Set language code

The API guesses the language from the script if none is specified, defaulting to English for Latin text. For non-English Latin-script text, explicitly set the language parameter to avoid errors. Supported languages include Arabic, Chinese, French, German, Japanese, Korean, Spanish, and others listed in the voices endpoint.

Handling Long Texts

Sound wave illustration for: Handling Long Texts

The API enforces a strict 4096-character limit per request, so longer articles must be segmented before synthesis. We recommend splitting your text by sentences or paragraphs to maintain natural pauses between generated audio files.

Split text into 4096 char chunks

Divide your input string into blocks of 4096 characters or fewer. Ensure you do not cut mid-word if possible, though the API accepts any valid text up to the limit. Spaces and punctuation count toward this character total.

Generate parts separately

Send each chunk as an individual POST request to /v1/audio/speech. Since requests are processed sequentially, longer texts may experience queue delays during high traffic. Monitor your rate limit (60 requests/minute) to avoid throttling.

Join audio files together

Receive the audio binary for each part and concatenate them in your Python script. The resulting file will play as a single continuous episode. This method keeps memory usage low and allows you to handle individual synthesis errors gracefully.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. Whether you are publishing news, personal essays, or technical guides, your specific words do not become part of the engine’s learning pool.

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. LibriTTS-R corpus (OpenSLR 141)
  3. Creative Commons Attribution 4.0
  4. Node.js documentation
  5. LibriTTS-R paper (arXiv 2305.18802)
  6. openai-node on GitHub
  7. OpenAI API reference: create speech
  8. TRON developer hub: TRC-20
  9. FFmpeg documentation
  10. curl documentation
  11. W3C WAI: making audio and video accessible
  12. MDN: Web Speech API

More on this site