import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class LyricsParser {
public static class LyricEntry {
public final long timestamp; // 时间戳(毫秒)
public final String text; // 歌词文本
public LyricEntry(long timestamp, String text) {
this.timestamp = timestamp;
this.text = text;
}
}
public List<LyricEntry> parseLrcFile(File lrcFile) {
List<LyricEntry> lyrics = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(lrcFile))) {
String line;
while ((line = reader.readLine()) != null) {
LyricEntry entry = parseLine(line);
if (entry != null) {
lyrics.add(entry);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return lyrics;
}
private LyricEntry parseLine(String line) {
if (line.startsWith("[") && line.contains("]")) {
int endIndex = line.indexOf(']');
String timeString = line.substring(1, endIndex);
String text = line.substring(endIndex + 1).trim();
long timestamp = parseTime(timeString);
return new LyricEntry(timestamp, text);
}
return null;
}
private long parseTime(String timeString) {
String[] parts = timeString.split(":");
if (parts.length == 2) {
int minutes = Integer.parseInt(parts[0]);
String[] secondsParts = parts[1].split("\\.");
int seconds = Integer.parseInt(secondsParts[0]);
int milliseconds = secondsParts.length > 1 ? Integer.parseInt(secondsParts[1]) : 0;
return (minutes * 60 + seconds) * 1000 + milliseconds * 10;
}
return 0;
}
}
上面是读取歌词的文件。
读取歌词
File lrcFile = new File(playInfo.currentPlaying.dir+File.separator+playInfo.currentPlaying.title+".lrc");
if (lrcFile.exists()) {
LyricsParser parser = new LyricsParser();
lyrics = parser.parseLrcFile(lrcFile);
} else {
lyrics = null;
}
使用recyclerview显示歌词,根据播放的时间回调判断是哪句歌词在显示,把这句歌词居中
if (lyrics.getPos() >= 0) {
((LinearLayoutManager) (binding.rvLrcList.getLayoutManager())).scrollToPositionWithOffset(Math.max(lyrics.getPos()- 1, 0), 0);
} else {
((LinearLayoutManager) (binding.rvLrcList.getLayoutManager())).scrollToPositionWithOffset(0, 0);
}