Day23 of #100DaysOfCode

Kushagra Kesav
2 min readMar 2, 2022

--

#CodeTogether Day 23/100

Hii folks 🙌

Today I have completed the 23rd video of JavaScript30!

Project 23: Speech Synthesis

Source: https://javascript30.com

Learnings:

Today we have been tasked to build a web interface for Speech Synthesis!

This is an interface for the Web Speech API. It contains the content that the speech service will read, as well as options that can be configured, such as language and pitch.

The Voiceinator 5000

First, we declared a new variable containing the message, and an empty array to contain various digital voices from the API.

const msg = new SpeechSynthesisUtterance();let voices = [];

We selected the necessary HTML elements including the text box value (The written message) placed in an array.

const voicesDropdown = document.querySelector('[name="voice"]');
const options = document.querySelectorAll('[type="range"], [name="text"]');
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');
msg.text = document.querySelector('[name="text"]').value;

It can also be used to start and pause the speech. A function brought the selection of synthesized voices and put them in a dropdown menu.

function populateVoices() {
voices = this.getVoices();
voicesDropdown.innerHTML = voices
.filter(voice => voice.lang.includes('en'))
.map(voice => `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`)
.join('');
}

Above, are examples of properties and methods that can be used to alter the state of the speech device.

function setVoice() {
msg.voice = voices.find(voice => voice.name === this.value);
toggle();
}
function toggle(startOver = true) {
speechSynthesis.cancel();
if (startOver) {
speechSynthesis.speak(msg);
}
}
function setOption() {
console.log(this.name, this.value);
msg[this.name] = this.value;
toggle();
}

Finally the event listeners for interactivity. Each is linked to one of the above functions.

speechSynthesis.addEventListener('voiceschanged', populateVoices);
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption));
speakButton.addEventListener('click', toggle);
stopButton.addEventListener('click', ()=> toggle(false));

Today I Learned (T-I-L):

  • To create a Speech Synthesis web app
  • Linking event listener to each user-defined function!🙌

That is all for Day23 ✅

Thanks for reading, See you tomorrow!

--

--