DEV Community

timothyokooboh
timothyokooboh

Posted on

How To Add Speech Functionality To Your App

In this article, I will show you how to add speech functionality to your applications.

I recently made a simple dictionary app with vue.js using the owlbot-js API. so I needed users to listen to the correct pronunciation of the words. I used the technique am about to show you and it took less than a minute to add speech functionality to my dictionary app.

P.S: On my android phone, I sometimes experience some delay before the voice note begins. But on my laptop, there is never a delay.

So let's begin!

I'm gonna embed a code pen.

First, we initialize the built-in speech synthesis API

const speech = window.speechSynthesis;

Then, we access the DOM to select the text we want to get spoken.

const text = document.querySelector("#text"). innerHTML;

The speech synthesis API has a constructor called SpeechSynthesisUtterance. This constructor receives one argument which is the text we want to get spoken. In our code, this argument is the same as the text variable we declared.

const utterance = new SpeechSynthesisUtterance(text)

So, we created a variable called utterance and assigned it the SpeechUtterance constructor

function sayTheWords(){
speech.speak(utterance);
}

Finally, when our button is clicked, we call the built-in speak method on the speech synthesis API. The built-in speak method receives one argument, which is the utterance variable we declared.

So that's how you can add speech functionality to your app.

You can think of several use cases where this functionality may be useful in your app. For instance, apart from displaying flash messages when a user creates, edits, or deletes a post, you could also send a voice message.

To learn more about the speech synthesis API, you can check out this video by Brad Traversy

He went further to explain how you could select the particular voice, pitch, and even the rate at which the voice note is spoken.

Thanks for reading.

Top comments (3)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

If choosing language, I find it not normalized between desktop and mobile.

Collapse
 
timothyokooboh profile image
timothyokooboh

Yes it's not. The language options are quite different on mobile and desktop

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt