Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to record and play audio in JavaScript?
Are you also willing to add a custom audio recording feature to your web application? If yes, you are in the right place, as we will learn to record and play audio using JavaScript in this tutorial.
Some applications like Discord allow you to record the audio and store it inside that to play it anytime. The recorded audio can also be used as a meme for fun, alerts in the discord meetings, etc.
We can also use the MediaRecorder API of JavaScript to add the recording audio feature to our web application. Here, we will learn a step-by-step guide to recording, storing, and playing audio.
Syntax
Users can follow the syntax below to record and play audio using the MediaRecorder API.
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
audioRecorder = new MediaRecorder(stream);
audioRecorder.start();
audioRecorder.stop();
const blobObj = new Blob(audioChunks, { type: 'audio/webm' });
const audioUrl = URL.createObjectURL(blobObj);
const audio = new Audio(audioUrl);
audio.play();
})
Parameters and Methods Explained
Navigator.mediaDevices ? The mediaDevices object provides access to the media related functionality such as audio and video stream.
getUserMedia() ? The getUserMedia() method requests the user's media stream's permission. It takes the object containing the type of media streams as a parameter. Here we used { audio: true } to access the audio stream and ask for the permission of the microphone.
Stream ? We passed it as a parameter of the callback function, which we get after users approve the permission.
MediaRecorder ? We can use the MediaRecorder() constructor by passing the stream variable as a parameter to create a new media recorder.
start() ? It is used to start recording.
stop() ? It is used to stop recording.
Blob() ? It is used to convert audio chunks in the blob object.
createObjectURL() ? It creates audio URLs from the blob object.
Audio() ? It converts audio URLs to audio.
play() ? It is used to play the audio URL.
Example
We added the start, stop, and play recording buttons in the example below. In JavaScript, we access the media stream of users' devices, and after that, we initialize the media recorder object using the media stream.
Next, we invoke the method based on the button clicked and store the recorder audio in the 'audioChunks' array. Also, we used the catch() block to catch errors while recording the audio.
In the output, users can click the start recording button to start the recording. After that, click the stop recording button once the recording completes. Next, click the play recording button to play the recorded audio.
<html>
<head>
<style>
button {
margin: 5px;
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
div {
margin-top: 20px;
}
#output {
padding: 10px;
background-color: #f8f9fa;
border-radius: 5px;
margin-top: 10px;
}
</style>
</head>
<body>
<h3>Using the MediaRecorder API to record audio in the web browser</h3>
<div>
<button id="start">Start Recording</button>
<button id="stop">Stop Recording</button>
<button id="play">Play Recorded Audio</button>
</div>
<div id="output">Click 'Start Recording' to begin</div>
<script>
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const playButton = document.getElementById('play');
const output = document.getElementById('output');
let audioRecorder;
let audioChunks = [];
// Request microphone access
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
// Initialize the media recorder object
audioRecorder = new MediaRecorder(stream);
// dataavailable event is fired when data is available
audioRecorder.addEventListener('dataavailable', e => {
audioChunks.push(e.data);
});
// Start recording when the start button is clicked
startButton.addEventListener('click', () => {
audioChunks = [];
audioRecorder.start();
output.innerHTML = '? Recording started! Speak now...';
startButton.disabled = true;
stopButton.disabled = false;
});
// Stop recording when the stop button is clicked
stopButton.addEventListener('click', () => {
audioRecorder.stop();
output.innerHTML = '?? Recording stopped! Click "Play" to hear your recording.';
startButton.disabled = false;
stopButton.disabled = true;
playButton.disabled = false;
});
// Play the recorded audio when the play button is clicked
playButton.addEventListener('click', () => {
const blobObj = new Blob(audioChunks, { type: 'audio/webm' });
const audioUrl = URL.createObjectURL(blobObj);
const audio = new Audio(audioUrl);
audio.play();
output.innerHTML = '?? Playing the recorded audio!';
});
// Initialize button states
stopButton.disabled = true;
playButton.disabled = true;
})
.catch(err => {
output.innerHTML = '? Error accessing microphone: ' + err.message;
console.log('Error: ' + err);
});
</script>
</body>
</html>
Key Features of MediaRecorder API
Browser Support ? Works in modern browsers (Chrome, Firefox, Safari, Edge)
Audio Formats ? Supports webm, ogg, and mp4 formats depending on browser
Real-time Recording ? Records audio in real-time with minimal latency
Event-driven ? Uses events like 'dataavailable' and 'stop' for control
Browser Compatibility
The MediaRecorder API is well-supported across modern browsers. However, users need to grant microphone permission for the recording to work. If permission is denied, the application will display an error message.
Conclusion
The MediaRecorder API provides a straightforward way to record audio in web browsers. Users can easily implement audio recording features with proper permission handling and user feedback. This API is perfect for creating voice notes, audio messages, or any application requiring audio input.
