Skip to content

Instantly share code, notes, and snippets.

@katspaugh
Created December 9, 2024 07:54
Show Gist options
  • Save katspaugh/5cc63deca8da61df67c85b01d4004247 to your computer and use it in GitHub Desktop.
Save katspaugh/5cc63deca8da61df67c85b01d4004247 to your computer and use it in GitHub Desktop.
// Regions plugin
import WaveSurfer from 'wavesurfer.js'
import RegionsPlugin from 'wavesurfer.js/dist/plugins/regions.esm.js'
// Initialize the Regions plugin
const regions = RegionsPlugin.create()
// Create a WaveSurfer instance
const ws = WaveSurfer.create({
container: '#waveform',
waveColor: 'rgb(200, 0, 200)',
progressColor: 'rgb(100, 0, 100)',
url: '/examples/audio/audio.wav',
plugins: [regions],
})
// Give regions a random color when they are created
const random = (min, max) => Math.random() * (max - min) + min
const randomColor = () => `rgba(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)}, 0.5)`
// Create some regions at specific time ranges
ws.on('decode', () => {
})
regions.enableDragSelection({
color: 'rgba(255, 0, 0, 0.1)',
drag: false,
resize: true,
})
var regionTest = [];
// Listen for region creation
regions.on('region-created', (region) => {{
const now = Date.now();
// Add the new region with its timestamp
regionTest.push({ region, timestamp: now });
// If there is more than one recent region, remove all but the last
if (regionTest.length > 1) {{
const regionsToRemove = regionTest.slice(0, -1); // All but the last
console.log('regionsToRemove', regionsToRemove);
// Remove each region except the last
regionsToRemove.forEach(item => {{
console.log('removing region', item.region);
item.region.remove(); // Remove the region from Wavesurfer
}});
// Keep only the last region in the array
regionTest = [regionTest[regionTest.length - 1]];
}}
}});
/*
<html>
<div id="waveform"></div>
<p>
<label>
<input type="checkbox" checked="${loop}" />
Loop regions
</label>
<label style="margin-left: 2em">
Zoom: <input type="range" min="10" max="1000" value="10" />
</label>
</p>
<p>
📖 <a href="https://wavesurfer.xyz/docs/classes/plugins_regions.RegionsPlugin">Regions plugin docs</a>
</p>
</html>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment