-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
oscilloscope.js
57 lines (42 loc) · 1.63 KB
/
oscilloscope.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
var oscilloscope = function (context, elem) {
var analyser = context.createAnalyser();
var elem = document.getElementById(elem);
analyser.width = elem.offsetWidth;
analyser.height = elem.offsetHeight;
analyser.lineColor = 'white';
analyser.lineThickness = 1;
var svgNamespace = "http://www.w3.org/2000/svg";
var paper = document.createElementNS(svgNamespace, "svg");
paper.setAttribute('width', analyser.width);
paper.setAttribute('height', analyser.height);
paper.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
elem.appendChild(paper);
var oscLine = document.createElementNS(svgNamespace, "path");
oscLine.setAttribute("stroke", analyser.lineColor);
oscLine.setAttribute("stroke-width", analyser.lineThickness);
oscLine.setAttribute("fill","none");
paper.appendChild(oscLine);
var noDataPoints = 10,
freqData = new Uint8Array(analyser.frequencyBinCount);
var drawLine = function () {
analyser.getByteTimeDomainData(freqData);
var graphPoints = [],
graphStr = '';
graphPoints.push('M0, ' + (analyser.height/2));
for (var i = 0; i < freqData.length; i++) {
if (i % noDataPoints) {
var point = (freqData[i] / 128) * (analyser.height / 2);
graphPoints.push('L' + i + ', ' + point);
}
}
for (i = 0; i < graphPoints.length; i++) {
graphStr += graphPoints[i];
}
oscLine.setAttribute("stroke", analyser.lineColor);
oscLine.setAttribute("stroke-width", analyser.lineThickness);
oscLine.setAttribute("d", graphStr);
setTimeout(drawLine, 100);
};
drawLine();
return analyser;
};