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

浏览器兼容性

另见