SpeechSynthesis.getVoices()

Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

The getVoices() method of the SpeechSynthesis interface returns a list of SpeechSynthesisVoice (en-US) objects representing all the available voices on the current device.

Syntax

speechSynthesisInstance.getVoices();

参数

None.

返回值

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

Note: 使用此方法会返回存在错误规范的SpeechSynthesisVoiceList 对象, 可能已被从现有规范中移除。

示例

JavaScript

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

  voices = speechSynthesis.getVoices();

  for(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

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

Specifications

Specification Status Comment
Web Speech API
getVoices()
Draft Initial definition

Browser compatibility

BCD tables only load in the browser

See also