如何从媒体播放器获取剩余歌曲和总持续时间?
How to get songs remaining and total duration time from media player?
朋友们,我不知道如何从媒体播放器中获取剩余歌曲和总时长。在我的代码中,我想获取歌曲的总时长和剩余时长,并以适当的时间格式在文本视图中显示:
updateseekbar=new Thread(){
@Override public void run(){
int totalduration=mediaPlayer.getDuration();
int currnetpostion=0;
while (currnetpostion<totalduration){
try{
sleep(500);
currnetpostion=mediaPlayer.getCurrentPosition();
seekBar.setProgress(currnetpostion);
}catch (Exception e) {
e.printStackTrace();
}
}
}
};
我需要做什么才能实现这一目标?
您可以通过从总持续时间中减去当前持续时间来实现此目的,在您的代码中我可以看到您同时拥有总持续时间和当前持续时间。
remainingDuration = totalduration - currnetpostion=mediaPlayer.getCurrentPosition();
可能适合你的情况
正如我在您的代码中看到的那样....
totalduration=歌曲的总时长;
但是如果你想要媒体播放器的当前位置。你必须把你的代码放在 runnable 中并每秒更新当前位置....
final Handler handler=new Handler();
handler.post(new Runnable() {
@Override
public void run() {
int duration=mediaplayer.getcurrentPosition();
//and update your seekbar from handler
//change your int to time format...
String time = String.format("%02d:%02d ", TimeUnit.MILLISECONDS.toMinutes(duration), TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
updateseekbar();
handler.postDelayed(this,1000);
}
});
如果你不明白再问一遍
朋友们,我不知道如何从媒体播放器中获取剩余歌曲和总时长。在我的代码中,我想获取歌曲的总时长和剩余时长,并以适当的时间格式在文本视图中显示:
updateseekbar=new Thread(){
@Override public void run(){
int totalduration=mediaPlayer.getDuration();
int currnetpostion=0;
while (currnetpostion<totalduration){
try{
sleep(500);
currnetpostion=mediaPlayer.getCurrentPosition();
seekBar.setProgress(currnetpostion);
}catch (Exception e) {
e.printStackTrace();
}
}
}
};
我需要做什么才能实现这一目标?
您可以通过从总持续时间中减去当前持续时间来实现此目的,在您的代码中我可以看到您同时拥有总持续时间和当前持续时间。
remainingDuration = totalduration - currnetpostion=mediaPlayer.getCurrentPosition();
可能适合你的情况
正如我在您的代码中看到的那样....
totalduration=歌曲的总时长;
但是如果你想要媒体播放器的当前位置。你必须把你的代码放在 runnable 中并每秒更新当前位置....
final Handler handler=new Handler();
handler.post(new Runnable() {
@Override
public void run() {
int duration=mediaplayer.getcurrentPosition();
//and update your seekbar from handler
//change your int to time format...
String time = String.format("%02d:%02d ", TimeUnit.MILLISECONDS.toMinutes(duration), TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
updateseekbar();
handler.postDelayed(this,1000);
}
});
如果你不明白再问一遍