為互動環節加上恰當的音效,往往能顯著改善使用者體驗。我們熟悉的 Windows 系統就是個好例子——清空回收站時那聲碎紙音,總讓人印象深刻。
以下是一個利用 HTML5 與 jQuery 為頁面加上音效的小元件(注意,它只是用來播放音效,並非播放器)。
原理其實很簡單:善用 HTML5 的 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 處理數組最後一個逗號的差異來判斷 */
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');
}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>
這段代碼有幾個用心的小細節:初始時把音量設為最小值,避免一載入就「叮」地一聲嚇到使用者;IE 分支用 bgsound,其他瀏覽器則用 audio 標籤並提供備選音源,以應對不同瀏覽器對音頻格式的支援差異。
附表:各瀏覽器對常見音頻格式的支援情況
Ogg Vorbis No Yes Yes Yes No
MP3 Yes No No Yes Yes
Wav No Yes Yes Yes Yes