const aObj =
new
(window.AudioContext ||
window.webkitAudioContext)();
const analyseObj = aObj.createAnalyser();
const canvas =
document.getElementById(
'visualizer'
);
const ctx = canvas.getContext(
'2d'
);
analyseObj.fftSize = 256;
const leng = analyseObj.frequencyBinCount;
const dArr =
new
Uint8Array(leng);
const src =
aObj.createMediaElementSource(document
.getElementById(
'audioPlayer'
));
src.connect(analyseObj);
analyseObj.connect(aObj.destination);
document.getElementById(
'audioFileInput'
)
.addEventListener(
'change'
,
function
(e) {
const file = e.target.files[0];
if
(file) {
const objectURL = URL.createObjectURL(file);
document.getElementById(
'audioPlayer'
).src = objectURL;
}
});
function
draw() {
analyseObj.getByteFrequencyData(dArr);
ctx.fillStyle =
'#2c3e50'
;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const barWidth = (canvas.width / leng) * 2.5;
let x = 0;
dArr.forEach(
function
(data) {
const barHeight = data;
ctx.fillStyle = `rgb(0, ${barHeight + 100}, 0)`;
ctx.fillRect(x, canvas.height - barHeight / 2,
barWidth, barHeight / 2);
x += barWidth + 1;
});
requestAnimationFrame(draw);
}
function
currTimeFunction() {
const ap = document.getElementById(
'audioPlayer'
);
const curr = document.getElementById(
'currentTime'
);
curr.textContent =
`Current Time: ${ap.currentTime.toFixed(2)}s`;
}
function
peakFreqFunction() {
analyseObj.getByteFrequencyData(dArr);
const idx = dArr.indexOf(Math.max(...dArr));
const freq = (idx / leng) * aObj.sampleRate / 2;
const freqEle = document.getElementById(
'peakFrequency'
);
freqEle.textContent = `Peak Frequency: ${freq.toFixed(2)} Hz`;
}
function
avgVolumeFunction() {
analyseObj.getByteFrequencyData(dArr);
const avgVol = dArr.reduce((acc, val) => acc + val, 0) / dArr.length;
const avgVolEle = document.getElementById(
'averageVolume'
);
avgVolEle.textContent = `Average Volume: ${avgVol.toFixed(2)}`;
}
document.getElementById(
'audioPlayer'
)
.addEventListener(
'timeupdate'
,
function
() {
currTimeFunction();
peakFreqFunction();
avgVolumeFunction();
});
draw();
currTimeFunction();
peakFreqFunction();
avgVolumeFunction();