Skip to content

About

Add read-aloud to any site with Microsoft Edge neural TTS. Headless controller + web component + word highlighting.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

read-aloud

@baryodev/read-aloud

Add "listen to this article" to any site, using Microsoft Edge's neural voices.
A tiny Node engine plus a framework-free browser reader: controller, web component, and word highlighting.


Edge's read-aloud voices are free and good. The catch: a browser can't call the service directly (it needs headers browsers refuse to set), so you need a small server piece. This package ships both halves:

  • Server: an EdgeTTS engine, an AzureSpeechTTS engine (official Azure AI Speech, needs a key), and a drop-in endpoint handler. The Edge path needs no key but is best effort and currently failing, see Azure AI Speech.
  • Browser: a headless ReadAloud controller you build any UI on, plus an optional button and <read-aloud> web component.
  • Highlighting: per-word timings from the engine drive word highlighting in your article, formatting preserved.

Build your own UI, or use the one included. Both sit on the same controller.

Install

npm i @baryodev/read-aloud

1. Add the endpoint (server)

The Fetch-style handler works in Next.js App Router, Hono, Bun, Deno, and Cloudflare (Node runtime).

// app/api/read-aloud/route.ts
import { createReadAloudHandler } from "@baryodev/read-aloud/server";

export const POST = createReadAloudHandler();

Express / classic Node:

import express from "express";
import { createReadAloudExpressHandler } from "@baryodev/read-aloud/server";

const app = express();
app.post("/api/read-aloud", express.json(), createReadAloudExpressHandler());

Options, all optional:

createReadAloudHandler({
  defaultVoice: "en-US-JennyNeural",
  defaults: { rate: "+0%", pitch: "+0Hz", volume: "+0%" },
  maxChars: 8000,                // longer text is cut off at this length, not rejected
  stripHtml: true,               // incoming HTML is flattened to text
  wordBoundaries: true,          // send per-word timings for highlighting
  allowedVoices: ["en-US-JennyNeural", "en-GB-RyanNeural"], // also checked against the default voice
  maxBodyBytes: 262144,          // Fetch handler: bigger request bodies answer 413
  timeoutMs: 30000,              // give up on the speech service after this long
  onError: (err) => console.error(err), // the real error behind a 500
  authorize: (body, request) => request.headers.get("authorization") === `Bearer ${token}`, // Fetch handler, see below
});

authorize(body, request) receives the parsed JSON body ({ text, voice, rate, pitch, volume }) first, then the incoming request for headers, cookies or the IP. The body is already read, so do not call request.json() or clone() inside authorize. Return false to answer 401. Callbacks that take only body keep working.

The request is a Request in the Fetch handler and the Express req in the Express handler, so the header read differs:

// Fetch handler
createReadAloudHandler({
  authorize: (body, request) => isSignedIn(request.headers.get("authorization")),
});

// Express handler
createReadAloudExpressHandler({
  authorize: (body, req) => isSignedIn(req.headers.authorization),
});

What the endpoint answers:

Status Body When
200 { audio, contentType, boundaries } audio is base64 MP3. Sent with Cache-Control: no-store.
400 { error } Invalid JSON or a body that is not an object, no text left after stripping, a voice outside allowedVoices, or an invalid voice, rate, pitch or volume.
401 { error: "unauthorized" } authorize returned false.
413 { error } The Fetch handler's request body is over maxBodyBytes.
500 { error: "read-aloud: synthesis failed" } The speech service failed, timed out, or authorize threw. The message is fixed; use onError to see the cause.

2. Read the page (browser)

The one-liner: drop a button next to your article.

import { mountButton } from "@baryodev/read-aloud";

mountButton("#listen", {
  source: "#article",   // read this element's text
  highlight: true,      // light each word as it's spoken
});

Or the web component, with no build step and no framework:

<script type="module">
  import { defineReadAloudElement } from "@baryodev/read-aloud";
  defineReadAloudElement();
</script>

<article id="article"> … </article>
<read-aloud for="#article" voice="en-GB-RyanNeural" highlight></read-aloud>

Attributes on <read-aloud>:

Attribute Same as
for (or source) source selector
endpoint endpoint
voice, rate, pitch, volume the same options
playback-rate playbackRate
label button text, default "Listen"
highlight highlight: true
icon-only showText: false

