Skip to content

Instantly share code, notes, and snippets.

@mendes5
Last active March 7, 2017 17:02
Show Gist options
  • Select an option

  • Save mendes5/9954d11cbe72f0e4ecd56a7f646d8449 to your computer and use it in GitHub Desktop.

Select an option

Save mendes5/9954d11cbe72f0e4ecd56a7f646d8449 to your computer and use it in GitHub Desktop.
Simple audio visualization using web audio api
let x=0,y=0,tx=0,ty=0,r=150,a=0; //States
let context = new AudioContext(); //Audio context
let times = new Uint8Array(360); //Typed array to hold only 360 items
let canvas = document.createElement('canvas'); //Create the canvas
let ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
document.body.appendChild(canvas);
document.body.style.margin = '0px';
let resize = ()=>{ //On resize function
hh = (canvas.height = window.innerHeight) / 2;
ww = (canvas.width = window.innerWidth) / 2;
};
resize();
addEventListener('resize',resize,false);
navigator.getUserMedia({audio:true},(a)=>{ //Get the microphone i recommend to change the input device to the sytem audio output
let input = context.createMediaStreamSource(a); //Create the stream source instead of the microphone and play your favorite song
analyser = context.createAnalyser(); //Create the analyzer
input.connect(analyser); //Connect the stream to the analyzer
update(); //Start loop
},b => console.error(b));
function update() { //Main loop
analyser.getByteFrequencyData(times); //Get the frequency data
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
r = times[20]/2.3; //Get the current radius of the center
ctx.strokeStyle = `hsl(${r},100%,50%)`; //Change the color based on the radius
a+=0.003; //Increase the rotation
for ( var i = 0 ; i <= 360 ; i++) {
x = r * Math.cos(i+a) + ww; //Draw the center
y = r * Math.sin(i+a) + hh;
tx = (r + times[i]) * Math.cos(i+a) + ww; //Draw the corners
ty = (r + times[i]) * Math.sin(i+a) + hh;
ctx.moveTo(x,y);
ctx.lineTo(tx,ty);
}
ctx.stroke(); //Draw it
requestAnimationFrame(update); //Repeat!
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment