Skip to content

Instantly share code, notes, and snippets.

@haneulee
Created December 8, 2022 09:16
Show Gist options
  • Save haneulee/2f784075017fd046643ff36a4e45dd32 to your computer and use it in GitHub Desktop.
Save haneulee/2f784075017fd046643ff36a4e45dd32 to your computer and use it in GitHub Desktop.
recording
let recorder = null;
let audio = null;
const audioChunks = [];
const recordAudio = () =>
new Promise(async (resolve) => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream);
mediaRecorder.addEventListener("dataavailable", (event) => {
audioChunks.push(event.data);
});
const start = () => mediaRecorder.start();
const stop = () =>
new Promise((resolve) => {
mediaRecorder.addEventListener("stop", () => {
console.log(audioChunks);
const audioBlob = new Blob(audioChunks);
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
const play = () => audio.play();
resolve({ audioBlob, audioUrl, play });
});
mediaRecorder.stop();
});
resolve({ start, stop });
});
const onClick = async () => {
if (recorder) {
audio = await recorder.stop();
recorder = null;
const file = new File([audio.audioBlob], "name.wav", {
lastModified: new Date().getTime(),
type: "audio/wav",
});
console.log(audio, file);
} else {
recorder = await recordAudio();
recorder.start();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment