├── index.html └── script.js /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /script.js: -------------------------------------------------------------------------------- 1 | const playButton = document.getElementById('play-button') 2 | const pauseButton = document.getElementById('pause-button') 3 | const stopButton = document.getElementById('stop-button') 4 | const textInput = document.getElementById('text') 5 | const speedInput = document.getElementById('speed') 6 | let currentCharacter 7 | 8 | playButton.addEventListener('click', () => { 9 | playText(textInput.value) 10 | }) 11 | pauseButton.addEventListener('click', pauseText) 12 | stopButton.addEventListener('click', stopText) 13 | speedInput.addEventListener('input', () => { 14 | stopText() 15 | playText(utterance.text.substring(currentCharacter)) 16 | }) 17 | 18 | const utterance = new SpeechSynthesisUtterance() 19 | utterance.addEventListener('end', () => { 20 | textInput.disabled = false 21 | }) 22 | utterance.addEventListener('boundary', e => { 23 | currentCharacter = e.charIndex 24 | }) 25 | 26 | function playText(text) { 27 | if (speechSynthesis.paused && speechSynthesis.speaking) { 28 | return speechSynthesis.resume() 29 | } 30 | if (speechSynthesis.speaking) return 31 | utterance.text = text 32 | utterance.rate = speedInput.value || 1 33 | textInput.disabled = true 34 | speechSynthesis.speak(utterance) 35 | } 36 | 37 | function pauseText() { 38 | if (speechSynthesis.speaking) speechSynthesis.pause() 39 | } 40 | 41 | function stopText() { 42 | speechSynthesis.resume() 43 | speechSynthesis.cancel() 44 | } --------------------------------------------------------------------------------