-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
119 lines (98 loc) · 2.62 KB
/
script.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const WIDTH = 1024;
const HEIGHT = 500;
const BAR_NUM = 64;
const FFTSIZE = 1024;
const blob = window.URL || window.webkitURL;
let audio;
let file = document.getElementById('exfile');
let color = document.getElementById('color');
let bgColor = document.getElementById('bg-color');
let ctx,
analyser,
dataArray,
source,
bufferLength,
mainCanvas,
canvas,
canvasCtx,
canvasCtxBottom,
rgb = [71, 184, 224];
file.onchange = function () {
audio = document.getElementById('audio');
const reader = new FileReader();
reader.onload = function (evt) {
url = evt.target.result;
audio.src = url;
audio.controls = true;
audio.crossOrigin = 'anonymous';
audio.play();
ctx.resume();
};
reader.readAsDataURL(this.files[0]);
draw();
};
color.onchange = function () {
rgb = getRGB(this.value);
};
bgColor.onchange = function () {
const rgb = getRGB(this.value);
document.getElementsByClassName(
'main-container'
)[0].style.backgroundColor = `rgb(${rgb.join(',')})`;
};
function init() {
audio = document.getElementById('audio');
// Get Conetxt & ANALYSER
ctx = new AudioContext();
analyser = ctx.createAnalyser();
analyser.fftSize = FFTSIZE; // Fast Fourier Transform
// Get Data Array
bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
// Source Connect
source = ctx.createMediaElementSource(audio);
source.connect(analyser);
source.connect(ctx.destination);
// Get Element & Access Context
canvas = document.getElementById('canvas');
canvasCtx = canvas.getContext('2d');
canvasCtx.fillStyle = 'rgb(71, 184, 224)';
}
function draw() {
requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
// Bar x, y, position
let x = 0;
let y = 0;
const radius = WIDTH / (2 * BAR_NUM);
for (let i = 0; i < bufferLength; i++) {
y = (dataArray[i] - 128) * 2 + 50;
if (y <= 1) {
y = 0;
}
// Drawing Rect
canvasCtx.fillStyle =
'rgb(' +
(y - 150 + rgb[0]) +
',' +
(y - 150 + rgb[1]) +
',' +
(y - 150 + rgb[2]) +
')';
canvasCtx.fillRect(x, HEIGHT - y - radius, WIDTH / BAR_NUM, y);
// Drawing Arc
canvasCtx.beginPath();
canvasCtx.arc(x + radius, HEIGHT - radius, radius, 0, Math.PI, false);
canvasCtx.arc(x + radius, HEIGHT - y - radius, radius, 0, Math.PI, true);
canvasCtx.closePath();
canvasCtx.fill();
// Set Next Bar X position
x += WIDTH / BAR_NUM + 5;
}
}
function getRGB(hex) {
let rgb = hex.match(/[A-Za-z0-9]{2}/g);
rgb = rgb.map((v) => parseInt(v, 16));
return rgb;
}