-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio-controller.js
More file actions
80 lines (64 loc) · 2.13 KB
/
audio-controller.js
File metadata and controls
80 lines (64 loc) · 2.13 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
console.clear();
const buttons = document.querySelectorAll(".btn");
const audios = document.querySelectorAll("audio");
let canvas, ctx, source, context, analyser, fbc_array, bars, bar_pos,
bar_width, bar_height;
let MEDIA_ELEMENT_NODES = new WeakMap();
buttons.forEach((btn) => {
btn.addEventListener("click", () => {
let idx = Number(btn.id);
let curr_audio = audios[idx];
audios.forEach(audio => { // 재생할 오디오 이외 소리 모두 stop
if (audio !== curr_audio){
audio.pause();
}
})
if (curr_audio.paused === true) {
curr_audio.loop = true;
curr_audio.volume = 0.5;
curr_audio.play();
showUpEQ(curr_audio, idx);
} else {
curr_audio.pause();
}
}, false);
})
function showUpEQ(audio, idx) {
if (context == undefined) {
context = new AudioContext();
}
analyser = context.createAnalyser();
canvas = document.getElementById("canvas" + idx);
ctx = canvas.getContext("2d");
if (MEDIA_ELEMENT_NODES.has(audio)){
source = MEDIA_ELEMENT_NODES.get(audio);
}
else{
source = context.createMediaElementSource(audio);
MEDIA_ELEMENT_NODES.set(audio, source);
}
source.connect(analyser);
analyser.connect(context.destination);
canvas.width = window.innerWidth * 0.4;
canvas.height = window.innerHeight * 0.4;
frameLooper();
}
function frameLooper() {
window.RequestAnimationFrame =
window.requestAnimationFrame(frameLooper) ||
window.msRequestAnimationFrame(frameLooper) ||
window.mozRequestAnimationFrame(frameLooper) ||
window.webkitRequestAnimationFrame(frameLooper);
fbc_array = new Uint8Array(analyser.frequencyBinCount);
bar_count = window.innerWidth / 2;
analyser.getByteFrequencyData(fbc_array);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ffffff";
for (var i = 0; i < bar_count; i++) {
bar_pos = i * 8;
bar_width = 1;
bar_height = -(fbc_array[i] / 2);
ctx.fillRect(bar_pos, canvas.height + 10, bar_width, bar_height);
ctx.setTransform(1, 0, 0, -1, 0, canvas.height);
}
}