New project announcement
I shipped skillcraft.ai - a tool that helps you find the best learning resources tailored to your goals. All you need to do is tell it what you want to learn, and I’ll find the right resources to get you there.
Archived
Published
5 min read

Trevor I. Lasn

Building tools for developers. Currently building skillcraft.ai and blamesteve.lol

Peaks.js — Interact With Audio Waveforms

Peaks.js is a client-side JavaScript component to display and interact with audio waveforms in the browser

Peaks.js lets you display and interact with audio waveforms right in the browser. This can be super helpful when you need to:

Interact With Audio Waveforms

  • Zoom in on a specific section of the audio.
  • Add markers to highlight important parts, like speech or music breaks.
  • Allow users to make precise clippings.

You can use Peaks.js to visually navigate through audio content, much like you see in professional audio editing software.

Why Would You Use Peaks.js?

  1. You need a way to let users interact with audio content — like scrolling through a waveform.
  2. You want to allow users to make selections or mark points — for clipping or just for reference.
  3. You need zoomable views — so users can get a detailed look at specific parts of the audio.

This is great for building things like podcast editors, audio annotation tools, or music players where interaction matters.

Setting Up Peaks.js in Your Project

Let’s get to the fun part. I’m going to show you how to set this up from scratch. You’ll see how easy it is to get this running.

1. Install Peaks.js

You can install it using npm:

Terminal window
npm install --save peaks.js

Or just grab it from a CDN if you don’t want to use a bundler.

  1. Basic Setup with Web Audio Here’s a simple way to get Peaks.js working using the Web Audio API. This approach doesn’t require you to pre-generate waveform data, but it’s important to note that it’s CPU intensive and works best with shorter audio files. Here’s how to get started:
<audio id="audio" src="sample.mp3" controls></audio>
<div id="overview-waveform"></div>
<div id="zoomview-waveform"></div>
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();
const options = {
containers: {
overview: document.getElementById('overview-waveform'),
zoomview: document.getElementById('zoomview-waveform')
},
mediaElement: document.getElementById('audio'),
webAudio: {
audioContext: audioContext
}
};
Peaks.init(options, function(err, peaks) {
if (err) {
console.error('Error initializing Peaks.js:', err);
} else {
console.log('Waveform is ready');
}
});

What’s happening here?

  • We define two div elements where Peaks.js will render the overview and zoomable waveforms.
  • The mediaElement points to an <audio> element that holds the audio file.
  • We initialize Peaks.js with the webAudio option, which uses the Web Audio API to generate waveforms.

What’s Good About This?

  • You don’t need to generate waveform data files ahead of time.
  • Users can zoom in on the waveform and interact with it right away.

But, as I mentioned, it can be slow for long audio files since the browser has to download the whole audio file before showing the waveform.

Pre-Generated Waveform Data (For Larger Files)

If you’re working with longer audio files, it’s better to pre-generate the waveform data. Peaks.js supports both JSON and binary formats. Let’s say you have a 1-hour podcast file, and you don’t want to make users wait.

You can use a tool called audiowaveform to generate the waveform data. Generate binary waveform data:

Terminal window
audiowaveform -i sample.mp3 -o sample.dat -b 8

This will output a .dat file that Peaks.js can use to render the waveform efficiently. Now you just need to load this into Peaks.js:

const options = {
containers: {
overview: document.getElementById('overview-waveform'),
zoomview: document.getElementById('zoomview-waveform')
},
mediaElement: document.getElementById('audio'),
dataUri: {
arraybuffer: 'sample.dat'
}
};
Peaks.init(options, function(err, peaks) {
if (err) {
console.error('Error initializing Peaks.js:', err);
} else {
console.log('Waveform is ready');
}
});

Why this is better for longer audio

  • Peaks.js doesn’t need to analyze the audio file on the fly.
  • The pre-generated .dat file is much smaller, and Peaks.js can load the waveform faster.

