6

I want to access the list of voices that are part of the SpeechSynthesis API on desktop Chrome, Safari, and Firefox. If I open a new tab in each browser and, via the console, run:

speechSynthesis.getVoices()

...I expect an array containing 'SpeechSynthesisVoice' objects (i.e. the available voices) to be returned. Firefox and Safari behave as expected, but in Chrome the first call to getVoices() returns an empty array. I have to call the method again in order to receive the expected populated array.

Why does Chrome behave like this? Does it do some kind of lazy loading of certain web APIs? Please help me understand.

Paul Rumkin
  • 6,737
  • 2
  • 25
  • 35
elphe
  • 63
  • 4
  • 1
    Possible duplicate of [Getting the list of voices in speechSynthesis (Web Speech API)](https://stackoverflow.com/questions/21513706/getting-the-list-of-voices-in-speechsynthesis-web-speech-api) – esqew Jul 14 '20 at 09:32
  • @esqew It's a duplicate, but has shorter and more relevant question. Maybe it's the reason to modify the question you referred to. – Paul Rumkin Jul 14 '20 at 10:35

1 Answers1

8

This happens because SpeechSynthesis API allows the usage of remote servers for speech synthesis and Chrome requests a list of voices from Google's servers. To fix this you need to wait when voices will be loaded and then request them again.

To do so you should to listen a voicechanged event, and then initialise your program's logic:

speechSynthesis.addEventListener("voiceschanged", () => {
  const voices = speechSynthesis.getVoices()
})
Paul Rumkin
  • 6,737
  • 2
  • 25
  • 35