Speak text aloud in the browser with the Web Speech API: utterances, voices, and playback.

Speech synthesis

Introduction

Build an utterance, pick a voice, and pass it to speechSynthesis.speak().

Speaking

function speak (message) {
  const msg = new SpeechSynthesisUtterance(message)
  window.speechSynthesis.speak(msg)
}
speak('Hello, world')

See: speak() (developer.mozilla.org)

Voices

getVoices() may return [] until the browser loads its voices. Read the list again once the voiceschanged event fires.

let voices = speechSynthesis.getVoices()

if (voices.length === 0) {
  speechSynthesis.onvoiceschanged = () => {
    voices = speechSynthesis.getVoices()
  }
}

Then set msg.voice = voices[0] before calling speechSynthesis.speak(msg).

See: getVoices(), voiceschanged (developer.mozilla.org)

0 Comments for this cheatsheet. Write yours!