</pre><pre name="code" class="java">//歌词解析类
public class LrcParser {
/** 用于向外通知歌词载入、变化的监听器 */
public interface LyricListener {
/**
* 歌词载入时调用
*
* @param LrcInfos
* 歌词文本处理后的所有歌词句子
* @param indexOfCurSentence
* 正在播放的句子在句子集合中的索引号
*/
public abstract void onLyricLoaded(List<LrcInfo> LrcInfos,
int indexOfCurSentence);
/**
* 歌词变化时调用
*
* @param indexOfCurSentence
* 正在播放的句子在句子集合中的索引号 */
public abstract void onLrcInfoChanged(int indexOfCurSentence);
}
private static final String TAG = LrcParser.class.getSimpleName();
public static final int STATE_COMPLETE=1;
public static final int STATE_PROCESS=2;
public static final int STATE_FAIL=3;
public static final int STATE_OTHER=4;
/** 句子集合 */
private ArrayList<LrcInfo> mLrcInfos = new ArrayList<LrcInfo>();
private LyricListener mLyricListener = null;
private boolean mHasLyric = false;
/** 当前正在播放的歌词句子的在句子集合中的索引号 */
private int mIndexOfCurrentSentence = -1;
/** 用于缓存的一个正则表达式对象,识别[]中的内容,不包括中括号 */
private final Pattern mBracketPattern = Pattern
.compile("(?<=\\[).*?(?=\\])");
private final Pattern mTimePattern = Pattern
.compile("(?<=\\[)(\\d{2}:\\d{2}\\.?\\d{0,3})(?=\\])");
private final String mEncoding = "utf-8";
private Context mContext;
public List<LrcInfo> getLrcInfos() {
return mLrcInfos;
}
public void setLyricListener(LyricListener listener) {
this.mLyricListener = listener;
}
public LrcParser(Context context){
this.mContext=context;
}
public void setIndexOfCurrentSentence(int index) {
mIndexOfCurrentSentence = index;
}
public int getIndexOfCurrentSentence() {
return mIndexOfCurrentSentence;
}
/**
* 根据歌词文件的路径,读取出歌词文本并解析
*
* @param lyricPath
* 歌词文件路径
* @return true表示存在歌词,false表示不存在歌词
*/
public boolean loadLyric(String lyricPath,int State) {
mHasLyric = false;
mLrcInfos.clear();
if (lyricPath != null) {
//判断状态再修改显示信息----点击歌词时重复加载歌词需要改下
File file = new File(lyricPath);
if (file.exists()) {
mHasLyric = true;
try {
FileInputStream fr = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fr, mEncoding);
BufferedReader br = new BufferedReader(isr);
String line = null;
// 逐行分析歌词文本
while ((line = br.readLine()) != null) {
// Log.i(TAG, "lyric line:" + line);
parseLine(line);
}
// 按时间排序句子集合
Collections.sort(mLrcInfos,
new Comparator<LrcInfo>() {
// 内嵌,匿名的compare类
public int compare(LrcInfo object1,
LrcInfo object2) {
if (object1.getStartTime() > object2
.getStartTime()) {
return 1;
} else if (object1.getStartTime() < object2
.getStartTime()) {
return -1;
} else {
return 0;
}
}
});
for (int i = 0; i < mLrcInfos.size() - 1; i++) {
mLrcInfos.get(i).setDuringTime(
mLrcInfos.get(i + 1).getStartTime());
}
mLrcInfos.get(mLrcInfos.size() - 1)
.setDuringTime(Integer.MAX_VALUE);
fr.close();