aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/speechsynthesis/getvoices/index.md
blob: 8a46a3f896fe0fd64d8684fb5f785ca5828310cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
---
title: SpeechSynthesis.getVoices()
slug: Web/API/SpeechSynthesis/getVoices
tags:
  - API
  - Method
  - Reference
  - SpeechSynthesis
  - Web Speech API
  - getVoices
  - speech
  - synthesis
translation_of: Web/API/SpeechSynthesis/getVoices
---
{{APIRef("Web Speech API")}}

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

## 语法

```js
getVoices()
```

### 参数

无。

### 返回值

返回一个类型为 {{domxref("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>
```

{{EmbedLiveSample("示例", 400, 25)}}

## 规范

{{Specifications}}

## 浏览器兼容性

{{Compat}}

## 参见

- [Web Speech API](/zh-CN/docs/Web/API/Web_Speech_API)