簡體   English   中英

Android Mediaplayer-基於seekbar進度更新textview中音頻的經過時間

[英]Android Mediaplayer - based on seekbar progress update the elapsed time of audio in textview

使用Mediaplayer播放音頻文件。

一切正常,但是音頻的播放時間需要在textview中更新。

textview.setText(mediaplayer.getCurrentPosition()/100000.0).toString();

這給出了雙精度值,但是如果結束時間超過一分鍾,並且經過的時間為1分鍾,則顯示0:60 ...但應為1:00 ...

還有其他方法可以根據搜索欄進度顯示經過的時間嗎?

謝謝。

這有效-取自另一篇文章的答案: 如何正確顯示MediaPlayer的位置/持續時間?

DateFormat適用於日期,不適用於時間間隔。 因此,如果位置為1秒,則數據格式會將其解釋為意味着日期/時間是日歷開始后的1秒。


private String getTimeString(long millis) {
    StringBuffer buf = new StringBuffer();

    int hours = millis / (1000*60*60);
    int minutes = ( millis % (1000*60*60) ) / (1000*60);
    int seconds = ( ( millis % (1000*60*60) ) % (1000*60) ) / 1000;

    buf
        .append(String.format("%02d", hours))
        .append(":")
        .append(String.format("%02d", minutes))
        .append(":")
        .append(tring.format("%02d", seconds));

    return buf.toString();
}

然后做類似的事情


totalTime.setText(getTimeString(duration));
currentTime.setText(getTimeString(position));

音樂示例應用程序具有一個MusicUtils類:

    /*  Try to use String.format() as little as possible, because it creates a
 *  new Formatter every time you call it, which is very inefficient.
 *  Reusing an existing Formatter more than tripled the speed of
 *  makeTimeString().
 *  This Formatter/StringBuilder are also used by makeAlbumSongsLabel()
 */
private static StringBuilder sFormatBuilder = new StringBuilder();
private static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
private static final Object[] sTimeArgs = new Object[5];

public static String makeTimeString(Context context, long secs) {
    String durationformat = context.getString(
            secs < 3600 ? R.string.durationformatshort : R.string.durationformatlong);

    /* Provide multiple arguments so the format can be changed easily
     * by modifying the xml.
     */
    sFormatBuilder.setLength(0);

    final Object[] timeArgs = sTimeArgs;
    timeArgs[0] = secs / 3600;
    timeArgs[1] = secs / 60;
    timeArgs[2] = (secs / 60) % 60;
    timeArgs[3] = secs;
    timeArgs[4] = secs % 60;

    return sFormatter.format(durationformat, timeArgs).toString();
}

您可以使用。

但是,如果將getCurrentPosition()的結果除以1000,則carlovv的解決方案也將起作用,因為該方法將返回毫秒。

這就是你的strings.xml

    <string translatable="false" name="durationformatshort">
    <xliff:g id="format">%2$d:%5$02d</xliff:g>
</string>
<string translatable="false" name="durationformatlong">
    <xliff:g id="format">%1$d:%3$02d:%5$02d</xliff:g>
</string>

您可以將getCurrentPosition轉換為date並使用dateFormat設置輸出字符串。

Date d = new Date();
d.setTime(mediaplayer.getCurrentPosition());
private final SimpleDateFormat timeFormat = new SimpleDateFormat("HH.mm");
String time = timeFormat.format(d).toString();

暫無
暫無

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

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