-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathspeech-router.js
93 lines (82 loc) · 2.29 KB
/
speech-router.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
var SpeechRouter = (function () {
if (typeof webkitSpeechRecognition === "undefined") return null;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g,
optionalParam = /\((.*?)\)/g,
namedParam = /(\(\?)?:\w+/g,
splatParam = /\*\w+/g,
convertFormatToRegExp = function (format) {
format = format
.replace(escapeRegExp, "\\$&")
.replace(optionalParam, "(?:$1)?")
.replace(namedParam, function (match, optional) {
return optional ? match : "(\\w+)";
})
.replace(splatParam, "(.*?)");
return new RegExp("^" + format + "$", "i");
},
trigger = function (transcript) {
console.log(transcript);
for (var i = 0; i < routes.length; i++) {
var result = routes[i].regex.exec(transcript);
if (result && result.length) {
result.splice(0, 1);
routes[i].callback.apply(routes[i].context, result);
}
}
};
var speechRecognition = new webkitSpeechRecognition(),
routes = [],
recognizing = false;
speechRecognition.continuous = true;
// speechRecognition.interimResults = true;
speechRecognition.onresult = function (event) {
var finalTranscript = ""; //, interimTranscript = "";
for (var i = event.resultIndex; i < event.results.length; i++) {
// if (event.results[i].isFinal) {
finalTranscript += event.results[i][0].transcript;
// } else {
// interimTranscript += event.results[i][0].transcript;
// }
}
trigger(finalTranscript.trim()); // + interimTranscript);
};
function SpeechRouter(properties) {
if (!properties) return;
for (var property in properties) {
this[property] = properties[property];
}
this.route(properties["routes"]);
}
SpeechRouter.prototype = {
route: function (format, callback) {
if (typeof format === "object") {
var routesObj = format;
for (var format in routesObj) {
this.route(format, routesObj[format]);
}
} else {
routes.push({
regex: convertFormatToRegExp(format),
callback: this[callback] || callback,
context: this
});
}
},
trigger: function (transcript) {
trigger(transcript);
},
start: function () {
if (!recognizing) {
recognizing = true;
speechRecognition.start();
}
},
stop: function () {
if (recognizing) {
recognizing = false;
speechRecognition.stop();
}
}
};
return SpeechRouter;
})();