微信内自动播放音乐,队列播放音乐,请求播放音乐。

微信内自动播放音乐,队列播放音乐,请求播放音乐。

需求介绍 通过ajax轮询,获得播放信息,如果返回的有音乐名称则播放,反之不播放。

个人流程总结

  1. 首先进入页面调用监听 playReady()函数,在函数中发起第一次请求
  2. 在第一次的请求回调中,播放一段静音音乐,然后再进行请求轮询
  3. 在请求轮询中根据返回信息判断是不是要放入播放列表,放入后再调用一次播放方法,调用时要根据当前播放状态决定是否调用。
  4. 在播放监听事件中,监听播放完毕后播放下标累加1,然后重新调用播放方法。

关键函数部分

    //自动播放音乐 无论是网页中还是微信中。
    function playReady(){ 
      let that = this;
      let play = function(){
        that.getStartMonito();
        document.removeEventListener("touchstart",play, false);
      };

      document.addEventListener("WeixinJSBridgeReady", function () {
        that.getStartMonito();
      }, false);
      document.addEventListener("touchstart",play, false);
    },

    that.domObj = document.getElementById("audio"); //获得audio对象
    that.domObj.addEventListener("ended",function(){
        //监听播放完毕
    });
    that.domObj.addEventListener("playing",function(){
        //播放中 
    });
    that.domObj.addEventListener("pause",function(){
        //暂停 
    });


    //播放函数
    function playMusic(){
      let that = this;
      console.log(that.playState);
      console.log("播放第"+(that.playIndex+1)+"个,**"+that.audioSrcs+"****一共"+this.audioSrcs.length+"个");
      console.log("当前播放"+that.audioSrcs[that.playIndex]);
      if(that.playIndex<this.audioSrcs.length){
        this.domObj.src = './static/braceletMusic/'+that.audioSrcs[that.playIndex]+'.mp3';
        this.domObj.pause();
        this.domObj.play();
      }else{
        console.log("undefind,此次不予播放");
      }
    },

我的业务代码

首先调用这个请求,在这个请求回调中首先播放一段空音乐,防止不能自动播放,我个人做过测试,如果我在轮询的回调中开始第一次播放音乐,是播放不了的。
不确定是不是因为延时任务的原因。所以我就先在第一次请求回调中播放了一个3S的静音音频然后再轮询中根据返回信息,往我们的播放列表中添加,
监听到播放完毕后,播放下标加1,一直排列播放。
getStartMonito(){
      let that = this;
      let data={
        user_uuid:that.user_uuid
      }
      that.$http({
        method:"post",
        url:"",
        data:Qs.stringify(data)
      }).then((res)=>{
         that.audioSrcs.push('jy3');
         that.playMusic();
         //开始轮询;
         that.intervalFun=setInterval(()=>{
           that.getData();
         },2000)
      },(err)=>{
        console.log(err);
      })
  }
getData(){
      let that = this;
      let data={
        user_uuid: that.user_uuid
      }
      that.$http({
        method:"post",
        url:"",
        data:Qs.stringify(data),
        async: false
      }).then((res)=>{
        console.log(res);
        if(res.data.code!="-1"){
          //将第一次的值进行保存,为以后轮询的数据进行比对,如果接收到新的数据则去除弹出框;
          if(that.flag == 0){
            that.update_date = res.data.data.bracelet.update_date;
          }
          //如果有一个不相等,则说明已经获取到了数据,则隐藏loading
          if(that.update_date != res.data.data.bracelet.update_date){
            console.log("获取到不同数据,更新视图,结束Loading");
            that.dataObj = res.data.data.bracelet;
            console.log(that.oldAudioList+"---"+res.data.data.bracelet.audios)
            //根据业务需求,判断此次返回的音频名称是否放入播放列表
            if(that.oldAudioList!=res.data.data.bracelet.audios && that.oldDate!=res.data.data.bracelet.update_date){
              if(res.data.data.bracelet.audios){
                let ms = res.data.data.bracelet.audios.split(";")
                for(let i=0;i<ms.length;i++){
                  that.audioSrcs.push(ms[i]);   
                }
              }
            }
            //如果当前返回请求时,发现有音乐在播放则不能调用播放方法,不然会切断当前播放音乐。要在播放完毕后调用,为什么要在此处调用播放方法
            //因为虽然有播放完毕监听,但是当播放列表播放完成时,这个时候如果在往播放列表中添加,就不会在自动播放了。
            if(that.playState){
              that.playMusic();
            }
            that.oldAudioList = res.data.data.bracelet.audios;
            that.oldDate = res.data.data.bracelet.update_date;
            that.dataObj.start_time = that.baseFun.formatTime(that.dataObj.start_time);
            that.lixianFlag = 0;
            that.loadingFun = false;
          }
        } 
      },(error)=>{
        console.log(error);
      });
      
    },

