wavesurfer.js README

The project's README from github.com/katspaugh/wavesurfer.js. As one markdown file: README.md.

logo wavesurfer.js

npm sponsor DigitalOcean

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.

waveform screenshot

Gold Sponsor 💖 Closed Caption Creator – Professional Subtitle Editor


Table of contents

  1. Getting started
  2. API reference
  3. Plugins
  4. Advanced / reactive API
  5. CSS styling
  6. Frequent questions
  7. Development
  8. Tests
  9. Feedback

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.

Documentation

See the wavesurfer.js guide on our website for beginner-friendly, practical documentation covering common use cases, plugins, framework integration, and troubleshooting.

API reference

The full generated API reference lives at wavesurfer.xyz/docs/api:

Plugins

We maintain a number of official plugins that add various extra features:

Advanced / reactive API

Beyond the imperative wavesurfer.on(...) events, v8 exposes a small reactive surface for apps that want to read state instead of tracking it themselves:

const state = wavesurfer.getState()

state.isPlaying.subscribe((playing) => console.log('playing:', playing))
console.log(state.loadPhase.value) // 'idle' | 'fetching' | 'decoding' | 'ready' | 'error'

const { startTime, endTime } = wavesurfer.getRenderer().getVisibleRange().value

getState() returns read-only Signal objects (.value to read, .subscribe(fn) to watch) for things like currentTime, isPlaying, volume, muted, loadPhase and scrollPosition. getRenderer().getVisibleRange() is a derived signal with the currently visible {startTime, endTime} of the viewport, useful for plugins that need to sync to what's on screen (e.g. a custom minimap or timeline).

If you're writing a plugin, WaveSurfer.definePlugin(name, (ctx, options) => api) is an alternative to subclassing BasePlugin: ctx gives you { wavesurfer, scope, state, emit }, and anything you register on ctx.scope (listeners, timers, child scopes) is torn down automatically on destroy() — no manual cleanup array required.

import WaveSurfer from 'wavesurfer.js'

const MyPlugin = WaveSurfer.definePlugin('MyPlugin', (ctx, options) => {
  ctx.scope.listen(ctx.wavesurfer.getWrapper(), 'click', () => ctx.emit('my-event'))
  return { doSomething: () => {} }
})

The Spectrogram plugin accepts a rendering: 'windowed' option for very long audio files: it renders only the visible time range and evicts off-screen segments, instead of computing the whole file's frequency data up front.

SpectrogramPlugin.create({ rendering: 'windowed', /* ...other options */ })

This replaces the standalone WindowedSpectrogramPlugin (spectrogram-windowed.js), which is now deprecated in favor of the merged option above — it's kept working as a thin backward-compatible shim, but new code should use SpectrogramPlugin directly.

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 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.
Why does my waveform look asymmetrical? By default, wavesurfer.js renders stereo audio as a single waveform, with the left channel on the top half and the right channel on the bottom half. If your audio has hard-panned sounds, this will result in an asymmetrical waveform. To render each channel separately, use the splitChannels option.

Development

To get started with development, follow these steps:

  1. Install dev dependencies:
yarn
  1. 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!


wavesurfer.js (katspaugh/wavesurfer.js)

Searching Database…

这是什么东西?wavesurfer.js 是一个开源库,用于网页应用:它能渲染可交互的音频波形并播放音频,基于 Web Audio 等现代浏览器技术构建。
它是要加到我自己代码里的库,还是一个现成的播放器应用?是一个库:你用 npm 安装它,在页面的 JavaScript 里引入,然后自己实现播放器的各种行为。
怎么把它加到网站上?用 npm 安装,然后创建一个实例,指定一个容器元素和一个音频 URL;wavesurfer 会自己获取音频并画出波形。
除了浏览器,运行它还需要别的东西吗?不需要后端或服务器端处理:解码完全通过 Web Audio API 在浏览器里完成,所以有一个现代浏览器就够了。
加载其他域名的音频会有什么坑吗?有,就是 CORS:wavesurfer 需要获取音频 URL 来解码,所以音频所在的主机必须允许来自你域名的请求;同源的文件则没有任何问题。
它怎么显示立体声音轨?默认显示为一条波形——左声道在上半部分,右声道在下半部分。使用 splitChannels 选项可以把每个声道分开渲染。
它自带哪些插件?它有一套插件系统(继承 BasePlugin,或者使用 ctx API,销毁时会自动清理监听器和定时器)。Spectrogram 插件还有 'windowed' 模式,只渲染非常长的文件中当前可见的时间范围,而不用提前计算全部频率数据。
这个项目成熟吗?它从 2012 年就存在了,GitHub 上超过 1 万颗星,还带有 Cypress 端到端测试和视觉回归测试——是网页音频领域一个成熟且在持续开发的选择。
Creator
katspaugh
Size
50.1 MB
Stars
10.4K
Age
14y
Commits · 90 Days