This repository has been archived by the owner on Jul 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listen-for-snap.js
74 lines (73 loc) · 2.54 KB
/
listen-for-snap.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
var stopped = false;
var restart = function () {
if (stopped) {
return;
}
if (window.speechSynthesis.speaking) { // don't listen while speaking
setTimeout(restart, 500); // try again in half a second
return;
}
try {
window.speech_recognition.start();
console.log("Speech recognition started");
} catch (error) {
if (error.name === 'InvalidStateError') {
// delay needed, at least in Chrome 52
setTimeout(restart, 2000);
} else {
console.log(error);
}
}
};
var handle_result = function (callback, event) {
var spoken = event.results[0][0].transcript;
console.log("Confidence is " + event.results[0][0].confidence + " for " + spoken);
window.speech_recognition.stop();
invoke(callback, new List([spoken]));
};
var handle_error = function (callback, event) {
if (event.error === 'aborted') {
if (!stopped) {
console.log("Aborted so restarting speech recognition in half a second");
setTimeout(restart, 500);
}
return;
}
if (event.error === 'no-speech') {
window.speech_recognition.onend = null;
window.speech_recognition.onresult = null;
window.speech_recognition.stop();
}
console.log("Recognition error: " + event.error);
if (typeof callback === 'object') {
invoke(callback, new List([event.error]));
}
};
if (!window.speech_recognition) {
window.speech_recognition = (typeof SpeechRecognition === 'undefined') ?
new webkitSpeechRecognition() :
new SpeechRecognition();
}
window.speech_recognition.onresult = function (event) {
handle_result(spoken_callback, event);
};
window.speech_recognition.onerror = function (event) {
handle_error(error_callback, event);
};
window.speech_recognition.onend = function (event) {
console.log("recognition ended");
restart();
};
restart();
window.addEventListener("message",
function(message) {
if (message.data === 'hidden') {
stopped = true;
window.speech_recognition.stop();
console.log("Stopped because tab/window hidden.");
} else if (message.data === 'shown') {
stopped = false;
restart();
console.log("Restarted because tab/window shown.");
}
});