-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
83 lines (74 loc) · 2.8 KB
/
script.js
File metadata and controls
83 lines (74 loc) · 2.8 KB
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
const container = document.getElementById('container');
const canvas = document.getElementById('canvas1');
const file = document.getElementById('fileupload');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
let audioSource;
let analyser;
container.addEventListener('click', function(){
const audio1 = document.getElementById('audio1');
const audioContext = new AudioContext();
audio1.play();
audioSource = audioContext.createMediaElementSource(audio1);
analyser = audioContext.createAnalyser();
audioSource.connect(analyser);
analyser.connect(audioContext.destination);
analyser.fftSize = 512;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
const barWidth = 15;
let barHeight;
let x;
function animate(){
x = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
analyser.getByteFrequencyData(dataArray);
drawVisualiser(bufferLength, x, barWidth, barHeight, dataArray);
requestAnimationFrame(animate);
}
animate();
});
file.addEventListener('change', function(){
const files = this.files;
const audio1 = document.getElementById('audio1');
audio1.src = URL.createObjectURL(files[0]);
audio1.load();
audio1.play();
audioSource = audioContext.createMediaElementSource(audio1);
analyser = audioContext.createAnalyser();
audioSource.connect(analyser);
analyser.connect(audioContext.destination);
analyser.fftSize = 51;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
const barWidth = 1;
let barHeight;
let x;
function animate(){
x = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
analyser.getByteFrequencyData(dataArray);
drawVisualiser(bufferLength, x, barWidth, barHeight, dataArray);
requestAnimationFrame(animate);
}
animate();
});
function drawVisualiser(bufferLength, x, barWidth, barHeight, dataArray){
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i] * 1.2;
barWidth = dataArray[i] * 0.2;
ctx.save();
let x = Math.sin(i/30 * Math.PI / 180) * 1;
let y = Math.cos(i/30 * Math.PI / 180) * 90;
ctx.translate(canvas.width/2 + x, canvas.height/2 - y/5)
ctx.rotate( i + Math.PI * 2/bufferLength);
const hue = i / 6 + 20;
ctx.fillStyle = 'hsl(' + hue + ',90%, 40%)';
ctx.strokeStyle = 'hsl(1, 100%, ' + i/2 + '%)';
ctx.fillRect(x, y, barWidth, barHeight);
ctx.strokeRect(x, y, barWidth, barHeight);
ctx.restore();
x += barWidth;
}
}