Window: speechSynthesis 属性
Window 对象的只读属性 speechSynthesis 返回一个 SpeechSynthesis 对象,这是使用 Web Speech API 语音合成功能的入口点。
值
一个 SpeechSynthesis 对象。
示例
在我们基本的 语音合成器演示 中,我们首先通过 window.speechSynthesis 获取 SpeechSynthesis 控制器的引用。定义了一些必要的变量后,我们使用 SpeechSynthesis.getVoices() 来检索可用语音列表,并用它们填充一个选择菜单,以便用户可以选择他们想要的语音。
在 inputForm.onsubmit 处理程序中,我们使用 preventDefault() 停止表单提交,创建一个包含文本 <input> 中文本的新 SpeechSynthesisUtterance 实例,将 utterance 的语音设置为 <select> 元素中选择的语音,并通过 SpeechSynthesis.speak() 方法开始 utterance 发声。
js
const synth = window.speechSynthesis;
const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");
function populateVoiceList() {
voices = synth.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);
voiceSelect.appendChild(option);
}
}
populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
inputForm.onsubmit = (event) => {
event.preventDefault();
const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
const selectedOption =
voiceSelect.selectedOptions[0].getAttribute("data-name");
utterThis.voice = voices.find((v) => v.name === selectedOption);
synth.speak(utterThis);
inputTxt.blur();
};
规范
| 规范 |
|---|
| Web Speech API # tts-section |
浏览器兼容性
加载中…