如何从媒体播放器获取剩余歌曲和总持续时间?

朋友们,我不知道如何从媒体播放器中获取剩余的歌曲和总持续时间。在我的代码中,我想获取歌曲的总持续时间和剩余持续时间,并以正确的时间格式显示在文本视图中:


 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();

                      }


                  }

            }

        };

为了实现这一目标,我需要做些什么?


潇湘沐
浏览 123回答 2
2回答

慕村225694

正如我在你的代码中看到的...总持续时间=歌曲的总时间;但是如果你想媒体播放器的当前位置。你必须把你的代码放在可运行的范围内,并在每秒更新当前位置。&nbsp;final Handler handler=new Handler();&nbsp; &nbsp; handler.post(new Runnable() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int duration=mediaplayer.getcurrentPosition();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //and update your seekbar from handler&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //change your int to time format...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String time = String.format("%02d:%02d ", TimeUnit.MILLISECONDS.toMinutes(duration), TimeUnit.MILLISECONDS.toSeconds(duration) -&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;updateseekbar();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler.postDelayed(this,1000);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });如果你没有得到它,请再次询问

萧十郎

您可以通过从总持续时间中减去当前持续时间来实现此目的,在您的代码中,我可以看到您同时具有“总”和“当前持续时间”。remainingDuration&nbsp;&nbsp;=&nbsp;totalduration&nbsp;-&nbsp;&nbsp;&nbsp;currnetpostion=mediaPlayer.getCurrentPosition();可能是工作你的案例
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java