Comment: This article mainly introduces the example of adding sound effects to your html5 web page. Friends who need it can refer to it.
Adding the right sound to the interaction often improves the user experience. In the windows we are familiar with, the sound of clearing the shredded paper in the recycling bin is a good example.
Here is a widget that uses HTML5 and Jquery to add sound effects to the page (just add sound effects, not a player).
In fact, it is very simple, it is to use the audio tags in HTML5 to play sounds. However, in order to take care of IE 6-8, I still used bgsound.
Compatible with all mainstream browsers (non-mainstream is not considered)
Less gossip, add the code:
<a href="#">Play</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:'', //Audio file address
altSrc:'', //Alternative audio file address (the audio formats supported by different browsers are different, see the attached table)
loop:false // Whether to play loop, this parameter is not useful now
};
if(profile) {
$.extend(this.profile,profile);
}
this.soundObj=null;
this.isIE = !-[1,];
/*This method was invented by a predecessor, using JScript in IE and non-IE to process the difference between the last comma of the array,
However, for IE 9, this method is invalid, but it is just right for me to use it because IE 9 supports 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 is the minimum volume. Turn the volume to the lowest level first, so as not to make a jingle sound as soon as it loads, which will scare people.
}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; //Open the volume.
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>