Don't use MediaPlayer! It is inefficient
Use MediaMetadataRetriever
instead to get only the meta data that you need
Java Solution
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()
Kotlin Extension Solution
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())