show time when song is playing in android

若如初见. 提交于 2019-11-27 15:15:27

问题


i am trying to play a song by using MediaPlayer from the given list.i want include time duration for the song from starting to ending of the song. how to add time and how to update that time from 0:00 to till the end of that song


回答1:


You can use the method getCurrentPosition() which gives you the current position in milliseconds.

You can also use the method getDuration() to get the full length of the song.

You can use a separate thread to update the timer.




回答2:


To show the playing time, I've used Timer and TimerTask, which updates TextView tv every 1000ms. Note that not using tv.post(Runnable action) for setting text in Text View would not block the UI thread and may cause problems.

if (player != null) {
    player.start();
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (player != null && player.isPlaying()) {
                        tv.post(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText(player.getCurrentPosition());
                            }
                        });
                    } else {
                        timer.cancel();
                        timer.purge();
                    }
                }
            });
        }
    }, 0, 1000);
}



回答3:


Give this solution a shot. According to the post, it only works for Android 1.5, but this should point you in the right direction. The issue is that there is no documented way (that I know of) of getting currently playing track info, though I've not really utilized the audio portion of the Android SDK as my projects require concentration elsewhere.



来源:https://stackoverflow.com/questions/6060563/show-time-when-song-is-playing-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!