SpeechSynthesis onend bug workaround

by opike99

HTML

<button id='x'>
Click for speech audio
</button>

JavaScript

var wordsToSpeak = [
  'We propose additional funds for other engine development and for unmanned explorations—explorations which are particularly important for one purpose which this nation will never overlook: the survival of the man who first makes this daring flight.',
  'Now end event is fired!',
  'You can use global variables to store utterance object.'
];

let voice;

  const getVoices = () => {
    if (window.speechSynthesis) {
      const tmp = speechSynthesis.getVoices();

      if (tmp.length !== 0) {
      // This voice has a problem.
      voice = tmp[146];
      
      // This voice doesn't have a problem.
      //voice = tmp[0];
      
      }
    }
  };
// this object for storing utterances globally
window.utterances = [];

  getVoices();
  speechSynthesis.addEventListener('voiceschanged', getVoices);

function speak(text) {
  var utterance = new SpeechSynthesisUtterance(text);
  console.log(voice);
  utterance.voice = voice;

  utterance.onend = function() {
    // this code is not called
    console.log(text);
  };

  // if you will comment this line, end event will not work!
  window.utterances.push(utterance);
  
  speechSynthesis.speak(utterance);
}


document.getElementById("x").addEventListener("click", () => {
  for (var i = 0; i < wordsToSpeak.length; i++) {
    speak(wordsToSpeak[i])
  }
});