audio.js
2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
}