SpeechSynthesis:voiceschanged 事件
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 |
瀏覽器相容性
載入中…