android studio 显示lrc歌词文件
时间: 2023-11-20 15:59:11 浏览: 194
要在Android Studio中显示LRC歌词文件,可以按照以下步骤进行操作:
1.在布局文件中添加一个TextView,用于显示歌词。
2.在Java代码中读取LRC文件并将其解析为Map,其中键为时间戳,值为歌词文本。
3.在MediaPlayer的OnPreparedListener中启动一个线程,该线程将定期更新TextView以显示当前播放时间的歌词。
下面是一个简单的示例代码,可以帮助你实现这个功能:
```java
// 在布局文件中添加一个TextView,用于显示歌词
TextView lrcTextView = findViewById(R.id.lrcTextView);
// 在Java代码中读取LRC文件并将其解析为Map
Map<Long, String> lrcMap = new HashMap<>();
try {
BufferedReader br = new BufferedReader(new FileReader(lrcFile));
String line;
while ((line = br.readLine()) ! null) {
Matcher matcher = Pattern.compile("\\[(\\d{2}):(\\d{2})\\.(\\d{2})\\](.*)").matcher(line);
if (matcher.find()) {
long time = Long.parseLong(matcher.group(1)) * 60 * 1000
+ Long.parseLong(matcher.group(2)) * 1000
+ Long.parseLong(matcher.group(3)) * 10;
String text = matcher.group(4);
lrcMap.put(time, text);
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
// 在MediaPlayer的OnPreparedListener中启动一个线程,该线程将定期更新TextView以显示当前播放时间的歌词
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
new Thread(new Runnable() {
@Override
public void run() {
while (mediaPlayer.isPlaying()) {
long time = mediaPlayer.getCurrentPosition();
if (lrcMap.containsKey(time)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
lrcTextView.setText(lrcMap.get(time));
}
});
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
// 播放音乐
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)