forked from 9jaswag/speechrec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
212 lines (184 loc) · 6.27 KB
/
main.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
class App {
constructor () {
window.SpeechRecognition = window.SpeechRecognition || webkitSpeechRecognition;
this.recognition = new SpeechRecognition();
this.synth = window.speechSynthesis;
this.icon = document.querySelector('i.fa.fa-microphone');
this.paragraph = document.createElement('p');
this.container = document.querySelector('.text-box');
this.sound = document.querySelector('.sound');
this.listening = false;
this.question = false;
this.appendParagraph();
this.voices = [];
this.initializeVoicePopulation();
this.handleMicIconClick();
this.watchRecognition();
this.cachedWeather = false;
}
appendParagraph() {
this.container.appendChild(this.paragraph);
}
populateVoiceList() {
if(typeof speechSynthesis === 'undefined') {
return;
}
this.voices = speechSynthesis.getVoices();
let i;
for(i = 0; i < this.voices.length ; i++) {
let option = document.createElement('option');
option.textContent = this.voices[i].name + ' (' + this.voices[i].lang + ')';
if(this.voices[i].default) {
option.textContent += ' -- DEFAULT';
}
option.setAttribute('data-lang', this.voices[i].lang);
option.setAttribute('data-name', this.voices[i].name);
document.getElementById("voiceSelect").appendChild(option);
}
}
initializeVoicePopulation() {
this.populateVoiceList();
if (typeof speechSynthesis !== 'undefined' && speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = this.populateVoiceList;
}
}
handleMicIconClick() {
this.icon.addEventListener('click', () => {
if (this.listening) {
this.recognition.stop();
return;
}
this.sound.play();
this.dictate();
});
}
watchRecognition() {
this.recognition.onstart = function() {
this.listening = true;
console.log('Speech recognition service has started');
};
this.recognition.onend = function() {
console.log('Speech recognition service disconnected');
};
}
dictate() {
console.log('dictating...');
this.recognition.start();
this.recognition.onresult = (event) => {
const speechToText = Array.from(event.results)
.map(result => result[0])
.map(result => result.transcript)
.join('');
this.paragraph.textContent = speechToText;
if (event.results[0].isFinal) {
this.container.scrollTo(0, this.container.scrollHeight);
this.paragraph = document.createElement('p');
this.appendParagraph();
this.handleRequest(speechToText);
}
};
// this.recognition.onend = this.recognition.start
}
speak(action) {
const utterThis = new SpeechSynthesisUtterance(action());
this.setVoice(utterThis);
this.synth.speak(utterThis);
}
setVoice(utterThis) {
const selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
let i;
for(i = 0; i < this.voices.length ; i++) {
if(this.voices[i].name === selectedOption) {
utterThis.voice = this.voices[i];
}
}
}
handleRequest(speech) {
if (speech.includes('what is the time')) {
this.speak(this.getTime);
};
if (speech.includes('what is today\'s date')) {
this.speak(this.getDate);
};
if (speech.includes('what is the weather in')) {
this.getWeather(speech);
};
if (speech.includes('open a url')) {
const utterThis = new SpeechSynthesisUtterance('what URL do you want to open?');
this.setVoice(utterThis);
this.synth.speak(utterThis);
this.recognition.abort();
this.recognition.stop();
this.question = true;
return;
};
if (speech.includes('open') && this.question) {
this.openUrl(speech.split(' ')[1]);
this.question = false;
};
}
getTime() {
const time = new Date(Date.now());
return `the time is ${time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })}`
}
getDate() {
const time = new Date(Date.now())
return `today is ${time.toLocaleDateString()}`;
}
getWeather(speech) {
self = this;
const url = `http://api.openweathermap.org/data/2.5/weather?q=${speech.split(' ')[5]}&appid=6aa90859f3e957ff6c77ec9b1bc86296&units=metric`
if ('caches' in window) {
/*
* Check if the service worker has already cached this city's weather
* data. If the service worker has the data, then display the cached
* data while the app fetches the latest data.
*/
caches.match(url).then(function(response) {
if (response) {
self.cachedWeather = true;
response.json().then(function updateFromCache(json) {
if (json.cod === '404') {
const utterThis = new SpeechSynthesisUtterance(`I cannot find the weather for ${speech.split(' ')[5]}`);
self.setVoice(utterThis);
self.synth.speak(utterThis);
return;
}
const utterThis = new SpeechSynthesisUtterance(`the weather condition in ${json.name} is mostly full of
${json.weather[0].description} at a temperature of ${json.main.temp} degrees Celcius`);
self.setVoice(utterThis);
self.synth.speak(utterThis);
});
}
});
}
fetch(url)
.then(function(response){
return response.json();
}).then(function(weather){
if (self.cachedWeather) {
return;
}
if (weather.cod === '404') {
const utterThis = new SpeechSynthesisUtterance(`I cannot find the weather for ${speech.split(' ')[5]}`);
self.setVoice(utterThis);
self.synth.speak(utterThis);
return;
}
const 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`);
self.setVoice(utterThis);
self.synth.speak(utterThis);
});
}
openUrl(url) {
window.open(`http://${url}`,'_newtab');
}
}
const speechRec = new App();
// add service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}