Fixing a skip that played the previous song: a race in an audio player
A race condition in Melodius's web player: while the next track's source resolved, the old audio element's events still reached the store. How it showed up, why, and the fix.
Some bugs only appear in a window a few hundred milliseconds wide. This one lived in the Melodius web and desktop player and made skipping feel broken.
The symptom
Pause a song, press next, then press play quickly. For a moment the previous song played under the new title, with the old song's clock ticking below it.
The cause
Skipping starts resolving the next track's source, which takes a network round trip. During that time the previous track's audio element is still the engine's active one. Its events, pause, progress, ended and crossfade, kept flowing into the player store as if they described the new track. And a play request in that window resumed the element that existed: the old song.
The fix
- Events from the active element are ignored until the new source has actually reached the engine.
- A play request made during the gap waits for the new source instead of resuming the old element.
- Metadata arriving early no longer flips a track from "loading" to "ready" before its audio can play.
The same idea, applied to visuals
Once the rule was clear, "only switch when the next thing is ready", it fixed flicker too. The cover art swaps only after the next image has decoded, the now-playing panel reuses that stable cover, and the full-screen artist image stays until the next one arrives. Nothing on screen claims to be the next song before the next song can play.
Related: how the player decides what to do when a track fails, in retry, skip or wait.
