炫酷纯音乐小程序的设计与实现

小程序已上线,搜一搜“壹曲觅知音”即可体验,里面有很多我珍藏的好听的纯音乐哦。

如若无法正常使用说明我的服务器已经到期。

本小程序为原创小程序,未经授权不得用于商业用途

源码中暴露了真实的请求地址,并且后台没在安全机制上做过多考虑,别搞破坏啊难过

小程序的完整源码下载地址:https://download.csdn.net/download/qq_37518622/10540741

又用python写了个爬即将上映的电影用邮件推送给自己:https://blog.csdn.net/qq_37518622/article/details/81479204

猜歌小程序界面如下:

1、主界面

2、猜歌界面

3、排行榜界面

4、收藏音乐界面

5、抽积分界面

代码如下:

主界面

<!--index.wxml-->
<view class="container">
      <view class='item'>
       <button open-type="getUserInfo" bindgetuserinfo="jumpguess" class="button big gray rounded">知音</button>
       </view>
       <view class='item'>
       <button open-type="getUserInfo" bindgetuserinfo="jumprank" class="button big blue rounded">排行榜</button>
       </view>
       <view class='item'>
       <button open-type="getUserInfo" bindgetuserinfo="jumpcollect" class="button big green rounded">音库</button>
       </view>
       <view class='item'>
       <button open-type="getUserInfo" bindgetuserinfo="jumpluck" class="button big purple rounded">抽积分</button>
       </view>
       <view class='item'>
       <button bindtap='jumpintroduction' class="button big orange rounded"><text>说明</text></button>
       </view>
