audio.js 2.72 KB
export function Audio(url, callBack) {
  // this.IsIOS = false
  this.IsIOS = window.$IsIOS
  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' && !this.IsIOS) {
      if (this.isPlayingBGM || off) {
        this.sourceNode && this.sourceNode.stop()
        this.isPlayingBGM = false
        console.log('暂停——————————————', this.sourceNode)
      } else this._playSourceNode()
    } else {
      if (this.audioContext.paused && !off) this.audioContext.play()
      else this.audioContext.pause()
    }
  }
  this.stopVideo = function () {
    if (typeof this.sourceNode == 'object' && !this.IsIOS) {
      if (this.isPlayingBGM) {
        this.sourceNode && this.sourceNode.stop()
        this.isPlayingBGM = false
        console.log('暂停——————————————', this.sourceNode)
      }
    } else this.audioContext.pause()
  }
  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 => {
    let _this = this
    if (!this.IsIOS) {
      const audioContext = this.audioContext
      const xhr = new XMLHttpRequest()
      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()
    } else {
      this.audioContext = document.getElementById('audio')
      this.audioContext.src = url
      this.audioContext.click()
      wx.getNetworkType({
        success: function (res) {
          _this.audioContext.play()
          callBack()
        }
      })
    }
  }
  loadAndAutoPlay(url)
  loadAndAutoPlay = null
}