好长时间以来,自己就有个想法为自己写一个音乐播放器小程序,以方便自己的使用,找网上的好多API,找不到,想抓接口,好多大厂都用了加密。结果自己仅仅整了点本地的数据。

 

只介绍一些具体的方法:

// 解码>>中文
 reconvert: function (str) {
 str = str.replace(/(\\u)(\w{1,4})/gi, function ($0) {
 return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
 });
 str = str.replace(/(&#x)(\w{1,4});/gi, function ($0) {
 return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16));
 });
 str = str.replace(/(&#)(\d{1,6});/gi, function ($0) {
 return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
 });
 return str;
 },
 // 解析歌词的方法
 parseLyric: function (lrc) {
 var lyrics = lrc.split("\n");
 var lrcObj = {};
 for (var i = 0; i < lyrics.length; i++) {
 var lyric = decodeURIComponent(lyrics[i]);
 var timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
 var timeRegExpArr = lyric.match(timeReg);
 if (!timeRegExpArr)
 continue;
 var clause = lyric.replace(timeReg, '');
 if (clause.length > 0) {
 for (var k = 0, h = timeRegExpArr.length; k < h; k++) {
 var t = timeRegExpArr[k];
 var min = Number(String(t.match(/\[\d*/i)).slice(1)),
 sec = Number(String(t.match(/\:\d*/i)).slice(1));
 var time = min * 60 + sec;
 lrcObj[time] = clause;
 }
 }
 }
 return lrcObj;
 },
 // 转换时间格式
 timeToString: function (duration) {
 var str = '';
 var minute = parseInt(duration / 60) < 10
 ? ('0' + parseInt(duration / 60))
 : (parseInt(duration / 60));
 var second = duration % 60 < 10
 ? ('0' + duration % 60)
 : (duration % 60);
 str = minute + ':' + second;
 return str;
},

 

2.播放控制

// 播放状态控制
 songPlay: function () {
 clearInterval(timer);
 var timer = setInterval(function () {
 // 获取后台音乐播放状态
 wx.getBackgroundAudioPlayerState({
 success: function (res) {
 // 播放状态 1表示播放中
 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)
 }
 });
 var i = that.data.currentIndex
 if (i < that.data.lyric.length) {
 if (res.currentPosition - 4 >= parseInt(that.data.lyric[i][0])) {
 that.setData({
 currentIndex: i + 1
 })
 }
 }
 if (that.data.currentIndex >= 5) {
 that.setData({
 scrollTop: (that.data.currentIndex - 5) * 20,
 })
 }
 } else {
 that.setData({ isPlaying: false });
 clearInterval(timer);
 }
 }
 });
 }, 1000);
 }, 

具体项目我已经放https://github.com/dt8888/JokeProject,请去下载参考!

专栏作家

honey缘木鱼。小程序社区博主,坚持原创分享技术博文。

本文原创发布于小程序社区。未经许可,禁止转载


原文地址:音乐播放小程序demo-微信小程序联盟/博主专区-微信小程序开发社区-微信小程序联盟

 

相关文章:

微信小程序Demo:音乐之声(音乐播放小程序)

微信小程序Demo:TealMusic音乐播放器


本文转载:CSDN博客