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()
})
标签:handle,xhr,自动播放,source,error,const,AudioContext,event 来源: https://www.cnblogs.com/coderDemo/p/14105323.html