android 歌词同步代码,android手机音乐播放器实现歌词同步
最近在做一款android手機(jī)上的音樂(lè)播放器,學(xué)習(xí)到了很多東西,像是Fragment,ActionBar的使用等等,這里就先介紹一下歌詞同步的實(shí)現(xiàn)問(wèn)題。
歌詞同步的實(shí)現(xiàn)思路很簡(jiǎn)單:獲取歌詞文件LRC中的時(shí)間和歌詞內(nèi)容,然后在指定的時(shí)間內(nèi)播放相應(yīng)的內(nèi)容。獲取不難,難就在于如何在手機(jī)屏幕上實(shí)現(xiàn)歌詞的滾動(dòng)。
先上效果圖:
先從最基本的讀取歌詞文件開(kāi)始:
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("沒(méi)有歌詞文件,趕緊去下載");
} catch (IOException e) {
e.printStackTrace();
mWords.add("沒(méi)有讀取到歌詞");
}
}
public List getWords() {
return mWords;
}
public List getTime() {
return mTimeList;
}
// 分離出時(shí)間
private int timeHandler(String string) {
string = string.replace(".", ":");
String timeData[] = string.split(":");
// 分離出分、秒并轉(zhuǎn)換為整型
int minute = Integer.parseInt(timeData[0]);
int second = Integer.parseInt(timeData[1]);
int millisecond = Integer.parseInt(timeData[2]);
// 計(jì)算上一行與下一行的時(shí)間轉(zhuǎn)換為毫秒數(shù)
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,
str.length() - 1)));
}
}
}
一般歌詞文件的格式大概如下:
[ar:藝人名]
[ti:曲名]
[al:專(zhuān)輯名]
[by:編者(指編輯LRC歌詞的人)]
[offset:時(shí)間補(bǔ)償值] 其單位是毫秒,正值表示整體提前,負(fù)值相反。這是用于總體調(diào)整顯示快慢的。
但也不一定,有時(shí)候并沒(méi)有前面那些ar:等標(biāo)識(shí)符,所以我們這里也提供了另一種解析方式。
歌詞文件中的時(shí)間格式則比較統(tǒng)一:[00:00.50]等等,00:表示分鐘,00.表示秒數(shù),.50表示毫秒數(shù),當(dāng)然,我們最后是要將它們轉(zhuǎn)化為毫秒數(shù)處理才比較方便。
總結(jié)
以上是生活随笔為你收集整理的android 歌词同步代码,android手机音乐播放器实现歌词同步的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: 从苹果到索尼:六大生态系统的崛起
- 下一篇: 暴雪插件占用服务器,暴雪:大服务器机制是
