Integrating Text-to-Speech API with Python

By VoxMold editorial team · Updated 2026-11-19

This guide details the integration of the VoxMold text-to-speech API into Python environments, specifically for startups generating synthetic speech datasets. It covers account setup, SDK configuration, and batch processing workflows to streamline data pipelines.

Readers will learn to manage voice selection, handle rate limits, and optimize costs using standard formats. The guide provides concrete code examples for request handling, error management, and production scaling, ensuring reliable audio generation for machine learning applications.

Integrating Text-to-Speech API with Python

Frequently asked questions

How do I install the required libraries?

Install the OpenAI Python SDK via pip. Configure the base_url to https://api.xxx444.cc/v1 and provide your API key. The SDK handles JSON serialization and HTTP requests automatically, allowing you to use standard methods like Audio.create for synthesis without writing custom HTTP client code.

What is the best way to handle rate limits?

The limit is 60 requests per minute per key. Implement exponential backoff in your Python script to retry failed requests. Monitor the response headers for usage data. If you exceed the limit, pause generation briefly before resuming to avoid repeated 429 errors during high-volume dataset creation.

Can I use the API for generating audiobooks?

Yes, the API supports generating audio for audiobooks. Input text is limited to 4096 characters per request. You must split longer texts into chunks, generate audio for each, and join the resulting files. The service returns standard audio formats compatible with audiobook distribution pipelines.

How do I switch between voices programmatically?

Pass the desired voice identifier in the voice field of the request body. Available voices include aria, nova, luna, sage, felix, milo, atlas, and orion. You can change the voice dynamically for each request by updating the parameter value in your Python script before calling the API.

Is there a limit to the number of requests per day?

There is no daily request limit. The constraint is 60 requests per minute per API key. You can generate unlimited audio as long as you respect the per-minute rate limit. Balance does not expire, allowing you to process large datasets over extended periods without time pressure.

How do I detect the language of my input text?

Set the language parameter to an ISO code. If omitted, the API guesses the language, defaulting to English for Latin script. For non-English Latin text, explicitly set the language field to ensure accurate synthesis. Supported languages include English, Spanish, German, French, and 18 others.

What is the difference between MP3 and WAV formats?

MP3 is a compressed format, reducing file size for storage and transmission. WAV is uncompressed, preserving original audio quality. Both are supported response formats. Choose MP3 for efficient storage in ML datasets or WAV if your pipeline requires lossless audio input for further processing.

Can I pause and resume a batch job?

The API does not support pausing or resuming a single request. You must manage batching in your Python code. Generate audio for chunks sequentially or in parallel, respecting the 60 requests per minute limit. Save intermediate results to disk to allow manual resumption if the script stops.

How do I monitor my API usage in real-time?

Check the /get-api-key/ page to view current balance, characters used, and trial status. The API does not provide a real-time usage stream. Monitor your local script logs and request counts. Use the GET /v1/voices endpoint to verify available voices and formats for your pipeline.

Is the API suitable for high-volume data generation?

Yes, for startups building synthetic speech datasets. The API processes requests sequentially, so high volume may require queuing. With 60 requests per minute, plan your batch sizes accordingly. Audio generation takes roughly real-time duration, so factor in processing time for large text volumes in your pipeline.

How do I handle audio files generated in Python?

The API returns audio data in the response body. Save the binary content directly to a file using standard Python file I/O. Ensure you handle the response_format correctly (mp3, wav, opus, flac, pcm). Each generated file contains an inaudible watermark marking it as synthetic speech.

What is the recommended speed for natural speech?

The default speed is 1.0. You can adjust the speed parameter between 0.25 and 4.0. For natural-sounding synthetic speech, keep the speed near 1.0. Extreme speeds may affect clarity. Use the speed parameter to match the pacing required by your specific machine learning dataset standards.

Can I use the API to generate silent audio segments?

