java歌词分割
程序员文章站
2022-06-21 22:25:53
...
@RequestMapping(value = "selectLyric")
@ResponseBody
public List<Map<String ,String>> selectLyric(Integer mId,HttpServletRequest request) throws IOException {
String encoding = "utf-8";
log.info("进入音乐控制器 的 selectById 方法");
log.info("入参 mId;{}",mId);
List<Map<String ,String>> list = new ArrayList<>();
CloudmusicWithBLOBs cloudmusicWithBLOBs = service.selectById(mId);
String lyricPath = cloudmusicWithBLOBs.getMLyric();
byte[] data = null;
//这里之后才是重点lrc格式歌词,酷狗下载的版本,
try {
File file = new File(lyricPath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
data = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String lyricString = new String(data);
if(lyricString != null && !"".equals(lyricString)){
//分割歌词
String lyric[] = lyricString.split("\\r");
String regex = "\\[(\\d{1,2}):(\\d{1,2}).(\\d{1,2})\\]"; // 正则表达式
Pattern pattern = Pattern.compile(regex); // 创建 Pattern 对象
Map<String ,String> map = new HashMap<>();
for (String s : lyric) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
// [02:34.94] ----对应---> [分钟:秒.毫秒]
String min = matcher.group(1); // 分钟
String sec = matcher.group(2); // 秒
String mill = matcher.group(3); // 毫秒,注意这里其实还要乘以10
String time = getStringTime(min, sec, mill + "0");
// 获取当前时间的歌词信息
String text = s.substring(matcher.end());
map.put(time, text); // 添加到容器中
}
}
list.add(map);
}
log.info("出参 list:{}",list);
return list;
}
private String getStringTime(String min, String sec, String mill) {
// 转成整型
int m = Integer.parseInt(min);
int s = Integer.parseInt(sec);
int ms = Integer.parseInt(mill);
if (s >= 60) {
System.out.println("警告: 出现一个时间不正确的项 --> [" + min + ":" + sec + "." + mill.substring(0, 2) + "]");
}
// 组合成一个长整型表示的以毫秒为单位的时间
String time = m * 60 * 1000 + s * 1000 + ms + "";
return time;
}