I've added to my script from an example on the p5.js website.
I'd expect that an amplitude beyond 1.0 would satisfy the condition of their being a peak. I have set my amplitude range from 0 to 1.2, depending on the mouse y position. I can see that the amplitude reads out as 1.2, but the peakDectect.isDetected
does not trigger.
fft.analyze
was called, then fft is passed to peakDetect.update()
so that it reads peakDetect.update(fft)
.
Code I'm using is below.
let fft, peakDetect, osc, lfo, playing, freq, amp;
function setup() {
let cnv = createCanvas(300, 100);
cnv.mousePressed(playOscillator);
osc = new p5.Oscillator('sine');
lfo = new p5.Oscillator('sine');
filter = new p5.Filter();
fft = new p5.FFT();
peakDetect = new p5.PeakDetect();
// chain
lfo.disconnect();
osc.disconnect();
osc.connect(filter);
}
function draw() {
background(220)
freq = constrain(map(mouseX, 0, width, 40, 1000), 40, 1000);
amp = constrain(map(mouseY, height, 0, 0, 1.2), 0, 1.2);
if (playing) {
// smooth the transitions by 0.1 seconds
lfo.freq(2.9);
osc.freq(freq, 0.1);
osc.amp(amp, 0.1);
filter.freq(1200);
filter.res(14);
// how many Hz should the LFO oscillate
lfo.amp(1500);
// connect the lfo
filter.freq(lfo);
let spectrum = fft.analyze();
noStroke();
fill(255, 0, 255);
for (let i = 0; i < spectrum.length; i++) {
let x = map(i, 0, spectrum.length, 0, width);
let h = -height + map(spectrum[i], 0, 255, height, 0);
rect(x, height, width / spectrum.length, h)
}
let waveform = fft.waveform();
noFill();
beginShape();
stroke(255, 100, 0);
for (let i = 0; i < waveform.length; i++) {
let x = map(i, 0, waveform.length, 0, width);
let y = map(waveform[i], -1, 1, 0, height);
vertex(x, y);
}
endShape();
// fft.analyze() has already been called.
// check fft for peak detection.
peakDetect.update(fft);
var ellipseWidth = 10;
if (peakDetect.isDetected) {
ellipseWidth = 50;
} else {
ellipseWidth *= 0.95;
}
noStroke();
fill(0, 0, 0);
ellipse(width / 2, height / 2, ellipseWidth, ellipseWidth);
}
fill(0, 0, 0);
noStroke();
text('tap to play', 20, 20);
text('freq: ' + freq, 20, 40);
text('amp: ' + amp, 20, 60);
}
function playOscillator() {
osc.start();
lfo.start();
playing = true;
}
function mouseReleased() {
// ramp amplitude to 0 over 0.5 seconds
osc.amp(0, 0.2);
playing = false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/addons/p5.sound.min.js"></script>