解决IOS微信打开网页语音和视频无法自动播放的问题(获取不到长度)

1,340 阅读1分钟

问题描述:最近做了一个根据音频地址获取语音时长,并通过手动点击触发语音播放,并显示播放进度的功能,在安卓上正常,在ios上死活获取不到,必须要点击一次才行,用了几种方式都不行,后来无意中发现某位大佬和我遇到了同样的问题,下边有某位大佬的解决方式,步骤如下:

<template>
  <div id='voicePlay' @click="playVoice">
    <audio class="audio" preload src="http://192.168.123.1/09fec52c-92f4-4833-b52e-b8420fd43033.wav" ref="audioEle">音频无法播放</audio>
    <i :class="['audio-play iconfont',isPlay?'icon-bofang':'icon-bofang1']"></i>
    <p class="audio-time">{{protime?protime:this.voice.long}}秒</p>
  </div>
</template>

<script>
export default {
    name:'voiceplayer',
    data(){
        return{
            protime:'',
            isPlay:false,
            voice:{}
        }
    },
    props:{
        url:""
    },
    mounted(){
        this.$nextTick(()=>{
        /*
        *主要是这里:WeixinJSBridgeReady
        *注意:此方法必须是在微信中打开网页才有效,如果在其它浏览器中打开需要做一下平台判断。
        */
          document.addEventListener('WeixinJSBridgeReady',()=>{
            const audio = this.$refs.audioEle;
            if(audio){
              audio.load();
              this.playVoice();
              audio.oncanplay=()=>{
                  const time = audio.duration;
                  const longTime = Math.round(time%60);
                  this.$set(this.voice,'long',longTime);
              };
              // audio.addEventListener('loadedmetadata',()=>{
              //     const time = audio.duration;
              //     const longTime = Math.round(time%60);
              //     this.$set(this.voice,'long',longTime);
              // });
              audio.addEventListener('timeupdate',()=>{
                  const curtime = audio.currentTime;
                  this.protime = this.voice.long-Math.round(curtime%60);
                  if(this.protime==0){
                      this.isPlay = false;
                  };
              });
            };
          });
        });
    },
    methods:{
        playVoice(){
            this.$nextTick(()=>{
                this.isPlay = true;
                const audio = this.$refs.audioEle;
                if(audio.paused){
                    audio.play();
                }else{
                    audio.pause();
                    this.isPlay = false;
                };
            });
        }
    }
}
</script>

<style>
#voicePlay{
    color: #57A2FF;
    text-align: center;
    font-size: 0.5rem;
    margin-top: 0.2rem;
    width: 100%;
    height: 100%;
}
#voicePlay>.audio{
    display:none;
}
#voicePlay .audio-play{
    margin-top: .7rem;
    display: inline-block;
}
</style>

针对WeixinJSBridgeReady的其它几个功能列举:
1、隐藏微信网页右上角的按钮
2、隐藏微信网页底部的导航栏

document.addEventListener('WeixinJSBridgeReady',function onBridgeReady() {
  // 通过下面这个API隐藏右上角按钮
  WeixinJSBridge.call('hideOptionMenu');
  // 通过下面这个API显示右上角按钮`
  WeixinJSBridge.call('showOptionMenu');
  // 通过下面这个API隐藏底部导航栏
  WeixinJSBridge.call('hideToolbar');
  // 通过下面这个API显示底部导航栏
  WeixinJSBridge.call('showToolbar');
});