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