在卡拉 OK 模式中,如何根据音节时长逐字染色?
解读
面试官真正想看的是“时间轴 + 逐字渲染”的闭环能力,而不是简单地把字符串染成红色。
国内项目里,歌词通常用 LRC 或 KRC 格式,每个字自带“开始时间+持续时间”。
你要在 Pygame 的主循环里,把当前播放时间(由 pygame.mixer.music.get_pos() 或自行维护的 timer)与字级时间戳比对,动态生成“已唱/未唱”两份 Surface,再按字宽拼回同一行,保证 60 FPS 不闪、不错位、不乱码。
如果只说“我用 font.render 然后 fill 颜色”,会被追问性能、对齐、换行、标点、空拍、暂停、拖拽进度条怎么办。
因此答案必须体现:
- 数据层——如何把 LRC 解析成 [(char, start_ms, dur_ms), …];
- 渲染层——如何缓存字形尺寸、如何双缓冲避免每帧全量 render;
- 时间层——如何与音乐播放进度同步,并处理 seek、pause、变速;
- 性能层——如何只在时间片边界或字变更时重绘,保证移动端也能跑。
知识点
- Pygame 字体子系统:pygame.freetype.Font(比 pygame.font 抗锯齿更好,支持 metrics 精准取字宽)。
- 时间同步:pygame.mixer.music.get_pos() 返回的是“播放头位置”,单位毫秒,但启动瞬间有 ~10 ms 抖动;需用自定义 Timer 与 SDL_GetTicks 做漂移修正。
- 字形缓存:pre-render 所有字符到两张 dict(color_a: 已唱颜色,color_b: 未唱颜色),记录 (w, h, surface);避免每帧 render。
- 定位算法:累加 pre-cached 字宽得到每个字的 x 偏移,用 surface.blits([(surf, (x, 0)) …]) 一次批量绘制,比逐次 blit 快 3× 以上。
- 事件驱动:只在“当前字索引变更”时重新拼合一行,其余帧直接 blit 缓存好的 line_surf,降低 Python 层 CPU 占用。
- 对齐与换行:中文标点避让、英文连字、\n 分行,需要把“行”作为独立对象,每行维护自己的 char_list 与 current_idx。
- 安全兜底:音乐未加载或 seek 到负时间,要 clamp 索引;文件编码 UTF-8 BOM 处理;异常字用 □ 占位。
答案
给出一个可直接落地的 120 行以内核心实现,兼顾可读性与性能,方便面试时白板书写。
import pygame, pygame.freetype, re
class KaraokeLine:
def __init__(self, line_text: str, timing: list, font: pygame.freetype.Font,
done_color=(255,80,80), todo_color=(255,255,255)):
"""
line_text: 纯文本,如 "我爱你中国"
timing: [(start_ms, dur_ms), ...] 与 line_text 逐字对应
"""
self.text = line_text
self.timing = timing
self.font = font
self.done_color = done_color
self.todo_color = todo_color
# 预渲染
self.done_surfs = [] # [(surf, w)]
self.todo_surfs = []
total_w = 0
for ch in line_text:
s1, r1 = font.render(ch, fgcolor=done_color)
s2, r2 = font.render(ch, fgcolor=todo_color)
w = r1.width
self.done_surfs.append((s1, w))
self.todo_surfs.append((s2, w))
total_w += w
self.total_width = total_w
self.cache = pygame.Surface((total_w, self.done_surfs[0][0].get_height()), pygame.SRCALPHA)
self.dirty = True
self.last_idx = -1
def update(self, t_ms: int):
"""根据时间计算已唱到第几个字,触发重绘"""
idx = -1
for i, (start, dur) in enumerate(self.timing):
if t_ms >= start:
idx = i
else:
break
if idx != self.last_idx:
self.dirty = True
self.last_idx = idx
def draw(self, screen, x, y):
if self.dirty:
self.cache.fill((0,0,0,0))
dx = 0
for i, ((dsurf, dw), (tsurf, tw)) in enumerate(zip(self.done_surfs, self.todo_surfs)):
if i <= self.last_idx:
self.cache.blit(dsurf, (dx, 0))
else:
self.cache.blit(tsurf, (dx, 0))
dx += dw
self.dirty = False
screen.blit(self.cache, (x, y))
def parse_lrc_line(lrc_line: str):
"""
示例: "[00:12.34]我[00:12.80]爱[00:13.20]你"
返回 ("我爱你", [(start_ms, dur_ms), ...])
"""
pattern = r'\[(\d{2}):(\d{2})\.(\d{2})\]'
matches = list(re.finditer(pattern, lrc_line))
chars, starts = [], []
for m in matches:
mm, ss, cs = map(int, m.groups())
starts.append(mm*60000 + ss*1000 + cs*10)
chars.append(lrc_line[m.end()])
# 计算持续时间
durs = []
for i in range(len(starts)):
if i < len(starts)-1:
durs.append(starts[i+1] - starts[i])
else:
durs.append(500) # 最后一字默认 500 ms
return ''.join(chars), list(zip(starts, durs))
# ---------------- demo ----------------
pygame.init()
screen = pygame.display.set_mode((800, 200))
font = pygame.freetype.Font("simsun.ttc", 48)
clock = pygame.time.Clock()
# 假设只演示一行
text, timing = parse_lrc_line("[00:01.00]我[00:01.50]爱[00:02.00]你[00:02.50]中[00:03.00]国")
line = KaraokeLine(text, timing, font)
# 模拟播放
START_TICK = pygame.time.get_ticks()
running = True
while running:
for e in pygame.event.get():
if e.type == pygame.QUIT: running = False
now = pygame.time.get_ticks() - START_TICK
line.update(now)
screen.fill((30,30,30))
line.draw(screen, 100, 70)
pygame.display.flip()
clock.tick(60)
亮点
- 预渲染 + 脏矩形:只在字级变更时重拼一行,其余帧直接 blit 缓存,60 FPS 稳。
- 时间解析用正则一次扫完,面试写起来快,且能处理 10 ms 级精度。
- 使用 freetype 取 metrics,避免 Pygame 默认 font 对齐误差。
- 代码量小,却覆盖了“解析→同步→渲染→优化”完整链路,方便在白板 10 分钟内写完。
拓展思考
- 多行滚动:把 KaraokeLine 放到列表里,当第一行最后一个字唱完,整体向上滚动一行;用 pygame.Surface.scroll 或预先渲染整屏 texture。
- 进度拖拽:监听鼠标或触摸,根据 x 坐标反算目标时间,再调用 pygame.mixer.music.play(start=target_sec) 并同步重置所有行的 last_idx。
- 着色样式扩展:渐变遮罩、描边、阴影、每字不同已唱颜色(彩虹流);可用 GPU shader(pygame._sdl2.gpu 或 moderngl)把纹理坐标当时间轴采样。
- 网络合唱:用 MQTT 或 WebRTC 发送“当前时间 + 已唱索引”,对方客户端做 ±40 ms 抖动缓冲,实现异地同步对唱。
- 性能极限:在树莓派 Zero 上测试,单行 40 字、4 行同时滚动,仍保持 60 FPS;若出现瓶颈,可把拼合操作下沉到 Cython 或提前离线生成 atlas 贴图。