JSFiddle - React, Tailwind, and code Playground
by Christian Sonne
HTML
<canvas id="c"></canvas>
CSS
html, body {
margin: 0;
padding: 0;
}
canvas {
background: #eee;
}
JavaScript
let c = document.getElementById("c"); // funfact: you can leave this line out
c.width = window.innerWidth;
c.height = window.innerHeight / 2;
navigator.getUserMedia = (
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
);
let i = 100;
let nBins = 256;
function Viz(canvas, nBins) {
this.canvas = canvas;
this.width = canvas.width;
this.height = canvas.height;
this.nBins = nBins;
this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if (navigator.getUserMedia) {
console.log('getUserMedia supported.');
navigator.getUserMedia(
// constraints - only audio needed for this app
{audio: true},
// Success callback
function(stream) {
let source = this.audioCtx.createMediaStreamSource(stream);
this.setup(source);
}.bind(this),
// Error callback
function(err) {
console.log('The following gUM error occured: ' + err);
}
);
} else {
console.log('getUserMedia not supported on your browser!');
}
}
Viz.prototype = {
setup: function(source) {
this.source = source;
//set up the different audio nodes we will use for the app
this.analyser = this.audioCtx.createAnalyser();
this.analyser.minDecibels = -90;
this.analyser.maxDecibels = -10;
this.analyser.smoothingTimeConstant = 0.5;
this.analyser.fftSize = this.nBins * 2;
this.dataArrayAlt = new Uint8Array(this.nBins);
this.source.connect(this.analyser);
// set up canvas context for visualizer
this.canvasCtx = this.canvas.getContext("2d");
this.canvasCtx.shadowColor = '#7cd7ff';
this.canvasCtx.shadowBlur = 3;
this.canvasCtx.fillStyle = 'white';
this.draw();
},
draw: function(time) {
window.requestAnimationFrame(this.draw.bind(this));
this.analyser.getByteFrequencyData(this.dataArrayAlt);
this.shift_canvas(0, 0, this.width, this.height, 0, -5);
let barWidth = this.width / this.nBins / 2;
for (let i = 0; i < this.nBins; i++) {
let barHeight...