欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

为你的html5网页添加音效示例

程序员文章站 2023-12-05 17:37:58
这篇文章主要介绍了为你的html5网页添加音效示例,需要的朋友可以参考下... 14-04-03...

为交互添加恰当的音效,常常能改善用户体验。在我们所熟悉的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处理数组最后一个逗号“,”的差异,
不过对于ie 9,这个办法就无效了,但此处正合我用,因为ie 9支持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>