The API generates audio from input text. Passing an empty string or whitespace may produce audio, but it is not guaranteed to be silent. The service synthesizes speech based on the input characters. For precise silence, generate a short audio file and trim it in your pipeline.

How do I update my API key without downtime?

Issue a new key from the dashboard. The old key stops immediately upon issuance. Update your Python configuration with the new key. Ensure your script uses the new key for subsequent requests. There is no overlap period, so coordinate the switch to avoid request failures.

Preparation

Sound wave illustration for: Preparation

Create a VoxMold account via /get-api-key/ using Google or email. This establishes your identity for billing and key management within the API ecosystem.

Account Creation

Register on the /get-api-key/ page using Google or email. Google sign-ins receive $0.50 trial credit valid for 7 days; email accounts start without credit. Each site account is independent.

  • Google sign-in includes $0.50 trial credit
  • Email accounts start with zero balance
  • Accounts are per-site (xxx444.cc)

Key Generation

The dashboard displays your single active API key. Use this key for authentication. Issuing a new key immediately invalidates the previous one, so ensure your pipelines update promptly.

  • One active key per account
  • New key invalidates old key instantly
  • Key format: tts-...

Balance Check

Monitor your balance and usage directly in the dashboard. You can view characters consumed, remaining credit, and rate limit status. Balance does not expire.

  • Real-time balance tracking
  • Character consumption history
  • Rate limit status (60 req/min)

Setup

Sound wave illustration for: Setup

Configure the SDK to point to the VoxMold endpoint. Set the base URL to https://api.xxx444.cc/v1. This allows standard OpenAI Python SDKs to process requests without custom client logic. The API accepts the same JSON structure as the OpenAI speech endpoint, ensuring compatibility with existing codebases designed for synthetic audio generation.

SDK Installation

Install the OpenAI SDK via pip. This library handles JSON serialization and HTTP transport for the API. It is the recommended client for Python integration, providing a straightforward interface for sending text and receiving audio files.

Base URL Configuration

Set the base URL to https://api.xxx444.cc/v1. This directs requests to the correct infrastructure. The SDK uses this endpoint for all speech synthesis operations, replacing the default OpenAI URL.

Environment Variables

Store the API key in an environment variable named OPENAI_API_KEY. The SDK automatically reads this variable for authentication. This prevents hardcoding credentials in source files and simplifies deployment across development and production environments.

First Request

Sound wave illustration for: First Request

The API accepts text input and returns synthesized audio via a standard HTTP POST request. You must include your bearer token in the Authorization header and specify the model, voice, and desired response format within the JSON body. Ensure the input text does not exceed 4096 characters to avoid truncation errors.

Successful requests return the audio file directly in the response body. Failed requests incur no charge, allowing you to retry without penalty. This deterministic behavior ensures reliable integration into your data pipelines for synthetic speech dataset generation.

Curl Example

Use the following curl command to test the endpoint. Replace <your-api-key> with your actual key. The request specifies the tts-1 model, the nova voice, and requests the output in MP3 format. This command sends a short text string and saves the resulting audio file to output.mp3.

curl -X POST "https://api.xxx444.cc/v1/audio/speech" \ -H "Authorization: Bearer <your-api-key>" \ -H "Content-Type: application/json" \ -d '{"model": "tts-1", "input": "Hello world", "voice": "nova", "response_format": "mp3"}' \ -o output.mp3

Python Script

Install the official OpenAI SDK via pip. Configure the base URL to point to the VoxMold API endpoint. Initialize the client with your API key. Send the text payload using the audio.speech.create method. The SDK handles the JSON serialization and HTTP transport automatically.

from openai import OpenAI client = OpenAI( api_key="<your-api-key>", base_url="https://api.xxx444.cc/v1" ) response = client.audio.speech.create( model="tts-1", voice="nova", input="Testing integration", response_format="mp3" )

Response Parsing

The API returns the audio binary directly. In Python, you can write the response.content to a file or process it in memory. Check the HTTP status code to confirm success. A 200 OK status indicates the audio was generated. Any other status code indicates an error, such as invalid input or insufficient balance.

