效果演示
主要源码如下:
(function () {
const audio = document.getElementById('audio');
const canvas = document.getElementById('analyzerCanvas');
const ctx = canvas.getContext('2d');
let bufferLength = 256;
let audioContext, analyser, dataArray = new Uint8Array(bufferLength);
function createOrGetAnalyser() {
if (!analyser) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
const source = audioContext.createMediaElementSource(audio);
analyser = audioContext.createAnalyser();
source.connect(analyser);
analyser.connect(audioContext.destination);
analyser.fftSize = 256;
bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
}
return analyser;
}
function draw() {
requestAnimationFrame(draw);
if (analyser) {
analyser.getByteFrequencyData(dataArray);
}
ctx.fillStyle = 'rgb(200, 200, 200)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const barWidth = (canvas.width / bufferLength) * 2;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const v = dataArray[i];
ctx.fillStyle = `rgb(${v}, ${v}, ${v})`;
ctx.fillRect(x, canvas.height - v, barWidth, v);
x += barWidth;
}
}
draw();
audio.addEventListener('play', createOrGetAnalyser);
})();