I have read Visualizations with Web Audio API and just wanted to check on my own if I can build a small working example that can read the audio input from the Web Audio API.
Here as example audio frequency bars.
Here the HTML, CSS and JavaScript code behind it.
<style>
#canvas {
width: 100%;
height: 200px;
background-color: #cdebd3;
}
</style>
<canvas id="canvas"></canvas>
<script>
navigator.getUserMedia = (
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
);
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var source;
var stream;
var analyser = audioCtx.createAnalyser();
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
analyser.fftSize = 128;
var bufferLength = analyser.frequencyBinCount;
var distortion = audioCtx.createWaveShaper();
var gainNode = audioCtx.createGain();
var biquadFilter = audioCtx.createBiquadFilter();
var convolver = audioCtx.createConvolver();
var canvas = document.getElementById("canvas");
if (navigator.getUserMedia) {
navigator.getUserMedia(
{audio: true},
function(stream) {
source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(convolver);
convolver.connect(gainNode);
gainNode.connect(audioCtx.destination);
readAudioData();
},
function(err) {
console.log(err);
}
);
} else {
console.log('UserMedia not supported on your browser');
}
var readAudioData = function() {
requestAnimationFrame(readAudioData);
var dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);
draw(dataArray);
}
function draw(dataArray) {
var rect = canvas.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
var context = canvas.getContext("2d");
context.fillStyle = "#42ca5b";
var barWidth = rect.width / bufferLength;
for (var i = 0; i < bufferLength; i++) {
var barHeight = (rect.height * dataArray[i])/256;
context.fillRect(i * barWidth, rect.height - barHeight, barWidth, barHeight);
}
}
</script>