Created
December 8, 2022 09:16
-
-
Save haneulee/2f784075017fd046643ff36a4e45dd32 to your computer and use it in GitHub Desktop.
recording
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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