市北党建引领小程序初始化
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

136 lines
3.5 KiB

2 years ago
Component({
data: {
audioManager: '',
isPlayAudio: false, // 是否在播放
max: 60, // 时间轴最大值
step: 10, // 时间轴滑动间隔 10ms - 1000ms
time: 0, // 时间轴当前值
// duration: 60, // 音频时长 默认时长60S
playTime: '00:00', // 正在播放的时间
durationText: '00:00', //
setInter: '', //
},
properties: {
url: {
type: String,
value: ''
},
duration: {
type: Number,
value: 60
}
},
observers: {
url (newUrl) {
this.setData({
'audioManager.src': newUrl
})
},
duration (newDuration) {
this.setData({
max: newDuration * (1000/this.data.step),
durationText: this.formartTimeText(newDuration * (1000/this.data.step))
})
}
},
lifetimes: {
attached: function() {
// 在组件实例进入页面节点树时执行
this.initAudio()
},
detached: function() {
// 在组件实例被从页面节点树移除时执行
this.data.audioManager.destroy()
},
},
pageLifetimes: {
},
methods: {
initAudio () {
// 音频播放
this.data.audioManager = wx.createInnerAudioContext()
this.setData({
'audioManager.src': this.data.url,
max: this.data.duration * (1000/this.data.step),
durationText: this.formartTimeText(this.data.duration * (1000/this.data.step))
})
this.data.audioManager.onPlay(() => {
this.countTime()
})
this.data.audioManager.onCanplay(()=>{
// console.log(this.data.audioManager.duration) // 不好用
})
this.data.audioManager.onStop(() => {
clearInterval(this.data.setInter)
this.setData({
isPlayAudio: false,
time: 0,
playTime: '00:00'
})
})
this.data.audioManager.onEnded(() => {
clearInterval(this.data.setInter)
this.setData({
isPlayAudio: false,
time: 0,
playTime: '00:00'
})
})
this.data.audioManager.onError(() => {
console.log('音频播放错误', this.data.audioManager.src)
clearInterval(this.data.setInter)
this.setData({
isPlayAudio: false,
time: 0,
playTime: '00:00'
})
})
},
onPlayAudio () {
this.setData({
isPlayAudio: !this.data.isPlayAudio
})
if (this.data.isPlayAudio) {
this.data.audioManager.play()
} else {
this.data.audioManager.stop()
}
},
formartTimeText (duration) {
duration = parseInt(duration / (1000 / this.data.step))
let text = '00:00'
if (duration < 10) {
text = '00:0' + duration
} else if (duration < 60) {
text = '00:' + duration
} else if (duration / 60 < 10) {
if (duration % 60 < 10) {
text = '0' + parseInt(duration / 60) + ':0' + duration % 60
} else {
text = '0' + parseInt(duration / 60) + ':' + duration % 60
}
} else {
if (duration % 60 < 10) {
text = parseInt(duration / 60) + ':0' + duration % 60
} else {
text = parseInt(duration / 60) + ':' + duration % 60
}
}
return text
},
countTime () {
clearInterval(this.data.setInter)
this.data.setInter = setInterval(() => {
this.setData({
time: this.data.time + 1
}, () => {
this.setData({
playTime: this.formartTimeText(this.data.time)
})
})
}, this.data.step)
},
}
})