-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlearn.js
73 lines (60 loc) · 1.69 KB
/
learn.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
require('./globals');
const Logger = requireModule('logger').initialize(__filename);
const Sox = requireModule('private_modules/sox');
const { fft: fft, util: fftUtil } = require('fft-js');
const SAMPLE_RATE_HZ = 16000;
function compareMagnitudes(magnitudesA, magnitudesB) {
let diff = magnitudesB.map((magnitudeB, i) => {
let magnitudeA = magnitudesA[i];
return magnitudeB - magnitudeA;
});
return diff.reduce((sum, entry) => sum + entry, 0) / diff.length;
}
function onComplete(results) {
console.log(compareMagnitudes(results[0][0], results[1][0]));
}
class Learn {
constructor() {
this.iteration = 0;
this.results = [];
}
start() {
Logger.info(`Starting learning process. Iteration: ${this.iteration}`);
if (!this.results[this.iteration]) {
this.results[this.iteration] = [];
}
let sox = new Sox();
let soxProcess = sox.record({
inputFileName: '0'
});
soxProcess.start();
console.log('Speak NOW!');
let stream = soxProcess.getStream();
stream.on('data', (data) => {
let phasors = fft(data);
let frequencies = fftUtil.fftFreq(phasors, SAMPLE_RATE_HZ);
let magnitudes = fftUtil.fftMag(phasors);
let both = frequencies.map((frequency, i) => {
return {
frequency: frequency,
magnitude: magnitudes[i]
};
});
this.results[this.iteration].push(magnitudes);
});
setTimeout(() => {
console.log('STOP!');
soxProcess.stop();
if (this.iteration < 1) {
this.iteration++;
this.start();
} else {
onComplete(this.results);
}
}, 3000);
}
}
(function learn() {
let learn = new Learn();
learn.start();
})();