Build a Simple Audio Trimmer
This is the core technique behind Haven Toolbox's Audio Edit tool, stripped down to the basics: load an audio file into memory, then play back just a portion of it. No server, no upload, just the Web Audio API.
The HTML: a file input and playback controls
<input type="file" id="fileInput" accept="audio/*">
<label>Start (seconds) <input type="number" id="start" value="0"></label>
<label>End (seconds) <input type="number" id="end" value="5"></label>
<button id="playBtn">Play trimmed clip</button>
Decode the file
const fileInput = document.querySelector('#fileInput');
let audioBuffer = null;
let audioCtx = null;
fileInput.addEventListener('change', async () => {
audioCtx = new AudioContext();
const arrayBuffer = await fileInput.files[0].arrayBuffer();
audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
});
An AudioContext is the Web Audio API's entry point; almost everything else
happens through it. decodeAudioData takes the raw file bytes and turns them
into an AudioBuffer: the actual decoded audio samples, sitting in memory,
ready to play.
Play just a portion of it
document.querySelector('#playBtn').addEventListener('click', () => {
const start = Number(document.querySelector('#start').value);
const end = Number(document.querySelector('#end').value);
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.start(0, start, end - start);
});
A BufferSource plays an AudioBuffer once connected to the
context's destination (your speakers). start takes three
arguments: when to begin playing (0 means immediately), where in the buffer to
start reading from, and how long to play. Passing the start and end values from the form
turns this into a trim: whatever comes before start or after
end is simply never played.
Where to go from here
This plays a trimmed section live; it doesn't save one. Actually exporting the trimmed
audio as a downloadable file needs an OfflineAudioContext to render the result
instead of just playing it, and combining multiple clips means scheduling each one to start
at a different point on a shared timeline. Both of those, plus fades, volume control, and a
draggable waveform, are exactly what Haven Toolbox's
Audio
Edit and Audio
Merge tools do. See the local-only guide for more on
why none of this needs a server, or JavaScript
basics if this is your first look at a browser API like this one.