js判断mp3音频文件audio是否加载完成
以下是代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script type="text/javascript"> function canPlayAudioMP3(src,callback){ try { var audio = new Audio(); //Shortcut which doesn't work in Chrome (always returns ""); pass through // if "maybe" to do asynchronous check by loading MP3 data: URI if(audio.canPlayType('audio/mpeg') == "probably") callback(true); return; //If this event fires, then MP3s can be played audio.addEventListener('canplaythrough', function(e){ callback(true); }, false); //If this is fired, then client can't play MP3s audio.addEventListener('error', function(e){ callback(false, this.error) }, false); //Smallest base64-encoded MP3 I could come up with (<0.000001 seconds long) audio.src = src; audio.load(); } catch(e){ callback(false, e); } } function getAllSrc(){ var src = "Track01.wav"; canPlayAudioMP3(src,function(type,msg){ console.log(type,msg); console.log(document.body); if(type === true){ var x = document.createElement("audio"); x.src = src; document.body.appendChild(x); x.play(); return; } }); } getAllSrc(); </script> </body> </html>