In this article you will learn how to use Audio Recording API, RecordRTC is a library for Audio, Video or Canvas recording
So lets start to implement Audio recording feature in website,
Key Features
- Audio Recording
- Start and Stop Recording
- Auto Stop Recording
- Download Recording
- Listening the recording after stop recording
Creating a Recording page
<html>
<head>
<style>
html,
body {
margin: 0 !important;
padding: 0 !important;
}
</style>
<title>Audio Recording | RecordRTC</title>
<h1>Audio Recording using RecordRTC | technostuf.com</h1>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
</head>
<button id="btn-start-recording">Start Recording</button>
<button id="btn-stop-recording" disabled>Stop Recording</button>
<button id="btn-release-microphone" disabled>Release Microphone</button>
<button id="btn-download-recording" disabled>Download</button>
<hr>
<div>
<audio controls autoplay playsinline></audio>
</div>
<script src="./RecordRTC.js"></script>
</html>
We will use a popular RecordRTC open source library from Muaz khan, we need to include first in HTML
HTML Output
![audio recording - technostuf.com](https://technostuf.com/wp-content/uploads/2022/03/screen.png)
Start Recording
var audio = document.querySelector('audio');
function captureMicrophone(callback) {
btnReleaseMicrophone.disabled = false;
if(microphone) {
callback(microphone);
return;
}
if(typeof navigator.mediaDevices === 'undefined' || !navigator.mediaDevices.getUserMedia) {
alert('This browser does not supports WebRTC getUserMedia API.');
if(!!navigator.getUserMedia) {
alert('This browser seems supporting deprecated getUserMedia API.');
}
}
navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: false
}
}).then(function(mic) {
callback(mic);
}).catch(function(error) {
alert('Unable to capture your microphone. Please check console logs.');
console.error(error);
});
}
function replaceAudio(src) {
var newAudio = document.createElement('audio');
newAudio.controls = true;
newAudio.autoplay = true;
if(src) {
newAudio.src = src;
}
var parentNode = audio.parentNode;
parentNode.innerHTML = '';
parentNode.appendChild(newAudio);
audio = newAudio;
}
var recorder; // globally accessible
var microphone;
var btnStartRecording = document.getElementById('btn-start-recording');
var btnStopRecording = document.getElementById('btn-stop-recording');
var btnReleaseMicrophone = document.querySelector('#btn-release-microphone');
var btnDownloadRecording = document.getElementById('btn-download-recording');
btnStartRecording.onclick = function() {
this.disabled = false;
if (!microphone) {
captureMicrophone(function(mic) {
microphone = mic;
click(btnStartRecording);
});
return;
}
replaceAudio();
audio.muted = true;
audio.srcObject = microphone;
var options = {
type: 'audio',
numberOfAudioChannels: 2,
checkForInactiveTracks: true,
bufferSize: 16384
};
if(navigator.platform && navigator.platform.toString().toLowerCase().indexOf('win') === -1) {
options.sampleRate = 48000; // or 44100 or remove this line for default
}
if(recorder) {
recorder.destroy();
recorder = null;
}
recorder = RecordRTC(microphone, options);
recorder.startRecording();
btnStopRecording.disabled = false;
btnDownloadRecording.disabled = true;
};
function click(el) {
el.disabled = false; // make sure that element is not disabled
var evt = document.createEvent('Event');
evt.initEvent('click', true, true);
el.dispatchEvent(evt);
}
When user clicking on the start button click event code will be execute, on the first attempt captureMicrophone() function will be call
The MediaDevices.getUserMedia() method prompt the user permission to use media input use in MedeaStream, getUserMedia() method can be use for video recording, screen recording, audio recording etc..
Stop Recording
btnStopRecording.onclick = function() {
this.disabled = true;
recorder.stopRecording(stopRecordingCallback);
};
function stopRecordingCallback() {
replaceAudio(URL.createObjectURL(recorder.getBlob()));
btnStartRecording.disabled = false;
setTimeout(function() {
if(!audio.paused) return;
setTimeout(function() {
if(!audio.paused) return;
audio.play();
}, 1000);
audio.play();
}, 300);
audio.play();
btnDownloadRecording.disabled = false;
}
Release a Microphone
btnReleaseMicrophone.onclick = function() {
this.disabled = true;
btnStartRecording.disabled = false;
if(microphone) {
microphone.stop();
microphone = null;
}
if(recorder) {
// click(btnStopRecording);
}
};
The release will release the system microphone access, microphone.stop() method will stop the access of microphone
Download Recording
btnDownloadRecording.onclick = function() {
this.disabled = true;
if(!recorder || !recorder.getBlob()) return;
var blob = recorder.getBlob();
var file = new File([blob], getFileName('mp3'), {
type: 'audio/mp3'
});
invokeSaveAsDialog(file);
};
function getRandomString() {
if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
var a = window.crypto.getRandomValues(new Uint32Array(3)),
token = '';
for (var i = 0, l = a.length; i < l; i++) {
token += a[i].toString(36);
}
return token;
} else {
return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
}
}
function getFileName(fileExtension) {
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var date = d.getDate();
return 'Video-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
}
invokeSaveAsDialog is global method, accept two parameter, 1st is file or blob object and second parameter is file name, it is optional
You can download the working example of How to Record Audio in JavaScript
https://github.com/technostuf/audio-recording
Related Post
- React Material UI Form example
- React Material UI Autocomplete with getting selected value
- React Area chart using recharts example
- React Pie chart using recharts with legend and custom label
- React google maps draggable marker example
- React datepicker using the most popular react-datepicker library
- React toast notification using react-toastify with example
- React responsive carousel slider with react-slick
- React tooltip using rc-tooltip with example
- React hook form schema validation using yup