Window: speechSynthesis 屬性

Baseline 已廣泛支援

此功能已成熟,並可在多種裝置和瀏覽器版本上使用。自 2018 年 9 月以來,它已在各種瀏覽器中推出。

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

瀏覽器相容性

另見