How to Integrate the TTS API with JavaScript for Audio Generation?

By LinguaCode editorial team · Updated 2026-11-19

This guide shows teachers and methodologists how to integrate the SonoSpeak TTS API into JavaScript applications for language learning. You will learn to send text and receive audio files using standard HTTP requests, enabling pronunciation drills and reading practice. The process relies on the OpenAI-compatible endpoint structure, allowing you to use familiar tools while accessing our specific engine.

Readers will find concrete code examples for generating speech, handling responses, and managing errors. We cover prerequisites like obtaining an API key, selecting voices, and splitting long texts. This page is designed for developers building educational tools who need reliable, character-based billing without streaming or complex setup.

How to Integrate the TTS API with JavaScript for Audio Generation?

Frequently asked questions

What is the easiest way to start?

Sign up on /get-api-key/ using Google or email to receive your API key. Use the official OpenAI SDK by setting base_url to https://api.iclub88.cc/v1. Send a POST request to /v1/audio/speech with your key, model, input text, and voice preset to receive the audio file immediately.

Do I need a backend server?

No. You can call the API directly from the browser using JavaScript. Pass your API key in the Authorization header. Note that rate limits apply per key (60 requests per minute), so manage concurrent calls carefully to avoid throttling during high usage periods.

Can I use this in a browser?

Yes. The API accepts standard HTTP POST requests from any JavaScript environment. Use the OpenAI SDK or fetch API with base_url https://api.iclub88.cc/v1. Ensure your API key is secure if exposing it client-side, as requests are processed directly from the browser to the API endpoint.

How do I play the audio?

The API returns an audio file (mp3, wav, opus, flac, or pcm). Store the response blob and use the HTML5 <audio> element or Web Audio API to play it. Handle the response stream or buffer in your JavaScript code to trigger playback after synthesis completes.

What is the best voice for learning?

Q: Which voice is suitable for learning? A: Aria (warm, clear narrator) and Milo (friendly, conversational) are well-suited for language learning. Their clear articulation supports pronunciation drills and reading practice. Select the voice via the voice parameter in your request. We do not claim any voice is the "best"; test different voices to match your specific educational content style and target audience needs.

How do I handle special characters?

Send standard UTF-8 JSON in the request body. The API handles special characters within the 4096 character limit per request. Spaces and punctuation count toward the character limit. Ensure your JSON encoding is correct to avoid request errors during transmission to the synthesis endpoint.

Is the API fast?

Q: How fast is the API? A: Synthesis runs at roughly real-time speed (25 characters per second). Short phrases take a few seconds. Requests are processed sequentially, so under load, wait times may occur. Plan your audio generation timing accordingly, especially for interactive language learning applications requiring immediate feedback.

Can I pause and resume?

The API does not support streaming or partial audio generation. You must wait for the full audio file to be generated and returned before playing or pausing. Use the HTML5 audio element’s controls to pause or resume playback of the complete file after receipt.

How do I test with a small text?

Use the free trial credit of $0.50 (about 50,000 characters) valid for 7 days after signing in with Google. Send a short text request to /v1/audio/speech to verify integration. Check the response for the audio blob and confirm playback in your application.

What if the text is in a different language?

Set the optional language parameter to the ISO code (e.g., 'fr', 'de', 'es'). If omitted, the API guesses the language, defaulting to English for Latin script. Explicitly setting the language ensures correct pronunciation and voice selection for non-English content in your language learning tools.

Can I use the API for subtitles?

The API generates audio, not text. You must generate subtitles separately using your own speech-to-text or manual transcription tools. The API returns audio files only. Integrate your subtitle file with the generated audio in your player for synchronized language learning exercises.

How do I debug a failed request?

Check the HTTP response status code and body for error details. Failed requests are free, with charges returned in full. Verify your API key, input text length (max 4096 chars), and voice validity. Ensure the request format matches the required JSON structure for the speech endpoint.

Is there a limit on daily usage?

There is no daily usage limit. The rate limit is 60 requests per minute per key (10 per minute before the first top-up). You can generate as much audio as needed, provided you stay within the per-minute request threshold and have sufficient balance.

Can I use the API for free?

Yes, with a free trial of $0.50 credit (about 50,000 characters) valid for 7 days when signing in with Google. After the trial, top up with USDT on TRON. Accounts created with email/password start without trial credit. Failed requests are always free.

Prerequisites

Sound wave illustration for: Prerequisites

Before integrating the TTS API, ensure you have a valid API key from the /get-api-key/ dashboard. Your JavaScript environment must support modern fetch capabilities. A basic understanding of HTTP requests and JSON handling is required to construct the payload correctly.

API key from the dashboard

Sign up on the site or log in with Google to access your unique key. This key authenticates all requests to the API endpoint. Keep it secure, as it controls your usage and billing.

  • One active key per account
  • New key invalidates the old one immediately
  • Visible on the /get-api-key/ page

JavaScript environment

Use any modern JavaScript runtime or browser environment. The fetch API is standard in all current browsers and Node.js. Ensure your environment handles binary data (blobs) for audio playback.

Basic understanding of fetch

You need to send a POST request with a JSON body. The request must include the Authorization header with your Bearer token. Understanding how to handle responses is crucial for processing the audio file.

  • POST method for /v1/audio/speech
  • JSON body structure
  • Bearer token in headers

Step 1: Get Your API Key

Sound wave illustration for: Step 1: Get Your API Key

Access the API key by creating an account on iclub88.cc. You can sign up using Google or an email and password. Accounts are specific to this site, so ensure you register on iclub88.cc to generate your credentials.

Sign up on the site

Visit the registration page to create your account. Google sign-in provides immediate access with a $0.50 trial credit valid for 7 days. Email-based accounts start without trial credit. Both methods generate a unique account identifier for this storefront.

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

Navigate to /get-api-key/

Once logged in, go to the /get-api-key/ dashboard. This page displays your active API key, current balance, and usage statistics. The interface provides a ready curl example for quick reference.

  • View active key and balance
  • Check character usage history
  • Access pre-built curl examples

Copy your key

Copy the key starting with tts- from the dashboard. This key authenticates all requests to https://api.iclub88.cc/v1. You can issue a new key at any time, which immediately invalidates the previous one.

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

Step 2: Prepare the Request

Sound wave illustration for: Step 2: Prepare the Request

Before sending a request, ensure your text input stays within the 4096-character limit per request. Spaces and punctuation count toward this limit, so plan your splitting strategy accordingly.

Select one of the eight available voices and specify the language using its ISO code. This prevents automatic detection errors, especially for non-English Latin script text.

Define the text input

Place your text string into the input field of the JSON body. Keep each request under 4096 characters to avoid truncation.

Select a voice and language

Choose a voice ID from the 8 presets (e.g., 'aria', 'nova'). Set the language field explicitly to ensure correct pronunciation, as the API guesses Latin scripts as English by default.

  • Voice: 'aria' for clear narration
  • Language: ISO code (e.g., 'es', 'fr')

Set the response format

Specify the desired audio format in the response_format field. Supported formats include mp3, wav, opus, flac, and pcm.

  • mp3: Standard compressed audio
  • wav: Lossless uncompressed audio

Step 3: Send the Request

Sound wave illustration for: Step 3: Send the Request

The core of the integration is an asynchronous POST request to the speech endpoint. You send your text payload to receive an audio file in return, ensuring the engine processes the synthesis request efficiently.

Use the POST endpoint

Direct your request to https://api.iclub88.cc/v1/audio/speech. This endpoint accepts standard HTTP POST methods, making it compatible with most JavaScript HTTP clients and fetch APIs used in modern web environments.

Include the Bearer token

Authentication is handled via the Authorization header. Include your API key in the format Bearer tts-.... This ensures the request is associated with your account's balance and rate limits.

Send JSON body

Structure your payload as JSON containing model, input, voice, and response_format. The input field holds the text string, while voice selects one of the eight presets. Ensure the text does not exceed 4096 characters per request.

  • Set model to 'tts-1' or 'tts-1-hd'
  • Include input as the text string
  • Specify voice from the available presets
  • Define response_format (e.g., mp3, wav)

Step 4: Handle the Response

Sound wave illustration for: Step 4: Handle the Response

Upon successful synthesis, the API returns the audio file directly in the response body. The content type matches your requested format (mp3, wav, opus, flac, or pcm). You receive raw binary data, not a JSON object with a URL, ensuring minimal latency for immediate playback.

The audio is returned after synthesis completes, so you can process it directly in memory. There is no need to poll for a status or wait for a separate download step. This design supports pronunciation drills where audio is available after generation.

Receive audio data

The response contains the raw audio bytes. Ensure your HTTP client does not automatically parse the body as JSON, as this will corrupt the audio data. The status code 200 confirms successful generation and billing.

Convert to blob or base64

