A audio-record demo, with recording audio wave and playing audio wave.
Install Parcel:
npm install -g parcel-bundler
Go to the demo root folder and install dependencies:
npm install
Run:
npm start
Visit http://localhost:1234/.
Build:
npm run build
Using Recorder lib to record audio.
Initiate:
const rec = Recorder({
type: "mp3",
sampleRate: 16000,
bitRate: 16
});
Start:
rec.open(function () {
rec.start();
});
Stop and process audio data:
rec.stop(function (blob) {
rec.close();
// Show audio wave.
loadWave(blob);
// Enable audio download.
enableDownload(blob);
}, function () {
console.log('Record failed');
});
The audio wave is generated with Wavesurfer.js.
HTML code:
<!-- Wave container -->
<div id="waveform"></div>
<script src="https://unpkg.com/wavesurfer.js"></script>
<!-- Microphone plugin for recording wave -->
<script src="https://unpkg.com/wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js"></script>
Initiate:
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
cursorColor: 'white',
plugins: [
// Using microphone plugin to create wave when recording.
WaveSurfer.microphone.create()
]
});
Generate playing wave with load
method and ObjectURL
:
function loadWave(blob) {
objectURL = URL.createObjectURL(blob);
wavesurfer.load(objectURL);
}
Recording wave is created by microphone plugin of WaveSurfer.js, when the start
method below is success, the wave is generated.
wavesurfer.microphone.start();
HTML:
<button class="btn btn-download" id="downloadButton" disabled>
Download
<a href="#" class="download-link" id="download-link" download></a>
</button>
Style (Hide the a
tag when download button was disabled):
.btn-download {
position: relative;
&:disabled {
a {
display: none;
}
}
a {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
}
JavaScript:
function enableDownload(blob) {
const downloadLinkEl = document.getElementById('download-link');
const fileName = new Date().toLocaleString() + 'mp3';
downloadLinkEl.href = URL.createObjectURL(blob);
downloadLinkEl.download = fileName;
downloadButton.disabled = false;
}