Member-only story
Convert Text to Speech Using Web Speech API in JavaScript
Let’s listen to those words!
I spent a lot of time on Medium. Sometimes to write about something, but mostly to read. Read about the experiences that other developers are willing to share with the community.
Recently, I noticed that the Medium has a play button for each and every story. Initially, I thought this privilege is given to only a few stories or writers. But at the next moment, I knew that this is for all the readers. This means we can even listen to the stories on Medium. Awesome!
Then, just like a typical developer, I thought, how did they do that? I knew that in the JavaScript realm, we have a web API called Web Speech API for that, but I never used or learned about that.
So today, let's learn about this web API together, and let's even create a working example as well.
Voice data is incorporated into online apps using the Web Speech API. In this article, we’ll create a simple webpage that implements text-to-speech using the Web Speech API.
For the sake of this demo, let’s create a new directory and create two new files: index.html
and text-to-speech.js
The HTML File
In the HTML file, let’s set up the following elements:
- A
select
menu with no options. Using JavaScript, we’ll fill the emptyselect
menu with a list of possible voices - Range sliders for volume, pitch, and rate
- A
textarea
to type in - Control buttons for the speech
In this demo, we are going to use Bootstrap 5 for the styling. Here’s some code:
This is how it will look in the browser:
