Gingerbread123321
Gingerbread123321

Reputation: 249

Get duration of audio file Android

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

Upvotes: 3

Views: 5769

Answers (3)

Vijay
Vijay

Reputation: 1388

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.

Upvotes: 0

N-JOY
N-JOY

Reputation: 7635

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.

Upvotes: 4

Lee Boon Kong
Lee Boon Kong

Reputation: 1056

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.

Upvotes: 2

Related Questions