完整代码

<template>
  <div class="all">
    <audio autoplay id="audio"></audio>
  </div>
</template>

<script>
import Qs from 'qs'
import clockEchart from "../reportComponent/clockEchart";
import loading from "../reportComponent/topLoading";

export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: '测试',
      activeName:'week',
      intervalFun:"",
      dataObj:"",
      isNight:true,
      user_uuid:"",
      loadingFun:true,
      checkData:{},
      flag:0,
      userStatus:"",
      loadingMsg:"数据读取中",
      lixianFlag:0,
      domObj:"",
      update_date:"",
      audioSrcs:[],
      playIndex:0,
      playState:"", //是否播放完毕
      oldAudioList:"",
      oldDate:""
    }
  },
  components:{
    "v-clockEchart":clockEchart,
    "v-loading":loading
  },
  methods: {
    getData(){
      let that = this;
      let data={
        user_uuid: that.user_uuid
      }
      that.$http({
        method:"post",
        url:"******",
        data:Qs.stringify(data),
        async: false
      }).then((res)=>{
        console.log(res);
        // that.audioSrcs.push('AB7_3','B11B23_1');
        // if(that.playState){
        //   that.playMusic();
        // }
        // return false;
        if(res.data.code!="-1"){
          //将第一次的值进行保存,为以后轮询的数据进行比对,如果接收到新的数据则去除弹出框;
          if(that.flag == 0){
            that.update_date = res.data.data.bracelet.update_date;
          }
          //如果有一个不相等,则说明已经获取到了数据,则隐藏loading
          if(that.update_date != res.data.data.bracelet.update_date){
            console.log("获取到不同数据,更新视图,结束Loading");
            that.dataObj = res.data.data.bracelet;
            console.log(that.oldAudioList+"---"+res.data.data.bracelet.audios)
            if(that.oldAudioList!=res.data.data.bracelet.audios && that.oldDate!=res.data.data.bracelet.update_date){
              if(res.data.data.bracelet.audios){
                let ms = res.data.data.bracelet.audios.split(";")
                for(let i=0;i<ms.length;i++){
                  that.audioSrcs.push(ms[i]);   
                }
              }
            }
            if(that.playState){
              that.playMusic();
            }
            that.oldAudioList = res.data.data.bracelet.audios;
            that.oldDate = res.data.data.bracelet.update_date;
            // that.audioSrcs.push("AB89_3");
            that.dataObj.start_time = that.baseFun.formatTime(that.dataObj.start_time);
            that.lixianFlag = 0;
            that.loadingFun = false;
          }else{
            console.log("更新时间相同..."+that.lixianFlag);
            that.lixianFlag+=1;
          }
          that.flag+=1;
          if(that.lixianFlag == "10"){
            that.loadingMsg = "未检测到设备的实时数据,请检查设备状态,3秒后返回。";
            setTimeout(() => {
              that.loadingFun = false;
              var path = '******';
              wx.miniProgram.switchTab({url: path}); 
            }, 3000);
          }  
        }else{
            that.loadingMsg = "未检测到设备的实时数据,请检查设备状态,3秒后返回。";
            setTimeout(() => {
              that.loadingFun = false;
              var path = '******';
              wx.miniProgram.switchTab({url: path}); 
            }, 3000);
        }  
      },(error)=>{
        that.flag+=1;
        console.log(error);
      });
      
    },
    playMusic(){
      let that = this;
      console.log(that.playState);
      console.log("播放第"+(that.playIndex+1)+"个,**"+that.audioSrcs+"****一共"+this.audioSrcs.length+"个");
      console.log("当前播放"+that.audioSrcs[that.playIndex]);
      if(that.playIndex<this.audioSrcs.length){
        this.domObj.src = './static/braceletMusic/'+that.audioSrcs[that.playIndex]+'.mp3';
        this.domObj.pause();
        this.domObj.play();
      }else{
        console.log("undefind,此次不予播放");
      }
    },
    playReady(){
      let that = this;
      let play = function(){
        that.getStartMonito();
        document.removeEventListener("touchstart",play, false);
      };
      //   that.getStartMonito();
      document.addEventListener("WeixinJSBridgeReady", function () {
          that.getStartMonito();
      }, false);
      document.addEventListener("touchstart",play, false);
    },
    test(){

    },
    getStartMonito(){
      let that = this;
      let data={
        user_uuid:that.user_uuid
      }
      that.audioSrcs.push('jy3');
      that.playMusic();
      that.$http({
        method:"post",
        url:"****",
        data:Qs.stringify(data)
      }).then((res)=>{
        // console.log(res);
        if(res.data.code == "-1"){
          that.loadingMsg = res.data.msg+"3秒后返回。";
          setTimeout(() => {
              that.loadingFun = false;
              var path = '****';
              wx.miniProgram.switchTab({url: path}); 
            }, 3000);
        }else{
          //开始轮询;
          that.intervalFun=setInterval(()=>{
            that.getData();
          },2000)
        }
      },(err)=>{
        console.log(err);
      })
    }
  },
  mounted(){
    let that = this;
    // that.loadingFun = false;
    // that.playReady();//初次进入即开始调用播放,此时播放为空以触发为主。
    this.domObj = document.getElementById("audio");
    that.domObj.addEventListener("ended",function(){ //监听播放完毕
      console.log("第"+(that.playIndex+1)+"首已经播放完毕");
      that.playIndex+=1;
      that.playMusic();
    });
    that.domObj.addEventListener("playing",function(){ //播放中
      that.playState = false;
    });
    that.domObj.addEventListener("pause",function(){ //暂停
      that.playState = true;
    });
    that.isNight = that.baseFun.getNowIsNight();  //判断是否夜晚
    let uuid=this.baseFun.getQueryString("uuid"); //获取地址栏URL
    that.user_uuid = uuid || 'd52e6c92-d9da-11e9-a51d-00163e006c50';  // 
    that.playReady();
  },
  beforeDestroy(){
    that.audioSrcs.length=0;  
    that.domObj.src="";
    window.clearInterval(this.intervalFun);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.load{
  opacity: 0.4;
}
.headerback{
  width: 100px;
  display: inline-block;
  font-weight: bold;
  padding-left: 8px;
  vertical-align: super; 
  font-size: 1.1rem;
  .header-date{
    font-weight: 500;
    letter-spacing: 1px;
    font-size: 1rem;
    display: none;
  }
}
.headertitle{
  width: calc(100% - 110px);
  display: inline-block;
  text-align: center;
  font-size: 1.1rem;
  letter-spacing: 1px;
  margin-left: -50px;
}
.content-tab{
  width: 100%;
  height: 28px;
  @include font-main-color($font-main-color1);
  line-height: 30px;
  border-radius: 5px;
  .content-tab-menu{
    width: 25%;
    float: left;
    height: inherit;
    line-height:26px;
    text-align: center;
    border: 1.5px solid;
    margin-right: -1.5px;
    font-size: 1rem;
    @include  border-color($font-main-color1);
  }
}
.active-tab{
  @include font-main-background-color($font-main-color1);
}
.content-tab :nth-child(1){
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
}

.content-tab :nth-child(4){
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}
.content-date{
  width: 100%;
  margin-top: 10px;
  padding: 0px 5px; 
  .content-date-left{
    float: left;
    text-align: left;
    width: 44%;
    span{
      @include background-icon-color($background-icon-color1);
      border-radius: 50%;
      @include font-main-color($font-main-color1);
      padding: 5px;
      display: inline-block;
      text-align: center;
      font-weight: bold;
    }
  }
  .content-date-center{
    float: left;
    text-align: center;
    width: 12%;
    border-bottom: 1px solid;
    letter-spacing: 2px;
    @include border-color($font-main-color1);
    font-weight: bold;
    @include font-main-color($font-main-color1);
  }
  .content-date-right{
    float: left;
    text-align: right;
    width: 44%;
    span{
      @include background-icon-color($background-icon-color1);
      border-radius: 50%;
      @include font-main-color($font-main-color1);
      display: inline-block;
      padding: 5px;
      text-align: center;
      font-weight: bold;
    }
  }
}
.content-echart{
  width: 100%;
  padding-top: 10px;
  height: calc(100% - 35px);
  overflow: hidden;
  .content-echart-top-content{
    width: 100%;
    font-size: 0;
    height: auto;
    @include font-tiemtext-color($font-tiemtext-color1);
    .content-echart-top-content-left{
      display: flex;
      width: 50%;
      float: left;
      flex-direction: column;
      justify-content: space-around;
      padding-left: 20px;
      padding-bottom: 0px;
      .content-echart-top-content-left-wenzi{
        font-size: 0.9rem;
         @include  font-timetitle-color($font-timetitle-color1);
      }
      .content-echart-top-content-left-shijian{
        @include deviceMonSleepStage-color($deviceMonSleepStage-color1);
        font-size: 0.9rem;
        letter-spacing: 1.5px;
        width: 200px;
        margin-top: 5px;
        strong{
          font-size: 1rem;
          font-weight: bold;
        }
      }
    }
    .content-echart-top-content-right{
      display: flex;
      width: 50%;
      font-size: 1rem;  
      float: left;
      flex-direction: column;
      justify-content: space-around;
      text-align: right;
      padding-right: 20px;
      .content-echart-top-content-right-wenzi{

        .content-echart-top-content-right-wenzi1{
          font-size: 0.9rem;
          @include  font-timetitle-color($font-timetitle-color1);
          display: inline-block;
        }
        .content-echart-top-content-right-shijian{
          font-size: 1rem;
          font-weight: bold;
          display: inline-block;
        }
      }
    }
  }
}
.content-description{
  width: 100%;
  text-align: center;
  font-size: 1.3rem;
  font-weight: bold;
  letter-spacing: 1px;
  // @include font-result-color($font-result-color1);
}
.content-hr-margin{
  width: 92%;
  margin-left: 4%;
}
.content-explain{
  width: 90%;
  margin-left: 5%;
  font-size: 0;
  height: calc(100% - 63px);
  overflow-y: scroll;
  overflow-x: hidden;
  padding-bottom: 20px;
  .content-explain-wenzi{
    width: 48%;
    height: 100%;
    margin-left: 1%;
    float: left;
    overflow-x: hidden;
    overflow-y: scroll;
      div{
        // display: inline-block;
        font-size: 0.8rem;
        width: 100%;
        height: auto;
        text-align: left;
        color: #1C8FBF;
        margin: 2%;
        border-radius: 5px;
        word-break: break-all;
        padding: 7px;
        line-height: 20px;
        vertical-align: middle;
        letter-spacing: 1px;
        // @include background-explain-color($background-explain-color1);
        strong{
          // font-size: 1.3rem;
          // color: #292020;
          font-weight: 400;
        }
        img{
          width: 28px;
          vertical-align: sub;
        }
      }
  }
}
.dataList{
  height: 12px;
  span{
     @include font-main-color($font-main-color1);
  }
}
</style>
发布了114 篇原创文章 · 获赞 67 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_38880700/article/details/102996757