xxxxxxxxxx
99
// Visualizes current sound loudness and average sound loudness
// using a circle
//
// This sketch is part of a series:
// - v1: simple version: https://editor.p5js.org/jonfroehlich/sketches/JeFJHpkb7
// - v2: with fade: https://editor.p5js.org/jonfroehlich/sketches/NqEkDeon1
// - v3: this sketch
//
// By Professor Jon E. Froehlich
// https://makeabilitylab.cs.washington.edu/
let mic;
let xCircle;
let yCircle;
const MIN_CIRCLE_DIAMETER = 50;
const MAX_CIRCLE_DIAMETER = 800;
// Set up average smoothing
let micLevelBuffer = null;
let micLevelBufferIndex = 0;
let micLevelRunningTotal = 0;
let micLevelAverage = 0;
function setup() {
createCanvas(400, 400);
// see https://p5js.org/reference/#/p5.AudioIn
mic = new p5.AudioIn();
mic.start();
// We read the mic level once per frame. By default,
// we draw 60 frames/sec. So, let's set the mic level buffer
// to one half second (30 samples).
// Make this bigger to average more values
micLevelBuffer = new Array(30).fill(0);
// Set x,y of circle in middle of canvas
xCircle = width / 2;
yCircle = height / 2;
//noLoop();
}
function draw() {
background(100, 100, 100, 10);
//background(100);
// get current microphone level, which returns a
// value between 0 and 1 where 1 is loudest (highest amplitude)
let micLevel = mic.getLevel(0.8); // smoothing value is 0.8
addMicLevelToBuffer(micLevel)
// the size of the circle proportional to mic level
// The min and max of micLevel is 0 - 1. Map this to
// the diameter values of 5 to maxDiameter
let currentMicDiameter = map(micLevel, 0, 1, MIN_CIRCLE_DIAMETER, MAX_CIRCLE_DIAMETER);
noFill();
fill(0, 0, 200, 100);
noStroke();
//strokeWeight(5);
//stroke(200, 0, 0, 200);
circle(xCircle, yCircle, currentMicDiameter);
// Draw the average circle
let avgMicDiameter = map(micLevelAverage, 0, 1, MIN_CIRCLE_DIAMETER, MAX_CIRCLE_DIAMETER);
fill(0, 200, 0, 100);
noStroke();
//noFill();
strokeWeight(1);
//stroke(0, 0, 200, 200);
circle(xCircle, yCircle, avgMicDiameter);
}
function addMicLevelToBuffer(micLevel){
// subtract the last reading:
micLevelRunningTotal = micLevelRunningTotal - micLevelBuffer[micLevelBufferIndex];
// read from the sensor:
micLevelBuffer[micLevelBufferIndex] = micLevel;
// add the reading to the total:
micLevelRunningTotal = micLevelRunningTotal + micLevelBuffer[micLevelBufferIndex];
// advance to the next position in the array:
micLevelBufferIndex = micLevelBufferIndex + 1;
// if we're at the end of the array...
if (micLevelBufferIndex >= micLevelBuffer.length) {
// Wrap around to the beginning:
micLevelBufferIndex = 0;
}
micLevelAverage = micLevelRunningTotal / micLevelBuffer.length;
}