<audio src="{{resources[currentAudioIndex].resource}}" id="myAudio" bindtimeupdate="playing" bindplay="funplay" action="{{action}}" bindended="audio_end"></audio>
Component({ /** * 组件的属性列表 */ properties: { resources: { type:Array, value:[] }, plan: { type:String, value:‘loop‘ } }, data: { isPlay:false, currentAudioIndex: 0 }, lifetimes: { attached: function() { this.audioCtx = wx.createAudioContext(‘myAudio‘) bus.on("user_change_time",data=> { //接收收了用户的改变,执行暂停操作 this.audioPause(); }); bus.on("change_time",time=> { //拖动放下了 this.setAudioTime(time); this.audioPlay(); }); }, detached: function() { // 在组件实例被从页面节点树移除时执行 }, }, methods: { audio_end() { //播放结束源事件,播放下一首 this.nextAudio(); }, playing(e) { //从外发出正在播放的信息this.triggerEvent("play_ing",e); }, //播放音频,与暂停相应 audioPlay() { this.setData({ action: { method: ‘play‘ } }); this.setData({ isPlay:true }) //向外发送音频已开始播放 bus.emit("audio_play"); //向外发送音频已开始播放,组件 this.triggerEvent("play",{ current_play_index:this.data.currentAudioIndex, resources:this.data.resources }); }, //暂停,与播放相应 audioPause() {this.setData({ action: { method: ‘pause‘ } }); this.setData({ isPlay:false }) //向外发送音频已暂停this.triggerEvent("pause"); }, //下一首 nextAudio() { this.audioPause() //组件播放结束,触发的源事件,由组件外传入next的策略 if(this.data.currentAudioIndex < this.data.resources.length-1) { var length = this.data.resources; var plan_val = 0; //根据策略,生成下一首的歌曲索引 if(this.data.plan == ‘loop‘) { plan_val = ++this.data.currentAudioIndex; }else if(this.plan == ‘random‘){ play_val = Math.floor((Math.random()*length)); } //播放生成的索引 this.setData({ currentAudioIndex: plan_val }) }else { this.setData({ currentAudioIndex: 0 }) } var gthis = this; setTimeout(function() { gthis.audioPlay(); },100); }, //设置播放时间 setAudioTime(time) { this.setData({ action: { method: ‘setCurrentTime‘, data: time } }); }, } })
使用:
songdata: [ { id:0, name:‘千百度‘, img:‘https://zjazn.test.utools.club/images/2.jpg‘, resource:‘https://zjazn.test.utools.club/许篙 - 千百度.mp3‘, author:‘许蒿‘, }, { id:1, name:‘胡萝卜须‘, img:‘https://zjazn.test.utools.club/images/1.jpg‘, resource:‘https://zjazn.test.utools.club/许嵩 - 胡萝卜须.mp3‘, author:‘许蒿‘, }, { id:2, name:‘清明雨上‘, img:‘https://zjazn.test.utools.club/images/3.jpg‘, resource:‘https://zjazn.test.utools.club/许嵩 - 清明雨上.mp3‘, author:‘许蒿‘, } ]
<playUtil resources="{{ --传入资源,格式如上-- }}" plan="loop" bindplay_next="--下一首播放时要触发的函数--" bindplay_ing="--播放的信息要调用那个函数接收--" bindplay="--开始继续播放时要触发的函数--" bindpause="
--暂停时时要触发的函数--
" ></playUtil>