我在两个场景中都使用了这个确切的代码。
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[1];
msg.text = "hello world";
msg.lang = 'en-US';
speechSynthesis.speak(msg);
如果我在Chrome控制台中运行此功能,我会发出女声。但是,如果我将确切的代码放在index.html中并运行它,它会播放男声。任何人都可以澄清为什么会出现这种差异。提前谢谢。
答案 0 :(得分:1)
找到根本原因。 Getting the list of voices in speechSynthesis of Chrome (Web Speech API)
调用是异步的,所以当我尝试在index.html中运行时,voices数组为空。正如我所说,当我运行它然后使用说话它工作正常。
var msg;
var voices;
var timer = setInterval(function() {
voices = speechSynthesis.getVoices();
console.log(voices);
if (voices.length !== 0) {
msg = new SpeechSynthesisUtterance();
msg.voice = voices[0];
speechSynthesis.speak(msg);
msg.lang = 'en-US';
clearInterval(timer);
}
}, 200);
timer();
speechSynthesis.speak("hello world");