Adding Markers and Segments

One of the best features of Peaks.js is the ability to add markers. You can use these markers to create reference points in your audio or even create segments for clipping.

Here’s an example of how you can add a marker at 10 seconds:

peaks.segments.add({
id: 'marker1',
startTime: 10,
endTime: 15,
labelText: 'Clip Segment'
});
peaks.points.add({
time: 10,
labelText: 'Start Point'
});

Why markers matter

  • You can let users visually interact with specific points in the audio.
  • Great for building editors where users can clip sections of the audio.

Real-World Example: Podcast Editor

Imagine you’re building a simple podcast editor. Peaks.js allows users to visually interact with their podcast episodes, zoom in to trim dead air, and mark segments for editing.

function setupPodcastEditor() {
const options = {
containers: {
overview: document.getElementById('overview-waveform'),
zoomview: document.getElementById('zoomview-waveform')
},
mediaElement: document.getElementById('audio'),
dataUri: {
arraybuffer: 'podcast_waveform.dat'
}
};
Peaks.init(options, function(err, peaks) {
if (!err) {
peaks.segments.add({
id: 'intro',
startTime: 0,
endTime: 30,
labelText: 'Podcast Intro'
});
console.log('Podcast editor is ready');
}
});
}

This setup lets the user zoom in on the intro, mark it, and make precise edits.

Peaks.js is a fantastic tool for anyone needing to interact with audio content in the browser. Whether you’re building a podcast editor or just need to create audio clippings, Peaks.js makes it easy to render, zoom, and mark your audio waveforms.

If you’re working with short audio, the Web Audio API option works well, but for longer files, pre-generating the waveform data is your best bet.


Found this article helpful? You might enjoy my free newsletter. I share dev tips and insights to help you grow your coding skills and advance your tech career.


Check out these related articles that might be useful for you. They cover similar topics and provide additional insights.

Webdev
3 min read

CSS :has() - The Parent Selector We've Always Wanted

Transform your CSS with :has(), the game-changing selector that finally lets us style elements based on their children.

Dec 4, 2024
Read article
Webdev
4 min read

Open Dyslexic Font: Improve Your Web Accessibility

How to implement the Open-Dyslexic font to enhance readability for users with dyslexia

Oct 12, 2024
Read article
Webdev
8 min read

Become a Web Developer in 180 Days

A comprehensive roadmap to becoming a proficient web developer

Oct 29, 2019
Read article
Webdev
8 min read

Stop Using localStorage for Sensitive Data: Here's Why and What to Use Instead

Understanding the security risks of localStorage and what to use instead for tokens, secrets, and sensitive user data

Oct 28, 2024
Read article
Webdev
4 min read

How To Implement Content Security Policy (CSP) Headers For Astro

Content Security Policy (CSP) acts like a shield against XSS attacks. These attacks are sneaky - they trick your browser into running malicious code by hiding it in content that seems trustworthy. CSP's job is to spot these tricks and shut them down, while also alerting you to any attempts it detects.

Oct 16, 2024
Read article
Webdev
3 min read

CSS ::target-text for Text Highlighting

A look at how browsers can highlight text fragments using CSS ::target-text, making text sharing and navigation more user-friendly

Dec 17, 2024
Read article
Webdev
6 min read

Inside the CSS Engine: CSSOM Explained

A deep dive into how browsers parse and manipulate CSS, its impact on web performance, and why it matters

Oct 25, 2024
Read article
Webdev
4 min read

LH and RLH: The CSS Units That Make Vertical Spacing Easy

Exploring new CSS line-height units that eliminate guesswork from vertical rhythm

Dec 3, 2024
Read article
Webdev
8 min read

Invisible columns in SQL

It’s a small feature, but it can make a big difference.

Aug 26, 2024
Read article

This article was originally published on https://www.trevorlasn.com/blog/peaks-js-interact-with-audio-waveforms. It was written by a human and polished using grammar tools for clarity.