js判断音频文件是否加载完成主要是根据这个函数
myAudio.addEventListener('canplaythrough', function(e){
//加载完成
}, false);
如下我已经封装成一个函数
/*
*@desc 加载音频文件
*@param url:音频地址
*@param aid:音频的id 可选
@param aloop:是否循环播放 可选 true|false
*/
function music_creat(url,aid,aloop){
var myAudio = new Audio();
myAudio.src = url;
if(typeof(aid) !== 'undefined'){
myAudio.id = aid;
}
if(typeof(aloop) !== 'undefined'){
myAudio.loop = aloop;
}
myAudio.load();//预加载文件
//myAudio.play();//播放音频文件 只有通过点击事件触发才会生效
//myAudio.pause();//暂停播放
document.getElementById("music").appendChild(myAudio);
if(myAudio.canPlayType('audio/mpeg') == "probably"){
window[aid] = myAudio;
}
myAudio.addEventListener('canplaythrough', function(e){
window[aid] = myAudio;
}, false);
}
预览一个例子
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>音频文件加载</title> </head> <body> <a href="javascript:;" onClick="music_play('music');">点我试试</a> <div id="music"></div> <script type="text/javascript"> /* *@desc 加载音频文件 *@param url:音频地址 *@param aid:音频的id 可选 @param aloop:是否循环播放 可选 true|false */ function music_creat(url,aid,aloop){ var myAudio = new Audio(); myAudio.src = url; if(typeof(aid) !== 'undefined'){ myAudio.id = aid; } if(typeof(aloop) !== 'undefined'){ myAudio.loop = aloop; } myAudio.load();//预加载文件 //myAudio.play();//播放音频文件 只有通过点击事件触发才会生效 //myAudio.pause();//暂停播放 document.getElementById("music").appendChild(myAudio); if(myAudio.canPlayType('audio/mpeg') == "probably"){ window[aid] = myAudio; } myAudio.addEventListener('canplaythrough', function(e){ window[aid] = myAudio; }, false); //return myAudio; } function music_play(name,mmuted){ if(typeof(window[name]) !== 'undefined'){ var thisobj = window[name]; thisobj.load(); if(typeof(mmuted) !== 'undefined'){ thisobj.muted = mmuted; } thisobj.play(); } } var url = 'https://tts.baidu.com/text2audio?tex=%E6%81%AD%28gong1%29%E5%96%9C%28xi3%29%E5%8F%91%28fa1%29%E8%B4%A2%28cai2%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&per=4100'; var aid = 'music'; music_creat(url,aid); </script> </body> </html>