xxxxxxxxxx
108
let mic, recorder, soundFile, originalSoundFile;
let recordButton, playButton, highButton, lowButton, echoButton, reverseButton;
let isRecording = false;
let maxRecordingTime = 2; // in seconds
function preload() {
// load the background image
bgImage = loadImage('bg_Image.png');
}
function setup() {
createCanvas(500, 500);
background(bgImage);
mic = new p5.AudioIn();
mic.start();
recorder = new p5.SoundRecorder();
recorder.setInput(mic);
soundFile = new p5.SoundFile();
originalSoundFile = soundFile; // store the original sound file
recordButton = createButton('Record');
recordButton.mousePressed(startRecording);
playButton = createButton('Play');
playButton.mousePressed(playRecording);
highButton = createButton('High Pitch');
highButton.mousePressed(highPitch);
lowButton = createButton('Low Pitch');
lowButton.mousePressed(lowPitch);
echoButton = createButton('Echo');
echoButton.mousePressed(addEcho);
reverseButton = createButton('Reverse');
reverseButton.mousePressed(reverseSound);
}
function startRecording() {
if (!isRecording) {
recorder.record(soundFile, maxRecordingTime, () => {
console.log('Recording stopped');
});
recordButton.html('Stop Recording');
isRecording = true;
} else {
recorder.stop();
recordButton.html('Record');
isRecording = false;
}
}
function playRecording() {
soundFile.play();
}
function highPitch() {
soundFile.rate(2);
soundFile.play();
setTimeout(() => {
soundFile.rate(1);
}, soundFile.duration() * 1000);
}
function lowPitch() {
soundFile.rate(0.5);
soundFile.play();
setTimeout(() => {
soundFile.rate(1);
}, soundFile.duration() * 1000);
}
function addEcho() {
let delayTime = 0.3; // in seconds
let decayRate = 0.5;
let newSound = new p5.SoundFile();
// create a new sound with delay effect
for (let i = 0; i < soundFile.buffer.length; i++) {
let sample = soundFile.buffer.getChannelData(0)[i];
let delayIndex = i - int(delayTime * soundFile.buffer.sampleRate);
let delaySample = delayIndex < 0 ? 0 : soundFile.buffer.getChannelData(0)[delayIndex];
let decay = pow(decayRate, i);
newSound.buffer.getChannelData(0)[i] = sample + delaySample * decay;
}
soundFile = newSound;
soundFile.play();
}
function reverseSound() {
let newSound = new p5.SoundFile();
// create a new sound that is the reverse of the original sound
for (let i = 0; i < soundFile.buffer.length; i++) {
let sample = soundFile.buffer.getChannelData(0)[i];
let newIndex = soundFile.buffer.length - i - 1;
newSound.buffer.getChannelData(0)[newIndex] = sample;
}
soundFile = newSound;
soundFile.play();
}