Vanilla JavaScript text-to-speech π¬

I'm a full-stack developer from South Africa πΏπ¦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa πΏπ¦. I love writing about JavaScript, HTML and CSS.
No comments yet. Be the first to comment.
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

I have quite an intriguing background in the TTS (Text-to-speech) field. It always caught my eye.
Back in my school period, my projects would always involve either some kind of TTS or webcam interaction.
Now those were always super cool but couldn't really be of any use in most websites.
Yeah, it looks cool, but when do you really need it.
Another side to TTS is that it was very hard to use. You needed a vast amount of plugins or third-party parses.
These days we are a bit luckier with how powerful JavaScript has become.
So today, I wanted to have another look at Text to speech in JavaScript.
The end result for today: Try it out on the following Codepen.
We can leverage the Web Speech API, which uses the SpeechSynthesis interface.
To have our computer talk to us, we must then make use of the SpeechSynthesisUtterance interface.
This basically translates to: speech request.
In this interface, we define the voice, language, and volume.
It comes with the following elements:
lang: The language of the outputpitch: Sets a pitch for the output spoken wordsrate: The rate (speed) at which spoken istext: The actual text that's spokenvoice: Which voice you want to usevolume: The output volumeSince this method is not fully supported by all browsers, we will need to detect if our browser has this option.
const SpeechSynthesisUtterance =
window.webkitSpeechSynthesisUtterance ||
window.mozSpeechSynthesisUtterance ||
window.msSpeechSynthesisUtterance ||
window.oSpeechSynthesisUtterance ||
window.SpeechSynthesisUtterance;
Here we define a const to check if the support is defined.
We can then easily check this const.
if (SpeechSynthesisUtterance !== undefined) {
// Do the speech stuff
} else {
console.warn('sorry not supported π');
}
I don't know about you, but I love to play around with any device's voice options.
If it's my Google Home, or something like the Speech API.
The cool part about the Web Speech API is that we can query all available voices.
const voices = window.speechSynthesis.getVoices();
console.log(voices);
// []
Now running this will likely result in a empty result, so another cool thing the API comes with is a callback for once the voices are loaded:
window.speechSynthesis.onvoiceschanged = () => {
const voices = window.speechSynthesis.getVoices();
console.log(voices);
// (67) [SpeechSynthesisVoice, SpeechSynthesisVoice, ...]
};
Now, let's add a select list to our HTML and render the voices as options.
<select id="voiceSelect"></select>
And in our JavaScript:
const voiceSelect = document.getElementById('voiceSelect');
let voices;
if (SpeechSynthesisUtterance !== undefined) {
window.speechSynthesis.onvoiceschanged = () => {
voices = window.speechSynthesis.getVoices();
voices.forEach((voice, key) => {
let option = document.createElement('option');
option.textContent = voice.name + ' (' + voice.lang + ')';
option.value = key;
voiceSelect.appendChild(option);
});
};
}
We should now have a select list that is populated with all the available voices.

Now let's also add an input field where the user can type some text that will be spoken.
Our HTML will look like this:
<form>
<select id="voiceSelect"></select>
<input id="voiceInput" />
<button type="submit">Speak</button>
</form>
Then in our JavaScript let's first define the variables we need:
const form = document.querySelector('form'),
voiceSelect = document.getElementById('voiceSelect'),
voiceInput = document.getElementById('voiceInput');
Now we need to catch the form submit and prevent it from submitting to a blank page.
form.onsubmit = function(event) {
event.preventDefault();
// Do the speech action
};
Now it's finally time to have the computer talk to us.
form.onsubmit = function(event) {
event.preventDefault();
let speak = new SpeechSynthesisUtterance(voiceInput.value);
speak.voice = voices[voiceSelect.value];
window.speechSynthesis.speak(speak);
};
Now you can type something in the input field and select your voice. Press the speak button, and you should hear some spoken words!
Again, pretty good coverage for a fairly new API. Of course, IE is a pain like always, and mobile Opera and Android have some issues with it.

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter