forked from SophieShears/MidiToChiptune
-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualize.js
65 lines (50 loc) · 1.76 KB
/
visualize.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
let analysers = null;
let contexts = null;
// Blue, Red, Yellow, Black
let colors = {0: "#569dcb", 1: "#f9b131", 2: "#a92326", 3: "#242121"};
// Create analysers for each instrument then connect them
function getAnalysers(instruments) {
const allAnalysers = {};
for (let instrument = 0; instrument < Object.keys(instruments).length; instrument ++) {
allAnalysers[instrument] = new Tone.Analyser("waveform", 1024);
instruments[instrument].fan(allAnalysers[instrument]);
}
analysers = allAnalysers;
}
// Create a context object for each insturment
function allContext(instruments) {
const allContexts = {};
for (let instrument = 0; instrument < Object.keys(instruments).length; instrument ++) {
try {
allContexts[instrument] = document.querySelector('#wave' + instrument).getContext('2d');
}
catch (DOMException) {}
}
contexts = allContexts;
}
// Create soundwave of each instrument
function createWave(context, values, color) {
const canvasWidth = 250, canvasHeight = 100;
if(context != null) {
context.clearRect(0, 0, canvasWidth, canvasHeight);
context.beginPath();
context.lineJoin = "round";
context.lineWidth = 2;
context.moveTo(0, (values[0] / 255) * canvasHeight);
for (let i = 1, len = values.length; i < len; i++){
let val = values[i];
let x = canvasWidth * (i / len);
let y = val * canvasHeight;
context.lineTo(x, y);
}
context.stroke();
context.strokeStyle = colors[color % 4];
}
}
// Draw them all to canvas
function drawWave() {
requestAnimationFrame(drawWave);
for (let i = 0; i < Object.keys(analysers).length; i ++) {
createWave(contexts[i], analysers[i].getValue(), i);
}
}