-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
93 lines (82 loc) · 2.55 KB
/
app.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
window.SpeechRecognition =
window.webkitSpeechRecognition || window.SpeechRecognition;
const synth = window.speechSynthesis;
const recognition = new SpeechRecognition();
const icon = document.querySelector("i.fa.fa-microphone");
const saveButton = document.querySelector("i.fa.fa-download");
let paragraph = document.createElement("p");
let container = document.querySelector(".text-box");
container.appendChild(paragraph);
const sound = document.querySelector(".sound");
icon.addEventListener("click", () => {
sound.play();
dictate();
});
saveButton.addEventListener("click", () => {
saveFunction();
});
const saveFunction = () => {
const file = new Blob([paragraph.textContent], { type: "text/plain" });
const anchor = document.createElement("a");
anchor.href = URL.createObjectURL(file);
anchor.download = "save.txt";
anchor.click();
};
const dictate = () => {
recognition.start();
recognition.onresult = (event) => {
const speechToText = event.results[0][0].transcript;
paragraph.textContent = speechToText;
console.log(paragraph.textContent);
if (event.results[0].isFinal) {
if (speechToText.includes("what is the time")) {
speak(getTime);
}
if (speechToText.includes("what is today's date")) {
speak(getDate);
}
if (speechToText.includes("what is the weather in")) {
getTheWeather(speechToText);
}
}
};
};
const speak = (action) => {
utterThis = new SpeechSynthesisUtterance(action());
synth.speak(utterThis);
};
const getTime = () => {
const time = new Date(Date.now());
return `the time is ${time.toLocaleString("en-US", {
hour: "numeric",
minute: "numeric",
hour12: true,
})}`;
};
const getDate = () => {
const time = new Date(Date.now());
return `today is ${time.toLocaleDateString()}`;
};
const getTheWeather = (speech) => {
fetch(
`http://api.openweathermap.org/data/2.5/weather?q=${
speech.split(" ")[5]
}&appid=58b6f7c78582bffab3936dac99c31b25&units=metric`
)
.then(function (response) {
return response.json();
})
.then(function (weather) {
if (weather.cod === "404") {
utterThis = new SpeechSynthesisUtterance(
`I cannot find the weather for ${speech.split(" ")[5]}`
);
synth.speak(utterThis);
return;
}
utterThis = new SpeechSynthesisUtterance(
`the weather condition in ${weather.name} is mostly full of ${weather.weather[0].description} at a temperature of ${weather.main.temp} degrees Celcius`
);
synth.speak(utterThis);
});
};