簡體   English   中英

如何在android中以分鍾和秒為單位獲取音頻長度

[英]how to get length of audio in minutes and seconds in android

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

來自媒體播放器

以毫秒為單位的持續時間,如果沒有可用的持續時間(例如,如果流式傳輸實時內容),則返回 -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);
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;
    }

它已經 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;
}

毫秒 / 1000 將毫秒轉換為秒。 例子:

allSeconds = 68950 / 1000 = 68 seconds

如果 allSeconds 大於 60,我們會將分鍾與秒分開,然后我們將使用以下方法將 allSeconds = 68 轉換為分鍾:

minutes = allSeconds / 60 = 1 left 8

剩下的數字將是秒

seconds = allSeconds % 60 = 8

如果秒數小於 10,方法 formatSeconds(byte seconds) 添加零。

所以最后會是: 1:08 : 1:08

為什么是字節? Long 的性能很差,那么最好使用字節進行更長的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM