How to Integrate TTS API with JavaScript for Accessibility?

By AccessiVoices editorial team · Updated 2026-11-19

This page provides a practical guide for product teams integrating our text-to-speech API into web applications to support users with dyslexia. You will learn how to send text via a standard REST endpoint and receive audio files using native JavaScript, ensuring consistent and clear speech output without requiring third-party SDKs.

We cover environment setup, payload construction, and browser-based audio playback using Blob URLs. The guide includes concrete code examples for both Node.js and client-side scripts, along with strategies for error handling, performance optimization, and accessibility compliance. By the end, you will have a working implementation ready for production use.

How to Integrate TTS API with JavaScript for Accessibility?

Frequently asked questions

What is JavaScript TTS integration?

JavaScript TTS integration connects your web app to the AccessiVoices API. You send text via POST requests to receive audio files. This allows dynamic speech generation for users with dyslexia. The API uses standard JSON bodies, making it compatible with common JavaScript fetch libraries for seamless accessibility implementation.

How do I make a POST request?

Send a POST request to https://api.11bets.cc/v1/audio/speech. Include your Bearer token in the Authorization header. The JSON body requires the model (tts-1 or tts-1-hd), input text, and voice preset. You can also specify response_format, speed, and language. The API returns the audio file directly.

What is a Blob URL?

A Blob URL is a temporary link to binary data stored in memory. After receiving audio from the API, you create a Blob from the response. Then, use URL.createObjectURL() to generate a playable URL. This allows you to assign the audio directly to an HTML <audio> element for immediate playback.

How do I handle errors in JS?

Wrap your fetch call in a try-catch block to handle network issues. Check the response status code; failed synthesis requests are free. If the request fails, the API returns an error object. Log these errors to debug missing headers or invalid JSON bodies before retrying the request.

Can I use React for TTS?

Yes, React works perfectly with the standard fetch API. Use useEffect to trigger synthesis when a text prop changes. Store the resulting Blob URL in state to update the audio player component. Since the API is HTTP-based, no custom SDK is needed, ensuring consistent audio outputs for accessibility.

How do I play audio in the browser?

Use the HTML5 <audio> element. Assign the Blob URL from your API response to the src attribute. Call the play() method programmatically or let users trigger it. The API supports formats like mp3 and wav, ensuring broad browser compatibility without requiring additional plugins or external libraries for playback.

What is ARIA accessibility?

ARIA (Accessible Rich Internet Applications) attributes enhance web content for assistive technologies. Use aria-live regions to announce generated speech to screen readers. Set aria-labels on audio controls. This ensures users with visual impairments or reading difficulties can navigate your app effectively, complementing the clear audio outputs from the TTS API.

How do I cache audio?

Cache audio by storing Blob URLs or the raw audio bytes in localStorage or IndexedDB. Since generated audio is not stored by the API, you must manage caching locally. Reuse the same voice and text combinations to retrieve cached files, reducing API calls and improving performance for repeated content access.

What is the character limit?

The API accepts up to 4096 characters per request. If your text exceeds this limit, split it into parts. Generate audio for each part separately, then join the files. Spaces and punctuation count toward the character limit. This ensures consistent synthesis quality and prevents request failures due to oversized payloads.

How do I rotate API keys in code?

Generate a new key from your account dashboard. Update the Authorization header in your code to use the new Bearer token. The old key stops working immediately upon issuing the new one. Ensure your application handles the transition smoothly to avoid service interruptions during the rotation process.

Is the API synchronous?

The API is synchronous in terms of request-response. You send a POST request and wait for the audio file. However, processing happens in a queue, so longer texts may take time. Typical speed is roughly real-time on long texts. Short phrases take a few seconds to generate.

How do I test the integration?

Use the provided curl example or a tool like Postman. Send a test request with a short text and a valid voice preset. Verify the response contains the audio file. Check your balance and usage stats on the dashboard to confirm the request was processed and charged correctly.

What tools do I need?

