Building Text to Speech App in Javascript using Speech Synthesis API

devsmitra

Rahul Sharma

Posted on November 7, 2023

Building Text to Speech App 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">
  <head>
    <script src="script.js"></script>
  </head>
  <body>
    <main>
      <h1>Text To Speech</h1>
      <button onclick="speak()">Speak</button>
    </main>
  </body>
</html>
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
  speechSynthesis.speak(utterance);
}
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 Dev.to.
Catch me on

Youtube Github LinkedIn Medium Stackblitz Hashnode HackerNoon

💖 💪 🙅 🚩
devsmitra
Rahul Sharma

Posted on November 7, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related