xxxxxxxxxx
62
var song;
var amp;
var volhistory = [];
function preload() {
song = loadSound('drums.mp3');
}
function setup() {
createCanvas(windowWidth, windowHeight);
background(0);
song.loop();
amp = new p5.Amplitude();
}
function draw() {
background(0);
//get current amplitude and add to array
var vol = amp.getLevel();
volhistory.push(vol);
stroke(255);
noFill();
//draw each amplitude in the array
beginShape();
for (var i = 0; i < volhistory.length; i++) {
var y = map(volhistory[i], 0, 1, height/2, 0);
vertex(i, y);
}
endShape();
// if the graph reaches the edge of the window, delete the oldest item in the array to scroll the graph
if (volhistory.length > width-50) {
volhistory.splice(0, 1);
}
// red playhead
stroke(255, 0, 0);
line(volhistory.length, 0, volhistory.length, height);
//visual pause indicator
if (song.isPaused()) {
fill(255);
rect(30, 30, 30, 30);
}
}
// toggle playback by clicking sketch window
function mousePressed() {
if ( song.isPlaying() ) {
song.pause();
} else {
song.play();
}
}