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

浏览器兼容性

另见