2015-12-01 46 views
1

我已經創建了一個框,我將在其中輸入音頻標籤的鏈接,然後點擊提交後,我需要音頻的長度。 但是,如果我給靜態url,那麼它給出的長度作爲回報,但是當我使用這種方法的文本框它不顯示長度請幫助。輸入url後的音頻長度

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例子。

回答

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>

http://jsbin.com/xicixo