我遇到使用原生SpeechSynthesisUtterance的问题(或错误)。我建立了一个基本功能"说",它将采用给定的字符串" 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中完美运行,选择语音&#34; Alex&#34;然后用那个声音发出给定的文本。另一方面,在Chrome中,我遇到了一个问题。出于某种原因,&#34; Alex&#34;只有在Chrome中第二次调用该功能时才会选择。第一次调用该函数时,会使用默认的女性语音说出文本,但之后将语音设置为&#34; Alex&#34;它完美无缺。我已将此错误限制为Chrome问题,但是,我仍然希望将其修复。非常感谢任何帮助!
答案 0 :(得分:3)
getVoices是asynchronus(在规范勘误中提到),你需要听http://regexr.com/3cc0r,推理有点令人沮丧但有意义,语音系统是懒惰加载的,第一次调用getVoices会阻塞主线程所以对android的第一次调用返回0结果,然后当声音可用时触发onvoiceschanged
。
// Chrome loads voices asynchronously.
window.speechSynthesis.onvoiceschanged = function(e) {
loadVoices();
};
voiceschanged event错误地在话语上设置voice
属性。这不存在,而是您需要更改lang和可选的voiceURI以更改默认使用的语音,如下面和linked 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;
}