(开始与关闭之间的切换效果)
先看一段代码:
html代码:
<div>
<audio id="audio" autoplay="autoplay" loop="loop">
<source src="music/xxx.mp3"/>
</audio>
</div>
<div id="music">
<img src="images/xxx.png" alt="" id="musicicon"/>
</div>
JS代码:
var myAudio = document.getElementById("audio");
myAudio.play();
//音乐的暂停与播放
var musicBtn = document.getElementById("music");
var musicIcon = document.getElementById("musicicon");
musicBtn.addEventListener("touchstart", playPause, false);
function playPause() {
if (myAudio.paused) {
myAudio.play();
music_status = 0;
musicIcon.src = "images/xxx.png";
} else {
myAudio.pause();
music_status = 1;
musicIcon.src = "images/xxx.png";
}
}
来到这里, 一般情况下,这样在微信就可以自动播放了,但是有一些iPhone机不可以,微信要用到“jweixin-1.0.0.js”这个js.
//微信必须加入Weixin JSAPI的WeixinJSBridgeReady才能生效
document.addEventListener("WeixinJSBridgeReady", function () {
myAudio.play();
// document.getElementById('video').play(); //视频自动播放
}, false);
var EventUtil = {
addHandler: function (element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
};
(function () {
EventUtil.addHandler(window, "pageshow", function (event) {
myAudio.play();
});
})();