直接放出代码
object LyricParser {
private fun toTimeInSeconds(input: String): Int {
val timeParts = input.split(":")
val minutes = timeParts[0].toInt()
val seconds = timeParts[1].substringBefore(".").toInt()
return minutes * 60 + seconds
}
fun parse(lyric: String): MutableMap<Int, String> {
val lyricsMap = mutableMapOf<Int, String>()
var currentLyric = ""
for (line in lyric.trimIndent().lines()) {
val parts = line.split("]")
val times = parts.dropLast(1).map { toTimeInSeconds(it.substring(1).replace(".000", "").trim()) }
val content = parts.last().trim()
if (times.isNotEmpty()) {
for (time in times) {
lyricsMap[time] = currentLyric.trim()
}
currentLyric = content
} else {
currentLyric += " $content"
}
}
val keys = lyricsMap.keys.toList()
val values = lyricsMap.values.toList()
keys.dropLast(1)
val shiftedValues = values.drop(1)
val shiftedLyricsMap = mutableMapOf<Int, String>()
for (i in keys.indices) {
shiftedLyricsMap[keys[i]] = shiftedValues.getOrElse(i) { "" }
}
return shiftedLyricsMap
}
fun parseQQLyric(lyrics: String): Map<Int, String> {
val lyricsMap = mutableMapOf<Int, String>()
val regex = """\[(\d{2}):(\d{2})\.(\d{2})](.*)""".toRegex()
lyrics.lines().forEach { line ->
val matchResult = regex.find(line)
if (matchResult != null) {
val minute = matchResult.groups[1]?.value?.toInt() ?: 0
val second = matchResult.groups[2]?.value?.toInt() ?: 0
val millis = matchResult.groups[3]?.value?.toInt() ?: 0
val lyricText = matchResult.groups[4]?.value?.trim() ?: ""
val totalSeconds = minute * 60 + second + if (millis >= 50) 1 else 0
if (lyricText.isNotEmpty()) {
lyricsMap[totalSeconds] = lyricText
}
}
}
return lyricsMap
}
}
parse
方法是解析网易云歌词的parseQQLyric
是解析QQ音乐的歌词, 最终的结果都是返回一个Map<Int, String>
, Int是对应的秒数, String是秒数对应的歌词
1.本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:[email protected],工作室将第一时间处理!
2.资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。
3.所有资源仅限于参考和学习,版权归原作者所有。