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

浏览器兼容性

另见