21

I am making a Media player in Android. I require a code to get length of video without using a video view.

I saw many pages in Stack overflow but ever page used to show how to get length of a video in video view but i require without video view.

hasnain_ahmad
  • 325
  • 6
  • 17
AngryBird
  • 344
  • 1
  • 4
  • 15

1 Answers1

67

You could use the MediaMetadataRetriever to get such an information. This class is meant to be used by users who wants to get specific informations about a media without having to use the MediaPlayer.

Here's a sample of how to use it :

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(your_data_source);
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInmillisec = Long.parseLong( time );
long duration = timeInmillisec / 1000;
long hours = duration / 3600;
long minutes = (duration - hours * 3600) / 60;
long seconds = duration - (hours * 3600 + minutes * 60);
Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71
  • 1
    This Code Dose Not Work On Android 2.2 And API < 10 – Criss Aug 24 '15 at 12:40
  • No, the `MediaMetadataRetriever` class only exists on API10+. – Halim Qarroum Aug 24 '15 at 13:36
  • 1
    I just ran this code and it's pretty slow when only querying like 20 videos. – Gooey Oct 27 '15 at 23:09
  • Yes, the `MediaMetadataRetriever` causes the framework to actually parse the media for special headers or metadata frames, so I believe it can take some time, especially if it fetches a remote media. – Halim Qarroum Oct 27 '15 at 23:17
  • @HalimQarroum I get this error java.lang.IllegalArgumentException at android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriev I am passing remote url (not a local file path) – eawedat Sep 10 '18 at 20:42
  • @eawedat This may be related : https://stackoverflow.com/questions/27566480/mediametadataretriever-setdatasource-throws-illegalargumentexception – Halim Qarroum Sep 10 '18 at 21:34
  • @HalimQarroum , after reading there, it seems that we should replace the line retriever.setDataSource(URL); with retriever.setDataSource(URL, new HashMap()); and it works – eawedat Sep 11 '18 at 06:33