Shikha Ratra Shikha Ratra - 3 months ago 21
Android Question

VideoView time duration

I am using videoview to play videos from urls. when i play video the current time is some sec more than the total time duration of the video.

04-05 17:20:27.457 9342-9342/exoplayer.com.videoview V/TOTAL: 00:45
04-05 17:20:27.557 9342-9342/exoplayer.com.videoview V/CURRENT: 00:46


public String stringForTime(long timeMs) {
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
long totalSeconds = timeMs / 1000;
int seconds = (int) (totalSeconds % 60);
int minutes = (int) ((totalSeconds / 60) % 60);
int hours = (int) (totalSeconds / 3600);
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}

Answer

I did it using joda time, there's probably a better way but i think this is neater than the solution listed above

private String setTime(long elapsed) {
    final String PADDED_TIME_FORMAT = "00%s";
    final Period duration = new Period(elapsed);
    final String hours = String.format(PADDED_TIME_FORMAT, duration.getHours());
    final String minutes = String.format(PADDED_TIME_FORMAT, duration.getMinutes());
    final String seconds = String.format(PADDED_TIME_FORMAT, duration.getSeconds());
    return String.format("%s:%s:%s",
            hours.substring(hours.length() -2, hours.length()),
            minutes.substring(minutes.length() -2, minutes.length()),
            seconds.substring(seconds.length() -2, seconds.length()));
}
Comments