このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

SpeechSynthesis: voiceschanged イベント

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2022年9月.

voiceschangedウェブ音声 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);
  }
};

仕様書

Specification
Web Speech API
# eventdef-speechsynthesis-voiceschanged
Web Speech API
# dom-speechsynthesis-onvoiceschanged

ブラウザーの互換性

関連情報