refactor(utils/lyrics): better parsing logic

This commit is contained in:
pan93412 2022-01-26 23:41:53 +08:00
parent 1c7344beaf
commit 3ddfe9c3bb
No known key found for this signature in database
GPG Key ID: 42154B1B1CFE3377

View File

@ -9,32 +9,37 @@ export function lyricParser(lrc) {
}; };
} }
export function parseLyric(lrc) { const extractTimeRegex = /^(?<rawTime>\[(?<min>\d+):(?<sec>\d+)(?:\.|:)(?<ms>\d+)\])\s*(?<content>(.+|))$/;
const lyrics = lrc.split('\n');
const lrcObj = []; function parseLyric(lrc) {
for (let i = 0; i < lyrics.length; i++) { const lyrics = lrc.trim().split('\n');
const lyric = lyrics[i];
const timeReg = /\[\d*:\d*((\.|:)\d*)*\]/g; const parsedLyrics = lyrics
const timeRegExpArr = lyric.match(timeReg); .filter(lyric => lyric.length) // filter the lyric line which is empty
if (!timeRegExpArr) continue; .map((/** @type {string} */ line) => {
const content = lyric.replace(timeReg, ''); try {
for (let k = 0, h = timeRegExpArr.length; k < h; k++) { const extractedLyric = extractTimeRegex.exec(line);
const t = timeRegExpArr[k];
const min = Number(String(t.match(/\[\d*/i)).slice(1)); // If this line is not a lyric.
const sec = Number(String(t.match(/:\d*/i)).slice(1)); if (!extractedLyric) throw 'This line is not a lyric.';
const ms = Number(t.match(/\d*\]/i)[0].slice(0, 2)) / 100;
const time = min * 60 + sec + ms; // Otherwise, we extract the lyric part.
if (content !== '') { const { rawTime, min, sec, ms, content } = extractedLyric.groups;
lrcObj.push({ const time = Number(min) * 60 + Number(sec) + 0.01 * Number(ms);
time: time,
rawTime: timeRegExpArr[0], return {
time,
rawTime,
content: trimContent(content), content: trimContent(content),
}); };
} catch (e) {
console.warn(`Failed to extract "${line}". ${e}`);
} }
} })
} .filter(response => !!response) // remove "undefined" entries
lrcObj.sort((a, b) => a.time - b.time); .sort((a, b) => a.time - b.time);
return lrcObj;
return parsedLyrics;
} }
function trimContent(content) { function trimContent(content) {