You can process the response if needed, but for dataset generation, saving the file immediately is more efficient. The response headers may contain metadata about the character count processed. Use this to track usage against your balance. Ensure your script handles potential network timeouts by implementing retries with exponential backoff.

  • Check HTTP status code for success
  • Write response.content to a file
  • Parse headers for character count
  • Handle timeouts with retries

Voice Selection

Sound wave illustration for: Voice Selection

VoxMold provides eight voice presets categorized by gender and tonal quality. Selecting the correct voice ensures your synthetic speech dataset maintains consistent acoustic properties, which is critical for training robust machine learning models. The available voices include female options like Aria and Nova, and male options such as Felix and Milo.

Choosing Presets

Each voice has a distinct profile: Aria offers a warm, clear narrator style, while Luna provides a soft storytelling tone. For instructional content, Sage is calm and precise. Male voices range from Felix’s energetic promo style to Orion’s deep, documentary delivery. Atlas serves as a neutral news voice, and Milo delivers friendly, conversational speech.

  • Aria: warm, clear narrator
  • Nova: bright, upbeat
  • Luna: soft, storytelling
  • Sage: calm, instructional
  • Felix: energetic, promo
  • Milo: friendly, conversational
  • Atlas: neutral, news
  • Orion: deep, documentary

Matching Tone

Align the voice preset with the semantic intent of your text. Use Orion for documentary-style corpora or Felix for promotional datasets. Avoid mismatching tone and content, as this introduces noise into your training data. Each voice is derived from licensed recordings, ensuring consistent synthetic characteristics across all generated audio files.

Language Alignment

All eight voices support 23 languages, allowing you to generate multilingual datasets without switching voices. If the language parameter is omitted, the API guesses the language based on the script, defaulting to English for Latin text. For non-English Latin-script content, explicitly set the language field to ensure accurate pronunciation and reduce training errors.

  • Arabic, Chinese, Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, Turkish

Batch Processing

Sound wave illustration for: Batch Processing

Batch processing requires splitting input text into chunks of 4,096 characters to comply with API constraints. Generated audio files are then joined sequentially. This approach ensures deterministic output for synthetic speech datasets, maintaining consistent audio quality across the entire dataset without exceeding request limits.

Since requests are processed one after another, concurrency is limited to 60 requests per minute per key. Higher usage requires queuing or parallel keys to maintain throughput without triggering rate limit errors.

Splitting Long Texts

Divide input text into segments not exceeding 4,096 characters. Each segment triggers a separate synthesis request. The resulting audio files are concatenated to form the final output. This method preserves the deterministic nature of the generated audio, which is critical for machine learning data pipelines.

  • Maximum input length: 4,096 characters per request
  • Audio files are joined sequentially after generation
  • Ensures consistent audio quality for dataset creation

Concurrency Limits

The API enforces a limit of 60 requests per minute per key. Under load, requests may wait in a queue. For higher throughput, generate multiple keys and distribute requests across them. Each key maintains its own rate limit, allowing parallel processing of text segments.

  • Rate limit: 60 requests per minute per key
  • Requests are processed sequentially under low load
  • Use multiple keys for parallel processing

Queue Management

Implement a queue to manage pending requests when the rate limit is reached. Prioritize requests based on dataset creation deadlines. Monitor queue depth to adjust key distribution or request timing. This ensures efficient use of API resources and prevents data loss during high-volume synthesis operations.

  • Implement a queue for pending requests
  • Monitor queue depth for performance tuning
  • Distribute requests across multiple keys

Error Handling

Sound wave illustration for: Error Handling

Robust error handling ensures your synthetic speech pipeline remains stable during high-volume data generation. This section covers rate limits, input validation, and network resilience to prevent silent failures or unnecessary costs.

Rate Limit Errors

