How do I correctly display the position/duration of a MediaPlayer?
DateFormat
works for dates, not for time intervals. So if you get a position of 1 second, the DateFormat interprets this as meaning that the date/time is 1 second after the beginning the calendar (which is January 1st, 1970).
You'd need to do something like
private String getTimeString(long millis) {
StringBuffer buf = new StringBuffer();
int hours = (int) (millis / (1000 * 60 * 60));
int minutes = (int) ((millis % (1000 * 60 * 60)) / (1000 * 60));
int seconds = (int) (((millis % (1000 * 60 * 60)) % (1000 * 60)) / 1000);
buf
.append(String.format("%02d", hours))
.append(":")
.append(String.format("%02d", minutes))
.append(":")
.append(String.format("%02d", seconds));
return buf.toString();
}
And then do something like
totalTime.setText(getTimeString(duration));
currentTime.setText(getTimeString(position));
just try this one
fun getDurationString(durationMs: Long, negativePrefix: Boolean): String {
val hours = TimeUnit.MILLISECONDS.toHours(durationMs)
val minutes = TimeUnit.MILLISECONDS.toMinutes(durationMs)
val seconds = TimeUnit.MILLISECONDS.toSeconds(durationMs)
return if (hours > 0) {
format(
Locale.getDefault(), "%s%02d:%02d:%02d",
if (negativePrefix) "- " else "",
hours,
minutes - TimeUnit.HOURS.toMinutes(hours),
seconds - TimeUnit.MINUTES.toSeconds(minutes)
)
} else format(
Locale.getDefault(), "%s%02d:%02d",
if (negativePrefix) "- " else "",
minutes,
seconds - TimeUnit.MINUTES.toSeconds(minutes)
)
}