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

View in English Always switch to English

SpeechSynthesis: voiceschanged イベント

Baseline 広く利用可能

この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。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);
  }
};

仕様書

仕様書
Web Speech API
# eventdef-speechsynthesis-voiceschanged
Web Speech API
# dom-speechsynthesis-onvoiceschanged

ブラウザーの互換性

関連情報