<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
Creating an audio visualizer
using HTML CANVAS API
</
title
>
</
head
>
<
body
>
<
h1
style
=
"color:green"
>
GeeksforGeeks
</
h1
>
<
h3
>
How to make an audio visualizer
with HTML CANVAS API?
</
h3
>
<
button
id
=
"mybtn"
>Click Me</
button
>
<
canvas
id
=
"visualizer"
width
=
"100px"
height
=
"100px"
style="border:5px solid blue;
border-radius:100px">
</
canvas
>
<
script
type
=
"text/javascript"
>
var btn = document.getElementById("mybtn");
var visualizer = document.getElementById("visualizer");
btn.onclick = async () => {
let stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: true
});
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const mediaStreamSource =
audioContext.createMediaStreamSource(stream);
// Connecting the analyzer to the media source
mediaStreamSource.connect(analyser);
analyser.fftSize = 256;
drawVisualizer();
function drawVisualizer() {
requestAnimationFrame(drawVisualizer)
const bufferLength = analyser.frequencyBinCount
const dataArray = new Uint8Array(bufferLength)
// Updating the analyzer with the new
// generated data visualization
analyser.getByteFrequencyData(dataArray)
const width = visualizer.width
const height = visualizer.height
const barWidth = 10
const canvasContext = visualizer.getContext('2d')
canvasContext.clearRect(0, 0, width, height)
let x = 0
dataArray.forEach((item, index, array) => {
// This formula decides the height of the vertical
// lines for every item in dataArray
const y = item / 255 * height * 1.1
canvasContext.strokeStyle = `blue`
// This decides the distances between the
// vertical lines
x = x + barWidth
canvasContext.beginPath();
canvasContext.lineCap = "round";
canvasContext.lineWidth = 2;
canvasContext.moveTo(x, height);
canvasContext.lineTo(x, height - y);
canvasContext.stroke();
})
}
}
</
script
>
</
body
>
</
html
>