Use Web Speech API to make the browser speak out loud using SpeechSynthesis

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

Did you know that your browser can speak?

That's right - using the [https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API](Web Speech API) it is possible to use speech synthesis in the browser without any additional libraries.

In this quick lesson we're going to use window.speechSynthesis in order to build an app that will say anything we put into a text input out loud using a default voice/pitch/volume set by the browser.

Tomasz Łakomy: [0:00] We have a simple app with an input and a button. I would like to have a behavior where if I type in "hello" and click on the button, I would like the browser to say, "Hello" out load.

[0:11] Luckily, we can implement that using the Web Speech API. This is an experimental API that allows us to incorporate voice data into web apps. There are two parts of this API. There is the SpeechSynthesis, which is basically Text-to-Speech, and SpeechRecognition.

[0:26] When it comes to browser support, it's surprisingly large. Basically, only one desktop browser and one browser on mobile devices is not supporting this API.

[0:34] To implement that, let me first get the value of the input. I'm going to do const value = textInput.value. Next, I'm going to create another variable, const sayThis = new speechSynthesisUtterance, and I'm going to pass in the value. Basically, this variable represents a speech request, and it contains the content that speech service should read and information how to read that, for instance, language, pitch and volume.

[1:00] Those things are configured by default, but nevertheless we can change all of them if you want to. For now, let's stick to default. I'm going to do window.speechSynthesis.speak, and I'm going to pass in sayThis variable.

[1:12] If I save that and type in "hello egghead friends!" and click on Say it!, the browser is going to speak to us.

Emily Harber
Emily Harber
~ 4 years ago

This is so cool and now I have a bunch of ideas for really dumb weird apps that talk to people lol

Markdown supported.
Become a member to join the discussionEnroll Today