网页制作 
首页 > 网页制作 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/30 浏览:3 次 )

为交互添加恰当的音效,常常能改善用户体验。在我们所熟悉的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="/UploadFiles/2021-03-30/'+this.profile.src+'"><source src="'+this.profile.altSrc+'"> }
}else{
if(this.isIE){
this.soundObj=$
('<bgsound volume="-10000" loop="1" src="'+this.profile.src+'"> //-10000是音量的最小值。先把音量关到最小,免得一加载就叮的一声,吓到人。
}else{
this.soundObj=$('<audio preload="auto" autobuffer>
<source src="/UploadFiles/2021-03-30/'+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浏览器成为支持html5的浏览器的解决方法(使用html5shiv)
下一篇:使用jquery实现HTML5响应式导航菜单教程
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网