/
audio_visual.js
41 lines (34 loc) · 1.08 KB
/
audio_visual.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
/* eslint-env node, jquery, browser */
let audioContext;
let mediaSource;
let audioSource;
let analyser;
function initAudioVisualization() {
audioContext = new window.AudioContext();
mediaSource = document.getElementById('music');
mediaSource.crossOrigin = 'anonymous';
audioSource = audioContext.createMediaElementSource(mediaSource);
analyser = audioContext.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
audioSource.connect(analyser);
audioSource.connect(audioContext.destination);
}
function visualizeAudio() {
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Float32Array(bufferLength);
analyser.getFloatFrequencyData(dataArray);
let avg = 0;
for (let i = 0; i < 2; i += 1) {
avg += dataArray[i] / (2);
}
avg += 140;
let beatChangeAux = (avg - 95) / 25;
if (beatChangeAux < 0.3) {
beatChangeAux = 0;
}
const beatChange = Math.floor(beatChangeAux * 200);
$('body').css('background-color', `rgb(${0},${0},${beatChange})`);
}