### Integrate LrcView and PitchView in KTV Activity Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Demonstrates the full lifecycle management of LrcView and PitchView, including view initialization, lyric data loading, and progress synchronization with a MediaPlayer. ```java public class KtvRoomActivity extends AppCompatActivity { private LrcView lrcView; private PitchView pitchView; private MediaPlayer mediaPlayer; private Handler handler = new Handler(Looper.getMainLooper()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ktv_room); initViews(); loadSong("https://example.com/song.mp3", "https://webdemo.agora.io/ktv/chocolateice.xml"); } private void initViews() { lrcView = findViewById(R.id.lrcView); pitchView = findViewById(R.id.pitchView); // 配置歌词视图 lrcView.setEnableDrag(true); lrcView.setActionListener(new LrcView.OnActionListener() { @Override public void onProgressChanged(long time) { mediaPlayer.seekTo((int) time); } @Override public void onStartTrackingTouch() {} @Override public void onStopTrackingTouch() {} }); // 配置打分回调 pitchView.onActionListener = new PitchView.OnActionListener() { @Override public void onOriginalPitch(float pitch, int totalCount) { // 处理原唱音调 } @Override public void onScore(double score, double cumulativeScore, double totalScore) { // 更新分数显示 } }; } private void loadSong(String audioUrl, String lrcUrl) { // 下载并加载歌词 DownloadManager.getInstance().download(this, lrcUrl, file -> { LrcData lrcData = LrcLoadUtils.parse(file); runOnUiThread(() -> { lrcView.setLrcData(lrcData); pitchView.setLrcData(lrcData); }); }, Throwable::printStackTrace ); // 初始化播放器 mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(audioUrl); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(mp -> { lrcView.setTotalDuration(mp.getDuration()); mp.start(); startProgressUpdate(); }); } catch (Exception e) { e.printStackTrace(); } } private void startProgressUpdate() { handler.post(new Runnable() { @Override public void run() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { long position = mediaPlayer.getCurrentPosition(); lrcView.updateTime(position); pitchView.updateTime(position); handler.postDelayed(this, 50); } } }); } @Override protected void onDestroy() { super.onDestroy(); handler.removeCallbacksAndMessages(null); lrcView.reset(); if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } } } ``` -------------------------------- ### Handle User Interaction Events Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Implement LrcView.OnActionListener to respond to user gestures like dragging the lyrics to seek playback. ```java public class KtvActivity extends AppCompatActivity implements LrcView.OnActionListener { private LrcView lrcView; private MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ktv); lrcView = findViewById(R.id.lrcView); // 设置事件监听器 lrcView.setActionListener(this); } @Override public void onProgressChanged(long time) { // 用户拖动歌词后松手时回调,time 为用户选中的歌词对应的时间戳(毫秒) // 跳转音乐播放进度到对应位置 mediaPlayer.seekTo((int) time); // 更新歌词显示 lrcView.updateTime(time); } @Override public void onStartTrackingTouch() { // 用户开始拖动歌词时回调 // 可以在此暂停歌词自动滚动或显示拖动指示器 Log.d("LrcView", "开始拖动歌词"); } @Override public void onStopTrackingTouch() { // 用户停止拖动歌词时回调 // 可以在此恢复歌词自动滚动 Log.d("LrcView", "停止拖动歌词"); } } ``` -------------------------------- ### Integrate LrcView into Project Source: https://github.com/agoraio-community/lrcview-android/blob/main/lrcview/README.md Add the library module as a dependency in your build.gradle file. ```gradle implementation project(':lrcview') ``` -------------------------------- ### LrcLoadUtils.parse - Parse Lyric Files Source: https://context7.com/agoraio-community/lrcview-android/llms.txt This utility class parses lyric files, supporting standard LRC format and Migu XML format. It automatically detects the file format and uses the appropriate parser, returning a unified LrcData structure. ```APIDOC ## LrcLoadUtils.parse ### Description Parses lyric files, supporting standard LRC and Migu XML formats. Automatically detects file format and returns a unified `LrcData` structure. ### Methods - `parse(File lrcFile)`: Automatically detects file format (LRC or XML) and parses it. - `parse(LrcData.Type type, File lrcFile)`: Parses the file with a specified format. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Auto-detect format parsing LrcData lrcDataAuto = LrcLoadUtils.parse(lrcFile); // Parsing with specified format (e.g., Migu XML) LrcData lrcDataMigu = LrcLoadUtils.parse(LrcData.Type.Migu, lrcFile); // Inspecting parsed data if (lrcDataAuto != null && lrcDataAuto.entrys != null) { for (LrcEntryData entry : lrcDataAuto.entrys) { long startTime = entry.getStartTime(); long endTime = entry.getEndTime(); for (LrcEntryData.Tone tone : entry.tones) { String word = tone.word; long begin = tone.begin; long end = tone.end; int pitch = tone.pitch; long duration = tone.getDuration(); } } } ``` ### Response `LrcData`: A data structure containing parsed lyric information, including entries with start/end times and tones with word, timing, and pitch details. #### Success Response (200) `LrcData` object. #### Response Example ```json { "entrys": [ { "startTime": 0, "endTime": 1000, "tones": [ { "word": "Hello", "begin": 0, "end": 500, "pitch": 10, "duration": 500 }, { "word": "World", "begin": 500, "end": 1000, "pitch": 12, "duration": 500 } ] } ] } ``` ``` -------------------------------- ### DownloadManager - Lyric File Download Manager Source: https://context7.com/agoraio-community/lrcview-android/llms.txt DownloadManager is a singleton utility class for downloading lyric files from the network to local cache. It supports caching to avoid redundant downloads. ```APIDOC ## DownloadManager ### Description A singleton utility class for downloading lyric files from the network to local cache, with support for caching. ### Methods - `getInstance()`: Gets the singleton instance of DownloadManager. - `download(Context context, String url, FileDownloadSuccessCallback successCallback, FileDownloadFailureCallback failureCallback)`: Downloads a lyric file from the given URL. - `clearCache(Context context)`: Clears all cached lyric files. - `clearFile(Context context, String fileName)`: Clears the cache for a specific lyric file. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Download a lyric file DownloadManager.getInstance().download(context, "http://example.com/lyrics.lrc", new DownloadManager.FileDownloadSuccessCallback() { @Override public void onSuccess(File file) { Log.d("Download", "Lyric file downloaded successfully: " + file.getAbsolutePath()); // Parse the lyrics LrcData lrcData = LrcLoadUtils.parse(file); } }, new DownloadManager.FileDownloadFailureCallback() { @Override public void onFailed(Exception exception) { Log.e("Download", "Lyric file download failed", exception); } } ); // Clear all cache boolean clearAllSuccess = DownloadManager.getInstance().clearCache(context); Log.d("Cache", "Clear all cache result: " + clearAllSuccess); // Clear a specific file cache boolean clearFileSuccess = DownloadManager.getInstance().clearFile(context, "lyrics.lrc"); Log.d("Cache", "Clear file cache result: " + clearFileSuccess); ``` ### Response - `download()`: Returns void, callbacks handle success/failure. - `clearCache()`: Returns `boolean` indicating success or failure. - `clearFile()`: Returns `boolean` indicating success or failure. #### Success Response (200) Callbacks provide details on success or failure. #### Response Example None ``` -------------------------------- ### Include LrcView Module in settings.gradle Source: https://github.com/agoraio-community/lrcview-android/blob/main/README.md Add the LrcView module to your project's settings.gradle file to make it available. ```gradle include ':lrcview' ``` -------------------------------- ### Manage Lyric Downloads with DownloadManager Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Download lyric files with built-in caching support and clear local cache when necessary. ```java public class LrcDownloadExample { // 下载歌词文件 public void downloadLrc(Context context, String url) { DownloadManager.getInstance().download(context, url, new DownloadManager.FileDownloadSuccessCallback() { @Override public void onSuccess(File file) { // 下载成功,file 为本地缓存文件 Log.d("Download", "歌词文件下载成功: " + file.getAbsolutePath()); // 解析歌词 LrcData lrcData = LrcLoadUtils.parse(file); } }, new DownloadManager.FileDownloadFailureCallback() { @Override public void onFailed(Exception exception) { // 下载失败 Log.e("Download", "歌词文件下载失败", exception); } } ); } // 清除所有缓存 public void clearAllCache(Context context) { boolean success = DownloadManager.getInstance().clearCache(context); Log.d("Cache", "清除缓存结果: " + success); } // 清除单个文件缓存 public void clearFileCache(Context context, String fileName) { boolean success = DownloadManager.getInstance().clearFile(context, fileName); Log.d("Cache", "清除文件缓存结果: " + success); } } ``` -------------------------------- ### Initialize LrcView in Activity Source: https://github.com/agoraio-community/lrcview-android/blob/main/README.md Declare and find the LrcView instance within your Activity's onCreate method. ```java public class LiveActivity extends RtcBaseActivity { private LrcView mLrcView; @Override protected void onCreate(Bundle savedInstanceState) { ... mLrcView = findViewById(R.id.lrc_view); ... } } ``` -------------------------------- ### LrcView Integration and XML Usage Source: https://github.com/agoraio-community/lrcview-android/blob/main/lrcview/README.md Instructions on how to include the LrcView library in your Android project and configure it using XML attributes. ```APIDOC ## LrcView Integration and XML Usage ### Description This section details how to add the LrcView library to your Android project and customize its appearance and behavior through XML attributes. ### Gradle Dependency ```gradle implementation project(':lrcview') ``` ### XML Usage ```xml ``` ### XML Attributes | Attribute Name | Description | Corresponding Method | |-----------------------|-------------------------------------|----------------------| | `lrcCurrentTextColor` | Highlighted lyric text color | `setCurrentColor` | | `lrcNormalTextColor` | Normal lyric text color | `setNormalColor` | | `lrcTextSize` | Highlighted lyric text size | `setCurrentTextSize` | | `lrcNormalTextSize` | Normal lyric text size | `setNormalTextSize` | | `lrcLabel` | Default text when no lyrics are found | `setLabel` | | `lrcTextGravity` | Lyric text alignment | N/A | | `lrcDividerHeight` | Spacing between lyric lines | N/A | ``` -------------------------------- ### Load Lyrics Data Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Parse lyrics files using LrcLoadUtils and apply the resulting LrcData to the LrcView instance. ```java // 从 URL 下载并加载歌词 public class MainActivity extends AppCompatActivity { private LrcView lrcView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lrcView = findViewById(R.id.lrcView); // 从网络下载歌词文件并解析 String lrcUrl = "https://webdemo.agora.io/ktv/chocolateice.xml"; DownloadManager.getInstance().download(this, lrcUrl, file -> { // 解析歌词文件(自动识别 LRC 或 XML 格式) LrcData lrcData = LrcLoadUtils.parse(file); // 设置歌词数据到视图 lrcView.setLrcData(lrcData); }, error -> { error.printStackTrace(); } ); } } ``` -------------------------------- ### Add PitchView to Layout Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Include the PitchView in your XML layout file. Customize text colors and initial score using attributes. ```xml ``` -------------------------------- ### Update Lyrics Progress Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Synchronize the lyrics display with the media player's current position using a periodic update loop. ```java public class KtvActivity extends AppCompatActivity { private LrcView lrcView; private MediaPlayer mediaPlayer; private Handler handler = new Handler(Looper.getMainLooper()); private Runnable updateRunnable = new Runnable() { @Override public void run() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { // 获取当前播放位置(毫秒) long currentPosition = mediaPlayer.getCurrentPosition(); // 更新歌词显示进度 lrcView.updateTime(currentPosition); // 每 50ms 更新一次,保证流畅的逐字高亮效果 handler.postDelayed(this, 50); } } }; private void startPlaying() { mediaPlayer.start(); handler.post(updateRunnable); } private void stopPlaying() { handler.removeCallbacks(updateRunnable); mediaPlayer.pause(); } } ``` -------------------------------- ### Core LrcView API Methods Source: https://github.com/agoraio-community/lrcview-android/blob/main/README.md Configuration and control methods for the LrcView component. ```APIDOC ## Core LrcView API Methods ### Methods - **setActionListener(OnActionListener listener)**: Subscribes to callback events. - **setEnableDrag(boolean enable)**: Enables or disables lyric dragging. - **setTotalDuration(long duration)**: Sets total song duration in milliseconds. - **setNormalColor(int color)**: Sets color for non-active lyrics. - **setCurrentColor(int color)**: Sets color for the current active lyric. - **setNormalTextSize(float size)**: Sets text size for non-active lyrics. - **setCurrentTextSize(float size)**: Sets text size for the current active lyric. - **setLabel(String label)**: Sets text displayed when no lyrics are available. - **setLrcData(Object data)**: Manually sets lyric data. - **reset()**: Resets internal state and clears loaded lyrics. - **loadLrc(String mainLrcText, String secondLrcText)**: Loads local LRC files (supports bilingual). - **onLoadLrcCompleted()**: Callback for completion of lyric loading. - **updateTime(long time)**: Updates lyric progress based on playback time (ms). - **hasLrc()**: Returns true if lyrics are valid, false otherwise. ``` -------------------------------- ### Configure Lyric Dragging in LrcView Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Use setEnableDrag to toggle whether users can manually adjust playback progress by dragging the lyrics. ```java public class KtvActivity extends AppCompatActivity { private LrcView lrcView; private boolean isHost; private void initLrcView() { lrcView = findViewById(R.id.lrcView); // 只有主播可以拖动歌词调整进度,观众禁用拖动 if (isHost) { lrcView.setEnableDrag(true); } else { lrcView.setEnableDrag(false); } } } ``` -------------------------------- ### OnActionListener Scoring Callbacks Source: https://github.com/agoraio-community/lrcview-android/blob/main/README.md Interface for receiving pitch and scoring updates during song playback. ```APIDOC ## OnActionListener Scoring Callbacks ### Description Interface to receive real-time pitch data and sentence-level scoring updates for karaoke functionality. ### Methods - **onOriginalPitch(double pitch, int totalCount)**: Callback for raw reference pitch values per tone. - **onScore(double score, double cumulativeScore, double totalScore)**: Callback for sentence-level scores (40-100 range) and cumulative progress. ### Note When score callbacks are enabled, the drag functionality of the LrcView is disabled. ``` -------------------------------- ### Parse Lyric Files with LrcLoadUtils Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Parse LRC or XML files into LrcData structures, either via auto-detection or explicit type specification. ```java public class LrcParseExample { // 自动识别格式解析 public LrcData parseAutoDetect(File lrcFile) { // 自动检测文件格式(LRC 或 XML)并解析 return LrcLoadUtils.parse(lrcFile); } // 指定格式解析 public LrcData parseWithType(File lrcFile, LrcData.Type type) { // 明确指定格式解析 // LrcData.Type.Default - 标准 LRC 格式 // LrcData.Type.Migu - 咪咕 XML 格式 return LrcLoadUtils.parse(type, lrcFile); } // 解析结果数据结构示例 public void inspectLrcData(LrcData lrcData) { if (lrcData != null && lrcData.entrys != null) { for (LrcEntryData entry : lrcData.entrys) { // 获取该行歌词的开始时间 long startTime = entry.getStartTime(); // 获取该行歌词的结束时间 long endTime = entry.getEndTime(); // 遍历每个字/音调 for (LrcEntryData.Tone tone : entry.tones) { String word = tone.word; // 歌词文字 long begin = tone.begin; // 开始时间(毫秒) long end = tone.end; // 结束时间(毫秒) int pitch = tone.pitch; // 音调值(用于打分) long duration = tone.getDuration(); // 持续时间 } } } } } ``` -------------------------------- ### Lyric Style Customization Source: https://context7.com/agoraio-community/lrcview-android/llms.txt LrcView offers methods to dynamically customize the appearance of lyrics at runtime, including text color, size, and default label text. These changes are reflected immediately. ```APIDOC ## Lyric Style Customization ### Description Dynamically customize the display style of lyrics at runtime, including colors, sizes, and default label text. ### Methods - `setCurrentColor(int color)`: Sets the color for the current line (highlighted) lyrics. - `setNormalColor(int color)`: Sets the color for non-current line lyrics. - `setCurrentTextSize(float size)`: Sets the font size for the current line lyrics in pixels. - `setNormalTextSize(float size)`: Sets the font size for non-current line lyrics in pixels. - `setLabel(String label)`: Sets the default text to display when no lyrics are available. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Set current line lyric color to red lrcView.setCurrentColor(Color.parseColor("#FF619F")); // Set normal line lyric color to white lrcView.setNormalColor(Color.parseColor("#FFFFFF")); // Set current line text size to 26sp lrcView.setCurrentTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 26, getResources().getDisplayMetrics())); // Set normal line text size to 16sp lrcView.setNormalTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); // Set label for no lyrics lrcView.setLabel("暂无歌词"); ``` ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Configure LrcView in XML Source: https://github.com/agoraio-community/lrcview-android/blob/main/lrcview/README.md Define the LrcView component in your layout XML with custom attributes for text styling and spacing. ```xml ``` -------------------------------- ### LrcView Main API Source: https://github.com/agoraio-community/lrcview-android/blob/main/lrcview/README.md Overview of the primary methods available in the LrcView component for controlling its functionality. ```APIDOC ## LrcView Main API ### Description This section outlines the key API methods provided by the LrcView component to manage lyric loading, playback progress, and user interactions. ### API Methods | Method Name | Description | |--------------------|---------------------------------------------------| | `setActionListener`| Binds an event listener for runtime events. | | `setTotalDuration` | Sets the total duration of the music in milliseconds. | | `loadLrc` | Loads a local lyric file. | | `setEnableDrag` | Enables or disables seeking by dragging lyrics. | | `updateTime` | Updates the current playback time in milliseconds. | | `hasLrc` | Checks if a lyric file is loaded. | | `reset` | Resets the internal state and clears loaded lyrics. | ### Usage Flow ![Usage Flow](./uml.png) ``` -------------------------------- ### Implement OnActionListener for Scoring Callbacks Source: https://github.com/agoraio-community/lrcview-android/blob/main/README.md Implement this interface to receive callbacks for original pitch values or built-in scoring. The built-in scoring disables drag functionality when enabled. ```java public interface OnActionListener { /** 咪咕歌词原始参考pitch值回调, 用于开发者自行实现打分逻辑. 歌词每个tone回调一次 * pitch: 当前tone的pitch值 * totalCount: 整个xml的tone个数, 用于开发者方便自己在app层计算平均分. */ void onOriginalPitch(double pitch, int totalCount); /** paas组件内置的打分回调, 每句歌词结束的时候提供回调(句指xml中的sentence节点), 并提供totalScore参考值用于按照百分比方式显示分数 * score: 这次回调的分数 40-100之间 * cumulativeScore: 累计的分数 初始分累计到当前的分数 * total: 总分 = 初始分(默认值0分) + xml中sentence的个数 * 100 * 当开启分数回调后, 可拖动功能失效 */ void onScore(double score, double cumulativeScore, double totalScore); } ``` -------------------------------- ### Configure LRCView Scoring and Drag Behavior in XML Source: https://github.com/agoraio-community/lrcview-android/blob/main/README.md Set the initial score, enable or disable drag functionality, and enable scoring callbacks using these XML attributes. ```xml ``` -------------------------------- ### Customize LrcView Visual Styles Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Modify colors, text sizes, and default labels at runtime. Changes take effect immediately upon calling these methods. ```java public class KtvActivity extends AppCompatActivity { private LrcView lrcView; private void customizeLrcStyle() { lrcView = findViewById(R.id.lrcView); // 设置当前行(高亮)歌词颜色 lrcView.setCurrentColor(Color.parseColor("#FF619F")); // 设置非当前行歌词颜色 lrcView.setNormalColor(Color.parseColor("#FFFFFF")); // 设置当前行歌词字体大小(像素) lrcView.setCurrentTextSize(TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 26, getResources().getDisplayMetrics())); // 设置非当前行歌词字体大小(像素) lrcView.setNormalTextSize(TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); // 设置无歌词时显示的默认文字 lrcView.setLabel("暂无歌词"); } } ``` -------------------------------- ### KTV Scoring Activity Integration Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Integrate PitchView into an Android Activity for KTV scoring. This involves setting up listeners, loading lyrics, and updating the view with playback progress and microphone pitch. ```java public class KtvScoringActivity extends AppCompatActivity implements PitchView.OnActionListener { private PitchView pitchView; private LrcView lrcView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ktv_scoring); pitchView = findViewById(R.id.pitchView); lrcView = findViewById(R.id.lrcView); // 设置打分回调监听器 pitchView.onActionListener = this; // 加载歌词 loadLyrics(); } private void loadLyrics() { String lrcUrl = "https://webdemo.agora.io/ktv/chocolateice.xml"; DownloadManager.getInstance().download(this, lrcUrl, file -> { LrcData lrcData = LrcLoadUtils.parse(file); // 同时设置给歌词视图和音调视图 lrcView.setLrcData(lrcData); pitchView.setLrcData(lrcData); }, Throwable::printStackTrace ); } // 在音乐播放进度回调中调用 private void onPlaybackProgress(long currentTimeMs) { // 更新歌词显示 lrcView.updateTime(currentTimeMs); // 更新音调视图和打分计算 pitchView.updateTime(currentTimeMs); } // 在麦克风音频回调中调用,pitch 为检测到的音调频率(Hz) private void onMicrophonePitch(float pitchHz) { // 更新用户音调,触发打分计算 pitchView.updateLocalPitch(pitchHz); } @Override public void onOriginalPitch(float pitch, int totalCount) { // 原唱音调回调,每个歌词音调触发一次 // pitch: 当前音调的参考值 // totalCount: 歌词中总音调数量,可用于计算平均分 Log.d("Pitch", "原唱音调: " + pitch + ", 总数: " + totalCount); } @Override public void onScore(double score, double cumulativeScore, double totalScore) { // 打分回调,每句歌词结束时触发 // score: 本句得分 (0-100) // cumulativeScore: 累计得分 // totalScore: 歌曲总分 Log.d("Score", String.format("本句: %.1f, 累计: %.1f, 总分: %.1f", score, cumulativeScore, totalScore)); // 更新 UI 显示分数 runOnUiThread(() -> { // 显示百分比分数 int percent = (int) (cumulativeScore / totalScore * 100); scoreTextView.setText(percent + "分"); }); } } ``` -------------------------------- ### Set Total Duration Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Define the total duration of the audio track to ensure accurate lyrics timing for the final segments. ```java public class KtvActivity extends AppCompatActivity { private LrcView lrcView; private MediaPlayer mediaPlayer; private void initPlayer(String audioPath, String lrcPath) { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(audioPath); mediaPlayer.prepare(); // 获取音频总时长并设置给歌词视图 long duration = mediaPlayer.getDuration(); lrcView.setTotalDuration(duration); // 加载歌词 LrcData lrcData = LrcLoadUtils.parse(new File(lrcPath)); lrcView.setLrcData(lrcData); } } ``` -------------------------------- ### Configure LrcView in XML Layout Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Add the LrcView component to your Android layout file with custom styling for text colors, sizes, and interaction settings. ```xml ``` -------------------------------- ### reset - Reset Lyric State Source: https://context7.com/agoraio-community/lrcview-android/llms.txt This method clears the currently loaded lyrics and resets all internal states of the LrcView. It's typically called when switching songs or exiting playback. ```APIDOC ## reset ### Description Clears the currently loaded lyrics and resets all internal states of the LrcView. ### Method `reset()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Resetting the lyric view state before loading new lyrics lrcView.reset(); // Resetting when the activity is destroyed @Override protected void onDestroy() { super.onDestroy(); lrcView.reset(); } ``` ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### LrcView XML Layout Customization Source: https://github.com/agoraio-community/lrcview-android/blob/main/README.md Define and customize the LrcView in your Activity's layout XML. Attributes control text colors, spacing, alignment, and default labels. ```xml ``` -------------------------------- ### Reset LrcView State Source: https://context7.com/agoraio-community/lrcview-android/llms.txt Clear lyric data and internal states when switching songs or destroying the view. ```java public class KtvActivity extends AppCompatActivity { private LrcView lrcView; private void switchSong(String newLrcUrl) { // 重置歌词视图状态 lrcView.reset(); // 加载新歌词 DownloadManager.getInstance().download(this, newLrcUrl, file -> { LrcData lrcData = LrcLoadUtils.parse(file); lrcView.setLrcData(lrcData); }, Throwable::printStackTrace ); } @Override protected void onDestroy() { super.onDestroy(); // 退出时重置 lrcView.reset(); } } ``` -------------------------------- ### setEnableDrag - Control Lyric Dragging Source: https://context7.com/agoraio-community/lrcview-android/llms.txt This method controls whether the user can drag the lyrics to adjust the playback progress. It's useful for scenarios like a pure display mode where dragging should be disabled. ```APIDOC ## setEnableDrag ### Description Controls whether the user can drag the lyrics to adjust playback progress. ### Method `setEnableDrag(boolean enable)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java lrcView.setEnableDrag(true); // or lrcView.setEnableDrag(false); ``` ### Response None #### Success Response (200) None #### Response Example None ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.