using HaloPixelToolBox.Core.Models.Lyrics;
using System.Text.RegularExpressions;
namespace HaloPixelToolBox.Core.Utilities;
/// <summary>
/// 解析标准 LRC 时间标签并生成按时间排序的歌词行。
/// </summary>
public static partial class LrcParser
{
[GeneratedRegex(@"\[(\d+):(\d+)(?:[:\.](\d+))?\]")]
private static partial Regex LrcTimeRegex();
[GeneratedRegex(@"\[\d+:\d+(?:[:\.]\d+)?\]")]
private static partial Regex CleanTimecodeRegex();
public static List<LyricLine> Parse(string lrcContent)
{
List<LyricLine> lines = [];
if (string.IsNullOrWhiteSpace(lrcContent))
return lines;
foreach (var line in lrcContent.Split(["\r\n", "\r", "\n"], StringSplitOptions.RemoveEmptyEntries))
{
var match = LrcTimeRegex().Match(line);
if (!match.Success || !int.TryParse(match.Groups[1].Value, out var minutes) ||
!int.TryParse(match.Groups[2].Value, out var seconds))
continue;
var milliseconds = ParseMilliseconds(match.Groups[3].Value);
var text = CleanTimecodeRegex().Replace(line[match.Length..], string.Empty).Trim();
if (string.IsNullOrEmpty(text))
continue;
lines.Add(new()
{
Timestamp = new TimeSpan(0, 0, minutes, seconds, milliseconds),
Text = text
});
}
lines.Sort(static (left, right) => left.Timestamp.CompareTo(right.Timestamp));
return lines;
}
private static int ParseMilliseconds(string fraction)
{
if (string.IsNullOrEmpty(fraction) || !int.TryParse(fraction[..Math.Min(fraction.Length, 3)], out var value))
return 0;
return fraction.Length switch
{
1 => value * 100,
2 => value * 10,
_ => value
};
}
}
using HaloPixelToolBox.Core.Models.Lyrics;
using System.Text.RegularExpressions;
namespace HaloPixelToolBox.Core.Utilities;
/// <summary>
/// 解析标准 LRC 时间标签并生成按时间排序的歌词行。
/// </summary>
public static partial class LrcParser
{
[GeneratedRegex(@"\[(\d+):(\d+)(?:[:\.](\d+))?\]")]
private static partial Regex LrcTimeRegex();
[GeneratedRegex(@"\[\d+:\d+(?:[:\.]\d+)?\]")]
private static partial Regex CleanTimecodeRegex();
public static List<LyricLine> Parse(string lrcContent)
{
List<LyricLine> lines = [];
if (string.IsNullOrWhiteSpace(lrcContent))
return lines;
foreach (var line in lrcContent.Split(["\r\n", "\r", "\n"], StringSplitOptions.RemoveEmptyEntries))
{
var match = LrcTimeRegex().Match(line);
if (!match.Success || !int.TryParse(match.Groups[1].Value, out var minutes) ||
!int.TryParse(match.Groups[2].Value, out var seconds))
continue;
var milliseconds = ParseMilliseconds(match.Groups[3].Value);
var text = CleanTimecodeRegex().Replace(line[match.Length..], string.Empty).Trim();
if (string.IsNullOrEmpty(text))
continue;
lines.Add(new()
{
Timestamp = new TimeSpan(0, 0, minutes, seconds, milliseconds),
Text = text
});
}
lines.Sort(static (left, right) => left.Timestamp.CompareTo(right.Timestamp));
return lines;
}
private static int ParseMilliseconds(string fraction)
{
if (string.IsNullOrEmpty(fraction) || !int.TryParse(fraction[..Math.Min(fraction.Length, 3)], out var value))
return 0;
return fraction.Length switch
{
1 => value * 100,
2 => value * 10,
_ => value
};
}
}