You need a standard web browser, a code editor, and a JavaScript runtime. Use the OpenAI SDK (with base_url changed) or plain fetch for API calls. A text editor for writing HTML and JS is sufficient. No special plugins or mobile SDKs are required. Basic knowledge of JSON and HTTP requests is essential.

How do I optimize for performance?

Pre-generate audio for static content and cache the Blob URLs. For dynamic text, split long inputs to stay under 4096 characters. Use the tts-1 model. Monitor your rate limit of 60 requests per minute. Avoid redundant API calls by reusing previously generated audio files for identical text inputs.

Understanding the API Structure

Sound wave illustration for: Understanding the API Structure

AccessiVoices provides a straightforward RESTful interface designed for seamless integration into web applications. By adhering to standard HTTP methods, the API allows product teams to easily incorporate text-to-speech capabilities without complex protocol negotiations. This simplicity ensures that accessibility features can be deployed rapidly within existing JavaScript frameworks.

The core interaction revolves around a single endpoint that accepts text input and returns synthesized audio. This design minimizes the learning curve for developers while ensuring consistent, clear audio outputs suitable for users with dyslexia. Understanding this structure is the first step toward building inclusive web experiences.

RESTful Endpoint Design

All synthesis requests are sent to the POST https://api.11bets.cc/v1/audio/speech endpoint. This endpoint follows standard REST conventions, making it compatible with common HTTP libraries in JavaScript. The API accepts JSON payloads and returns audio files directly.

The endpoint supports standard HTTP status codes to indicate success or failure. A 200 OK response contains the audio data, while other codes signal issues like authentication errors or rate limits. This predictable behavior helps in building robust error-handling routines within your application.

  • Endpoint: POST https://api.11bets.cc/v1/audio/speech
  • Method: POST
  • Format: JSON request, binary audio response

JSON Request Body

The request body is a JSON object containing the text to be spoken and configuration parameters. Required fields include the model (tts-1 or tts-1-hd) and the input text, which must not exceed 4096 characters. You can also specify the voice, response_format, and speed to tailor the output.

Authentication is handled via the Authorization header with a Bearer token. This key, obtained from your account dashboard, identifies your account and tracks usage. Including the correct key ensures that your requests are processed and billed correctly against your balance.

The input field accepts plain text strings. Special characters and punctuation are counted toward the character limit. For languages other than English, explicitly set the language field to ensure accurate pronunciation, as the API guesses the language otherwise.

  • model: 'tts-1' or 'tts-1-hd'
  • input: text string (max 4096 chars)
  • voice: one of 8 presets
  • response_format: mp3, wav, opus, flac, or pcm
  • speed: 0.25 to 4.0
  • language: optional ISO code

Audio Response Handling

Upon successful synthesis, the API returns an audio file in the specified format. For web applications, this is typically handled by creating a Blob URL from the response body. This allows the browser's native audio elements to play the synthesized speech directly without downloading a separate file.

The response includes the audio data in the body and appropriate headers indicating the content type. Developers should parse the response as a blob or array buffer to ensure compatibility with various audio playback methods.

Since the API processes requests sequentially, long texts may take time to synthesize. Implementing proper loading states in your UI can improve the user experience while waiting for the audio file to be generated and returned by the server.

Setting Up Your Environment

Sound wave illustration for: Setting Up Your Environment

Begin by installing the necessary dependencies to handle HTTP requests and audio processing in your Node.js environment. This setup ensures your application can communicate effectively with the API endpoint.

Installing Node.js Dependencies

Use npm to install the axios or node-fetch package for making HTTP requests. Ensure your project includes a package manager for consistent dependency management across development and production environments.

  • Install axios or node-fetch via npm
  • Ensure Node.js version 14 or higher is active

Configuring Environment Variables

Store your API key in a .env file to prevent accidental exposure in version control. Use a library like dotenv to load these variables securely at runtime, keeping your authentication credentials separate from your codebase.

Testing Connectivity

Send a simple request to the GET /v1/voices endpoint to verify your key and network connection. A successful response confirms that your environment is correctly configured to interact with the TTS service.

Making Your First Request

Sound wave illustration for: Making Your First Request

