SpeechSynthesisVoice

Baseline Widely available

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

Giao diện SpeechSynthesisVoice của Web Speech API đại diện cho một giọng nói mà hệ thống hỗ trợ. Mỗi SpeechSynthesisVoice có dịch vụ giọng nói riêng bao gồm thông tin về ngôn ngữ, tên và URI.

Thuộc tính phiên bản

SpeechSynthesisVoice.default Read only

Một giá trị boolean cho biết liệu giọng nói có phải là giọng nói mặc định cho ngôn ngữ ứng dụng hiện tại (true) hay không (false).

SpeechSynthesisVoice.lang Read only

Trả về một BCP 47 language tag cho biết ngôn ngữ của giọng nói.

SpeechSynthesisVoice.localService Read only

Một giá trị boolean cho biết liệu giọng nói có được cung cấp bởi dịch vụ tổng hợp giọng nói cục bộ (true) hay dịch vụ tổng hợp giọng nói từ xa (false).

SpeechSynthesisVoice.name Read only

Trả về một tên dễ đọc đại diện cho giọng nói.

SpeechSynthesisVoice.voiceURI Read only

Trả về loại URI và vị trí của dịch vụ tổng hợp giọng nói cho giọng nói này.

Ví dụ

Đoạn mã sau được trích từ Speech synthesizer demo.

js
const synth = window.speechSynthesis;
function populateVoiceList() {
  voices = synth.getVoices();

  for (const voice of voices) {
    const option = document.createElement("option");
    option.textContent = `${voice.name} (${voice.lang})`;

    if (voice.default) {
      option.textContent += " — DEFAULT";
    }

    option.setAttribute("data-lang", voice.lang);
    option.setAttribute("data-name", voice.name);
    voiceSelect.appendChild(option);
  }
}

populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  for (const voice of voices) {
    if (voice.name === selectedOption) {
      utterThis.voice = voice;
    }
  }
  utterThis.pitch = pitch.value;
  utterThis.rate = rate.value;
  synth.speak(utterThis);

  utterThis.onpause = (event) => {
    const char = event.utterance.text.charAt(event.charIndex);
    console.log(
      `Speech paused at character ${event.charIndex} of "${event.utterance.text}", which is "${char}".`,
    );
  };

  inputTxt.blur();
};

Thông số kỹ thuật

Specification
Web Speech API
# speechsynthesisvoice

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

Xem thêm