首頁  >  文章  >  web前端  >  為你的html5網頁加入音效範例_html5教學技巧

為你的html5網頁加入音效範例_html5教學技巧

WBOY
WBOY原創
2016-05-16 15:48:151782瀏覽

為互動添加適當的音效,常常能改善使用者體驗。在我們所熟悉的windows裡,清空回收站的碎紙聲就是很好的例子。
以下是利用HTML5, Jquery,為頁面加上音效的小元件(只是加上音效,不是播放器)。
其實很簡單,就是利用HTML5中的audio標籤,播放聲音。不過為了照顧IE 6-8,還是用了bgsound。
相容於所有主流瀏覽器(非主流不在考慮之列了)
閒話少說,上碼:


複製程式碼
程式碼如下:

播放
<script><br />/*Play sound component*/<br />/*<br /> * profile: JSON, {src:'chimes.wav',altSrc :'',loop:false}<br /> * <br /> * setSrc: Function, set the source of sound<br /> * play: Function, play sound<br /> */<br />if (!FUI){<br /> var FUI = {};<br />}<br />FUI.soundComponent=function(profile){<br /> this.profile={<br /> src:'',    〜   〜 〜〜 〜 〜 〜 〜 〜 〜〜 〜] '',         //備選音訊檔案位址(不同瀏覽器支援的音訊格式不同,可見附表)<br /> loop:false        //是否循環播放,這個參數現在沒有用上。 if(profile) {<br /> $.extend(this.profile,profile);<br /> }<br /> this.soundObj=null;<br /> this.isIE = !-[1,];<br /> / *這個方法是前輩大牛發明的,利用ie跟非ie中JScript處理數組最後一個逗號“,”的差異,<br /> 不過對於IE 9,這個辦法就無效了,但此處正合我用,因為IE 9支援audio*/<br /> this.init();<br />};<br />FUI.soundComponent.prototype={<br /> init:function(){<br /> this._setSrc();<br /> }, <br /> _setSrc:function(){<br /> if(this.soundObj){ <br /> if(this.isIE){<br /> this.soundObj[0].src=this.profile. ; <br /> }else{<br /> this.soundObj[0].innerHTML='<source src="' this.profile.src '" /><br /><source src="' this.profile.altSrc ' " />'; <br /> } <br /> }else{<br /> if(this.isIE){<br /> this.soundObj=$<br />('<bgsound volume="-10000" loop="1 " src="' this.profile.src '">').appendTo('body');<br /> //-10000是音量的最小值。先把音量關到最小,免得一載就叮的一聲,嚇到人。 <br /> }else{<br /> this.soundObj=$('<audio preload="auto" autobuffer><br /><source src="' this.profile.src '" /><br /><source src= "' this.profile.altSrc '" /><br />').appendTo('body');<br /> } <br /> } <br /> },<br /> setSrc:function(src,function(src, altSrc){<br /> this.profile.src=src;<br /> if(typeof altSrc!='undefined'){<br /> this.profile.altSrc=altSrc;<br /> } <br /> this.profile.altSrc=altSrc;<br /> } <br /> this.this_Src( );<br /> },<br /> play:function(){<br /> if(this.soundObj){<br /> if(this.isIE){<br /> this.soundObj[0].volume = 1; //把音量打開。 <br /> this.soundObj[0].src = this.profile.src;<br /> }else{<br /> this.soundObj[0].play();<br /> }<br /> }<br /> } <br />};<br />var sd=new FUI.soundComponent({src:'ding.wav',altSrc:'ding.mp3'});<br />$('.fui-btn').bind( 'click',function(e){<br /> sd.play();<br />}); <br /></script>

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn