最近在做一款android手機上的音樂播放器,學習到了很多東西,像是Fragment,ActionBar的使用等等,這里就先介紹一下歌詞同步的實現問題。
歌詞同步的實現思路很簡單:獲取歌詞文件LRC中的時間和歌詞內容,然后在指定的時間內播放相應的內容。獲取不難,難就在于如何在手機屏幕上實現歌詞的滾動。
先上效果圖:

先從最基本的讀取歌詞文件開始:
Public class LrcHandle {
private List mWords = new ArrayList();
private List mTimeList = new ArrayList();
//處理歌詞文件
public void readLRC(String path) {
File file = new File(path);
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String s = "";
while ((s = bufferedReader.readLine()) != null) {
addTimeToList(s);
if ((s.indexOf("[ar:") != -1) || (s.indexOf("[ti:") != -1)
|| (s.indexOf("[by:") != -1)) {
s = s.substring(s.indexOf(":") + 1, s.indexOf("]"));
} else {
String ss = s.substring(s.indexOf("["), s.indexOf("]") + 1);
s = s.replace(ss, "");
}
mWords.add(s);
}
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
mWords.add("沒有歌詞文件,趕緊去下載");
} catch (IOException e) {
e.printStackTrace();
mWords.add("沒有讀取到歌詞");
}
}
public List getWords() {
return mWords;
}
public List getTime() {
return mTimeList;
}
// 分離出時間
private int timeHandler(String string) {
string = string.replace(".", ":");
String timeData[] = string.split(":");
// 分離出分、秒并轉換為整型
int minute = Integer.parseInt(timeData[0]);
int second = Integer.parseInt(timeData[1]);
int millisecond = Integer.parseInt(timeData[2]);
// 計算上一行與下一行的時間轉換為毫秒數
int currentTime = (minute * 60 + second) * 1000 + millisecond * 10;
return currentTime;
}
private void addTimeToList(String string) {
Matcher matcher = Pattern.compile(
"[d{1,2}:d{1,2}([.:]d{1,2})?]").matcher(string);
if (matcher.find()) {
String str = matcher.group();
mTimeList.add(new LrcHandle().timeHandler(str.substring(1,
新聞熱點
疑難解答