To begin, construct a JSON payload targeting https://api.11bets.cc/v1/audio/speech. Include your model (e.g., "tts-1"), the input text, and a voice preset like "sage" for clear instructional audio. Set the Authorization header with your Bearer key.

Constructing the JSON Payload

Define the request body with model, input, voice, and response_format. Ensure the text does not exceed 4,096 characters, as longer inputs require splitting. Specify a voice preset such as "nova" for upbeat content or "atlas" for neutral news-style output.

  • Model: "tts-1" or "tts-1-hd"
  • Voice: e.g., "sage", "aria", "atlas"
  • Format: "mp3" or "wav"
  • Max input: 4,096 characters

Sending the POST Request

Send a POST request to the speech endpoint with the JSON body. Use your API key in the Authorization header. The request is processed sequentially, so under load, responses may queue. Failed requests incur no charge.

  • Endpoint: POST /v1/audio/speech
  • Auth: Bearer tts-...
  • Rate limit: 60 req/min

Parsing the Audio Response

The API returns the audio file directly in the response body. Convert this binary data into a Blob or ArrayBuffer. You can then assign this Blob to an HTML <audio> element’s src property for immediate playback in your web application.

Handling Audio Playback

Sound wave illustration for: Handling Audio Playback

The API returns complete audio files rather than streaming chunks, allowing you to handle playback via standard browser audio elements. You receive the full file after processing, which simplifies integration for accessibility features like ARIA labels and keyboard navigation.

For optimal performance, create Blob URLs from the response data. This approach enables seamless audio playback while managing memory usage efficiently, ensuring a smooth experience for users with dyslexia or reading difficulties.

Browser Audio Element

Use the native HTML5 audio element to play the returned audio files. This method supports standard controls and integrates easily with ARIA labels for screen readers.

Ensure keyboard navigation is supported by focusing the audio element when playback begins. This helps users with motor impairments navigate your application effectively.

  • Supports standard audio controls
  • Integrates with ARIA labels
  • Enables keyboard navigation

Blob URL Creation

Convert the audio response into a Blob URL to play the audio directly in the browser. This method is efficient for managing memory and handling multiple audio files.

Blob URLs allow you to play audio without storing the files permanently, reducing storage overhead and improving application performance.

  • Efficient memory management
  • No permanent storage needed
  • Direct browser playback

Streaming vs Blob

Our API returns complete audio files, not streaming chunks. You receive the full file after processing.

Unlike WebSocket streams, this approach ensures consistent audio quality and simplifies error handling, making it ideal for accessibility-focused applications.

Error Handling Strategies

Sound wave illustration for: Error Handling Strategies

Reliable audio delivery is critical for users with dyslexia, where a failed read-aloud breaks the reading flow. Error handling ensures your application gracefully manages network hiccups and API limits without leaving the user confused or stranded.

By implementing robust strategies, you can distinguish between transient network issues and permanent failures, allowing your interface to provide clear feedback and automatic recovery options seamlessly.

Network Error Handling

Network errors occur when the client cannot reach https://api.11bets.cc/v1 or the connection drops. These are often temporary and do not consume your character credit. Detect these by catching fetch promise rejections or timeout events.

Provide immediate visual feedback, such as a spinner or a "Retrying..." message, rather than a static error. This maintains the user’s context while the network recovers.

  • Use try/catch blocks around fetch calls.
  • Implement a timeout threshold (e.g., 10 seconds).
  • Show a non-intrusive loading indicator.

API Error Responses

The API returns specific HTTP status codes for failures. A 401 Unauthorized indicates an invalid or expired API key. A 429 Too Many Requests means you have exceeded the 60 requests per minute limit.

Unlike network errors, these usually require user action or waiting. Display the exact error message from the JSON response to help developers debug quickly, but show a user-friendly message to end-users.

Note that failed synthesis requests are free, so retrying after a 429 does not incur extra character costs.

  • Handle 401: Re-authenticate or refresh the API key.
  • Handle 429: Wait before retrying.
  • Handle 400: Check input text length (max 4096 chars).

