audio.js 2.09 KB
export function Audio (url, callBack) {
  this.audioContext = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)()
  this.sourceNode = null
  this.buffer = null
  this.isPlayingBGM = false
  this.toggleBGM = function (off) {
    if (typeof this.sourceNode == 'object') {
      if (this.isPlayingBGM || off) {
        this.sourceNode.stop()
        this.isPlayingBGM = false
        console.log('暂停——————————————', this.sourceNode)
      } else this._playSourceNode()
    }
  }
  this.stopVideo = function () {
    if (typeof this.sourceNode == 'object') {
      if (this.isPlayingBGM) {
        this.sourceNode.stop()
        this.isPlayingBGM = false
        console.log('暂停——————————————', this.sourceNode)
      }
    }
  }
  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
    console.log('播放——————————————', this.sourceNode)
    this.isPlayingBGM = true
  }
  let loadAndAutoPlay = (audioUrl) => {
    const audioContext = this.audioContext
    const xhr = new XMLHttpRequest()
    let _this = this
    xhr.open('GET', `${audioUrl}?v=${Date.now()}`, true)
    xhr.responseType = 'arraybuffer'
    xhr.onreadystatechange = () => {
      if (xhr.status < 400 && xhr.status >= 200 && xhr.readyState === 4) {
        audioContext.decodeAudioData(xhr.response, buffer => {
          this.buffer = buffer
          if (buffer) {
            if (wx.getNetworkType) wx.getNetworkType({
              success: function (res) {
                _this._playSourceNode()
                callBack()
              }
            })
            else {
              _this._playSourceNode()
              callBack()
            }
          }
        })
      }
    }
    xhr.send()
  }
  loadAndAutoPlay(url)
  loadAndAutoPlay = null
}