微信小程序音乐播放器简单代码

571 views

目前功能,上一首,下一首,不知道是啥原因,使用bindended播放完毕事件。无效。所以就使用bindtimeupdate 去判断currentTime和duration是否一致来粗暴实现。然后加了一个Math.flool,将数值整数化。解决音乐播放完毕后,播放下一首。

wxml代码:

<view style=”text-align:center;margin-top:10px;margin-bottom:10px;”>
<audio poster=”{{poster}}” name=”{{name}}” author=”{{author}}” src=”{{src}}” id=”{{myAudio}}” controls loop bindtimeupdate=”funtimeupdate” bindended=”funended”>
</audio>
</view>
<view style=”display:flex;flex-direction:row;”>
<button type=”primary” bindtap=”audioNext” style=”width:120px;height:30px;line-height:30px;background:#cccccc;”>下一首</button>
<button type=”primary” bindtap=”audioPre” style=”width:120px;height:30px;line-height:30px;background:#cccccc;”>上一首</button>
</view>

JS代码:

Page({
/**
* 页面的初始数据 */
onReady: function (e) {
this.audioCtx = wx.createAudioContext(‘myAudio’, this),
this.audioCtx.play()
},
data: {
current:0,
myAudio:’myAudio’,
poster: ‘music.jpg’,
name: ‘测试’,
author: ‘测试’,
src: ‘6039.mp3’,
list: [{
id: 1,
poster: ‘music.jpg’,
name: ‘送别’,
author: ‘朴树’,
src: ‘songbie.mp3’
}, {
id: 2,
poster: ‘zhaolei2.jpg’,
name: ‘我们的时光’,
author: ‘赵雷’,
src: ‘womendeshiguang.mp3’
}, {
id: 3,
poster: ‘hanggai.jpg’,
name: ‘杭盖’,
author: ‘杭盖乐队’,
src: ‘hanggai.mp3’
}, {
id: 4,
poster: ‘zhaolei1.jpg’,
name: ‘成都’,
author: ‘沈虫虫’,
src: ‘chengdou.mp3’
}, {
id: 5,
poster: ‘maobuyi.jpg’,
name: ‘像我这样的人’,
author: ‘毛不易’,
src: ‘xiangwozheyangderen.mp3’
}, {
id: 6,
poster: ‘maobuyi.jpg’,
name: ‘测试’,
author: ‘测试’,
src: ‘6039.mp3’
}
],
},
audioNext:function(){
if(this.data.current<5){
this.data.current++
console.log(this.data.current)
};
if (this.data.current == 5) {
this.data.current = 0;
console.log(this.data.current)
}
this.funPlayIndex(this.data.current)
},
audioPre:function(){
if (this.data.current >0) {
this.data.current–
console.log(this.data.current)
};
if (this.data.current == 0) {
this.data.current = 5;
console.log(this.data.current)
}
this.funPlayIndex(this.data.current)
},
funtimeupdate: function (u) {
//当前播放时间
// console.log(Math.floor(u.detail.currentTime));
//歌曲总时间
// console.log(Math.floor(u.detail.duration));
if (Math.floor(u.detail.currentTime) == Math.floor(u.detail.duration)){
console.log(“audio end”);
this.audioNext()
}
},
funended: function () {
console.log(“audio end”);
},
funPlayIndex(_current){
this.audioCtx.setSrc(this.data.list[_current].src),
this.audioCtx.play()
var page = this;
page.setData({ name: this.data.list[_current].name })
page.setData({ author: this.data.list[_current].author })
page.setData({ poster: this.data.list[_current].poster })
}
})

 

使用JS中函数与变量里需要加this.这是一个变化。

如果您觉得这篇文章对您有帮助,欢迎继续关注本站!!!我要赞助本站>>>

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注