</view>
/**index.wxss**/
.container{
  width: 100%;
  height: 100%;
   background: grey;
    background: -moz-linear-gradient(top, grey 0%, #943bea 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, grey), color-stop(100%, #943bea));
    background: -webkit-linear-gradient(top, grey 0%, #943bea 100%);
    background: -o-linear-gradient(top, grey 0%, #943bea 100%);
    background: -ms-linear-gradient(top, grey 0%, #943bea 100%);
    background: linear-gradient(to bottom, grey 0%, #943bea 100%);
    background-size: 100% 100%;
    padding-top: 50px;

}

.container .item{
  display: inline-block;
  width: 230px;
  margin-bottom: 50px;
  margin-left: 17%;
}
.button{
	font:15px Calibri, Arial, sans-serif;

	/* A semi-transparent text shadow */
	text-shadow:1px 1px 0 rgba(255,255,255,0.4);
	
	/* Overriding the default underline styling of the links */
	text-decoration:none !important;
	white-space:nowrap;
	
	display:block;
	position:relative;
	cursor:pointer;
	padding:10px 20px;
	
	background-repeat:no-repeat;

	/* The following two rules are fallbacks, in case
	   the browser does not support multiple backgrounds. */

	background-position:bottom left;
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png');
	
	/* Multiple backgrounds version. The background images
	   are defined individually in color classes */
	
	background-position:bottom left, top right, 0 0, 0 0;
	background-clip:border-box;
	
	/* Applying a default border raidus of 8px */
	
	-moz-border-radius:8px;
	-webkit-border-radius:8px;
	border-radius:8px;
	
	/* A 1px highlight inside of the button */
	
	-moz-box-shadow:0 0 1px #fff inset;
	-webkit-box-shadow:0 0 1px #fff inset;
	box-shadow:0 0 1px #fff inset;
	
	/* Animating the background positions with CSS3 */
	/* Currently works only in Safari/Chrome */
	
	-webkit-transition:background-position 1s;
	-moz-transition:background-position 1s;
	transition:background-position 1s;
}

/*.button:hover{*/
	

.button:active{
	/* Moving the button 1px to the bottom when clicked */
	bottom:-1px;
	background-position:top left;
	background-position:top left, bottom right, 0 0, 0 0;
}

/* The three buttons sizes */

.button.big		{ font-size:30px;}
.button.medium	{ font-size:18px;}
.button.small	{ font-size:13px;}

/* A more rounded button */

.button.rounded{
	-moz-border-radius:4em;
	-webkit-border-radius:4em;
	border-radius:4em;
}


/* Defining four button colors */


/* BlueButton */

.blue.button{
	color:#0f4b6d !important;
	
	border:1px solid #84acc3 !important;
	
	/* A fallback background color */
	background-color: #48b5f2;
	
	/* Specifying a version with gradients according to */
	
	background-image:	url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'),
						-moz-radial-gradient(	center bottom, circle,
												rgba(89,208,244,1) 0,rgba(89,208,244,0) 100px),
						-moz-linear-gradient(#4fbbf7, #3faeeb);

	background-image:	url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'),
						-webkit-gradient(	radial, 50% 100%, 0, 50% 100%, 100,
											from(rgba(89,208,244,1)), to(rgba(89,208,244,0))),
						-webkit-gradient(linear, 0% 0%, 0% 100%, from(#4fbbf7), to(#3faeeb));
}

.blue.button:hover{
	background-color:#63c7fe;
	
	background-image:	url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'),
						-moz-radial-gradient(	center bottom, circle,
												rgba(109,217,250,1) 0,rgba(109,217,250,0) 100px),
						-moz-linear-gradient(#63c7fe, #58bef7);
						
	background-image:	url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'),
						-webkit-gradient(	radial, 50% 100%, 0, 50% 100%, 100,
											from(rgba(109,217,250,1)), to(rgba(109,217,250,0))),
						-webkit-gradient(linear, 0% 0%, 0% 100%, from(#63c7fe), to(#58bef7));
}

/* Green Button */

.green.button{
	color:#345903 !important;
	border:1px solid #96a37b !important;	
	background-color: #79be1e;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(162,211,30,1) 0,rgba(162,211,30,0) 100px),-moz-linear-gradient(#82cc27, #74b317);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(162,211,30,1)), to(rgba(162,211,30,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#82cc27), to(#74b317));
}

.green.button:hover{
	background-color:#89d228;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(183,229,45,1) 0,rgba(183,229,45,0) 100px),-moz-linear-gradient(#90de31, #7fc01e);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(183,229,45,1)), to(rgba(183,229,45,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#90de31), to(#7fc01e));
}

/* Orange Button */

.orange.button{
	color:#693e0a !important;
	border:1px solid #bea280 !important;	
	background-color: #e38d27;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(232,189,45,1) 0,rgba(232,189,45,0) 100px),-moz-linear-gradient(#f1982f, #d4821f);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(232,189,45,1)), to(rgba(232,189,45,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#f1982f), to(#d4821f));
}

.orange.button:hover{
	background-color:#ec9732;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(241,192,52,1) 0,rgba(241,192,52,0) 100px),-moz-linear-gradient(#f9a746, #e18f2b);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(241,192,52,1)), to(rgba(241,192,52,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#f9a746), to(#e18f2b));
}

.gray.button{
	color:#525252 !important;
	border:1px solid #a5a5a5 !important;	
	background-color: #a9adb1;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(197,199,202,1) 0,rgba(197,199,202,0) 100px),-moz-linear-gradient(#c5c7ca, #92989c);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(197,199,202,1)), to(rgba(197,199,202,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#c5c7ca), to(#92989c));
}

.gray.button:hover{
	background-color:#b6bbc0;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(202,205,208,1) 0,rgba(202,205,208,0) 100px),-moz-linear-gradient(#d1d3d6, #9fa5a9);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(202,205,208,1)), to(rgba(202,205,208,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#d1d3d6), to(#9fa5a9));
}

.purple.button{
	color:#525252 !important;
	border:1px solid #a5a5a5 !important;	
	background-color: #a020f0;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(106,90,205,1) 0,rgba(106,90,205,0) 100px),-moz-linear-gradient(#8470FF, #7B68EE);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(255,236,139,1)), to(rgba(238,220,130,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#FFEC8B), to(#EEDC82));
}

.purple.button:hover{
	background-color:#a020f0;
	
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -moz-radial-gradient(center bottom, circle, rgba(106,90,205,1) 0,rgba(106,90,205,0) 100px),-moz-linear-gradient(#8470FF, #7B68EE);
	background-image:url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), url('https://nanmatou.club/files/zhiyin/icons/button_bg.png'), -webkit-gradient(radial, 50% 100%, 0, 50% 100%, 100, from(rgba(255,236,139,1)), to(rgba(238,220,130,0))),-webkit-gradient(linear, 0% 0%, 0% 100%, from(#FFEC8B), to(#EEDC82));
}
//index.js
//获取应用实例
const app = getApp()
var index=0;
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },
 

  jumpguess:function(e){
    app.globalData.userInfo = e.detail.userInfo
    wx.navigateTo({
      url: '../guess/guess'
    })
 },

  jumprank: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    wx.navigateTo({
      url: '../ranklist/ranklist'
    })
  },


  jumpcollect: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    wx.navigateTo({
      url: '../collectList/collectList'
    })
  },

  jumpluck: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    wx.navigateTo({
      url: '../luck/luck'
    })
  },

  jumpintroduction: function (e) {
    wx.navigateTo({
      url: '../introduction/introduction'
    })
  },

})

猜歌

<!--guess.wxml-->
<view class="container">
   <block>
    <image class="play-icon {{isRotation?'rotation':''}}" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524222813702&di=1b2468eebc105b308f8318da8e5a9b74&imgtype=0&src=http%3A%2F%2Fpic.qiantucdn.com%2F58pic%2F15%2F60%2F68%2F06T58PICw3s_1024.jpg" background-size="cover" bindtap='clickPlayIcon'></image>
    <image class="tip-icon" src="https://nanmatou.club/files/zhiyin/icons/tip1.png" background-size="cover" bindtap='getTip'></image>
    </block> 
  <view class="footer">
      <view class="{{showVoiceIcon?'sendmessage':'sendmessage-hidden'}}">
          <image src='https://nanmatou.club/files/zhiyin/icons/record.png' bindtap='clickSmallRecordIcon'></image>
          <input type="text" bindinput="answerInput" confirm-type="done" value='{{answerInput}}' placeholder="输入答案" maxlength='20' />
          <button type='primary' bindtap='submitAnswer' class="blue btn button">发送</button>
          <input style='display:none' type="" bindinput="bindChange" confirm-type="done" placeholder="" />
        </view>
        <view class="{{showVoiceIcon?'sendVoice':'sendVoice-hidden'}}">
              <view class="dot" bindtouchstart='startRecord' bindtouchend='endRecord'></view>
              <view class="{{palseVisible?'':'pause-hidden'}}">
                <view class="pulse"></view>
                <view class="pulse1"></view>
              </view>
        </view>
      <!-- <audio src="{{src}}" id="music"></audio> -->
  </view>
</view>
/**guess.wxss**/
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding-top: 100px;
  box-sizing: border-box;
  background-image: url('http://img.zcool.cn/community/01eacf5543e0210000019ae90753a1.jpg');
  background-size: cover;
} 


.container .play-icon {
  width: 256rpx;
  height: 256rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.container .tip-icon{
  width: 100rpx;
  height: 100rpx;
  position: absolute;
  top:10px;
  margin-left:40%;
}



@-webkit-keyframes rotation {
    from {-webkit-transform: rotate(0deg);
}to {
    -webkit-transform: rotate(360deg);
}}

.rotation {
    -webkit-transform: rotate(360deg);
    animation: rotation 8s linear infinite;
    -moz-animation: rotation 8s linear infinite;
    -webkit-animation: rotation 8s linear infinite;
    -o-animation: rotation 8s linear infinite;
}

.footer{
  margin-top: 76%;
  width: 100%;
} 
.footer .sendmessage {
  background-image: url('https://nanmatou.club/files/zhiyin/icons/bg.jpg');
  opacity:0.7;
  width: 100%;
  /* bottom: 0rpx; */
  height: 45px;
  display: flex;
  flex-direction: row;
  padding-top: 15px;
  margin-top: -185px;
}

.footer .sendmessage-hidden {
  background-image: url('https://nanmatou.club/files/zhiyin/icons/bg.jpg');
  opacity:0.7;
  width: 100%;
  /* bottom: 0rpx; */
  height: 45px;
  display: flex;
  flex-direction: row;
  padding-top: 15px;
}

.footer .sendmessage image,.sendmessage-hidden image {
  width: 34px;
  height: 34px;
  background: #fff;
  color: #000;
  line-height: 40px;
  font-size: 14px;
  border-radius: 100%;
   margin-left: 3%;
}

.footer .sendmessage input,.sendmessage-hidden input {
  width: 65%;
  height: 30px;
  background-color: white;
  line-height: 40px;
  font-size: 14px;
  border: none;
  margin-left: 7px;
  padding-left: 5px;
  box-shadow: 1px 1px 5px #B6B6B6;
  border-radius: 8px;
  text-shadow: 1px 1px 1px #9E3F3F;
}

.footer .sendmessage button,.sendmessage-hidden button {
  width: 15%;
  height: 30px;
  background: lightblue;
  color: white;
  line-height: 30px;
  font-size: 10px;
  margin-left: 10px;

  -webkit-animation-name: bluePulse;
  -webkit-animation-duration: 2s;
  -webkit-animation-iteration-count: infinite;
} 


.footer .sendVoice {
  width: 100%;
  height: 165px;
  padding-top: 20px;
  padding-left: 34%;
   opacity: 1;
  background: rgba(255, 255, 255, 0.23);
}

/* .footer .sendVoice image{
  width: 100px;
  height: 150px; 
  margin-left: 3%;
} */

.footer .sendVoice text{
  margin-top:5px;
  display: block;
  margin-left: 6%;
}

.footer .sendVoice-hidden {
  display: none;
}


 @-webkit-keyframes bluePulse {
  from { background-color: #0D8BA5; -webkit-box-shadow: 0 0 9px #333; }
  50% { background-color: #00BFFF; -webkit-box-shadow: 0 0 18px #00BFFF; }
  to { background-color: #1392AA; -webkit-box-shadow: 0 0 9px #333; }
}

audio{
  display: none;
}


/*点击录音的CSS*/

.footer .dot {
    position: absolute;
    width: 92px;
    height: 92px;
    margin-left: 2%;
    top: 420px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border: 2px solid red;
    border-radius: 50%;
    z-index: 2;
}


.footer .pulse {
    position: absolute;
    width: 320px;
    height: 320px;
    left: 3%;
    top: 302px;
    border: 6px solid red;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    z-index: 1;
    opacity: 0;
    -webkit-animation: warn 2s ease-out;
    -moz-animation: warn 2s ease-out;
    animation: warn 2s ease-out;
    -webkit-animation-iteration-count: infinite;
    -moz-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
    box-shadow: 1px 1px 30px red;
}


.footer .pulse1 {
    position: absolute;
    width: 320px;
    height: 320px;
    left: 3%;
    top: 302px;
    border: 6px solid red;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    z-index: 1;
    opacity: 0;
    -webkit-animation: warn1 2s ease-out;
    -moz-animation: warn1 2s ease-out;
    animation: warn1 2s ease-out;
    -webkit-animation-iteration-count: infinite;
    -moz-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
    box-shadow: 1px 1px 30px red;
}

.pause-hidden{
  display: none;
}
@keyframes warn{
  0% {
      transform: scale(0.3);
      -webkit-transform: scale(0.3);
      opacity: 0.0;
  }
  25% {
      transform: scale(0.3);
      -webkit-transform: scale(0.3);
      opacity: 0.1;
  }
  50% {
      transform: scale(0.5);
      -webkit-transform: scale(0.5);
      opacity: 0.3;
  }
  75% {
      transform: scale(0.8);
      -webkit-transform: scale(0.8);
      opacity: 0.5;
  }
  100% {
      transform: scale(1);
      -webkit-transform: scale(1);
      opacity: 0.0;
  }
}

@keyframes warn1{
  0% {
      transform: scale(0.3);
      -webkit-transform: scale(0.3);
      opacity: 0.0;
  }
  25% {
      transform: scale(0.3);
      -webkit-transform: scale(0.3);
      opacity: 0.1;
  }
  50% {
      transform: scale(0.3);
      -webkit-transform: scale(0.3);
      opacity: 0.3;
  }
  75% {
      transform: scale(0.5);
      -webkit-transform: scale(0.5);
      opacity: 0.5;
  }
  100% {
      transform: scale(0.8);
      -webkit-transform: scale(0.8);
      opacity: 0.0;
  }
}
//guess.js
//获取应用实例
const app = getApp() 
var userId;//存储userId
var musicId;//musicId
var musicUrl;//music的地址
var answer;//答案
var chance;//答题机会
var needChance;//兑换机会数
var currentAnswer='当前没有播放音乐';//答案(音乐名)
var recordFlag=0;//录音标识
var hasNextMusic=true;//当前用户是否还未全部答出歌
// const innerAudioContext = wx.createInnerAudioContext()//音频上下文
const backgroundAudioManager = wx.getBackgroundAudioManager()
// innerAudioContext.onPlay(() => {
//   console.log('开始播放')
// })
// innerAudioContext.onError((res) => {
//   console.log("播放音乐时发生错误")
// })
//录音用的
const recorderManager = wx.getRecorderManager()

const options = {
  duration: 60000,
  sampleRate: 16000,
  numberOfChannels: 1,
  format: 'mp3',
  encodeBitRate: 24000
  //frameSize: 50
}

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showVoiceIcon: false,//是否显示大录音图标
    palseVisible: false,
    answerInput: '',//清空文本框用的
    isRotation: false,//播放图标是否旋转
  },

  onLoad: function (options) {
    console.log("加载到信息:" + app.globalData.userInfo)
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }    

      })
    }

    wx.getStorage({
      key: 'userId',
      success: function (res) {
          userId = res.data;
        console.log("首次加载页面时取到userId:" + res.data)
      },

      fail: function () {
        //do nothing
      }
    })
  
  },

  onUnload:function(){
    console.log("hide")
    backgroundAudioManager.stop();
  },

 //注册用户
registerUser: function(){
    wx.request({
      url: app.globalData.globalReqUrl+'/user/add',
      data: {
        avatarUrl: app.globalData.userInfo.avatarUrl,
        city: app.globalData.userInfo.city,
        country: app.globalData.userInfo.country,
        gender: app.globalData.userInfo.gender,
        nickname: app.globalData.userInfo.nickName,
        language: app.globalData.userInfo.language,
        province: app.globalData.userInfo.province
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code != 4001) {
          userId = res.data.content;
          console.log("新增或清除本地数据的用户的ID是:" + userId)
          //设置缓存
          wx.setStorage({
            key: "userId",
            data: userId
          })
          wx.showToast({
            title: '初始化信息成功',
            icon: 'success',
            duration: 1000
          })
        }
      },
      fail: function () {
        console.log("新增用户的请求失败");
      }
    })
},


  //得到用户信息
  getUserInfoByStorage: function() {
    var that = this;
    console.log("获取到的授权信息为:"+app.globalData.userInfo)
      //先从本地存储取userId,如果没有的话就注册
      wx.getStorage({
        key: 'userId',
        success: function (res) {
          if (res.data == undefined || res.data == 'undefined'){
            that.registerUser();
          }else{
            userId = res.data;
          }
          
          console.log("从本地取到userId:" + res.data)
        },

        fail: function () {
          that.registerUser();
        }
      })
   
    
  },




//监听输入框事件
answerInput: function (e) {
  this.setData({
    answer: e.detail.value
  })
},

//随机出题
getRandomMusic: function(){
  wx.request({
    url: app.globalData.globalReqUrl+'/music/getRandomMusic',
    data: {
      userId: userId
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded' // 默认值
    },
    method: 'POST',
    success: function (res) {
      if (res.data.content!=-1){
        musicId = res.data.content.id;
        musicUrl = res.data.content.url;
        currentAnswer = res.data.content.name;
        backgroundAudioManager.title = '壹曲觅知音'
        backgroundAudioManager.singer = '细肥尸丁'
        backgroundAudioManager.coverImgUrl = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524222813702&di=1b2468eebc105b308f8318da8e5a9b74&imgtype=0&src=http%3A%2F%2Fpic.qiantucdn.com%2F58pic%2F15%2F60%2F68%2F06T58PICw3s_1024.jpg'
        backgroundAudioManager.src = musicUrl// 设置了 src 之后会自动播放 
        console.log("音乐关键字:" + res.data.content.keywords)
        console.log("音乐URL:" + res.data.content.url)
      }else{
        hasNextMusic=false;
        wx.showToast({
          title: '乐库的音乐全部猜对了,敬请期待更多音乐',
          icon: 'none',
          duration: 2000
        })
      }
    },
    fail: function () {
      console.log("请求音乐失败")
    }
  })
},

  getUserChance:function(){
    var that = this;
    if (userId == undefined||userId=='undefined'){
     that.getUserInfoByStorage();
     console.log("getUserInfo时得到的userId:" + userId);
   }else{
      //先从本地存储取userId,如果没有的话就注册
      wx.getStorage({
        key: 'userId',
        success: function (res) {
          userId = res.data;
          console.log("点击播放按钮是加载到userID:" + userId)
          wx.request({
            url: app.globalData.globalReqUrl+'/user/getUserInfo',
            data: {
              id: userId
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: 'POST',
            success: function (res) {
              chance = res.data.content.chances
              console.log("用户还有" + chance + "次机会")
            },
            fail: function () {
              console.log("更新用户机会失败")
            }
          })
        },

        fail: function () {
          that.registerUser();
        }
      })
   }
  },


//点击发送按钮事件
submitAnswer: function(){
  var that = this;
  wx.getStorage({
    key: 'userId',
    success: function (res) {
      userId = res.data;
      console.log("从本地取到userId:" + res.data)
      console.log("发送的musicId是:" + musicId);
      console.log("发送的答案是:" + that.data.answer);
      answer = that.data.answer;
      that.setData({

        answerInput: ''

      });
      console.log(musicId)
      if(musicId!=undefined){
        that.answerByText();
      }else{
        wx.showToast({
          title: '请先播放音乐再识音',
          icon: 'none',
          duration: 1000
        })
      }
    },
    fail: function(){
      that.getUserInfoByStorage();
      if (musicId != undefined) {
        that.answerByText();
      }else{
        wx.showToast({
          title: '请先播放音乐再识音',
          icon: 'none',
          duration: 1000
        })
      }
    }
  });

  
},


answerByText: function () {
  var that = this;
  wx.request({
    url: app.globalData.globalReqUrl+'/user/answerByText',
    data: {
      userId: userId,
      musicId: musicId,
      answer: answer
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    method: 'POST',
    success: function (res) {
      console.log("文字结果:"+res.data)
      wx.showToast({
        title: res.data.msg,
        icon: 'success',
        duration: 2000
      })

      if (res.data.code == 1001) {
        //正确就换歌
        that.getRandomMusic();
      }

      if (res.data.code == 4003){
        that.registerUser();
      }

    },
    fail: function () {
      console.log("答题请求失败")
    },

    complete: function () {


    }

  })
},




clickSmallRecordIcon: function () {
    var that = this;

    that.setData({

      showVoiceIcon: (!that.data.showVoiceIcon)

    })
  },

  clickPlayIcon: function(){
    console.log("点击播放按钮时得到:"+app.globalData.userInfo)
    var that = this;
    if (app.globalData.userInfo == undefined || app.globalData.userInfo==null){
      wx.showModal({
        content: '您没授予壹曲觅知音获得用户信息的权限,是否去设置打开?',
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          console.log(res);
          //点击“确认”时打开设置页面
          if (res.confirm) {
            console.log('用户点击确认')
            wx.openSetting({
              success: (res) => {
                wx.getUserInfo({
                  success: res => {
                    app.globalData.userInfo = res.userInfo
                    that.getUserInfoByStorage();
                  }

                })
               }
            })
          } else {
            console.log('用户取消授权')
          }
        }
      });
    }else{
      var that = this;
      console.log("是否在旋转状态"+that.data.isRotation)
      if (!that.data.isRotation) {
        // that.getUserChance();
        var that = this;
        if (userId == undefined || userId == 'undefined') {
          that.getUserInfoByStorage();
         console.log("有权限时点击播放按钮userId为undefined")
        }else{
          wx.request({
            url: app.globalData.globalReqUrl+'/user/getUserInfo',
            data: {
              id: userId
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: 'POST',
            success: function (res) {
              chance = res.data.content.chances
              console.log("用户还有" + chance + "次机会")
              if (chance <= 0) {
                wx.showModal({
                  title: '免费机会已用完',
                  content: '是否使用积分兑换机会',
                  success: function (res) {
                    if (res.confirm) {
                      wx.showActionSheet({
                        itemList: ['10次机会', '5次机会', '3次机会', '2次机会', '1次机会'],
                        success: function (res) {
                          needChance = res.tapIndex
                          that.convertBanlanceToChance();
                        },
                        fail: function (res) {
                          console.log(res.errMsg)
                        }
                      })
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })
              } else {
                that.setData({
                  isRotation: (!that.data.isRotation),
                })
                that.getRandomMusic();
              }
            },
            fail: function () {
              console.log("更新用户机会失败")
            }
          })
        }
        

      } else {
         backgroundAudioManager.stop()//停止播放
         if(hasNextMusic){      
            wx.request({
                url: app.globalData.globalReqUrl+'/user/cutSong',
                data: {
                  userId: userId
                },
                header: {
                  'content-type': 'application/x-www-form-urlencoded' // 默认值
                },
                method: 'POST',
                success: function (res) {
                  console.log("切歌"+res.data.msg) 
                  wx.showToast({
                    title: '消耗了一次猜歌机会',
                    icon: 'none',
                    duration: 1000
                  })
                },
                fail: function () {
                  console.log("切歌请求失败")
                }
              })

         }

         that.setData({
           isRotation: (!that.data.isRotation),
         })
      }
    }
   
  },

  



  //录音键长按按钮
  startRecord: function (e) {
    console.log(recordFlag)
    if(recordFlag==0){
      recordFlag=recordFlag+1;
    }else{
      var that = this;
      // 设置询问
      wx.authorize({
        scope: 'scope.record',
        success(res) {
          recorderManager.start(options)
          wx.showLoading({
            title: '正在录音',
          })

          that.setData({
            palseVisible: true
          })
        },
        fail(res) {
          wx.showModal({
            content: '您没授予壹曲觅知音录音的权限,是否去设置打开?',
            confirmText: "确认",
            cancelText: "取消",
            success: function (res) {
              console.log(res);
              //点击“确认”时打开设置页面
              if (res.confirm) {
                console.log('用户点击确认')
                wx.openSetting({
                  success: (res) => {

                  }
                })
              } else {
                console.log('用户取消授权')
              }
            }
          });
        },
      })
    }
     
  },

  endRecord: function (e) {
    var that = this;
    wx.hideLoading()
    recorderManager.stop()
    that.setData({
      palseVisible: false
    })
    wx.showLoading({
      title: '正在解析',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1000)
    recorderManager.onStop((res) => {
      var that = this;
      var tempFilePath = res.tempFilePath;
      wx.getStorage({
        key: 'userId',
        success: function (res) {
          userId = res.data;
          console.log("从本地取到userId:" + userId)
          console.log("发送的musicId是:" + musicId);
          console.log("发送的录音文件路径是:" + tempFilePath);
          if(musicId!=undefined){
            wx.uploadFile({
              url: app.globalData.globalReqUrl+'/user/answerByVoice',
              filePath: tempFilePath,
              name: 'file',
              formData: {
                userId: userId,
                musicId: musicId,
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              method: 'POST',
              success: function (res) {

                console.log(res.data)
                var temp = res.data
                var msgStart = temp.lastIndexOf(':');
                var msgEnd = temp.lastIndexOf('"');
                var msg = temp.substring(msgStart + 2, msgEnd)

                var codeStart = temp.indexOf(":");
                var codeEnd = temp.indexOf(',');
                var code = temp.substring(codeStart + 1, codeEnd)

                console.log("语音回答后得到消息:" + msg)
                console.log("语音回答后得到代码:" + code)
                wx.showToast({
                  title: msg,
                  icon: 'none',
                  duration: 1000
                })
                if (code == 1001) {
                  console.log("语音答对了")
                  that.getRandomMusic();
                }

                if (code == 4003) {
                  that.registerUser();
                }
              },


              fail: function (res) {
                console.log("答题请求失败")
              }
            })
          }else{
            wx.showToast({
              title: '请先播放音乐再识音',
              icon: 'none',
              duration: 2000
            })
          }
          
        },
        fail: function () {
          console.log("获取localstorage失败")
          that.registerUser();
        },
      });
    })

    recorderManager.onError((res) => {
      console.log('录音时间太短:' + res.errMsg)
      wx.showToast({
        title: '录音时间太短',
        icon: 'none',
        duration: 1000
      })
    })

  },

  convertBanlanceToChance:function(){
    console.log(needChance)
    console.log(userId)
    wx.request({
      url: app.globalData.globalReqUrl+'/user/convertBanlanceToChance',
      data: {
        userId: userId,
        chanceNum: needChance
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
       console.log(res.data.msg)
       wx.showToast({
         title: res.data.msg,
         icon: 'none',
         duration: 2000
       })

      },
      fail: function () {
        console.log("答题请求失败")
      }

    })
  },

  getTip: function(){
    var that = this;
    if (currentAnswer != '当前没有播放音乐'){
      wx.showModal({
        title: '获取答案',
        content: '是否使用5积分获取答案',
        success: function (res) {
          if (res.confirm) {
            wx.request({
              url: app.globalData.globalReqUrl+'/user/getTipByBalance',
              data: {
                userId: userId
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
              },
              method: 'POST',
              success: function (res) {
                if (res.data.code == 2001){
                  that.setData({
                    answerInput: currentAnswer,
                    answer: currentAnswer
                  });
                  wx.showToast({
                    title: currentAnswer,
                    icon: 'success',
                    duration: 2000
                  })
                }else{
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                  })
                }
                
              },
              fail: function () {
                console.log("更新用户机会失败")
              }
            })

          } else if (res.cancel) {
            console.log('用户获取答案取消')
          }
        }
      })
    }else{
      wx.showToast({
        title: currentAnswer,
        icon: 'none',
        duration: 2000
      })
    }
  }


})

排行榜

<!--ranklist.wxml-->
<view class="container">
  <view class="header">
    <text class='text1' bindtap='moveTabR'>知音榜</text><text class='text2' bindtap='moveTabL'>积分榜</text>
    <view class='bg {{tabPosition}}'></view>
     <!-- <view class='tab'>积分榜</view> -->
  </view>
  <scroll-view class="list" scroll-y bindscrolltolower="{{hasReachBottom}}">
      <view wx:for-items="{{key}}" wx:key="item" wx:for-index="index">
          <view class="item">
                  <text class="index">{{index+1}}</text>
                  <image class="avatar" src="{{item.avatarUrl}}"></image>
                  <view class="left">
                      <text wx:if="{{item.gender==1}}" class="male">♂</text>
                      <text wx:elif="{{item.gender==2}}" class="female">♀</text>
                      <text wx:else class="unknow">ET</text>
                      <text class="nickname">{{item.nickname}}</text>
                      <text wx:if="{{item.city!=''}}" class="city">来自:{{item.city}}</text>
                      <text wx:else class="city">来自:外星</text>
                  </view>
                  <view class="right">
                    <text class="solve">{{tabPosition=='transformL'?'获得 '+item.balance+' 积分':'知音 '+item.solveCount+' 首'}}</text>
                    <text wx:if="{{item.type==0}}" class="type">普通群众</text>
                    <text wx:elif="{{item.type==1}}" class="type">开发者好友</text>
                    <text wx:elif="{{item.type==2}}" class="type">普通VIP</text>
                    <text wx:elif="{{item.type==3}}" class="type">至尊VIP</text>
                    <text wx:else class="type">开发者</text>
                  </view>
          </view>
        </view>
    </scroll-view>
    <view class="list">
      <view class="me">
              <text class="index">{{me.rank==NaN?'∞':me.rank}}</text>
                  <image class="avatar" src="{{me.avatarUrl==undefined?'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524222813702&di=1b2468eebc105b308f8318da8e5a9b74&imgtype=0&src=http%3A%2F%2Fpic.qiantucdn.com%2F58pic%2F15%2F60%2F68%2F06T58PICw3s_1024.jpg':me.avatarUrl}}"></image>
                  <view class="left">
                      <text wx:if="{{me.gender==1}}" class="male">♂</text>
                      <text wx:elif="{{me.gender==2}}" class="female">♀</text>
                      <text wx:else class="unknow">ET</text>
                      <text class="nickname">{{me.nickname==undefined?'未授权用户':me.nickname}}</text>
                      <text wx:if="{{me.city.length>0}}" class="city">来自:{{me.city}}</text>
                      <text wx:else class="city">来自:外星</text>
                  </view>
                  <view class="right">
                    <text wx:if="{{me.solveCount!=undefined&&me.balance!=undefined}}" class="solve">{{tabPosition=='transformL'?'获得 '+me.balance+' 积分':'知音 '+me.solveCount+' 首'}}</text>
                    <text wx:else class="solve">{{tabPosition=='transformL'?'获得 0 积分':'知音 0 首'}}</text>
                    <text wx:if="{{me.type==4}}" class="type">开发者</text>
                    <text wx:elif="{{me.type==1}}" class="type">开发者好友</text>
                    <text wx:elif="{{me.type==2}}" class="type">普通VIP</text>
                    <text wx:elif="{{me.type==3}}" class="type">至尊VIP</text>
                    <text wx:else class="type">普通用户</text>
                  </view>
       </view>
     </view>
</view>
 
/**ranklist.wxss**/
@import "../../bootstrap.wxss";
.container{
  width: 100%;
  height: 100%;
   background: #1DC7EA;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #1DC7EA), color-stop(100%, #4091ff));
    background: -webkit-linear-gradient(top, #1DC7EA 0%, #4091ff 100%);
    background: -o-linear-gradient(top, #1DC7EA 0%, #4091ff 100%);
    background: -ms-linear-gradient(top, #1DC7EA 0%, #4091ff 100%);
    background: linear-gradient(to bottom, #1DC7EA 0%, #4091ff 100%);
    overflow-y:hidden;
}

.header{
  height:45px;
  width: 91%;
  flex-direction:row;
  color: #FFFFFF;
  opacity: 1;
  background: rgba(255, 255, 255, 0.23);
  margin-top:10px;
  margin-bottom: 5px;
  border-radius: 10px;
  
}
.header .text1{
  position: absolute;
  margin-left:13%; 
  font-size: 27px;
  margin-top:3px;
}
.header .text2{
  position: absolute;
  margin-left:57%; 
  font-size: 27px;
   margin-top:3px;
}
.header .bg{
  height:45px;
  width: 50%;
  display: inline-block;
  flex-direction:row;
  color: whitesmoke;
  opacity: 1;
  background: rgba(0, 255, 255, 0.63);
  border-radius: 10px;
  z-index: -1;
  
}
.transformL{
  animation:moveToRight 1s forwards;
}
.transformR{
  animation:moveToLeft 1s forwards;
}
@keyframes moveToRight{
    0%{
         margin-left: 0%; 
    }
       
   100%{
          margin-left: 50%; 
    }
}
@keyframes moveToLeft{
    0%{
        margin-left: 50%;  
    }
      
   100%{
        margin-left: 0%; 
    }
}

.list{
  height:400px;
}
.footer{
  height: 30px;
}

.list .item{
  width: 91%;
  height: 75px;
  display: flex;
  flex-direction:row;
  color: #FFFFFF;
  opacity: 1;
  background: rgba(255, 255, 255, 0.23);
  margin-top:10px;
  margin-bottom: 10px;
  border-radius: 10px;
}

.list .me{
  width: 91%;
  height: 75px;
  display: flex;
  flex-direction:row;
  color: #FFEEEF;
  opacity: 1;
  background: rgba(0, 255, 255, 0.63);
  margin-top:10px;
  margin-bottom: 10px;
  border-radius: 10px;
}

.list .index{
  margin-top: 23px;
  margin-left: 15px;
  margin-right: 10px;
  color: greenyellow;
}

.list .avatar{
  width: 50px;
  height: 50px;
  display: flex;
  border-radius: 50%;
  align-items: center;
  justify-content: center;
  overflow: hidden;
   margin-top: 12px;
}

.list .left{
  display: inline-block;
  margin-top: 10px;
  text-overflow:ellipsis;
  width: 130px;
  overflow:hidden;
  white-space:nowrap;
}

.list .male{
  font-size: 20px;
  margin-top: 10px;
  margin-left: 5px;
  color: blue;
}

.list .female{
  font-size: 20px;
  margin-top: 10px;
  margin-left: 5px;
  color: plum;
}

.list .unknow{
  font-size: 20px;
  margin-top: 10px;
  margin-left: 5px;
  color: black
}

.list .nickname{
  font-size: 20px;
  margin-top: 10px;
  margin-left: 1px;
}

.list .city{
  margin-top: 5px;
  margin-left: 5px;
  display:block;
  font-size: 15px;
}


.list .right{
  display: inline-block;
  position: absolute;
  margin-left: 60%;
  margin-top: 15px;
}

.list .solve{
  font-size: 15px;
  display: block;
}

.list .type{
  margin-top: 5px;
  display:block;
  font-size: 15px;
  color: gold;
}
//ranklist.js
const app = getApp()
var user;
var userId;
var users;
var page=1;
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    mode: 1,
    hasReachBottom: "lower",
    tabPosition:''
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    var that = this;
    that.getRankList();
    that.getUserInfoByStorage();
   
  },
  //得到排行榜数据
 getRankList:function(){
    var that =this;
    page=1;
    wx.request({
      url: app.globalData.globalReqUrl+'/user/getRankList',
      data: {
        pageNum: page,
        pageSize: 10,
        mode: that.data.mode
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {

        users = res.data.content
        console.log('得到的用户数据为:' + users)
        that.setData({
          key: users,
          page: page
        });

      },
      fail: function () {
        console.log("请求用户失败")
      }
    })
 },

 appendRankList:function(){
   var that = this;
   // 页数+1  
   page = page + 1;
   console.log("当前页:" + page)
   wx.request({
     url: app.globalData.globalReqUrl+'/user/getRankList',
     data: {
       pageNum: page,
       pageSize: 10,
       mode: that.data.mode
     },
     header: {
       'content-type': 'application/x-www-form-urlencoded'
     },
     method: 'POST',
     success: function (res) {
       console.log(res.data.content.length)
       if (res.data.content.length>0) {
         users = users.concat(res.data.content);
         console.log('追加了用户数据,数据长度:' + users.length)
         that.setData({
           key: users,
           page: page
         });
       } else {
         that.setData({
           hasReachBottom: 'reachBottom'
         })
       }

       // 隐藏加载框  
       wx.hideLoading();
     },
     fail: function () {
       console.log("请求用户失败")
     }
   })
 },

  lower: function () {
    console.log('上拉了')
    var that = this;
    // 显示加载图标  
    wx.showLoading({
      title: '玩命加载中',
    })
    that.appendRankList(); 
  },  
  reachBottom: function(){
    wx.showToast({
      title: '已经到底部啦',
      icon: 'none',
      duration: 1000
    })
  },

  moveTabR: function(){
    var that = this;
    console.log("向左")
    page=1;
    that.setData({
      tabPosition: 'transformR',
      mode: 1,
      hasReachBottom: "lower" 
    })
    that.getRankList();
    that.getUserInfoById();
  },
  moveTabL: function () {
    var that = this;
    console.log("向右")
    page=1;
    that.setData({
      tabPosition: 'transformL',
      mode: 2,
      hasReachBottom: "lower"
    })
    that.getRankList();
    that.getUserInfoById();
  },
  //得到用户信息
  getUserInfoByStorage: function () {
    var that = this;
    console.log("获取到的授权信息为:" + app.globalData.userInfo)
    //先从本地存储取userId,如果没有的话就注册
    wx.getStorage({
      key: 'userId',
      success: function (res) {
        console.log("从本地取到用户Id:" + res.data)
        userId = res.data;
        if (userId!=undefined&&userId!='undefined'){
          that.getUserInfoById();
        }
      },

      fail: function () {
        if (app.globalData.userInfo!=null){
          that.registerUser();
        }
      }
    })


  },
  //注册用户
  registerUser: function () {
    var that = this;
    wx.request({
      url: app.globalData.globalReqUrl+'/user/add',
      data: {
        avatarUrl: app.globalData.userInfo.avatarUrl,
        city: app.globalData.userInfo.city,
        country: app.globalData.userInfo.country,
        gender: app.globalData.userInfo.gender,
        nickname: app.globalData.userInfo.nickName,
        language: app.globalData.userInfo.language,
        province: app.globalData.userInfo.province
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code != 4001) {
          userId = res.data.content;
          console.log("新增或清除本地数据的用户的ID是:" + userId)          
          //设置缓存
          wx.setStorage({
            key: "userId",
            data: userId
          })
          //得到单条用户信息
          wx.request({
            url: app.globalData.globalReqUrl+'/user/getUserInfoRanked',
            data: {
              id: userId,
              mode: that.data.mode
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            success: function (res) {
              user = res.data.content;
              console.log("新增或清除本地数据的用户的数据是:" + user)
              that.setData({
                me: user
              });
            },
            fail: function () {
              console.log("新增用户的请求失败");
            }
          })
        }
      },
      fail: function () {
        console.log("新增用户的请求失败");
      }
    })
  },
  getUserInfoById: function(){
    var that = this;
    //得到单条用户信息
    wx.request({
      url: app.globalData.globalReqUrl+'/user/getUserInfoRanked',
      data: {
        id: userId,
        mode: that.data.mode
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        user = res.data.content;
        console.log("新增或清除本地数据的用户的数据是:" + user)
        that.setData({
          me: user
        });
      },
      fail: function () {
        console.log("新增用户的请求失败");
      }
    })
  }
})

音乐收藏

<!--collectList.wxml-->
<view class="container">
    <view class="header">
      <text class='text1' bindtap='moveTabR'>已知音</text><text class='text2' bindtap='moveTabL'>已收藏</text>
      <view class='bg {{tabPosition}}'></view>
    </view>
 <scroll-view class="list" scroll-y bindscrolltolower="{{hasReachBottom}}">   
  <view wx:for-items="{{key}}" wx:key="item" wx:for-index="index">
      <view class="item">
        
              <text class="index">{{index+1}}</text>
              <view class="left">
                  <text class="songname">{{item.name}}</text>
                  <text class="author">{{item.author}}</text>
              </view>
              <view class="center">
                <text class="solve">已有 {{item.solveCount}} 知音</text>
                <text class="rate">{{tabPosition=='transformR'?'知音率 '+item.correctRate+' %':'已被 '+item.collectCount+' 知音收藏'}}</text>
              </view>
              <view class="right">
                <image src='https://nanmatou.club/files/zhiyin/icons/play.png' class="image" data-id='{{index}}' data-src='{{item.url}}' data-songname='{{item.name}}' data-author='{{item.author}}' style='{{playing==index?"display:none;":""}}'   bindtap='playMusic'></image>
                <image src='https://nanmatou.club/files/zhiyin/icons/pause.png' class="image" data-id='{{index}}' style='{{playing==index?"":"display:none;"}}' bindtap='pauseMusic'></image>
                <image src='https://nanmatou.club/files/zhiyin/icons/heart.png' data-id='{{index}}' data-musicid='{{item.id}}' class='image {{item.collect==false?"notCollect":"collect"}}' bindtap='collectOrNot'></image>
              </view>
      </view>
    </view>
  </scroll-view>
</view>

       
 
/**collectList.wxss**/
@import "../../bootstrap.wxss";
.container{
  width: 100%;
  height: 100%;
  background: #87CB16;
    background: -moz-linear-gradient(top, #87CB16 0%, #6dc030 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #87CB16), color-stop(100%, #6dc030));
    background: -webkit-linear-gradient(top, #87CB16 0%, #6dc030 100%);
    background: -o-linear-gradient(top, #87CB16 0%, #6dc030 100%);
    background: -ms-linear-gradient(top, #87CB16 0%, #6dc030 100%);
    background: linear-gradient(to bottom, #87CB16 0%, #6dc030 100%);
    background-size: 150% 150%;
}

.container .header{
  height:45px;
  width: 91%;
  flex-direction:row;
  color: #FFFFFF;
  opacity: 1;
  background: rgba(255, 255, 255, 0.23);
  margin-top:10px;
  margin-bottom: 5px;
  border-radius: 10px;
}

.container .list{
  height: 600px;
}

.header .text1{
  position: absolute;
  margin-left:13%; 
  font-size: 27px;
  margin-top:3px;
}
.header .text2{
  position: absolute;
  margin-left:57%; 
  font-size: 27px;
   margin-top:3px;
}
.header .bg{
  height:45px;
  width: 50%;
  display: inline-block;
  flex-direction:row;
  color: whitesmoke;
  opacity: 1;
  background: rgba(255, 215, 0, 0.63);
  border-radius: 10px;
  z-index: -1;
  
}
.transformL{
  animation:moveToRight 1s forwards;
}
.transformR{
  animation:moveToLeft 1s forwards;
}
@keyframes moveToRight{
    0%{
         margin-left: 0%; 
    }
       
   100%{
          margin-left: 50%; 
    }
}
@keyframes moveToLeft{
    0%{
        margin-left: 50%;  
    }
      
   100%{
        margin-left: 0%; 
    }
}

.container .item{
  width: 91%;
  height: 75px;
  display: flex;
  flex-direction:row;
  color: #FFFFFF;
  opacity: 1;
  background: rgba(255, 255, 255, 0.23);
  margin-top:13px;
  margin-bottom: 10px;
  border-radius: 10px;
}

.index{
  margin-top: 23px;
  margin-left: 15px;
  margin-right: 10px;
  color: greenyellow;
}


.left{
  display: inline-block;
  margin-top: 10px;
}


.songname{
  font-size: 17px;
  margin-top: 3px;
  margin-left: 1px;
  text-overflow:ellipsis;
  width: 100px;
  overflow:hidden;
  white-space:nowrap;
  display: block;
}

.author{
  margin-top: 3px;
  margin-left: 5px;
  display:block;
  font-size: 15px;
  text-overflow:ellipsis;
  width: 100px;
  overflow:hidden;
  white-space:nowrap;
}

.center{
  display: inline-block;
  position: absolute;
  margin-left: 40%;
  margin-top: 12px;
}


.solve{
  width: 20px;
  height: 20px;
  font-size: 15px;
}

.rate{
  margin-top: 5px;
  display:block;
  font-size: 15px;
  color: blueviolet
}

.right{
  position: absolute;
  margin-left: 70%;
  margin-top: 25px;
}

.image{
  margin-left: 5px;
   margin-right: 5px;
   width:20px;
   height:20px;
}

.invisible{
  display: none;
}

.collect{
  opacity: 0.4;
}

.notCollect{
 opacity: 1;
}
//collectList.js
const app = getApp()
var musics;
var page=1;
var userId;
const backgroundAudioManager = wx.getBackgroundAudioManager()

backgroundAudioManager.onEnded(function () {
  var index = parseInt(musics.length * Math.random())
  backgroundAudioManager.src = musics[index].url;
  console.log("随机播放了歌:" + musics[index].url);
  backgroundAudioManager.title = musics[index].name
  backgroundAudioManager.singer = musics[index].author
  backgroundAudioManager.coverImgUrl = 'https://nanmatou.club/files/zhiyin/icons/logo.png'
})


Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    playState: 'play',
    tabPosition: 'transformR',
    hasReachBottom: "lower",
  },
  onLoad: function (options) {
    page=1;
    var that = this;
    that.getUserInfoByStorage();

    wx.onBackgroundAudioStop(function () {
      console.log('onBackgroundAudioStop')
    })
  },

  //得到用户信息
  getUserInfoByStorage: function () {
    var that = this;
    console.log("获取到的授权信息为:" + app.globalData.userInfo)
    //先从本地存储取userId,如果没有的话就注册
    wx.getStorage({
      key: 'userId',
      success: function (res) {
        console.log("从本地取到用户Id:" + res.data)
        userId = res.data;
        if(userId==undefined||userId=='undefined'){
          that.registerUser();
        }else{
          that.getSolveMusic();
        }
      },

      fail: function () {
        if (app.globalData.userInfo!=null){
          that.registerUser();
        }
      }
    })


  },
  //注册用户
  registerUser: function () {
    var that = this;
    wx.request({
      url: app.globalData.globalReqUrl+'/user/add',
      data: {
        avatarUrl: app.globalData.userInfo.avatarUrl,
        city: app.globalData.userInfo.city,
        country: app.globalData.userInfo.country,
        gender: app.globalData.userInfo.gender,
        nickname: app.globalData.userInfo.nickName,
        language: app.globalData.userInfo.language,
        province: app.globalData.userInfo.province
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code != 4001) {
          userId = res.data.content;
          console.log("新增或清除本地数据的用户的ID是:" + userId)
          that.getSolveMusic();
          //设置缓存
          wx.setStorage({
            key: "userId",
            data: userId
          })
        }
      },
      fail: function () {
        console.log("新增用户的请求失败");
      }
    })
  },

  getSolveMusic:function(){
    var that = this;
    wx.request({
      url: app.globalData.globalReqUrl+'/user/getSolveList',
      data: {
        pageNum: page,
        pageSize: 10,
        userId: userId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {

        musics = res.data.content
        that.setData({
          key: musics,
          page: page
        });

      },
      fail: function () {
        console.log("请求用户失败")
      }
    })
  },

  lower: function () {
    console.log('上拉了')
    var that = this;
    // 显示加载图标  
    wx.showLoading({
      title: '玩命加载中',
    })
    // 页数+1  
    page = page + 1;
    wx.request({
      url: app.globalData.globalReqUrl+'/user/getSolveList',
      data: {
        pageNum: page,
        pageSize: 10,
        userId: userId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        console.log(res.data.content)
        if (res.data.content != undefined && res.data.content.length>0) {
            musics =musics.concat(res.data.content);
            that.setData({
              key: musics,
              page: page
            });
        
        }else{
          that.setData({
            hasReachBottom: 'reachBottom'
          })
        }
        wx.hideLoading(); // 隐藏加载框  
      },
      fail: function () {
        console.log("请求用户失败")
      }
    })
  },  
  reachBottom: function () {
    wx.showToast({
      title: '已经到底部啦',
      icon: 'none',
      duration: 1000
    })
  },

  playMusic: function(e){
     var that = this;
   
     //获取当前item的下标id  通过currentTarget.id
    var dataset = e.currentTarget.dataset;
    var id = dataset.id;
    var src = dataset.src;
    var songname = dataset.songname;
    var author = dataset.author;
    that.setData({
      playing: id
    })
    backgroundAudioManager.title = songname
    backgroundAudioManager.singer = author
    backgroundAudioManager.coverImgUrl = 'https://nanmatou.club/files/zhiyin/icons/logo.png'
    if(that.data.playing!=-1){
      backgroundAudioManager.src = src// 设置了 src 之后会自动播放 
      console.log("播放了歌:"+src);
    }
    
  },
  pauseMusic: function (e) {
    var that = this;
    //获取当前item的下标id  通过currentTarget.id
    var dataset = e.currentTarget.dataset;
    var id = dataset.id;
    that.setData({
      playing: -1//重置播放图标
    })
    backgroundAudioManager.pause();
    // console.log("当前播放位置:"+)
  },
  collectOrNot:function(e){
    var that = this;
    //获取当前item的下标id  通过currentTarget.id
    var dataset = e.currentTarget.dataset;
    var id = dataset.id;
    var musicid = dataset.musicid;
    console.log("获取"+id)
    wx.request({
      url: app.globalData.globalReqUrl+'/user/collectOrRemoveMusic',
      data: {
        userId: userId,
        musicId: musicid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        console.log("收藏结果:"+res.data.content)
        console.log(that.data.tabPosition)
        if (that.data.tabPosition =='transformR'){
          that.moveTabR();
        }else{
          that.moveTabL();
        }

      },
      fail: function () {
        console.log("请求用户失败")
      }
    })
  },
  moveTabR: function () {
    var that = this;
    console.log("向左")
    that.setData({
      tabPosition: 'transformR',
      hasReachBottom: 'lower'
    })
    page=1;
    that.getSolveMusic();
  },
  moveTabL: function () {
    var that = this;
    console.log("向右")
    that.setData({
      tabPosition: 'transformL',
      hasReachBottom: 'reachBottom'
    })
    if (userId != undefined || userId != 'undefined'){
      wx.request({
        url: app.globalData.globalReqUrl+'/user/getCollectMusic',
        data: {
          userId: userId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: function (res) {

          musics = res.data.content
          console.log(musics)
          that.setData({
            key: musics,
          });

        },
        fail: function () {
          console.log("请求用户失败")
        }
      })
    }
    
  },
  
})

抽积分

<!--luck.wxml -->
<view class="container">
<view class='note'>{{userBalance==null?'跪求∞积分(*^__^*) ':'您当前有 '+ userBalance+' 积分'}}</view>
<view class="container-out">
  <view class="circle" wx:for="{{circleList}}" style="top:{{item.topCircle}}rpx;left:{{item.leftCircle}}rpx;background-color: {{(index%2==0)?colorCircleFirst:colorCircleSecond}};"></view>
  <view class="container-in">
    <view class="content-out" wx:for="{{awardList}}" style="top:{{item.topAward}}rpx;left:{{item.leftAward}}rpx;background-color: {{(index==indexSelect)?colorAwardSelect:colorAwardDefault}};">
      <text class="award-image">{{item.imageAward}}</text>
    </view>
    <view class="start-btn" bindtap="startGame" style=" background-color:{{isRunning?'#e7930a':'#ffe400'}}">START</view>
  </view>
</view>
</view>
/**luck.wxss**/
.container{
  width: 100%;
  height: 610px;
    background: #7B68EE;
    overflow-y:hidden;
}
.container-out {
  height: 600rpx;
  width: 650rpx;
  background-color: #b136b9;
  margin: 0 auto;
  border-radius: 40rpx;
  box-shadow: 0 10px 0 #871a8e;
  position: relative;
}

.container-in {
  width: 580rpx;
  height: 530rpx;
  background-color: #871a8e;
  border-radius: 40rpx;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

/**小圆球
box-shadow: inset 3px 3px 3px #fff2af;*/

.circle {
  position: absolute;
  display: block;
  border-radius: 50%;
  height: 20rpx;
  width: 20rpx;
}

.content-out {
  position: absolute;
  height: 150rpx;
  width: 166.6666rpx;
  background-color: #f5f0fc;
  border-radius: 15rpx;
  box-shadow: 0 5px 0 #d87fde;
}

/**居中 加粗*/

.start-btn {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border-radius: 15rpx;
  height: 150rpx;
  width: 166.6666rpx;
  background-color: #ffe400;
  box-shadow: 0 5px 0 #e7930a;
  color: #f6251e;
  text-align: center;
  font-size: 45rpx;
  font-weight: bolder;
  line-height: 150rpx;
}

.award-image {
  position: absolute;
  margin: auto;
  top: 25px;
  left: 10px;
  text-align: center;
  height: 140rpx;
  width: 130rpx;
  font-size: 30rpx;
}

.note{
  text-align: center;
  margin-bottom: 5px;
  margin-top:230rpx;
  color: whitesmoke;
}
//luck.js
const app = getApp() 
var awardLength = 8;
var lucknum;
var lastLucktime;
var userId;
var userBalance;
var needModal=0;
Page({
  data: {
    circleList: [],//圆点数组
    awardList: [],//奖品数组
    colorCircleFirst: '#FFDF2F',//圆点颜色1
    colorCircleSecond: '#FE4D32',//圆点颜色2
    colorAwardDefault: '#F5F0FC',//奖品默认颜色
    colorAwardSelect: '#ffe400',//奖品选中颜色
    indexSelect: 0,//被选中的奖品index
    isRunning: false,//是否正在抽奖
    imageAward: [
      '再接再厉',
      '1积分',
      '2积分',
      '3积分',
      '再接再厉',
      '5积分',
      '10积分',
      '20积分',
    ],//奖品图片数组
  },

  onLoad: function () {
    var _this = this;
    //圆点设置
    var leftCircle = 7.5;
    var topCircle = 7.5;
    var circleList = [];
    for (var i = 0; i < 24; i++) {
      if (i == 0) {
        topCircle = 15;
        leftCircle = 15;
      } else if (i < 6) {
        topCircle = 7.5;
        leftCircle = leftCircle + 102.5;
      } else if (i == 6) {
        topCircle = 15
        leftCircle = 620;
      } else if (i < 12) {
        topCircle = topCircle + 94;
        leftCircle = 620;
      } else if (i == 12) {
        topCircle = 565;
        leftCircle = 620;
      } else if (i < 18) {
        topCircle = 570;
        leftCircle = leftCircle - 102.5;
      } else if (i == 18) {
        topCircle = 565;
        leftCircle = 15;
      } else if (i < 24) {
        topCircle = topCircle - 94;
        leftCircle = 7.5;
      } else {
        return
      }
      circleList.push({ topCircle: topCircle, leftCircle: leftCircle });
    }
    _this.setData({
      circleList: circleList
    })
    //圆点闪烁
    setInterval(function () {
      if (_this.data.colorCircleFirst == '#FFDF2F') {
        _this.setData({
          colorCircleFirst: '#FE4D32',
          colorCircleSecond: '#FFDF2F',
        })
      } else {
        _this.setData({
          colorCircleFirst: '#FFDF2F',
          colorCircleSecond: '#FE4D32',
        })
      }
    }, 500)
    //奖品item设置
    var awardList = [];
    //间距,怎么顺眼怎么设置吧.
    var topAward = 25;
    var leftAward = 25;
    for (var j = 0; j < 8; j++) {
      if (j == 0) {
        topAward = 25;
        leftAward = 25;
      } else if (j < 3) {
        topAward = topAward;
        //166.6666是宽.15是间距.下同
        leftAward = leftAward + 166.6666 + 15;
      } else if (j < 5) {
        leftAward = leftAward;
        //150是高,15是间距,下同
        topAward = topAward + 150 + 15;
      } else if (j < 7) {
        leftAward = leftAward - 166.6666 - 15;
        topAward = topAward;
      } else if (j < 8) {
        leftAward = leftAward;
        topAward = topAward - 150 - 15;
      }
      var imageAward = this.data.imageAward[j];
      awardList.push({ topAward: topAward, leftAward: leftAward, imageAward: imageAward });
    }
    _this.setData({
      awardList: awardList
    })


    wx.getStorage({
      key: 'userId',
      success: function (res) {
        userId = res.data;
        console.log("首次加载页面时取到userId:" + res.data)
      },

      fail: function () {
        //do nothing
      }
    })
  },
  //开始游戏
  startGame: function () {
    var that = this;
    if (app.globalData.userInfo == undefined || app.globalData.userInfo == null) {
      wx.showModal({
        content: '您没授予壹曲觅知音获得用户信息的权限,是否去设置打开?',
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          console.log(res);
          //点击“确认”时打开设置页面
          if (res.confirm) {
            console.log('用户点击确认')
            wx.openSetting({
              success: (res) => {
                wx.getUserInfo({
                  success: res => {
                    app.globalData.userInfo = res.userInfo
                    that.getUserInfoByStorage();
                  }

                })
              }
            })
          } else {
            console.log('用户取消授权')
          }
        }
      });
    }else{
    if (this.data.isRunning) return

    if (userId == undefined || userId == 'undefined') {
      that.getUserInfoByStorage();
      console.log("有权限时点击播放按钮userId为undefined")
    } else {
      wx.request({
        url: app.globalData.globalReqUrl+'/user/getUserInfo',
        data: {
          id: userId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        method: 'POST',
        success: function (res) {
          lastLucktime = res.data.content.lastLucktime.time
          lucknum = res.data.content.lucknum
          userBalance = res.data.content.balance
         
          console.log('上次抽奖时间:'+lastLucktime)
          console.log('剩余抽奖次数:'+lucknum)
          
          var nowTime = new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime();
           //如果还有机会次数并且
          if (lastLucktime < nowTime){
            console.log("小于了")
                that.setData({
                  isRunning: true
                })
                var _this = this;
                var indexSelect = parseInt(awardLength * Math.random())
                var balance = 0;
                if (indexSelect == 0) {
                  balance = 1;
                } else if (indexSelect == 1) {
                  balance = 2;
                } else if (indexSelect == 2) {
                  balance = 3;
                } else if (indexSelect == 4) {
                  balance = 5;
                } else if (indexSelect == 5) {
                  balance = 10;
                } else if (indexSelect == 6) {
                  balance = 20;
                } else {
                  balance = 0;
                }
                var i = 0;
                var timer = setInterval(function () {
                  indexSelect++;
                  //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度
                  i += 60;
                  if (i > 1000) {
                    //去除循环
                    clearInterval(timer)
                    //获奖提示

                    
                    if (balance != 0) {
                      wx.request({
                        url: app.globalData.globalReqUrl+'/user/drawluck',
                        data: {
                          balance: balance,
                          userId: userId,
                          isToday:false
                        },
                        header: {
                          'content-type': 'application/x-www-form-urlencoded'
                        },
                        method: 'POST',
                        success: function (res) {


                        },
                        fail: function () {
                          console.log("抽奖请求失败")
                        }
                      })

                      wx.showModal({
                        title: '恭喜您',
                        content: '获得了' + balance + "积分",
                        showCancel: false,//去掉取消按钮
                        success: function (res) {
                          if (res.confirm) {
                            that.setData({
                              isRunning: false,
                              userBalance: userBalance-5+balance
                            })
                          }
                        }
                      })
                    } else {
                      wx.showModal({
                        title: '很遗憾',
                        content: '没有获得积分,再接再厉',
                        showCancel: false,//去掉取消按钮
                        success: function (res) {
                          if (res.confirm) {
                            that.setData({
                              isRunning: false
                            })
                          }
                        }
                      })
                    }
                  }
                  indexSelect = indexSelect % 8;
                  that.setData({
                    indexSelect: indexSelect
                  })
                }, (200 + i))
          } else if (lastLucktime >= nowTime && lucknum>0){//如果是当日第二次抽奖
            console.log("大于了")
            that.setData({
              isRunning: true
            })
            var _this = this;
            var indexSelect = parseInt(awardLength * Math.random())
            var balance = 0;
            if (indexSelect == 0) {
              balance = 1;
            } else if (indexSelect == 1) {
              balance = 2;
            } else if (indexSelect == 2) {
              balance = 3;
            } else if (indexSelect == 4) {
              balance = 5;
            } else if (indexSelect == 5) {
              balance = 10;
            } else if (indexSelect == 6) {
              balance = 20;
            } else {
              balance = 0;
            }
            var i = 0;
            var timer = setInterval(function () {
              indexSelect++;
              //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度
              i += 60;
              if (i > 1000) {
                //去除循环
                clearInterval(timer)
                //获奖提示


                if (balance != 0) {
                  wx.request({
                    url: app.globalData.globalReqUrl+'/user/drawluck',
                    data: {
                      balance: balance,
                      userId: userId,
                      isToday: true
                    },
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    method: 'POST',
                    success: function (res) {


                    },
                    fail: function () {
                      console.log("抽奖请求失败")
                    }
                  })

                  wx.showModal({
                    title: '恭喜您',
                    content: '获得了' + balance + "积分",
                    showCancel: false,//去掉取消按钮
                    success: function (res) {
                      if (res.confirm) {
                        that.setData({
                          isRunning: false,
                          userBalance: userBalance-5+balance
                        })
                      }
                    }
                  })
                } else {
                  wx.showModal({
                    title: '很遗憾',
                    content: '没有获得积分,再接再厉',
                    showCancel: false,//去掉取消按钮
                    success: function (res) {
                      if (res.confirm) {
                        that.setData({
                          isRunning: false
                        })
                      }
                    }
                  })
                }
              }
              indexSelect = indexSelect % 8;
              that.setData({
                indexSelect: indexSelect
              })
            }, (200 + i))
          }
          else{
            console.log(needModal)
            if (needModal==0){
              needModal = needModal+1;
              wx.showModal({
                title: '今日抽奖次数已用完',
                content: '是否使用5积分兑换一次抽奖机会',
                success: function (res) {
                  if (res.confirm) {
                    that.getBalanceByBalance();

                  } else if (res.cancel) {
                    console.log('用户花积分抽奖取消')
                  }
                }
              })
            }else{
              that.getBalanceByBalance();
            }
           
          }
          

        },
        fail: function () {
          console.log("更新用户机会失败")
        }
      })
    }
    }
  },


 getBalanceByBalance: function(){
   var that = this;
   if (userBalance >= 5) {

     that.setData({
       isRunning: true,
       userBalance: userBalance - 5
     })
     var _this = this;
     var indexSelect = parseInt(awardLength * Math.random())
     var balance = 0;
     if (indexSelect == 0) {
       balance = 1;
     } else if (indexSelect == 1) {
       balance = 2;
     } else if (indexSelect == 2) {
       balance = 3;
     } else if (indexSelect == 4) {
       balance = 5;
     } else if (indexSelect == 5) {
       balance = 10;
     } else if (indexSelect == 6) {
       balance = 20;
     } else {
       balance = 0;
     }
     var i = 0;
     var timer = setInterval(function () {
       indexSelect++;
       //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度
       i += 60;
       if (i > 1000) {
         //去除循环
         clearInterval(timer)
         //获奖提示


         if (balance != 0) {
           wx.showModal({
             title: '恭喜您',
             content: '获得了' + balance + "积分",
             showCancel: false,//去掉取消按钮
             success: function (res) {
               if (res.confirm) {
                 that.setData({
                   isRunning: false,
                   userBalance: userBalance - 5 + balance
                 })
               }
             }
           })
         } else {
           wx.showModal({
             title: '很遗憾',
             content: '没有获得积分,再接再厉',
             showCancel: false,//去掉取消按钮
             success: function (res) {
               if (res.confirm) {
                 that.setData({
                   isRunning: false
                 })
               }
             }
           })
         }

         wx.request({
           url: app.globalData.globalReqUrl+'/user/getBalanceByBalance',
           data: {
             balance: balance,
             userId: userId,
           },
           header: {
             'content-type': 'application/x-www-form-urlencoded'
           },
           method: 'POST',
           success: function (res) {


           },
           fail: function () {
             console.log("抽奖请求失败")
           }
         })
       }
       indexSelect = indexSelect % 8;
       that.setData({
         indexSelect: indexSelect
       })
     }, (200 + i))

   } else {
     wx.showToast({
       title: '积分不足',
       icon: 'none',
       duration: 2000
     })
   }
 },

  //得到用户信息
  getUserInfoByStorage: function () {
    var that = this;
    console.log("获取到的授权信息为:" + app.globalData.userInfo)
    //先从本地存储取userId,如果没有的话就注册
    wx.getStorage({
      key: 'userId',
      success: function (res) {
        if (res.data == undefined || res.data == 'undefined') {
          that.registerUser();
        } else {
          userId = res.data;
        }

        console.log("从本地取到userId:" + res.data)
      },

      fail: function () {
        that.registerUser();
      }
    })


  },

  //注册用户
  registerUser: function () {
    wx.request({
      url: app.globalData.globalReqUrl+'/user/add',
      data: {
        avatarUrl: app.globalData.userInfo.avatarUrl,
        city: app.globalData.userInfo.city,
        country: app.globalData.userInfo.country,
        gender: app.globalData.userInfo.gender,
        nickname: app.globalData.userInfo.nickName,
        language: app.globalData.userInfo.language,
        province: app.globalData.userInfo.province
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        if (res.data.code != 4001) {
          userId = res.data.content;
          console.log("新增或清除本地数据的用户的ID是:" + userId)
          //设置缓存
          wx.setStorage({
            key: "userId",
            data: userId
          })
          wx.showToast({
            title: '初始化信息成功',
            icon: 'success',
            duration: 1000
          })
        }
      },
      fail: function () {
        console.log("新增用户的请求失败");
      }
    })
  },
})

全局配置

app.js

//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    globalReqUrl:'https://nanmatou.club/zhiyin',
    globalResourceUrl: 'https://nanmatou.club/files/zhiyin'
  }
})

app.json

{
  "pages":[
    "pages/index/index",
    "pages/introduction/introduction",
    "pages/ranklist/ranklist",
    "pages/luck/luck",
    "pages/guess/guess",
    "pages/collectList/collectList"
  
  ],
  "window":{
    "backgroundTextStyle":"dark",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "壹曲觅知音",
    "navigationBarTextStyle":"black"
  }
}

然后将bootstrap.css改编成bootstrap.wxss放在根目录

猜你喜欢

转载自blog.csdn.net/qq_37518622/article/details/81040200