Recording Audio Using JavaScript

JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side scripts to interact with the user and make dynamic pages. Here one important thing is that recording audio or video on web pages is also done using JavaScript.

Step 1:- Create an index.html file and add the following code in your HTML file

<!doctype html>
<title>Record Audio Test</title>
<h1>Audio Recording Test</h1>
<p>Talk for 3 seconds, then you will hear your recording played back</p>
<script src="index.js"></script>
<button id="action" onclick="handleAction()">Start recording...</button>

Step 2:- Create an index.js file and add the following code in your js file

const recordAudio = () =>
new Promise(async resolve => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream);
const audioChunks = [];

mediaRecorder.addEventListener("dataavailable", event => {

const start = () => mediaRecorder.start();

const stop = () =>
new Promise(resolve => {
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { type: "audio/mpeg" });
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
const play = () =>;
resolve({ audioBlob, audioUrl, play });


resolve({ start, stop });

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

const handleAction = async () => {
const recorder = await recordAudio();
const actionButton = document.getElementById("action");
actionButton.disabled = true;
await sleep(3000);
const audio = await recorder.stop();;
await sleep(3000);
actionButton.disabled = false;

Here’s an example of how to use the API we just created. This example records audio for 3 seconds, then plays the audio that was recorded.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories