Guest User

Offtopical Audio Visualization

a guest
Feb 1st, 2019
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var color = '#1f1833' // color
  2.  
  3. var canvasCtx = document.getElementById( 'audioCanvas' ).getContext( '2d' ); // Canvas Context
  4.  
  5. var audioCtx = new AudioContext(); // Audio Context
  6. var analyser = audioCtx.createAnalyser(); // Analyser to analyse the audio
  7.  
  8. var source = audioCtx.createMediaElementSource( document.getElementById( 'podcastAudio' ) ); // The audio source, the audio element
  9. source.connect( analyser ); // Connect the source to the analyser
  10. analyser.connect( audioCtx.destination ); // Connect the Analyser to the the context destination.
  11.  
  12. var bufferLength, dataArray; // Define variables.
  13. var setup = function() {
  14.   document.getElementById( 'audioCanvas' ).width = window.innerWidth;
  15.   document.getElementById( 'audioCanvas' ).height = window.innerHeight; // Set canvas size
  16.   analyser.fftSize = Math.pow( 2, Math.ceil( Math.log( window.innerWidth ) / Math.log( 2 ) ) ) * 2; // Set the the fft size to the window width rounded up to the nearest power of 2
  17.   bufferLength = analyser.frequencyBinCount; // How many values are in the array
  18.   dataArray = new Uint8Array( bufferLength ); // Make the Array for the fft data
  19. }
  20. window.onresize = setup; // Change fft size when window resizes
  21. setup();
  22.  
  23. function draw() {
  24.   drawVisual = requestAnimationFrame( draw );
  25.  
  26.   analyser.getByteFrequencyData( dataArray ); // Put fft data into array
  27.  
  28.   canvasCtx.clearRect(0, 0, window.innerWidth, window.innerHeight ); // Clear the canvas
  29.  
  30.   var barWidth = 1;
  31.   var barHeight;
  32.   var x = 0;
  33.  
  34.   for(var i = 0; i < bufferLength; i++) {
  35.     barHeight = dataArray[i];
  36.    
  37.     canvasCtx.fillStyle = color; // Change fill to color;
  38.     canvasCtx.fillRect( Math.floor( x ), window.innerHeight - barHeight, barWidth, barHeight ); // Draw the bar
  39.    
  40.     x += window.innerWidth / bufferLength; // Change the position of bar.
  41.   }
  42. };
  43.  
  44. draw(); // Start Drawing
Add Comment
Please, Sign In to add comment