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