wavesurfer.js is a customizable audio waveform visualization, built on top of Web Audio API and HTML5 Canvas.
First of all, you need to insert the wavesurfer.js library into your HTML page. You can grab the latest version from cdnjs.com.
<script src="wavesurfer.min.js"></script>
Create a container where you want the waveform to appear:
<div id="waveform"></div>
Next, in your JavaScript code, create an instance of the global WaveSurfer object.
var wavesurfer = WaveSurfer.create({
container: '#waveform'
});
The only required parameter is container. It can be either a unique CSS3 selector, or a DOM element.
However, you can also pass any number of options. For example, to make the waveform scrollable, pass the the scrollParent option:
var wavesurfer = WaveSurfer.create({
container: '#waveform',
scrollParent: true
});
See the full list of Options later in this document.
After creating an instance, you may want to load an audio track and draw its waveform. You can load files either from the same domain:
wavesurfer.load('../audio/song.mp3');
wavesurfer.js will load the file, decode it and display a nice waveform image. When it's done, it will fire the ready event.
wavesurfer.js has a number of useful events you can subscribe to. The ready event, mentioned above, can be used like this:
wavesurfer.on('ready', function () {
wavesurfer.play();
});
This is the list of parameters you can pass to var wavesurfer = WaveSurfer.create({ ... })
to create an instance of the player.
option | type | default | description |
---|---|---|---|
audioRate | float | 1 | Speed at which to play audio. Lower number is slower. |
audioContext | object | none | Use your own previously initialized AudioContext or leave blank. |
audioScriptProcessor | object | none | Use your own previously initialized ScriptProcessorNode or leave blank. |
autoCenter | boolean | TRUE | If a scrollbar is present, center the waveform around the progress. |
backend | string | WebAudio | WebAudio or MediaElement. In most cases you don't have to set this manually. MediaElement is a fallback for unsupported browsers. |
barGap | number | none | The optional spacing between bars of the wave, if not provided will be calculated in legacy format. |
barHeight | number | 1 | Height of the waveform bars. Higher number than 1 will increase the waveform bar heights. |
barWidth | number | none | If specified, the waveform will be drawn like this: ▁ ▂ ▇ ▃ ▅ ▂ |
closeAudioContext | boolean | FALSE | Close and nullify all audio contexts when the destroy method is called. |
container | mixed | none | CSS-selector or HTML-element where the waveform should be drawn. This is the only required parameter. |
cursorColor | string | #333 | The fill color of the cursor indicating the playhead position. |
cursorWidth | integer | 1 | Measured in pixels. |
fillParent | boolean | TRUE | Whether to fill the entire container or draw only according to minPxPerSec. |
forceDecode | boolean | FALSE | Force decoding of audio using web audio when zooming to get a more detailed waveform. |
height | integer | 128 | The height of the waveform. Measured in pixels. |
hideScrollbar | boolean | FALSE | Whether to hide the horizontal scrollbar when one would normally be shown. |
interact | boolean | TRUE | Whether the mouse interaction will be enabled at initialization. You can switch this parameter at any time later on. |
loopSelection | boolean | TRUE | (Use with regions plugin) Enable looping of selected regions. |
maxCanvasWidth | integer | 4000 | Maximum width of a single canvas in pixels, excluding a small overlap (2 * pixelRatio, rounded up to the next even integer). If the waveform is longer than this value, additional canvases will be used to render the waveform, which is useful for very large waveforms that may be too wide for browsers to draw on a single canvas. This parameter is only applicable to the MultiCanvas renderer. |
mediaControls | boolean | FALSE | (Use with backend MediaElement) this enables the native controls for the media element. |
mediaType | string | audio | 'audio' or 'video'. Only used with backend MediaElement. |
minPxPerSec | integer | 50 | Minimum number of pixels per second of audio. |
normalize | boolean | FALSE | If true, normalize by the maximum peak instead of 1.0. |
partialRender | boolean | FALSE | Use the PeakCache to improve rendering speed of large waveforms. |
pixelRatio | integer | window.devicePixelRatio | Can be set to 1 for faster rendering. |
plugins | array | [] | An array of plugin definitions to register during instantiation. They will be directly initialised unless they are added with the deferInit property set to true. |
progressColor | string | #555 | The fill color of the part of the waveform behind the cursor. |
removeMediaElementOnDestroy | boolean | TRUE | Set to false to keep the media element in the DOM when the player is destroyed. This is useful when reusing an existing media element via the loadMediaElement method. |
renderer | Object | MultiCanvas | Can be used to inject a custom renderer. |
responsive | boolean or float | FALSE | If set to true resize the waveform, when the window is resized. This is debounced with a 100ms timeout by default. If this parameter is a number it represents that timeout. |
scrollParent | boolean | FALSE | Whether to scroll the container with a lengthy waveform. Otherwise the waveform is shrunk to the container width (see fillParent). |
skipLength | float | 2 | Number of seconds to skip with the skipForward() and skipBackward() methods. |
splitChannels | boolean | FALSE | Render with seperate waveforms for the channels of the audio. |
waveColor | string | #999 | The fill color of the waveform after the cursor. |
xhr | Object | {} | XHR options. |
After creating an instance of the player (with var wavesurfer = WaveSurfer.create({ ... }))
, you can call the following methods on it:
destroy()
– Removes events, elements and disconnects Web Audio nodes.empty()
– Clears the waveform as if a zero-length audio is loaded.getCurrentTime()
– Returns current progress in seconds.getDuration()
– Returns the duration of an audio clip in seconds.getPlaybackRate()
– Returns the playback speed of an audio clip.getVolume()
– Returns the volume of the current audio clip.getMute()
– Returns the current mute status.getFilters()
– Returns an array of the current set filters.getReady()
– Returns the current ready status.getWaveColor()
– Returns the fill color of the waveform after the cursor.exportPCM(length, accuracy, noWindow, start)
– Exports PCM data into a JSON array. Optional parameters length [number] - default: 1024, accuracy [number] - default: 10000, noWindow [true|false] - default: false, start [number] - default: 0exportImage(format, quality)
– Return waveform image as data URI.isPlaying()
– Returns true if currently playing, false otherwise.load(url, peaks, preload)
– Loads audio from URL via XHR. Optional array of peaks. Optional preload parameter [none|metadata|auto], parsed to the Audio element if using backend MediaElement.loadBlob(url)
– Loads audio from a Blob or File object.on(eventName, callback)
– Subscribes to an event. See WaveSurfer Events for the list of all events.un(eventName, callback)
– Unsubscribes from an event.unAll()
– Unsubscribes from all events.pause()
– Stops playback.play([start[, end]])
– Starts playback from the current position. Optional start and end measured in seconds can be used to set the range of audio to play.playPause()
– Plays if paused, pauses if playing.seekAndCenter(progress)
– Seeks to a progress and centers view [0..1] (0 = beginning, 1 = end).seekTo(progress)
– Seeks to a progress [0..1] (0 = beginning, 1 = end).setHeight(height)
– Sets the height of the waveform.
setFilter(filters) - For inserting your own WebAudio nodes into the graph. See Connecting Filters below.setPlaybackRate(rate)
– Sets the speed of playback (0.5 is half speed, 1 is normal speed, 2 is double speed and so on).setVolume(newVolume)
– Sets the playback volume to a new value [0..1] (0 = silent, 1 = maximum).setMute(mute)
– Mute the current sound. Can be a boolean value of true to mute sound or false to unmutesetWaveColor(color)
– Sets the fill color of the waveform after the cursor.skip(offset)
– Skip a number of seconds from the current position (use a negative value to go backwards).
skipBackward() - Rewind skipLength seconds.
skipForward() - Skip ahead skipLength seconds.
setSinkId(deviceId) - Set the sink id to change audio output device.stop()
– Stops and goes to the beginning.toggleMute()
– Toggles the volume on and off.toggleInteraction()
– Toggle mouse interaction.toggleScroll()
– Toggles scrollParent.zoom(pxPerSec)
– Horizontally zooms the waveform in and out. The parameter is a number of horizontal pixels per second of audio. It also changes the parameter minPxPerSec and enables the scrollParent option.You can use on()
and un()
methods to subscribe and unsubscribe from various player events. For example:
wavesurfer.on('pause', function () {
wavesurfer.params.container.style.opacity = 0.9;
});
Here's the list of available events:
audioprocess
– Fires continuously as the audio plays. Also fires on seeking.destroy
– When instance is destroyed.error
– Occurs on error. Callback will receive (string) error message.finish
– When it finishes playing.interaction
– When there's interaction with the waveform.loading
– Fires continuously when loading via XHR or drag'n'drop. Callback will receive (integer) loading progress in percents [0..100] and (object) event target.mute
– On mute change. Callback will receive (boolean) new mute status.pause
– When audio is paused.play
– When playback starts.ready
– When audio is loaded, decoded and the waveform drawn. This fires before the waveform is drawn when using MediaElement, see waveform-ready.
scroll - When the scrollbar is moved. Callback will receive a ScrollEvent object.seek
– On seeking. Callback will receive (float) progress [0..1].volume
– On volume change. Callback will receive (integer) new volume.waveform-ready
– Fires after the waveform is drawn when using the MediaElement backend. If you're using the WebAudio backend, you can use ready.zoom
– On zooming. Callback will receive (integer) minPxPerSec.