SpeechSynthesis

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本上使用。自 2018 年 9 月以来,它已在各种浏览器中推出。

SpeechSynthesis 接口是 Web Speech API 的语音服务控制器接口;可以使用它来获取有关设备上可用语音合成语音的信息、开始和暂停语音,以及执行其他命令。

EventTarget SpeechSynthesis

实例属性

SpeechSynthesis 还继承了其父接口 EventTarget 的属性。

SpeechSynthesis.paused 只读

一个布尔值,如果 SpeechSynthesis 对象处于暂停状态,则返回 true

SpeechSynthesis.pending 只读

一个布尔值,如果语音队列包含尚未朗读的语音,则返回 true

SpeechSynthesis.speaking 只读

一个布尔值,如果当前正在朗读语音(即使 SpeechSynthesis 处于暂停状态),则返回 true

实例方法

SpeechSynthesis 还继承了其父接口 EventTarget 的方法。

SpeechSynthesis.cancel()

从语音队列中移除所有语音。

SpeechSynthesis.getVoices()

返回一个表示当前设备上所有可用语音的 SpeechSynthesisVoice 对象列表。

SpeechSynthesis.pause()

SpeechSynthesis 对象置于暂停状态。

SpeechSynthesis.resume()

SpeechSynthesis 对象置于非暂停状态:如果它已暂停,则恢复它。

SpeechSynthesis.speak()

将一个 utterance 添加到语音队列中;它将在队列中排在它之前的任何其他语音朗读完毕后进行朗读。

事件

使用 addEventListener() 或通过将事件监听器分配给此接口的 oneventname 属性来监听此事件。

voiceschanged

SpeechSynthesis.getVoices() 方法将返回的 SpeechSynthesisVoice 对象列表发生更改时触发。也可通过 onvoiceschanged 属性访问。

示例

首先,一个示例

js
let utterance = new SpeechSynthesisUtterance("Hello world!");
speechSynthesis.speak(utterance);

现在我们将看一个更全面的示例。在我们的 Speech synthesizer demo 中,我们首先使用 window.speechSynthesis 获取 SpeechSynthesis 控制器的引用。在定义了一些必要的变量后,我们使用 SpeechSynthesis.getVoices() 获取可用语音列表,并用它们填充一个 select 菜单,以便用户可以选择他们想要的语音。

inputForm.onsubmit 处理程序中,我们使用 preventDefault() 阻止表单提交,创建一个包含文本 <input> 中文本的新 SpeechSynthesisUtterance 实例,将语音设置为 <select> 元素中选定的语音,并通过 SpeechSynthesis.speak() 方法开始朗读该语音。

js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector(".txt");
const voiceSelect = document.querySelector("select");
const pitch = document.querySelector("#pitch");
const pitchValue = document.querySelector(".pitch-value");
const rate = document.querySelector("#rate");
const rateValue = document.querySelector(".rate-value");

let voices = [];

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");
  for (const voice of voices) {
    if (voice.name === selectedOption) {
      utterThis.voice = voice;
    }
  }
  utterThis.pitch = pitch.value;
  utterThis.rate = rate.value;
  synth.speak(utterThis);

  inputTxt.blur();
};

规范

规范
Web Speech API
# tts-section

浏览器兼容性

另见