(Android)如何在我的音乐播放器上显示时间

Twi*_*oon 2 java android android-mediaplayer

音乐可以正常播放但我无法在我的音乐播放器上显示音乐时间.我该怎么办?

在主要班级

 public void onClick(View v) {

     if (mMedia.isPlaying()) {
            txtView.setText("Playing : music.mp3....");
                mMedia.pause();
            } else {
                txtView.setText("pause : music.mp3....");
                mMedia.start();
            }
        }
private void UpdateseekChange(View v){
    if(mMedia.isPlaying()){
        SeekBar sb = (SeekBar)v;
        mMedia.seekTo(sb.getProgress());
    }
Run Code Online (Sandbox Code Playgroud)

ysh*_*hak 10

这应该工作:

public void onClick(View v) {

    if (mMedia.isPlaying()) {
        txtView.setText("Playing : music.mp3....");
        mMedia.pause();
    } else {
        txtView.setText("pause : music.mp3....");
        mMedia.start();
        txtView.post(mUpdateTime);
    }
}

private Runnable mUpdateTime = new Runnable() {
    public void run() {
        int currentDuration;
        if (mMedia.isPlaying()) {
            currentDuration = mp.getCurrentPosition();
            updatePlayer(currentDuration);
            txtView.postDelayed(this, 1000);
        }else {
            txtView.removeCallbacks(this);
        }
    }
};

private void updatePlayer(int currentDuration){
    txtView.setText("" + milliSecondsToTimer((long) currentDuration));
}

/**
 * Function to convert milliseconds time to Timer Format
 * Hours:Minutes:Seconds
 * */
public  String milliSecondsToTimer(long milliseconds) {
    String finalTimerString = "";
    String secondsString = "";

    // Convert total duration into time
    int hours = (int) (milliseconds / (1000 * 60 * 60));
    int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
    int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
    // Add hours if there
    if (hours > 0) {
        finalTimerString = hours + ":";
    }

    // Prepending 0 to seconds if it is one digit
    if (seconds < 10) {
        secondsString = "0" + seconds;
    } else {
        secondsString = "" + seconds;
    }

    finalTimerString = finalTimerString + minutes + ":" + secondsString;

    // return timer string
    return finalTimerString;
}
Run Code Online (Sandbox Code Playgroud)

当然,您需要在轨道完成时删除runnable.