android歌詞同步

來源:互聯網
上載者:User

http://blog.csdn.net/waterinet/article/details/7892834

最近做了一個android的音樂播放器,下面將介紹歌詞同步顯示的實現。網上關於這一塊的參考執行個體,多數人推薦了Yoyoplayer。YOYOPlayer是一個用JAVA編寫的,跨平台的音樂播放軟體.集播放,歌詞顯示於一體,並且開放原始碼,感興趣的朋友可以自行google。

一、LRC歌詞檔案的解析

        先要瞭解LRC檔案的格式,可以參考:http://baike.baidu.com/view/80650.htm。總體思路是這樣的,按行讀入歌詞文本,忽略每行中的注釋,即“[:]”後的內容;再解析標識標籤(ID-tags);最後解析出時間標籤及其對應的歌詞語句。具體實現如下:

1、忽略注釋

private String removeComment(String line){Matcher m = Pattern.compile("\\[:\\]").matcher(line);String str = line;while (m.find()){if (m.start() == 0)//整行都是注釋     str = null;else             str = line.substring(0, m.start());}return str;}

2、解析標識標籤

private void getLyricIdTags(String line){        Matcher m = Pattern.compile("\\[((ti)|(ar)|(al)|(by)):.+\\]")     .matcher(line);while (m.find()){String type = m.group().substring(1, 3);if (type.equals("ti")){title = m.group().substring(4, m.end()-1);}else if (type.equals("ar")){artist = m.group().substring(4, m.end()-1);}else if (type.equals("al")){album = m.group().substring(4, m.end()-1);}else if (type.equals("by")){author = m.group().substring(4, m.end()-1);}}}

3、解析時間標籤 

    這裡我用了map結構來儲存歌詞開始時間及歌詞語句的配對關係,value為歌詞語句,key值為該歌詞開始時間。這裡用了一個Regex來匹配時間標籤,支援[ : ] 、[  : : ] 、[ : . ]三種格式的時間標籤。getTimeOfLine()函數的作用是將時間標籤轉換成以毫秒為單位的時間量。

private void getLyricTimeTags(String line){Matcher m = Pattern.compile("\\[\\d{1,2}:\\d{1,2}([\\.:]\\d{1,2})?\\]").matcher(line);            List<Integer> time = new ArrayList<Integer>();         int begIndex = 0;        while (m.find())        {        time.add(getTimeOfLine(m.group()));        begIndex = m.end();        }        for (int i : time)        {        sortedLyric.put(i, line.substring(begIndex, line.length()));        }    }

 

二、歌詞語句分行

    LRC檔案中的單句歌詞可能過長,在android螢幕的給定地區中未必能單行顯示,從而需要依據螢幕歌詞顯示地區的寬度進行斷句分行。其中尋找分割點的實現如下:

private int getDividePoint(String str, int begIndex, int endIndex){//not to divide (letter,letter) or (digit,digit)int original = endIndex; while ( (charType(str.charAt(endIndex)) == LETTER && charType(str.charAt(endIndex-1)) == LETTER) || ( charType(str.charAt(endIndex)) == DIGIT && charType(str.charAt(endIndex-1)) == DIGIT) ){if (endIndex > begIndex)     endIndex--;else {     endIndex = original;     break;}}return endIndex;}

分割過程如下,其中tp為android中TextPaint類型的對象,TextPaint用於在view中繪製文本,它提供了一個測定文本寬度的函數measureText():

int begIndex = 0;for (int i = 0; i <= line.length(); ++i){String str = line.substring(begIndex, i);if (tp.measureText(str) > width){int dividePoint = getDividePoint(line, begIndex, i-1);lines.add(line.substring(begIndex, dividePoint));begIndex = dividePoint;}if (i == line.length())////添加分行結果的最後一部分lines.add(line.substring(begIndex, i));}

三、歌詞的同步顯示

       要把歌詞同步滾動地顯示在手機螢幕上,需要自訂view,這裡我選擇繼承自TextView。主要是重寫TextView中的onDrow()函數。主要實現思路是先繪製當前現正播放的歌詞,然後繪製當前歌詞之上的歌詞和當前歌詞之下的歌詞(指在螢幕上顯示的位置)。根據歌曲的播放進度,不斷重繪歌詞以達到同步滾動效果。

Bundle currentLine = lyric.getLineFromTime(currentTime);float offset = calOffsetOfCurrentLine();Bundle bundle = drawCurrentLine(canvas, offset, height, currentLine.getStringArrayList("Lines"));drawAboveLines(canvas, bundle.getFloat("PositionAbove"), lineWidth, lyric.valuesOfHeadMap(currentTime, false));drawBelowLines(canvas, bundle.getFloat("PositionBelow"), lineWidth, height, lyric.valuesOfTailMap(currentTime, false));

其中,函數getLineFromTime()根據當前播放進度擷取應該顯示的歌詞,calOffsetOfCurrentLine()返回當前歌詞距離初始顯示位置的位移量,因為一句歌詞從進入高亮顯示到結束高亮顯示有一段時間,這段時間裡高亮歌詞也是在滾動的,如所示:

    

“敵動我不動 你動我不動”這句開始高亮顯示                             “敵動我不動 你動我不動”結束高亮顯示

其中,calOffsetOfCurrentLine()函數為:

private float calOffsetOfCurrentLine(){Bundle bundle = lyric.getLineFromTime(currentTime);int numOfLines = bundle.getInt("Number");float fromTime = bundle.getInt("FromTime");float toTime = bundle.getInt("ToTime");float offset = (currentTime - fromTime) * 1.0f/(toTime - fromTime) * (30 * numOfLines);return offset;}

 

四、拖動歌詞控制播放進度

      這裡首先要明確,上下滑動歌詞只是一種動作,控制音樂播放進度。往上滑動表示進度往前,往下滑動表示進度往後。自己設定一個合適的滑動距離與時間的轉換關係即可。

public boolean onTouchEvent(MotionEvent event){ switch (event.getAction()){ case MotionEvent.ACTION_DOWN: isMoving = true; targetTime = currentTime; startY = event.getY(); break; case MotionEvent.ACTION_MOVE: targetTime = moveTo(event.getY()-startY); currentTime = targetTime; postInvalidate(); break; case MotionEvent.ACTION_UP: Intent intent = new Intent(getContext(), MusicPlayService.class); intent.setAction(MyIntentAction.SEEK_TO_FROM_LYRIC); intent.putExtra("SeekTo", currentTime); getContext().startService(intent);  isMoving = false; break;}return true;}

        這裡的MoveTo就是我設定的一個滑動距離與時間的轉換關係。分三個步驟:手指按下時記錄起始滑動點;活動過程中持續更新歌詞進度(即歌詞的上下滑動效果);手指放開時修改歌曲播放進度。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.