Skip to content

Instantly share code, notes, and snippets.

@bryanjenningz
Created October 7, 2018 17:31
Show Gist options
  • Save bryanjenningz/f60c42b0a2091c91bad21c91faadc88d to your computer and use it in GitHub Desktop.
Save bryanjenningz/f60c42b0a2091c91bad21c91faadc88d 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