SpeechSynthesisUtterance
Baseline 廣泛可用 *
SpeechSynthesisUtterance 介面是 Web Speech API 的一部分,用於表示一個語音請求。它包含了語音服務應讀取的內容以及如何讀取的資訊(例如,語言、音高和音量)。
建構函式
SpeechSynthesisUtterance()-
返回一個新的
SpeechSynthesisUtterance物件例項。
例項屬性
SpeechSynthesisUtterance 還繼承了其父介面 EventTarget 的屬性。
SpeechSynthesisUtterance.lang-
獲取和設定語音的語言。
SpeechSynthesisUtterance.pitch-
獲取和設定語音的音高。
SpeechSynthesisUtterance.rate-
獲取和設定語音的語速。
SpeechSynthesisUtterance.text-
獲取和設定語音合成時將要朗讀的文字。
SpeechSynthesisUtterance.voice-
獲取和設定用於朗讀語音的語音。
SpeechSynthesisUtterance.volume-
獲取和設定語音的音量。
事件
使用 addEventListener() 或將事件監聽器分配給此介面的 oneventname 屬性來監聽這些事件。
示例
在我們提供的基本 語音合成器演示中,我們首先使用 window.speechSynthesis 獲取 SpeechSynthesis 控制器的引用。在定義了一些必要的變數後,我們使用 SpeechSynthesis.getVoices() 獲取可用語音列表,並用它們填充一個 select 選單,以便使用者可以選擇他們想要的語音。
在 inputForm.onsubmit 處理程式中,我們使用 preventDefault() 阻止表單提交,使用 constructor 建立一個新的語音例項,其中包含來自文字 <input> 的文字,將語音的 voice 設定為 <select> 元素中選擇的語音,並透過 SpeechSynthesis.speak() 方法開始朗讀語音。
js
const synth = window.speechSynthesis;
const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");
let voices;
function loadVoices() {
voices = synth.getVoices();
for (const [i, voice] of voices.entries()) {
const option = document.createElement("option");
option.textContent = `${voice.name} (${voice.lang})`;
option.value = i;
voiceSelect.appendChild(option);
}
}
// in Google Chrome the voices are not ready on page load
if ("onvoiceschanged" in synth) {
synth.onvoiceschanged = loadVoices;
} else {
loadVoices();
}
inputForm.onsubmit = (event) => {
event.preventDefault();
const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
utterThis.voice = voices[voiceSelect.value];
synth.speak(utterThis);
inputTxt.blur();
};
規範
| 規範 |
|---|
| Web Speech API # speechsynthesisutterance |
瀏覽器相容性
載入中…