微信內自動播放音樂,隊列播放音樂,請求播放音樂。

微信內自動播放音樂,隊列播放音樂,請求播放音樂。

需求介紹 通過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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章