微信小程序–音乐播放器(Java爬虫后台在下文篇章公布)

主页面:
Java爬虫后台+微信小程序之音乐播放器(上)wxml:
css就不展示了,比较多

<view class='container' style='width:{{wid}} height={{he}}'>
    <view class="inputView"> 
      <form bindsubmit='submit'>
    <input class="input" type="text" value="{{toname}}" name="toname" placeholder-style="color: red" />
      <view class='bt'>
    <button  type="default"plain="true" form-type='submit'><image src='../../images/08f790529822720e679f1edc70cb0a46f21fab47.jpg' ></image></button>
    </view>
    </form>
    </view>
    <view class='swiper'>
      <swiper indicator-dots="{{indicatorDots}}"
  autoplay="{{autoplay}}"
  interval="{{interval}}"
  duration="{{duration}}">
      <block wx:for="{{lunbo}}">
        <swiper-item><image src='{{item}}'></image></swiper-item>
        </block>
      </swiper>
    </view>
    <view class='rank'>
      <view class='rank-h' bindtap='xingeClick'><view class='rank-i'><image src='../../images/20190321162220.png'></image></view>新歌榜         </view>
      <view class='rank-h' bindtap='regeClick'><view class='rank-i'><image src='../../images/20190321162328.png'></image></view>热歌榜         </view>
      <view class='rank-h'  bindtap='biaoshengClick'><view class='rank-i'><image src='../../images/20190321162656.png'></image></view>飙升榜          </view>
    </view>
      <view class='gedan-head'>推荐歌单 ></view>
     <view class='ggg' >
      <block wx:for="{{tuijian}}" class='gedan-body'>
        <view class='gedan-it' bindtap='tuijianClick' id='{{index}}'><image src='{{item}}'></image><view class='lis'><image src='../../images/20190322105830.png'></image>999+</view></view>
      </block>
    </view>
 </view>

js:

//index.js
const app = getApp()
var method='x';
var tid=''
Page({
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
 toname:'',
 wid:'',
 he:'',
    lunbo: [],
  },
  onLoad: function (options) {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({ wid: res.windowWidth })
        that.setData({ he: res.windowHeight })
      },
      
    })
    wx.request({
      url: 'http://localhost:8080/spider/servlet.do',
      data: {
        x: 'index',
        y: ''
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          lunbo: res.data[0].img,
          tuijian:res.data[1].tuijianImg

        })
      }

    })
  },
  
  submit:function(e){
    if (e.detail.value.toname != null && e.detail.value.toname !=""){
      method="b"
    wx.navigateTo({
      url: '/pages/songlist/songlist?me='+ e.detail.value.toname+"&method="+method,
    })

    }
  }
,

xingeClick (){
method='xinge'
  wx.navigateTo({
    url: '/pages/songlist/songlist?method=' + method,
  })
}
  , regeClick() {
    method = 'rege'
    wx.navigateTo({
      url: '/pages/songlist/songlist?method=' + method,
    })
  }
  , biaoshengClick() {
    method = 'biaosheng'
    wx.navigateTo({
      url: '/pages/songlist/songlist?method=' + method,
    })
  },
  tuijianClick(e){
    method = e.currentTarget.id;
    wx.navigateTo({
      url: '/pages/songlist/songlist?method=' + method,
    })
  }
})
```接下来是列表页面:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190326221329186.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxODAyMjI5,size_16,color_FFFFFF,t_70)
***wxml:***

{{index}} {{item.songname}} {{item.singer}} ``` js:
var app=getApp();
var  method='b'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name:'',
    sources:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
   onLoad: function (options) {
    var that = this;
     if (options.method!=null){
    method=options.method;}
   if(method=='b'){
    var me = options.me
    wx.request({
      url: 'http://localhost:8080/spider/servlet.do?songname=' + me, // 仅为示例,并非真实的接口地址
      data: {
        x: 'song',
        y: ''
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          sources: res.data,
          
        })
        app.globalData.allsong=res.data
      }

     })
   }
   else{
     this.getsonglist()
   }
    },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    var that = this;
   


  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },
  toplay:function(e){
    var that=this
    app.globalData.allsong = that.data.sources
    var t = that.data.sources[e.currentTarget.id].address
    var se = that.data.sources[e.currentTarget.id].songname
    var sr = that.data.sources[e.currentTarget.id].singer
    var id = e.currentTarget.id
   // console.log(t)
     wx.navigateTo({
       url: '/pages/play/play?id='+id,
     })

  },
  getsonglist() {
    var that = this;
    wx.request({
      url: 'http://localhost:8080/spider/servlet.do',
      data: {
        x: method.toString(),
        y: 'bangdan'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          sources: res.data,
        })
      }
    })
  },
})

