微信小程序音樂播放器簡單代碼

7,632 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

電子郵件地址不會被公開。 必填項已用*標注