How to prevent HTML5 audio from predownload / streaming on load?

拈花ヽ惹草 提交于 2019-11-30 02:45:14
<audio controls="controls" preload="none">
  <source src="song.ogg" type="audio/ogg" />
  <source src="song.mp3" type="audio/mpeg" />
  Your browser does not support the audio element.
</audio> 

Note - preload="none" - can be used with VIDEO HTML5 and AUDIO HTML5.

The preload attribute is supported in all major browsers, except Internet Explorer and Opera.

MSIE still accounts for some 30% of all web traffic, so preload="none" is only a part solution. In a few pages where I had this problem, I add a small script to my page headers:

<script type="text/javascript">
function addAudio(t) {
  var l=t.innerHTML.length;
  var audioName=t.parentElement.id;
  if( t.children.length==0) {
    t.innerHTML=t.innerHTML+'&nbsp; &nbsp; <audio controls="controls"><source src="'+
      audioName+'.ogg" type="audio/ogg" /><source src="'+
      audioName+'.mp3" type="audio/mp3" /> No audio tag support</audio>';
  }
}
</script>

and then use DHMTL to dynamically add the audio tag, for example:

<li id="2_Lesson_1_Hello"><span onclick="addAudio(this)">Γεια σας</span></li>

What this does is to define a list item containing a text span. When the person browsing clicks on the spanned text, the javascript fires and appends the <audio> tag. You could alternatively use the onmouseover attribute so that the audio tag is added on hover.

Add the preload attribute to the generated code if you wish. This is the simple approach, but if you are already using jQuery on your webpage, I note that this offers elegant alternatives.

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