You guys are awesome. This is what I was making ( the full code that the above problem was a snippet from ). I am having problems with this algorithm in the below code. Specifically the guy in the article uses 250 as his constant C (See beat algorithm 2 - frequency selected sound energy), no idea how he got that number, but it doesn’t work at all for me. See what you think, maybe this belongs in another post all together, but thought I’d share.
let sound;
let size;
function preload() {
//put your sound file here
sound = loadSound("../audio/17.mp3");
}
function setup() {
createCanvas(500,500);
frameRate(60);
beatDetect = new BeatDetect();
sound.loop();
}
function draw() {
background(0);
if( beatDetect.detectBeat() ) {
fill(255,0,0);
//console.log(size);
ellipse(width/2,height/2,size,size);
}
}
//BeatDetect constructor
function BeatDetect() {
//http://archive.gamedev.net/archive/reference/programming/features/beatdetection/
let sampleBuffer=[]; //sample history buffer
let bandsAverage=[]; //array of averages of the bands
let energyBuffer=[]; //array of current sound energies per band
let fourier = new p5.FFT();
this.detectBeat = function() {
//analyze fourier
let spectrum=fourier.analyze();
var count=0; // reset count every frame
var isBeat=false; // reset isBeat every frame
let bandsEnergy=[]; // start a new array each frame, so we don't pass in an array reference :)
let bands_temp=[]; // temp array to split the frequency bands
for(let i=0; i < spectrum.length; i++) {
energyBuffer[i] = spectrum[i] * spectrum[i];
bands_temp.push(energyBuffer[i]); // temp array to split into grouped bands
//collect 32 samples (one band of 1024 i.e. 1024/32 = 32 bands)
if(bands_temp.length == 32) {
let sum=0; // init the sum to zero
for(let j=0; j < bands_temp.length; j++) {
sum+=bands_temp[j]; // get the sum of the band's samples
bandsEnergy[count] = sum; // get average energy of band's grouping
}
bands_temp=[]; //clear temp bands_sum array for next set of 32 samples;
count++; //increment count index, reset this every frame;
}
}
sampleBuffer.push(bandsEnergy);
//+1 since we remove a value each frame
if(sampleBuffer.length == 43 + (1)) {
for(let j = 0; j < bandsEnergy.length; j++) {
let bandSum=0; // reset bandSum when we get to a new band
//loop through all arrays in history buffer
for(let k=0; k < sampleBuffer.length; k++) {
bandSum += sampleBuffer[k][j]; // get the sum for each freq. band in the buffer
}
//calc avg from sum in each band of the buffer
bandsAverage[j] = bandSum/sampleBuffer.length;
}
//remove the oldest sample from the array
sampleBuffer.splice(0,1);
}
for(let k=0; k < sampleBuffer.length; k++) {
let c = 1; //???
if(bandsEnergy[k] > bandsAverage[k]*c) {
isBeat=true;
size=(bandsEnergy[k])*.0002;
return isBeat;
}
}
//console.log(bandsEnergy.length);
//console.log(sampleBuffer.length);
//console.log( bandsAverage[14] + "bandAverage");
//console.log( bandsEnergy[14] + "bandEnergy");
} // end DETECT
} // end CONSTRUCTOR