我创建了一个框,我将在其中输入音频标签的链接,然后在单击提交后我需要音频的长度。 但是,如果我给静态网址然后它给予长度作为回报,但当我使用这种方法的文本框时,它没有显示长度请帮助。
HTML
<input type="text" id="mp_source">
<input type="button" id="save" value="save">
<audio id="track" width="320" height="176" controls>
<source id="sourceMp3" type="audio/mp3"/>
</audio>
<p id="time"></p>
JS
<script type="text/javascript">
$(document).ready(function(){
$("#save").click(function(){
var get_source = $("#mp_source").val();
$("#sourceMp3").attr('src',get_source);
myFunction();
});
});
</script>
<script>
function
myFunction() {
var vid = document.getElementById("track");
var len = vid.duration/60;
var n = len.toFixed(2);
var res = n.split(".");
var result = res[0]+':'+res[1];
document.getElementById("time").innerHTML = result;
}
</script>
以下是fiddle示例。
答案 0 :(得分:1)
document.querySelector('button').onclick = function(){
var url = document.querySelector('input').value;
// create new audio to get the data from the file
var audio = new Audio();
// listen to the event that the broswer done to read the file
audio.addEventListener('loadedmetadata', function(e) {
// get the duration from the track
var duration = e.path[0].duration;
console.log(duration);
document.querySelector('#result').innerHTML = duration + 's';
});
audio.src = url;
//audio.play();
};
<input type="text" placeholder="Type url here" value="http://www.w3schools.com/html/horse.ogg" />
<button>Go</button>
<hr />
<div id="result"></div>