How to Use the HTML5 SpeechSynthesis API for Browser Text‑to‑Speech

This guide shows how to create a simple web page that converts a given text string into spoken audio using the HTML5 SpeechSynthesis API, with a complete code example, execution steps, and browser compatibility notes.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
How to Use the HTML5 SpeechSynthesis API for Browser Text‑to‑Speech

Scenario

Goal: synthesize speech from a given text string directly in a web page using the HTML5 Speech Synthesis API.

Implementation

Create an HTML file containing a button that invokes a JavaScript function. The function defines the text, obtains window.speechSynthesis, creates a SpeechSynthesisUtterance with the text, and calls synth.speak(msg) to play the audio.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Speech Synthesis Demo</title>
</head>
<body>
  <h1>Speech Synthesis Demo</h1>
  <input id="btn1" type="button" value="Click Me" onclick="test();"/>
</body>
<script>
function test() {
  const text = `Speech Synthesis Demo`;
  const synth = window.speechSynthesis;
  let msg = new SpeechSynthesisUtterance(text);
  synth.speak(msg);
}
</script>
</html>

Open the file in a browser and click the button; the test function runs, creating a SpeechSynthesisUtterance and invoking synth.speak(msg), which produces audible speech.

Core speech‑synthesis statements:

const text = `Speech Synthesis Demo`;
const synth = window.speechSynthesis;
let msg = new SpeechSynthesisUtterance(text);
synth.speak(msg);

Browser Compatibility

Chrome is recommended because HTML5 support for the Speech Synthesis API varies across browsers.

Browser compatibility chart
Browser compatibility chart
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJavaScriptWeb APIHTML5text-to-speechSpeechSynthesis
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.