javascript - 为什么在页面加载时触发 voiceschanged 事件?

标签 javascript webspeech-api

在 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/

相关文章:

javascript - 图像转换 jquery

javascript - 如何在 4 帧之间连续制作动画

Javascript 声音开始/停止和图像更改第 2 部分

javascript - Firefox 中的语音识别

html - Web Speech API - iOS 中的语音识别

javascript - 从 Google Apps 脚本调试客户端代码

javascript - 如何将此 PHP 对象转换为数组?

javascript - 网络语音 API "Detecting known words"

dom-events - 获取speechSynthesis(Web Speech API)中的语音列表

javascript - 如何向 Web Speech API 添加标点符号?