HTML5实现MP3上传前的预览和播放时长的获取

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8"/>  
  5.     <title></title>  
  6.     <script language="JavaScript" src="http://code.jquery.com/jquery-1.11.0.js"></script>  
  7.     <script>  
  8.         $(function () {  
  9.             $("#test").change(function () {  
  10.                 var objUrl = getObjectURL(this.files[0]);  
  11.                 $("#audio").attr("src", objUrl);  
  12.                 $("#audio")[0].play();  
  13.                 $("#audio").show();  
  14.                 getTime();  
  15.             });  
  16.         });  
  17.         <!--获取mp3文件的时间 兼容浏览器-->  
  18.         function getTime() {  
  19.             setTimeout(function () {  
  20.                 var duration = $("#audio")[0].duration;  
  21.                 if(isNaN(duration)){  
  22.                     getTime();  
  23.                 }  
  24.                 else{  
  25.                     console.info("该歌曲的总时间为:"+$("#audio")[0].duration+"秒")  
  26.                 }  
  27.             }, 10);  
  28.         }  
  29.         <!--把文件转换成可读URL-->  
  30.         function getObjectURL(file) {  
  31.             var url = null;  
  32.             if (window.createObjectURL != undefined) { // basic  
  33.                 url = window.createObjectURL(file);  
  34.             } else if (window.URL != undefined) { // mozilla(firefox)  
  35.                 url = window.URL.createObjectURL(file);  
  36.             } else if (window.webkitURL != undefined) { // webkit or chrome  
  37.                 url = window.webkitURL.createObjectURL(file);  
  38.             }  
  39.             return url;  
  40.         }  
  41.     </script>  
  42. </head>  
  43. <body>  
  44. <input id="test" type="file" multiple="multiple"/>  
  45. <audio id="audio" controls="" style="display: none;"></audio>  
  46. </body>  
  47. </html>