因为是全局的背景音乐,所以控制音乐的图标和音乐资源都应该在App.vue中
<template>
<div id="app">
<img
:class="['musicicon', isOff ? '' : 'rotateimg']"
src="./assets/img/musicbtn.png"
@click="changeOn"
/>
<router-view />
<audio
id="audio"
src="./assets/media/bgm.mp3"
preload
controls
loop
hidden
></audio>
</div>
</template>
这里因为是公众号页面,所以借助微信提供的sdk来实现音乐自动播放。
首先,先安装 weixin-js-sdk ;
npm i weixin-js-sdk -S
然后,在页面的JS中引入,并使用:
<script>
// 引入weixin-js-sdk
import wx from "weixin-js-sdk";
export default {
name: "App",
data() {
return {
isOff: true,
};
},
mounted() {
// 自动播放音乐效果,解决微信自动播放问题
document.addEventListener("touchstart", this.audioAutoPlay, false);
document.addEventListener("WeixinJSBridgeReady", this.audioAutoPlay, false);
let oAudio = document.querySelector("#audio");
oAudio.onended = function () {
//播放完毕,重新循环播放
oAudio.load();
oAudio.play();
};
},
methods: {
// 点击图标控制音乐播放暂停
changeOn() {
let oAudio = document.querySelector("#audio");
if (this.isOff) {
oAudio.play(); //让音频文件开始播放
} else {
oAudio.pause(); //让音频文件暂停播放
}
this.isOff = !this.isOff;
},
// 自动播放
audioAutoPlay() {
let audio = document.getElementById("audio");
this.isOff = false;
audio.play();
document.removeEventListener("touchstart", this.audioAutoPlay);
},
},
};
</script>
部分css:
.musicicon {
position: absolute;
top: 1.5rem;
right: 2rem;
width: 55px;
height: 55px;
z-index: 9;
}
.rotateimg {
animation: rotateimgani 3s linear infinite;
}
@keyframes rotateimgani {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
素材,右键保存可以使用哦~
更新(Vue3)
<script setup>
import { RouterView } from 'vue-router'
import { onMounted, ref, watch } from 'vue'
const isOff = ref(true)
let micon = ref(new URL('@/assets/img/music_on.png', import.meta.url).href)
// 背景音乐管理器
function BGMAutoPlayMgr(url) {
this.audioContext = new (window.AudioContext ||
window.webkitAudioContext ||
window.mozAudioContext)()
this.sourceNode = null
this.buffer = null
this.isPlayingBGM = false
this.toggleBGM = function () {
if (typeof this.sourceNode == 'object') {
if (this.isPlayingBGM) {
this.sourceNode.stop()
this.isPlayingBGM = false
} else this._playSourceNode()
}
}
this._playSourceNode = function () {
const audioContext = this.audioContext
audioContext.resume()
const _sourceNode = audioContext.createBufferSource()
_sourceNode.buffer = this.buffer
_sourceNode.loop = true
_sourceNode.connect(audioContext.destination)
_sourceNode.start(0)
this.sourceNode = _sourceNode
this.isPlayingBGM = true
}
let loadAndAutoPlay = (audioUrl) => {
const audioContext = this.audioContext
const xhr = new XMLHttpRequest()
xhr.open('GET', audioUrl, true)
xhr.responseType = 'arraybuffer'
xhr.onreadystatechange = () => {
if (xhr.status < 400 && xhr.status >= 200 && xhr.readyState === 4) {
audioContext.decodeAudioData(xhr.response, (buffer) => {
this.buffer = buffer
// WeixinJSBridge 微信浏览器内置对象
WeixinJSBridge.invoke('getNetworkType', {}, () => this._playSourceNode())
})
}
}
xhr.send()
}
// 播放
loadAndAutoPlay(url)
loadAndAutoPlay = null
this.isOff = false //按钮状态
}
// 判断是否是安卓
const CheckIsAndroid = () => {
var browser = {
versions: (function () {
var u = navigator.userAgent,
app = navigator.appVersion
return {
//移动终端浏览器版本信息
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器 //u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
iPad: u.indexOf('iPad') > -1 //是否iPad
}
})()
}
//if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
// return false;
//}
if (browser.versions.android) return true
return false
}
// 初始化音乐自动播放
const initBGM = () => {
const bgm = new BGMAutoPlayMgr(new URL('@/assets/media/bgm.mp3', import.meta.url).href)
setTimeout(() => {
if (CheckIsAndroid()) {
//如果是Android
micon.value = new URL('@/assets/img/music_on.png', import.meta.url).href
bgm.toggleBGM()
}
}, 500)
let ctrlbtn = document.getElementById('ctrlbtn')
// 点击按钮控制音乐播放/暂停
ctrlbtn.addEventListener('click', () => {
bgm.toggleBGM()
isOff.value = !isOff.value
})
}
watch(isOff, (newVal) => {
if (newVal) {
micon.value = new URL('@/assets/img/music_on.png', import.meta.url).href
} else {
micon.value = new URL('@/assets/img/music_off.png', import.meta.url).href
}
})
onMounted(() => {
initBGM()
})
</script>
<template>
<div class="musicicon">
<img :src="micon" id="ctrlbtn" />
</div>
<RouterView />
</template>
<style lang="scss">
.musicicon {
position: absolute;
top: 30px;
right: 30px;
width: 60px;
height: 60px;
z-index: 9;
border-radius: 50%;
overflow: hidden;
img {
display: block;
width: 100%;
}
}
</style>