Integrate Speech Synthesis into Your Python App

By MedSynth editorial team · Updated 2026-11-19

This page provides a complete guide for integrating the VoxMedix text-to-speech API into Python applications. We focus on health-tech startups needing to convert medical documentation into accessible patient guides efficiently. The instructions cover authentication, request structure, and SDK usage, ensuring you can generate compliant audio files with minimal code overhead.

You will learn how to obtain an API key, send your first synthesis request, and handle responses in various formats like MP3 or WAV. The guide also details rate limits, voice selection across 23 languages, and error handling. By following these steps, you can quickly add clear, synthetic speech to your patient communication tools without enterprise contracts.

Integrate Speech Synthesis into Your Python App

Frequently asked questions

What Python version is supported?

The API is language-agnostic and works with any Python version capable of making HTTP requests. Since we rely on standard HTTP calls or the OpenAI Python SDK, compatibility depends on your environment’s network libraries rather than a specific Python release version.

Do I need a specific SDK?

No proprietary SDK is required. You can use the official OpenAI Python SDK by adjusting the base URL, or make plain HTTP requests using libraries like requests. This approach ensures flexibility without locking you into a specific vendor’s client library.

How do I set the base_url?

Configure your SDK or HTTP client to point to https://api.heybhaji.cc/v1. This endpoint mirrors the standard speech API structure, allowing you to reuse existing code patterns by simply changing the base URL to our domain for all API interactions.

Can I use async Python?

Yes, since the API is accessed via standard HTTP, you can use any async library like aiohttp or the OpenAI SDK’s async client. There are no protocol restrictions preventing asynchronous calls, allowing you to integrate synthesis seamlessly into concurrent workflows.

How do I handle large texts?

Split your input text into chunks of up to 4096 characters. Generate audio for each chunk individually and then join the resulting audio files. This ensures compliance with the single-request character limit while allowing you to process longer documents.

What is the max character limit?

Each API request supports a maximum of 4096 characters in the input field. This limit applies per request, so longer texts must be segmented. Spaces and punctuation count toward this total, so plan your chunking strategy accordingly for optimal results.

Do voices support all languages?

Voices support 23 specific languages, including English, Spanish, German, and Japanese. Any voice can speak any of these languages. If the language is not specified, it is guessed from the script, but you should explicitly set it for non-English Latin text.

Is there a WebSocket option?

No, there is no WebSocket or streaming option. The API returns the complete audio file in the response after synthesis. You must wait for the full file generation before receiving the data, as there are no real-time partial audio streams.

How do I get the API key?

Sign up on the /get-api-key/ page using Google or an email and password. Once registered, your account dashboard displays your unique API key, which you can use immediately for authentication in your Python scripts or other API integrations.

What headers are required?

You must include the Authorization header with your Bearer token: Authorization: Bearer tts-... This key authenticates your requests. Ensure your HTTP client sends this header with every POST request to the speech endpoint to avoid authentication errors.

Are requests encrypted?

The API uses standard HTTPS for all communication, ensuring data is encrypted in transit. Input text is used only to produce the audio and is not used for training. Generated audio is returned in the response and not stored. Request metadata (time, characters, status) is kept for billing.

Can I change the API key?

Yes, you can issue a new API key at any time from your dashboard. When you generate a new key, the old one stops working immediately. This allows you to rotate credentials securely without needing to wait for expiration periods.

What happens if rate limit hit?

You are limited to 60 requests per minute per key. If you exceed this, requests may queue or fail. New accounts start with a 10 requests per minute limit until the first top-up. Failed requests do not incur charges.

Is there a Python example?

Yes, the /get-api-key/ page provides a ready-to-use curl example. You can easily translate this into Python using the requests library or the OpenAI SDK by setting the base URL to https://api.heybhaji.cc/v1 and passing your audio parameters in JSON.

First request

curl

curl https://api.heybhaji.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.heybhaji.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.heybhaji.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

Get Your API Key

Sound wave illustration for: Get Your API Key

Access the API by creating an account at /get-api-key/. This page displays your unique key, balance, and usage statistics. You can begin generating audio immediately after setup.

Sign up on /get-api-key/

Sign up on /get-api-key/

Navigate to the key management page to register. The interface provides a ready-to-use cURL example and displays your current character allowance. This is the central hub for managing your health-tech TTS integration.

  • View real-time character usage
  • Generate cURL examples instantly
  • Monitor API balance

Google or email authentication

Google or email authentication

Choose between Google sign-in or standard email registration. Google accounts receive a $0.50 free trial valid for seven days. Email-based accounts start with zero trial credit but function identically otherwise.

  • Google OAuth for quick access
  • Email/password for standard accounts
  • Automatic trial credit for Google users

One active key per account

Each account holds a single active API key. If you issue a new key, the previous one stops working immediately. This ensures secure, straightforward access control for your medical documentation workflows.

  • Single active key per account
  • Instant invalidation on rotation
  • Simplified security model

