安卓/IOS微信环境H5背景音乐自动播放

141 阅读1分钟

网上找的解决办法

// 兼容ios & 安卓
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(
  'https://www.i-hudong.com/www/founoll/audio/5c89a08f6dd3056907.mp3',
);

// 切换播放状态
function toggleBGM() {
  bgm.toggleBGM();
}