audio.js
2.72 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
}