First Request with Curl

Sound wave illustration for: First Request with Curl

Before writing code, verify the API endpoint works using a simple command-line request. This confirms your authentication and connectivity are correct before integrating into your Python application.

The request sends medical text to the synthesis engine, which returns the generated audio file directly in the response body.

POST to /v1/audio/speech

Send a POST request to https://api.heybhaji.cc/v1/audio/speech. Include your API key in the Authorization header as a Bearer token.

This endpoint accepts the text payload and processes it through the TTS engine.

  • Endpoint: https://api.heybhaji.cc/v1/audio/speech
  • Method: POST
  • Header: Authorization: Bearer tts-...

JSON body with model and input

The request body must be valid JSON containing the model, input (your text up to 4096 characters), and voice selection.

Example: `{"model": "tts-1", "input": "Please take this medication with food.", "voice": "aria"}`.

  • model: "tts-1" or "tts-1-hd"
  • input: string, max 4096 characters
  • voice: one of 8 presets
  • response_format: mp3, wav, opus, flac, or pcm

Receive audio file in response

On success, the response contains the raw audio binary data. Save this directly to a file or process it in memory.

If the synthesis fails, the response includes an error JSON object with details like invalid characters or rate limits.

  • Content-Type: audio/mpeg (for MP3)
  • Binary data stream
  • Error codes on failure

Using the OpenAI SDK

Sound wave illustration for: Using the OpenAI SDK

The OpenAI Python SDK works seamlessly with our API because the request shape is identical. You simply point the client to our base URL instead of OpenAI's servers. This allows you to use the familiar openai package without writing custom HTTP logic or parsing raw JSON responses.

Set base_url to our endpoint

Configure the SDK to target https://api.heybhaji.cc/v1. This directs all speech synthesis requests to our infrastructure while maintaining standard OpenAI compatibility.

Use official OpenAI Python SDK

Install the standard openai library. Import OpenAI and initialize the client with your base URL. Call audio.speech.create() with your model, voice, and input text parameters just as you would for OpenAI's TTS endpoint.

Replace API key in headers

Pass your unique tts-... key as the api_key parameter. The SDK automatically adds the Authorization: Bearer header. Ensure this key is from your account on heybhaji.cc, as our keys are specific to this storefront.

  • Use OpenAI(base_url="https://api.heybhaji.cc/v1", api_key="tts-...")
  • Keys are single-active; issuing a new one invalidates the old immediately

Request Parameters

Sound wave illustration for: Request Parameters

Configure the core parameters to generate speech that matches your clinical documentation needs. The API accepts standard request fields, allowing you to control voice selection, input length, and audio quality with precision.

Model: tts-1 or tts-1-hd

Select "tts-1" for standard generation or "tts-1-hd" for higher fidelity. Both models use the same underlying engine and incur identical pricing, so choose based on your audio quality requirements without worrying about cost differences.

Input: text up to 4096 chars

Pass your medical text or patient guide instructions in the input field. The limit is 4096 characters per request, including spaces and punctuation. For longer documents, split the text into chunks and concatenate the resulting audio files.

Voice: select from 8 presets

Choose from eight distinct voices tailored for clarity and tone. Female options include Aria (warm narrator), Nova (upbeat), Luna (storytelling), and Sage (instructional). Male options include Felix (energetic), Milo (conversational), Atlas (neutral news), and Orion (deep documentary).

  • Each voice supports 23 languages, ensuring clear articulation for diverse patient populations.

Response Formats

Sound wave illustration for: Response Formats

The response_format parameter lets you choose the audio container that best fits your application’s playback engine. Selecting the right format ensures optimal compatibility with your patient guide delivery system without unnecessary conversion steps.

MP3 for web playback

MP3 is the default choice for web-based patient portals and mobile apps. It offers a balance between file size and audio quality, making it ideal for playback of generated audio files on varying network connections.

WAV for high fidelity

Choose WAV when you need uncompressed, high-fidelity audio for clinical review or archival. This format preserves the full quality of the synthesized voice, ensuring clarity for complex medical terminology without data loss.

OPUS, FLAC, PCM options

OPUS provides superior compression for low-bandwidth environments, while FLAC offers lossless compression for storage efficiency. PCM is available for raw audio processing pipelines where you need uncompressed samples for immediate analysis or further editing.

Select the format that aligns with your storage constraints and playback requirements. All formats are generated from the same engine, so voice quality remains consistent regardless of your choice.

Response Formats

Rate Limits

Sound wave illustration for: Rate Limits

The API enforces a strict rate limit of 60 requests per minute for authenticated accounts, ensuring stable performance for your health-tech applications. This limit applies to your single active API key, which is generated upon signing in via Google or email on the /get-api-key/ page.

