① android 如何實現 邊錄音 同時顯示 歌詞評分有原理,代碼就好了。。
歌曲播放時歌詞同步顯示,我們需要讀取以上歌詞文件的每一行轉換成成一個個歌詞實體,可根據當前播放器的播放進度與每句歌詞的開始時間,得到當前屏幕中央高亮顯示的那句歌詞
我們需要讀取以上歌詞文件的每一行轉換成成一個個歌詞實體:
代碼如下:
public class LyricObject {
public int begintime; // 開始時間
public int endtime; // 結束時間
public int timeline; // 單句歌詞用時
public String lrc; // 單句歌詞
}
可根據當前播放器的播放進度與每句歌詞的開始時間,得到當前屏幕中央高亮顯示的那句歌詞。在UI線程中另起線程,通過回調函數 onDraw() 每隔100ms重新繪制屏幕,實現歌詞平滑滾動的動畫效果。MainActivity代碼如下:
代碼如下:
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private LyricView lyricView;
private MediaPlayer mediaPlayer;
private Button button;
private SeekBar seekBar;
private String mp3Path;
private int INTERVAL=45;//歌詞每行的間隔
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mp3Path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LyricSync/1.mp3";
lyricView = (LyricView) findViewById(R.id.mylrc);
mediaPlayer = new MediaPlayer();
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
ResetMusic(mp3Path);
SerchLrc();
lyricView.SetTextSize();
button = (Button) findViewById(R.id.button);
button.setText("播放");
seekBar = (SeekBar) findViewById(R.id.seekbarmusic);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mediaPlayer.seekTo(progress);
lyricView.setOffsetY(220 - lyricView.SelectIndex(progress)
* (lyricView.getSIZEWORD() + INTERVAL-1));
}
}
});
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer.isPlaying()) {
button.setText("播放");
mediaPlayer.pause();
} else {
button.setText("暫停");
mediaPlayer.start();
lyricView.setOffsetY(220 - lyricView.SelectIndex(mediaPlayer.getCurrentPosition())
* (lyricView.getSIZEWORD() + INTERVAL-1));
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
ResetMusic(mp3Path);
lyricView.SetTextSize();
lyricView.setOffsetY(200);
mediaPlayer.start();
}
});
seekBar.setMax(mediaPlayer.getDuration());
new Thread(new runable()).start();
}
public void SerchLrc() {
String lrc = mp3Path;
lrc = lrc.substring(0, lrc.length() - 4).trim() + ".lrc".trim();
LyricView.read(lrc);
lyricView.SetTextSize();
lyricView.setOffsetY(350);
}
public void ResetMusic(String path) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(mp3Path);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class runable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(100);
if (mediaPlayer.isPlaying()) {
lyricView.setOffsetY(lyricView.getOffsetY() - lyricView.SpeedLrc());
lyricView.SelectIndex(mediaPlayer.getCurrentPosition());
seekBar.setProgress(mediaPlayer.getCurrentPosition());
mHandler.post(mUpdateResults);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Handler mHandler = new Handler();
Runnable mUpdateResults = new Runnable() {
public void run() {
lyricView.invalidate(); // 更新視圖
}
};
}
② java解析lrc文件代碼
lrc可以通過如下util工具類進行轉換,如果想知道結果是否讀取的有問題,可以直接用記事本打開lrc文件的,之後和輸出結果比對一下就行。
package com.routon.utils;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.util.Log;
/**
* parse lrc file tool
* eg:
* utilLrc lrc = new utilLrc("/sdcard/test.lrc");
* get song name : String title = lrc.getTitle();
* get performer name : String artist = lrc.getArtist();
* get album name: String album = lrc.getAlbum();
* get lrcmaker name: String lrcMaker = lrc.getLrcMaker();
* get song list: List<Statement> list = lrc.getLrcList();
*
* @author xuweilin
*
*/
public class utilLrc {
private static String TAG = "utilLrc";
public class Statement {
private double time = 0.0; //time, 0.01s
private String lyric = ""; //song word
/*
* get time
*/
public double getTime() {
return time;
}
/*
* set time
*/
public void setTime(double time) {
this.time = time;
}
/*
* set time.format:mm:ss.ms
*/
public void setTime(String time) {
String str[] = time.split(":|\\.");
this.time = Integer.parseInt(str[0])*60+Integer.parseInt(str[1])+Integer.parseInt(str[2])*0.01;
}
/*
* get lrc word
*/
public String getLyric() {
return lyric;
}
/*
* set lrc word
*/
public void setLyric(String lyric) {
this.lyric = lyric;
}
}
private BufferedReader bufferReader = null;
private String title = "";
private String artist = "";
private String album = "";
private String lrcMaker = "";
private List<Statement> statements = new ArrayList<Statement>();
/*
*
* fileName
*/
public utilLrc(String fileName) throws IOException{
FileInputStream file = new FileInputStream(fileName);
bufferReader = new BufferedReader(new InputStreamReader(file, "utf-8"));
readData();
}
/*
* read the file
*/
private void readData() throws IOException{
statements.clear();
String strLine;
while(null != (strLine = bufferReader.readLine()))
{
if("".equals(strLine.trim()))
{
continue;
}
if(null == title || "".equals(title.trim()))
{
Pattern pattern = Pattern.compile("\\[ti:(.+?)\\]");
Matcher matcher = pattern.matcher(strLine);
if(matcher.find())
{
title=matcher.group(1);
continue;
}
}
if(null == artist || "".equals(artist.trim()))
{
Pattern pattern = Pattern.compile("\\[ar:(.+?)\\]");
Matcher matcher = pattern.matcher(strLine);
if(matcher.find())
{
artist=matcher.group(1);
continue;
}
}
if(null == album || "".equals(album.trim()))
{
Pattern pattern = Pattern.compile("\\[al:(.+?)\\]");
Matcher matcher = pattern.matcher(strLine);
if(matcher.find())
{
album=matcher.group(1);
continue;
}
}
if(null == lrcMaker || "".equals(lrcMaker.trim()))
{
Pattern pattern = Pattern.compile("\\[by:(.+?)\\]");
Matcher matcher = pattern.matcher(strLine);
if(matcher.find())
{
lrcMaker=matcher.group(1);
continue;
}
}
int timeNum=0;
String str[] = strLine.split("\\]");
for(int i=0; i<str.length; ++i)
{
String str2[] = str[i].split("\\[");
str[i] = str2[str2.length-1];
if(isTime(str[i])){
++timeNum;
}
}
for(int i=0; i<timeNum;++i)
{
Statement sm = new Statement();
sm.setTime(str[i]);
if(timeNum<str.length)
{
sm.setLyric(str[str.length-1]);
}
statements.add(sm);
}
}
sortLyric();
}
/*
* judge the string is or not date format.
*/
private boolean isTime(String string)
{
String str[] = string.split(":|\\.");
if(3!=str.length)
{
return false;
}
try{
for(int i=0;i<str.length;++i)
{
Integer.parseInt(str[i]);
}
}
catch(NumberFormatException e)
{
Log.e(TAG, "isTime exception:"+e.getMessage());
return false;
}
return true;
}
/*
* sort the word by time.
*/
private void sortLyric()
{
for(int i=0;i<statements.size()-1;++i)
{
int index=i;
double delta=Double.MAX_VALUE;
boolean moveFlag = false;
for(int j=i+1;j<statements.size();++j)
{
double sub;
if(0>=(sub=statements.get(i).getTime()-statements.get(j).getTime()))
{
continue;
}
moveFlag=true;
if(sub<delta)
{
delta=sub;
index=j+1;
}
}
if(moveFlag)
{
statements.add(index, statements.get(i));
statements.remove(i);
--i;
}
}
}
/**
* get title
* @return
*/
public String getTitle(){
return title;
}
/**
* get artist
* @return
*/
public String getArtist(){
return artist;
}
/**
* get album
* @return
*/
public String getAlbum(){
return album;
}
/**
* get lrc maker
* @return
*/
public String getLrcMaker(){
return lrcMaker;
}
/**
* get song list
* @return
*/
public List<Statement> getLrcList(){
return statements;
}
}