歌詞同步是音樂播放器的核心體驗之一。本文完整演示從 LRC 文件解析、時間戳轉換、自定義 WordView 繪製滾動效果 到 播放進度驅動歌詞高亮 的全流程實現,附帶關鍵代碼與邏輯圖解。
[ar:藝人]
[ti:標題]
[al:專輯]
[by:製作人]
[offset:0] // 毫秒偏移,正值提前
[00:12.34]第一句歌詞
[00:15.87]第二句歌詞
public class LrcParser {
private final List lines = new ArrayList<>();
private final List timestamps = new ArrayList<>();
public void parse(String lrcContent) {
String[] rawLines = lrcContent.split("\n");
Pattern timePattern = Pattern.compile("\\[(\\d{2}):(\\d{2})[.:](\\d{2,3})\\]");
for (String line : rawLines) {
Matcher m = timePattern.matcher(line);
if (m.find()) {
// 可能一行多個時間標籤,取最後一個作為顯示時間
long time = 0;
do {
int min = Integer.parseInt(m.group(1));
int sec = Integer.parseInt(m.group(2));
int ms = Integer.parseInt(m.group(3));
// 處理 2/3 位毫秒
if (m.group(3).length() == 2) ms *= 10;
time = (min * 60 + sec) * 1000 + ms;
} while (m.find());
String text = timePattern.matcher(line).replaceAll("").trim();
timestamps.add(time);
lines.add(text.isEmpty() ? "" : text);
} else {
// 元數據行
if (line.startsWith("[ti:") || line.startsWith("[ar:") || line.startsWith("[al:")) {
// 可選保存元數據
}
}
}
}
public List getLines() { return lines; }
public List getTimestamps() { return timestamps; }
}
public class WordView extends View {
private List lyrics;
private List times;
private Paint highlightPaint, normalPaint;
private int currentLine = 0;
private float lineHeight = 80f;
private float centerY;
public WordView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
highlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
highlightPaint.setColor(Color.YELLOW);
highlightPaint.setTextSize(48);
highlightPaint.setTextAlign(Paint.Align.CENTER);
highlightPaint.setTypeface(Typeface.DEFAULT_BOLD);
normalPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
normalPaint.setColor(Color.WHITE);
normalPaint.setTextSize(36);
normalPaint.setTextAlign(Paint.Align.CENTER);
}
public void setLyrics(List lyrics, List times) {
this.lyrics = lyrics;
this.times = times;
invalidate();
}
public void updateCurrentTime(long currentMs) {
// 二分查找當前應高亮的行
int low = 0, high = times.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (times.get(mid) <= currentMs) {
currentLine = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
invalidate(); // 觸發重繪
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
centerY = h * 0.4f; // 高亮行位於上方 40%
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
if (lyrics == null) return;
// 繪製當前高亮行
canvas.drawText(lyrics.get(currentLine), getWidth() / 2f, centerY, highlightPaint);
// 繪製上方歷史行(漸變透明度)
float y = centerY - lineHeight;
for (int i = currentLine - 1; i >= 0; i--) {
if (y < 0) break;
int alpha = Math.max(50, 255 - (currentLine - i) * 40);
normalPaint.setAlpha(alpha);
canvas.drawText(lyrics.get(i), getWidth() / 2f, y, normalPaint);
y -= lineHeight;
}
// 繪製下方即將到來的行
y = centerY + lineHeight;
for (int i = currentLine + 1; i < lyrics.size(); i++) {
if (y > getHeight()) break;
int alpha = Math.max(50, 255 - (i - currentLine) * 40);
normalPaint.setAlpha(alpha);
canvas.drawText(lyrics.get(i), getWidth() / 2f, y, normalPaint);
y += lineHeight;
}
}
}
public class PlayerService extends Service {
private MediaPlayer mediaPlayer;
private WordView wordView;
private Handler handler = new Handler(Looper.getMainLooper());
private Runnable syncRunnable = new Runnable() {
@Override public void run() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
wordView.updateCurrentTime(mediaPlayer.getCurrentPosition());
handler.postDelayed(this, 100); // 100ms 刷新一次
}
}
};
// ... 播放/暫停時啟動/停止 syncRunnable
}

offset 全局時間偏移校準。[00:12.34][00:15.00]雙時間標籤(翻譯/羅馬音)。ValueAnimator 實現行平滑滾動動畫,而非瞬間跳變。掌握此完整鏈路,即可打造媲美 QQ音樂/網易雲音樂級別的歌詞同步體驗。