-
-
Save RafaelQuirino/477b996003fc81bf17729c1f01e3def6 to your computer and use it in GitHub Desktop.
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
<button onclick="recordStop()" id="record-stop-button">Record</button> | |
<button onclick="playAudio()" disabled id="play-audio-button">Play</button> | |
<script> | |
const recordAudio = () => | |
new Promise(async resolve => { | |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
const mediaRecorder = new MediaRecorder(stream); | |
const audioChunks = []; | |
mediaRecorder.addEventListener("dataavailable", event => { | |
audioChunks.push(event.data); | |
}); | |
const start = () => mediaRecorder.start(); | |
const stop = () => | |
new Promise(resolve => { | |
mediaRecorder.addEventListener("stop", () => { | |
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 }); | |
}); | |
let recorder = null; | |
let audio = null; | |
const recordStop = async () => { | |
if (recorder) { | |
audio = await recorder.stop(); | |
recorder = null; | |
document.querySelector("#record-stop-button").textContent = "Record"; | |
document.querySelector("#play-audio-button").removeAttribute("disabled"); | |
} else { | |
recorder = await recordAudio(); | |
recorder.start(); | |
document.querySelector("#record-stop-button").textContent = "Stop"; | |
} | |
}; | |
const playAudio = () => { | |
if (audio && typeof audio.play === "function") { | |
audio.play(); | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment