简体   繁体   中英

How to parse song duration from media player to correct minutes in android

I call getDuration() method in MP Android. It returns ms value. For example 267180 . This value equals to 04:27 . The question: how do I can parse convert 267180 into 04:27 programmatically? Thanks.

On Android you can use the TimeUnit functions to make conversion from milliseconds to eg seconds or minutes easy and human-readable.

import java.util.concurrent.TimeUnit;

@Test
public void testFormatDuration() throws Exception {
    assertEquals("00:00", formatDuration(0));
    assertEquals("04:27", formatDuration(267180));
    assertEquals("01:00", formatDuration(60000));
    assertEquals("10:00", formatDuration(600000));
}

private String formatDuration(long duration) {
    long minutes = TimeUnit.MINUTES.convert(duration, TimeUnit.MILLISECONDS);
    long seconds = TimeUnit.SECONDS.convert(duration, TimeUnit.MILLISECONDS)
            - minutes * TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES);

    return String.format("%02d:%02d", minutes, seconds);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM