小程序mpvue 项目 播放语音切换动图

Posted on 2020-01-14 15:24  嗷呜~  阅读(487)  评论(0编辑  收藏  举报

近期 小程序项目 ,个人简介模块有个语音介绍功能,播放语音时需要 切换gif 动图 来标识正在播放语音,暂停或停止播放时 切换为png 图片。

刚开始 是定义了两个类,想要通过添加 移除 类名来实现。但是发现在vue中 获取 dom元素时,报错。getElementById  if undefined。

最后发现 自己想多了。完全可以通过 vue 的 v-if 来实现。先定义一个 变量,在播放状态改变时 只需改变该变量的值即可。

具体实现 如下:

1,v-if 判断

 <span v-if="imgActive"  class="voicePlayImg text-xxl padding-left-sm "></span>
 <span v-else  class="voicePlayImgActive text-xxl padding-left-sm "></span>

2,定义变量

 

 

3,修改变量值

playVoice(tempFilePath, index, data) {
      let that = this;
      if (that.innerAudioContext && index == that.playIndex && !that.isPause) {
        that.innerAudioContext.pause();
        that.innerAudioContext.onPause(res => {
          that.isPause = true;
          console.log("已暂停");
          this.imgActive = true
        });
        return;
      }
      if (that.innerAudioContext) {
        that.isPause = false;
        that.innerAudioContext.destroy();
      }
      that.innerAudioContext = mpvue.createInnerAudioContext();
      that.innerAudioContext.autoplay = false;
      that.innerAudioContext.src = tempFilePath;
      that.innerAudioContext.play();
      that.innerAudioContext.onPlay(() => {
        that.isPause = false;
        console.log("开始播放");
        this.imgActive = false
        
      });
      that.innerAudioContext.onStop(() => {
        console.log("停止播放");
        innerAudioContext.destroy();
        this.imgActive = true
       
      });
      that.innerAudioContext.onError(res => {
        innerAudioContext.destroy();
      });
      that.innerAudioContext.onEnded(res => {
        console.log("结束播放");
        console.log(res);
        this.imgActive = true
        
      });
      if (index && index > -1) {
        that.playIndex = index;
        that.datas[index].voice = 1;
        if (data.voice) {
          that
            .http({
              url: api_url + "changeVoice",
              data: {
                id: data.id
              }
            })
            .then(res => {
              if (res.status) {
                console.log("语音状态更新成功");
              } else {
                console.log("语音状态更新接口changeVoice出错失败");
              }
            });
        }
      }
 },

4,style

.voicePlayImg{
  background: url('../../../../static/images/auto.png') no-repeat center/32rpx 32rpx; 
}
.voicePlayImgActive{
  background: url('../../../../static/images/auto.gif') no-repeat center/32rpx 32rpx; 
}