In this lesson I convert text to a new speech synthesis utterance from the browser.
First I create a new speech synthesis utterance (const msg = new SpeechSynthesisUtterance()). I get the following elements: <select>, 'speak' <button>, 'stop' <button> All <input> elements. I initialise an empty 'voices[]' array, as well as set what 'msg' text will be spoken by grabbing the [name='text'] element.
I listen for the following events:
-
speechSynthesis
- 'voiceschanged', populateVoices()
- This event is needed before populating the voices in-order to give the browser enough time to have the required event ready.
-
<select>
-
<option>
-
speakButton
- toggle
- This will start the speech synthesis.
-
stopButton
- 'click', () => toggle(false)
- This will stop the speech synthesis.
In populateVoices() - First to get the 'voices' use .getVoices() from 'this' (speechSynthesis). Then set the 'innerHTML' of <select> to the list of 'voices'. Next .filter() over each voice to only include voices with a language of 'en'. Then .map() over each voice to add <option> HTML to each entry. Lastly .join('') to convert the array into one string.
In setVoice() - First set 'msg.voice' to the 'voice' that matches the <select> item (msg.voice = voices.fint(voice => voice.name === this.value)). Then run toggle().
In toggle(true/false) - First stop any currently playing speech (speechSynthesis.cancel();). Then check if either true or false was passed into the function. If false, do nothing more. If true (default), restart the speech synthesis (speechSynthesis.speak(msg);).
In setOption() - This sets the 'msg' voice to the <option> that was selected. Then run toggle().
See the Pen
JavaScript30 - 23 - Speech Synthesis by Corey Noble (@CoreyNoble)
on CodePen.