效果圖

效果圖
沒有需求背景,純碎是清明在家無聊
主要的幾個功能
- 歌詞解析
- 播放/暫停(跟隨播放器)
- seek操作
- 以中間為錨點(diǎn)的滾動
lrc文件格式分析
[ti:現(xiàn)代愛情故事]
[ar:張智霖 許秋怡]
[al:現(xiàn)代愛情故事]
[by:esor]
[00:00.00]現(xiàn)代愛情故事
[00:08.00]張智霖 許秋怡
[00:16.00]專輯:現(xiàn)代愛情故事
[01:49.19][00:24.00]
[01:56.86][00:24.91]女:別離沒有對錯 要走也解釋不多
有幾個特點(diǎn)
- 只顯示有時間的內(nèi)容,
[ti:現(xiàn)代愛情故事]等不會顯示 - 同一句歌詞,可能有多次顯示的時機(jī)
所以我們根據(jù)正則去對內(nèi)容進(jìn)行匹配提取內(nèi)容,把每一句歌詞封裝成LrcLineEntity,[01:56.86][00:24.91]女:別離沒有對錯 要走也解釋不多最后會變成兩個LrcLineEntity,最后一個歌詞文件就可以轉(zhuǎn)換為一個List<LrcLineEntity>。為了保證代碼清晰,我們最后轉(zhuǎn)換成一個LrcEntity而不是一個List
public class LrcLineEntity {
public String content;
public long startPosition;
}
public class LrcEntity {
public List<LrcLineEntity> lrcLines;
public long totalLength;
}
歌詞解析
單行歌詞解析
public class LrcLineEntity {
// 提取時間正則
private static final Pattern TIME_PATTERN = Pattern.compile("\\[(\\d{2}:\\d{2}\\.\\d{2})\\]");
// 提取內(nèi)容正則
private static final Pattern CONTENT_PATTERN = Pattern.compile("\\[.*](.*)");
// 該句歌詞內(nèi)容
public String content;
// 該句歌詞開始播放的時間
public long startPosition;
public LrcLineEntity(String content, long startPosition) {
this.content = content;
this.startPosition = startPosition;
}
/**
* 解析單行歌詞
*
* @param lrcLine exam:[01:56.86][00:24.91]女:別離沒有對錯 要走也解釋不多
* @return
*/
@NonNull
public static List<LrcLineEntity> parseLine(@NonNull String lrcLine) {
List<LrcLineEntity> result = new ArrayList<>();
// 對內(nèi)容進(jìn)行提取
Matcher contentMatcher = CONTENT_PATTERN.matcher(lrcLine);
String content = "";
if (contentMatcher.find()) {
content = contentMatcher.group(1);
}
// 對多段時間進(jìn)行提取
Matcher timeMatcher = TIME_PATTERN.matcher(lrcLine);
while (timeMatcher.find()) {
String timeText = timeMatcher.group(1);
result.add(new LrcLineEntity(content, parseTimeText(timeText)));
}
return result;
}
/**
* 解析時間內(nèi)容,轉(zhuǎn)換為毫秒(相對時間)
*
* @param timeText exam:01:56.86-》(1*100*60*60+56*100*60+86)*10
* @return
*/
private static long parseTimeText(@NonNull String timeText) {
String[] numbers = timeText.split("[^\\d]");
long hour = 0;
long minutes = 0;
long seconds = 0;
long ms = 0;
try {
// 從后往前解析,某些值不存在會出現(xiàn)越界錯誤,最后得到0不影響計算
ms = Long.parseLong(numbers[numbers.length - 1]);
seconds = Long.parseLong(numbers[numbers.length - 2]);
minutes = Long.parseLong(numbers[numbers.length - 3]);
hour = Long.parseLong(numbers[numbers.length - 4]);
} catch (Exception ignored) {
}
return (hour * 100 * 60 * 60 + minutes * 100 * 60 + seconds * 100 + ms) * 10;
}
}
歌詞文本解析
public class LrcEntity {
public List<LrcLineEntity> lrcLines;
public long totalLength;
/**
* 對多行歌詞進(jìn)行解析
*
* @param lrcContent 歌詞內(nèi)容
* @return
*/
@Nullable
public static LrcEntity parse(@NonNull String lrcContent) {
try {
// 轉(zhuǎn)換成流
return parseStream(new ByteArrayInputStream(lrcContent.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 根據(jù)輸入流進(jìn)行解析
*
* @param inputStream
* @return
* @throws IOException
*/
@NonNull
public static LrcEntity parseStream(@NonNull InputStream inputStream) throws IOException {
LrcEntity result = new LrcEntity();
List<LrcLineEntity> lines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = reader.readLine()) != null) {
lines.addAll(LrcLineEntity.parseLine(line));
}
reader.close();
// 所有行解析后對讓行根據(jù)時間進(jìn)行排序
Collections.sort(lines, new Comparator<LrcLineEntity>() {
@Override
public int compare(LrcLineEntity o1, LrcLineEntity o2) {
return (int) (o1.startPosition - o2.startPosition);
}
});
int lineSize = lines.size();
// 記錄歌詞總長度
result.totalLength = lines.get(lineSize - 1).startPosition;
result.lrcLines = lines;
return result;
}
public int lineCount() {
return lrcLines.size();
}
}
至此,數(shù)據(jù)模型方面的代碼就已經(jīng)完成了。
View編寫
因為歌詞可能有很多行組成,但是屏幕上可視的View是有限的,所以推薦使用ListView或者RecyclerView去實現(xiàn)。
LrcView
public class LrcView extends ListView {
private LrcAdapter mAdapter;
public LrcView(Context context) {
this(context, null);
}
public LrcView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public LrcView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOverScrollMode(OVER_SCROLL_NEVER);
mAdapter = new LrcAdapter();
setAdapter(mAdapter);
}
}
LrcAdapter
public class LrcAdapter extends BaseAdapter {
private LrcEntity mData; // 數(shù)據(jù)源
private int mCurrentPosition; // 當(dāng)前播放的歌曲位置,一般會有突出的效果
@Override
public int getCount() {
return mData == null ? 0 : mData.lineCount();
}
@Override
public Object getItem(int position) {
return mData == null ? null : mData.lrcLines.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.line_text, parent, false);
}
TextView textView = (TextView) convertView;
textView.setText(mData.lrcLines.get(position).content);
if (mCurrentPosition == position) {
// 當(dāng)前播放的歌詞顯示黑色
textView.setTextColor(Color.BLACK);
} else {
// 其他情況顯示灰色
textView.setTextColor(Color.GRAY);
}
return textView;
}
public void setData(LrcEntity data) {
this.mData = data;
notifyDataSetChanged();
}
public LrcEntity getData() {
return mData;
}
public void setCurrentPosition(int currentPosition) {
this.mCurrentPosition = currentPosition;
notifyDataSetChanged();
}
public int getCurrentPosition() {
return mCurrentPosition;
}
}
line_text.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp"
android:text="hello world"
android:textColor="#000"
android:textSize="16dp">
</TextView>
Adapter和布局都比較簡單,下面針對LrcView進(jìn)行說明
主要思想是根據(jù)mStartTime和當(dāng)前時間去計算一個差值計算得出一個相對時間值,然后對歌詞進(jìn)行遍歷,找出符合結(jié)果的。如果是暫停操作,那么就記錄mPauseTime值,start操作時根據(jù)mPauseTime - mStartTime計算得出已經(jīng)播放的時間,然后再根據(jù)該值給mStartTime賦予正確的值,這樣就能讓start和pause的時間銜接上
LrcView
public class LrcView extends ListView {
private LrcAdapter mAdapter;
private int mOldPosition = -1; // 用于優(yōu)化,記錄上次高亮位置
private long mStartTime = 0; // 用于計算相對時間
// mPauseTime - mStartTime就是已經(jīng)播放的時間,主要用戶pause之后再start,對mStartTime正確賦值
private long mPauseTime = 0;
private volatile boolean mIsStart = false;
private Runnable mSetPositionRunnable = new Runnable() {
@Override
public void run() {
if (!mIsStart) {
// 因為在消息隊列中,所以會有延遲,基于mIsStart進(jìn)行判斷
return;
}
setPosition((int) (System.currentTimeMillis() - mStartTime));
// 用于循環(huán)
postDelayed(mSetPositionRunnable, 100);
}
};
public LrcView(Context context) {
this(context, null);
}
public LrcView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public LrcView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOverScrollMode(OVER_SCROLL_NEVER);
mAdapter = new LrcAdapter();
setAdapter(mAdapter);
}
public void setLrc(String lrcContent) {
reset();
mAdapter.setData(LrcEntity.parse(lrcContent));
}
public void setLrc(InputStream inputStream) throws IOException {
reset();
mAdapter.setData(LrcEntity.parseStream(inputStream));
}
/**
* 根據(jù)已經(jīng)播放的相對位置進(jìn)行UI更新
*
* @param position 單位ms,已經(jīng)播放的時間
*/
private void setPosition(int position) {
if (mAdapter.getData() == null) {
return;
}
int currentPosition = mAdapter.getCurrentPosition();
int newPosition = -1;
List<LrcLineEntity> lrcLines = mAdapter.getData().lrcLines;
int size = lrcLines.size();
// 最常見的情況就是一句挨著一句,所以先從當(dāng)前位置開始遍歷
for (int i = currentPosition + 1; i < size; i++) {
LrcLineEntity entity = lrcLines.get(i);
if (entity.startPosition > position) {
newPosition = i - 1;
break;
}
}
if (newPosition == -1) {
// 如果遍歷不到,那么就從頭開始遍歷
for (int i = 0; i < currentPosition; i++) {
LrcLineEntity entity = lrcLines.get(i);
if (entity.startPosition > position) {
newPosition = i - 1;
break;
}
}
}
if (newPosition == mOldPosition) {
// 兩次找到歌詞是一樣的位置,那么就不更新UI了
return;
}
if (newPosition == -1) {
// 當(dāng)前位置已經(jīng)超出所有歌詞所在時間范圍內(nèi),停留在最后一句歌詞
pause();
return;
}
mAdapter.setCurrentPosition(newPosition);
// 計算一半屏幕可容納的View的數(shù)量
int halfOfVisibleCount = (getLastVisiblePosition() - getFirstVisiblePosition()) / 2;
int scrollPosition = 0;
// 歌詞居中操作
if (mOldPosition + halfOfVisibleCount < getLastVisiblePosition()) {
// 歌詞從下滾到上面,要讓高亮歌詞居中則少滾動半屏幕行數(shù)
scrollPosition = newPosition >= (halfOfVisibleCount) ? newPosition - halfOfVisibleCount : newPosition;
} else {
// 歌詞從上滾到下面,要讓高亮歌詞居中則多滾動半屏幕行數(shù)
scrollPosition = newPosition >= (halfOfVisibleCount) ? newPosition + halfOfVisibleCount : newPosition;
}
smoothScrollToPosition(scrollPosition);
mOldPosition = newPosition;
}
/**
* 重置
*/
public void reset() {
mIsStart = false;
mStartTime = 0;
mPauseTime = 0;
mOldPosition = -1;
mAdapter.setCurrentPosition(-1);
setPosition(0);
}
/**
* 開始播放歌詞
*/
public void start() {
if (mIsStart) {
return;
}
mStartTime = System.currentTimeMillis() - (mPauseTime - mStartTime);
mIsStart = true;
post(mSetPositionRunnable);
}
/**
* 暫停播放歌詞
*/
public void pause() {
if (!mIsStart) {
return;
}
mPauseTime = System.currentTimeMillis();
mIsStart = false;
}
/**
* 移動相對位置
*
* @param position 單位ms,已經(jīng)播放的時間
*/
public void seekTo(int position) {
if (position < 0 || position > mAdapter.getData().totalLength) {
return;
}
mStartTime = System.currentTimeMillis() - position;
mPauseTime = 0;
// 下次更新UI強(qiáng)制刷新
mOldPosition = -1;
mAdapter.setCurrentPosition(-1);
}
}