SpeechSynthesis: speak() 方法

Baseline 已廣泛支援

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

SpeechSynthesis 介面的 speak() 方法會將一個 utterance 新增到佇列中;當它之前的任何其他 utterance 都朗讀完畢後,它就會被朗讀。

語法

js
speak(utterance)

引數

utterance

一個 SpeechSynthesisUtterance 物件。

返回值

無(undefined)。

示例

此程式碼片段摘自我們的 Speech synthesizer demo線上檢視)。當包含我們想要朗讀的文字的表單提交時,我們會(在其他操作中)建立一個包含此文字的新 utterance,然後透過將其作為引數傳遞給 speak() 來進行朗讀。

js
const synth = window.speechSynthesis;

// …

inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  for (const voice of voices) {
    if (voice.name === selectedOption) {
      utterThis.voice = voice;
    }
  }
  synth.speak(utterThis);
  inputTxt.blur();
};

規範

規範
Web Speech API
# dom-speechsynthesis-speak

瀏覽器相容性

另見