mirror of
https://github.com/qier222/YesPlayMusic.git
synced 2024-11-22 12:47:27 +08:00
refactor(utils/lyrics): better parsing logic
This commit is contained in:
parent
1c7344beaf
commit
3ddfe9c3bb
|
@ -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) {
|
||||||
|
|
Loading…
Reference in New Issue
Block a user