Recipe 9.4

Synthesizing Speech

Demo

Code

JavaScript
const voiceSelect = document.querySelector('#voices');

let voices = [];

function speakText(text) {
  const utterance = new SpeechSynthesisUtterance(text);
  utterance.voice = voices[voiceSelect.value];
  speechSynthesis.speak(utterance);
}

function populateVoiceOptions() {
  if (!voices.length) {
    voices = speechSynthesis.getVoices();
    voices.forEach((voice, index) => {
      const option = new Option(voice.name, index);
      if (voice.name === 'Samantha') {
        option.selected = true;
      }
      voiceSelect.appendChild(option);
    });
  }
}

speechSynthesis.addEventListener('voiceschanged', () => populateVoiceOptions());
populateVoiceOptions();

document.querySelector('#speak-button').addEventListener('click', () => {
  speakText(document.querySelector('#speak-text').value);
});
HTML
<div class="mb-4">
  <label for="voices" class="form-label">Voice</label>
  <select class="form-select" id="voices"></select>
</div>

<div class="mb-4">
  <label for="speak-text" class="form-label">Text to speak</label>
  <textarea id="speak-text" class="form-control"></textarea>
</div>

<button id="speak-button" class="btn btn-primary">Speak!</button>
Web API Cookbook
Joe Attardi