### Install development dependencies Source: https://github.com/katspaugh/wavesurfer.js/blob/main/README.md Run this command to install all required project dependencies. ```bash yarn ``` -------------------------------- ### Install and import wavesurfer.js Source: https://github.com/katspaugh/wavesurfer.js/blob/main/README.md Use npm to install the package and import it into your project. ```bash npm install --save wavesurfer.js ``` ```js import WaveSurfer from 'wavesurfer.js' ``` -------------------------------- ### startRecording() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Starts the process of recording microphone audio to a blob. ```APIDOC ## startRecording() ### Description Starts recording microphone audio to a blob. Returns a promise that resolves when recording starts. ### Signature `public async startRecording(): Promise` ``` -------------------------------- ### Start development server Source: https://github.com/katspaugh/wavesurfer.js/blob/main/README.md Launches the TypeScript compiler in watch mode and starts an HTTP server for live reloading. ```bash yarn start ``` -------------------------------- ### Start Microphone Recording Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Initiate microphone access and start recording. Handle potential DOMExceptions if access is denied. ```javascript const record = wavesurfer.registerPlugin(Record.create()) try { await record.startMic() console.log('Recording started') } catch (err) { console.error('Microphone error:', err) } ``` -------------------------------- ### Register and use a plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/base-plugin.md Example of registering a custom plugin and listening to its events. ```javascript import WaveSurfer from 'wavesurfer.js' import MyPlugin from './my-plugin' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', }) // Register plugin const plugin = wavesurfer.registerPlugin( MyPlugin.create({ name: 'CustomName' }) ) // Listen to plugin events plugin.on('myEvent', (data) => { console.log('Plugin event:', data) }) ``` -------------------------------- ### startMic() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Starts the microphone input stream for real-time waveform rendering. ```APIDOC ## startMic() ### Description Starts recording from the microphone. Returns a promise that resolves when recording starts. ### Signature `public async startMic(): Promise` ### Throws - `DOMException` if microphone access is denied - `NotSupportedError` if Web Audio is not available ``` -------------------------------- ### play() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Starts audio playback asynchronously. ```APIDOC ## async play() ### Description Starts the playback of the loaded audio buffer. ### Request Example ```javascript await player.play(); ``` ``` -------------------------------- ### Initialize WaveSurfer with WebAudio Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Basic setup for using the WebAudio backend in WaveSurfer with event listeners. ```javascript const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', backend: 'WebAudio', }) // Listen to events wavesurfer.on('ready', (duration) => { console.log(`Audio ready: ${duration}s`) }) wavesurfer.on('play', () => { console.log('Playing on Web Audio') }) ``` -------------------------------- ### Fetch audio files with progress tracking Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/fetcher.md Examples demonstrating basic usage, custom headers, and abort signal integration for the fetchBlob method. ```javascript // Basic fetch const blob = await Fetcher.fetchBlob('/audio.mp3', (percent) => { console.log(`Loading: ${percent}%`) }) // With headers const blob = await Fetcher.fetchBlob( 'https://api.example.com/audio.mp3', (percent) => updateProgressBar(percent), { headers: { 'Authorization': 'Bearer token', }, } ) // With abort signal const controller = new AbortController() const blob = await Fetcher.fetchBlob( '/audio.mp3', (percent) => console.log(percent), { signal: controller.signal, } ) // Cancel if needed controller.abort() ``` -------------------------------- ### Play audio Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Start playback of the loaded audio buffer. ```typescript public async play(): Promise ``` ```javascript await player.play() ``` -------------------------------- ### Start Audio Blob Recording Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Begin recording microphone input into an audio blob. ```javascript await record.startRecording() ``` -------------------------------- ### Start Audio Playback Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Initiates playback and handles potential AbortError exceptions. ```typescript public async play(): Promise ``` ```javascript try { await player.play() console.log('Playback started') } catch (err) { if (err instanceof DOMException && err.name === 'AbortError') { console.log('Playback was aborted') } else { console.error('Play failed:', err) } } ``` -------------------------------- ### Documentation Use Case Mapping Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/MANIFEST.md A guide mapping common user requirements to the corresponding wavesurfer.js components. ```text If You Want To... ├── Play/pause audio → WaveSurfer ├── Control volume/rate → Player, WaveSurfer ├── Mark segments → Regions Plugin ├── Show timeline → Timeline Plugin ├── Navigate → Minimap Plugin ├── Record audio → Record Plugin ├── Handle events → EventEmitter ├── Create plugins → BasePlugin ├── Decode audio → Decoder ├── Load files → Fetcher ├── Use Web Audio → WebAudioPlayer ├── Configure everything → Configuration └── Understand types → Types ``` -------------------------------- ### Register Minimap Plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/minimap-plugin.md Example of importing and registering the Minimap plugin to a WaveSurfer instance. ```javascript import Minimap from 'wavesurfer.js/dist/plugins/minimap' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', }) const minimap = wavesurfer.registerPlugin( Minimap.create({ height: 50, waveColor: '#ddd', progressColor: '#999', }) ) ``` -------------------------------- ### Control Audio Playback Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Starts audio playback, optionally specifying start and end timestamps. Returns a promise that resolves when playback begins. ```typescript public async play(start?: number, end?: number): Promise ``` ```javascript // Play from the beginning await wavesurfer.play() // Play from 10 seconds await wavesurfer.play(10) // Play from 5 seconds to 15 seconds await wavesurfer.play(5, 15) ``` -------------------------------- ### Construct WebAudioPlayer instance Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Define the constructor signature and usage examples for creating a player with default or custom audio contexts. ```typescript constructor(audioContext?: AudioContext) ``` ```javascript // Use default audio context const player = new WebAudioPlayer() // Use custom audio context const audioContext = new AudioContext({ sampleRate: 48000 }) const player = new WebAudioPlayer(audioContext) ``` -------------------------------- ### WaveSurfer.play() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/INDEX.md Initiates playback of the audio, optionally starting and ending at specific timestamps. ```APIDOC ## WaveSurfer.play() ### Description Starts audio playback. Optionally accepts start and end times in seconds. ### Signature `async play(start?: number, end?: number) -> Promise` ### Parameters - **start** (number) - Optional - Start time in seconds. - **end** (number) - Optional - End time in seconds. ### Returns - **Promise** - Resolves when playback starts. ### Events - **play** - Emitted when playback begins. ### Errors - **DOMException** - Thrown if the playback is aborted. ``` -------------------------------- ### Listen to RecordPlugin events Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Attach event listeners to handle recording lifecycle events like start, progress, and completion. ```javascript record.on('record-start', () => { console.log('Started recording') }) record.on('record-progress', (time) => { console.log('Recorded:', time.toFixed(2), 'seconds') }) record.on('record-end', (blob) => { console.log('Recording complete:', blob.size, 'bytes') // Save or play the blob }) ``` -------------------------------- ### Import WaveSurfer.js Plugins (JavaScript) Source: https://github.com/katspaugh/wavesurfer.js/blob/main/cypress/e2e/index.html Imports the core WaveSurfer.js library and several of its official plugins, making them accessible globally on the window object. This setup is common for testing or simple web page integrations. ```javascript import WaveSurfer from '../../dist/wavesurfer.js' import Regions from '../../dist/plugins/regions.js' import Timeline from '../../dist/plugins/timeline.js' import Spectrogram from '../../dist/plugins/spectrogram.js' import Envelope from '../../dist/plugins/envelope.js' import Hover from '../../dist/plugins/hover.js' window.WaveSurfer = WaveSurfer window.Regions = Regions window.Timeline = Timeline window.Spectrogram = Spectrogram window.Envelope = Envelope window.Hover = Hover ``` -------------------------------- ### Implement basic recording functionality Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Initialize the plugin and use startMic and startRecording to capture audio, then stopRecording to retrieve the blob. ```javascript import WaveSurfer from 'wavesurfer.js' import Record from 'wavesurfer.js/dist/plugins/record' const wavesurfer = WaveSurfer.create({ container: '#waveform', height: 300, }) const record = wavesurfer.registerPlugin(Record.create()) // Start recording document.querySelector('#record-btn').onclick = async () => { await record.startMic() await record.startRecording() } // Stop recording document.querySelector('#stop-btn').onclick = async () => { const blob = await record.stopRecording() record.stopMic() // Play back await wavesurfer.loadBlob(blob) } ``` -------------------------------- ### record.startRecording() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Begins the audio recording process. ```APIDOC ## record.startRecording() ### Description Starts the recording of audio from the initialized microphone. ### Method Async Function ### Parameters None ``` -------------------------------- ### record.startMic() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Initializes the microphone input for the recording plugin. ```APIDOC ## record.startMic() ### Description Initializes and starts the microphone input stream for recording. ### Method Async Function ### Parameters None ``` -------------------------------- ### Get all regions Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Retrieves an array of all current Region instances. ```typescript public getRegions(): Region[] ``` ```javascript const allRegions = regions.getRegions() console.log(`${allRegions.length} regions`) ``` -------------------------------- ### Get Waveform Width Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Returns the current width of the waveform in pixels. ```typescript public getWidth(): number ``` ```javascript const width = wavesurfer.getWidth() ``` -------------------------------- ### RequestInit Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/types.md Configuration object for customizing audio file loading via the fetchParams option. ```APIDOC ## RequestInit ### Description Defines the options for the fetch request used to load audio files. This is passed to the `fetchParams` configuration option in `WaveSurfer.create`. ### Properties - **method** (string) - Optional - The HTTP request method. - **headers** (HeadersInit) - Optional - Request headers. - **body** (BodyInit) - Optional - The request body. - **mode** (RequestMode) - Optional - The mode of the request. - **credentials** (RequestCredentials) - Optional - Request credentials policy. - **cache** (RequestCache) - Optional - Cache mode. - **redirect** (RequestRedirect) - Optional - Redirect mode. - **referrer** (string) - Optional - Referrer policy. - **integrity** (string) - Optional - Subresource integrity value. - **keepalive** (boolean) - Optional - Whether to keep the request alive. - **signal** (AbortSignal) - Optional - AbortSignal to cancel the request. - **priority** (RequestPriority) - Optional - Request priority. ### Usage Example ```javascript const wavesurfer = WaveSurfer.create({ url: 'https://example.com/audio.mp3', fetchParams: { headers: { 'Authorization': 'Bearer token', }, credentials: 'include', }, }) ``` ``` -------------------------------- ### Get media element Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Provides access to the underlying HTMLAudioElement or HTMLVideoElement. ```javascript const media = player.getMediaElement() media.crossOrigin = 'anonymous' ``` -------------------------------- ### Get playback rate Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Retrieves the current playback speed multiplier. ```javascript const rate = player.getPlaybackRate() console.log(`Speed: ${rate}x`) ``` -------------------------------- ### WaveSurfer.create(options) Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/README.md Initializes a new WaveSurfer instance with the provided configuration options. ```APIDOC ## WaveSurfer.create(options) ### Description Creates a new WaveSurfer instance attached to a container. ### Parameters - **options** (Object) - Required - Configuration object including container selector. ``` -------------------------------- ### Get audio duration Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Retrieves the total duration of the audio in seconds. ```typescript public getDuration(): number ``` ```javascript const duration = player.getDuration() if (duration) { console.log(`Duration: ${duration.toFixed(2)}s`) } ``` -------------------------------- ### Integrate Recording with Playback Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Full workflow for initializing the plugin, recording audio, and loading the result into wavesurfer for playback. ```javascript const wavesurfer = WaveSurfer.create({ container: '#waveform', }) const record = wavesurfer.registerPlugin(Record.create()) // Record document.querySelector('#record-btn').onclick = async () => { await record.startMic() await record.startRecording() document.querySelector('#stop-btn').disabled = false document.querySelector('#record-btn').disabled = true } // Stop and play back document.querySelector('#stop-btn').onclick = async () => { const blob = await record.stopRecording() record.stopMic() // Load recording await wavesurfer.loadBlob(blob) // Play it back await wavesurfer.play() document.querySelector('#record-btn').disabled = false document.querySelector('#stop-btn').disabled = true } ``` -------------------------------- ### BasePlugin.onInit() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/base-plugin.md Lifecycle method called when the plugin is initialized with a WaveSurfer instance. ```APIDOC ## onInit() ### Description Called when the plugin is initialized. Override this method to set up plugin functionality. At this point, the `this.wavesurfer` instance is available for use. ``` -------------------------------- ### Unregister a plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/base-plugin.md Example of unregistering a plugin instance from the wavesurfer object. ```javascript const plugin = wavesurfer.registerPlugin(MyPlugin.create()) // Later, unregister and destroy wavesurfer.unregisterPlugin(plugin) ``` -------------------------------- ### Map Method Dependencies and Event Flows Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/INDEX.md Workflow diagrams for core audio loading, playback, and plugin management methods. ```text Audio Loading: load() / loadBlob() ├─ Fetcher.fetchBlob() [internal] ├─ Decoder.decode() [internal] └─ Emits: load, loading, decode, ready Playback: play() ├─ setTime() [optional] └─ Emits: play, timeupdate Plugins: registerPlugin() ├─ plugin._init(this) └─ Returns: plugin instance unregisterPlugin() └─ plugin.destroy() ``` -------------------------------- ### constructor(audioContext?: AudioContext) Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Initializes a new instance of the WebAudioPlayer. Optionally accepts a custom AudioContext. ```APIDOC ## constructor(audioContext?: AudioContext) ### Description Creates a new WebAudioPlayer instance. If no audioContext is provided, a new one is created by default. ### Parameters #### Path Parameters - **audioContext** (AudioContext) - Optional - A custom Web Audio API AudioContext instance. ### Request Example ```javascript const player = new WebAudioPlayer(new AudioContext()); ``` ``` -------------------------------- ### Get current playback position Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Retrieves the current playback position in seconds. ```typescript public getCurrentTime(): number ``` ```javascript const position = player.getCurrentTime() console.log(`Current: ${position.toFixed(2)}s`) ``` -------------------------------- ### Initialize and Manage Regions Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Demonstrates how to register the Regions plugin, add regions with custom content and colors, handle interaction events, and perform CRUD operations on regions. ```javascript import WaveSurfer from 'wavesurfer.js' import Regions from 'wavesurfer.js/dist/plugins/regions' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/podcast.mp3', }) const regions = wavesurfer.registerPlugin(Regions.create()) // Add regions const intro = regions.addRegion({ start: 0, end: 30, content: 'Intro', color: 'rgba(255, 0, 0, 0.1)', }) const mainContent = regions.addRegion({ start: 30, end: 3570, content: 'Main Content', color: 'rgba(0, 255, 0, 0.1)', }) const outro = regions.addRegion({ start: 3570, end: 3600, content: 'Outro', color: 'rgba(0, 0, 255, 0.1)', }) // Listen for interactions regions.on('region-clicked', (region, e) => { console.log('Clicked region:', region.id, region.start) }) regions.on('region-in', (region) => { console.log('Entered:', region.content) }) regions.on('region-out', (region) => { console.log('Left:', region.content) }) // Update region mainContent.setOptions({ start: 35, end: 3580, }) // Remove a region intro.remove() // Get all regions const allRegions = regions.getRegions() console.log(`Total regions: ${allRegions.length}`) // Clear all regions.clearRegions() ``` -------------------------------- ### RegionsPlugin.addRegion() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Adds a new region to the waveform with specified start and end times and configuration. ```APIDOC ## RegionsPlugin.addRegion() ### Description Creates and adds a new region to the waveform. Emits 'region-initialized' and 'region-created' events upon success. ### Signature `public addRegion(params: RegionParams): Region` ### Parameters - **params** (RegionParams) - Required - Configuration for the new region. ### RegionParams - **id** (string) - Optional - Unique identifier. - **start** (number) - Required - Start time in seconds. - **end** (number) - Optional - End time in seconds. - **drag** (boolean) - Optional - Enable dragging. - **resize** (boolean) - Optional - Enable resizing. - **resizeStart** (boolean) - Optional - Enable resizing start edge. - **resizeEnd** (boolean) - Optional - Enable resizing end edge. - **color** (string) - Optional - CSS color string. - **content** (string | HTMLElement) - Optional - Label or content for the region. - **minLength** (number) - Optional - Minimum duration. - **maxLength** (number) - Optional - Maximum duration. - **channelIdx** (number) - Optional - Channel index. - **contentEditable** (boolean) - Optional - Enable content editing. ### Returns - **Region** - The created region instance. ``` -------------------------------- ### Accessing WebAudioPlayer Properties Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Demonstrates how to instantiate the player and access basic playback state properties. ```javascript const player = new WebAudioPlayer() console.log('Current time:', player.currentTime) console.log('Duration:', player.duration) console.log('Volume:', player.volume) ``` -------------------------------- ### Initialize Timeline Plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/timeline-plugin.md Demonstrates how to register the Timeline plugin with custom height, interval, and time formatting options. ```javascript import WaveSurfer from 'wavesurfer.js' import Timeline from 'wavesurfer.js/dist/plugins/timeline' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', }) // Add timeline with custom options const timeline = wavesurfer.registerPlugin( Timeline.create({ height: 25, timeInterval: 5, primaryLabelInterval: 30, secondaryLabelInterval: 10, formatTimeCallback: (seconds) => { const mins = Math.floor(seconds / 60) const secs = Math.round(seconds % 60) return `${mins}:${secs.toString().padStart(2, '0')}` }, }) ) timeline.once('ready', () => { console.log('Timeline initialized') }) ``` -------------------------------- ### Get Waveform Wrapper Element Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Accesses the DOM element that contains the rendered waveform. ```typescript public getWrapper(): HTMLElement ``` ```javascript const wrapper = wavesurfer.getWrapper() wrapper.style.border = '1px solid black' ``` -------------------------------- ### Implement Progress UI with Fetcher Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/fetcher.md Use Fetcher.fetchBlob to manually load audio data and update UI elements based on the download progress callback. ```javascript import Fetcher from 'wavesurfer.js/dist/fetcher' const progressBar = document.querySelector('#progress') const statusText = document.querySelector('#status') const wavesurfer = WaveSurfer.create({ container: '#waveform', }) async function loadAudio(url) { try { const blob = await Fetcher.fetchBlob(url, (percent) => { progressBar.style.width = `${percent}%` statusText.textContent = `Loading: ${percent}%` }) await wavesurfer.loadBlob(blob) statusText.textContent = 'Ready' } catch (err) { statusText.textContent = `Error: ${err.message}` } } document.querySelector('#load-button').onclick = () => { loadAudio('/audio.mp3') } ``` -------------------------------- ### Get Active Plugins in WaveSurfer Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Retrieves an array of all currently registered plugin instances. ```typescript public getActivePlugins(): GenericPlugin[] ``` ```javascript const plugins = wavesurfer.getActivePlugins() console.log(`${plugins.length} plugins registered`) ``` -------------------------------- ### Build the project Source: https://github.com/katspaugh/wavesurfer.js/blob/main/README.md Compiles the project source code, required before running the test suite. ```bash yarn build ``` -------------------------------- ### Get current playback time in WaveSurfer.js Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Retrieve the current playback position in seconds. ```typescript public getCurrentTime(): number ``` ```javascript const currentTime = wavesurfer.getCurrentTime() console.log(`Current position: ${currentTime}s`) ``` -------------------------------- ### Get volume level with getVolume Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Retrieves the current volume as a float between 0 and 1. ```javascript const level = player.getVolume() console.log(`Volume: ${Math.round(level * 100)}%`) ``` -------------------------------- ### Player Constructor Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Initializes a new Player instance with optional configuration for media elements, controls, and playback settings. ```APIDOC ## constructor(options: PlayerOptions) ### Description Creates a new Player instance. Configuration options allow for specifying an external media element, toggling native controls, setting autoplay, and defining initial playback speed. ### Parameters - **options** (PlayerOptions) - Required - Configuration object containing media, mediaControls, autoplay, and playbackRate settings. ``` -------------------------------- ### Player.play() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Initiates audio playback for the player instance. ```APIDOC ## play() ### Description Starts audio playback. This method returns a promise that resolves when playback successfully begins. ### Returns - **Promise** - Resolves when playback starts. ### Errors - **AbortError** (DOMException) - Thrown if playback is aborted. ``` -------------------------------- ### Initialize Record Plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Register the Record plugin with a WaveSurfer instance to enable audio recording capabilities. ```javascript import Record from 'wavesurfer.js/dist/plugins/record' const wavesurfer = WaveSurfer.create({ container: '#waveform', }) const record = wavesurfer.registerPlugin(Record.create()) ``` -------------------------------- ### Control playback with WaveSurfer.play Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/INDEX.md Initiates audio playback with optional start and end time parameters. ```javascript WaveSurfer.play() → async play(start?, end?) • Parameters: optional start/end times in seconds • Returns: Promise • Emits: 'play' event • Throws: DOMException on abort ``` -------------------------------- ### Add a Region Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Create a new region on the waveform with specific start, end, and styling parameters. ```javascript const region = regions.addRegion({ start: 5, end: 15, color: 'rgba(255, 0, 0, 0.1)', content: 'Intro', drag: true, resize: true, }) // Get region properties console.log(region.id, region.start, region.end) ``` -------------------------------- ### Configure Audio Loading with fetchParams Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/types.md Demonstrates passing custom fetch parameters to the WaveSurfer instance during creation. ```javascript const wavesurfer = WaveSurfer.create({ url: 'https://example.com/audio.mp3', fetchParams: { headers: { 'Authorization': 'Bearer token', }, credentials: 'include', }, }) ``` -------------------------------- ### Get Horizontal Scroll Position Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Retrieves the current horizontal scroll position of the waveform in pixels. ```javascript const scroll = wavesurfer.getScroll() ``` -------------------------------- ### Get volume level in WaveSurfer.js Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Retrieve the current volume level as a value between 0 and 1. ```typescript public getVolume(): number ``` ```javascript const volume = wavesurfer.getVolume() console.log(`Volume: ${Math.round(volume * 100)}%`) ``` -------------------------------- ### Initialize with external media element Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/configuration.md Uses an existing HTML5 audio element as the media source for the waveform. ```javascript const audioElement = document.querySelector('audio') const wavesurfer = WaveSurfer.create({ container: '#waveform', media: audioElement, mediaControls: true, }) ``` -------------------------------- ### Get a region by ID Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Retrieves a specific region instance by its unique identifier, returning undefined if not found. ```typescript public getRegion(id: string): Region | undefined ``` ```javascript const region = regions.getRegion('intro') if (region) { console.log(`Region: ${region.start} - ${region.end}`) } ``` -------------------------------- ### Create Playlist UI with DOM Utilities Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/dom.md Shows how to dynamically generate a list of elements and insert them into the DOM relative to the waveform wrapper. ```javascript import WaveSurfer from 'wavesurfer.js' import BasePlugin from 'wavesurfer.js/dist/base-plugin' import * as dom from 'wavesurfer.js/dist/dom' class PlaylistPlugin extends BasePlugin { private playlistElement: HTMLElement | null = null protected onInit() { if (!this.wavesurfer) return // Create playlist UI this.playlistElement = dom.createElement('div', { class: 'playlist', style: 'margin-top: 20px; padding: 10px; border: 1px solid #ccc;', }) // Add songs const songs = [ { title: 'Song 1', duration: 180 }, { title: 'Song 2', duration: 240 }, { title: 'Song 3', duration: 200 }, ] songs.forEach((song, index) => { const item = dom.createElement('div', { class: 'playlist-item', id: `song-${index}`, style: 'padding: 5px; cursor: pointer; border-bottom: 1px solid #eee;', }, `${song.title} (${song.duration}s)`) item.addEventListener('click', () => { console.log(`Playing: ${song.title}`) }) this.playlistElement?.appendChild(item) }) // Insert after waveform const wrapper = this.wavesurfer.getWrapper() wrapper.parentElement?.insertBefore( this.playlistElement, wrapper.nextSibling ) } public destroy() { if (this.playlistElement) { this.playlistElement.remove() this.playlistElement = null } super.destroy() } } ``` -------------------------------- ### Play a region Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Plays the audio from the region's start time, optionally accepting a custom end time. ```typescript public play(end?: number): void ``` ```javascript region.play() // Play from region start to end region.play(region.end + 5) // Play past region end ``` -------------------------------- ### Configure Loading Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/README.md Specifies audio source, pre-computed data, and backend processing parameters. ```javascript { url: '/audio.mp3', // Audio URL peaks: [...], // Pre-computed peaks duration: 120, // Pre-known duration backend: 'WebAudio', // Audio backend sampleRate: 8000, // Decode sample rate } ``` -------------------------------- ### Configure Minimap Options Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/minimap-plugin.md Demonstrates setting custom height, colors, and insertion position for the Minimap plugin. ```javascript const minimap = Minimap.create({ height: 60, waveColor: '#ccc', progressColor: '#888', overlayColor: 'rgba(200, 200, 200, 0.2)', insertPosition: 'beforeend', }) ``` -------------------------------- ### Get Renderer Instance Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Access the internal renderer instance, typically used by plugins to interact with reactive streams. ```typescript public getRenderer(): Renderer ``` -------------------------------- ### Implement onInit lifecycle method Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/base-plugin.md Override the onInit method to access the wavesurfer instance and set up event subscriptions. ```typescript class MyPlugin extends BasePlugin { protected onInit() { if (!this.wavesurfer) throw Error('WaveSurfer not initialized') // Set up plugin functionality this.subscriptions.push( this.wavesurfer.on('ready', () => { console.log('Ready to play') }) ) } } ``` -------------------------------- ### Get audio duration in WaveSurfer.js Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Retrieve the total duration of the loaded audio in seconds. Returns 0 if no audio is currently loaded. ```typescript public getDuration(): number ``` ```javascript const duration = wavesurfer.getDuration() console.log(`Audio duration: ${duration}s`) ``` -------------------------------- ### Initialize a wavesurfer instance Source: https://github.com/katspaugh/wavesurfer.js/blob/main/README.md Create a new instance by providing a container selector and configuration options. ```js const wavesurfer = WaveSurfer.create({ container: '#waveform', waveColor: '#4F4A85', progressColor: '#383351', url: '/audio.mp3', }) ``` -------------------------------- ### Initialize WaveSurfer with WebAudio backend Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Configure the wavesurfer instance to use the WebAudio backend instead of the default HTMLMediaElement. ```javascript const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', backend: 'WebAudio', }) ``` -------------------------------- ### Record Audio with WebAudioPlayer Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Integrate the Record plugin to capture microphone input and load it into WaveSurfer. ```javascript import Record from 'wavesurfer.js/dist/plugins/record' const wavesurfer = WaveSurfer.create({ container: '#waveform', backend: 'WebAudio', }) const record = wavesurfer.registerPlugin(Record.create()) // Start recording microphone record.startMic() // Listen to recorded audio record.on('record-end', (blob) => { // Load recording wavesurfer.loadBlob(blob) }) ``` -------------------------------- ### BasePlugin Constructor Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/base-plugin.md Initializes a new instance of a plugin with the provided configuration options. ```APIDOC ## constructor(options: Options) ### Description Creates a new plugin instance. All custom plugins should extend this class. ### Parameters - **options** (Options) - Required - Plugin-specific configuration options. ### Generic Type Parameters - **EventTypes** (BasePluginEvents) - Events emitted by the plugin. - **Options** (Object) - Shape of the options object. ``` -------------------------------- ### Navigation Methods Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/README.md Methods for navigating the audio timeline and adjusting the view. ```APIDOC ## Navigation Methods - **setTime(seconds)**: Jump to time. - **seekTo(ratio)**: Seek to 0-1 ratio. - **skip(seconds)**: Skip forward/backward. - **zoom(pixelsPerSec)**: Change zoom level. - **setScroll(pixels)**: Set scroll position. - **setScrollTime(seconds)**: Scroll to time. ``` -------------------------------- ### Initialize WaveSurfer Player Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/START-HERE.md Creates a new WaveSurfer instance by specifying the container element and audio source URL. ```javascript import WaveSurfer from 'wavesurfer.js' const wavesurfer = WaveSurfer.create({ container: '#waveform', waveColor: '#4F4A85', progressColor: '#383351', url: '/audio.mp3', }) ``` -------------------------------- ### Initialize Player Instance Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/player.md Constructs a new Player instance using either internal or external media elements. ```typescript constructor(options: PlayerOptions) ``` ```javascript // Internal media element const player = new Player({ mediaControls: false, playbackRate: 1.5, }) // External media element const audio = document.querySelector('audio') const player = new Player({ media: audio, mediaControls: true, }) ``` -------------------------------- ### Configure fetch requests Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/fetcher.md Pass a RequestInit object as the third argument to customize headers, credentials, CORS mode, and other fetch options. ```javascript const blob = await Fetcher.fetchBlob( '/audio.mp3', (percent) => console.log(percent), { // HTTP method (usually GET) method: 'GET', // Request headers headers: { 'User-Agent': 'MyApp/1.0', 'Authorization': 'Bearer token', }, // Include credentials (cookies, auth) credentials: 'include', // CORS mode mode: 'cors', // Redirect behavior redirect: 'follow', // Cache control cache: 'default', // Abort signal for cancellation signal: abortController.signal, } ) ``` -------------------------------- ### Register Plugins Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/START-HERE.md Integrates plugins by passing an array of plugin instances to the configuration object during initialization. ```javascript import Regions from 'wavesurfer.js/dist/plugins/regions' import Timeline from 'wavesurfer.js/dist/plugins/timeline' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', plugins: [ Regions.create(), Timeline.create({ height: 20 }), ], }) ``` -------------------------------- ### Configure Web Audio backend Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/configuration.md Explicitly sets the backend to WebAudio for specific audio processing requirements. ```javascript const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', backend: 'WebAudio', audioRate: 1, }) ``` -------------------------------- ### Display API Coverage Matrix Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/INDEX.md A checklist summarizing the extent of documentation coverage for the API, plugins, and utilities. ```text API Completeness: ✓ Core instance methods (40+ documented) ✓ Event system (24 events documented) ✓ Plugin API (4 plugins × 5+ methods each) ✓ Type definitions (15+ types) ✓ Configuration options (25+ options) ✓ Utilities (4 utilities fully documented) ✓ Examples (100+ code snippets) ✓ Error handling patterns ✓ Performance tips ✓ Browser compatibility notes ``` -------------------------------- ### Register and use a plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/README.md Register a plugin instance with wavesurfer and listen for custom events. ```javascript const plugin = wavesurfer.registerPlugin(MyPlugin.create()) plugin.on('myEvent', (data) => { // Handle plugin event }) ``` -------------------------------- ### Register and manage plugins Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/README.md Extend functionality by registering plugins and managing their lifecycle. ```javascript const regions = wavesurfer.registerPlugin(Regions.create()) regions.addRegion({ start: 0, end: 10 }) // Later, unregister wavesurfer.unregisterPlugin(regions) ``` -------------------------------- ### Fetcher.fetchBlob() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/fetcher.md Fetches an audio file from a URL and returns it as a Blob, providing progress updates via a callback function. ```APIDOC ## Fetcher.fetchBlob() ### Description Fetches an audio file and returns it as a Blob with progress reporting. The progress callback provides a percentage (0-100) if the Content-Length header is available. ### Method Static Async Method ### Signature `static async fetchBlob(url: string, progressCallback: (percentage: number) => void, requestInit?: RequestInit): Promise` ### Parameters - **url** (string) - Required - URL to fetch. - **progressCallback** (Function) - Required - Called with 0-100 percentage. - **requestInit** (RequestInit) - Optional - Fetch options (headers, auth, etc.). ### Returns - **Promise** - Resolves to the fetched Blob. ### Throws - **Error** - If HTTP status >= 400, including URL and status code. ### Example ```javascript const blob = await Fetcher.fetchBlob('/audio.mp3', (percent) => { console.log(`Loading: ${percent}%`) }) ``` ``` -------------------------------- ### Create Plugin UI with DOM Utilities Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/dom.md Demonstrates creating and managing DOM elements within a custom plugin using the wavesurfer.js DOM utility module. ```typescript import BasePlugin from 'wavesurfer.js/dist/base-plugin' import * as dom from 'wavesurfer.js/dist/dom' class CustomPlugin extends BasePlugin { private element: HTMLElement | null = null protected onInit() { if (!this.wavesurfer) return // Create plugin UI this.element = dom.createElement('div', { class: 'custom-plugin', style: 'position: absolute; top: 0; right: 0;', }) const title = dom.createElement('h3', {}, 'Plugin Info') const info = dom.createElement('p', { id: 'info-text', }, 'Ready') this.element.appendChild(title) this.element.appendChild(info) const wrapper = this.wavesurfer.getWrapper() wrapper.appendChild(this.element) // Update on time change this.subscriptions.push( this.wavesurfer.on('timeupdate', (time) => { if (dom.isHTMLElement(info)) { info.textContent = `Time: ${time.toFixed(2)}s` } }) ) } public destroy() { if (this.element && dom.isHTMLElement(this.element)) { this.element.remove() } super.destroy() } } ``` -------------------------------- ### Listen to Timeline Ready Event Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/timeline-plugin.md The ready event fires once the timeline has finished initialization. ```javascript timeline.once('ready', () => { console.log('Timeline ready') }) ``` -------------------------------- ### Subscribe to state changes Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/types.md Demonstrates how to access the state and subscribe to changes in playback properties. ```javascript const state = wavesurfer.getState() state.currentTime.subscribe((time) => { console.log('Current time:', time) }) ``` -------------------------------- ### Implement a time display Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/README.md Format the current playback time into a minutes:seconds string for display. ```javascript const timeDisplay = document.querySelector('#time') wavesurfer.on('timeupdate', (time) => { const minutes = Math.floor(time / 60) const seconds = Math.round(time % 60) timeDisplay.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}` }) ``` -------------------------------- ### Initialize Timeline Plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/timeline-plugin.md Register the Timeline plugin with a wavesurfer.js instance. ```javascript import Timeline from 'wavesurfer.js/dist/plugins/timeline' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', }) const timeline = wavesurfer.registerPlugin( Timeline.create({ height: 20, }) ) ``` -------------------------------- ### MinimapPlugin.create() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/minimap-plugin.md Creates a new instance of the Minimap plugin to be registered with a WaveSurfer instance. ```APIDOC ## MinimapPlugin.create(options) ### Description Creates a Minimap plugin instance with the provided configuration options. ### Parameters #### Options - **options** (MinimapPluginOptions) - Required - Configuration object for the plugin. ### Options Details - **overlayColor** (string) - Optional - Viewport overlay color (Default: rgba(100, 100, 100, 0.1)) - **insertPosition** (InsertPosition) - Optional - Where to insert the minimap (Default: 'afterend') - **height** (number) - Optional - Height in pixels (Default: 50) - **waveColor** (string) - Optional - Miniature waveform color (Default: inherited) - **progressColor** (string) - Optional - Progress color (Default: inherited) ### Example ```javascript import Minimap from 'wavesurfer.js/dist/plugins/minimap' const minimap = Minimap.create({ height: 60, waveColor: '#ccc', progressColor: '#888', overlayColor: 'rgba(200, 200, 200, 0.2)', insertPosition: 'beforeend', }) ``` ``` -------------------------------- ### Create WaveSurfer Instance via Static Method Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Initializes a new WaveSurfer instance using the static create method with configuration options. ```typescript public static create(options: WaveSurferOptions): WaveSurfer ``` ```javascript const wavesurfer = WaveSurfer.create({ container: '#waveform', waveColor: '#4F4A85', progressColor: '#383351', url: '/audio.mp3', }) ``` -------------------------------- ### Initialize and Configure Minimap Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/minimap-plugin.md Registers the Minimap plugin with custom styling and event listeners for click and drag interactions. ```javascript import WaveSurfer from 'wavesurfer.js' import Minimap from 'wavesurfer.js/dist/plugins/minimap' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/podcast.mp3', minPxPerSec: 20, }) // Create minimap with custom styling const minimap = wavesurfer.registerPlugin( Minimap.create({ height: 50, waveColor: '#ddd', progressColor: '#999', overlayColor: 'rgba(100, 100, 100, 0.1)', }) ) // Listen to minimap interactions minimap.on('click', (relativeX) => { console.log('Minimap clicked at:', relativeX) }) minimap.on('drag', (relativeX) => { console.log('Minimap dragged to:', relativeX) }) // The main waveform tracks minimap position automatically wavesurfer.zoom(50) // Minimap updates automatically ``` -------------------------------- ### Check Web Audio API Support Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/webaudio-player.md Verify browser support for the Web Audio API before initializing the WebAudio backend. ```javascript if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') { console.log('Web Audio API supported') const wavesurfer = WaveSurfer.create({ container: '#waveform', backend: 'WebAudio', url: '/audio.mp3', }) } ``` -------------------------------- ### Include wavesurfer.js via CDN Source: https://github.com/katspaugh/wavesurfer.js/blob/main/README.md Use a UMD script tag to load the library globally. ```html ``` -------------------------------- ### Display Project File Inventory Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/INDEX.md A directory tree showing the organization of documentation files within the project. ```text output/ ├── README.md # Main overview and quick start ├── INDEX.md # This file ├── types.md # Type definitions ├── configuration.md # All configuration options └── api-reference/ ├── wavesurfer.md # Main WaveSurfer class ├── player.md # Player base class ├── event-emitter.md # EventEmitter system ├── base-plugin.md # Plugin base class ├── decoder.md # Audio decoder utility ├── fetcher.md # Audio fetcher utility ├── dom.md # DOM utilities ├── webaudio-player.md # Web Audio backend ├── regions-plugin.md # Regions plugin ├── timeline-plugin.md # Timeline plugin ├── minimap-plugin.md # Minimap plugin └── record-plugin.md # Record plugin ``` -------------------------------- ### TimelinePlugin Options Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/timeline-plugin.md Configuration options available when initializing the Timeline plugin. ```APIDOC ## TimelinePlugin Options ### Description Configuration properties for customizing the appearance and behavior of the timeline. ### Options - **height** (number) - Default: 20 - Timeline height in pixels. - **container** (HTMLElement | string) - Default: waveform container - Element to insert timeline into. - **insertPosition** (InsertPosition) - Optional - Where to insert the timeline element. - **duration** (number) - Default: auto - Timeline duration in seconds. - **timeInterval** (number) - Default: auto - Seconds between ticks. - **primaryLabelInterval** (number) - Default: auto - Seconds between numeric labels. - **secondaryLabelInterval** (number) - Default: auto - Seconds between secondary labels. - **primaryLabelSpacing** (number) - Default: auto - Ticks between primary labels. - **secondaryLabelSpacing** (number) - Default: auto - Ticks between secondary labels. - **timeOffset** (number) - Default: 0 - Offset in seconds for labels. - **style** (Partial | string) - Optional - Inline styles for the timeline. - **formatTimeCallback** (function) - Default: default - Custom formatter function: (seconds: number) => string. - **secondaryLabelOpacity** (number) - Default: 0.25 - Opacity of secondary labels. ``` -------------------------------- ### Audio Loading Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/README.md Methods for loading audio content into the instance. ```APIDOC ## Audio Loading - **load(url)**: Load audio from URL. - **loadBlob(blob)**: Load audio from Blob. - **load(url, peaks, duration)**: Load with pre-computed peaks. ``` -------------------------------- ### RegionsPlugin.create() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Initializes a new instance of the Regions plugin to be registered with a wavesurfer instance. ```APIDOC ## RegionsPlugin.create() ### Description Creates a new Regions plugin instance to enable region management on a waveform. ### Signature `public static create(options?: RegionsPluginOptions): RegionsPlugin` ### Parameters - **options** (RegionsPluginOptions) - Optional - Plugin configuration object. ### Returns - **RegionsPlugin** - The initialized plugin instance. ``` -------------------------------- ### Initialize Regions Plugin Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/regions-plugin.md Register the Regions plugin instance with a WaveSurfer instance. ```javascript import Regions from 'wavesurfer.js/dist/plugins/regions' const wavesurfer = WaveSurfer.create({ container: '#waveform', url: '/audio.mp3', }) const regions = wavesurfer.registerPlugin(Regions.create()) ``` -------------------------------- ### RecordPlugin.create() Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/record-plugin.md Creates a new instance of the Record plugin to be registered with a WaveSurfer instance. ```APIDOC ## RecordPlugin.create(options) ### Description Creates a Record plugin instance to enable audio recording features. ### Signature `public static create(options?: RecordPluginOptions): RecordPlugin` ### Parameters - **options** (RecordPluginOptions) - Optional - Plugin configuration object. ``` -------------------------------- ### Import and include plugins Source: https://github.com/katspaugh/wavesurfer.js/blob/main/README.md Plugins can be imported as modules or included via script tags. ```js import Regions from 'wavesurfer.js/dist/plugins/regions.esm.js' ``` ```html ``` -------------------------------- ### WaveSurfer Constructor Source: https://github.com/katspaugh/wavesurfer.js/blob/main/_autodocs/api-reference/wavesurfer.md Initializes a new WaveSurfer instance via the constructor. ```APIDOC ## new WaveSurfer(options: WaveSurferOptions) ### Description Creates a new WaveSurfer instance. Initialization is asynchronous and emits an 'init' event upon completion. ### Parameters - **options** (WaveSurferOptions) - Required - Configuration options for the instance. ### Example ```javascript const wavesurfer = new WaveSurfer({ container: '#waveform', height: 300, waveColor: '#999', progressColor: '#555', cursorWidth: 2, }) ``` ```