在 Chrome 中,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 的 explanation据我所知,声音改变时的火灾并不能解释它:
The voiceschanged event of the Web Speech API is fired when the list of SpeechSynthesisVoice objects that would be returned by the SpeechSynthesis.getVoices() method has changed (when the voiceschanged event fires.)
最佳答案
该事件会触发,因为当 Chrome 完成 API 调用以获取仅供 Chrome 用户使用的语音列表时,语音列表会发生变化。证明:
- 如果我加载基于语音合成 API 的网络应用程序,并连接到互联网,我有 21 种可用语音,而几个月前,我只记得 10 或 15 种左右。
- 如果我也这样做,在没有互联网连接的情况下,我只有两种声音:Microsoft David Desktop 和 Microsoft Zira Desktop。
您可能会注意到,没有互联网连接的两种声音相当无聊,而且几乎可以识别为用于廉价音频制作。但谷歌浏览器的浏览器是流畅的,几乎是变形的。当然,这个事件必须在声音加载时触发。快速浏览一下W3C Errata in the Web Speech API Specification 。任何时候加载语音时,voiceschanged
事件都会被触发......
voiceschanged: Fired when the contents of the SpeechSynthesisVoiceList, that the getVoices method will return, have changed. Examples include: server-side synthesis where the list is determined asynchronously, or when client-side voices are installed/uninstalled.
事实上,看看 MDN web docs 的最后一行您已链接...
With Chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below.
Speech Synthesis API-Based Source Code (来 self 的开源项目 PronounceThat)
关于javascript - 为什么在页面加载时触发 voiceschanged 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65688030/