android-将seekbar与音频歌曲同步
作者:互联网
我正在播放SD卡中的歌曲.
它的播放很好.我试图实现搜索栏,以便当用户移动搜索栏时,歌曲将根据搜索栏位置被转发或重新加密.
这是代码
public class ViewAudio extends Activity implements OnSeekBarChangeListener,OnSeekCompleteListener,OnCompletionListener,OnPreparedListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("audiofilename");
try {
mPlayer.setDataSource(filename);
} 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();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnSeekCompleteListener((OnSeekCompleteListener) this);
mPlayer.start();
TextView tv=(TextView) findViewById(R.id.file);
tv.setText("Playing "+filename);
seekbar = (SeekBar)findViewById(R.id.seekBar1);
mPlay = (Button)findViewById(R.id.play);
mPause = (Button)findViewById(R.id.pause);
seekbar.setProgress(0);
seekbar.setOnSeekBarChangeListener(this);
total = mPlayer.getDuration();
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Log.d("Progres changed",""+progress);
if(fromUser){
mPlayer.seekTo(progress);
seekbar.setProgress(progress);
}
}
}
现在,无论我在哪里单击搜索栏,歌曲都是从头开始播放,而不是从我单击的位置开始播放.而且它不是根据歌曲移动的.
任何人请帮忙.
解决方法:
我已经解决了.
创建一个线程,该线程将每秒检查一次歌曲的位置,并根据歌曲的位置移动搜索栏
mediaPos = mplayer.getCurrentPosition();
mediaMax = mplayer.getDuration();
seekbar.setMax(mediaMax); // Set the Maximum range of the
seekbar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100); //cal the thread after 100 milliseconds
}
/**
* The Move seek bar. Thread to move seekbar based on the current position
* of the song
*/
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mplayer.isPlaying()){
int mediaPos_new = mPlayer.getCurrentPosition();
int mediaMax_new = mPlayer.getDuration();
seekbar.setMax(mediaMax_new);
seekbar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); //Looping the thread after 0.1 second
}
}
};
标签:media-player,seekbar,audio,android 来源: https://codeday.me/bug/20191201/2083847.html