function playSound(){
var borswer = window.navigator.userAgent.toLowerCase();
if(!!window.ActiveXObject || "ActiveXObject" in window){
//IE内核浏览器
var strEmbed = '<embed name="embedPlay" src="../sounds/ding.wav" autostart="true" hidden="true" loop="false"></embed>';
if($("body").find("embed").length<=0){
$("body").append(strEmbed);
}else{
$("body").find("embed").remove();
$("body").append(strEmbed);
}
var embed = document.embedPlay;
//浏览器不支持 audion,则使用 embed 播放
embed.volume = 100;
}else{
//非IE内核浏览器
var strAudio = "<audio id='audioPlay' src='../sounds/ding.wav' hidden='true'>";
if($("body").find("audio").length<=0){
$("body").append(strAudio);
}
var audio = document.getElementById( "audioPlay" );
//浏览器支持 audion
audio.play();
}
}
chrome限制自动播放声音解决办法:
1. 进入网站设置,声音设为允许。
2. 写方法判断是否有自动播放权限,若没有则诱导用户对网站产生交互,以便正常播放声音。此方法每次进入网站都需产生交互才可正常播放声音。
function getSoundAccess(){
var strAudio = "<audio id='audioPlay' src='./images/sounds/sound.mp3' hidden='true'>";
if($("body").find("audio").length<=0){
$("body").append(strAudio);
}
var audio = document.getElementById( "audioPlay" );
var promise = audio.play();
if(promise !== undefined) {
promise.then(function(){
//audio.play();
}).catch(function(){
//此处进行弹窗提醒,诱导用户对网站进行点击
})
}
}