微信浏览器中实现音乐自动播放

近日微信浏览器中h5页面实现音乐自动播放,试了好多方法,最后还是下面方法比较好用

引入微信sdk

<script src="http: //res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
var $myaudio;
function getMusic(el, showMusic = true) {
     
    var className = 'play'
    // var trigger = 'ontouchend' in document ? 'touchstart' : 'click'
    var $musci = document.createElement('div')
    $myaudio = document.createElement('audio')

    // function start() {
     
    //     document.removeEventListener(trigger, start, false)
    //     if (!$audio.paused) return
    //     // $audio.play()
    // }

    function toggle() {
     
        if (!$audio.paused) return $audio.pause()
        $myaudio.currentTime = 0
        $myaudio.play()
    }

    function play() {
     
        $musci.classList.add(className)
    }

    function pause() {
     
        $musci.classList.remove(className)
    }

    $musci.className = 'music-icon'

    $myaudio.src = '';
    $myaudio.loop = true;
    document.body.appendChild($musci)
    $myaudio.setAttribute("id", "music");
    document.getElementById(el).appendChild($myaudio)
    $myaudio.addEventListener('play', play, false)
    $myaudio.addEventListener('pause', pause, false)
    $myaudio.addEventListener('ended', pause, false)
    $musci.addEventListener('click', toggle, false)
    if (showMusic) {
     
        $myaudio.load();
        $myaudio.play();
        document.addEventListener("WeixinJSBridgeReady", function () {
     
            $myaudio.load();
            $myaudio.play();
        }, false);

        // document.addEventListener(trigger, start, false)
    }

}
export default getMusic

在vue文件中

export default {
     
 data() {
     
    return {
     
       showMp3: localStorage.getItem("showMp3") == "true" ? true : false,
    };
  },
 mounted() {
     
  
    if (!document.getElementById("music")) {
     
       if (!this.showMp3) {
     
        getMusic("mc_play", false);
      } else {
     
        getMusic("mc_play");
      }
    }
 }
};

你可能感兴趣的:(javascript)