-
Notifications
You must be signed in to change notification settings - Fork 1
/
transcriber.html
446 lines (379 loc) · 13.5 KB
/
transcriber.html
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
<!--
# Copyright 2018 IBM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-->
<html>
<head>
<title>Audio Stream for Speech to Text</title>
</head>
<body>
<div id="no-script">
This application needs JavaScript enabled in your browser!
</div>
<div id="status-microphone">
</div>
<div id="status-socket">
</div>
<div id='audio-supported'>
<div>Click Record to start streaming audio, and Stop to stop.</div>
<div>
<button type="button" id="id_recordButton">
Record
</button>
<button type="button" id="id_stopButton">
Stop
</button>
<div id="id_datastore"></div>
</div>
</div>
<div id='audio-notsuppported'>
<div>Not able to capture audio in this browser.</div>
</div>
<div id='transcription'>
</div>
<!--
<div>
<audio id="id_player" controls></audio>
</div>
-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
var websocket = null;
var audioContext = window.AudioContext || window.webkitAudioContext;
var context = new audioContext();
$(document).ready(function() {
allofit();
});
$(document).unload(function() {
websocketDisconnect();
});
function allofit() {
javascriptCheck();
websocketConnect();
//setupAudioListener();
audioButtonStuff();
dataCacheStuff();
audioCheckStuff();
$('#id_stopButton').hide();
}
// ******************************************************
// Establish new context for a fresh recording
// ******************************************************
function flushAudioContext() {
context.close().then(function() {
context = new audioContext();
});
}
// ******************************************************
// if javascript is enabled on the browser then can
// remove the warning message
// ******************************************************
function javascriptCheck() {
$('#no-script').remove();
}
// ******************************************************
// Web Socket stuff
// ******************************************************
function websocketConnect() {
var uri = determineWSUri()
//console.log("connect", uri);
websocket = new WebSocket(uri);
//$('#id_startButton').data("webSocket", ws);
setupSockectListeners();
}
function websocketDisconnect() {
if (websocket) {
websocket.disconnect();
}
}
function determineWSUri() {
var wsUri = "ws:";
var loc = window.location;
//console.log(loc);
if (loc.protocol === "https:") {
wsUri = "wss:";
}
// This needs to point to the web socket in the Node-RED flow
// ... in this case it's ws/stt
wsUri += "//" + loc.host + "/ws/stt";
return wsUri;
}
// ******************************************************
// We have a notification from the server, let's check
// if its a transcription
// ******************************************************
function setupSockectListeners() {
websocket.onmessage = function(msg) {
//console.log('data received from websocket', msg);
if (msg.data) {
console.log(msg.data);
var data = JSON.parse(msg.data);
if (data.results && (data.results instanceof Array)) {
console.log(data.results[0]);
if (data.results[0].alternatives &&
(data.results[0].alternatives instanceof Array)) {
console.log(data.results[0].alternatives[0]);
if (data.results[0].alternatives[0].transcript) {
$('#transcription').text(data.results[0].alternatives[0].transcript);
}
}
}
}
}
websocket.onopen = function() {
$('#status-socket').text('connected');
console.log("connected");
}
websocket.onclose = function() {
$('#status-socket').text('not connected');
// in case of lost connection tries to reconnect every 2 secs
setTimeout(websocketConnect, 2000);
}
}
function audioButtonStuff() {
var stopButton = $('#id_stopButton');
var recordButton = $('#id_recordButton');
(function() {
recordButton.click(
function() {
var message = {
action: 'start',
'content-type': 'audio/wav',
'interim_results': true
};
websocket.send(JSON.stringify(message));
recordButton.hide();
stopButton.show();
requestAudioRecording();
});
stopButton.click(
function() {
recordButton.show();
stopButton.hide();
processAudioOnlyStream();
localStream = stopButton.data("mediaStream");
if (localStream) {
localStream.getTracks().forEach(function(track) {
track.stop();
});
}
flushAudioContext();
});
})();
}
function resetAudioButtons() {
$('#id_stopButton').hide();
$('#id_recordButton').hide();
}
// ******************************************************
// This flushes the channel buffers, which are held as data
// in a datastore field on the page.
// ******************************************************
function dataCacheStuff() {
console.log('Flushing the Channels');
//$('#id_datastore').removeData();
var leftchannel = new Array();
var rightchannel = new Array();
leftchannel.length = 0;
rightchannel.length = 0;
$('#id_datastore').data("leftchannel", leftchannel);
$('#id_datastore').data("rightchannel", rightchannel);
$('#id_datastore').data("recording", false);
$('#id_datastore').data("recordlength", 0);
}
// ******************************************************
// Audio support checks
// ******************************************************
function audioCheckStuff() {
var supported = false;
if (isUserMediaSupported()) {
supported = true;
$('#audio-notsuppported').hide();
}
$('#id_datastore').data("audiosupported", supported);
}
function isUserMediaSupported() {
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
function getUserMediaFunction() {
return (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
}
// **********************************************
// The record button has been pressed, so first there
// is a user prompt to allow recording to happen
// **********************************************
function requestAudioRecording() {
navigator.getUserMedia = getUserMediaFunction();
navigator.getUserMedia({
audio: true
},
startAudioRecording,
notAllowed
);
}
function notAllowed(e) {
var etxt = "Media Persmission Denied - " + e.name;
setStatusMessage('e', etxt);
resetAudioButtons();
}
// **********************************************
// Recording is being permitted.
// **********************************************
function startAudioRecording(localMediaStream) {
console.log('Start Audio Recording');
dataCacheStuff();
$('#id_stopButton').data("mediaStream", localMediaStream);
sampleRate = context.sampleRate;
// creates a gain node
volume = context.createGain();
// creates an audio node from the microphone incoming stream
audioInput = context.createMediaStreamSource(localMediaStream);
// connect the stream to the gain node
audioInput.connect(volume);
/* From the spec: This value controls how frequently the audioprocess event is
dispatched and how many sample-frames need to be processed each call.
Lower values for buffer size will result in a lower (better) latency.
Higher values will be necessary to avoid audio breakup and glitches */
var bufferSize = 2048;
//Stick to 2 input and 2 output channel
var recorder;
if (!context.createScriptProcessor) {
recorder = context.createJavaScriptNode(bufferSize, 2, 2);
} else {
recorder = context.createScriptProcessor(bufferSize, 2, 2);
}
if (recorder) {
recorder.onaudioprocess = function(e) {
var recording = $('#id_datastore').data("recording");
if (recording) {
console.log('recording');
var left = e.inputBuffer.getChannelData(0);
var right = e.inputBuffer.getChannelData(1);
//we clone the samples
var leftchannel = $('#id_datastore').data("leftchannel");
var rightchannel = $('#id_datastore').data("rightchannel");
if (leftchannel && rightchannel) {
leftchannel.push(new Float32Array(left));
rightchannel.push(new Float32Array(right));
recordingLength = bufferSize + $('#id_datastore').data("recordlength");
$('#id_datastore').data("recordlength", recordingLength)
}
}
};
// we connect the recorder
volume.connect(recorder);
recorder.connect(context.destination);
console.log('setting recording to on');
$('#id_datastore').data("recording", true);
}
}
// **********************************************
// Stop Recording button has been pressed. No Cancels allowed
// **********************************************
function processAudioOnlyStream() {
if ($('#id_datastore').data("recording")) {
$('#id_datastore').data("recording", false);
var leftchannel = $('#id_datastore').data("leftchannel");
var rightchannel = $('#id_datastore').data("rightchannel");
var recordingLength = $('#id_datastore').data("recordlength");
console.log('recordingLength ', recordingLength);
var leftBuffer = createAudioBuffer(leftchannel, recordingLength);
var rightBuffer = createAudioBuffer(rightchannel, recordingLength);
var interleaved = interleave(leftBuffer, rightBuffer);
// we create our wav file
var buffer = new ArrayBuffer(44 + interleaved.length * 2);
var view = new DataView(buffer);
// RIFF chunk descriptor
writeUTFBytes(view, 0, 'RIFF');
view.setUint32(4, 44 + interleaved.length * 2, true);
writeUTFBytes(view, 8, 'WAVE');
// FMT sub-chunk
writeUTFBytes(view, 12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
// stereo (2 channels)
view.setUint16(22, 2, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * 4, true);
view.setUint16(32, 4, true);
view.setUint16(34, 16, true);
// data sub-chunk
writeUTFBytes(view, 36, 'data');
view.setUint32(40, interleaved.length * 2, true);
// write the PCM samples
var lng = interleaved.length;
var index = 44;
var volume = 1;
for (var i = 0; i < lng; i++) {
view.setInt16(index, interleaved[i] * (0x7FFF * volume), true);
index += 2;
}
// our final binary blob
var blob = new Blob([view], {
type: 'audio/wav'
});
sendToServer(blob);
}
}
function createAudioBuffer(channelBuffer, recordingLength) {
var result = new Float32Array(recordingLength);
var offset = 0;
var lng = channelBuffer.length;
for (var i = 0; i < lng; i++) {
var buffer = channelBuffer[i];
result.set(buffer, offset);
offset += buffer.length;
}
return result;
}
function interleave(leftChannel, rightChannel) {
var length = leftChannel.length + rightChannel.length;
var result = new Float32Array(length);
var inputIndex = 0;
for (var index = 0; index < length;) {
result[index++] = leftChannel[inputIndex];
result[index++] = rightChannel[inputIndex];
inputIndex++;
}
return result;
}
function writeUTFBytes(view, offset, string) {
var lng = string.length;
for (var i = 0; i < lng; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
// ********************************************
// Will be sending the audio to be processed.
// Send to a holding function on the parent page which should know how to handle
// ********************************************
function sendToServer(audioBlob) {
console.log('sending blob through web socket');
console.log(audioBlob);
websocket.send(audioBlob);
setTimeout(() => {
console.log('sending stop through web socket');
var message = {
action: 'stop'
};
websocket.send(JSON.stringify(message));
}, 1000);
}
</script>
</body>
<html>