The API enforces a limit of 60 requests per minute per key. Exceeding this triggers a 429 status code. Implement exponential backoff to retry requests automatically without overwhelming the server.

  • Standard limit: 60 requests/minute/key

Input Validation

Ensure input text does not exceed 4096 characters per request. Shorter texts may take a few seconds to generate, while longer texts require splitting. Validate characters before sending to avoid wasted credits on failed synthesis.

  • Max length: 4096 characters

Network Issues

Handle transient network errors by retrying with a short delay. If synthesis fails, the charge is returned in full, but ensure your code distinguishes between network timeouts and successful audio generation.

Optimization

Sound wave illustration for: Optimization

Optimizing your TTS pipeline requires balancing generation speed, file size, and cost efficiency. By adjusting the speed parameter and selecting appropriate audio formats, you can significantly reduce latency and storage overhead for your synthetic speech datasets.

This section details how to configure these settings to maximize throughput while maintaining the deterministic quality required for machine learning data pipelines.

Speed Settings

The speed parameter accepts values from 0.25 to 4.0. Increasing speed reduces generation time but may alter audio characteristics. For dataset creation, standard speeds (1.0) provide a balance between fidelity and processing time.

  • Range: 0.25–4.0
  • Adjustable per request

Format Selection

Choose mp3 or opus for compressed, smaller files suitable for large-scale storage. Use wav or flac if your ML models require uncompressed, lossless audio. pcm is available for raw data processing.

  • Compressed: mp3, opus
  • Lossless: wav, flac
  • Raw: pcm

Cost Reduction

Pricing is $0.01 per 1,000 characters. Failed requests incur no charge, so validate inputs before submission. Split long texts into 4096-character chunks to manage queue latency.

  • $0.01 per 1,000 chars
  • Failed requests are free
  • Min 4096 chars per request
Optimization

Testing

Sound wave illustration for: Testing

Validating the integration before production deployment ensures your synthetic speech pipeline meets quality standards. Use the trial credit to verify audio fidelity and latency characteristics without consuming your primary balance.

Trial Credits

New accounts receive $0.50 in trial credit, generating approximately 50,000 characters of audio. This allows you to test all eight voice presets and multiple formats without immediate payment.

  • Valid for 7 days from sign-in.
  • Generates ~50,000 characters of audio.

Quality Check

Download generated files in WAV or FLAC for lossless analysis. Verify that the synthetic watermark is present and that the audio matches the expected voice preset's tonal characteristics.

Latency Measurement

Measure end-to-end time from request submission to audio receipt. Expect roughly 25 characters per second for long texts, with short phrases taking a few seconds due to queue processing.

Production

Sound wave illustration for: Production

Deploying the TTS API for synthetic dataset generation requires handling volume and reliability. With a limit of 60 requests per minute per key, you must manage concurrency to avoid queue delays. For large-scale data pipelines, consider running multiple independent keys to parallelize generation without hitting the per-key rate limit.

Monitoring character consumption ensures budget alignment. Since costs are $0.01 per 1,000 characters, tracking usage per voice helps optimize dataset diversity against cost. Regularly review the usage dashboard to identify inefficient workflows or unexpected spikes in request volume.

Scaling Up

Increase throughput by issuing additional API keys. Each key allows 60 requests per minute, so multiple keys enable linear scaling. Ensure your client library distributes requests evenly across keys to prevent any single key from hitting the 60 rpm limit prematurely.

For long texts, split input into 4096-character chunks and process them concurrently. Join the resulting audio files sequentially to maintain narrative continuity. This approach maximizes utilization of the queue while respecting the per-request character limit.

  • Use multiple keys to parallelize requests beyond 60 rpm.
  • Split text into 4096-character segments for concurrent processing.
  • Join audio files sequentially after generation.

Monitoring Usage

Track character consumption against your balance. Failed requests are refunded, but successful generations are charged immediately. Monitor the dashboard to ensure sufficient credit for your dataset size. Adjust speed settings if latency becomes a bottleneck during high-volume runs.

