SpeechSynthesis:voiceschanged 事件

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本上运行。自 2022 年 9 月起,所有浏览器都已支持此功能。

voiceschanged 事件是 Web Speech API 的一个事件,当通过 SpeechSynthesis.getVoices() 方法可以获取到的 SpeechSynthesisVoice 对象列表发生变化时(即触发 voiceschanged 事件时)会触发此事件。

语法

在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。

js
addEventListener("voiceschanged", (event) => { })

onvoiceschanged = (event) => { }

事件类型

一个通用的 Event,没有额外的属性。

示例

这可以用于在事件触发时重新填充用户可以选择的语音列表。您可以在 addEventListener 方法中使用 voiceschanged 事件

js
const synth = window.speechSynthesis;

synth.addEventListener("voiceschanged", () => {
  const voices = synth.getVoices();
  for (const voice of voices) {
    const option = document.createElement("option");
    option.textContent = `${voice.name} (${voice.lang})`;
    option.setAttribute("data-lang", voice.lang);
    option.setAttribute("data-name", voice.name);
    voiceSelect.appendChild(option);
  }
});

或者使用 onvoiceschanged 事件处理程序属性

js
const synth = window.speechSynthesis;
synth.onvoiceschanged = () => {
  const voices = synth.getVoices();
  for (const voice of voices) {
    const option = document.createElement("option");
    option.textContent = `${voice.name} (${voice.lang})`;
    option.setAttribute("data-lang", voice.lang);
    option.setAttribute("data-name", voice.name);
    voiceSelect.appendChild(option);
  }
};

规范

规范
Web Speech API
# eventdef-speechsynthesis-voiceschanged
Web Speech API
# dom-speechsynthesis-onvoiceschanged

浏览器兼容性

另见