自定义一个音频播放组件,在页面调用,音频播放后页面关闭但音频未停止仍然继续播放,不知道哪里出了问题?
使用场景是这样的页面上有多个音频源,需要点击一个播放,不允许同时播放,点击一条当前就播放点击的这条音频源
给出代码
var util = require('../../utils/util.js');
const innerAudioContext = wx.createInnerAudioContext();
const app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
src: {
type: String
},
z2isPlay: {
type: Boolean
},
id:{
type: String
}
},
/**
* 组件的初始数据
*/
data: {
isPlayAudio: false,
isLoading: false,
btnBindTap: "btn_play",
btnsrc: '/pages/images/ico-audio-play.svg',
processBarWidth: "0", //百分比
audioSeek: "00:00",
audioDuration: 0,
},
/**
* 组件的方法列表
*/
methods: {
btn_play: function() {
console.log(this.data)
if (this.data.isPlayAudio) {
innerAudioContext.stop()
this.triggerEvent('z2isPlaying', {
z2isPlay: this.data.isPlayAudio
}, {})
} else {
innerAudioContext.src = this.properties.src
innerAudioContext.play()
innerAudioContext.onPlay(() => {
console.log('开始播放')
this.setData({
isPlayAudio: true,
isLoading: false,
btnsrc: '/pages/images/ico-audio-pause.svg',
btnBindTap: 'btn_pause'
})
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
innerAudioContext.onTimeUpdate(() => {
var
a = innerAudioContext.currentTime.toFixed(2),
b = innerAudioContext.duration.toFixed(2),
c = util.formatSeconds(b - a)
//parseInt()
this.setData({
audioSeek: c,
audioDuration: a,
processBarWidth: parseInt(a / b * 100) + '%'
})
console.log('进度更新了总进度为:' + innerAudioContext.duration + '当前进度为:' + innerAudioContext.currentTime, '进度条', parseInt(a / b * 100));
})
innerAudioContext.onEnded(() => {
console.log('播放结束')
// innerAudioContext.stop()
this.setData({
isPlayAudio: false,
btnBindTap: "btn_play",
btnsrc: '/pages/images/ico-audio-play.svg',
processBarWidth: "0", //百分比
audioSeek: "00:00",
})
})
}
this.triggerEvent('z2isPlaying', {
z2isPlay: this.data.isPlayAudio
}, {})
},
btn_pause: function() {
console.log(this.data)
innerAudioContext.pause()
innerAudioContext.onPause(() => {
console.log('暂停播放')
this.setData({
isPlayAudio: false,
btnsrc: '/pages/images/ico-audio-play.svg',
btnBindTap: 'btn_play'
})
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
this.triggerEvent('isPlaying', {
isPlaying: this.data.isPlayAudio
}, {})
},
},
attached() {
// 第二种方式通过组件的生命周期函数执行代码
console.log('z2isPlay', this.properties.z2isPlay);
this.setData({
isPlayAudio: this.properties.z2isPlay
})
}
})