如何在android中获得分钟和秒钟的音频长度

时间:2017-05-07 07:15:46

标签: java android c android-layout github

int duration = mediaPlayer.getDuration(); 
textView = (TextView) findViewById(R.id.tvduration); textView.setText(duration);

3 个答案:

答案 0 :(得分:6)

来自MediaPlayer

  

持续时间(以毫秒为单位),如果没有可用的持续时间(for   例如,如果流媒体直播内容),则返回-1。

这就是为什么你会从getDuration()获得持续时间(以毫秒为单位) 您可以使用它来将MediaPlayer的时间作为字符串:

int duration = mediaPlayer.getDuration();
String time = String.format("%02d min, %02d sec", 
    TimeUnit.MILLISECONDS.toMinutes(duration),
    TimeUnit.MILLISECONDS.toSeconds(duration) - 
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
);

然后当你写下你的问题时:

TextView textView = (TextView) findViewById(R.id.tvduration); 
textView.setText(time);

答案 1 :(得分:1)

public static 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 + ":";
        }

        // Pre appending 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;
    }

答案 2 :(得分:0)

它已经 3 岁了,但没有人回答正确,然后我会回答

public String format(long millis) {
    long allSeconds = millis / 1000;
    int allMinutes;
    byte seconds, minutes, hours;
    if (allSeconds >= 60) {
        allMinutes = (int) (allSeconds / 60);
        seconds = (byte) (allSeconds % 60);
        if (allMinutes >= 60) {
            hours = (byte) (allMinutes / 60);
            minutes = (byte) (allMinutes % 60);
            return String.format(Locale.US, "%d:%d:" + formatSeconds(seconds), hours, minutes, seconds);
        } else
            return String.format(Locale.US, "%d:" + formatSeconds(seconds), allMinutes, seconds);
    } else
        return String.format(Locale.US, "0:" + formatSeconds((byte) allSeconds), allSeconds);
}

public String formatSeconds(byte seconds) {
    String secondsFormatted;
    if (seconds < 10) secondsFormatted = "0%d";
    else secondsFormatted = "%d";
    return secondsFormatted;
}

millis / 1000 将毫秒转换为秒。示例:

allSeconds = 68950 / 1000 = 68 seconds

如果 allSeconds 大于 60,我们会将分钟与秒分开,然后我们将使用以下方法将 allSeconds = 68 转换为分钟:

minutes = allSeconds / 60 = 1 left 8

剩下的数字将是秒

seconds = allSeconds % 60 = 8

formatSeconds(byte seconds) 方法在秒数是否小于 10 时加零。

所以最后会是:1:08

为什么是字节? Long 的性能很差,那么最好使用字节进行更长的操作。