How to Implement Text to Speech JS Code for Dyslexia Apps?

By EasyRead editorial team · Updated 2026-11-19

This guide shows accessibility teams how to integrate our Text-to-Speech API into JavaScript applications for dyslexia support. You will learn to send text via POST requests to /v1/audio/speech and receive audio files using standard libraries like fetch. We cover authentication, voice selection, and playback logic specifically for educational platforms needing reliable narration at scale.

You will also see how to handle rate limits, error states, and accessibility features like speed adjustment. The instructions are concrete, avoiding hype, and include real code examples for Node.js and browsers. This page is designed for developers who need to implement compliant, high-quality audio synthesis without custom voice cloning or streaming dependencies.

How to Implement Text to Speech JS Code for Dyslexia Apps?

Frequently asked questions

What is the best way to handle long texts in JS?

Split input text into chunks of up to 4096 characters. Send each chunk as a separate POST request to the speech endpoint. Concatenate the returned audio files to create a single continuous stream. This ensures compliance with character limits while maintaining narrative flow for the end user.

Can I play audio directly from the API response?

Yes. The API returns the audio file directly in the response body. You can assign this binary data to an HTML5 audio element or a Blob URL in JavaScript. No intermediate storage is required, allowing immediate playback of the synthesized speech in your dyslexia support application.

How do I handle rate limits in a Node.js app?

The API allows 60 requests per minute per key. Implement a queue system in Node.js to process synthesis requests sequentially or with controlled concurrency. Monitor your usage via the /get-api-key/ dashboard to ensure you stay within the 60 RPM limit, especially during peak usage hours.

Does the API support WebSockets for real-time audio?

No. The API uses standard HTTP POST requests to return complete audio files. There is no WebSocket support for real-time partial audio streaming. You must wait for the full synthesis of each text chunk to complete before receiving the audio data for playback.

What is the difference between tts-1 and tts-1-hd?

Both models use the same engine and price. The only difference is the model identifier string you send in the request body. Selecting either 'tts-1' or 'tts-1-hd' results in identical audio quality and costs the same amount per character processed by the API.

How do I set the language explicitly in JS?

Include the 'language' field in your JSON request body with the ISO code. This is crucial for non-English Latin-script text, as the API guesses English by default. Explicitly setting the language ensures accurate pronunciation for the specific language you are targeting in your application.

Can I use the API with React or Vue?

Yes. Use the OpenAI SDK (by changing the base URL) or plain HTTP requests. Change the base URL to https://api.x999bet.cc/v1. Pass your API key in the Authorization header. This works seamlessly with any JavaScript framework, including React and Vue, for integrating text-to-speech capabilities.

How do I detect voice errors in JavaScript?

Check the HTTP status code of the response. If synthesis fails, the request is free and the charge is returned. Handle errors by inspecting the response body for error details. Failed requests do not consume your character balance, ensuring accurate billing tracking in your application.

Is there a way to preview audio before saving?

Yes. Receive the audio file in the response and create a Blob URL. Assign this URL to an audio element to play the preview immediately. Since the audio is returned directly, you can test the voice, speed, and format before deciding to save or discard it.

How do I calculate character count accurately?

Count all characters in the input text, including spaces and punctuation. The price is $0.01 per 1,000 characters. Ensure your JS logic accurately counts every character in the string before sending it to the API to predict costs and manage your account balance effectively.

Can I use the API in a serverless environment?

Yes. The API is a standard HTTP REST endpoint. You can call it from any serverless function that supports HTTP requests. Ensure you handle the 60 requests per minute limit appropriately within your serverless architecture to avoid throttling during concurrent invocations of your dyslexia app.

How do I manage API keys in a JS app?

Store your single active API key securely. You can issue a new key at any time via the dashboard, which invalidates the old one immediately. In JS, pass the key in the Authorization header. Rotate keys regularly to maintain security for your application's users.

What is the default speed of the API?

The default speed is 1.0. You can adjust the speed between 0.25 and 4.0 by including the 'speed' field in your request. This allows you to customize the narration pace for users with dyslexia, ensuring the audio is comfortable and easy to follow.

Can I change the voice mid-stream?

No. Each request generates audio for a single voice preset. To change voices, you must send a new request with the desired voice parameter. Concatenate the resulting audio files in your JS app to create a seamless experience with different voices for different text segments.

Understanding the API Endpoint

Sound wave illustration for: Understanding the API Endpoint

EasyRead exposes a single cloud endpoint for text-to-speech synthesis. You send text to the API and receive an audio file in return, enabling seamless integration into dyslexia-friendly reading applications.

POST Request to /v1/audio/speech

Send a POST request to https://api.x999bet.cc/v1/audio/speech with your text payload. The API processes the input and returns the synthesized audio file directly in the response body.

JSON Body Structure

The request body must be JSON containing the model ("tts-1" or "tts-1-hd"), input text, voice preset, response_format, and optional speed or language parameters. Text is limited to 4096 characters per request.

  • model: "tts-1" or "tts-1-hd"
  • input: string up to 4096 characters
  • voice: one of 8 presets (e.g., aria, nova)
  • response_format: mp3, wav, opus, flac, or pcm

Authentication Header Requirement

Include your API key in the Authorization header as Bearer tts-.... Each account holds one active key, which can be refreshed at any time via the dashboard.

Setting Up the JavaScript Environment

Sound wave illustration for: Setting Up the JavaScript Environment

To generate audio directly in the browser, use the native fetch API. For server-side processing or complex queue management, install Node.js to run JavaScript outside the browser environment. Both environments support the standard HTTP requests required by our API.

Installing Node.js or Using Browser Fetch

Browser-based implementations rely on fetch, requiring no external dependencies. Node.js users should ensure their runtime supports modern async/await patterns for cleaner asynchronous code handling.

Configuring the Base URL

Point your API client to https://api.x999bet.cc/v1. This base URL ensures all requests hit the correct endpoint for speech synthesis, replacing the default OpenAI base URL if you are adapting existing code.

Preparing the API Key

Retrieve your key from the /get-api-key/ dashboard. Store it securely in environment variables or local storage, then attach it to every request using the Authorization: Bearer <key> header.

Writing the Synthesis Request

Sound wave illustration for: Writing the Synthesis Request

The synthesis request begins by defining the input text variable, ensuring the content stays within the 4096-character limit per request. Spaces and punctuation count toward this total, so text must be split if longer. This constraint applies to every API call, requiring careful character counting before submission to avoid errors during synthesis.

Selecting the appropriate voice involves choosing from eight presets that support 23 languages. For dyslexia apps, clear narrators like Aria or Sage provide distinct articulation. The language field should be explicitly set for non-English text to ensure accurate pronunciation, as the API guesses language by script otherwise.

Defining the Input Text Variable

The input field accepts plain text up to 4096 characters. Each character, including spaces, contributes to the character count for billing and limits. If your content exceeds this, split the text into chunks and join the resulting audio files afterward to maintain narrative continuity for the user.

Ensure the text variable is sanitized to handle special characters correctly. The API processes text sequentially, so long inputs may queue behind other requests, affecting generation time. For optimal performance, keep individual requests concise to minimize latency in your application's user interface.

  • Maximum 4096 characters per request
  • Spaces and punctuation count as characters
  • Split longer texts into manageable chunks

Selecting the Appropriate Voice

Choose from eight voices such as Aria (warm narrator) or Sage (calm instructor). Each voice supports all 23 languages, allowing consistent tone across diverse content. For accessibility, prioritize voices with clear enunciation to aid reading comprehension for dyslexic users.

Set the voice parameter to one of the preset identifiers. If the language field is omitted, the system guesses based on the script, which may fail for Latin-script texts in other languages. Explicitly setting the language code ensures accurate delivery and reduces comprehension errors.

  • Aria: warm, clear narrator
  • Sage: calm, instructional tone
  • Supports all 23 listed languages

Setting Response Format to MP3

Set response_format to 'mp3' for broad browser compatibility and smaller file sizes. MP3 is ideal for web playback, though WAV, OPUS, FLAC, and PCM are also supported. Choose MP3 to balance audio quality with efficient data transfer for users with limited bandwidth.

The API returns binary audio data in the response body. Ensure your JavaScript code handles this binary stream correctly, converting it into a playable audio object. MP3 files are widely supported by HTML5 audio players, simplifying integration into existing web applications.

  • MP3 offers best browser compatibility
  • Smaller file size reduces load time
  • Other formats: WAV, OPUS, FLAC, PCM

Handling Audio Playback

Sound wave illustration for: Handling Audio Playback

Once the API returns binary audio data, convert it into a Blob object and create a temporary object URL. This allows the browser to handle the audio playback natively without requiring external libraries.

Play the audio directly in the web browser using the standard HTML5 audio element. The generated MP3 file plays after synthesis completes, providing feedback for users reading text.

Converting Binary Response to Audio Object

Fetch the response as a blob. Assign the blob to a variable and generate a URL using URL.createObjectURL(). This creates a reference to the audio data in memory.

  • Use response.blob() to capture the binary stream.
  • Assign the result to a Blob object with MIME type audio/mpeg.

Playing Audio in Web Browsers

Create an <audio> element and set its src attribute to the object URL. Call the play() method to start narration. This ensures compatibility with all modern browsers used by accessibility teams.

  • Instantiate a new HTMLAudioElement.
  • Set the source to the generated blob URL.
  • Invoke the play method for immediate audio output.

Storing Audio Temporarily if Needed

If the audio needs to be reused, store the blob in the browser's session storage or local storage, noting that this consumes client-side storage space. This avoids re-fetching the same text and saves API characters for future use.

Managing Rate Limits in JS

Sound wave illustration for: Managing Rate Limits in JS

To handle high-volume narration for dyslexia apps, your JavaScript client must respect the 60 requests-per-minute limit per key. Before the first top-up, this drops to 10 RPM, so monitor usage closely to avoid throttling during initial integration.

Understanding the 60 RPM Limit

The API enforces a strict 60 requests per minute limit per key. If your app sends bulk text for accessibility, exceeding this limit will result in temporary rejection until the window resets.

Implementing Retry Logic

Implement exponential backoff in your fetch logic. When a 429 Too Many Requests error occurs, wait briefly before retrying. This prevents overwhelming the server during peak usage times.

Queueing Requests for Large Texts

Split texts exceeding 4096 characters into chunks. Queue these chunks sequentially in your JS application to ensure they stay within the rate limit. Process them one by one to maintain steady generation without hitting caps.

Error Handling Best Practices

Sound wave illustration for: Error Handling Best Practices

Robust error handling ensures your accessibility application remains stable when the TTS API encounters issues. By validating responses early, you prevent silent failures that could leave users without audio narration for critical content.

Proper logging also aids troubleshooting, allowing teams to identify recurring issues before contacting support by email.

### Checking for HTTP Status Codes

Always inspect the HTTP status code from the POST /v1/audio/speech response. A 200 indicates success, while 4xx errors (like 401 for invalid keys or 429 for rate limits) require immediate attention. Treat 5xx errors as temporary server issues and retry with backoff.

### Handling Character Limit Exceeded Errors

The API enforces a strict 4096-character limit per request. If your input text exceeds this, split the text into chunks and synthesize them sequentially. Handle the error gracefully by concatenating the resulting audio files rather than failing the entire reading session.

### Logging API Response Data

Log the request ID, timestamp, character count, and status code for every call. This metadata is essential for auditing usage and diagnosing why a specific text segment failed. Ensure logs do not store the actual input text if privacy is a concern, as input is not retained.

[]

### Checking for HTTP Status Codes

Always inspect the HTTP status code from the POST /v1/audio/speech response. A 200 indicates success, while 4xx errors (like 401 for invalid keys or 429 for rate limits) require immediate attention. Treat 5xx errors as temporary server issues and retry with backoff.

### Handling Character Limit Exceeded Errors

The API enforces a strict 4096-character limit per request. If your input text exceeds this, split the text into chunks and synthesize them sequentially. Handle the error gracefully by concatenating the resulting audio files rather than failing the entire reading session.

### Logging API Response Data

Log the request ID, timestamp, character count, and status code for every call. This metadata is essential for auditing usage and diagnosing why a specific text segment failed. Ensure logs do not store the actual input text if privacy is a concern, as input is not retained.

[]

Optimizing for Accessibility

Sound wave illustration for: Optimizing for Accessibility

Text-to-speech integration enhances accessibility by allowing users to control playback speed. The API supports a speed range from 0.25 to 4.0, enabling dyslexic readers to slow down narration for better comprehension or accelerate it for efficiency. This flexibility is critical for maintaining focus during long reading sessions.

Voice selection significantly impacts readability. Clear, consistent narrators reduce cognitive load compared to dynamic or expressive voices that may vary in tone. Using preset voices with neutral, steady delivery helps users track text more easily without distraction from unexpected vocal nuances.

Adjusting Speed for Readability

Users can dynamically adjust the speed parameter (0.25–4.0) in their JS requests. Slower speeds aid decoding, while faster speeds support review. Implement UI sliders that update the speed value in subsequent API calls, allowing real-time adaptation to user preference.

Note that shorter phrases may take a few seconds to generate regardless of speed, while longer texts process at roughly real-time speed (25 characters per second). Queueing logic should account for this processing time to prevent UI freezes.

  • Set speed between 0.25 and 4.0 based on user needs.
  • Adjust speed dynamically via UI controls.
  • Account for generation time in queueing logic.

Choosing Clear Narrator Voices

