Audio File Info / Duration w/ File API

How to use HTML5's <audio> element and File API to get information for an audio file, including the duration of a .mp3.

by HemalathaThanigaivel

HTML

<script src="https://rawgithub.com/moment/moment/2.2.1/min/moment.min.js"></script>
<p>Select a .mp3 file</p>
<input type="file" id="file" />

<audio id="audio"></audio>

<p>
  <label>File Name:</label>
  <span id="filename"></span>
</p>

<p>
  <label>File Type:</label>
  <span id="filetype"></span>
</p>

<p>
  <label>File Size:</label>
  <span id="filesize"></span>
</p>

<p>
  <label>Song Duration:</label>
  <span id="duration"></span>
</p>

CSS

audio {
    display: none;
}

JavaScript

var objectUrl;

$("#audio").on("canplaythrough", function(e){
    var seconds = e.currentTarget.duration;
    var duration = moment.duration(seconds, "seconds");
    
    var time = "";
    var hours = duration.hours();
    if (hours > 0) { time = hours + ":" ; }
    
    time = time + duration.minutes() + ":" + duration.seconds();
    $("#duration").text(time);
    
    URL.revokeObjectURL(objectUrl);
});

$("#file").change(function(e){
    var file = e.currentTarget.files[0];
   
    $("#filename").text(file.name);
    $("#filetype").text(file.type);
    $("#filesize").text(file.size);
    
    //objectUrl = URL.createObjectURL(file);
    $("#audio").prop("src", 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_5MG.mp3');
});