视频在H5页面在微信浏览器不能自动播放问题

  • Post author:
  • Post category:其他


//引用官方的JS文件
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

//正式方法
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.invoke("getNetworkType", {}, () => this._playSourceNode());
      });
    }
  }
  xhr.send();
 }
   loadAndAutoPlay(url);
   loadAndAutoPlay = null;
}

// 调用
const bgm = new BGMAutoPlayMgr('视频地址');
bgm.toggleBGM();



版权声明:本文为masterphp原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。