This repository has been archived by the owner on Mar 27, 2023. It is now read-only.
forked from tstachlewski/voice-translator-app
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvoice-translator.js
255 lines (220 loc) · 7.97 KB
/
voice-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
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// AWS configuration
var awsRegion = "us-east-1";
var requestId;
var source_language = "en";
var target_language = "es";
function babel_select(mode, language) {
document.getElementById(mode + "_" + language).src = "./graphics/flags/" + language + "2.png";
if (mode == "source") {
source_language = language;
} else {
target_language = language;
}
}
function babel_unselect_source() {
document.getElementById("source_en").src = "./graphics/flags/en.png";
// document.getElementById("source_gb").src = "./graphics/flags/gb.png";
document.getElementById("source_es").src = "./graphics/flags/es.png";
// document.getElementById("source_ca").src = "./graphics/flags/ca.png";
// document.getElementById("source_fr").src = "./graphics/flags/fr.png";
}
function babel_unselect_target() {
document.getElementById("target_en").src = "./graphics/flags/en.png";
document.getElementById("target_gb").src = "./graphics/flags/gb.png";
document.getElementById("target_de").src = "./graphics/flags/de.png";
document.getElementById("target_pl").src = "./graphics/flags/pl.png";
document.getElementById("target_es").src = "./graphics/flags/es.png";
document.getElementById("target_ca").src = "./graphics/flags/ca.png";
document.getElementById("target_fr").src = "./graphics/flags/fr.png";
document.getElementById("target_ja").src = "./graphics/flags/ja.png";
document.getElementById("target_ru").src = "./graphics/flags/ru.png";
document.getElementById("target_it").src = "./graphics/flags/it.png";
document.getElementById("target_sv").src = "./graphics/flags/sv.png";
}
function babel_stop() {
document.getElementById("stop_button").src = "./graphics/stop2.png";
document.getElementById("start_button").src = "./graphics/start.png";
document.getElementById("stop_button").classList.remove("clickableimage");
document.getElementById("start_button").classList.add("clickableimage");
}
function babel_start() {
document.getElementById("stop_button").src = "./graphics/stop.png";
document.getElementById("start_button").src = "./graphics/start2.png";
document.getElementById("stop_button").classList.add("clickableimage");
document.getElementById("start_button").classList.remove("clickableimage");
}
AWS.config.update({
region: awsRegion,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId
})
});
// S3 object for storing input and output audio
var s3 = new AWS.S3({
apiVersion: "2006-03-01",
params: { Bucket: bucketName },
region: awsRegion
});
// Define variables for audio recorder
var recorder;
var recorderInput;
var getUserMediaStream;
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext;
// Get buttons from DOM
var recordStartButton = document.getElementById("start_button");
var recordStopButton = document.getElementById("stop_button");
// Add click event callbacks to buttons
recordStartButton.addEventListener("click", startRecording);
recordStopButton.addEventListener("click", stopRecording);
// Generate unique identifiers
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
}
// Check if URL returns HTTP 200 OK
function urlExists(url) {
var http = new XMLHttpRequest();
http.open("HEAD", url, false);
http.send();
return http.status == 200;
}
// Polling for result
function poll(fn, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
var checkCondition = function(resolve, reject) {
// If the condition is met, we're done!
var result = fn();
if (result) {
resolve(result);
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(checkCondition, interval, resolve, reject);
}
// Didn't match and too much time, reject!
else {
reject(new Error("timed out for " + fn + ": " + arguments));
}
};
return new Promise(checkCondition);
}
//TODO Change the function for showing the transcript value instead of processing AFTER executing lamdba function
// Adjust buttons and message for processing
function processingView() {
// Show processing message
document.getElementById("processing").style.display = "inline";
// Disable all buttons
recordStartButton.disabled = true;
recordStopButton.disabled = true;
}
// Adjust buttons and message for recording
function recordingView() {
// Hide processing message
document.getElementById("processing").style.display = "none";
// Hide audio playback
document.getElementById("audio-output").style.display = "none";
// Disable all buttons
recordStartButton.disabled = true;
recordStopButton.disabled = false;
}
// Reset buttons and hide messages
function resetView() {
// Hide processing message
document.getElementById("processing").style.display = "none";
// Hide audio playback
document.getElementById("audio-output").style.display = "none";
// Disable all buttons
recordStartButton.disabled = false;
recordStopButton.disabled = true;
}
// Generate request ID
function generateRequestId() {
return guid();
}
// Record audio with device microphone
function startRecording() {
audioContext = new AudioContext();
// Adjust buttons and message for recording
recordingView();
// Define constraints object for MediaStream
var constraints = { audio: true, video: false };
// Access MediaDevices to get audio stream
navigator.mediaDevices
.getUserMedia(constraints)
.then(function(stream) {
getUserMediaStream = stream;
recorderInput = audioContext.createMediaStreamSource(stream);
// Create Recorder.js object and start recording
recorder = new Recorder(recorderInput, { numChannels: 1 });
recorder.record();
})
.catch(function(err) {
alert(err);
// Reset buttons and message in case of failure
resetView();
// Inform user that recording failed (most likely was blocked by browser due
// to insecure origin)
alert("....Recording failed, try using Firefox or local copy of the app from your machine.");
});
}
function stopRecording() {
// Reset buttons and message
resetView();
// Stop recording with Recorder.js object
recorder.stop();
// Stop microphone and get recorded audio
getUserMediaStream.getAudioTracks()[0].stop();
// Pass blob with audio data to callback
recorder.exportWAV(uploadAudioRecording);
}
function uploadAudioRecording(blob) {
// Show processing phase in the UI
processingView();
// Generate unique ID for upload audio file request
requestId = generateRequestId();
// Create key for S3 object and upload input audio file
var inputKey = "input/" + requestId + ".wav";
s3.upload(
{
Key: inputKey,
Body: blob
},
function(err, data) {
if (err) {
return alert("There was an error uploading your recording: ", err.message);
} else {
var lambda = new AWS.Lambda({ region: awsRegion, apiVersion: "2015-03-31" });
var input = {
FunctionName: lambdaFunction,
InvocationType: "RequestResponse",
LogType: "None",
Payload: JSON.stringify({
bucket: bucketName,
key: inputKey,
sourceLanguage: source_language,
targetLanguage: target_language
})
};
lambda.invoke(input, function(err, data) {
if (err) {
console.log(err);
alert("There was a problem with Lambda function!!! ");
} else {
var resultUrl = data.Payload.replace(/['"]+/g, "");
resetView();
// Hide audio playback
document.getElementById("audio-output").style.display = "inline";
document.getElementById("audio-output").innerHTML =
'<audio controls><source src="' + resultUrl + '" type="audio/mpeg"></audio><br/>';
}
});
}
}
);
}