fix: fill line-timed lyrics as they play #139
@@ -16,11 +16,15 @@ export type LyricLine = {
|
||||
text: string
|
||||
/** Seconds; `null` for plain lyrics. */
|
||||
start: number | null
|
||||
/** Set only on word-timed lines. */
|
||||
/**
|
||||
* The line's words as they are sung. Line-timed lyrics get estimated
|
||||
* ones (see `estimateWords`); plain lyrics have none.
|
||||
*/
|
||||
words: LyricWord[] | null
|
||||
}
|
||||
|
||||
export type Lyrics = {
|
||||
/** How the source was timed, whatever `words` were estimated. */
|
||||
synced: "none" | "line" | "word"
|
||||
lines: LyricLine[]
|
||||
}
|
||||
@@ -29,6 +33,8 @@ const LINE_STAMP = /^\[(\d+):(\d+(?:[.:]\d+)?)\]/
|
||||
const WORD_STAMP = /<(\d+):(\d+(?:[.:]\d+)?)>/g
|
||||
const HAS_WORD_STAMP = /<\d+:\d+(?:[.:]\d+)?>/
|
||||
const ID_TAG = /^\[[a-z]+:.*\]$/i
|
||||
/** A rough singing pace, so a line-timed line's fill tracks its words. */
|
||||
const ESTIMATED_SECONDS_PER_CHAR = 0.07
|
||||
|
||||
function seconds(minutes: string, rest: string) {
|
||||
return Number(minutes) * 60 + Number(rest.replace(":", "."))
|
||||
@@ -107,10 +113,31 @@ export function parseLyrics(raw: string): Lyrics | null {
|
||||
}
|
||||
lines.sort((a, b) => a.start! - b.start!)
|
||||
if (lines.length === 0) return null
|
||||
return {
|
||||
synced: lines.every((line) => line.words) ? "word" : "line",
|
||||
lines,
|
||||
}
|
||||
const synced = lines.every((line) => line.words) ? "word" : "line"
|
||||
if (synced === "line") estimateWords(lines)
|
||||
return { synced, lines }
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives timed lines without word timing words spread over them by length,
|
||||
* at a singing pace but never past the next line, so they fill as they play.
|
||||
*/
|
||||
function estimateWords(lines: LyricLine[]) {
|
||||
lines.forEach((line, index) => {
|
||||
if (line.words || line.start === null) return
|
||||
const next = lines[index + 1]?.start ?? Infinity
|
||||
const duration = Math.min(
|
||||
next - line.start,
|
||||
line.text.length * ESTIMATED_SECONDS_PER_CHAR
|
||||
)
|
||||
const perChar = duration / line.text.length
|
||||
let at = line.start
|
||||
line.words = (line.text.match(/\S+\s*/g) ?? []).map((text) => {
|
||||
const start = at
|
||||
at += text.length * perChar
|
||||
return { text, start, end: at }
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** The text without timestamps, one line per row, for search and snippets. */
|
||||
|
||||
Reference in new issue
Block a user