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:
JavaScript
x
7
1
$(document).ready(function() {
2
var audio = $("#audio-1")[0];
3
$("#audio-1").on("loadedmetadata", function() {
4
alert(audio.duration);
5
});
6
});
7
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:
JavaScript
1
8
1
$(document).ready(function() {
2
var audio = $("#audio-1")[0];
3
$("#click").on("click", function() {
4
$("#audio-1").on("loadedmetadata", function() {
5
$(".duration").data{(audio.duration)};
6
});
7
});
8
});
JavaScript
1
1
1
.duration {height:20px;border:1px solid #ccc}
JavaScript
1
7
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<audio id="audio-1" src="https://media.acast.com/dth/weekinreviewfortheweekof6-21-21-dth/media.mp3" preload="metadata"></audio>
3
4
Duration:
5
<div class="duration"></div>
6
7
<button id="click">Click</button>
Advertisement
Answer
JavaScript
1
7
1
$(function(){
2
$('#btn').click(function() {
3
var audio = $("#audio-1")[0];
4
5
$("#duration").html(audio.duration);
6
});
7
});
JavaScript
1
14
14
1
<html>
2
<head>
3
<title>First Pen</title>
4
</head>
5
<body>
6
<div>
7
<div id="duration"></div>
8
9
<button id="btn">Click</button>
10
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
11
<audio id="audio-1" src="https://media.acast.com/dth/weekinreviewfortheweekof6-21-21-dth/media.mp3" preload="metadata"></audio>
12
</div>
13
</body>
14
</html>
I did this and it worked.