### Minimal KRC Parsing Example and Output Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/kugou-krc A minimal example demonstrating parsing a short KRC string and accessing the content and start times of the first syllable. ```kotlin val krc = """ [3463,720]<0,352,0>How <352,368,0>long [4527,1352]<0,207,0>Can <207,225,0>we <432,328,0>stay <760,592,0>awake """.trimIndent() val lyrics = KugouKrcParser.parse(krc) println(lyrics.lines.size) // 2 val first = lyrics.lines[0] as KaraokeLine.MainKaraokeLine println(first.syllables[0].content) // "How " println(first.syllables[0].start) // 3463 (3463 + 0) println(first.syllables[1].content) // "long" println(first.syllables[1].start) // 3815 (3463 + 352) ``` -------------------------------- ### Kugou KRC Line and Word Timing Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/kugou-krc Illustrates the format for line and word timing in KRC files, where each word has an offset and duration relative to the line start. ```text [lineStartMs,lineDurationMs]wordtext ``` ```text [3463,720]<0,352,0>How <352,368,0>long [4527,1352]<0,207,0>Can <207,225,0>we <432,328,0>stay <760,592,0>awake ``` -------------------------------- ### TTMLParser Usage Examples Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/ttml Provides examples of how to instantiate and use the TTMLParser, both with and without a fallback phonetic provider. ```kotlin // No phonetic provider val parser = TTMLParser() val lyrics = parser.parse(ttmlContent) // With a fallback phonetic provider val parserWithPhonetics = TTMLParser(fallbackPhoneticProvider = myProvider) val lyrics = parserWithPhonetics.parse(ttmlContent) ``` -------------------------------- ### Lyricify Syllable Notation Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/lyricify-syllable Demonstrates the basic syllable notation with start and duration in milliseconds. ```text Hello(12340,200) World(12540,300) ``` -------------------------------- ### Full LRC Parse Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/lrc Demonstrates parsing a complete LRC string into a structured lyrics object. Shows how to access the title, the number of lines, and details of individual synchronized lines including content, translation, and start time. ```kotlin val lrcContent = """ [ti:Starlight] [ar:Example Artist] [al:Demo Album] [00:10.00]Under the open sky [00:10.00]在开阔的天空下 [00:15.50]I see the stars align [00:21.00]And fade into the night """.trimIndent() val lyrics = EnhancedLrcParser.parse(lrcContent) println(lyrics.title) // Starlight println(lyrics.lines.size) // 3 val first = lyrics.lines[0] as SyncedLine println(first.content) // Under the open sky println(first.translation) // 在开阔的天空下 println(first.start) // 10000 ``` -------------------------------- ### Line-Level Phonetic Provider Example (Pinyin) Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/phonetic-provider Example implementation of PhoneticProvider for line-level phonetic romanization, specifically for Mandarin pinyin. It delegates the conversion to an external library. ```kotlin class PinyinProvider : PhoneticProvider { override val phoneticLevel: PhoneticLevel = PhoneticLevel.LINE override fun getPhonetic(string: String): String { // Delegate to your chosen romanisation library. return convertToPinyin(string) } } ``` -------------------------------- ### Syllable-Level Phonetic Provider Example (Romaji) Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/phonetic-provider Example implementation of PhoneticProvider for syllable-level phonetic romanization, specifically for Japanese romaji. It delegates the conversion to an external library. ```kotlin class RomajiProvider : PhoneticProvider { override val phoneticLevel: PhoneticLevel = PhoneticLevel.SYLLABLE override fun getPhonetic(string: String): String { // Called once per KaraokeSyllable.content return convertToRomaji(string) } } ``` -------------------------------- ### Full Lyricify Syllable Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/lyricify-syllable Illustrates a complete example with attribute codes for main vocals and accompaniments. ```text [4]I (0,214)promise (214,345)that (559,185)you'll (744,154)never (898,334)find (1232,202)another (1434,470)like (1904,363)me(2267,658) [2]我(0,214)保证(214,345)你(559,185)永远(744,154)找不到(898,334)另一个(1232,202)像我(1434,470)这样(1904,363)的(2267,658) [8]Background (800,200)vocals(1000,300) ``` -------------------------------- ### Full LrcExporter Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/lrc-exporter Provides a complete example of creating a SyncedLyrics object and exporting it to LRC format, including ID3 tags and translations. ```kotlin import com.mocharealm.accompanist.lyrics.core.exporter.LrcExporter import com.mocharealm.accompanist.lyrics.core.model.Artist import com.mocharealm.accompanist.lyrics.core.model.SyncedLyrics import com.mocharealm.accompanist.lyrics.core.model.synced.SyncedLine val lyrics = SyncedLyrics( title = "Song Title", artists = listOf(Artist(name = "Artist Name")), lines = listOf( SyncedLine( content = "First line of lyrics", translation = "Translation of first line", start = 12_340, end = 23_450 ), SyncedLine( content = "Second line of lyrics", translation = null, start = 23_450, end = 34_560 ) ) ) val lrcString = LrcExporter.export(lyrics) println(lrcString) ``` -------------------------------- ### Minimal Custom ILyricsParser Implementation Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/ilyrics-parser A basic example of implementing ILyricsParser, showing how to provide canParse and one parse overload. ```kotlin class MyParser : ILyricsParser { override fun canParse(content: String): Boolean = content.startsWith("#MY_FORMAT") override fun parse(content: String): SyncedLyrics { // parse and return return SyncedLyrics(lines = emptyList()) } } ``` -------------------------------- ### Implement parse Method for String Content Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/custom-parser Implement the parse(content: String) overload if your format requires processing the raw string. This example parses lines starting with a timestamp and separated by a pipe. ```kotlin override fun parse(content: String): SyncedLyrics { val lines = content.lines() .filter { it.isNotBlank() && !it.startsWith("##") } .mapIndexedNotNull { _, line -> val parts = line.split("|") if (parts.size < 2) return@mapIndexedNotNull null val startMs = parts[0].toLongOrNull()?.toInt() ?: return@mapIndexedNotNull null val text = parts[1] SyncedLine( content = text, translation = null, start = startMs, end = startMs + 3000 // placeholder end time ) } return SyncedLyrics(lines = lines) } ``` -------------------------------- ### Example KaraokeLine Output Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/enhanced-lrc-exporter Demonstrates the output format for a KaraokeLine, showing line-level and syllable-level timestamps. ```plaintext [00:12.340]<00:12.340>Hel<00:12.600>lo <00:12.900>World<00:13.200> ``` -------------------------------- ### Custom Exporter Implementation (Basic) Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/ilyrics-exporter An example of implementing ILyricsExporter as an object. This basic structure iterates through lyrics lines to build a custom format. ```kotlin object MyExporter : ILyricsExporter { override fun export(lyrics: SyncedLyrics): String { val sb = StringBuilder() for (line in lyrics.lines) { // build your format } return sb.toString() } } ``` -------------------------------- ### KaraokeSyllable progress Usage Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-syllable Demonstrates how to use the `progress` method to animate syllable highlighting. It drives a horizontal clip effect on a Canvas to reveal the syllable content progressively. ```kotlin val positionMs = player.currentPosition.toInt() line.syllables.forEach { syllable -> val progress = syllable.progress(positionMs) // Drive a horizontal clip: reveal `progress * width` pixels of the highlighted layer Canvas(modifier = Modifier.width(textWidth)) { drawText(syllable.content, color = Color.Gray) clipRect(right = size.width * progress) { drawText(syllable.content, color = Color.White) } } } ``` -------------------------------- ### iTunes Translations Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/ttml Demonstrates how out-of-band translations are provided in a block within the section of a TTML file, keyed by itunes:key. ```xml 你好世界 ``` -------------------------------- ### Rendering a Plain Lyrics Line Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line Example of how to render a SyncedLine object, displaying its content and optional translation. ```APIDOC ## Usage Example: Rendering a Plain Lyrics Line ### Description This example demonstrates how to display the content of a `SyncedLine` and its translation if available. ### Code ```kotlin val line: SyncedLine = lyrics.lines.filterIsInstance().first() Text(text = line.content) line.translation?.let { Text(text = it, style = MaterialTheme.typography.bodySmall) } ``` ``` -------------------------------- ### Format Conversion Pipeline Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/overview Shows how to use an exporter in conjunction with a parser to convert between formats. This example reads a TTML file and writes it as a standard LRC file. ```kotlin import com.mocharealm.accompanist.lyrics.core.parser.TTMLParser import com.mocharealm.accompanist.lyrics.core.exporter.LrcExporter val ttmlContent = File("track.ttml").readText() val lyrics = TTMLParser.parse(ttmlContent) // SyncedLyrics val lrc = LrcExporter.export(lyrics) // standard LRC string File("track.lrc").writeText(lrc) ``` -------------------------------- ### Background Vocal Line Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/enhanced-lrc-exporter Shows the format for background vocal lines using the [bg:...] wrapper. ```plaintext [bg:<00:14.000>Back<00:14.300>ground<00:14.600>] ``` -------------------------------- ### iTunes Transliterations Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/ttml Shows how transliterations are embedded within iTunesMetadata in TTML files, with each syllable mapped using spans and itunes:key. ```xml ``` -------------------------------- ### Driving Line Highlights from Media Player Position Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-lyrics Example of how to use `getCurrentFirstHighlightLineIndexByTime` to update UI based on media player's current playback position. ```kotlin // Called on each player position update (e.g. from a ViewModel) val lyrics: SyncedLyrics = parsedLyrics fun onPositionChanged(positionMs: Int) { val index = lyrics.getCurrentFirstHighlightLineIndexByTime(positionMs) // index is safe to use directly as a list index when < lyrics.lines.size if (index < lyrics.lines.size) { highlightLine(lyrics.lines[index]) } } ``` -------------------------------- ### Background Vocal Translation Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/enhanced-lrc-exporter Demonstrates the format for background vocal lines that also include a translation. ```plaintext [bg:<00:14.000>Background vocals<00:14.600>] [bg:<00:14.000>Translation of background<00:14.600>] ``` -------------------------------- ### Hypothetical Custom Lyric Format Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/custom-parser Example of a custom lyric format with a header tag and lines in '|' format. ```text ##MY_FORMAT## 0|Welcome to the show 3200|The lights go down 6800|And the music starts ``` -------------------------------- ### Expected TTML Output from Full Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/ttml-exporter This is the condensed XML output generated by the TTMLExporter for the provided SyncedLyrics object, including multi-voice metadata. ```xml

Lead vocal主唱

Response

``` -------------------------------- ### Example LRC File Content Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/attributes Shows the structure of a sample LRC file, including metadata tags like title, artist, album, offset, and length, followed by timestamped lyric lines. ```lrc [ti:Hello] [ar:Adele] [al:25] [offset:0] [length:295000] [00:25.73]Hello, it's me [00:31.40]I was wondering if after all these years ``` -------------------------------- ### Implement ILyricsExporter with Metadata Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/ilyrics-exporter Example of creating a custom ILyricsExporter that includes title and artist metadata in the exported lyrics. Ensure your format supports these header fields. ```kotlin object MyExporter : ILyricsExporter { override fun export(lyrics: SyncedLyrics): String { val sb = StringBuilder() // Write header block if (lyrics.title.isNotEmpty()) sb.appendLine("[ti:${lyrics.title}]") lyrics.artists?.forEach { artist -> sb.appendLine("[ar:${artist.name}]") } // Write lyric lines … return sb.toString() } } ``` -------------------------------- ### Kugou KRC Background Vocal Line Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/kugou-krc Shows how background vocal lines are indicated using the '[bg:…]' prefix and how they are attached to the preceding main vocal line. ```text [12000,2000]<0,300,0>Main<300,400,0> vocal [bg:<0,300,0>Back<300,400,0>ground] ``` -------------------------------- ### TTML Format Overview Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/ttml An example of the TTML (Timed Text Markup Language) format used by Apple Music, including metadata, agents, and timed text spans. ```xml

Hel lo World 你好世界

``` -------------------------------- ### Get Current Lyric Line Index by Time Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/playback-integration Use `getCurrentFirstHighlightLineIndexByTime` for most cases or `getCurrentAllHighlightLineIndicesByTime` for overlapping/duet tracks. These methods perform a binary search for efficient lookups. ```kotlin val currentIndex = lyrics.getCurrentFirstHighlightLineIndexByTime(currentTimeMs) val activeIndices = lyrics.getCurrentAllHighlightLineIndicesByTime(currentTimeMs) ``` -------------------------------- ### Iterating Through Parsed LRC Lines in Kotlin Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/enhanced-lrc Example of iterating through the parsed lyrics, distinguishing between KaraokeLine.MainKaraokeLine and SyncedLine, and accessing their properties like syllables, translations, and background vocals. ```kotlin val lyrics = EnhancedLrcParser.parse(enhancedLrcContent) for (line in lyrics.lines) { when (line) { is KaraokeLine.MainKaraokeLine -> { println("Karaoke [${line.alignment}] ${line.start}ms–${line.end}ms") // Syllable-level access for (syllable in line.syllables) { println(" ${syllable.start}ms: '${syllable.content}'") } // Optional translation line.translation?.let { println(" → $it") } // Background / accompaniment vocals attached to this line line.accompanimentLines?.forEach { bg -> println(" [BG] ${bg.syllables.joinToString("") { it.content }}") bg.translation?.let { println(" → $it") } } } is SyncedLine -> { println("${line.start}ms: ${line.content}") line.translation?.let { println(" → $it") } } } } ``` -------------------------------- ### Get Current Line by Playback Time Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/quickstart Use `getCurrentFirstHighlightLineIndexByTime` to find the index of the line that should be highlighted at a given playback position. This function performs a binary search and is safe to call frequently. ```kotlin val timeMs: Int = player.currentPositionMs.toInt() val currentIndex: Int = lyrics.getCurrentFirstHighlightLineIndexByTime(timeMs) if (currentIndex < lyrics.lines.size) { println("Now playing line $currentIndex: ${lyrics.lines[currentIndex]}") } ``` -------------------------------- ### Rebuild Line Text from Syllables Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-syllable Extracts the full text content and phonetic representation of a line's syllables. Useful for displaying lyrics or phonetic guides. ```kotlin val line: KaraokeLine = lyrics.lines.filterIsInstance().first() val fullText: String = line.syllables.contentToString() val phonetics: String = line.syllables.phoneticToString() println(fullText) // e.g. "Hello world" println(phonetics) // e.g. "hēllō wörld" ``` -------------------------------- ### Example of a Plain Synced Line in TTML Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/ttml Demonstrates the structure of a TTML

element that represents a plain synced line without timed spans, including an inline x-translation span for Chinese lyrics. ```xml

This is a plain synced line 这是一行歌词

``` -------------------------------- ### Get All Active Lines by Playback Time Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/quickstart For scenarios with multiple simultaneous lines (like duets), use `getCurrentAllHighlightLineIndicesByTime` to retrieve all active line indices at the current playback time. This also uses binary search for efficiency. ```kotlin val activeIndices: List = lyrics.getCurrentAllHighlightLineIndicesByTime(timeMs) activeIndices.forEach { index -> println("Active line $index: ${lyrics.lines[index]}") } ``` -------------------------------- ### Enhanced LRC with Square-Bracket Syllable Timing (Legacy) Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/enhanced-lrc Example of Enhanced LRC format using square brackets for syllable start times. This legacy format is also supported by the parser. ```lrc [00:12.34][00:12.34]Hel[00:12.60]lo [00:12.90]World ``` -------------------------------- ### Enhanced LRC with Angle-Bracket Syllable Timing Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/enhanced-lrc Example of Enhanced LRC format using angle brackets for syllable start times. The line-level timestamp precedes the first syllable's timestamp. ```lrc [00:12.34]<00:12.34>Hel<00:12.60>lo <00:12.90>World<00:13.20> ``` -------------------------------- ### Using AutoParser with Custom Parsers Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/ilyrics-parser Demonstrates how to initialize AutoParser with a list of parsers, including a custom parser, to automatically detect and parse lyrics content. The order in the list determines the parsing priority. ```kotlin val parser = AutoParser( parsers = listOf( MyParser(), // your format checked first TTMLParser(), LyricifySyllableParser, EnhancedLrcParser, KugouKrcParser, ) ) val lyrics = parser.parse(rawContent) ``` -------------------------------- ### Dispatching on KaraokeLine Subtype with 'when' Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-line Demonstrates how to handle different subtypes of KaraokeLine (MainKaraokeLine and AccompanimentKaraokeLine) using a 'when' expression to render them appropriately. ```kotlin when (val line = lyrics.lines[index]) { is KaraokeLine.MainKaraokeLine -> { renderMain(line) line.accompanimentLines?.forEach { renderAccompaniment(it) } } is KaraokeLine.AccompanimentKaraokeLine -> renderAccompaniment(line) else -> {} } ``` -------------------------------- ### Using Built-in and Custom Exporters Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/ilyrics-exporter Demonstrates how to parse raw lyric content into a SyncedLyrics object and then export it using either the built-in LrcExporter or a custom exporter like MyExporter. ```kotlin val lyrics: SyncedLyrics = AutoParser().parse(rawContent) // Built-in exporter — object singleton, call directly val lrcOutput: String = LrcExporter.export(lyrics) // Custom exporter val myOutput: String = MyExporter.export(lyrics) ``` -------------------------------- ### KaraokeSyllable Constructor Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-syllable Constructs a KaraokeSyllable object with content, start and end times, and optional phonetic annotation. The end time must be greater than or equal to the start time. ```APIDOC ## Constructor KaraokeSyllable ### Description Creates a new KaraokeSyllable instance. ### Parameters #### Path Parameters * **content** (String) - Required - The display text of this syllable (e.g. `"hel"`, `"lo"`). * **start** (Int) - Required - Start time in milliseconds. Must be less than or equal to `end`. * **end** (Int) - Required - End time in milliseconds. Must be greater than or equal to `start`; otherwise construction throws `IllegalArgumentException`. * **phonetic** (String?) - Optional, defaults to null - Optional phonetic (romanized) annotation for this syllable. When present, it is used by `phoneticToString()` to build a full phonetic string for the line. ``` -------------------------------- ### KaraokeSyllable Data Class Constructor Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-syllable Defines the structure for a single karaoke syllable, including its content, start and end times in milliseconds, and an optional phonetic annotation. Construction enforces that end time must be greater than or equal to start time. ```kotlin data class KaraokeSyllable( val content: String, val start: Int, val end: Int, val phonetic: String? = null, ) ``` -------------------------------- ### Translation Line Example Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/enhanced-lrc-exporter Illustrates how translation lines are appended with the same line-level timestamp as the primary line. ```plaintext [00:12.340]<00:12.340>Hel<00:12.600>lo <00:12.900>World<00:13.200> [00:12.340]Translation text ``` -------------------------------- ### Basic Exporter Usage Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/overview Demonstrates the single-line calling convention for all three exporters (LrcExporter, EnhancedLrcExporter, TTMLExporter). ```kotlin val lrcString = LrcExporter.export(lyrics) val enhancedLrc = EnhancedLrcExporter.export(lyrics) val ttml = TTMLExporter.export(lyrics) ``` -------------------------------- ### KaraokeLine with Syllable Timestamps Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/enhanced-lrc-exporter Example of a KaraokeLine serialized with inline syllable timestamps, including line-level and per-syllable timing. ```plaintext [mm:ss.xxx]syllable ``` -------------------------------- ### Handling Duets and Overlapping Lines with Media Player Position Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-lyrics Demonstrates using `getCurrentAllHighlightLineIndicesByTime` to highlight multiple lines simultaneously, suitable for duets or background vocals. ```kotlin fun onPositionChanged(positionMs: Int) { val indices = lyrics.getCurrentAllHighlightLineIndicesByTime(positionMs) indices.forEach { i -> highlightLine(lyrics.lines[i]) } } ``` -------------------------------- ### ISyncedLine Interface Definition Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line Defines the minimal interface for lyrics lines, exposing start, end, and duration in milliseconds. ```kotlin interface ISyncedLine { val start: Int val end: Int val duration: Int } ``` -------------------------------- ### Configure AutoParser with PhoneticProvider Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/phonetic-provider Shows how to provide a PhoneticProvider to AutoParser, which will then forward it to the internal TTMLParser. ```kotlin val autoParser = AutoParser(fallbackPhoneticProvider = PinyinProvider()) val lyrics = autoParser.parse(rawContent) ``` -------------------------------- ### Iterate and Process Parsed Lyrics in Kotlin Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/lyricify-syllable Shows how to iterate through the parsed lyrics, distinguishing between main and accompaniment lines, and accessing syllable details. ```kotlin val lyrics = LyricifySyllableParser.parse(content) for (line in lyrics.lines) { when (line) { is KaraokeLine.MainKaraokeLine -> { println("Main [${line.alignment}] ${line.start}ms–${line.end}ms") for (syllable in line.syllables) { println(" ${syllable.start}ms–${syllable.end}ms '${syllable.content}'") } line.accompanimentLines?.forEach { bg -> println(" [BG] ${bg.syllables.joinToString("") { it.content }}") } } is KaraokeLine.AccompanimentKaraokeLine -> { // Reached only when there was no preceding main line println("Standalone BG: ${line.syllables.joinToString("") { it.content }}") } } } ``` -------------------------------- ### KaraokeAlignment Enum Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-line An enum to specify the visual alignment of a karaoke line within a UI layout, supporting Start, End, or Unspecified alignment. ```kotlin enum class KaraokeAlignment { Start, End, Unspecified } ``` -------------------------------- ### Configure TTMLParser with PhoneticProvider Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/phonetic-provider Demonstrates how to pass a PhoneticProvider instance to the TTMLParser constructor as a fallback mechanism. ```kotlin val parser = TTMLParser(fallbackPhoneticProvider = PinyinProvider()) val lyrics = parser.parse(ttmlContent) ``` -------------------------------- ### Convert UncheckedSyncedLine to SyncedLine Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line Converts an UncheckedSyncedLine to a SyncedLine, ensuring that end time is not before start time. Use this when you need to guarantee valid timestamps. ```kotlin fun toSyncedLine(): SyncedLine ``` ```kotlin val unchecked = UncheckedSyncedLine( content = "Verse one", translation = null, start = 500, end = 2000 ) val checked: SyncedLine = unchecked.toSyncedLine() ``` -------------------------------- ### Instantiating TTMLParser with PhoneticProvider Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/phonetic-provider Shows how to pass a PhoneticProvider implementation directly to TTMLParser or AutoParser. ```kotlin // Pass directly to TTMLParser val parser = TTMLParser(fallbackPhoneticProvider = PinyinProvider()) // Or pass to AutoParser, which forwards it to TTMLParser internally val autoParser = AutoParser(fallbackPhoneticProvider = PinyinProvider()) ``` -------------------------------- ### SyncedLine Data Class Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line Represents a validated lyrics line with content, translation, and precise start/end timestamps. Enforces end >= start during construction. ```kotlin data class SyncedLine( val content: String, val translation: String?, override val start: Int, override val end: Int, ) : ISyncedLine { override val duration = end - start // init: requires end >= start } ``` -------------------------------- ### Configure AutoParser with Custom Parser List and PhoneticProvider Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/phonetic-provider Illustrates how to configure AutoParser with a custom list of parsers, ensuring that a TTMLParser with a PhoneticProvider is explicitly included. ```kotlin // Custom parser list — create TTMLParser manually with the provider val autoParser = AutoParser( parsers = listOf( TTMLParser(fallbackPhoneticProvider = PinyinProvider()), LyricifySyllableParser, EnhancedLrcParser, KugouKrcParser ) ) ``` -------------------------------- ### UncheckedSyncedLine Data Class Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line UncheckedSyncedLine is a lenient implementation used during parsing that tolerates end < start by clamping duration to 0. It can be converted to a SyncedLine after validation. ```APIDOC ## UncheckedSyncedLine `UncheckedSyncedLine` is a lenient counterpart to `SyncedLine` used during parsing. It tolerates `end < start` by clamping `duration` to `0` rather than throwing. Call `toSyncedLine()` once the data is validated to obtain a checked `SyncedLine`. ### Properties - **content** (String): The display text of the lyrics line. - **translation** (String?): Optional translation string; `null` when not provided. - **start** (Int): Start time of the line in milliseconds. - **end** (Int): End time of the line in milliseconds. - **duration** (Int): Calculated as `(end - start).takeIf { it >= 0 } ?: 0`. Clamped to 0 if `end < start`. ``` -------------------------------- ### ISyncedLine Interface Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line The ISyncedLine interface defines the minimal contract for all lyrics line types, exposing start time, end time, and duration in milliseconds. ```APIDOC ## ISyncedLine `ISyncedLine` is the common interface implemented by all line types — including [`SyncedLine`](#syncedline), [`UncheckedSyncedLine`](#uncheckedsyncedline), and the [`KaraokeLine`](/api/karaoke-line) hierarchy. ### Properties - **start** (Int): Start time of the line in milliseconds. - **end** (Int): End time of the line in milliseconds. - **duration** (Int): Length of the line in milliseconds. Implementations compute this as `end - start`. ``` -------------------------------- ### Basic LrcExporter Usage Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/lrc-exporter Demonstrates how to use LrcExporter to convert SyncedLyrics to an LRC string and write it to a file. ```kotlin import com.mocharealm.accompanist.lyrics.core.exporter.LrcExporter val lrcString = LrcExporter.export(lyrics) // Write to a file File("track.lrc").writeText(lrcString) ``` -------------------------------- ### PhoneticProvider Interface Definition Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/guides/phonetic-provider Defines the interface for providing phonetic romanization. It includes the phonetic level and a method to get the phonetic string for a given input. ```kotlin interface PhoneticProvider { val phoneticLevel: PhoneticLevel fun getPhonetic(string: String): String } ``` -------------------------------- ### Line-Level RomajiProvider Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/phonetic-provider Implements PhoneticProvider for line-level phonetic conversion to Romaji. Use this when you need phonetic representation for entire lines. Requires a Romaji library. ```kotlin class RomajiProvider : PhoneticProvider { override val phoneticLevel: PhoneticLevel = PhoneticLevel.LINE override fun getPhonetic(string: String): String { return yourRomajiLibrary.toRomaji(string) } } val parser = AutoParser(fallbackPhoneticProvider = RomajiProvider()) ``` -------------------------------- ### Declare Dependency in Version Catalog Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/installation Manage dependencies using a `libs.versions.toml` catalog. Define the version and library coordinates for Accompanist Lyrics Core. ```toml [versions] accompanist-lyrics = "0.4.5" [libraries] accompanist-lyrics-core = { group = "com.mocharealm.accompanist", name = "lyrics-core", version.ref = "accompanist-lyrics" } ``` -------------------------------- ### UncheckedSyncedLine Data Class Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line A lenient lyrics line implementation used during parsing. It tolerates end < start by clamping duration to 0. Use toSyncedLine() for validation. ```kotlin data class UncheckedSyncedLine( val content: String, val translation: String?, override val start: Int, override val end: Int, ) : ISyncedLine { override val duration = (end - start).takeIf { it >= 0 } ?: 0 fun toSyncedLine(): SyncedLine } ``` -------------------------------- ### Multi-singer layout using alignment Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-line Renders lyrics with multiple singers, applying custom horizontal alignments to both main and accompaniment lines based on their KaraokeAlignment. ```kotlin val mainLines = lyrics.lines .filterIsInstance() mainLines.forEach { main -> val mainAlign = when (main.alignment) { KaraokeAlignment.Start -> Alignment.Start KaraokeAlignment.End -> Alignment.End KaraokeAlignment.Unspecified -> Alignment.CenterHorizontally } renderLine(main, mainAlign) main.accompanimentLines?.forEach { acc -> val accAlign = when (acc.alignment) { KaraokeAlignment.Start -> Alignment.Start KaraokeAlignment.End -> Alignment.End KaraokeAlignment.Unspecified -> Alignment.CenterHorizontally } renderLine(acc, accAlign) } } ``` -------------------------------- ### Export Synced Lyrics to Enhanced LRC Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/exporters/enhanced-lrc-exporter Demonstrates how to create a SyncedLyrics object with karaoke details and export it using EnhancedLrcExporter. The output preserves title, artist, main lyrics with syllable timing, translations, and background vocal lines. ```kotlin import com.mocharealm.accompanist.lyrics.core.exporter.EnhancedLrcExporter import com.mocharealm.accompanist.lyrics.core.model.Artist import com.mocharealm.accompanist.lyrics.core.model.SyncedLyrics import com.mocharealm.accompanist.lyrics.core.model.karaoke.KaraokeAlignment import com.mocharealm.accompanist.lyrics.core.model.karaoke.KaraokeLine import com.mocharealm.accompanist.lyrics.core.model.karaoke.KaraokeSyllable val lyrics = SyncedLyrics( title = "Song Title", artists = listOf(Artist(name = "Artist Name")), lines = listOf( KaraokeLine.MainKaraokeLine( syllables = listOf( KaraokeSyllable(content = "Hel", start = 12_340, end = 12_600), KaraokeSyllable(content = "lo ", start = 12_600, end = 12_900), KaraokeSyllable(content = "World", start = 12_900, end = 13_200) ), translation = "你好,世界", alignment = KaraokeAlignment.Unspecified, start = 12_340, end = 13_200, accompanimentLines = listOf( KaraokeLine.AccompanimentKaraokeLine( syllables = listOf( KaraokeSyllable(content = "Back", start = 14_000, end = 14_300), KaraokeSyllable(content = "ground", start = 14_300, end = 14_600) ), translation = null, alignment = KaraokeAlignment.Unspecified, start = 14_000, end = 14_600 ) ) ) ) ) val enhancedLrc = EnhancedLrcExporter.export(lyrics) println(enhancedLrc) ``` ```text [ti:Song Title] [ar:Artist Name] [00:12.340]<00:12.340>Hel<00:12.600>lo <00:12.900>World<00:13.200> [00:12.340]你好,世界 [bg:<00:14.000>Back<00:14.300>ground<00:14.600>] ``` -------------------------------- ### AutoParser Usage for Automatic Format Detection Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/overview Instantiate AutoParser and use its parse method to automatically detect and parse lyrics content. This is the recommended approach for most applications. ```kotlin val autoParser = AutoParser() val lyrics = autoParser.parse(content) // format detected automatically ``` -------------------------------- ### KaraokeLine isFocused() Method Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-line Determines if the current playback position falls within the start and end times of the karaoke line. Useful for applying active visual states. ```kotlin fun isFocused(current: Int): Boolean ``` -------------------------------- ### AccompanimentKaraokeLine Data Class Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/karaoke-line Defines the structure for background or harmony vocal lines in karaoke. It includes syllables, translation, alignment, start and end times, and optional phonetic annotation. ```kotlin data class AccompanimentKaraokeLine( override val syllables: List, override val translation: String?, override val alignment: KaraokeAlignment, override val start: Int, override val end: Int, override val phonetic: String? = null ) : KaraokeLine ``` -------------------------------- ### Use Version Catalog Dependency in KMP Source Set Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/installation Reference the Accompanist Lyrics Core dependency from your version catalog within a Kotlin Multiplatform project's `commonMain` source set. ```kotlin kotlin { sourceSets { commonMain { dependencies { implementation(libs.accompanist.lyrics.core) } } } } ``` -------------------------------- ### UncheckedSyncedLine to SyncedLine Conversion Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line Converts an UncheckedSyncedLine to a SyncedLine, ensuring that the end timestamp is not before the start timestamp. It's recommended to call this method after validating timestamps or within a try-catch block. ```APIDOC ## Method: `toSyncedLine()` ### Description Converts this `UncheckedSyncedLine` to a `SyncedLine`. The resulting `SyncedLine` enforces `end >= start`; call this only after confirming the timestamps are valid, or wrap in a try/catch. ### Signature ```kotlin fun toSyncedLine(): SyncedLine ``` ### Request Example ```kotlin val unchecked = UncheckedSyncedLine( content = "Verse one", translation = null, start = 500, end = 2000 ) val checked: SyncedLine = unchecked.toSyncedLine() ``` ``` -------------------------------- ### SyncedLine Data Class Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-line SyncedLine represents a fully validated, single line of lyrics with millisecond timestamps. It enforces that end time is greater than or equal to start time during construction. ```APIDOC ## SyncedLine `SyncedLine` represents a fully validated, single line of lyrics with millisecond timestamps. The `init` block enforces `end >= start`; construction throws `IllegalArgumentException` if that constraint is violated. ### Constructor parameters - **content** (String, required): The display text of the lyrics line. - **translation** (String?, optional): An optional translation of the line, or `null` if no translation is available. - **start** (Int, required): Start time in milliseconds. Must be less than or equal to `end`. - **end** (Int, required): End time in milliseconds. Must be greater than or equal to `start`; otherwise construction throws `IllegalArgumentException`. ### Properties - **content** (String): The display text of the lyrics line. - **translation** (String?): Optional translation string; `null` when not provided. - **start** (Int): Start time of the line in milliseconds. - **end** (Int): End time of the line in milliseconds. - **duration** (Int): Computed as `end - start`. Always non-negative due to the `init` constraint. ``` -------------------------------- ### Get All Current Highlight Line Indices by Time Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-lyrics Retrieves a sorted list of indices for all lines active at a specific time. Useful for scenarios with overlapping lyrics like duets. ```kotlin fun getCurrentAllHighlightLineIndicesByTime(time: Int): List ``` -------------------------------- ### Use Version Catalog Dependency in build.gradle.kts Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/installation Reference the declared Accompanist Lyrics Core dependency from your version catalog in your module's `build.gradle.kts` file. ```kotlin dependencies { implementation(libs.accompanist.lyrics.core) } ``` -------------------------------- ### Syllable-Level PinyinProvider Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/phonetic-provider Implements PhoneticProvider for syllable-level pinyin conversion. Use this when you need pinyin for individual syllables. Requires a pinyin library. ```kotlin class PinyinProvider : PhoneticProvider { override val phoneticLevel: PhoneticLevel = PhoneticLevel.SYLLABLE override fun getPhonetic(string: String): String { // Convert to pinyin using your preferred library return yourPinyinLibrary.toPinyin(string) } } // Usage val parser = TTMLParser(fallbackPhoneticProvider = PinyinProvider()) ``` -------------------------------- ### Access SyncedLine Data Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/quickstart Iterate through lyrics lines and access common properties like start time, end time, and content. Handle plain or translated lines that do not have syllable data. ```kotlin import com.mocharealm.accompanist.lyrics.core.model.synced.SyncedLine import com.mocharealm.accompanist.lyrics.core.model.karaoke.KaraokeLine for (line in lyrics.lines) { when (line) { is SyncedLine -> { // Plain or translated line — no syllable data println("${line.start}ms – ${line.end}ms: ${line.content}") line.translation?.let { println(" ↳ Translation: $it") } } is KaraokeLine.MainKaraokeLine -> { // Syllable-timed main vocal line val fullText = line.syllables.joinToString("") { it.content } println("${line.start}ms – ${line.end}ms: $fullText") // Individual syllable timestamps for (syllable in line.syllables) { print("${syllable.content}[${syllable.start}–${syllable.end}ms] ") } println() // Optional translation and phonetic annotation line.translation?.let { println(" ↳ Translation: $it") } line.phonetic?.let { println(" ↳ Phonetic: $it") } // Background / accompaniment vocals embedded in the same line line.accompanimentLines?.forEach { val bgText = it.syllables.joinToString("") { it.content } println(" ↳ Background: $bgText") } } is KaraokeLine.AccompanimentKaraokeLine -> { // Stand-alone accompaniment/background vocal line val bgText = line.syllables.joinToString("") { it.content } ``` -------------------------------- ### getCurrentFirstHighlightLineIndexByTime Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/api/synced-lyrics Retrieves the index of the first lyric line that should be highlighted at a given playback time. This method uses binary search for efficient lookups. ```APIDOC ## getCurrentFirstHighlightLineIndexByTime ### Description Returns the index of the first line whose time window `[start, end]` contains the given time. This method is optimized with binary search for performance. ### Method `getCurrentFirstHighlightLineIndexByTime(time: Int): Int` ### Endpoint N/A (Method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **time** (Int) - Required - Current playback position in milliseconds. ### Response #### Success Response (Int) Returns an `Int` representing the index of the first highlightable line. Returns `0` if `lines` is empty, the index of the next upcoming line if `time` falls in a gap, or `lines.size` if `time` is after all lines. #### Response Example ```json { "example": 5 } ``` ``` -------------------------------- ### Basic AutoParser Usage Source: https://mintlify.wiki/6xingyv/accompanist-lyrics-core/parsers/auto-parser Instantiate AutoParser with default settings and call parse to automatically detect and parse lyrics content. Returns a SyncedLyrics object, or an empty SyncedLyrics if no parser recognizes the content. ```kotlin val autoParser = AutoParser() val lyrics = autoParser.parse(content) ```