Javascript如何预加载声音?

JavaScript09

Javascript如何预加载声音?,第1张

声音预加载,可以通过绕一下的方式去实现它,就是首先在头部构建你所需要加载的声音,然后添加对应的bgsound对象,让其同步加载,当声音全部加在完后,html回去执行window.onload动作,这个时候,声音已经在本地IE缓存中,然后在onload中删除预加载的bgsound对象,这样就是先了声音的预加载。

你在测试的时候可以先清空IE缓存,然后执行代码,再查看缓存。

代码如下:

<HTML>

<HEAD>

<TITLE>New Document </TITLE>

<bgsound volume='-5000' id='bgsound1' loop='1' src="http://localhost:8088/bpelDemo/aaa.mp3">

<bgsound volume='-5000' id='bgsound2' loop='1' src="http://localhost:8088/bpelDemo/bbb.mp3">

<bgsound volume='-5000' id='bgsound3' loop='1' src="http://localhost:8088/bpelDemo/ccc.mp3">

<bgsound volume='-5000' id='bgsound4' loop='1' src="http://localhost:8088/bpelDemo/ddd.mp3">

</HEAD>

<BODY>

<script>

function window.onload(){

var bgSoundObj = document.getElementById("bgsound1")

bgSoundObj.src=""

bgSoundObj.volume=1

//删除多余的bgsound对象

var bgSoundObjs = document.getElementsByTagName("bgsound")

for(var i=1i<bgSoundObjs.lengthi++){

bgSoundObjs[i].removeNode()

}

alert("目前所有音乐加载完成,可以去IE缓存查看加载MP3文件")

}

</script>

声音已经加载,播放无需重新加载<p>

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/aaa.mp3"' value="music1">

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/bbb.mp3"' value="music2">

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/ccc.mp3"' value="music3">

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/ddd.mp3"' value="music4">

</script>

</BODY>

</HTML>

可以用<bgsound>标签。

<html>

  <head>

    <script>

       function init(){

          if(判断条件有消息){

                 document.getElementById("sound").src="sound.wav"

                 或者document.all.sound.src="sound.wav"

                 或者document.getElementsByName("*").sound.src="sound.wav"

                     }

                 }

    </script>

  </head>

  <body>

    <bgsound id="sound">

  </body>

</html>

这样就可以播放了默认情况下不会循环。如果使用<embed>也可以使用上面的想法

<embed id="sound" src="msg.wav" width="42" height="35" hidden="true" autostart="false"></embed>

如果是ie就直接写document.getElementById("sound").play()

如果是mozilla-firefox就就把document.getElementById("sound").autostart=true