在使用audio时,存在一个问题,就是大部分IOS系统和少部分Android微信不支持自动播放。
使用的解决方案是:监听WeixinJSBridgeReady事件、DOMContentLoaded事件,直接上代码:
** HTML**
<div id="musicControl" class="musicPlay">
<a id="mc_play" >
<audio id="musicfx" src="mp3/yangguanghaitan.mp3" loop></audio>
</a>
</div>
** CSS **
// 音乐播放样式
@keyframes reverseRotataZ{
0%{-webkit-transform: rotateZ(0deg);}
100%{-webkit-transform: rotateZ(-360deg);}
}
#musicControl {
widows: .6rem;
height:.6rem;
position: absolute;; left:10px; top:20px;
margin-top:0;
z-index:99999999;
background-color: rgba(114, 114, 114, .65);
text-align: center;
border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
}
#musicControl a {
display:inline-block;
width:.6rem;
height:.6rem;
overflow:hidden;
background:url('../assets/i/play.png') no-repeat center;
background-size:100%;
}
#musicControl a audio{width:100%;height:.6rem;}
#musicControl.musicPlay { animation: reverseRotataZ 1.2s linear infinite;}
** JS **
原生结合jquery一起实现
document.addEventListener('DOMContentLoaded', function () {
function audioAutoPlay() {
let audio = document.getElementById('musicfx');
audio.play();
document.addEventListener("WeixinJSBridgeReady", function () {
audio.play();
}, false);
const xxEvents = ('ontouchstart' in window) ? { start: 'touchstart', move: 'touchmove', end: 'touchend' } : { start: 'mousedown', move: 'mousemove', end: 'mouseup' };
let musicBtn = $('#musicControl');
musicBtn.on(xxEvents.start, function (e) {
audio.paused ? audio.play() : audio.pause();
e.preventDefault();
});
audio.addEventListener('play',function(){
musicBtn.addClass('musicPlay');
})
audio.addEventListener('pause',function(){
musicBtn.removeClass('musicPlay');
})
}
audioAutoPlay();
});