DEV Community

Cover image for Convert Text to Speech in Javascript using Speech Synthesis API
Rahul Sharma
Rahul Sharma

Posted on

Convert Text to Speech in Javascript using Speech Synthesis API

Welcome to this quick tutorial on using the browser Speech Synthesis API for Text to Speech! In this tutorial, I will show you how to convert text into speech using JavaScript and the browser Speech Synthesis API.

What is Speech Synthesis?

The Speech Synthesis API is a JavaScript API that allows you to integrate text-to-speech (TTS) capabilities into web applications. It provides control over the voice, pitch, rate, and volume of the synthesized speech, offering flexibility in how the spoken output sounds. This API is supported in modern browsers like Chrome, Firefox, and Edge. Be sure to check the documentation for the latest updates on compatibility.

Getting Started with the Speech Synthesis API

To get started with the Speech Synthesis API, create an HTML file and add the following code to it:

<!DOCTYPE html>
<html lang="en">
    <script src="script.js"></script>
      <h1>Text To Speech</h1>
      <button onclick="speak()">Speak</button>
Enter fullscreen mode Exit fullscreen mode

Then, create a JavaScript file (script.js) and add the following code to it:

function speak() {
  // Create a SpeechSynthesisUtterance
  const utterance = new SpeechSynthesisUtterance("Welcome to this tutorial!");

  // Select a voice
  const voices = speechSynthesis.getVoices();
  utterance.voice = voices[0]; // Choose a specific voice

  // Speak the text
Enter fullscreen mode Exit fullscreen mode

After that, open the HTML file in your browser and click the Speak button. You should hear the text being spoken out loud. If you do not hear anything, check the console for any errors.

Note: Voices can be different depending on the different browsers. You can check the list of voices available in your browser by logging the voices array to the console.

Demo: Link

Thanks for reading! I hope you enjoyed this article. Feel free to share your thoughts in the comments below.

Must Read If you haven't

More content at
Catch me on

Youtube Github LinkedIn Medium Stackblitz Hashnode HackerNoon

Top comments (0)