-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathstream-to-text.js
59 lines (51 loc) · 1.65 KB
/
stream-to-text.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
const EventEmitter = require('events');
const speech = require('@google-cloud/speech');
const appSettings = require('./settings.js').appSettings;
exports.Transcripter = class Transcripter extends EventEmitter {
constructor() {
super()
this.stream = null;
this.dataBuffer = Buffer.alloc(0);
}
start() {
if(appSettings.useSpeech) {
const client = new speech.SpeechClient({
keyFilename: appSettings.apiKeyfile
});
const request = {
config: {
encoding: 'LINEAR16',
sampleRateHertz: appSettings.sampleRate,
languageCode: appSettings.language
},
interimResults: true
};
this.stream = client.streamingRecognize(request)
.on('error', (err) => {
this.emit('error', err);
})
.on('data', (data) => {
if(data.error)
this.emit('error', data.error);
else if(data.results)
this.emit('data', data.results);
});
}
}
stop() {
if(this.stream != null) {
this.stream.end();
this.stream = null;
this.dataBuffer = Buffer.alloc(0);
}
}
putData(data) {
if(this.stream != null) {
this.dataBuffer = Buffer.concat([this.dataBuffer, data]);
if(this.dataBuffer.length > (appSettings.sampleRate / 10)) {
this.stream.write(this.dataBuffer);
this.dataBuffer = Buffer.alloc(0);
}
}
}
}