4

Using below code i captured Video,but how to get duration of captured video in android ? and also when sometimes user discard video and record new video then get duration of new video .

Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(cameraIntent, TAKE_VIDEO);
MAC
  • 15,799
  • 8
  • 54
  • 95

3 Answers3

9

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))
    );
Nolesh
  • 6,848
  • 12
  • 75
  • 112
  • By uriOfFile, do you mean the file Path appended with `file://` prefix ? – Salman Khakwani Sep 02 '14 at 09:11
  • Please don't create MediaPlayer instance just to get file length. There is a dedicated MediaMetadataRetriever class in android for this. More details available in the following answer: stackoverflow.com/a/33247728/1713920 – vir us Mar 19 '16 at 12:32
8

Using cursor you can get duration and there are duration Column in Cursor and you can get as a string.

Cursor cursor = MediaStore.Video.query(getContentResolver(),data.getData(),
                new String[] { MediaStore.Video.VideoColumns.DURATION });
System.out.println(">>>>>>>>>>"+cursor.getCount());
cursor.moveToFirst();

String duration = cursor.getString(cursor.getColumnIndex("duration"));
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • 2
    1)Above suggested is working for getting duration from recorded video. 2)But when i tried to retrieve the duration from gallery selected video it is throwing IllegalArgumentException. – Harish Jul 22 '15 at 09:37
  • I am using this solution, But i am getting error and Carsh my app – Arti Jul 22 '21 at 13:55
0

MediaPlayer is a heavy object. Use MediaMetadataRetriever instead

fun getMediaDurationMs(context: Context, fileUri: Uri): Int? {
    val mmr = MediaMetadataRetriever()
    mmr.setDataSource(context, fileUri)
    return mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toInt()
}
Kallos Zsolty
  • 211
  • 3
  • 5