Skip to content

Instantly share code, notes, and snippets.

@RafaelQuirino
Forked from bryanjenningz/record-stop.html
Created November 6, 2018 16:03
Show Gist options
  • Save RafaelQuirino/477b996003fc81bf17729c1f01e3def6 to your computer and use it in GitHub Desktop.
Save RafaelQuirino/477b996003fc81bf17729c1f01e3def6 to your computer and use it in GitHub Desktop.
<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