Started working on an AI Wearable project and needed a clean native way of recording voice and saving it.
This methodology is the best and cross-platform. Enjoy using it 😉
<button id="startButton">Start Recording</button>
<button id="stopButton" style="display: none;">Stop Recording</button>
<script>
let mediaRecorder;
let audioChunks = [];
document.getElementById("startButton").addEventListener("click", function() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
mediaRecorder.addEventListener("dataavailable", event => {
audioChunks.push(event.data);
});
this.style.display = 'none';
document.getElementById("stopButton").style.display = '';
});
});
document.getElementById("stopButton").addEventListener("click", function() {
mediaRecorder.stop();
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
// Create a download link for the WAV file
const downloadLink = document.createElement("a");
downloadLink.href = audioUrl;
downloadLink.download = "recorded_audio.wav";
downloadLink.textContent = "Download WAV";
document.body.appendChild(downloadLink);
audioChunks = [];
this.style.display = 'none';
document.getElementById("startButton").style.display = '';
});
});
</script>
Here is the working demo that you can try on codepen.
Tested Chrome and Firefox works fine. Not sure about Safari. Safari pain in the ass I will not even bother looking for that stupid browser. Maybe later.