Search code examples
javascriptgoogle-chrome-devtoolstext-to-speech

JavaScript code for window.speechSynthesis not working from localhost


Following code works fine in Chrome DevTools but when I run this through localhost allVoices returns an empty array.

tts = window.speechSynthesis

// from here code only works if put into DevTools, not from file or localhost
allVoices = tts.getVoices()

console.log(allVoices) // gives empty array

What am I doing wrong?


Solution

  • In Chrome getVoices() returns empty, then there's an event when the voices are ready, onvoiceschanged, which accepts a callback.

    Your commands work in DevTools because by the time you've typed 'allVoices = tts.getVoices()' the voices have already arrived and are available.

    However other browsers e.g. Safari return voices synchronously and there's no need for a callback.

    Therefore the best code seems to be:

    let voices = speechSynthesis.getVoices();
      if (voices.length) {
        resolve(voices);
        return;
      }
      speechSynthesis.onvoiceschanged = () => {
        voices = speechSynthesis.getVoices();
        if (voices.length) resolve(voices);
      };