Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mp3 duration in android

How to get mp3 track duration without creating MediaPlayer instance? I just need to show mp3 song length in mp3 file list, so I think that I shouldn't create MediaPlayer object for each of tracks in the list

And another:

sometimes MediaPlayer returns wrong duration of the song ( I think its so because bitrate of those files is dinamic ). How can I get right duration of the song?

like image 441
pleerock Avatar asked Nov 07 '11 20:11

pleerock


People also ask

How do I find the length of a MP3 file on my Android?

You can use the MediaMetadataRetriever to get the duration of a song. Use the METADATA_KEY_DURATION in combination with the extractMetadata() funciton.

What is MediaPlayer in Android?

android.media.MediaPlayer. MediaPlayer class can be used to control playback of audio/video files and streams. MediaPlayer is not thread-safe. Creation of and all access to player instances should be on the same thread. If registering callbacks, the thread must have a Looper.


1 Answers

       // load data file
       MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
       metaRetriever.setDataSource(filePath);

String out = "";
       // get mp3 info

      // convert duration to minute:seconds
String duration =  
     metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    Log.v("time", duration);
    long dur = Long.parseLong(duration);
    String seconds = String.valueOf((dur % 60000) / 1000);

    Log.v("seconds", seconds);
    String minutes = String.valueOf(dur / 60000);
    out = minutes + ":" + seconds;
    if (seconds.length() == 1) {
        txtTime.setText("0" + minutes + ":0" + seconds);
    }else {
        txtTime.setText("0" + minutes + ":" + seconds);
    }
    Log.v("minutes", minutes);
      // close object
       metaRetriever.release();
like image 180
Android Avatar answered Oct 15 '22 16:10

Android