--- title: SpeechSynthesis slug: Web/API/SpeechSynthesis tags: - API - Experimental - Interface - SpeechSynthesis - Web Speech API - speech translation_of: Web/API/SpeechSynthesis ---
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
网页语音 API 的SpeechSynthesis
接口是语音服务的控制接口;它可以用于获取设备上关于可用的合成声音的信息,开始、暂停语音,或除此之外的其他命令。
SpeechSynthesis
也从它的父接口继承属性, {{domxref("EventTarget")}}.
SpeechSynthesis
处于暂停状态时, {{domxref("Boolean")}} 值返回 true
。true
。SpeechSynthesis
处于暂停状态, {{domxref("Boolean")}} 返回 true
。SpeechSynthesis
也从它的父接口继承方法, {{domxref("EventTarget")}}.
SpeechSynthesis
对象置为暂停状态。SpeechSynthesis
对象置为一个非暂停状态:如果已经暂停了则继续。在我们基础的 Speech synthesiser演示中 ,我们第一次用 window.speechSynthesis
抓取了关于语音播放控制器的参考。在定义了一些必要的变量后,我们用 {{domxref("SpeechSynthesis.getVoices()")}}获取了一列可用的声音并且用它们生成一列可选表单,这样用户能够选择他们想要的声音。
inputForm.onsubmit
的内部操作中,我们用preventDefault()阻止了表单的提交,创建了一个从{{htmlelement("input")}}文本框获取文本的新{{domxref("SpeechSynthesisUtterance")}}实例,在{{htmlelement("select")}}元素可选的声音设置成语音谈话的voice属性,然后通过{{domxref("SpeechSynthesis.speak()")}}方法开始语音播放。
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 | Status | Comment |
---|---|---|
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}} | {{Spec2('Web Speech API')}} |