Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get duration of a video file?

Tags:

android

I'm a beginner in Android programming.

I'm writing an application to list all video file in a folder and display information of all videos in the folder. But when i try to get the video duration it return null and i can't find the way to get it.

Any one can help me?

Below is my code:

Uri uri = Uri.parse("content://media/external/video/media/9");
Cursor cursor = MediaStore.Video.query(res, data.getData(), new String[]{MediaStore.Video.VideoColumns.DURATION});
if(cursor.moveToFirst()) {
    String duration = cursor.getString(0);
    System.out.println("Duration: " + duration);
}
like image 309
Tue Nguyen Avatar asked Oct 14 '10 18:10

Tue Nguyen


2 Answers

Use MediaMetadataRetriever to retrieve media specific data:

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//use one of overloaded setDataSource() functions to set your data source
retriever.setDataSource(context, Uri.fromFile(videoFile));
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInMillisec = Long.parseLong(time );

retriever.release()
like image 63
vir us Avatar answered Oct 17 '22 22:10

vir us


I think the easiest way is:

MediaPlayer mp = MediaPlayer.create(this, Uri.parse(uriOfFile));
int duration = mp.getDuration();
mp.release();
/*convert millis to appropriate time*/
return String.format("%d min, %d sec", 
        TimeUnit.MILLISECONDS.toMinutes(duration),
        TimeUnit.MILLISECONDS.toSeconds(duration) - 
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
    );
like image 42
Nolesh Avatar answered Oct 17 '22 22:10

Nolesh