此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

SpeechSynthesis.getVoices()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2018年9月⁩.

SpeechSynthesis 接口的 getVoices() 方法返回一个 SpeechSynthesisVoice 列表,用于表示当前设备上所有可用的语音。

语法

js
getVoices()

参数

无。

返回值

返回一个类型为 SpeechSynthesisVoice 的数组(array)列表(list)。

示例

JavaScript

js
function populateVoiceList() {
  if (typeof speechSynthesis === "undefined") {
    return;
  }
  var voices = speechSynthesis.getVoices();
  for (var i = 0; i < voices.length; i++) {
    var option = document.createElement("option");
    option.textContent = voices[i].name + " (" + voices[i].lang + ")";
    if (voices[i].default) {
      option.textContent += " -- DEFAULT";
    }
    option.setAttribute("data-lang", voices[i].lang);
    option.setAttribute("data-name", voices[i].name);
    document.getElementById("voiceSelect").appendChild(option);
  }
}
populateVoiceList();
if (
  typeof speechSynthesis !== "undefined" &&
  speechSynthesis.onvoiceschanged !== undefined
) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

HTML

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

规范

Specification
Web Speech API
# dom-speechsynthesis-getvoices

浏览器兼容性

参见