Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 19, 2020 05:14 pm GMT

Text To Speech In 3 Lines Of JavaScript

If you're curious about trying this out, that's the 3 lines of code below

var msg = new SpeechSynthesisUtterance();msg.text = "Hello World";window.speechSynthesis.speak(msg);

But if you're not in a hurry, this article explains everything you need to know about converting text to speech (spoken words) on the web with JavaScript.

Introducing

In a previous article, I had wrote about the Web Speech API and also how to convert Speech To Text
Another amazing feature of the Web Speech API is to convert Text to Speech.

Note: Text To Speech != Speech To Text

  • Text To Speech is when we give the computer some words and the computer will say this words out loud in some robotic/human voice. While
  • Speech To Text is when we say some words to the computer, and what we'd just said will be converted to text (I guess this is explanatory enough )

Getting Started

The first thing we'll need to do is check if our browser supports the speech synthesis API. And the code below does that:

if ('speechSynthesis' in window) {// Speech Synthesis supported }else{  // Speech Synthesis Not Supported   alert("Sorry, your browser doesn't support text to speech!");}

Next step is to create a new speechSynthesis object, add required property and make our app talk

var msg = new SpeechSynthesisUtterance();msg.text = "Good Morning";window.speechSynthesis.speak(msg);

Code Explanation

  • Line 1: We created a variable msg, and the value assigned to it is a new instance of the speechSynthesis class.
  • Line 2: The .text property is used to specify the text we want to convert to speech
  • And finally, the code on the 3rd(last) line is what actually make our browser talks.

Altering Default Output

The speechSynthesis API gives room to also change alter the default output like changing the voice, volume, speech rate, language, pitch and more:

var msg = new SpeechSynthesisUtterance();var voices = window.speechSynthesis.getVoices();msg.voice = voices[10]; msg.volume = 1; // From 0 to 1msg.rate = 1; // From 0.1 to 10msg.pitch = 2; // From 0 to 2msg.text = "Como estas Joel";msg.lang = 'es';speechSynthesis.speak(msg);

Getting Supported Voices

The code below helps you retrieve the list of all supported voices:

speechSynthesis.getVoices().forEach(function(voice) { console.log(voice.name, voice.default ? voice.default :'');});

Conclusion

Well, there's nothing to conclude here I guess
But you could follow me on Twitter, I tweet and retweet interesting technical stuffs; you sure want to see em.

Thanks for reading


Original Link: https://dev.to/asaoluelijah/text-to-speech-in-3-lines-of-javascript-b8h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To