使用¶
使用本库非常简单:构造歌词数据,将其传给 KaraokeLyricsView 即可。
构造数据¶
虽然你可以手动构造歌词数据,我们仍然推荐使用我们的 lyrics-core 来解析各类文件。
val lyrics = SyncedLyrics(
lines = listOf(
KaraokeLine(
start = 0,
end = 700,
syllables = listOf(
KaraokeSyllable("你", 0, 300),
KaraokeSyllable("好", 300, 700)
),
// ... 其他参数如 translation, isAccompaniment, alignment
),
// ...
)
)
传递给 Composable¶
将构造好的歌词数据传给 KaraokeLyricsView。下面是与播放器配合的典型用法:
@Composable
fun PlayerScreen(player: Player) {
// 1. 获取当前播放位置(作为 State 或值提供者)
// 注意:KaraokeLyricsView 接受一个 lambda () -> Int 来获取位置
// 以避免直接读取 State 导致这层 Composable 过度重组。
val currentPosition = { player.currentPosition.toInt() }
// 2. Remember list state
val listState = rememberLazyListState()
KaraokeLyricsView(
listState = listState,
lyrics = lyrics,
currentPosition = currentPosition,
onLineClicked = { line -> player.seekTo(line.start.toLong()) },
onLinePressed = { line -> /* 处理长按 */ },
modifier = Modifier.fillMaxWidth()
)
}
根据你的设计调整 modifier、normalLineTextStyle、accompanimentLineTextStyle 等参数。
预热(可选)¶
为了避免首次渲染时因从磁盘加载字体和生成字形(SDF Glyph)产生的卡顿(Jank),你可以预热 NativeTextEngine 和 SdfAtlasManager。
这在处理大字体文件或复杂脚本(如 CJK 中日韩字符)时特别有用。
// 1. 创建并初始化 engine 和 atlas manager
// 你可能需要在更高层级的 State Holder 或 remember 中进行此操作
val nativeEngine = remember { NativeTextEngine() }
val sharedAtlasManager = rememberSdfAtlasManager(2048, 2048)
val platformContext = getPlatformContext()
val fontBytes = rememberFontResourceBytes(Res.font.my_font) // 或者你的字体加载逻辑
// 2. 初始化 engine(确保在使用前运行)
LaunchedEffect(nativeEngine, fontBytes) {
nativeEngine.init(2048, 2048)
if (fontBytes != null) {
nativeEngine.loadFont(fontBytes)
}
// 如果需要,加载系统回退字体
val fallbacks = getSystemFallbackFontBytes(platformContext)
fallbacks.forEach { nativeEngine.loadFallbackFont(it) }
}
// 3. (可选) 预热 ASCII 字符
val fontSize = with(LocalDensity.current) { textStyle.fontSize.toPx() }
val fontWeight = textStyle.fontWeight?.weight?.toFloat() ?: 400f
LaunchedEffect(Unit) {
warmupAscii(
nativeEngine,
sharedAtlasManager,
fontSize,
fontWeight
)
}
// 4. 将它们传递给 KaraokeLyricsView
KaraokeLyricsView(
lyrics = lyrics,
// ...
sharedAtlasManager = sharedAtlasManager,
sharedNativeEngine = nativeEngine // 传递预热后的 engine
)
通过共享 engine 和 atlas manager,你可以确保预热期间生成的字形被歌词视图复用。
[!NOTE] 如果你不共享
nativeEngine,视图将创建自己的实例,从而使预热失效。
说明¶
- 有条件时优先使用
lyrics-core来生成歌词数据,以获得更准确的时序和更丰富的元数据。 - 示例中时间单位为毫秒(ms),请确保数据时序一致。
更多格式解析和辅助工具请查看 lyrics-core。
Use¶
Use this library is simple. Construct the data, pass it to the KaraokeLyricsView, and done.
Construct teh data¶
Though you can construct the lyrics data manually, we still recommend you to use our lyrics-core