HTML 5 - Speech API

Subscribe to my newsletter and never miss my upcoming articles

Vanilla javascript: How to use html5 speech API.

Resources: HTML5 - SpeechSynthesis API

note: The getVoices() method of the SpeechSynthesis interface returns a list of SpeechSynthesisVoice objects representing all the available voices on the current device.

In this article I will show you code examples to create a speech application in javascript.

What we need to do:

create an instance of SpeechSynthesisUtterance class.

         let message = new SpeechSynthesisUtterance();

create an array variable to store all available voices in the API.

         let voices = [];

Add an event listener to handle 'voiceschanged' event. Loads all available voices from current device into the voices array. Creates option elements with each voice in the array.

     speechSynthesis.addEventListener('voiceschanged', () => {
           voices = speechSynthesis.getVoices(); 
           voices.forEach((voice) => {
                const option = document.createElement('option');
                option.value = voice.name;
                option.innerText = voice.name;
          voicesSelect.appendChild(option);
         });
    });

Add an event listener to handle voice change event from select option. Sets selected voice as current.

 voicesSelect.addEventListener('change', (e) => {
       message.voice = voices.find(voice => voice.name === e.target.value);
  });

Add an event listener to handle read click button event. Set message from textarea and play the message.

    readBtn.addEventListener('click', () => {
           message.text = text.value;
           speechSynthesis.speak(message);
    });

Please see a live example here.

Thanks for reading this article.

Let's Connect

twitter Ruedatech

Next article: undefined

No Comments Yet