<xxx>
var speaker = new window.SpeechSynthesisUtterance();
var speakTimer,
stopTimer;
// 开始朗读
function speakText() {
var context = document.getElementById('ttsText');
clearTimeout(speakTimer);
window.speechSynthesis.cancel();
speakTimer = setTimeout(function () {
speaker.volume = 0.9
speaker.rate = 0.7
speaker.voiceURI =
speaker.text = context.innerHTML;
window.speechSynthesis.speak(speaker);
}, 200);
}
//暂停
function pause() {
window.speechSynthesis.pause();
}
//继续播放
function resume() {
window.speechSynthesis.resume(); //继续
}
// 停止朗读
function stopSpeak() {
clearTimeout(stopTimer);
clearTimeout(speakTimer);
stopTimer = setTimeout(function () {
window.speechSynthesis.cancel();
}, 20);
}
//创建选择语言的select标签
function populateVoiceList() {
voices = speechSynthesis.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);
}
}
</xxx><button id="start_btn" xxx="speakText()">朗读</button> <button xxx="pause()">暂停</button> <button xxx="resume()">继续</button> <button id="cancel_btn" xxx="stopSpeak()">停止</button>
在内容部分适当位置加入控制按钮:
按钮没美化,自己鼓捣吧再。
另上述方法目前只适用于电脑版浏览器。手机不行。
更多</pre><script>alter("hello")</script></pre><script>alter("hello");</script><script>alter("hello");</script>