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

时间:2025-02-21 08:13:03
<template>
	<audio preload="auto" loop  :src="require('../../assets/mp3/214.mp3')"></audio>
	<div @click="changeOn" :class="isOff?'isOff':'isOn'"></div>
</template>
data() {
      return {
          isOff:true
      }
    },
mounted() {
        // 自动播放音乐效果,解决微信自动播放问题
       ('touchstart',,false);
       ('WeixinJSBridgeReady', ,false);
       let oAudio = ("#audio");
         = function () {//播放完毕,重新循环播放
            ();
            ();
        }
    },
methods: { 
           changeOn(){
                let oAudio = ("#audio");
               if(){
                ();//让音频文件开始播放     
               }else{
                ();//让音频文件暂停播放 
               }
                = !;
           },
           audioAutoPlay() {
                let audio = ('audio');
                     = false;
                    ();
                ('touchstart',);
            }
    }
<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/") 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/") 0 -28px no-repeat;
    background-size:100%; 
}
</style>

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

mounted() {
            ('audio');
            // 自动播放音乐效果,解决微信自动播放问题
            ('touchstart',,false);
            ('WeixinJSBridgeReady', ,false);
            let oAudio = ("#audio");
             = function () {//播放完毕,重新循环播放
                ();
                ();
            }
        },