JavaScript 30- Day 23 Study Notes

Jeffrey Amen
2 min readJan 4, 2021
https://javascript30.com/

Day 23 of JavaScript 30 by Wes Bos involved making a speech synthesis app that converts a written text to digital voice. The program used the speech synthesis API that resides in most modern browsers. The app contained two input sliders to manipulate speech rate and pitch.

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) placing 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;

A function brought the selection of synthesized voices and put them in a dropdown menu.

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

The next function matched the voice with the one selected.

function setVoice(){msg.voice = voices.find(voice => voice.name === this.value);toggle();}

The toggle function reset the app to the beginning of the message.

function toggle(startOver = true){   speechSynthesis.cancel();   if(startOver){      speechSynthesis.speak(msg);   }}

The next function sets the rate, pitch, and text options.

function setOption(){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));

This program contains several moving parts. It was challenging to visualize the flow of the program. Also, I didn’t realize there were features contained within the browser, such as speech synthesizer and voice recognition. Bos called them APIs, but we did not have to access them using code. They were readily available to be called, similar to a higher-ordered function.

Follow my study notes as I progressed through JavaScript 30.

--

--

Jeffrey Amen

Retired physician, writer, aspiring website designer and developer