-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
83 lines (63 loc) · 1.6 KB
/
sketch.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
let song;
let fft;
const BAND_COUNT = 1024;
let rectWidth;
const promptDragDrop = () => {
background(20);
text("Drag and drop a song to begin", width / 2, height / 2 - 15);
text("(or click anywhere for a demo song)", width / 2, height / 2 + 15);
};
const promptDrop = () => {
background(20);
text("Drop it like it's hot!", width / 2, height / 2);
};
const playDemo = () => playSong("assets/summer-romance.mp3");
const playSong = (file) => {
if (song !== undefined) return;
file = file.data ? file.data : file;
song = loadSound(file, () => song.play());
song.onended(reset);
fft.setInput(song);
rectWidth = width / BAND_COUNT;
noFill();
loop();
};
function windowResized() {
resizeCanvas(innerWidth, innerHeight);
if (isLooping()) {
rectWidth = width / BAND_COUNT;
} else {
reset();
}
}
const reset = () => {
noLoop();
noStroke();
fill("white");
background(20);
song = undefined;
fft = new p5.FFT(0.8, BAND_COUNT);
promptDragDrop();
};
function setup() {
const cnv = createCanvas(innerWidth, innerHeight);
cnv.dragOver(promptDrop);
cnv.dragLeave(promptDragDrop);
cnv.drop(playSong, promptDragDrop);
cnv.mouseClicked(playDemo);
textAlign(CENTER);
textSize(20);
reset();
}
function draw() {
if (song === undefined) return;
background(20);
const spectrum = fft.analyze();
for (let i = 0; i < BAND_COUNT; i++) {
const hue = map(i, 0, BAND_COUNT, 0, 1);
const color = hslToRgb(hue, 1, 0.5);
const vol = -map(spectrum[i], 0, 255, 0.1, height / 3);
fill(color);
rect(i * rectWidth, height / 2 - vol, rectWidth, vol * 2);
}
}