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 |
瀏覽器相容性
載入中…