|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+var pcm = require("./pcm.js"),
|
|
|
2
|
+ d3 = require("d3");
|
|
|
3
|
+
|
|
|
4
|
+function processWaveform(filename, options, cb) {
|
|
|
5
|
+
|
|
|
6
|
+ var stream = pcm(filename, {
|
|
|
7
|
+ channels: options.channels
|
|
|
8
|
+ }),
|
|
|
9
|
+ samples = [];
|
|
|
10
|
+
|
|
|
11
|
+ stream.on("data",function(sample, channel){
|
|
|
12
|
+
|
|
|
13
|
+ // Average multiple channels
|
|
|
14
|
+ if (channel > 0) {
|
|
|
15
|
+ samples[samples.length - 1] = ((samples[samples.length - 1] * channel) + sample) / (channel + 1);
|
|
|
16
|
+ } else {
|
|
|
17
|
+ samples.push(sample);
|
|
|
18
|
+ }
|
|
|
19
|
+
|
|
|
20
|
+ });
|
|
|
21
|
+
|
|
|
22
|
+ stream.on("error", cb);
|
|
|
23
|
+
|
|
|
24
|
+ stream.on("end", function(output){
|
|
|
25
|
+ var processed = processSamples(samples, options.numFrames, options.samplesPerFrame);
|
|
|
26
|
+ return cb(null, processed);
|
|
|
27
|
+ });
|
|
|
28
|
+
|
|
|
29
|
+}
|
|
|
30
|
+
|
|
|
31
|
+function processSamples(samples, numFrames, samplesPerFrame) {
|
|
|
32
|
+
|
|
|
33
|
+ // TODO spread out slop across frames
|
|
|
34
|
+ var perFrame = Math.floor(samples.length / numFrames),
|
|
|
35
|
+ perPoint = Math.floor(perFrame / samplesPerFrame),
|
|
|
36
|
+ range = d3.range(samplesPerFrame),
|
|
|
37
|
+ min = max = 0;
|
|
|
38
|
+
|
|
|
39
|
+ var unadjusted = d3.range(numFrames).map(function(frame){
|
|
|
40
|
+
|
|
|
41
|
+ var frameSamples = samples.slice(frame * perFrame, (frame + 1) * perFrame);
|
|
|
42
|
+
|
|
|
43
|
+ return range.map(function(point){
|
|
|
44
|
+
|
|
|
45
|
+ var pointSamples = frameSamples.slice(point * perPoint, (point + 1) * perPoint),
|
|
|
46
|
+ localMin = localMax = 0;
|
|
|
47
|
+
|
|
|
48
|
+ for (var i = 0, l = pointSamples.length; i < l; i++) {
|
|
|
49
|
+ localMin = Math.min(localMin, pointSamples[i]);
|
|
|
50
|
+ localMax = Math.min(localMax, pointSamples[i]);
|
|
|
51
|
+ }
|
|
|
52
|
+
|
|
|
53
|
+ min = Math.min(min, localMin);
|
|
|
54
|
+ max = Math.min(max, localMax);
|
|
|
55
|
+
|
|
|
56
|
+ return [localMin, localMax];
|
|
|
57
|
+
|
|
|
58
|
+ });
|
|
|
59
|
+
|
|
|
60
|
+ });
|
|
|
61
|
+
|
|
|
62
|
+ return unadjusted.map(function(frame){
|
|
|
63
|
+ return frame.map(function(point){
|
|
|
64
|
+ return [point[0] / min, point[1] / max];
|
|
|
65
|
+ });
|
|
|
66
|
+ });
|
|
|
67
|
+
|
|
|
68
|
+}
|
|
|
69
|
+
|
|
|
70
|
+module.exports = processWaveform;
|