<template>
<audio src="./static/music.mp3" id="bgMusic" preload="auto" loop></audio>
<div class="bgMusicBtn" @click="bgMusicPlayOrPause('bgMusic')">
<img :src="playFlag ? playImg : pauseImg" :class="{rotate: playFlag}">
</div>
</template>
export default {
data() {
return {
playFlag: true,
playImg: require('../../static/play.png'),
pauseImg: require('../../static/pause.png'),
clickMusicBtn: false
}
},
mounted() {
this.audioAutoPlay('bgMusic');
document.addEventListener("visibilitychange", (e) => { // 兼容ios微信手Q
if (this.clickMusicBtn) { // 点击了关闭音乐按钮
if (this.playFlag) {
this.audioAutoPlay('bgMusic');
this.playFlag = true;
} else {
this.audioPause('bgMusic');
this.playFlag = false;
}
text.innerHTML = e.hidden;
if (e.hidden) { // 网页被挂起
this.audioAutoPlay('bgMusic');
this.playFlag = true;
} else { // 网页被呼起
this.audioPause('bgMusic');
this.playFlag = false;
}
} else { // 未点击关闭音乐按钮
if (this.playFlag) {
this.audioPause('bgMusic');
this.playFlag = false;
} else {
this.audioAutoPlay('bgMusic');
this.playFlag = true;
}
text.innerHTML = e.hidden;
if (e.hidden) { // 网页被挂起
this.audioPause('bgMusic');
this.playFlag = false;
} else { // 网页被呼起
this.audioAutoPlay('bgMusic');
this.playFlag = true;
}
}
});
},
methods: {
bgMusicPlayOrPause(id) {
this.clickMusicBtn = !this.clickMusicBtn;
if (this.playFlag) {
this.audioPause(id);
this.playFlag = false;
} else {
this.audioAutoPlay(id);
this.playFlag = true;
}
},
audioPause(id) {
var audio = document.getElementById(id);
audio.pause();
document.addEventListener("WeixinJSBridgeReady", function () {
audio.pause();
}, false);
document.addEventListener('YixinJSBridgeReady', function () {
audio.pause();
}, false);
},
audioAutoPlay(id) {
var audio = document.getElementById(id);
audio.play();
document.addEventListener("WeixinJSBridgeReady", function () {
audio.play();
}, false);
document.addEventListener('YixinJSBridgeReady', function () {
audio.play();
}, false);
}
}
}