forked from wesbos/JavaScript30
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
39 lines (33 loc) · 1.16 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
const voicesDropdown = document.querySelector('[name="voice"]')
const options = document.querySelectorAll('[type="range"], [name="text"]')
const speakButton = document.querySelector('#speak')
const stopButton = document.querySelector('#stop')
const text = document.querySelector('[name="text"]')
const synth = window.speechSynthesis
let voices = []
const populateVoices = () => {
voices = synth.getVoices()
voicesDropdown.innerHTML = voices
.filter(v => v.lang.includes('en'))
.map(voice =>
`<option value="${voice.name}">${voice.name} (${voice.lang})</option>`
)
.join('')
}
const speak = () => {
const utterance = new SpeechSynthesisUtterance(text.value)
utterance.voice = voices.find(voice => voice.name === voicesDropdown.value)
options.forEach(o => (utterance[o.name] = o.value))
synth.speak(utterance)
}
const changeVars = (doSpeak = true) => {
synth.cancel()
if (doSpeak) {
speak()
}
}
populateVoices()
speakButton.addEventListener('click', speak)
stopButton.addEventListener('click', changeVars.bind(null, false))
options.forEach(o => o.addEventListener('change', changeVars))
voicesDropdown.addEventListener('change', changeVars)