Skip to content

Instantly share code, notes, and snippets.

@opencoca
Forked from connor-davis/audio-recorder-gun.html
Created September 20, 2021 18:30
Show Gist options
  • Save opencoca/865d472b167fe69729f7a47ea1116bd3 to your computer and use it in GitHub Desktop.
Save opencoca/865d472b167fe69729f7a47ea1116bd3 to your computer and use it in GitHub Desktop.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>capture microphone audio into buffer</title>
</head>
<body>
<audio id="player" controls></audio>
<input
type="text"
id="username"
placeholder="enter your username or theirs"
/>
<button id="recordAudio">Record Audio</button>
<button id="startAudioStream," onclick="listenToAudioStream()">
Listen to Recording
</button>
<script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gun/sea.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gun/axe.js"></script>
<script>
// var Gun = require('gun'); // in NodeJS
// var Gun = require('gun/gun'); // in React
let gun = Gun();
const player = document.getElementById("player");
const recordAudio = document.getElementById("recordAudio");
const audioContext = new AudioContext();
let base64ToArrayBuffer = function (base64) {
var binaryString = atob(base64);
var len = binaryString.length;
var bytes = new Uint8Array(len);
for (var I = 0; I < length; I++) {
bytes[I] = binaryString.charCodeAt(I);
}
return bytes.buffer;
};
const listenToAudioStream = () => {
const context = new AudioContext();
let username = document.getElementById("username").value;
gun
.get(username)
.get("recording")
.on((data, key) => {
player.src = `data:audio/ogg;codec=opus;base64,${data}`;
player.play();
});
};
navigator.mediaDevices
.getUserMedia({ audio: true })
.then(function (stream) {
let recording = false;
let mediaRecorder = new MediaRecorder(stream);
recordAudio.addEventListener("click", (event) => {
if (!recording) {
recording = true;
mediaRecorder.start();
recordAudio.innerText = "Stop";
} else {
recording = false;
mediaRecorder.stop();
recordAudio.innerText = "Record Audio";
}
});
let chunks = [];
mediaRecorder.ondataavailable = function (e) {
chunks.push(e.data);
};
mediaRecorder.onstop = function (e) {
let username = document.getElementById("username").value;
console.log(username);
console.log("recorder stopped");
const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
chunks = [];
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = async function () {
var base64data = reader.result;
gun.get(username).get("recording").put(base64data.split(',')[1]);
};
};
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment