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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
