xxxxxxxxxx
67
let lowerPitchOsc;
let higherPitchOsc;
let lowerPitchTimer = 0;
let higherPitchTimer = 0;
let intervalLowerPitch = 1370;
let intervalHigherPitch = 1450;
let isPlaying = false;
function setup() {
createCanvas(400, 400);
// Create oscillators for the sounds
lowerPitchOsc = new p5.Oscillator(220, 'sine'); // 220 Hz (A3)
higherPitchOsc = new p5.Oscillator(440, 'sine'); // 440 Hz (A4)
// Create play and stop buttons
let playButton = createButton('Play');
playButton.position(150, 150);
playButton.mousePressed(playSounds);
let stopButton = createButton('Stop');
stopButton.position(250, 150);
stopButton.mousePressed(stopSounds);
}
function draw() {
background(220);
if (isPlaying) {
// Update timers
lowerPitchTimer += deltaTime;
higherPitchTimer += deltaTime;
// Check if it's time to play the lower pitch sound
if (lowerPitchTimer >= intervalLowerPitch) {
lowerPitchOsc.start();
lowerPitchOsc.amp(0.5, 0.5); // Set amplitude to 0.5 over 0.5 seconds
setTimeout(() => {
lowerPitchOsc.amp(0, 0.5); // Fade out over 0.5 seconds
}, 500); // Play for 0.5 seconds
lowerPitchTimer = 0;
}
// Check if it's time to play the higher pitch sound
if (higherPitchTimer >= intervalHigherPitch) {
higherPitchOsc.start();
higherPitchOsc.amp(0.5, 0.5); // Set amplitude to 0.5 over 0.5 seconds
setTimeout(() => {
higherPitchOsc.amp(0, 0.5); // Fade out over 0.5 seconds
}, 500); // Play for 0.5 seconds
higherPitchTimer = 0;
}
}
}
function playSounds() {
isPlaying = true;
}
function stopSounds() {
isPlaying = false;
lowerPitchOsc.stop();
higherPitchOsc.stop();
lowerPitchTimer = 0;
higherPitchTimer = 0;
}