-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
72 lines (47 loc) · 1.32 KB
/
index.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
/**
* Draw waveform in terminal/canvas
*
* @module audio-waveform
*/
var inherits = require('inherits');
var pcm = require('pcm-util');
var RenderStream = require('audio-render');
/**
* @constructor
*/
function Waveform (options) {
if (!(this instanceof Waveform)) return new Waveform(options);
RenderStream.call(this, options);
}
inherits(Waveform, RenderStream);
/** Offset of a sliding window */
Waveform.prototype.offset;
/** Size of a sliding window */
Waveform.prototype.size = 1024;
/** Draw in canvas */
Waveform.prototype.render = function (canvas, data) {
var self = this;
var offset = self.offset;
//if offset is undefined - show last piece of data
if (offset == null) {
offset = data.length - self.size;
if (offset < 0) offset = 0;
}
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
var amp = canvas.height / 2;
var frameData = data.slice(offset, offset + self.size);
var step = self.size / canvas.width;
var middle = amp;
context.beginPath();
context.moveTo(0, middle);
for (var i = 0; i < canvas.width; i++) {
var sampleNumber = Math.round(step * i);
var sample = frameData[sampleNumber];
//ignore undefined data
if (sample == null) continue;
context.lineTo(i, -sample * amp + middle);
}
context.stroke();
}
module.exports = Waveform;