Retry Mechanisms

Implement an exponential backoff strategy for transient errors. Start with a short delay (e.g., 1 second) and double it for each subsequent attempt, up to a maximum limit.

Limit retries to 3 attempts to prevent infinite loops. If the API remains unreachable, display a permanent error message with a "Retry" button for manual user intervention.

Ensure that retry logic does not trigger unnecessary network spikes, which could further exacerbate rate limit issues during high traffic.

Optimizing Performance

Sound wave illustration for: Optimizing Performance

Optimizing performance ensures smooth audio playback for users with dyslexia, preventing jarring pauses during text reading. By intelligently managing network requests and memory, you maintain a consistent listening experience even with variable generation speeds.

Focus on reducing latency and avoiding redundant API calls. This section covers strategies to cache audio, pre-fetch content, and handle memory efficiently within JavaScript environments.

Caching Audio Responses

Store generated audio blobs in memory or localStorage to avoid re-synthesizing identical text. Since requests are processed sequentially, caching prevents redundant API calls for repeated phrases or UI navigation states.

  • Cache responses for static content like help text or menu labels.
  • Use short-lived memory storage for dynamic text to save disk space.

Pre-fetching Next Sentences

Anticipate user navigation by sending synthesis requests for upcoming text segments while the current audio plays. This minimizes the gap between sentences, crucial for maintaining reading flow for users with reading difficulties.

  • Send requests for the next 1-2 sentences during playback.
  • Queue audio blobs and play them sequentially once generated.

Managing Memory Usage

Audio blobs can consume significant memory. Revoke object URLs after playback and limit the cache size to prevent browser crashes on long texts. Monitor memory usage to ensure stable performance during extended sessions.

  • Revoke Blob URLs after audio elements are removed from the DOM.
  • Limit cache to recent or frequently accessed audio segments.

Accessibility Features

Sound wave illustration for: Accessibility Features

Accessible TTS integration requires more than just audio generation; it demands thoughtful UI design that respects user control and cognitive needs. By leveraging standard web accessibility guidelines, product teams can ensure their speech-enabled applications are usable by individuals with dyslexia and other reading difficulties.

ARIA Labels for Audio

Ensure audio elements include descriptive aria-label attributes that indicate the content being spoken. This allows screen readers to announce the purpose of the audio player, helping users understand when text-to-speech is active without relying on visual cues alone.

  • Use aria-live regions to announce status changes during synthesis.
  • Label controls clearly for pause, play, and speed adjustments.

Keyboard Navigation Support

All TTS controls must be fully operable via keyboard. Users with motor impairments or those who prefer keyboard navigation should be able to trigger playback, adjust speed, and select voices using standard keys like Space or Enter.

  • Implement visible focus indicators for all interactive elements.
  • Ensure tabindex order follows logical reading flow.

Voice Clarity Settings

Leverage the API’s speed parameter (0.25–4.0) to adjust playback rate. Slower speeds (e.g., 0.75) aid users with processing difficulties, while faster rates help experienced readers. Allow users to choose from the 8 available voices, such as Sage for calm instruction or Luna for storytelling.

  • Pre-set speeds for common accessibility needs.
  • Persist user voice preferences locally.
Accessibility Features

Code Example: Node.js

Sound wave illustration for: Code Example: Node.js

This Node.js example demonstrates a standard integration using the native fetch API, suitable for backend services or server-side rendering environments. It constructs the required JSON payload with the tts-1 model and sends it to the API endpoint. The script handles the binary audio response efficiently, ensuring that character limits and authentication headers are correctly applied without external dependencies.

By leveraging modern JavaScript features, the integration remains lightweight and easy to maintain. The code snippet below illustrates how to send a request and receive the audio file, providing a solid foundation for accessibility features in your web applications.

Using Fetch API

The fetch method is used to send a POST request to https://api.11bets.cc/v1/audio/speech. The request body includes the model, voice, input, and response_format fields. Ensure the Authorization header contains your valid API key prefixed with Bearer .

