xxxxxxxxxx
// A sound file object
var song;
var analyzer;
function preload() {
// Load a sound file
song = loadSound('music-box.mp3');
}
function setup() {
createCanvas(710, 400);
song.loop();
// create a new Amplitude analyzer
analyzer = new p5.Amplitude();
// Patch the input to an volume analyzer
analyzer.setInput(song);
}
function draw() {
background(200);
// Set the volume to a range between 0 and 1.0
var volume = map(mouseX, 0, width, 0, 1);
volume = constrain(volume, 0, 1);
song.amp(volume);
// Set the rate to a range between 0.1 and 4
// Changing the rate alters the pitch
var speed = map(mouseY, 0.1, height, 0, 2);
speed = constrain(speed, 0.01, 4);
song.rate(speed);
// Draw some circles to show what is going on
stroke(0);
fill(51, 100);
ellipse(mouseX, 100, 48, 48);
text("<--Speed-->", width/4, 50);
stroke(0);
fill(51, 100);
ellipse(100, mouseY, 48, 48);
text("volume", 50, height/2);
// Get the average (root mean square) amplitude
var rms = analyzer.getLevel();
fill(127);
stroke(0);
// Draw an ellipse with size based on volume
ellipse(width/2, height/2, 10+rms*200, 10+rms*200);
noFill();
text("circle represents the amplitude of sound", width/2, height/2 - 30);
}