Playing with sound - 3

Make some 'art'

by blackpolygon

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.sound.min.js"></script>
<html>

  <head>
    <title>Playing with sound</title>
  </head>

  <body>
    <canvas id="canvas"></canvas>
  </body>

</html>

CSS

html {
  width: 100%;
  height: 100%;
}

body {
  margin: 0 auto;
  overflow: hidden;
  height: 100%;
}

JavaScript

var canvas, ctx, w2, mic, h2, fft, spectrum, waveform;

var cantRows = 220;
var cantCols = 80;
var squareWidth, squareHeight = 5;
var frame = 0;
var squares = [];

function setup() {
  canvas = document.getElementById('canvas');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  ctx = canvas.getContext('2d');
  ctx.lineWidth = 1;
  w2 = window.innerWidth / 2;
  h2 = window.innerHeight / 2;

  squareWidth = w2 / cantCols;
  squareHeight = canvas.height / cantRows;

  mic = new p5.AudioIn()
  mic.start();
  fft = new p5.FFT(0.8);
  fft.setInput(mic);

  // Do you think dinosaurs had dreams and hopes too?
  for (var i = 0; i < cantCols; i++) {
    squares[i] = [];
    for (var j = 0; j < cantRows; j++) {
      squares[i][j] = 0;
    }
  }
}

function draw() {

  var micLevel = mic.getLevel(0.8);
  var gray = map(micLevel, 0.0, 1, 0, 255);
  var greenColor = map(micLevel, 0.0, 1, 0, 100);

  var c = color(gray); // Make the background color change in intensity depending on the overall volume
  c.setAlpha(25.6); // an alpha gives the fading effect to the animations

  ctx.fillStyle = c.toString();
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // We need to call analyze before doing the next computations
  spectrum = fft.analyze();

  // Divide the spectrum in N slots, get the energy level for each frequency
  // Draw a circle with a radius that represents that amount of energy
  var energySlots = 100;
  var seRatio = spectrum.length / energySlots; // Spectrum/energy ratio
  for (var i = 0; i < energySlots; i++) {
    // Get the energy for that frequency
    var freq = seRatio * i;
    var e = fft.getEnergy(freq);

    // The purple color of the circle will change depending on its position
    var red = 155 + i;
    ctx.strokeStyle = "rgba(" + red + ", 0, 255, 1)";

    // Draw the circle
    ctx.beginPath();
    ctx.arc(w2, i * (canvas.height / energySlots), e, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.closePath();
  }

  let...