The element's controller property gives you the underlying ReadAloud. Pass a name to defineReadAloudElement("my-reader") to register a different tag. The web component always injects the default styles; use mountButton with injectStyle: false if you need to turn that off.

3. Or build your own UI (headless)

mountButton and <read-aloud> are thin wrappers. The real API is the ReadAloud controller. Wire it to whatever buttons, progress bar, or highlight style you want.

import { createReadAloud } from "@baryodev/read-aloud";

const reader = createReadAloud({
  source: "#article",
  voice: "en-US-JennyNeural",
  rate: "+0%",
  highlight: true,
  onState: (state) => { myButton.dataset.state = state; }, // idle|loading|ready|playing|paused|ended|error
  onWord: (i, word) => { /* your own highlighting */ },
  onProgress: ({ ratio }) => { myScrubber.value = ratio; },
  onError: (err) => toast(err.message),
});

myPlayButton.onclick = () => reader.toggle();
myStopButton.onclick = () => reader.stop();
myScrubber.oninput = () => reader.seek({ ratio: myScrubber.valueAsNumber });

Controller surface:

Member What it does
play() / pause() / toggle() Synthesize if needed, then play/pause.
stop() Pause and rewind to the start.
seek(seconds | { ratio }) Jump to a time or a 0 to 1 position.
preload() Fetch the audio ahead of time (e.g. on hover).
update({ voice, rate, … }) Change voice/prosody; invalidates cached audio.
destroy() Free the audio URL and unwrap highlighting.
state, duration, currentTime, boundaries Read-only getters.
audioElement, objectUrl The <audio> element and its blob URL, null before the first load.
onState, onWord, onProgress, onReady, onEnd, onError Events.

Download the recording

import { createReadAloud, downloadRecording } from "@baryodev/read-aloud";

await reader.preload();
downloadRecording(reader, "chapter-1.mp3"); // false if nothing is loaded yet

Customization

Everything is a plain option.

createReadAloud({
  endpoint: "/api/read-aloud",     // your route
  source: () => document.querySelector(".post-body"), // string | element | fn
  text: "Or just pass raw text.",  // skip the DOM entirely
  voice: "en-GB-SoniaNeural",
  rate: "+10%", pitch: "-2st", volume: "+0%",
  playbackRate: 1.25,              // native speed, no re-synthesis
  cache: true,                     // reuse audio across replays
  headers: { Authorization: `Bearer ${token}` },
  credentials: "include",
  highlight: {
    activeClass: "is-reading",     // your CSS instead of the default amber
    wordClass: "ra-word",
    scroll: true, scrollBlock: "center",
    skipSelectors: ["code", "pre", "script", "style", "figure"], // don't highlight these
    injectStyle: false,            // opt out of the built-in highlight CSS
  },
  fetchAudio: async (payload) => myProvider(payload), // swap the transport / TTS provider entirely
});

About skipSelectors:

  • It replaces the default list (code, pre, script, style, [data-read-aloud-skip]), so repeat the ones you still want.
  • It only stops highlighting. The text inside is still read aloud, because the reader reads the element's innerText, and highlighting drifts by the number of skipped words. To leave something out of both, pass text with that part removed.

Style the shipped button with plain CSS (or pass injectStyle: false and start from scratch):

.read-aloud-btn { background: #16a34a; }
.read-aloud-btn[data-state="playing"] { background: #dc2626; }
.read-aloud-word--active { background: #bfdbfe; }

Word highlighting on its own

Have your own audio pipeline but want the highlighting? Use Highlighter directly.

import { Highlighter } from "@baryodev/read-aloud";

const hl = new Highlighter(document.querySelector("#article"), { scroll: true });
hl.prepare();
// as your audio plays:
hl.highlight(wordIndex);
// cleanup:
hl.destroy();

Azure AI Speech (supported backend)

The default engine uses the public endpoint Microsoft Edge uses. That endpoint is unofficial, it has answered 403 since about October 12 2026, and it can change again. Treat it as best effort. For anything that has to work, use Azure AI Speech, which is a documented API with a key.

Create a Speech resource in the Azure portal, then give the handler its key and region:

import { createReadAloudHandler } from "@baryodev/read-aloud/server";

export const POST = createReadAloudHandler({
  azure: { key: process.env.MY_SPEECH_KEY, region: "eastus" },
});

Or set AZURE_SPEECH_KEY and AZURE_SPEECH_REGION and pass backend: "azure". The environment is only read when the Azure backend is selected, so setting it does not change a handler that has no azure or backend option. Without either option the handler uses Edge, as before.

AzureSpeechTTS has the same synthesize method as EdgeTTS, so it works with the direct-engine example below. Notes:

  • The key is sent only as the Ocp-Apim-Subscription-Key header. It is never logged and never put in an error. Errors carry the HTTP status, for example "read-aloud: azure speech answered 401". Redirects are not followed.
  • Every call has a timeout (timeoutMs, default 30000) and a cap on the audio read (azure.maxAudioBytes, default 16 MiB).
  • The REST API returns no word timings, so boundaries is empty and word highlighting does nothing with this backend.
  • Voice, rate, pitch and volume are checked the same way as for Edge, and text is XML-escaped.
  • azure.endpoint replaces the full URL, for sovereign clouds or a proxy. It must be https (http only for localhost) with no credentials or fragment, and region is ignored when it is set. backend must be "edge" or "azure", and "edge" cannot be combined with azure; anything else throws at setup. maxAudioBytes must be a positive integer. Billing and quotas are Azure's.

Using the engine directly

The handler is a thin layer over EdgeTTS. Use it on its own to pre-render audio, write files, or put it behind your own route.

import { writeFile } from "node:fs/promises";
import { EdgeTTS } from "@baryodev/read-aloud/server";

const { audio, boundaries, contentType } = await new EdgeTTS().synthesize("Hello there.", {
  voice: "en-GB-RyanNeural",
  rate: "+0%",
  wordBoundaries: true,
  signal: AbortSignal.timeout(30_000),
});
await writeFile("hello.mp3", audio);

boundaries is { text, offset, duration }[] in milliseconds. The engine gives up after timeoutMs (default 30000, 0 turns it off). Pass a signal to cancel sooner; a signal that is already aborted rejects at once. The handlers pass the request's signal for you.

Content Security Policy

If your site sends a CSP header, the reader needs:

Directive Value Why
media-src 'self' blob: Audio plays from a blob: URL made from the fetched bytes. Without it the browser blocks playback and the controller goes to error with "audio failed to load".
connect-src your endpoint's origin Only if the endpoint is on another origin. Same-origin is covered by 'self'.
style-src 'unsafe-inline' Only if you keep the built-in styles, which are added as a <style> element. Otherwise pass injectStyle: false to mountButton and to highlight, and ship the CSS yourself.

The Edge service is called from your server, so it never appears in the browser's CSP.

Voices

Any Microsoft neural voice name works, e.g. en-US-JennyNeural, en-US-GuyNeural, en-GB-RyanNeural, en-GB-SoniaNeural, en-AU-NatashaNeural, fil-PH-BlessicaNeural. Restrict what callers may pick with allowedVoices on the handler.

Troubleshooting

  • "audio failed to load" in the browser. Usually the CSP media-src above. Check the console for a CSP violation.
  • "read-aloud: connection closed before any audio". The service accepted the connection and closed it without sending audio, most often for an unknown voice name or a voice that does not support the language of the text.
  • The request hangs. The service sometimes accepts the connection and then sends nothing, for example when it rejects the time-based token because the server clock is off. The engine times out after timeoutMs (default 30 seconds) with "read-aloud: timed out". Keep the server clock synced.
  • The service drops the socket after the audio. Seen on some networks: it sends all the audio and the end-of-turn message, then disconnects. The engine has the audio by then and returns it, so this is not an error. A drop before the end-of-turn message rejects with "connection closed before the end of the audio".
  • Edge answers 403. Known and ongoing since about October 12 2026. The Edge path is best effort and currently failing; switch to the Azure backend above. This is the public endpoint Edge uses, not a contracted API, and Microsoft can change it. Check rany2/edge-tts for a protocol change and open an issue here.

Notes

  • SSR-safe. Importing does nothing until you call into it. The controller only touches the DOM in the browser.
  • No API key, no account on the Edge path. It rides the same public endpoint Edge uses, which is currently failing (see Azure above). Be a good citizen: cache, cap length (maxChars), and gate it if it's public.
  • Response shape. The endpoint returns { audio: base64, contentType, boundaries }. Point fetchAudio elsewhere to use a different backend.

License

MIT © BaryoDev

About

Add read-aloud to any site with Microsoft Edge neural TTS. Headless controller + web component + word highlighting.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages