Bio and Widget

Finding the current lyric line

By Nuz ·

Parsing timed lyric files, searching them quickly, and refusing results that belong to a different recording.

My profile page and a companion widget show lyrics in time with the music. The display looks simple, but it depends on three small pieces: reading the file, finding the right line, and making sure the lyrics are for the right song.

  1. Look up the track
  2. Verify the match
  3. Parse timestamps
  4. Search by playback time

Parsing LRC

Timed lyrics usually arrive in the LRC format, where each line starts with a time such as [01:12.50]. One line may carry several times when a chorus repeats, so the parser collects every timestamp, pairs each with the text, and sorts the result.

for (const line of String(lrc || '').split(/\r?\n/)) {
  const text = line.replace(/\[[^\]]*\]/g, '').trim();
  for (const [, minutes, seconds] of line.matchAll(/\[(\d+):(\d+(?:\.\d+)?)\]/g)) {
    lyrics.push({ time: Number(minutes) * 60 + Number(seconds), text });
  }
}
return lyrics.sort((a, b) => a.time - b.time);

Empty lines are kept on purpose. They mark instrumental breaks, so the previous words do not linger.

Binary search

The current line is the last one whose time is not after the playback position. Because the list is sorted, a binary search finds it in a handful of steps, and it behaves the same whether the song moved forward normally or someone jumped to the middle.

Matching the right recording

A title and artist can match a live version, an edit or a cover with different timing. Before using a result, the code compares normalized titles and artist names, and requires the duration to be within a few seconds. Timestamps that run well past the end of the track are rejected too. Showing nothing is better than showing confidently wrong words.

Being a polite client

The lyric sources are free public services. The widget caches a successful lookup for a day and a failed one for a minute. When a service answers that it is busy, with status 429 or 503, the widget reads the Retry-After header and waits at least a minute before asking again. Requests also time out instead of hanging.

If your own lyrics are consistently early or late, the LRC timing shifter can move them.

More build notes

← All build notes