无法将歌曲持续时间从ms转换为格式h:m:s

时间:2014-03-25 13:59:41

标签: java android

我开发了一个从sdcard中检索歌曲的代码,但我的问题是接收歌曲持续时间毫秒。我想将其转换为格式h:m:s。但都失败了。 这是我的代码`

public class SongsActivity extends ListActivity {
    SimpleCursorAdapter adapter;
    MediaPlayer myMediaPlayer;
    private Utilities utils;
    /** Called when the activity is first created. */
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        findViewById(R.id.dura);

        String[] from = {
            MediaStore.MediaColumns.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DURATION};
        int[] to = {
            R.id.title, R.id.artist, R.id.album, R.id.dura};


        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null, MediaStore.Audio.Media.TITLE);

        adapter = new SimpleCursorAdapter(this,
        R.layout.custom_list_item, cursor, from, to);
        setListAdapter(adapter);
  }

任何人请帮我告诉我如何将MediaStore.Media.Duratio从毫秒改为H:M:S。提前感谢您的帮助

2 个答案:

答案 0 :(得分:3)

一个微不足道的DateUtils.formatElapsedTime

DateUtils.formatElapsedTime(timeInMillis);

请参阅documentation

答案 1 :(得分:0)

假设您已经有毫秒的持续时间 (ms)

String.format("%02d : %02d : %02d", 
TimeUnit.MILLISECONDS.toHours(ms),
TimeUnit.MILLISECONDS.toMinutes(ms) -  
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)), 
TimeUnit.MILLISECONDS.toSeconds(ms) - 
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));   

以上代码会将其转换为 HH : MM : SS (注意%02d以指定位数)