1

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Gregory Schultz
  • 864
  • 7
  • 24

1 Answers1

1

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    But also note that the audio WILL download to user's computer because it is in an audio tag – mplungjan Jun 28 '21 at 18:36
  • This is great! A good start for me but if the MP3 is over 98MB then it won't read the file. – Gregory Schultz Jun 29 '21 at 05:31
  • You could potentially convert the AJAX call to listen for `headers_received` state instead of `done` (which means converting to a native `XMLHttpRequest` instead of jQuery) however the file will most likely still be downloaded by the browser. – Rory McCrossan Jun 29 '21 at 07:54