Making an audio seek bar feel smooth
Preview while dragging, one redraw per frame, and a short animation that a newer action can interrupt.
Setting audio.currentTime on every pointer movement makes a seek bar stutter and produces bursts of sound while dragging. The player on my profile page separates what the bar shows from what the audio is doing.
- Press: pause and remember
- Drag: update the preview
- Release or click
- Commit time and resume
A preview value
While someone drags, the controller holds a preview time. The interface reads the preview if there is one and the real playback time otherwise. The audio only jumps once, when the drag finishes. Before pausing, the controller records whether the track was playing, so a paused track stays paused.
One update per frame
Pointer events can fire more often than the screen redraws. Each movement stores the newest target, and only one animation frame is scheduled at a time. When it runs, it uses whatever the latest target is.
A short ease-out
A drag already shows its movement, so releasing it commits right away. A simple click is different: the preview glides to the clicked point over 220 milliseconds with a cubic ease-out, which starts quickly and settles gently:
const progress = Math.min(1, (now - started) / 220);
preview = start + (target - start) * (1 - (1 - progress) ** 3);
People who have asked their system for reduced motion skip the animation and jump straight to the new time.
Interrupted animations
A second drag can begin while the first animation is still running. A revision number handles this. Every reset increases it, and each animation step compares its own number with the current one before doing anything. An outdated step simply stops.
Easier testing
The controller receives the audio element, the render function and the frame scheduler as arguments. A test can pass in a fake audio object and run frames by hand, with no browser or sound required.