The response is parsed as an array buffer, which can then be converted into a Blob or written directly to a file. This approach avoids the overhead of additional HTTP libraries, keeping your bundle size minimal.

  • Set Content-Type to application/json
  • Include Authorization: Bearer tts-...
  • Define model as tts-1 or tts-1-hd
  • Limit input to 4096 characters

Async Await Pattern

Using async/await simplifies the handling of the Promise returned by fetch. This makes the code more readable and easier to debug, especially when dealing with network latency or API rate limits. It ensures that the audio data is fully received before proceeding to playback or storage.

The try...catch block captures any errors during the request, such as invalid API keys or network timeouts. This is crucial for maintaining a smooth user experience in accessibility-focused applications where audio clarity is paramount.

Error Logging

Proper error logging helps in identifying issues quickly, such as exceeded character limits or invalid voice presets. Log the status code and response body to diagnose failures without exposing sensitive API keys in the console.

In a production environment, consider logging these errors to a monitoring service to track usage patterns and potential issues. This data can help optimize your integration and ensure consistent audio delivery for users with reading difficulties.

Code Example: Browser JS

Sound wave illustration for: Code Example: Browser JS

Client-side integration allows direct browser-to-API communication, eliminating server-side proxy overhead. Use the Fetch API to send text to https://api.11bets.cc/v1 with your Bearer token. Ensure the input field respects the 4096-character limit to avoid silent truncation or errors.

Client-Side Request

Construct a JSON payload with model, input, and voice. Set the Authorization header to Bearer tts-.... The API returns an audio file directly, which can be processed as a Blob in the browser environment without intermediate storage.

  • Use fetch() with POST method.
  • Include Authorization: Bearer <key> header.
  • Set Content-Type: application/json.
  • Limit input to 4096 characters.

Direct Audio Playback

Convert the response into a Blob URL using URL.createObjectURL(). Assign this URL to an HTML <audio> element’s src attribute. This enables immediate playback without downloading the file to disk, supporting real-time accessibility for users with reading difficulties.

  • Create Blob from response blob.
  • Generate object URL via URL.createObjectURL().
  • Assign to <audio src>.
  • Revoke URL after playback to free memory.

UI Integration

Bind the playback to a button with clear ARIA labels. Ensure keyboard navigation works for users relying on screen readers. Display status messages for loading or errors, such as exceeding the 60 requests per minute rate limit, to maintain a smooth user experience.

  • Add ARIA labels to controls.
  • Support keyboard navigation.
  • Show loading states.
  • Handle rate limit errors gracefully.

Testing Your Integration

Sound wave illustration for: Testing Your Integration

Validating your TTS integration ensures reliable audio delivery for users with dyslexia or reading difficulties. Rigorous testing confirms that text-to-speech conversion works correctly under various conditions, from simple phrases to longer passages.

By combining unit, integration, and performance tests, you can catch issues early and maintain a smooth user experience. This section outlines how to verify your implementation’s reliability and efficiency.

Unit Testing Requests

Test individual API calls by mocking the POST https://api.11bets.cc/v1/audio/speech endpoint. Verify that your JSON payload correctly includes the model, voice, and input fields. Ensure that character counts align with the 4096-character limit per request.

Check that error responses are handled correctly, such as invalid voice IDs or missing authentication headers. This ensures your code gracefully manages edge cases without crashing the user interface.

  • Verify JSON structure matches the required schema.
  • Test character count limits (4096 chars max).
  • Confirm API key authentication in headers.

Integration Testing

Test the full workflow: sending text, receiving audio, and playing it in the browser. Use real API credentials in a staging environment to validate end-to-end functionality. Ensure audio formats like MP3 or WAV play correctly across different browsers.

Check that network errors or rate limits (60 requests/minute) are handled appropriately. Verify that the audio response is correctly converted to a Blob URL for playback.

  • Test end-to-end text-to-audio playback.
  • Validate audio format compatibility (MP3, WAV).
  • Simulate rate limit scenarios (60 req/min).

Performance Testing

