SpeechSynthesisUtterance Chrome 问题

SpeechSynthesisUtterance Chrome Issue

我在使用本机 SpeechSynthesisUtterance 时遇到问题(或错误)。我构建了一个基本函数 "speak",它将接受给定的字符串 "text" 并发音。

//Function for speaking text
function speak(text){
  if ('speechSynthesis' in window) {
    var sentence = new SpeechSynthesisUtterance();
    var voices = window.speechSynthesis.getVoices();
    for(var i = 0; i < voices.length; i++) {
          if(voices[i]['name'] == "Alex"){
            sentence.voice = voices[i];
          }
      }
    sentence.pitch = 0.5;
    sentence.rate = 1;
    sentence.text = text;
    window.speechSynthesis.speak(sentence);
  } else {
    console.log("Oops! Your browser does not support HTML SpeechSynthesis.")
  }
}

此功能在 Safari 中完美运行,select语音 "Alex" 然后用该语音读出给定的文本。另一方面,在 Chrome 中,我遇到了一个问题。由于某种原因,"Alex" 在 Chrome 中第二次调用该函数时仅 select。第一次调用该功能是用默认的女声说出文本,但之后声音设置为 "Alex" 并且效果很好。我已将此错误限制为 Chrome 问题,但是,我仍然希望它得到修复。非常感谢任何帮助!

getVoices 是异步的(在 Spec Errata 中提到),你需要听 voiceschanged event,推理有点令人沮丧但有道理,语音系统是延迟加载的,第一次调用 getVoices会阻塞主线程,所以第一次调用 android returns 0 结果,然后在语音可用时触发 onvoiceschanged

// Chrome loads voices asynchronously.
window.speechSynthesis.onvoiceschanged = function(e) {
  loadVoices();
};

linked demo incorrectly sets the voice attribute on the utterance. This doesn't exist, instead you need to change the lang and optionally the voiceURI to change the default used voice as can be seen below and in the new demo.

if (voiceSelect.value) {
  var selectedVoice = speechSynthesis.getVoices().filter(function(voice) { return voice.voiceURI == voiceSelect.value; })[0];

  msg.voiceURI = selectedVoice.voiceURI;
  msg.lang = selectedVoice.lang;

}