xxxxxxxxxx
70
//
// A basic scrolling visualization of sound level over time
//
// For a simpler non-scrolling version, see:
// https://editor.p5js.org/jonfroehlich/sketches/_0MKEdEqp
//
// By Professor Jon E. Froehlich
// https://jonfroehlich.github.io/
// http://makeabilitylab.cs.washington.edu
//
let mic;
let currentXPos = 0;
let circularBuffer; // efficient way to store values
let curWriteIndex = 0; // tracks where we are in the circular buffer
function setup() {
createCanvas(600, 400);
// Gets a reference to computer's microphone
// https://p5js.org/reference/#/p5.AudioIn
mic = new p5.AudioIn();
// Start processing audio input
// https://p5js.org/reference/#/p5.AudioIn/start
mic.start();
circularBuffer = new Array(width);
// Set stroke color
stroke(255);
}
function draw() {
background(100);
// Get current microphone level (between 0 and 1)
// See: https://p5js.org/reference/#/p5.AudioIn/getLevel
let micLevel = mic.getLevel(); // between 0 and 1
circularBuffer[curWriteIndex++] = micLevel;
// Set the circular buffer index back to zero when it reaches the
// right of the screen
if(curWriteIndex >= width){
curWriteIndex = 0;
}
// Draw the line graph based on data in circularBuffer
let xPos = 0;
for (let i = curWriteIndex; i < width; i++){
let val = circularBuffer[i];
drawLine(xPos, val);
xPos++;
}
for(let i = 0; i < curWriteIndex; i++){
let val = circularBuffer[i];
drawLine(xPos, val);
xPos++;
}
}
function drawLine(xPos, val){
const yStart = height;
const yLineHeight = val * height;
const yEnd = yStart - yLineHeight;
line(xPos, yStart, xPos, yEnd);
}