【发布时间】:2021-01-12 16:32:40
【问题描述】:
在 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 何时发声并没有解释它:
Web Speech API 的 voiceschanged 事件在列表时触发 SpeechSynthesisVoice 对象将由 SpeechSynthesis.getVoices() 方法已更改(当 voiceschanged 事件触发。)
【问题讨论】:
-
这种行为是否也出现在 Firefox/Edge 中,还是 Chrome 独有的?这是一个实验性的 API,所以我不希望它在浏览器之间保持一致,或者以目前有意义的方式运行。
-
Edge 中也会出现同样的行为。在 Firefox 中,显然该事件已被触发,但我只加载了两个声音。
-
旁注 - 即使使用 getVoices(),也只有两个声音被添加到 Firefox 中的数组中。 (我正在使用 VS Code 和 Live Server,我想知道这是否与它有关。)