Skip to content

Instantly share code, notes, and snippets.

@pwFoo
Forked from connor-davis/audio-recorder-gun.html
Created January 15, 2023 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwFoo/3516f565c7040d9d3a260487ffe5a6e4 to your computer and use it in GitHub Desktop.
Save pwFoo/3516f565c7040d9d3a260487ffe5a6e4 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