Code: Select all
Record and Play Sound
Start Recording and Play Sound
Stop Recording and Sound
let mediaRecorder;
let audioChunks = [];
let playAudioContext;
let source;
// document.addEventListener('DOMContentLoaded', async () => {
// });
document.getElementById('start').addEventListener('click', async () => {
// Play a sound in a separate audio context
playAudioContext = new (window.AudioContext || window.webkitAudioContext)();
const response = await fetch('/mp3');
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await playAudioContext.decodeAudioData(arrayBuffer);
source = playAudioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(playAudioContext.destination);
// recording
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = event => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
document.getElementById('audioPlayback').src = audioUrl;
audioChunks=[];
};
mediaRecorder.start(100);
source.start();
});
document.getElementById('stop').addEventListener('click', () => {
mediaRecorder.stop();
if (source) {
source.stop();
}
if (playAudioContext) {
playAudioContext.close();
}
});