Skip to content

Instantly share code, notes, and snippets.

@usametov
Last active June 13, 2023 02:58
Show Gist options
  • Save usametov/35be920178ccae1b864ae430bc976354 to your computer and use it in GitHub Desktop.
Save usametov/35be920178ccae1b864ae430bc976354 to your computer and use it in GitHub Desktop.
Simple audio recording demo
<!DOCYTPE html>
<html>
<head>
<title>Simple audio recording demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<input type="button" class="btn" value="click and hold to record" />
<script type="text/javascript">
// courtesy https://medium.com/@bryanjenningz/how-to-record-and-play-audio-in-javascript-faa1b2b3e49b
const recordAudio = () => {
return 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 });
});
}
/* simple timeout */
const sleep = time => new Promise(resolve => setTimeout(resolve, time));
/* init */
(async () => {
const btn = document.querySelector("input");
const recorder = await recordAudio();
let audio; // filled in end cb
const recStart = e => {
recorder.start();
btn.initialValue = btn.value;
btn.value = "recording...";
}
const recEnd = async e => {
btn.value = btn.initialValue;
audio = await recorder.stop();
audio.play();
uploadAudio(audio.audioBlob);
}
const uploadAudio = a => {
if (a.size > (10 * Math.pow(1024, 2))) {
document.body.innerHTML += "Too big; could not upload";
return;
}
const f = new FormData();
f.append("nonce", Math.floor(Math.random()*10000000));
f.append("payload", a);
fetch("upload_audio", {
method: "POST",
body: f
})
.then(_ => {
document.body.innerHTML += `
<br/> saved
`
});
}
btn.addEventListener("mousedown", recStart);
btn.addEventListener("touchstart", recStart);
window.addEventListener("mouseup", recEnd);
window.addEventListener("touchend", recEnd);
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment