Accessing global mic level with a local class

I'm making a sketch that uses mic volume via p5.audioIn() to change the shape of a bunch of circles. It was working when I did it all locally, but I decided making a class for each shape's x, y ,etc, would be cleaner.

Here is my main code:

var shapes = [];
var mic;

function setup() {
  createCanvas(600, 600);
  // Create an Audio input
  mic = new p5.AudioIn();
  // start the Audio Input.
  // By default, it does not .connect() (to the computer speakers)
  count = 10;
  for (var i = 0; i < count; i++) {
    shapes.push(new NoiseyShape());


function draw() {
  // Get the overall volume (between 0 and 1.0)
  //var vol = mic.getLevel();
  for (var i = 0; i < count; i++) {

And here is the code for NoiseyShape:

function NoiseyShape() {
  this.x = random(width);
   this.y = random(height);
    this.r = random(30, 60);
    this.n = 50;
    this.vol = mic.getLevel();
    this.variation = this.vol * 25; = function() {  
    // my secret codes

    this.update = function() {
    // my secret code

The problem is that the value for this.vol is always 0. Why doesn't this work anymore? Thanks!


  • edited December 2016 Answer ✓

    @ this.vol = mic.getLevel();, you're assigning the current p5.AudioIn's audio level value to NoiseyShape's vol property while in setup().

    However, that initial value never changes afterwards and stays forever that way! #-o

    How about cache getLevel() in each draw() before iterating over your NoiseyShape object?

    Then pass that value as an argument for NoiseyShape's update() method: *-:)

    NoiseyShape.prototype.update = function (vol) { // my secret code };

    function draw() {
      const level = mic.getLevel();
      for (let noisy of shapes)  noisy.update(level),;
  • Aha! I realize now that I was only declaring the value for vol upon setup. Thank you very much, I'm now passing it as an argument to the update function.

Sign In or Register to comment.