Recording MP3 audio using ReactJs
Hello folks. I was building a website using ReactJs and I came across a requirement to record an audio file on the web. Like, everyone, I started Googling it.
After googling some time, I came across an npm package that records mp3 files called mic-recorder-to-mp3
. You can find it in the below link.
https://www.npmjs.com/package/mic-recorder-to-mp3
Install and Import
To install the above npm package into your React project, do the following
npm install --save mic-recorder-to-mp3
After installing it you have to import the package in the project.
import MicRecorder from 'mic-recorder-to-mp3';
Configure MicRecorder
Now set the bit rate for the audio to be recorded to 128 bits
const Mp3Recorder = new MicRecorder({ bitRate: 128 });
Check for Browser Permissions
First set some basic state values like
this.state = {
isRecording: false,
blobURL: '',
isBlocked: false,
}
Before we start recording we should check if the permission for the microphone is allowed in the browser. To do that we need to use "navigator.getUserMedia()" function. Look more about it here.
I recommend using the below code in componentDidMount()
navigator.getUserMedia({ audio: true },
() => {
console.log('Permission Granted');
this.setState({ isBlocked: false });
},
() => {
console.log('Permission Denied');
this.setState({ isBlocked: true })
},
);
The above code checks the permissions of the web browser to access the microphone for recording audio. If permission is given the isBlocked
is set to true
or else false
Recording Audio
Set up two buttons and an HTML5 audio tag in the render()
function.
<button onClick={this.start} disabled={this.state.isRecording}>
Record
</button><button onClick={this.stop} disabled={!this.state.isRecording}>
Stop
</button><audio src={this.state.blobURL} controls="controls" />
To start the audio recording call the start()
function in the Mp3Recorder
which in turn returns a Promise.
start = () => {
if (this.state.isBlocked) {
console.log('Permission Denied');
} else {
Mp3Recorder
.start()
.then(() => {
this.setState({ isRecording: true });
}).catch((e) => console.error(e));
}
};
Now the audio starts to record once the above function is called. It continues to record until the stop()
function is called.
After the recording is stopped, getMp3()
is called which returns a Promise.
A blob and buffers are received as arguments when the Promise is resolved. We can create a “blob URL” from the received blob using URL.createObjectURL().
Now set the received URL as src for the audio tag.
stop = () => {
Mp3Recorder
.stop()
.getMp3()
.then(([buffer, blob]) => {
const blobURL = URL.createObjectURL(blob)
this.setState({ blobURL, isRecording: false });
}).catch((e) => console.log(e));
};
Hooray!!, Now you can record audio in MP3 format by clicking the start button.
The complete example is available in the GitHub link given below.
Say Hi, It’s free @matheswaaran_S or https://matheswaaran.com