接下来是播放页面:
Java爬虫后台+微信小程序之音乐播放器(上)
wxml:

<view class='container'  style='width:{{wid}} '>
  <view class='player'>
  <view class='header'>
  <view class='head'>
    <view class='songname'>{{songname}}</view>
     <view class='singer'>{{singer}}</view>
  </view></view>
  <view class="backcontrol" bindtap='change'>
      <view wx:if="{{ischange}}">
        <view class="lrc" style="">
           <view class='bb' style="top:{{marginTop}}px;height:{{lrcHeight}}px">
          <block wx:for="{{lry}}" wx:key="">
             <view class="lry1 {{currentIndex == index ? 'currentTime' : ''}}">{{item[1]}}</view>
        </block></view>
        </view>
      </view>
      <view wx:else>
      <view class='bk'>
      <view  class='audioBack' animation="{{animation}}">
        <image src='{{img}}' />
        </view></view>
      </view>
  </view>
     <view class='rail'>
    <view class='audioControls'>
      <view class='flexx'>
        <view class='slider'>
          <slider bindchange='sliderChange' activeColor='red' block-size="12" value='{{audioTime}}' />
        </view>
        <view class='time'>
          {{showTime1}}/{{showTime2}}
        </view>
      </view>
    </view>
      <view class='flex'>
        <view class='bottom1' bindtap='leftsong'>
            <image src='../../images/58164ac17ebcc_611.jpg'></image>
        </view>
        <view class='bottom' catchtap='playAudio'>
          <view wx:if="{{isPlayAudio}}">
            <image src='../../images/20180919153051430.png' />
          </view>
          <view wx:else>
            <image src='../../images/20180919153025300-1.png' />
          </view>
        </view>
        <view class='bottom2' bindtap='rightsong'>
            <image src='../../images/58164ac17ebcc_610.jpg' ></image>
        </view>

        <view class='list-msg' bindtap='bindShowMsg'>
        <image  src='{{orderimg}}'></image>
        </view>
        <view wx:if="{{isorder}}" class='s'>
          <view class='sb' bindtap='changeorder'data-name='../../images/20190326143641.png'><image src="../../images/20190326132448.png"></image></view>
           <view  class='sb' bindtap='changeorder'data-name='../../images/20190326143710.png'><image src="../../images/20190326132523.png"></image></view>
            <view  class='sb' bindtap='changeorder' data-name='../../images/20190326143801.png'><image src="../../images/20190326132507.png"></image></view>
        </view>

      </view>
      </view>
  </view>
</view>


js: (这部分比较多)

const inneraudio= wx.createInnerAudioContext();
var _animation; 
 var _animationIndex = 0; 
  var _animationIntervalId = -1;
    const _ANIMATION_TIME = 2000; 
var app=getApp()
var id=0
var ll="";
var isis="lcycle";

