DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
為 HTML5 網頁加上互動音效:打造一個輕量播放元件
編輯:HTML5詳解     

在介面互動裡安排恰到好處的音效,往往能讓操作手感提升一個檔次。最經典的例子莫過於 Windows 清空回收筒時那聲碎紙音——聲音一出現,使用者立刻就知道事情辦完了。

本文動手做一個小元件:用 HTML5 搭配 jQuery,替頁面加上「播放音效」的能力。要先說清楚,它不是音樂播放器,而是在使用者操作時被觸發的短音效。

核心思路

原理並不複雜,主要靠 HTML5 的 audio 標籤來發聲。為了照顧不認得 audio 的 IE 6–8,程式另外準備了 bgsound 當退路,如此一來主流瀏覽器都能正常作動。

完整程式碼

<a href="#" class="fui-btn">播放</a>
<script>
/*Play sound component*/
/*
* profile: JSON, {src:'chimes.wav',altSrc:'',loop:false}
* setSrc: Function, set the source of sound
* play: Function, play sound
*/
if (!FUI){
var FUI = {};
}
FUI.soundComponent=function(profile){
this.profile={
src:'', //音訊檔位置
altSrc:'', //備選音訊檔位置(不同瀏覽器支援的格式不同)
loop:false //是否迴圈播放
};
if(profile) {
$.extend(this.profile,profile);
}
this.soundObj=null;
this.isIE = !-[1,];
/*利用 IE 與非 IE 在 JScript 處理陣列最後一個逗號上的差異來判斷,
  IE9 之後這招無效,但此處正好合用,因為 IE9 已支援 audio */
this.init();
};
FUI.soundComponent.prototype={
init:function(){
this._setSrc();
},
_setSrc:function(){
if(this.soundObj){
if(this.isIE){
this.soundObj[0].src=this.profile.src;
}else{
this.soundObj[0].innerHtml='<source src="'+this.profile.src+'" />
<source src="'+this.profile.altSrc+'" />';
}
}else{
if(this.isIE){
this.soundObj=$('<bgsound volume="-10000" loop="1" src="'+this.profile.src+'">').appendTo('body');
//-10000 是音量最小值,先把音量關掉,免得頁面一載入就叮一聲嚇人
}else{
this.soundObj=$('<audio preload="auto" autobuffer>
<source src="'+this.profile.src+'" />
<source src="'+this.profile.altSrc+'" />
</audio>').appendTo('body');
}
}
},
setSrc:function(src,altSrc){
this.profile.src=src;
if(typeof altSrc!='undefined'){
this.profile.altSrc=altSrc;
}
this._setSrc();
},
play:function(){
if(this.soundObj){
if(this.isIE){
this.soundObj[0].volume = 1; //把音量打開
this.soundObj[0].src = this.profile.src;
}else{
this.soundObj[0].play();
}
}
}
};
var sd=new FUI.soundComponent({src:'ding.wav',altSrc:'ding.mp3'});
$('.fui-btn').bind('click',function(e){
sd.play();
});
</script>

幾個實作細節

  • profile 裡的 src 與 altSrc 用來放置不同格式,例如 mp3 與 wav 互為備援,瀏覽器會挑自己能播的那一份。
  • 偵測 IE 的 !-[1,] 是前輩留下的小技巧,靠的是 IE 與非 IE 解析陣列尾端逗號的差異。
  • 建立 bgsound 時先把音量壓到 -10000,可以避免頁面一開就發出聲音;真正要播放時再把 volume 調回來。

使用方式很直覺:new 出物件、傳入音訊路徑,再把 play() 綁到你想要的事件上即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved