1. 程式人生 > 其它 >springboot後端LRC歌詞檔案解析

springboot後端LRC歌詞檔案解析

package com.ruoyi.api.yuan;

import com.ruoyi.common.core.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* LRC歌詞檔案解析
*
*/
@RestController
@RequestMapping("/v2/yuan/testLrc")
public class TestLrc extends BaseController {

/**
* 歌詞解析
*
* @param path 歌詞地址
* @return 歌詞資訊list
*/
private List<Map<String, String>> parse(String path) {
//儲存歌詞資訊的容器
ArrayList<Map<String, String>> list = new ArrayList<>();
try {
//字串編碼格式
String encoding = "GBK";
File file = new File(path);
//判斷檔案是否存在
if (file.exists() && file.isFile()) {
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(reader);
//時間標籤正則匹配 例:[02:34.94]
String regex = "\\[(\\d{1,2}):(\\d{1,2}).(\\d{1,2})\\]";
//建立pattern物件
Pattern pattern = Pattern.compile(regex);
//每次讀取一行字串
String lineStr = null;
while ((lineStr = bufferedReader.readLine()) != null) {
Matcher matcher = pattern.matcher(lineStr);
while (matcher.find()) {
//儲存當前時間和文字的容器
Map<String, String> hashMap = new HashMap<>();
//分鐘
String min = matcher.group(1);
//秒
String second = matcher.group(2);
//毫秒
String mill = matcher.group(3);
String time = min + ":" + second + "." + mill;
String text = lineStr.substring(matcher.end());
hashMap.put(time, text);
list.add(hashMap);
}
}
reader.close();
return list;
} else {
System.out.println("找不到指定的檔案" + path);
}
} catch (Exception e) {
System.out.println("讀取檔案出錯");
e.printStackTrace();
}
return null;
}

private void printLrc(List<Map<String, String>> list) {
if (list == null || list.isEmpty()) {
System.out.println("沒有任何歌詞資訊");
} else {
for (Map<String, String> map : list) {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("[" + entry.getKey() + "]" + entry.getValue());
}
}
}
}

public static void main(String[] args) {
// 歌詞檔案路徑
String path = "D:\\a.lrc";
TestLrc lrc = new TestLrc();
List<Map<String, String>> list = lrc.parse(path);
lrc.printLrc(list);
}
}