Select voices known for clarity, such as Aria (warm, clear narrator) or Sage (calm, instructional). These presets offer consistent tone without excessive emotional variation, reducing cognitive strain for users with dyslexia. Avoid voices with heavy accent or dramatic inflection unless specifically requested.

Ensure the voice parameter matches the language. If the language is not set, the API guesses based on script, which may default to English for Latin text. Explicitly setting the language parameter prevents mispronunciation in mixed-language content.

  • Use Aria or Sage for consistent, clear narration.
  • Explicitly set the language parameter.
  • Avoid voices with heavy accent or dramatic inflection.

Ensuring Audio Quality for Dyslexic Users

Generate audio in MP3 or WAV format for broad browser compatibility. MP3 is smaller and loads faster, while WAV offers lossless quality. Both formats are widely supported in modern web browsers, ensuring smooth playback without codec issues.

The generated audio includes an inaudible watermark, marking it as synthetic. This does not affect audio quality or readability. Ensure your JS code handles binary responses correctly to avoid playback issues.

  • Use MP3 or WAV for broad compatibility.
  • Ensure binary response handling prevents corruption.
  • Audio quality is consistent across all voices.
Optimizing for Accessibility

Testing Your Implementation

Sound wave illustration for: Testing Your Implementation

Validating your TTS integration ensures that dyslexic users receive clear, accurate audio narration before scaling to production. Testing with the included trial credit allows teams to verify voice quality and playback behavior without immediate financial commitment.

Accurate character counting is critical because billing depends on exact input length, including spaces and punctuation. Verifying these metrics prevents unexpected costs and ensures the 4096-character limit is respected during synthesis.

Using the Free Trial Credit

Sign up via Google to receive $0.50 in trial credit, valid for 7 days. This provides approximately 50,000 characters of synthesis, allowing you to test multiple voices and formats without entering payment details. Note that email/password accounts do not receive this trial credit.

Use this balance to generate sample audio for various text lengths. Confirm that the API responds correctly to requests and that audio files are generated as expected before integrating into your main application logic.

  • Google sign-up grants $0.50 (50,000 characters)
  • Valid for 7 days
  • Email/password accounts start with zero credit

Verifying Audio Output

Play the generated MP3 or WAV files in your web browser to assess clarity. For dyslexia support, verify that voices like Aria or Sage provide a calm, clear narration style. Ensure the audio speed (0.25–4.0) is adjustable to suit individual reading preferences.

Check that the inaudible watermark is present in synthetic files if required for compliance. Confirm that the audio player handles the binary response correctly without buffering issues.

  • Test voices like Aria for clear narration
  • Adjust speed between 0.25 and 4.0
  • Verify binary response handling

Checking Character Count Accuracy

Ensure your JavaScript code counts every character, including spaces and punctuation, accurately. The API charges $0.01 per 1,000 characters, so precise counting is essential for cost control. Text exceeding 4,096 characters must be split manually before sending.

Log the character count in your request metadata to verify billing accuracy. Compare the input text length against the API’s usage statistics to ensure no silent truncation or counting errors occur.

  • Count spaces and punctuation
  • Split text at 4,096 characters
  • Log counts for billing verification

Scaling for Large Teams

Sound wave illustration for: Scaling for Large Teams

Organizations serving large teams with dyslexia support often distribute API keys across development, staging, and production environments. This separation ensures that testing loads do not impact production audio generation for end-users. Each key operates independently with its own 60 requests per minute limit, allowing teams to scale throughput by increasing key counts rather than waiting for a single key’s quota to reset.

Managing Multiple API Keys

Teams can issue new keys at any time, instantly invalidating the old one. This feature is useful for rotating credentials or isolating specific application modules. Since accounts are per site, ensure each team member or service uses a unique key to accurately track usage attribution and avoid rate limit collisions.

  • Generate keys via the /get-api-key/ dashboard.
  • Revoke old keys instantly when issuing new ones.
  • Issue separate keys for dev, staging, and prod.

Monitoring Usage and Balance

The dashboard displays real-time balance, trial status, and characters consumed. Since pricing is $0.01 per 1,000 characters, teams can predict costs precisely based on text volume. Failed requests are free, so monitoring error rates helps optimize input quality without inflating bills.

  • View character count and balance in the dashboard.
  • Track failed requests to identify input issues.
  • Calculate costs: $10 per 1 million characters.

Automating Top-Ups with USDT

Top-ups use USDT on the TRON network (TRC-20) with a minimum of $5. Credits are added automatically within minutes of transfer. There are no monthly plans or subscriptions, so teams only pay for what they use. Balance does not expire, allowing for flexible budgeting across fiscal quarters.

  • Send USDT (TRC-20) for instant credit.
  • Minimum top-up is $5.
  • No expiration on stored balance.

