AudioContext 自动播放

  class Music {
    constructor(url, loop) {
      this.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext)
      this.url = url
      this.handle = {}
      this.loop = loop || false
      this.source = null
      this.loadMusic()
    }

    stop() {
      if (this.source) {
        this.source.stop(0)
      }
    }

    play() {
      if (this.source) {
        this.source.start(0)
      }
    }

    addEventListener(eventName, callback) {
      if (!this.handle[eventName]) {
        this.handle[eventName] = []
      }
      this.handle[eventName].push(callback)
    }

    initSource(arrayBuffer) {
      const that = this
      that.context.decodeAudioData(arrayBuffer,
        function (buffer) {
          that.source = that.context.createBufferSource()
          that.source.buffer = buffer
          that.source.connect(that.context.destination)
          const event = that.handle['load']
          if (event) {
            event.map(v => v.call(that))
          }
        },
        function (error) {
          const event = that.handle['error']
          if (event) {
            event.map(v => v.call(that, error))
          }
        });
    }

    loadMusic() {
      const that = this
      const xhr = new XMLHttpRequest()
      xhr.open('GET', that.url, true)
      xhr.responseType = 'arraybuffer'
      xhr.send()
      xhr.addEventListener('load', function (e) {
        that.initSource(this.response)
      })
      xhr.addEventListener('error', function (error) {
        const event = that.handle['error']
        if (event) {
          event.map(v => v.call(that, error))
        }
      })
    }
  }

demo

const music = new Music('./demo.mp3', true)
  music.addEventListener('load', function () {
    this.play()
})
上一篇:谷歌浏览器 html5的声音和视频不能自动播放处理


下一篇:如何在喜欢上一个人的时候不那么上头