【Vue 公众号网页设置全局背景音乐】

本文介绍了如何在微信公众号页面上通过weixin-js-sdk实现全局背景音乐的控制和自动播放功能,包括图标交互、音频预加载和事件监听等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为是全局的背景音乐,所以控制音乐的图标和音乐资源都应该在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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值