Oi, this website is currently on the move to https://turboflip.de - party on there!

livecoding #4 – audio sensitive particles with p5.js

This example shows how to construct a p5.js application to run an object oriented approach, using independent particles to draw the stage canvas buffer.

ONLINE DEMO IN P5 Editor

// particle class aP.js
class aP{
   
 constructor( _id,_pos){
   
   // setup the basic parameters of each particle
    this.id = _id;
    this.pos = _pos;
    this.vel  = createVector(0,0);
    this.ppos =  this.pos;
 
  }
  
  // drawing routine for each particle
  drawMe(_thick){
    
    noStroke();
    ellipse(this.pos.x,this.pos.y,_thick,_thick);
    
    this.pos.x +=  (noise(this.id*.12,millis()*.0001)-.5)*10;
    this.pos.y +=2.;
    
    if( this.pos.y > height){
    
       this.pos.y = 0;
       this.pos.x = random(width);
      
    }
  }


}
// main script sketch.js

// basic variable definitions
let mic;
const particles  = [] ;
let pcount = 120;
let samp = 0;

// -----------------------

function setup() {
  createCanvas(window.innerWidth, window.innerHeight);
  background(220);
  
   // Create an Audio input
  mic = new p5.AudioIn();
  mic.start();
   
  // draw a slight smoothed shadow ( CPU INTENSE!!! )
    drawingContext.shadowColor = color(0, 0, 0,20);
	drawingContext.shadowBlur =20;
	drawingContext.shadowOffsetX = 5;
	drawingContext.shadowOffsetY = -5;

  
  for(let i=0;i<pcount;i++){
    
      let ipos = createVector(random(width),random(height));
      let np = new aP(i,ipos); 
      particles.push(np);
    
  }
  
}

// ----------------------- loop function 

function draw() {
     
  // read out the current mic amplitude
  samp = lerp(samp, mic.getLevel() * 1000 ,.1);
    
  // update and draw each particle
  for(let i=0;i<particles.length;i++){
  
     let cp = particles[i];
    cp.drawMe(samp+3);
    
  }
 
}