SpeechSynthesis

Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

网页语音 API 的**SpeechSynthesis** 接口是语音服务的控制接口;它可以用于获取设备上关于可用的合成声音的信息,开始、暂停语音,或除此之外的其他命令。

属性

SpeechSynthesis 也从它的父接口继承属性,EventTarget.

SpeechSynthesis.paused 只读

SpeechSynthesis 处于暂停状态时, Boolean (en-US) 值返回 true

SpeechSynthesis.pending (en-US) 只读

当语音播放队列到目前为止保持没有说完的语音时, Boolean (en-US) 值返回 true

SpeechSynthesis.speaking (en-US) 只读

当语音谈话正在进行的时候,即使SpeechSynthesis处于暂停状态, Boolean (en-US) 返回 true

事件操作

方法

SpeechSynthesis 也从它的父接口继承方法, EventTarget.

SpeechSynthesis.cancel() (en-US)

移除所有语音谈话队列中的谈话。

SpeechSynthesis.getVoices()

返回当前设备所有可用声音的 SpeechSynthesisVoice (en-US)列表。

SpeechSynthesis.pause() (en-US)

SpeechSynthesis 对象置为暂停状态。

SpeechSynthesis.resume() (en-US)

SpeechSynthesis 对象置为一个非暂停状态:如果已经暂停了则继续。

SpeechSynthesis.speak() (en-US)

添加一个 utterance 到语音谈话队列;它将会在其他语音谈话播放完之后播放。

示例

在我们基础的 Speech synthesiser 演示中,我们第一次用 window.speechSynthesis抓取了关于语音播放控制器的参考。在定义了一些必要的变量后,我们用 SpeechSynthesis.getVoices()获取了一列可用的声音并且用它们生成一列可选表单,这样用户能够选择他们想要的声音。

inputForm.onsubmit 的内部操作中,我们用preventDefault()阻止了表单的提交,创建了一个从<input>文本框获取文本的新SpeechSynthesisUtterance实例,在<select>元素可选的声音设置成语音谈话的 voice 属性,然后通过SpeechSynthesis.speak() (en-US)方法开始语音播放。

var synth = window.speechSynthesis;

var inputForm = document.querySelector('form');
var inputTxt = document.querySelector('.txt');
var voiceSelect = document.querySelector('select');

var pitch = document.querySelector('#pitch');
var pitchValue = document.querySelector('.pitch-value');
var rate = document.querySelector('#rate');
var rateValue = document.querySelector('.rate-value');

var voices = [];

function populateVoiceList() {
  voices = synth.getVoices();

  for(i = 0; i < voices.length ; i++) {
    var option = document.createElement('option');
    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';

    if(voices[i].default) {
      option.textContent += ' -- DEFAULT';
    }

    option.setAttribute('data-lang', voices[i].lang);
    option.setAttribute('data-name', voices[i].name);
    voiceSelect.appendChild(option);
  }
}

populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

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

  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
  for(i = 0; i < voices.length ; i++) {
    if(voices[i].name === selectedOption) {
      utterThis.voice = voices[i];
    }
  }
  utterThis.pitch = pitch.value;
  utterThis.rate = rate.value;
  synth.speak(utterThis);

  inputTxt.blur();
}

规范

Specification
Web Speech API
# tts-section

浏览器兼容性

BCD tables only load in the browser

参见