Before your first top-up, the limit is restricted to 10 requests per minute. Once you add USDT (TRC-20) to your balance, the full 60 requests per minute capacity is unlocked. Failed requests do not count against this limit, preserving your quota for successful synthesis tasks.

60 requests per minute

After your initial top-up, you can send up to 60 requests per minute. This capacity supports generating patient guides and medical documentation at scale without needing an enterprise contract.

Each request processes one text input of up to 4096 characters. Since requests are processed sequentially, high-volume usage may result in slight delays if the queue builds up.

  • Limit resets every 60 seconds.
  • Applies to your single active API key.
  • Failed requests are free and do not consume quota.

10 requests before first top-up

New accounts start with a 10 requests per minute limit. This allows you to test the API with your free trial credit of $0.50 before committing to a top-up.

You can top up via USDT on the TRON network (TRC-20) with a minimum of $5. Credits are added automatically within minutes, instantly increasing your rate limit to 60 requests per minute.

Queue processing under load

Requests are processed one after another. Under heavy load, your request may wait in a queue before synthesis begins. This ensures fair resource distribution but may increase latency for long texts.

Typical generation speed is roughly real-time (about 25 characters of text per second of generation). For shorter phrases, expect a few seconds of processing time.

Error Handling

Sound wave illustration for: Error Handling

Proper error handling ensures your health-tech application remains robust when API calls fail. The API returns standard HTTP status codes to indicate issues, allowing your Python client to distinguish between authentication failures, input constraints, and resource availability problems.

Invalid API key errors

Use the correct header format: Authorization: Bearer tts-.... If the key is missing, malformed, or revoked, the API returns a 401 Unauthorized error. Ensure you are using the active key from your dashboard, as issuing a new key instantly invalidates the previous one.

Character limit exceeded

Each request supports a maximum of 4096 characters in the input field. If you exceed this limit, the API rejects the request. For longer medical documentation, split your text into chunks, generate audio for each, and concatenate the resulting files in your application logic.

  • Count spaces and punctuation as characters.
  • Failed requests are free, so retrying invalid requests does not incur extra cost.

Voice not found errors

The voice parameter must match one of the eight available presets: aria, nova, luna, sage, felix, milo, atlas, or orion. Using an unrecognized voice name returns a 400 Bad Request error. Verify the voice ID against the /v1/voices endpoint before generating patient guide audio.

Voice Selection

Sound wave illustration for: Voice Selection

Select from eight distinct voice presets tailored for medical documentation. Female options include Aria (warm, clear narrator), Nova (bright, upbeat), Luna (soft, storytelling), and Sage (calm, instructional). Male presets feature Felix (energetic, promo), Milo (friendly, conversational), Atlas (neutral, news), and Orion (deep, documentary).

Each voice supports 23 languages, ensuring clear articulation for diverse patient populations. If the language parameter is omitted, the system guesses the language from the script, defaulting to English for Latin text. Explicitly setting the language code is recommended for non-English Latin-script content to avoid misinterpretation.

Female: Aria, Nova, Luna, Sage

Aria provides a warm, clear narration style ideal for standard patient guides. Nova offers a bright, upbeat tone suitable for engaging health tips. Luna delivers a soft, storytelling voice for complex medical histories. Sage is calm and instructional, perfect for step-by-step procedure explanations.

  • Aria: Warm, clear narrator
  • Nova: Bright, upbeat
  • Luna: Soft, storytelling
  • Sage: Calm, instructional

Male: Felix, Milo, Atlas, Orion

Felix brings an energetic, promo-like energy to health updates. Milo sounds friendly and conversational, reducing anxiety in patient communications. Atlas provides a neutral, news-style delivery for factual data. Orion offers a deep, documentary tone for serious medical conditions.

Each voice supports 23 languages, ensuring clear articulation for diverse patient populations.

  • Felix: Energetic, promo
  • Milo: Friendly, conversational
  • Atlas: Neutral, news
  • Orion: Deep, documentary

Each voice supports 23 languages

Any voice can speak any of the 23 supported languages, ensuring clear articulation for diverse patient populations. Supported languages include Arabic, Chinese, Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, and Turkish. If language is not set, it is guessed from the script, so for non-English Latin-script text, explicitly set the language parameter.

Voices are based on licensed recordings from LibriTTS-R and LibriVox. Every generated file carries an inaudible watermark marking it as synthetic speech.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. You do not need to install specialized medical audio libraries or custom wrappers.

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. Node.js documentation
  4. FFmpeg documentation
  5. openai-node on GitHub
  6. W3C WAI: making audio and video accessible
  7. IETF RFC 7845: Ogg Opus
  8. openai-python on GitHub
  9. TRON developer hub: TRC-20
  10. MDN: Web Speech API
  11. LibriTTS-R paper (arXiv 2305.18802)
  12. Creative Commons Attribution 4.0

More on this site