SpeechSynthesisVoice

Baseline 已廣泛支援

此功能已成熟,並可在多種裝置和瀏覽器版本上使用。自 2018 年 9 月以來,它已在各種瀏覽器中推出。

SpeechSynthesisVoice 介面是 Web Speech API 的一部分,它代表系統支援的聲音。每個 SpeechSynthesisVoice 都有其自身的相對語音服務,包括語言、名稱和 URI 資訊。

例項屬性

SpeechSynthesisVoice.default 只讀

一個布林值,指示該聲音是否為當前應用程式語言的預設聲音(true),或者不是(false)。

SpeechSynthesisVoice.lang 只讀

返回一個 BCP 47 語言標籤,指示聲音的語言。

SpeechSynthesisVoice.localService 只讀

一個布林值,指示該聲音是由本地語音合成服務提供(true),還是由遠端語音合成服務提供(false)。

SpeechSynthesisVoice.name 只讀

返回一個人類可讀的名稱,代表該聲音。

SpeechSynthesisVoice.voiceURI 只讀

返回此聲音的語音合成服務的 URI 型別和位置。

示例

以下程式碼片段摘錄自我們的 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();
};

規範

規範
Web Speech API
# speechsynthesisvoice

瀏覽器相容性

另見