Top Related Projects
JavaScript 3D Library.
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Simple HTML5 Charts using the <canvas> tag
Quick Overview
WaveSurfer.js is an interactive navigable audio visualization library for the web. It provides a customizable waveform viewer that allows users to play, pause, and seek through audio files directly in the browser. The library is lightweight, flexible, and supports various audio formats.
Pros
- Easy to integrate and customize with a simple API
- Supports multiple audio backends (Web Audio, MediaElement)
- Responsive design that adapts to different screen sizes
- Extensible through plugins for additional functionality
Cons
- Limited built-in features compared to some more comprehensive audio libraries
- Performance can degrade with very long audio files
- Documentation could be more comprehensive for advanced use cases
Code Examples
Creating a basic waveform viewer:
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
wavesurfer.load('audio.mp3');
Adding play/pause functionality:
const playButton = document.getElementById('playBtn');
playButton.addEventListener('click', () => {
wavesurfer.playPause();
});
Using the regions plugin to create selectable areas:
wavesurfer.plugins.regions.addRegion({
start: 1,
end: 3,
color: 'rgba(0, 255, 0, 0.1)'
});
wavesurfer.on('region-click', (region) => {
region.play();
});
Getting Started
- Install WaveSurfer.js using npm:
npm install wavesurfer.js
- Import and create a WaveSurfer instance in your JavaScript file:
import WaveSurfer from 'wavesurfer.js';
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'blue',
progressColor: 'purple'
});
wavesurfer.load('path/to/audio/file.mp3');
- Add a container element in your HTML:
<div id="waveform"></div>
- Customize and add controls as needed using the WaveSurfer API.
Competitor Comparisons
JavaScript 3D Library.
Pros of Three.js
- Extensive 3D rendering capabilities for complex graphics and animations
- Large, active community with frequent updates and extensive documentation
- Supports a wide range of 3D features, including lighting, materials, and physics
Cons of Three.js
- Steeper learning curve due to its complexity and broad feature set
- Larger file size, which may impact load times for web applications
- Overkill for simple 2D audio visualization tasks
Code Comparison
Three.js (3D scene setup):
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
Wavesurfer.js (Audio waveform setup):
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
wavesurfer.load('audio.mp3');
While Three.js is a powerful 3D graphics library suitable for complex visualizations and games, Wavesurfer.js is specifically designed for audio waveform visualization. Three.js offers more flexibility for custom 3D audio visualizations but requires more setup and knowledge. Wavesurfer.js provides a simpler API for quick audio waveform implementation but is limited to 2D representations.
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
Pros of p5.js
- Broader scope for creative coding and visual arts
- Extensive documentation and large community support
- Easier to learn for beginners with no prior programming experience
Cons of p5.js
- Less specialized for audio visualization compared to wavesurfer.js
- May require more custom code for advanced audio waveform rendering
- Potentially higher resource usage for complex visualizations
Code Comparison
p5.js (basic audio visualization):
function setup() {
createCanvas(400, 200);
mic = new p5.AudioIn();
mic.start();
}
function draw() {
let vol = mic.getLevel();
ellipse(width/2, height/2, vol*200, vol*200);
}
wavesurfer.js (basic waveform):
var wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
wavesurfer.load('audio.mp3');
While p5.js offers a more versatile platform for creative coding and visual arts, wavesurfer.js provides a specialized solution for audio waveform visualization with less setup required. p5.js may be preferred for projects that involve various multimedia elements, while wavesurfer.js excels in dedicated audio waveform applications.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Pros of PixiJS
- Powerful 2D rendering engine with WebGL support, offering high performance for complex graphics and animations
- Extensive feature set for game development, including sprite management, particle systems, and scene graphs
- Large and active community with frequent updates and extensive documentation
Cons of PixiJS
- Steeper learning curve due to its comprehensive API and focus on game development
- Larger file size and potentially higher resource usage compared to WaveSurfer.js
- Not specifically designed for audio visualization, requiring more custom implementation for audio-related features
Code Comparison
WaveSurfer.js (audio waveform visualization):
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
wavesurfer.load('audio.mp3');
PixiJS (basic sprite rendering):
const app = new PIXI.Application();
document.body.appendChild(app.view);
const sprite = PIXI.Sprite.from('image.png');
app.stage.addChild(sprite);
While WaveSurfer.js is specifically designed for audio waveform visualization, PixiJS is a more general-purpose 2D rendering engine. PixiJS offers greater flexibility for complex graphics and animations but requires more setup for audio-specific tasks. WaveSurfer.js provides a simpler API for audio visualization out of the box.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Pros of EaselJS
- Broader scope for general-purpose canvas rendering and interactive graphics
- Part of a larger suite (CreateJS) with complementary libraries for sound, tweening, and preloading
- More extensive documentation and examples for various use cases
Cons of EaselJS
- Steeper learning curve due to its more comprehensive feature set
- Larger file size and potentially higher overhead for simple projects
- Less specialized for audio visualization compared to WaveSurfer.js
Code Comparison
EaselJS (basic shape drawing):
var stage = new createjs.Stage("canvas");
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
stage.update();
WaveSurfer.js (basic waveform rendering):
var wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
wavesurfer.load('audio.mp3');
While EaselJS provides a more general-purpose canvas manipulation library, WaveSurfer.js is specifically tailored for audio waveform visualization. EaselJS offers greater flexibility for creating complex graphics and animations, but WaveSurfer.js provides a more straightforward API for audio-related tasks.
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Pros of Fabric.js
- More versatile for general-purpose canvas manipulation and drawing
- Extensive object model for shapes, images, and text
- Rich set of features for interactive canvas applications
Cons of Fabric.js
- Larger file size and potentially higher performance overhead
- Steeper learning curve due to its comprehensive API
- Not specifically optimized for audio visualization
Code Comparison
Fabric.js example:
var canvas = new fabric.Canvas('myCanvas');
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
Wavesurfer.js example:
var wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
wavesurfer.load('audio.mp3');
While Fabric.js is a powerful library for canvas manipulation, Wavesurfer.js is specifically designed for audio visualization. Fabric.js offers more flexibility for general graphics, but Wavesurfer.js provides a simpler API for working with audio waveforms. The choice between the two depends on the specific requirements of your project.
Simple HTML5 Charts using the <canvas> tag
Pros of Chart.js
- More versatile for creating various types of charts and graphs
- Extensive documentation and large community support
- Built-in responsiveness and animation features
Cons of Chart.js
- Not specialized for audio waveform visualization
- May require more setup and configuration for specific use cases
- Larger file size due to broader feature set
Code Comparison
Chart.js example:
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{
data: [12, 19, 3]
}]
}
});
Wavesurfer.js example:
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple'
});
wavesurfer.load('audio.mp3');
Chart.js is a general-purpose charting library that excels in creating various types of charts and graphs, while Wavesurfer.js is specifically designed for audio waveform visualization. Chart.js offers more flexibility for different data visualizations but may require more setup for audio-specific tasks. Wavesurfer.js provides a simpler API for audio waveforms but is limited to that specific use case.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
wavesurfer.js
Wavesurfer.js is an interactive waveform rendering and audio playback library, perfect for web applications. It leverages modern web technologies to provide a robust and visually engaging audio experience.
Gold sponsor ð Closed Caption Creator
Getting started
Install and import the package:
npm install --save wavesurfer.js
import WaveSurfer from 'wavesurfer.js'
Alternatively, insert a UMD script tag which exports the library as a global WaveSurfer
variable:
<script src="https://unpkg.com/wavesurfer.js@7"></script>
Create a wavesurfer instance and pass various options:
const wavesurfer = WaveSurfer.create({
container: '#waveform',
waveColor: '#4F4A85',
progressColor: '#383351',
url: '/audio.mp3',
})
To import one of the plugins, e.g. the Regions plugin:
import Regions from 'wavesurfer.js/dist/plugins/regions.esm.js'
Or as a script tag that will export WaveSurfer.Regions
:
<script src="https://unpkg.com/wavesurfer.js@7/dist/plugins/regions.min.js"></script>
TypeScript types are included in the package, so there's no need to install @types/wavesurfer.js
.
See more examples.
API reference
See the wavesurfer.js documentation on our website:
Plugins
We maintain a number of official plugins that add various extra features:
- Regions â visual overlays and markers for regions of audio
- Timeline â displays notches and time labels below the waveform
- Minimap â a small waveform that serves as a scrollbar for the main waveform
- Envelope â a graphical interface to add fade-in and -out effects and control volume
- Record â records audio from the microphone and renders a waveform
- Spectrogram â visualization of an audio frequency spectrum (written by @akreal)
- Hover â shows a vertical line and timestmap on waveform hover
CSS styling
wavesurfer.js v7 is rendered into a Shadow DOM tree. This isolates its CSS from the rest of the web page.
However, it's still possible to style various wavesurfer.js elements with CSS via the ::part()
pseudo-selector.
For example:
#waveform ::part(cursor):before {
content: 'ð';
}
#waveform ::part(region) {
font-family: fantasy;
}
You can see which elements you can style in the DOM inspector â they will have a part
attribute.
See this example to play around with styling.
Questions
Have a question about integrating wavesurfer.js on your website? Feel free to ask in our Discussions forum.
However, please keep in mind that this forum is dedicated to wavesurfer-specific questions. If you're new to JavaScript and need help with the general basics like importing NPM modules, please consider asking ChatGPT or StackOverflow first.
FAQ
I'm having CORS issues
Wavesurfer fetches audio from the URL you specify in order to decode it. Make sure this URL allows fetching data from your domain. In browser JavaScript, you can only fetch data eithetr from the same domain or another domain if and only if that domain enables CORS. So if your audio file is on an external domain, make sure that domain sends the right Access-Control-Allow-Origin headers. There's nothing you can do about it from the requesting side (i.e. your JS code).Does wavesurfer support large files?
Since wavesurfer decodes audio entirely in the browser using Web Audio, large clips may fail to decode due to memory constraints. We recommend using pre-decoded peaks for large files (see this example). You can use a tool like bbc/audiowaveform to generate peaks.What about streaming audio?
Streaming audio is supported only with pre-decoded peaks and duration.There is a mismatch between my audio and the waveform. How do I fix it?
If you're using a VBR (variable bit rate) audio file, there might be a mismatch between the audio and the waveform. This can be fixed by converting your file to CBR (constant bit rate).Alternatively, you can use the Web Audio shim which is more accurate.
How do I connect wavesurfer.js to Web Audio effects?
Generally, wavesurfer.js doesn't aim to be a wrapper for all things Web Audio. It's just a player with a waveform visualization. It does allow connecting itself to a Web Audio graph by exporting its audio element (see this example) but nothign more than that. Please don't expect wavesurfer to be able to cut, add effects, or process your audio in any way.v7 â a new TypeScript version
Wavesurfer.js v7 is a TypeScript rewrite of wavesurfer.js that brings several improvements:
- Typed API for better development experience
- Enhanced decoding and rendering performance
- New and improved plugins
Upgrading from v6
Most options, events, and methods are similar to those in previous versions.
Notable differences
- HTML audio playback by default (used to be an opt-in via
backend: "MediaElement"
) - The Markers plugin is removed â you should use the Regions plugin with just a
startTime
. - No Microphone plugin â superseded by the new Record plugin with more features.
- The Cursor plugin is replaced by the Hover plugin.
Removed options
audioContext
,closeAudioContext
,audioScriptProcessor
autoCenterImmediately
âautoCenter
is now always immediate unless the audio is playingbackgroundColor
,hideCursor
â this can be easily set via CSSmediaType
â you should instead pass an entire media element in themedia
option. Example.partialRender
â done by defaultpixelRatio
âwindow.devicePixelRatio
is used by defaultrenderer
â there's just one renderer for now, so no need for this optionresponsive
â responsiveness is enabled by defaultscrollParent
â the container will scroll ifminPxPerSec
is set to a higher valueskipLength
â there's noskipForward
andskipBackward
methods anymoresplitChannelsOptions
â you should now usesplitChannels
to pass the channel options. Passheight: 0
to hide a channel. See this example.drawingContextAttributes
,maxCanvasWidth
,forceDecode
â removed to reduce code complexityxhr
- please usefetchParams
insteadbarMinHeight
- the minimum bar height is now 1 pixel by default
Removed methods
getFilters
,setFilter
â see the Web Audio exampledrawBuffer
â to redraw the waveform, usesetOptions
instead and pass new rendering optionscancelAjax
â you can pass an AbortSignal infetchParams
skipForward
,skipBackward
,setPlayEnd
â can be implemented usingsetTime(time)
exportPCM
is replaced withexportPeaks
which returns arrays of floatstoggleMute
is now calledsetMuted(true | false)
setHeight
,setWaveColor
,setCursorColor
, etc. â usesetOptions
with the corresponding params instead. E.g.,wavesurfer.setOptions({ height: 300, waveColor: '#abc' })
See the complete documentation of the new API.
Development
To get started with development, follow these steps:
- Install dev dependencies:
yarn
- Start the TypeScript compiler in watch mode and launch an HTTP server:
yarn start
This command will open http://localhost:9090 in your browser with live reload, allowing you to see the changes as you develop.
Tests
The tests are written in the Cypress framework. They are a mix of e2e and visual regression tests.
To run the test suite locally, first build the project:
yarn build
Then launch the tests:
yarn cypress
Feedback
We appreciate your feedback and contributions!
If you encounter any issues or have suggestions for improvements, please don't hesitate to post in our forum.
We hope you enjoy using wavesurfer.js and look forward to hearing about your experiences with the library!
Top Related Projects
JavaScript 3D Library.
p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Simple HTML5 Charts using the <canvas> tag
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot