Reputation: 231
I am working on Video file duration finding in android. But i am unable to get it . My video files are available in the particular folder in the SD-card. Want to bind them as the list view with the duration and name . I have got the name . But searching solution to find the duration . Please help me . Thanks in advance .
Rajesh .
Upvotes: 3
Views: 12679
Reputation: 47107
Don't use MediaPlayer! It is inefficient
Use MediaMetadataRetriever
instead to get only the meta data that you need
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
// There are other variations of setDataSource(), if you have a different input
retriever.setDataSource(context, Uri.fromFile(videoFile));
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long durationMs = Long.parseLong(time);
retriever.release()
Here is the way to fetch media file duration in Kotlin
fun File.getMediaDuration(context: Context): Long {
if (!exists()) return 0
val retriever = MediaMetadataRetriever()
retriever.setDataSource(context, Uri.parse(absolutePath))
val duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
retriever.release()
return duration.toLongOrNull() ?: 0
}
If you want to make it safer (Uri.parse could throw exception), use this combination. The others are generally just useful as well :)
fun String?.asUri(): Uri? {
try {
return Uri.parse(this)
} catch (e: Exception) {
}
return null
}
val File.uri get() = this.absolutePath.asUri()
fun File.getMediaDuration(context: Context): Long {
if (!exists()) return 0
val retriever = MediaMetadataRetriever()
retriever.setDataSource(context, uri)
val duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
retriever.release()
return duration.toLongOrNull() ?: 0
}
Not necessary here, but generally helpful additional Uri extensions
val Uri?.exists get() = if (this == null) false else asFile().exists()
fun Uri.asFile(): File = File(toString())
Upvotes: 0
Reputation: 23596
You don't need to create MediaPlayer. I have made one function which will give you duration of your video file stored android device.
public static long checkVideoDurationValidation(Context context, Uri uri){
Log.d("CommonHandler", "Uri: " + uri);
Cursor cursor = MediaStore.Video.query(context.getContentResolver(), uri, new
String[]{MediaStore.Video.VideoColumns.DURATION});
long duration = 0;
if (cursor != null && cursor.moveToFirst()) {
duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Video
.VideoColumns.DURATION));
cursor.close();
}
return duration;
}
Let me know if you have any doubt in this.
Upvotes: 2
Reputation: 1747
int msec = MediaPlayer.create(context, Uri.fromFile(new File(path))).getDuration();
Upvotes: 10