Search code examples
javascriptjqueryajaxmp3html5-audio

How to get file size of a remote mp3 using jQuery?


I'm looking for a way to read a MP3 that's hosted remotely. I found something (How to get file size from url using jquery) that can read it without downloading:

var req;
req = $.ajax({
type: "HEAD",
url: $("#url").val(),
success: function () {
  alert("Size is " + request.getResponseHeader("Content-Length"));
}
});

But I'm having difficulty getting it work with my code. What I'm trying to do is that when you click on button, it gets the file size of a remote MP3 and save the data to a div.

Here's what I've gotten so far:

$(function() {
  $('#btn').click(function() {
    var audio = $("#audio-1")[0];
    var request;
    $("#duration").html(audio.duration);
    
    request = $.ajax({
      type: "HEAD",
      url: $("#audio-1").val(),
      success: function() {
        $("#size").html(request.getResponseHeader("Content-Length"));
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Duration: <div id="duration"></div>
Size: <div id="size"></div>

<button id="btn">Click</button>
<audio id="audio-1" src="https://media.acast.com/dth/weekinreviewfortheweekof6-21-21-dth/media.mp3" preload="metadata"></audio>


Solution

  • The issue is because you're attempting to access the val() of the audio element, and they do not have a value. To fix this, get the src property instead:

    $(function() {
      var $audio = $("#audio-1");
    
      $('#btn').click(function() {
        $("#duration").html($audio.prop('duration'));
    
        $.ajax({
          type: "HEAD",
          url: $audio.prop('src'),
          success: function(data, status, request) {
            $("#size").html(request.getResponseHeader("Content-Length"));
          }
        });
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Duration:
    <div id="duration"></div>
    Size:
    <div id="size"></div>
    
    <button id="btn">Click</button>
    <audio id="audio-1" src="https://media.acast.com/dth/weekinreviewfortheweekof6-21-21-dth/media.mp3" preload="metadata"></audio>

    Note that you can access the request object from the third argument of the success handler function. The code is logically identical, just slightly cleaner as you avoid the need to declare the variable at the higher scope.