Javascript 为什么页面加载时触发voiceschanged事件?
在Chrome中,Javascript 为什么页面加载时触发voiceschanged事件?,javascript,webspeech-api,Javascript,Webspeech Api,在Chrome中,voiceschanged在页面加载时启动,因此我不需要调用具有speechSynthesis.getVoices()的函数,只要我有一个事件侦听器在启动voiceschanged时调用它,我的空数组就会充满声音 // Store voices let voices = []; function getVoices() { voices = speechSynthesis.getVoices(); // Create an option for each voice
voiceschanged
在页面加载时启动,因此我不需要调用具有speechSynthesis.getVoices()
的函数,只要我有一个事件侦听器在启动voiceschanged
时调用它,我的空数组就会充满声音
// Store voices
let voices = [];
function getVoices() {
voices = speechSynthesis.getVoices();
// Create an option for each voice in array
voices.forEach((voice) => {
const option = document.createElement('option');
option.value = voice.name;
option.innerText = `${voice.name} ${voice.lang}`;
voicesSelect.appendChild(option);
});
}
// Voices changed
speechSynthesis.addEventListener('voiceschanged', getVoices);
// Not needed (in Chrome at least) because voiceschanged event fires on page load, calling getVoices due to event listener (trying to figure out why)
// getVoices();
我只是想了解这种行为——MDN的voiceschanged fires并没有尽我所能解释它:
Web语音API的voiceschanged事件在列表
将由
getVoices()方法已更改(当VoiceSchange
事件火灾。)
该事件会触发,因为当Chrome完成API调用以获取仅对Chrome用户可用的语音列表时,语音列表会发生变化。证明:
- 如果我加载基于语音合成API的web应用程序,连接互联网,我有21种可用语音,几个月前,我只记得10或15种左右
- 如果我也这样做,没有互联网连接,我只有两种声音:微软大卫桌面和微软Zira桌面
voiceschanged
事件
voiceschanged:当getVoices方法将返回的SpeechSynthesisVoiceList的内容发生更改时激发。示例包括:异步确定列表的服务器端合成,或者安装/卸载客户端语音
事实上,看看你们链接的最后一行
然而,对于Chrome,在填充列表之前,您必须等待事件触发,因此下面是底部的if语句
(来自我的开源项目声明)这种行为是否也发生在Firefox/Edge中,或者这是Chrome独有的?这是一个实验性的API,所以我不希望它在浏览器之间表现出一致的行为,也不希望它在此时以一种有意义的方式表现出来。在Firefox中,事件显然被触发,但我只加载了两个声音。旁注-即使使用getVoices(),Firefox中的数组中也只添加了两个声音。(我在Live Server上使用VS代码,我不知道这是否与此有关。)Microsoft David Desktop和Microsoft Zira Desktop——顺便说一句,这是我在尝试加载Firefox时得到的唯一两个。