想做一个功能齐全的类似qq音乐的微信小程序,demo来了,可供大家参考,包含音乐搜索、音乐列表及播放停止
示例代码:
var util = require('../../utils/util.js')
var app = getapp()
page({
data: {
playingsong: {},
songurl: '',
songimg: '',
songstate: {
progress: 0,
currentposition: '00:00',
duration: '00:00'
},
isplaying: true,
lyric: ''
},
onload: function(){
console.log('playsong onload');
let that = this;
let songdata = app.globaldata.songdata;
that.setdata({
playingsong: songdata,
songurl: 'http://ws.stream.qqmusic.qq.com/c100' + songdata.songmid + '.m4a?fromtag=38',
songimg: 'http://y.gtimg.cn/music/photo_new/t002r150x150m000' + songdata.albummid + '.jpg',
});
let thatdata = that.data;
wx.playbackgroundaudio({
dataurl: thatdata.songurl,
title: thatdata.playingsong.songname,
coverimgurl: thatdata.songimg,
success: function(res){
//do something
}
});
},
onready: function(){
console.log('playsong onready');
let that = this;
that.songplay();
wx.onbackgroundaudioplay(function(){
console.log('播放了');
that.songplay();
});
},
timetostring: function(duration){
let str = '';
let minute = parseint(duration/60) < 10 ? ('0'+ parseint(duration/60)) : (parseint(duration/60));
let second = duration%60 < 10 ? ('0'+duration%60) : (duration%60);
str = minute+':'+second;
return str;
},
songplay: function(){
let that = this;
let inv = setinterval(function(){
wx.getbackgroundaudioplayerstate({
success: function(res){
if(res.status == 1){
that.setdata({
isplaying: true,
songstate: {
progress: res.currentposition/res.duration*100,
currentposition: that.timetostring(res.currentposition),
duration: that.timetostring(res.duration)
}
})
}else{
that.setdata({
isplaying: false
});
clearinterval(inv);
}
}
});
}, 1000);
},
songtoggle: function(){
let that = this;
if(that.data.isplaying){
wx.pausebackgroundaudio();
}else{
wx.playbackgroundaudio({
title: that.data.playingsong.songname,
coverimgurl: that.data.songimg
});
};
that.songplay();
}
})
以上就是qq音乐微信小程序实例代码的详细内容。