Welcome folks today in this blog post we will be generating the audio waveform
of selected audio
file using the wavesurfer.js
library in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html> <head> <title>WaveSurfer.js Audio Waveform Example</title> <script src="https://unpkg.com/wavesurfer.js"></script> </head> <body> <input type="file" id="audio-file-input"> <div id="waveform"></div> <button id="play-button">Play</button> <button id="pause-button">Pause</button> </body> </html> |
As you can see we are importing the wavesurfer.js
library cdn and also we have the input
element where we allow the user to select the audio
file from the computer and then we have the div
where we will be displaying the audio waveform and then we have two buttons
to play and pause the audio file.
And now we need to write the javascript
code for this project as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<script> const waveformContainer = document.getElementById('waveform'); const audioFileInput = document.getElementById('audio-file-input'); const playButton = document.getElementById('play-button') const pauseButton = document.getElementById('pause-button') // Initialize WaveSurfer const wavesurfer = WaveSurfer.create({ container: waveformContainer }); // Handle file input change event audioFileInput.addEventListener('change', function () { const files = this.files; if (!files || !files[0]) { return; } const fileUrl = URL.createObjectURL(files[0]); // Load the audio file wavesurfer.load(fileUrl); }); // Handle play button click event playButton.addEventListener('click', function () { wavesurfer.play(); }); // Handle pause button click event pauseButton.addEventListener('click', function () { wavesurfer.pause(); }); </script> |
As you can see we are having the change
event listener on the input element to capture the audio
file which is selected by the user and then we are converting to url
using the createObjectURL() method. And then we are initializing the Wavesurfer
library and passing the div
to it where we need to display the audio waveform. And the we are using the load()
method of the wavesurfer
library to load the audio file. And then we have the play
and pause
buttons to play and pause the audio.