|
| 1 | +const msg = new SpeechSynthesisUtterance(); |
| 2 | +let voices = []; |
| 3 | +const voicesDropdown = document.querySelector('[name="voice"]'); |
| 4 | +const options = document.querySelectorAll('[type="range"], [name="text"]'); |
| 5 | +const speakButton = document.querySelector("#speak"); |
| 6 | +const stopButton = document.querySelector("#stop"); |
| 7 | + |
| 8 | +msg.text = document.querySelector('[name="text"]').value; |
| 9 | + |
| 10 | +function populateVoices() { |
| 11 | + voices = this.getVoices(); |
| 12 | + // console.log(voices); |
| 13 | + voicesDropdown.innerHTML = voices |
| 14 | + .filter((voice) => voice.lang.includes("en")) |
| 15 | + .map((voice) => `<option value="${voice.name}"> (${voice.lang})</option>`) |
| 16 | + .join(""); |
| 17 | +} |
| 18 | + |
| 19 | +function setVoice() { |
| 20 | + // console.log(this.value); |
| 21 | + msg.voice = voices.find((voice) => voice.name === this.value); |
| 22 | +} |
| 23 | + |
| 24 | +function toggle(startOver = true) { |
| 25 | + speechSynthesis.cancel(); |
| 26 | + if (startOver) { |
| 27 | + speechSynthesis.speak(msg); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +function setOption() { |
| 32 | + console.log(this.name, this.value); |
| 33 | + msg[this.name] = this.value; |
| 34 | + toggle(); |
| 35 | +} |
| 36 | + |
| 37 | +speechSynthesis.addEventListener("voiceschanged", populateVoices); |
| 38 | +voicesDropdown.addEventListener("change", setVoice); |
| 39 | +options.forEach((option) => option.addEventListener("change", setOption)); |
| 40 | +speakButton.addEventListener("click", toggle); |
| 41 | +// stopButton.addEventListener("click", toggle.bind(null, false)); |
| 42 | +stopButton.addEventListener("click", () => toggle(false)); |
0 commit comments