Page({
  data: {
    orderimg:'../../images/20190326143801.png',
    isorder:false,
    audiosrc: '',
    ischange:true,
    currentIndex: 0,
    lry: [],
    marginTop: 0,
    lrcHeight: 350,
    singer:'',
    songname:'',
    wid:'',
    animation: '',
   he:'',
    img:'',
  isPlayAudio:true,
  audioTime:0,
  showTime1:'00:00',
  showTime2:'00:00',
  audioSeek:0,
  audioDuration:0,
   
  },
  bindShowMsg(){
    this.setData({
      isorder:!this.data.isorder,
    })
  }
,
changeorder(e){
  var that=this
  var src = e.currentTarget.dataset.name;
  if (src =="../../images/20190326143641.png"){
    that.setData({
      orderimg: src,
      isorder: false,
    })
    isis="dcycle"
  }
  if (src == "../../images/20190326143710.png") {
    that.setData({
      orderimg: src,
      isorder: false,
    })
   isis="random"
    var jsonLength = 0;
    for (var i in app.globalData.allsong) {
      jsonLength++;
    }
    id=Math.floor(Math.random()*jsonLength*1)
  }
  if (src == "../../images/20190326143801.png"){
    isis = "lcycle"
    that.setData({
      orderimg: src,
      isorder: false,
    })
  }
},
 
  onReady: function () {
    _animationIndex = 0;
    _animationIntervalId = -1;
    this.data.animation = '';
  },
  
huancun(){
  var that = this
  that.setData({
    songname: app.globalData.allsong[id].songname,
    singer: app.globalData.allsong[id].singer
  })
  var hash2 = app.globalData.allsong[id].address
  wx.getStorage({
    key: hash2,
    success: function (res) {
      ll = res.data.geci
      that.setData({
        audiosrc: res.data.address,
        img: res.data.img.replace(/\\/g, ""),
        audioSeek: 0, audioTime: 0, showTime1: '00:00',
        currentIndex: 0,
        isPlayAudio: true,
        marginTop: 0,
        lrcHeight: 350
      })
      inneraudio.play()
      inneraudio.src = that.data.audiosrc;
      that.Initialization()
      that.songLrc()
    },
    fail: function () {
      that.getmp3();
    }
  })
},
  onLoad: function (options) {
    id = options.id;
   this.huancun()
    this.setData({
      songname: app.globalData.allsong[id].songname,
      singer: app.globalData.allsong[id].singer
    })
    var that=this
    wx.getSystemInfo({
      success: function(res) {
        that.setData({ wid: res.windowWidth, he: res.windowHeight})
      },
    })},
    getmp3 (){     
    var that=this
      that.setData({
        songname: app.globalData.allsong[id].songname,
        singer: app.globalData.allsong[id].singer
      })
     var hash1= app.globalData.allsong[id].address
    wx.request({
      url: 'http://localhost:8080/spider/servlet.do?hash=' + hash1, // 仅为示例,并非真实的接口地址
      data: {
        x: 'dd',
        y: ''
      },
      //http://tangxiao.free.idcfengye.com
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {       
        var size= Object.keys(res.data[0]).length
        //   "pages/index/index",
       // "pages/songlist/songlist",
        if (size==3){
          ll=res.data[0].geci
          that.setData({
            audiosrc: res.data[0].address,
            img: res.data[0].img.replace(/\\/g, ""),
            audioSeek: 0, audioTime: 0, showTime1: '00:00',
          currentIndex:0,
            isPlayAudio: true,
            marginTop: 0,
            lrcHeight: 350 
          })

          wx.setStorage({
            key: hash1,
            data: res.data[0]
          })
          inneraudio.src = that.data.audiosrc;
          that.Initialization()
          that.songLrc()
        }
        else{
          that.rightsong()
        }   
      }

    })}
  ,
  change(){
    if(this.data.ischange){
      this.setData({ ischange: false })
    }
    else{
      this.setData({ ischange: true })
    }
  },
  leftsong (){
    var that = this
    var jsonLength = 0;
    for (var i in app.globalData.allsong) {
      jsonLength++;
    }
    if (isis=="random") {
      id = Math.floor(Math.random() * jsonLength * 1)
      that.huancun()
    }
   else{
    if(id<=0){
      id = jsonLength*1-1;
    }
    else{
     id=id*1-1
    }
    this.huancun();
    }
  },
  rightsong() {
    var that=this
    var jsonLength = 0;
    for (var i in app.globalData.allsong) {
      jsonLength++;
    }
    if (isis == "random"){
      id = Math.floor(Math.random() * jsonLength * 1)
      that.huancun()
    }
   else{
    if (id == jsonLength*1 - 1) {
      id = 0;
    }
    else {
      id = id*1 +1;
    }
    this.huancun()
    }

  },
  onShow: function () {
    this.loadaudio();
    _animation = wx.createAnimation({ duration: _ANIMATION_TIME, timingFunction: 'linear',
     delay: 0,
      transformOrigin: '50% 50% 0'
     })
     if(this.data.isPlayAudio){
       this.startAnimationInterval();
     }
    
    
   
  },
  rotateAni: function (n) {
    _animation.rotate(100 * (n)).step()
    this.setData({
      animation: _animation.export()
    })
  },


startAnimationInterval: function () {
    var that = this; 
    that.rotateAni(++_animationIndex);
     _animationIntervalId = setInterval(function () {
        that.rotateAni(++_animationIndex);
         }, _ANIMATION_TIME); 
     },
       stopAnimationInterval: function () { 
         if (_animationIntervalId< 0) { 
           clearInterval(_animationIntervalId); 
           }
},
  Initialization() {
    var that = this;
    if (this.data.audiosrc.length != 0) {
      inneraudio.src = this.data.audiosrc;
      inneraudio.onCanplay(() => {
        inneraudio.play();
        inneraudio.duration
        setTimeout(function () {
          var duration = inneraudio.duration;
          var min = parseInt(duration / 60);
          var sec = parseInt(duration % 60);
          if (min.toString().length == 1) {
            min = `0${min}`;
          }
          if (sec.toString().length == 1) {
            sec = `0${sec}`;
          }
          that.setData({ audioDuration: inneraudio.duration, showTime2: `${min}:${sec}` })
        }
          , 1000
        )
     })
    }
else{
  this.rightsong()
}
  },
  playAudio(){
    var isPlayAudio=this.data.isPlayAudio;
    var seek=this.data.audioSeek;
    inneraudio.pause();
    clearInterval(_animationIntervalId)
    var that=this
    this.setData({isPlayAudio:!isPlayAudio})
    if(isPlayAudio){
      clearInterval(_animationIntervalId)
      this.setData({audioSeek:inneraudio.currentTime})
    }
    else{
      clearInterval(_animationIntervalId)
      inneraudio.src=this.data.audiosrc;
      if (inneraudio.duration != 0) {
        this.setData({ audioDuration:inneraudio.duration });
      }
      inneraudio.seek(seek);
      inneraudio.play();
    }
  },
  loadaudio(){
    var that=this;
    this.data.durationinterval=setInterval(function(){
      if(that.data.isPlayAudio){
        var seek=that.data.audioSeek;
        var time=that.data.audioTime;
        var duration=inneraudio.duration;
        time=parseInt(100*seek/duration);
        var min=parseInt((seek+1)/60);
        var sec=parseInt((seek+1)%60);
        if(min.toString().length==1){
          min=`0${min}`;
        }
        if (sec.toString().length == 1) {
          sec = `0${sec}`;
        }
        if(time>=100){
            that.setData({audioSeek:0,audioTime:0,showTime1:'00:00'})
            if(isis=="lcycle"){
          that.rightsong();
            }
            if(isis=="random"){
              var jsonLength = 0;
              for (var i in app.globalData.allsong) {
                jsonLength++;
              }
              id = Math.floor(Math.random()*jsonLength*1)
              that.huancun()
            }
            if(isis=="dcycle"){
             that.huancun()
            }
        }
        that.setData({audioSeek:seek+1,audioTime:time,showTime1:`${min}:${sec}`})
      }
        var i = that.data.currentIndex
        if (i < that.data.lry.length) {
          if (inneraudio.currentTime - 3>= parseInt(that.data.lry[i][0])) {
            that.setData({
              currentIndex: i + 1
            })
          }
        }
        if (that.data.currentIndex >= 6) {
          that.setData({
            marginTop: -(that.data.currentIndex - 6) * 29,
            lrcHeight: 350 + (that.data.currentIndex - 6) * 48
          })
        }
    },1000)
  }
,
sliderChange(e){
  var that=this;
  inneraudio.src= this.data.audiosrc;
  var value=e.detail.value;
  this.setData({audioTime:value});
  var duration=inneraudio.duration;
  value=parseInt(value*duration/100);
  this.setData({audioSeek:value,isPlayAudio:true});
  inneraudio.seek(value);
  inneraudio.play();
  var y = that.data.lry.length
  var x = value / duration
  var z = parseInt(x * y);
  that.setData({
    currentIndex: z * 1 +1
  })
},
onUnload(){
  clearInterval(this.data.durationinterval)
  clearInterval(_animationIntervalId); 

},
onHide(){
  clearInterval(this.data.durationinterval)
  clearInterval(_animationIntervalId); 
  this.rightsong();
},
   songLrc: function () {
     var that = this
     that.setData({
       lry: that.sliceNull(that.parseLyric(ll))
     })
   },
  sliceNull: function (lrc) {
    var result = []
    for (var i = 0; i < lrc.length; i++) {
      if (lrc[i][1] == "") {
      } else {
        result.push(lrc[i]);
      }
    }
    return result
  },
  parseLyric: function (text) {
    var lines = text.split('\\r\\n'),
      pattern = /\[\d{2}:\d{2}.\d{2}\]/g,
      result = [];
    var i=0;
    while (!pattern.test(lines[0])) {
      lines = lines.slice(1);
    };
    lines[lines.length - 1].length === 0 && lines.pop();
    lines.forEach(function (v , i, a ) {
      var time = v.match(pattern),
      value = v.replace(pattern, '');
      time.forEach(function (v1, i1, a1) {
        var t = v1.slice(1, -1).split(':');
        result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
      });
    });
    result.sort(function (a, b) {
      return a[0] - b[0];
    });
    return result;
  },  
})

相关文章: