DEV Community

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

Posted on • Edited on

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

Top comments (3)

Collapse
 
albirrkarim profile image
AlbirrKarim • Edited

Nice article, btw i also made similar research about text to speech with javascript like that. I made some amazing library. i combine the browser speech synthesis API and TTS API for doing text-to-speech task. and my library can highlight the text that is being spoken from both source browser speech synthesis or audio files.

Collapse
 
hussein_e8e073607fb08a087 profile image
Hussein

" ‏ستواجه صنفاً لا يفكر إلا بنفسه ، وآخر يخذلك في منتصف الطريق ، وآخر ينكر معروفاً لك وكأنه لم يعرفك يوماً . " 🖤