In JavaScript, convert the response stream into a Blob or ArrayBuffer. This allows you to create a temporary object URL for playback or encode it to Base64 if you need to embed it directly in HTML or send it to a backend service for storage.

Play or save the audio

Use the HTML5 <audio> element to play the Blob URL directly. For saving, trigger a download link. Note that generated files include an inaudible watermark identifying them as synthetic speech. Failed requests return no audio and refund the character count.

image":

Step 5: Error Handling

Sound wave illustration for: Step 5: Error Handling

Robust error handling ensures your language learning application remains stable during TTS generation. You must distinguish between network failures, server errors, and specific API conditions to manage user expectations correctly.

Implementing proper checks prevents silent failures and ensures that invalid requests do not consume your character allowance unnecessarily.

Check for HTTP errors

Always inspect the HTTP status code returned by the fetch request. A 4xx error indicates a client-side issue, such as an invalid API key or malformed JSON body, while a 5xx error suggests a temporary server problem.

If the status is not 200, parse the error response body to identify the specific cause. This allows you to display precise messages to teachers or students, such as 'Invalid voice ID' or 'Text too long'.

  • Status 401: Check your API key in the dashboard.
  • Status 400: Validate text length (max 4096 chars) and voice ID.
  • Status 429: You have exceeded 60 requests per minute limit.

Handle network issues

Network interruptions can occur during the request or when receiving the audio blob. Use try-catch blocks to handle promise rejections gracefully.

Implement retry logic with exponential backoff for temporary network failures. Since requests are processed sequentially, brief queues may also cause slight delays, but these are not network errors.

Refund on failure

If synthesis fails due to a server error or invalid input, the request is free. No characters are deducted from your balance.

This refund is automatic. You do not need to request it manually. Failed requests are returned in full, ensuring you only pay for successfully generated audio files.

Example: Generating Audio

Sound wave illustration for: Example: Generating Audio

The following example demonstrates a standard JavaScript fetch call to generate speech. It sends a JSON payload to the POST endpoint, authenticating with your Bearer token. The response returns an audio blob, which can be immediately played or saved for language learning drills.

Complete code snippet

```javascript const response = await fetch('https://api.iclub88.cc/v1/audio/speech', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_API_KEY' }, body: JSON.stringify({ model: 'tts-1', input: 'Hello, this is a test sentence.', voice: 'nova', response_format: 'mp3', speed: 1.0 }) }); const audioBlob = await response.blob(); const audioUrl = URL.createObjectURL(audioBlob); console.log('Audio ready:', audioUrl); ```

Explanation of fields

The model field accepts 'tts-1' or 'tts-1-hd'. The input text is limited to 4096 characters. The voice parameter selects one of the eight presets, such as 'nova' for a bright, upbeat tone. The response_format determines the output file type, here set to 'mp3'.

Testing the request

Ensure your API key is active and has sufficient balance. The free trial provides $0.50 credit, valid for 7 days. If the request fails, check the HTTP status code. Failed requests incur no charge, and the balance remains unchanged.

Example: Generating Audio

Advanced: Long Texts

Sound wave illustration for: Advanced: Long Texts

The API limits each request to 4,096 characters. For longer content, you must split the text into chunks and generate audio for each part separately.

The client is responsible for concatenating the resulting audio files. There is no built-in streaming or server-side joining of segments.

Split text into parts

Divide your input text into segments, ensuring each part does not exceed 4,096 characters. This limit includes spaces and punctuation.

Process these segments sequentially or in parallel, depending on your application’s architecture and rate limits (60 requests per minute).

  • Max 4096 characters per request
  • Include spaces and punctuation in the count
  • Process sequentially or in parallel

Join audio files

Receive each audio file in the response. Use a library like ffmpeg or a simple concatenation method to merge the files into a single track.

Ensure the format matches your response_format setting (mp3, wav, opus, flac, or pcm) to avoid compatibility issues during merging.

Manage character limits

Track the character count of each chunk before sending. If a chunk exceeds the limit, split it at a sentence boundary to avoid truncation.

Remember that short phrases may take a few seconds to generate, while longer texts process at roughly real-time speed (25 characters per second).

Common Issues

Sound wave illustration for: Common Issues

Integration issues usually stem from configuration mismatches or API constraints rather than code errors. Understanding these common pitfalls ensures smooth audio generation for your language learning application.

Wrong language detection

If the language field is omitted, the API guesses the language from the script. Latin text defaults to English, which causes incorrect pronunciation for other Latin-based languages like French or Spanish. Always explicitly set the language parameter for non-English Latin text to ensure accurate synthesis.

Rate limit errors

New accounts are limited to 10 requests per minute. After the first top-up, this increases to 60 requests per minute. Exceeding this limit results in a 429 error. Implement exponential backoff in your JavaScript client to handle these transient errors gracefully.

Invalid voice ID

Ensure the voice parameter matches one of the eight available presets (e.g., aria, nova, felix). Using an unsupported voice ID returns an error. Use the GET /v1/voices endpoint to retrieve the current list of valid voice IDs before sending synthesis requests.

Best Practices

Sound wave illustration for: Best Practices

Generating audio repeatedly for the same text wastes characters and costs. Since input text is not stored for reuse, caching locally prevents redundant API calls. Store the resulting audio files or their URLs to serve subsequent requests instantly.

Choosing the right voice reduces cognitive load for learners. Use clear, neutral voices like aria or atlas for pronunciation drills, and warmer voices like nova or luna for storytelling. Match the voice tone to the educational context to improve retention.

Cache generated audio

Store generated audio files locally or on a CDN. Check if a hash of the input text exists before making a new request. This saves characters and reduces latency for repeated practice sessions.

Use the response_format parameter to choose smaller file sizes like mp3 or opus for web delivery. Larger formats like wav or flac are better for offline distribution but consume more storage.

  • Hash input text to create cache keys
  • Store audio in local storage or a CDN
  • Use mp3 or opus for web efficiency

Use appropriate voices

Select voices that match the learning objective. For clear pronunciation, use neutral voices like atlas or aria. For engaging content, use upbeat voices like nova or friendly ones like milo.

Ensure the language field is set explicitly for non-English Latin text to avoid incorrect detection. This ensures accurate phoneme generation for language learners.

  • Use atlas or aria for drills
  • Use nova or luna for stories
  • Set language explicitly for non-English

Monitor usage

Track character counts to stay within budget. The API charges $0.01 per 1,000 characters, so even small texts add up over time.

Check the dashboard at /get-api-key/ for usage stats. Set up alerts for rate limits (60 requests per minute) to avoid service interruptions during peak teaching hours.

  • Track character counts regularly
  • Check dashboard for usage stats
  • Monitor rate limits (60 req/min)

Using OpenAI SDK

Sound wave illustration for: Using OpenAI SDK

The official OpenAI JavaScript SDK works seamlessly with this API by overriding the base URL. This allows you to use familiar methods without writing custom fetch logic, simplifying integration for language learning platforms.

Ensure your SDK version is compatible with the speech endpoint structure. The key remains the only requirement for authentication.

Install the SDK

Install the package via npm or yarn in your project directory. This provides the necessary TypeScript definitions and client utilities.

npm install openai

  • npm install openai
  • yarn add openai

Configure base URL

Initialize the client with your API key and set the base URL to the site's API endpoint. This redirects all requests to the correct service.

const openai = new OpenAI({ apiKey: 'tts-your-key', baseURL: 'https://api.iclub88.cc/v1' });

Make the call

Call the audio.speech method with the desired model, voice, and input text. The SDK handles the JSON serialization and returns the audio blob.

const response = await openai.audio.speech.create({ model: 'tts-1', voice: 'nova', input: 'Hello world', response_format: 'mp3' });

Support and Contact

Sound wave illustration for: Support and Contact

Support is available exclusively via email. There is no phone number, live chat, or dedicated forum for SonoSpeak. Send your inquiries regarding integration or billing to our support address.

Documentation is the primary resource for technical details. Use the links below to understand endpoints, voices, and pricing.

Email support

Our team handles all support tickets via email. We do not offer phone support or live chat. Please include your API key and error logs for faster resolution.

Documentation links

Refer to /docs/ for detailed API specifications, endpoint definitions, and code examples. Check /pricing/ for current rates and /get-api-key/ to manage your credentials.

Community resources

There is no official community forum. Share your JavaScript integration patterns for language learning tools in relevant developer groups. Use #SonoSpeakAPI to connect with other educators.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. Each voice is independent and does not require custom configuration.

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. TRON developer hub: TRC-20
  4. curl documentation
  5. Node.js documentation
  6. openai-python on GitHub
  7. openai-node on GitHub
  8. LibriVox public-domain audiobooks
  9. LibriTTS-R paper (arXiv 2305.18802)
  10. MDN: Web Speech API
  11. OpenAI API reference: create speech
  12. FFmpeg documentation

More on this site