Text to Speech in JavaScript

Today I’ll explain how to use Web Speech API(SpeechRecognition) in javascript to convert text to speech.

Web speech Api allows you to add voice in your web applications. It is pretty simple to use.

Here is a simple example showing how you can use the Web Speech API to convert text into speech using JavaScript.

 
<input type="text" id="txtWrite" placeholder="Type something that you want to hear">
<button onclick="convert_text_to_speech()">Speak</button>

<script>
function convert_text_to_speech() {
  const synth = window.speechSynthesis;
  const inputText = document.getElementById('txtWrite').value;
  if (inputText !== '') {
    const utterance = new SpeechSynthesisUtterance(inputText);
    utterance.pitch = 1;
    utterance.rate = 1;
    synth.speak(utterance);
  }
}
</script>
utterance.pitch sets the pitch of the voice. It’s value ranges from (0 to 2)
utterance.rate sets the speed of speech. It’s value ranges from (0.1 to 10)
utterance.volume is for the Volume (0 to 1)

In the example above, the text user writes in the input box will be converted to speech on click of the button.

Like I said, it’s pretty easy and with just a few lines of javascript, you can add voice to your website.

Don’t hesitate to add comments below for this post and you can also let us know in case of any questions!

Leave a Comment