Create a html5 audio and play it doesn't work

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 12:27:09

问题


I want create a html5 audio in dynamic and play it,here is the code:

 function playAnotherMusic(playUrl){
                var audioElement = document.createElement('audio'); 
                audioElement.setAttribute('src', playUrl); 
                audioElement.setAttribute('controls', true); 
                audioElement.setAttribute('preload', true); 
                audioElement.setAttribute('type', 'audio/mpeg'); 


                audioElement.addEventListener("load", function() { 
                audioElement.play(); 
                }, true);

                console.log(playUrl);
                audioElement.load();

  }

However it doesn't work,the firebug assigin me "HTTP "Content-Type" of "audio/mpeg" is not supported."

how can I solve this problem?


回答1:


You need to append the audio element to the an existing element. This would be something like

document.getElementById("my_audio_div").appendChild(audioElement);

Idealy, this should be done before you add the event listener, but after setting all the attributes

Also try audio/mp3 instead: audioElement.setAttribute('type', 'audio/mp3');




回答2:


You can't play mp3 files in firefox, it does not support them, you need an ogg version for firefox. Unless that changes, good to keep in mind.

Why doesn't Firefox support the MP3 file format in <audio>



来源:https://stackoverflow.com/questions/10407031/create-a-html5-audio-and-play-it-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!