DEV Community

Cover image for Text-2-Speech API - Tutorial
Young Mamba
Young Mamba

Posted on

Text-2-Speech API - Tutorial

This is going to be a quick tutorial( If you find Videos better, here's the link). Open up your code editor and create an HTML file. Inside just define the basic HTML skeleton, and add an h1 and a p tag, like so:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Exercitationem
      facere impedit eum perferendis ullam inventore quas vero cum similique.
      Voluptatum cupiditate eligendi beatae quos inventore omnis dolor, ullam
      recusandae maiores, cumque aspernatur. In fuga dignissimos officiis totam
      inventore vero natus possimus enim laudantium ullam numquam, laboriosam
      magnam nisi illum. Reiciendis.
    </p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Then go to ResponsiveVoice.org. This is where we will get the Text2Speech API. It's also completely free and you don't need to add any credit card information :)

Go To Sign In.

ResponsiveVoice SignIn

App Dashboard.
ResponsiveVoice AppDashboard

Create an account.
ResponsiveVoice CreateAnAccount

And copy the script tag you see on the screen.
ResponsiveVoiceKey

Enter that script tag before </body>.

Then create a separate script tag. And add responsiveVoice.speak("hello world");.

Your HTML file should look like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Exercitationem
      facere impedit eum perferendis ullam inventore quas vero cum similique.
      Voluptatum cupiditate eligendi beatae quos inventore omnis dolor, ullam
      recusandae maiores, cumque aspernatur. In fuga dignissimos officiis totam
      inventore vero natus possimus enim laudantium ullam numquam, laboriosam
      magnam nisi illum. Reiciendis.
    </p>

    <script src="https://code.responsivevoice.org/responsivevoice.js?key=YOUR_UNIQUE_KEY"></script>
    <script>
      responsiveVoice.speak("hello world");
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now open up the browser and you should hear "Hello World"

We can make this more dynamic. Instead of saying "hello world" we can say something inside of our h1 tag. To do that, write responsiveVoice.speak(document.getElementsByTagName("h1")[0].innerHTML)

You also might have noticed that by the second time you refreshed the page a different voice spoke. You can also choose which voice will speak. Here's a list of all the voices.

Once you've chosen a voice, you can add it in the responsiveVoice.speak function after the text, responsiveVoice.speak(document.getElementsByTagName("h1")[0].innerHTML, "Spanish Male")

Feel free to experiment with this!

Top comments (0)