--- title: SpeechSynthesis.getVoices() slug: Web/API/SpeechSynthesis/getVoices translation_of: Web/API/SpeechSynthesis/getVoices ---
{{APIRef("Web Speech API")}}{{SeeCompatTable}}

The getVoices() method of the {{domxref("SpeechSynthesis")}} interface returns a list of {{domxref("SpeechSynthesisVoice")}} objects representing all the available voices on the current device.

Syntax

speechSynthesisInstance.getVoices();

参数

None.

返回值

返回一个类型为{{domxref("SpeechSynthesisVoice")}} 的数组(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>

{{EmbedLiveSample("Example", 400, 25)}}

Specifications

Specification Status Comment
{{SpecName('Web Speech API', '#dfn-ttsgetvoices', 'getVoices()')}} {{Spec2('Web Speech API')}} Initial definition

Browser compatibility

{{Compat("api.SpeechSynthesis.getVoices")}}

See also