Search code examples
javascriptjqueryhtmlaccessibilitytext-to-speech

How do I implement text-to-speech in html or javascript for web browsers?


I want a webpage to read some text out loud (in a robot voice!).

On this webpage, there's a button that, when clicked, randomly displays one of 3 sentences. I'd like to have another button that can be clicked that will read the text aloud. Alternatively, the text can be read aloud automatically when the first button is clicked.

here's the relevant code...

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <script type="text/javascript">
    var randomStrings = [
     "this is an example of a random string",
     "here's another random string",
     "or maybe this string will be chosen at random"
      ];
    function RndMsg() {
      var msg = randomStrings[Math.floor(Math.random()*randomStrings.length)];
      document.getElementById('randomDiv').innerHTML = msg;
      }
  </script>
</head>

<body>
  <form action="" method="post" onsubmit="return false">
    <input type="button" value="Randomize!" name="sessionid" onclick="RndMsg()"/>
//click the button->text appears below... i want browser or OS to read it aloud
  </form>
  <form action="" method="post" onsubmit="return false">
    <div id="randomDiv"> </div>
  </form>
</body>
</html>

I am a newbie, so I'm wondering if there's a simple way to do this. thanks!


Solution

  • I have used speak.js for some personal projects before.

    From the GitHub page:

    A port of the eSpeak speech synthesizer from C++ to JavaScript using Emscripten.

    Enables text-to-speech on the web using only JavaScript and HTML5.

    Online demo: http://syntensity.com/static/espeak.html