微信网页背景音乐及互动音乐自动播放

因为移动端的普及,在制作微信 H5 及微信互动如:摇一摇时,会涉及到页面中添加音乐,然后现在在手机中,为了避免流量流失情况,安卓和苹果系统都已禁止视频的自动播放了,

解决方案:

    监听 DOM 加载,在DOM 加载之后来监听微信的 WeixinJSBridgeReady ,代码如下:

      document.addEventListener('DOMContentLoaded',function (){
        function audioAutoPlay(){
          var audioElem = document.getElementById('mail');
          audioElem .play();
          document.addEventListener("WeixinJSBridgeReady", function () {

            // 可在这里对 audioElem 进行 src 赋值   

            audioElem .play();
          }, false);
        }
          audioAutoPlay();
      });

摇一摇:

  var SHAKE_THRESHOLD = 300,

  last_update = 0,

  x = y = z = last_x = last_y = last_z = 0,

  function deviceMotionHandler(eventData) {
    var acceleration = eventData.accelerationIncludingGravity;
    var curTime = new Date().getTime();

    if ((curTime - last_update) > 500) { //多次移动事件中取两个点的事件间隔
      var diffTime = curTime - last_update;
      last_update = curTime;

      x = acceleration.x;
      y = acceleration.y;
      z = acceleration.z;
      //var speed = Math.abs(x + y + z - last_x - last_y - last_z) / (diffTime * 1000);

      var dist = Math.sqrt((x-last_x)*(x-last_x)+(y-last_y)*(y-last_y)+(z-last_y)*(z-last_y))
      var speed = dist/diffTime*10000;

      if (speed > SHAKE_THRESHOLD) { 
        alert('摇一摇显示');

        audioAutoPlay();
      }
      last_x = x;
      last_y = y;
      last_z = z;
    }
  }

 

posted @ 2018-12-12 15:36  白小奇  阅读(1021)  评论(0编辑  收藏  举报