-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
120 lines (108 loc) · 2.59 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const main = document.querySelector("main");
const voicesSelect = document.getElementById("voices");
const textarea = document.getElementById("text");
const readButton = document.getElementById("read");
const toggleButton = document.getElementById("toggle");
const closeButton = document.getElementById("close");
const data = [
{
image: "drink",
text: "I'm Thirsty",
},
{
image: "food",
text: "I'm Hungry",
},
{
image: "tired",
text: "I'm Tired",
},
{
image: "hurt",
text: "I'm Hurt",
},
{
image: "happy",
text: "I'm Happy",
},
{
image: "angry",
text: "I'm Angry",
},
{
image: "sad",
text: "I'm Sad",
},
{
image: "scared",
text: "I'm Scared",
},
{
image: "outside",
text: "I Want To Go Outside",
},
{
image: "home",
text: "I Want To Go Home",
},
{
image: "school",
text: "I Want To Go To School",
},
{
image: "grandma",
text: "I Want To Go To Grandmas",
},
];
function createBox(item) {
const box = document.createElement("div");
const { image, text } = item;
box.classList.add("box");
box.innerHTML = `
<img src='https://github.com/bradtraversy/vanillawebprojects/blob/master/speech-text-reader/img/${image}.jpg?raw=true' alt="${text}"/>
<p class="info">${text}</p>
`;
box.addEventListener("click", () => handleSpeech(text, box));
main.appendChild(box);
}
data.forEach(createBox);
let voices = [];
function getVoices() {
voices = speechSynthesis.getVoices();
voices.forEach((voice) => {
const option = document.createElement("option");
option.value = voice.name;
option.innerText = `${voice.name} ${voice.lang}`;
voicesSelect.appendChild(option);
});
}
function handleSpeech(text, box) {
setTextMessage(text);
speakText();
box.classList.add("active");
setTimeout(() => box.classList.remove("active"), 800);
}
const message = new SpeechSynthesisUtterance();
function setTextMessage(text) {
message.text = text;
}
function speakText() {
speechSynthesis.speak(message);
}
function setVoice(e) {
message.voice = voices.find((voice) => voice.name === e.target.value);
}
// Event Listeners
toggleButton.addEventListener("click", () => {
document.getElementById("text-box").classList.toggle("show");
});
closeButton.addEventListener("click", () => {
document.getElementById("text-box").classList.remove("show");
});
speechSynthesis.addEventListener("voiceschanged", getVoices);
voicesSelect.addEventListener("change", setVoice);
readButton.addEventListener("click", () => {
setTextMessage(textarea.value);
speakText();
});
getVoices();