-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.js
94 lines (75 loc) · 2.5 KB
/
translator.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
(function(window) {
'use strict';
window.Translator = function(config) {
// Config-related properties;
this.outputTarget = config.outputTarget;
this.interimTarget = config.interimTarget || false;
this.translateLang = config.language;
// Defalt properties
this.isListening = false;
this.confidence = 0;
// Speech Recognition obj & properties
this.recognizer = new (window.SpeechRecognition || window.webkitSpeechRecognition);
this.recognizer.continuous = true;
this.recognizer.interimResults = true;
this.recognizer.lang = 'en-US';
this.recognizer.onresult = function(event) {
var interimResults = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
if (this.interimTarget) {
this.interimTarget.innerText = '';
}
interimResults = '';
this.outputTarget.innerHTML += capitalise(this.translate(event.results[i][0].transcript)) + '. ';
}
else {
interimResults += event.results[i][0].transcript;
}
}
if (this.interimTarget) {
this.interimTarget.innerText = interimResults;
}
}.bind(this);
this.recognizer.onerror = function(err) {
this.stopListening();
this.isListening = false;
this.outputTarget.innerHTML = 'There was an error! Have you denied access to your microphone?';
}.bind(this);
};
Translator.prototype.setTranslateLanguage = function(lang) {
this.translateLang = lang;
};
Translator.prototype.startListening = function() {
if (!this.isListening) {
this.recognizer.start();
}
this.isListening = true;
};
Translator.prototype.stopListening = function() {
if (this.isListening) {
this.recognizer.stop();
}
this.isListening = false;
};
Translator.prototype.toggleListening = function() {
if (this.isListening) {
this.stopListening();
}
else {
this.startListening();
}
};
Translator.prototype.translate = function(txt) {
var translateURL = ['translate.google.com/translate_a/t?client=t&hl=en&sl=en&tl=',
this.translateLang, '&ie=UTF-8&oe=UTF-8&multires=1&otf=2&ssel=0&tsel=0&sc=1&q=',
encodeURIComponent(txt)].join('');
var request = new XMLHttpRequest();
request.open('GET', 'http://www.corsproxy.com/' + translateURL, false);
request.send();
var arr = eval(request.response); // JSON.parse fails on this response.
var translatedText = arr[0][0][0];
return translatedText;
};
function capitalise(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
})(window);