Skip to content
Advertisement

How to get audio.duration from a player and save it to a div on a click?

I’ve been looking for a way to get the duration of a MP3 file that’s hosted remotely and I found answer from another question (How can I get the html5 audio’s duration time) and now I’m trying to see if I make it work.

I’m hung up this part:

  $(document).ready(function() {
     var audio = $("#audio-1")[0];
     $("#audio-1").on("loadedmetadata", function() {
        alert(audio.duration);
     }); 
  });

What that code does is getting the duration of a MP3 file and display it in the console. What I’m trying to do get the duration of the MP3 file when you click on a button and save that data into a ”.

Here’s my code so far:

$(document).ready(function() {
   var audio = $("#audio-1")[0];
  $("#click").on("click", function() {
   $("#audio-1").on("loadedmetadata", function() {
   $(".duration").data{(audio.duration)};
   }); 
  });
});
.duration {height:20px;border:1px solid #ccc}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id="audio-1" src="https://media.acast.com/dth/weekinreviewfortheweekof6-21-21-dth/media.mp3" preload="metadata"></audio>

Duration:
<div class="duration"></div>

<button id="click">Click</button>

Advertisement

Answer

$(function(){
    $('#btn').click(function() {
       var audio = $("#audio-1")[0];
      
            $("#duration").html(audio.duration);
    });
});
<html>
  <head>
    <title>First Pen</title>
  </head>
  <body>
    <div>
      <div id="duration"></div>

<button id="btn">Click</button>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id="audio-1" src="https://media.acast.com/dth/weekinreviewfortheweekof6-21-21-dth/media.mp3" preload="metadata"></audio>
    </div>
  </body>
</html>

I did this and it worked.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement