-
Notifications
You must be signed in to change notification settings - Fork 0
/
callbot_vosk.js
285 lines (238 loc) · 7.17 KB
/
callbot_vosk.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
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
const fs = require('fs');
const recorder = require('node-record-lpcm16');
var vosk = require('./module/vosk');
const audio = require('./audio');
vosk.setLogLevel(0);
MODEL_PATH = "model"
const model = new vosk.Model(MODEL_PATH);
const sampleRateHertz = 44100;
const recording = recorder.record({
// Other options, see https://www.npmjs.com/package/node-record-lpcm16#options
channels: 1,
sampleRate: sampleRateHertz,
endOnSilence: false,
keepSilence: true,
recorder: 'sox', // Try also "arecord" or "sox"
});
var audio_transcription;
class VAD {
constructor() {
this.id = "VADClass";
this._speechTime = 0;
this._silenceTime = 0;
this._isSpeech = false;
this._speechFrames = []
}
get speechTime() {
return this._speechTime;
}
set speechTime(speechTime) {
this._speechTime = speechTime;
}
get silenceTime() {
return this._silenceTime;
}
set silenceTime(silenceTime) {
this._silenceTime = silenceTime;
}
get isSpeech() {
return this._isSpeech;
}
set isSpeech(isSpeech) {
this._isSpeech = isSpeech;
}
clearSpeechFrames() {
this._speechFrames = [];
}
writeWav() {
if (this._speechFrames.length > 0) {
const filename = `test_${new Date().getTime()}.wav`;
const file = new FileWriter(filename, { sampleRate: sampleRateHertz, channels: 1 });
var frames = this._speechFrames;
var that = this;
for (let i = 0; i < frames.length; i++) {
file.write(frames[i], function () {
if (i === frames.length - 1) {
file.end();
console.log(filename, ' - completed')
//that.getSTTResult(filename);
}
});
}
}
}
updateChunkData(frameData) {
// arrayBuffer = [ 4, 4, 5, 6, 6, 7, 8, 9 ];
var arryBufferInt16 = new Int16Array(frameData.buffer);
var arrayMean = arryBufferInt16.reduce((a, b) => a + b * b / arryBufferInt16.length, 0);
arrayMean = Math.sqrt(arrayMean);
arrayMean /= 32767;
var speechTr = 0.005;
// frame buffer time
var frameTime = arryBufferInt16.length / sampleRateHertz;
// check if current frame is speech
if (arrayMean > speechTr) {
this.speechTime = this.speechTime + frameTime;
if (this.speechTime > 0.1) {
// update speech
this.isSpeech = true;
// reset silence time
this.silenceTime = 0
}
// push speech frames
this._speechFrames.push(frameData);
}
else {
this.silenceTime = this.silenceTime + frameTime;
// silence case
if (this.isSpeech && this.silenceTime >= 0.5) {
// set no speech
this.speechTime = 0;
this.isSpeech = false;
//console.log(arrayMean);
this.clearSpeechFrames();
}
}
}
updateInformation(arrayBuffer) {
// calculate chunk data
var chunkSize = 1600; // 50ms
var chunkNum = Math.floor(arrayBuffer.byteLength / chunkSize);
// update chunk vad information
for (let i = 0; i < chunkNum - 1; i++) {
var stIdx = i * chunkSize;
var endIdx = (i + 1) * chunkSize;
this.updateChunkData(arrayBuffer.slice(stIdx, endIdx));
}
// update final chunk data in this frame
this.updateChunkData(arrayBuffer.slice((chunkNum - 1) * chunkSize, arrayBuffer.byteLength));
}
sayStatus() {
if (this.isSpeech) {
console.log("speaking");
}
else {
console.log("silent");
}
}
}
vad = new VAD()
class RestartableRecogniser {
constructor({ model, textCallback }) {
this.model = model;
this.textCallback = textCallback;
this.recStream = null;
this.started = false;
}
start() {
if (this.started) {
return;
}
this.recStream = new vosk.Recognizer({ model: model, sampleRate: sampleRateHertz });
this.started = true;
}
stop() {
if (!this.started) {
return;
}
this._clearRecStream();
this.started = false;
}
restart() {
this.stop();
this.start();
}
write(buf) {
if (!this.started) {
return;
}
if (this.recStream.acceptWaveform(buf))
this.textCallback(this.recStream.result().text);
else
this.textCallback(this.recStream.partialResult().partial);
}
_clearRecStream() {
if (!this.recStream) {
return;
}
let result = this.recStream.finalResult();
this.textCallback(result.text)
this.recStream.free();
this.recStream = null;
}
}
var recognizer = new RestartableRecogniser({
model: model,
textCallback: (data) => {
if (data) {
//console.log(data);
//var audio_is_playing = audio.audioIsPlaying();
//console.log('@vosk audio is playing', audio_is_playing);
//if (audio_is_playing == false)
audio_transcription = data;
//else audio_transcription = undefined;
}
},
});
//
function completedFn(data, completed) {
recognizer.write(data);
var statusBefore = vad.isSpeech;
vad.updateInformation(data);
var statusNow = vad.isSpeech;
if (statusBefore && !statusNow) {
recognizer.restart();
}
const remaining_task = que.length();
completed(null, { data, remaining_task });
}
const async = require('async');
const que = async.queue(completedFn, 1);
function recognizeFromMicrophone() {
recognizer.start();
recording
.stream()
.on('data', function (data) {
que.push(data, (err, { data, remaining }) => {
if (err) {
console.log(`there is an error in the task ${data}`);
} else {
//console.log(`queue has execute the task ${data}
// . ${remaining} tasks remaining`);
//rm
// cbFn();
}
}
);
})
.on('end', function () {
console.log('recording ended')
recognizer.stop();
});
//.pipe();
}
recognizeFromMicrophone();
var audio_is_playing_o;
var audio_is_playing;
setInterval(() => {
//console.log('vosk interval');
if (recognizer) {
audio_is_playing = audio.audioIsPlaying();
if (audio_is_playing != audio_is_playing_o) {
if (audio_is_playing == false) {
recognizer.start();
//console.log('start recognizer');
}
else {
recognizer.stop();
//console.log('stop recognizer');
}
}
}
}, 500);
function audioTranscription() {
return audio_transcription;
}
module.exports = {
audioTranscription: audioTranscription
}