I am building a simple sound level indicator for a listener. Using MDN's guide for this (https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API).
Unfortunately, I cannot access the audio from the browser, so that it could be sent over to a frequency analyser that I use for a visualization (the analyser returns a Uint8Array full of zeros, to be more specific).
Below is a code snippet.
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var audio = new Audio ("wss://demo...");
function analyseSound(){
audioCtx.resume().then(() => {
var analyser = audioCtx.createAnalyser();
var source = audioCtx.createMediaElementSource(audio);
source.connect(analyser);
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
console.log(dataArray); // returns Uint8Array(1024) [0, 0, 0, 0, ...]
var canvas = document.getElementById('indicator');
var canvasCtx = canvas.getContext("2d");
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = 'rgb(200, 200, 200)';
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
var barWidth = (canvas.width / bufferLength) * 2.5;
var barHeight;
var x = 0;
for(var i = 0; i < bufferLength; i++) {
barHeight = dataArray[i]/2;
canvasCtx.fillStyle = 'rgb(' + (barHeight+100) + ',50,50)';
canvasCtx.fillRect(x,canvas.height-barHeight/2,barWidth,barHeight);
x += barWidth + 1;
}
};
draw();
});
}
audioCtx is called upon a page load, and, then, resumed on a button-click, as Chrome does not allow AudioContext before any user interaction with the page.
I tried setting up a new Websocket, and playing around with that, but, unfortunately, I have a very limited knowledge around this topic, so, there is no much luck with that either.
Any help is very much appreciated!