vue项目的自动播放背景音乐

<template>
	<audio preload="auto" loop id="audio" :src="require('../../assets/mp3/214.mp3')"></audio>
	<div @click="changeOn" :class="isOff?'isOff':'isOn'"></div>
</template>
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);
            }
    }
<style lang="less" scoped>
.isOn{
    width: 28px;
    height: 28px;
    position: fixed;
    z-index: 2000;
    top: 20px;
    left: 20px;
     -webkit-animation: rotating 1.2s linear infinite;
    animation: rotating 1.2s linear infinite;
    background: url("../assets/images/play.png") 0 0 no-repeat;
    background-size:100%; 
}
@keyframes rotating {
    from { -webkit-transform: rotate(0) }
    to { -webkit-transform: rotate(360deg) }
 }
@-webkit-keyframes rotating {
    from { -webkit-transform: rotate(0) }
    to { -webkit-transform: rotate(360deg) }
 }
.isOff{
    width: 28px;
    height: 28px;
    position: fixed;
    z-index: 2000;
    top: 20px;
    left: 20px;
    background: url("../assets/images/play.png") 0 -28px no-repeat;
    background-size:100%; 
}
</style>

bty…理论上vue是无法自动播放,需要借助微信的一个接口,注意在其他页面做监听无法接收到微信的回调,一定要在App.vue页面,放上这一段:

mounted() {
            this.audioAutoPlay('audio');
            // 自动播放音乐效果,解决微信自动播放问题
            document.addEventListener('touchstart',this.audioAutoPlay,false);
            document.addEventListener('WeixinJSBridgeReady', this.audioAutoPlay,false);
            let oAudio = document.querySelector("#audio");
            oAudio.onended = function () {//播放完毕,重新循环播放
                oAudio.load();
                oAudio.play();
            }
        },
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值