SpeechSynthesis: getVoices() 方法
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 |
浏览器兼容性
加载中…