Skip to content

Commit 6cbb134

Browse files
committed
js30 day 23
1 parent 3af2313 commit 6cbb134

File tree

2 files changed

+42
-8
lines changed

2 files changed

+42
-8
lines changed

23 - Speech Synthesis/index.html

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,6 @@ <h1>The Voiceinator 5000</h1>
2828

2929
</div>
3030

31-
<script>
32-
const msg = new SpeechSynthesisUtterance();
33-
let voices = [];
34-
const voicesDropdown = document.querySelector('[name="voice"]');
35-
const options = document.querySelectorAll('[type="range"], [name="text"]');
36-
const speakButton = document.querySelector('#speak');
37-
const stopButton = document.querySelector('#stop');
38-
</script>
3931
<script src="js/script.js"></script>
4032
</body>
4133
</html>

23 - Speech Synthesis/js/script.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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

Comments
 (0)