3

I have a ListView with several audio files. For each one I have to get the duration in order to display it in the list.

This is what I have tried yet:

MediaPlayer getDuration() -> takes about 1 sec for 13 items

MediaStore and Cursor -> takes about 2 sec for 13 items

This is way too much for displaying the ListView.

So I have thought of this:

creating a database with file-names and duration when recording the audio files

-> this leads to a data inconsistency, because files could have been deleted

Is there a alternative way to achieve this?

Thanks in advance

Melquiades
  • 8,496
  • 1
  • 31
  • 46

3 Answers3

3

MediaMetadataRetriever can be used to get meta data related to media files

MediaMetadataRetriever mediaMetadataRetriever= new MediaMetadataRetriever();
 mediaMetadataRetriever.setDataSource(filePath);

String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));

extractMetadata(int) method can be used above Android API level 10.

duration will be in millisecs.

N-JOY
  • 10,344
  • 7
  • 51
  • 69
2

MediaMetaDataRetriever is what I use to collect metadata of an audio or video file, including video preview frames, check out https://developer.android.com/reference/android/media/MediaMetadataRetriever to see what type of meta data you can retrieve from a media file. You should be able to use

extractMetaData(MediaMetadataRetriever.METADATA_KEY_DURATION)

to get the duration of the audio/video file.

Lee Boon Kong
  • 1,007
  • 1
  • 8
  • 17
0

I had the same problem (in 2020), the number of audio files in my case is about 4000-5000 files (of 5-10 minutes each). So in my case, it was taking too long. So I created an SQLite database and after that filtering, the files was a work of milliseconds. Here multithreading can't help because it is a disk task, not a computation. I did same as @N-JOY told but it was taking long (in minutes). Still, I wanted to make it fast.

My solution - After recording the audio file, add the length in AudioFile name and extracting the length of the file is a very easy task from its name. In this way, my recycler view is faster. Hope it helps someone.

But in case you have a lot of files created already then the database is the best option.

Vijay
  • 1,163
  • 8
  • 22