SpeechSynthesisUtterance:text 屬性

Baseline 已廣泛支援

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

SpeechSynthesisUtterance 介面的 text 屬性獲取和設定當語音合成時要朗讀的文字。

文字可以提供為純文字,或格式良好的 SSML 文件。SSML 標籤將被不支援 SSML 的裝置移除。

一個字串,表示要合成的文字。每個 utterance 中可朗讀的文字最大長度為 32,767 個字元。

示例

js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");

const voices = synth.getVoices();

// …

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;
    }
  }
  console.log(utterThis.text);
  synth.speak(utterThis);
  inputTxt.blur();
};

規範

規範
Web Speech API
# dom-speechsynthesisutterance-text

瀏覽器相容性

另見