Skip to content

Instantly share code, notes, and snippets.

@sanjarcode
Created March 25, 2023 18:32
Show Gist options
  • Save sanjarcode/e16b1fdab0f0b11b13d6630ea506393f to your computer and use it in GitHub Desktop.
Save sanjarcode/e16b1fdab0f0b11b13d6630ea506393f to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Record Audio</title>
<style>
#audio-list {
list-style: none;
}
</style>
</head>
<body>
<div>
<button id="record">Record</button>
<button id="pause">Pause (don't work)</button>
<button id="stop">Stop (don't work)</button>
<button id="save">Save</button>
</div>
<div>
<h2>Audio list</h2>
<ul id="audio-list"></ul>
</div>
<script>
let chunks = [];
let recorder;
let blob = null;
const recordButton = document.getElementById("record");
const pauseButton = document.getElementById("pause");
const stopButton = document.getElementById("stop");
const saveButton = document.getElementById("save");
recordButton.addEventListener("click", startRecording);
pauseButton.addEventListener("click", pauseRecording);
stopButton.addEventListener("click", stopRecording);
saveButton.addEventListener("click", saveRecording);
async function startRecording() {
const audioStream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
recorder = new MediaRecorder(audioStream);
recorder.start();
recordButton.disabled = true;
pauseButton.disabled = false;
stopButton.disabled = false;
recorder.addEventListener("dataavailable", function (event) {
saveAsFile(event.data);
});
}
function saveRecording(blob) {
stopRecording();
recorder.stop();
}
function saveAsFile(blob) {
// const blob = new Blob(chunks, { type: "audio/wav" });
const url = URL.createObjectURL(blob);
addEntry(url);
return;
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = "recording.ogg";
a.click();
window.URL.revokeObjectURL(url);
}
function pauseRecording() {
if (recorder.state === "recording") {
recorder.pause();
pauseButton.innerHTML = "Resume";
} else if (recorder.state === "paused") {
recorder.resume();
pauseButton.innerHTML = "Pause";
}
}
function stopRecording() {
recorder.stop();
recordButton.disabled = false;
pauseButton.disabled = true;
stopButton.disabled = true;
}
function addEntry(url) {
const entryContainer = document.createElement("li");
const entryContent = document.createElement("audio");
entryContent.setAttribute("controls", "true");
entryContent.src = url;
entryContainer.appendChild(entryContent);
const entryList = document.getElementById("audio-list");
entryList.appendChild(entryContainer);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment