I am trying to change the color of an SVG image using audio from the microphone.
I have got the logic written, the color is updated on the SVG element, but nothing changes visually.
window.onload = function () {
if (navigator.getUserMedia) {
navigator.getUserMedia(
{ audio: true },
(stream) => {
var context = new AudioContext();
var src = context.createMediaStreamSource(stream);
var analyser = context.createAnalyser();
var svg = document.querySelector("#rangoli");
src.connect(analyser);
analyser.connect(context.destination);
analyser.fftSize = 256;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
function renderFrame() {
requestAnimationFrame(renderFrame);
analyser.getByteFrequencyData(dataArray);
for (var i = 0; i < bufferLength; i++) {
barHeight = dataArray[i] / 2;
var r = barHeight + 25 * (i / bufferLength);
var g = 250 * (i / bufferLength);
var b = 50;
svg.setAttribute("fill", `rgb(${r}, ${g}, ${b})`);
}
}
renderFrame();
},
() => console.log("Error")
);
}
};
Here is the SVG updating the fill value:

Here is a CodePen demo: https://codepen.io/GR8z/pen/qBjopZG