<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>
在內容部分適當位置加入控制按鈕:
按鈕沒美化,自己鼓搗吧再。
另上述方法目前只適用于電腦版瀏覽器。手機不行。