I recently completed a tutorial on audio recording in JavaScript where an array is used to store the recorded audio and convert it into a URL for playback. The setup includes a button with a function that both records and automatically plays the audio when clicked. However, I am now looking to add a second button that will only play the audio when pressed, rather than playing automatically after recording. How can I achieve this using plain JavaScript?
Any help or guidance would be greatly appreciated.
function setup() {
createCanvas(400, 400);
button = createButton('Audio Hack');
button.position(160, 180);
button.mousePressed(audioHack);
}
function audioHack() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
const mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
const audioChunks = [];
mediaRecorder.addEventListener("dataavailable", event => {
audioChunks.push(event.data);
});
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks);
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
});
setTimeout(() => {
mediaRecorder.stop();
}, 3000);
});
}