SpeechSynthesis: sự kiện voiceschanged

Baseline Widely available

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

Sự kiện voiceschanged của Web Speech API được kích hoạt khi danh sách các đối tượng SpeechSynthesisVoice mà phương thức SpeechSynthesis.getVoices() trả về đã thay đổi (khi sự kiện voiceschanged được phát ra.)

Cú pháp

Dùng tên sự kiện trong các phương thức như addEventListener(), hoặc đặt một thuộc tính trình xử lý sự kiện.

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

onvoiceschanged = (event) => { }

Kiểu sự kiện

Một Event tổng quát không có thuộc tính bổ sung.

Ví dụ

Điều này có thể được dùng để điền lại danh sách voice mà người dùng có thể chọn khi sự kiện được kích hoạt. Bạn có thể dùng sự kiện voiceschanged trong phương thức addEventListener:

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);
  }
});

Hoặc dùng thuộc tính trình xử lý sự kiện 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);
  }
};

Đặc tả kỹ thuật

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

Tính tương thích trên trình duyệt

Xem thêm