Regularly audit voice selection. Using diverse voices like 'aria' or 'atlas' can improve dataset quality, but monitor the cost per hour of audio generated. Optimize by selecting the most efficient format (e.g., mp3) if storage is a concern.

  • Track character consumption against balance.
  • Refunds apply only to failed requests.
  • Audit voice selection for cost efficiency.

Key Rotation

Generate a new API key at any time via the /get-api-key/ page. The old key becomes invalid immediately upon issuance, ensuring zero downtime if you switch keys in your environment variables. Rotate keys periodically to mitigate risk if a key is exposed.

Store the new key securely and update your Python configuration before revoking the old one. Since only one key is active per account, plan rotations during low-traffic periods to avoid disrupting running pipelines.

  • Generate new key anytime; old key invalidates instantly.
  • Update environment variables before revoking old key.
  • Rotate during low-traffic periods.

Advanced Features

Sound wave illustration for: Advanced Features

Beyond basic text submission, the API provides precise control over language detection and output formatting. These features ensure deterministic results for automated ML dataset pipelines without requiring manual preprocessing of input scripts.

Language Codes

The API guesses language from the script by default, but Latin text defaults to English. You must explicitly set the language parameter for non-English Latin-script text to ensure correct synthesis.

  • Supported ISO codes for 23 languages including Arabic, Chinese, Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, Turkish.
  • Not supported: Vietnamese, Indonesian, Thai, Ukrainian, Romanian, Czech, Bengali.

Response Formats

Select mp3, wav, opus, flac, or pcm via the response_format field. Standard formats like WAV and MP3 integrate directly into existing audio processing pipelines.

Metadata Tracking

Request metadata, including timestamp, character count, and status, is retained for billing reconciliation. Input text is used only for generation and is not stored long-term, while generated audio is returned in the response and not persisted.

Data Management

Sound wave illustration for: Data Management

VoxMold ensures strict data isolation for synthetic speech generation pipelines. Input text is used solely for audio synthesis and is not retained for model training. Generated audio files are returned directly to the client and are not stored on our servers after delivery, minimizing storage overhead for high-volume dataset creation.

Audio Storage

Since we do not store generated audio, your infrastructure must handle persistent storage. Each request returns the audio file immediately; ensure your application saves these files locally or to a cloud bucket before the session ends. This approach keeps our server footprint lean and aligns with standard ML data ingestion workflows.

  • Audio is not stored server-side.
  • Clients manage all persistent storage.
  • Immediate download upon response receipt.

Input Retention

The input text is processed exclusively to generate the requested audio format. We do not use your source text to train our voice models, ensuring your proprietary dataset content remains private. Once the audio is delivered, the text content is cleared from active processing memory.

Billing Records

We retain request metadata, including timestamp, character count, and status, strictly for billing purposes. This data tracks your usage against your USDT balance and verifies charge accuracy. No other personal or content data is kept beyond what is necessary to process the transaction and resolve billing disputes.

  • Metadata kept for billing only.
  • Includes time, characters, and status.
  • No long-term content retention.

Support

Sound wave illustration for: Support

VoxMold support operates exclusively via email. There is no phone number or live chat available for technical inquiries. For immediate assistance with API integration issues, direct your messages to the support email address listed in the footer.

Email Contact

Send all support requests to the designated email address. Include your API key and request ID in the subject line to ensure faster resolution. Responses are provided asynchronously.

  • Email only; no phone support
  • Include API key in requests
  • No guaranteed response time

Documentation Links

Refer to the /docs/ endpoint for the complete API specification, including the OpenAI-compatible request schema. The /get-api-key/ page provides ready-to-use curl examples and balance checks for quick verification.

Status Updates

Service status is not guaranteed. There is no public status page or uptime certificate. Monitor your request metadata for billing records and status codes to determine if an issue is systemic or isolated.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. The response headers may contain metadata about the character count processed.

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

More on this site