Common JS Integration Pitfalls

Sound wave illustration for: Common JS Integration Pitfalls

Even experienced developers sometimes overlook the Content-Type: application/json header, causing the API to reject valid payloads with a 415 error. Ensuring this header is set prevents unnecessary debugging delays during initial integration.

Another frequent issue is treating the audio response as text. The API returns binary audio data, not a JSON object, so failing to parse it correctly results in corrupted files or empty players.

Forgetting to Set Content-Type

Missing the content-type header is a common oversight. Without it, the server cannot parse the JSON body, leading to immediate rejection of the synthesis request.

  • Always include Content-Type: application/json in your fetch headers.
  • Verify headers in browser dev tools or Postman before production deployment.

Misinterpreting Binary Responses

The endpoint returns raw audio bytes, not a JSON structure. Developers often try to read the response as text, resulting in garbled output or errors when converting to an audio object.

Ensure your JavaScript code handles the response as a Blob or ArrayBuffer to correctly generate the audio URL for playback.

  • Use response.blob() or response.arrayBuffer() in fetch calls.
  • Convert the blob to a URL.createObjectURL() for <audio> tag sources.

Ignoring Rate Limit Headers

The API enforces a 60 requests per minute limit. Ignoring rate limits can lead to unexpected 429 errors when processing large texts.

Implement logic to check these headers and pause requests if the limit is approaching, ensuring smooth playback without interruption.

  • Read X-RateLimit-Remaining and X-RateLimit-Reset headers.
  • Queue subsequent requests if the remaining count drops to zero.

Future Enhancements for JS Apps

Sound wave illustration for: Future Enhancements for JS Apps

As your dyslexia application matures, users often require granular control over audio playback to match their individual reading pace. Integrating dynamic speed adjustments allows teams to tailor the experience without rebuilding the core synthesis pipeline.

Supporting multiple languages ensures inclusivity for diverse student bodies. Since the API supports 23 languages with any voice, you can easily extend your app’s reach by adding locale selectors that map user preferences to the correct language parameter.

Adding Speed Controls to UI

Implementing a slider that adjusts the speed parameter (0.25–4.0) in real-time enhances usability for users with varying processing speeds. This simple addition significantly improves comprehension without requiring complex audio re-processing.

You can store the user’s preferred speed in local storage, ensuring consistency across sessions. This reduces friction for repeated reading sessions.

  • Use a range input linked to the speed field
  • Cache preferences in localStorage
  • Adjust playback rate dynamically

Supporting Multiple Languages

Leverage the optional language ISO code field to ensure accurate pronunciation, especially for Latin-script texts that might otherwise default to English. This is critical for multilingual educational platforms.

The API allows any voice to speak any supported language, giving you flexibility in voice selection regardless of the language setting.

  • Map UI language selectors to ISO codes
  • Use explicit language fields for clarity
  • Support 23 languages natively

Integrating with Existing CMS Platforms

Connect the TTS API to your CMS by creating a script or plugin that triggers synthesis when new content is published. This automates the creation of audio versions for articles and lessons.

Store the resulting audio files or URLs in your CMS media library, making them easily embeddable in your frontend applications.

  • Trigger synthesis on content publish
  • Automate audio file storage
  • Embed audio via CMS media library

Support and Resources

Sound wave illustration for: Support and Resources

For detailed technical guidance, consult the comprehensive API documentation available at /docs/. This resource covers all endpoint specifications, parameter definitions, and code examples necessary for seamless integration into your accessibility workflows.

Documentation Link

The documentation provides clear examples for both Node.js and browser-based implementations, ensuring you can quickly validate your setup and resolve common integration questions without unnecessary delay.

Contact Support via Email

Our support team is available exclusively via email for any billing, technical, or account-related inquiries. Please note that we do not offer phone support or live chat, so allow standard business hours for response times.

Community Forums

While we do not host official community forums, developers often share integration tips and code snippets in general accessibility developer communities. You can also check the /about/ page for more information on our team and background.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. This control is crucial for educational platforms where precise pronunciation directly impacts comprehension for users with dyslexia.

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. ISO 639 language codes
  3. Creative Commons Attribution 4.0
  4. OpenAI API reference: create speech
  5. openai-node on GitHub
  6. LibriVox public-domain audiobooks
  7. Tether (USDT)
  8. Node.js documentation
  9. curl documentation
  10. TRON developer hub: TRC-20
  11. LibriTTS-R corpus (OpenSLR 141)
  12. MDN: Web Speech API

More on this site