Measure response times for various text lengths. Short phrases should return quickly, while longer texts may take seconds due to queuing. Monitor memory usage during audio playback to prevent leaks, especially when generating multiple audio segments.

Test concurrent requests to ensure the API handles load without significant delays. Use tools like Lighthouse or custom scripts to track performance metrics and identify bottlenecks in your integration.

  • Track response times for short vs. long texts.
  • Monitor memory usage during playback.
  • Test concurrent request handling.

image]:

Common Pitfalls

Sound wave illustration for: Common Pitfalls

Integrating TTS into accessibility workflows often fails due to simple configuration errors. These pitfalls are easy to overlook but disrupt the user experience for readers with dyslexia. Ensuring correct headers and valid inputs prevents unnecessary audio gaps.

Below are the three most common integration errors, based on standard API behavior and our specific constraints.

Incorrect Content-Type

Always send Content-Type: application/json in your POST request. If the server receives form data instead, it will reject the payload silently or return a 415 error, breaking the audio playback chain for your users.

Ensure your JSON body strictly follows the required schema. Extra fields may be ignored, but missing input or model will cause immediate failure.

  • Set header: Content-Type: application/json
  • Verify no trailing commas in JSON

Missing API Key

Every request must include Authorization: Bearer tts-.... Without this, the API returns a 401 Unauthorized error. Since we use a single active key per account, ensure you are rotating keys correctly if issued anew.

Store the key in environment variables, not in client-side code, to prevent exposure in your browser bundle.

  • Header: Authorization: Bearer tts-<your_key>
  • Check key validity in /get-api-key/

Character Limit Exceeded

Each request supports up to 4096 characters. Exceeding this limit causes a 400 Bad Request error. For longer texts, split your content into chunks before sending.

Remember that spaces and punctuation count toward the 4096-character limit. Plan your splitting logic to avoid cutting words mid-sentence, which harms clarity for dyslexic users.

  • Max: 4096 characters per request
  • Include spaces/punctuation in count

Next Steps

Sound wave illustration for: Next Steps

Integration is complete, but maintaining accessibility requires ongoing attention to usage metrics and user experience. Track your character consumption and error rates through the dashboard to ensure your budget aligns with your app’s growth.

Proactively manage scaling by splitting longer texts into 4096-character segments before sending requests. This prevents timeouts and ensures consistent audio quality as your user base expands, keeping the experience smooth for readers with dyslexia.

Monitoring Usage

Use the /v1/audio/speech endpoint statistics to monitor character counts and request success rates. Since failed requests are free, track failure reasons to optimize your text preprocessing logic without incurring unnecessary costs.

Set up alerts for rate limit proximity (60 requests/minute) to prevent queuing delays that might disrupt the user experience during peak reading sessions.

  • Check balance via /get-api-key/ dashboard
  • Monitor 60 RPM limit
  • Track failed vs. successful synthesis

Scaling Your App

Implement client-side text splitting to handle inputs exceeding 4096 characters, joining the resulting audio files seamlessly. This reduces server load and ensures long-form content is processed efficiently.

Pre-fetch audio for the next sentence while the user is reading the current one, minimizing latency and creating a continuous listening experience.

  • Split text < 4096 chars
  • Join audio files client-side
  • Pre-fetch next segments

Gathering User Feedback

Collect feedback on voice clarity and speed settings, as these directly impact comprehension for users with reading difficulties. Use this data to adjust default voice presets or speed ranges.

Since we do not offer custom voice cloning, focus feedback on the existing eight presets to determine which voices best support your specific content type.

  • Rate voice clarity
  • Adjust speed preferences
  • Suggest preset improvements

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. You can use any voice with any language, giving you flexibility in tone without restricting linguistic options.

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. IETF RFC 7845: Ogg Opus
  4. openai-python on GitHub
  5. TRON developer hub: TRC-20
  6. Node.js documentation
  7. FFmpeg documentation
  8. W3C WAI: making audio and video accessible
  9. Python documentation
  10. openai-node on GitHub
  11. LibriVox public-domain audiobooks
  12. LibriTTS-R paper (arXiv 2305.18802)

More on this site