Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Mic Audio Graphic Equalizer

I've started recording blog posts to turn them into mp3s. I want to post them to YouTube too, but I'm not interested in having to make myself presentable every time I want to record. I made this graphic equalizer display so I don't have to. It takes the audio input from a mic and turns it into pretty looking bars.

Click "Start" to request access to the mic and start showing the output full screen. (You can also set title and subtitle text which show when the display is in full screen mode)

HTML

<div id="p5Wrapper"></div>

HTML

<label>
  <div>Title</div>
  <input type="text" id="titleText" />
</label>

<label>
  <div>Subtitle</div>
  <input type="text" id="subtitleText" />
</label>

<label>
  <div>Size</div>
  <input type="number" id="titleSize" value="150" size="5" />
</label>

Head


<script src="/theme/scripts/p5/p5.min.js"></script>
<script src="/theme/scripts/p5/addons/p5.sound.min.js"></script>

JavaScript

let mic
let fft 
let totalBands = 32
let widthOfBands
let baseWidth = 200

function findHeight(fromWidth) {
  return window.screen.height / window.screen.width * fromWidth 
}

function handleFullscreenChange() {
  if (!document.fullscreenElement) {
    resizeCanvas(baseWidth, findHeight(baseWidth))
  } else {
    resizeCanvas(displayWidth, displayHeight)
  }
}

function toggleFullscreen() {
  if (!mic.enabled) {
    mic.start()
  }
  /*
  if (!document.fullscreenElement) {
    document.querySelector('#p5Canvas').requestFullscreen()
  } else {
    document.exitFullscreen()
  }
  */
}

function setup() {
  colorMode(HSB)
  mic = new p5.AudioIn()
  const canvas = createCanvas(baseWidth, findHeight(baseWidth))
  canvas.parent('p5Wrapper')
  canvas.id('p5Canvas')
  canvas.mouseClicked(toggleFullscreen)
  document.querySelector('#p5Canvas').addEventListener(
    'fullscreenchange', handleFullscreenChange
  )
  fft = new p5.FFT(0.9, totalBands)
  fft.setInput(mic)
  describe(`A black canvas that shows a 32 
  bar graphic equalizer display with varying 
  shades of red bars full screen when clicked.`);
}

function draw() {
  background(0)
  stroke(0)
  widthOfBands = width / totalBands
  var spectrum = fft.analyze()
  for (let i = 0; i < spectrum.length; i++) {
    var amp = spectrum[i]
    fill(i, 255, 255)
    var y = map(amp, 0, 256, height, 0)
    rect(i * widthOfBands, y, widthOfBands, height - y)
  }
  if (!mic.enabled) {
    textAlign(CENTER, CENTER)
    textSize(32)
    text("Start", width / 2, height / 2)
  } else if (fullscreen()) {
    textAlign(LEFT, TOP)
    textSize(getInt('#titleSize'))
    text(getValue('#titleText'), 20, 20)
    textSize(getInt('#titleSize') * 0.6)
    text(getValue('#subtitleText'), 20, getInt('#titleSize') + 20)
  }
}

Footnotes And References