SpeechSynthesis: getVoices() 方法

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本上使用。自 2018 年 9 月以来,它已在各种浏览器中推出。

getVoices() 方法是 SpeechSynthesis 接口的一部分,它返回一个 SpeechSynthesisVoice 对象列表,代表当前设备上所有可用的语音。

语法

js
getVoices()

参数

无。

返回值

一个 SpeechSynthesisVoice 对象的列表(数组)。

示例

JavaScript

js
function populateVoiceList() {
  if (typeof speechSynthesis === "undefined") {
    return;
  }

  const voices = speechSynthesis.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);
    document.getElementById("voiceSelect").appendChild(option);
  }
}

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

HTML

html
<select id="voiceSelect"></select>

规范

规范
Web Speech API
# dom-speechsynthesis-getvoices

浏览器兼容性

另见