Validation Check for Video Duration on Client side

Introduction

 
I had a requirement where I had a file upload control with me and I wanted to validate the video duration before uploading it. I did lot of R & D to find a way of validating the video duration to be let say greater than 2minutes before being uploaded.
 
HTML UI
 
 
We know, in HTML 5 we can check the duration of video using video element but the problem is video element needs to set with the source.
  1. <video controls width="500px" id="vid">  
  2.    <source src="vid.mp4" type="video/mp4" />  
  3. </video> 
This means I first need to upload the video to the server to set the src attribute, but that will add overhead to the server when the validation of 2minutes doesn’t match. So I need a way that will work on the client-side.
 
I came across something called as URL.createObjectURL().
 
It is a static method which creates DOMstring containing a Url representing the object.
 
Check the following code snippet.
  1. <div style="border:1px solid black">  
  2.     <h3>File Upload</h3>  
  3.     <input type="file" id="fl"></input>  
  4.     <br />  
  5.     <br />  
  6.     <input type="button" value="Validate" id="btn" />  
  7.     <br />  
  8.     <video controls width="500px" id="vid" style="display:none"></video>  
  9. </div>  
  10. <script type="text/ecmascript">  
  11. var objectUrl;  
  12.   
  13. $(document).ready(function() {  
  14.     $("#fl").change(function(e) {  
  15.         var file = e.currentTarget.files[0];  
  16.         objectUrl = URL.createObjectURL(file);  
  17.         $("#vid").prop("src", objectUrl);  
  18.     });  
  19.   
  20.     $('#btn').click(function() {  
  21.         var seconds = $("#vid")[0].duration;  
  22.         if (seconds <= 120)  
  23.             alert('Video duration should be more than 2 min');  
  24.     });  
  25.   
  26. });  
  27. </script> 
Explanation
 
- On fileupload file selection, get the video file and create an ObjectUrl of that file.
- Add a video element on the page but keep it hidden.
- Set the src attribute of the video element with blob object.
- On click of validating button, you can now easily access that video element and check its duration property (which is specified in seconds) 
  1. if(seconds <= 120)    
  2. alert('Video duration should be more than 2 min');   
 
That’s it. I hope you will like this small blog stating the validation check for video duration on client side.