vue3切换轮播图,改变音频对应进度条的位置

839 阅读1分钟

最近在做移动端的音频播放,以轮播图的形式展现。

如图:

1.png

已知接口返回:

1.一个图片数组。

2.一条音频,例如mp3格式

3.一个config数组,用来截取每张图对应的时间段:如:config: [3.691043,15.150091,23.904603,32.310227,40.448821,48.691315,58.746145,70.646372,74.762438] 话不多说,上代码:

2.png

轮播图是vant库里面的组件,注释掉的部分可以用来作为页码。

3.png 应要求,音频audio是不展示出来的,只显示进度条和时间就可以了,进度条也是vant的进度条,只不过需要对它的percentage处理一下。

4.png

上面定义一下,需要用的变量。

//音频加载成功后获取时长

const showLong = () => {
  if (audioPlay.value) {
    duration.value = parseInt(audioPlay.value.duration);
  }
};

//滑动图片的函数

const checkImage = (index) => {
  if (!state.isMove) {
    let ct = (progress.value * duration.value) / 100;
    if (!isNaN(ct)) {
      audioPlay.value.currentTime = ct;
    }
    if (index == 0) {
      curr.value = 0;
      audioPlay.value.currentTime = 0;
    } else {
      audioPlay.value.currentTime = props.config[index - 1];
    }
  }
};

//下面是音频进度条播放过程中的处理

5.png

//处理时间格式

const toTime = (sec) => {
  //秒数转化为mm:ss形式
  let s = sec % 60 < 10 ? "0" + (sec % 60) : sec % 60;
  let min =
    Math.floor(sec / 60) < 10
      ? "0" + Math.floor(sec / 60)
      : Math.floor(sec / 60);
  return min + ":" + s;
};

由于写的过程中遇到了一个问题,就是正常进度条改变时候,以上是会让轮播图滚动对应的图片的,但和手动滑动轮播图时,事件相互影响,起了冲突。所以上面用到了定义的isMove,拿它去进行动态处理事件。 以防万一,加上了touchstart等方法。

// 滑动时isMove为false,禁止 '根据音频播放进度去判断轮播图位置的逻辑(也就是getCurr里的逻辑)'
const touchstart = () => {
  state.isMove = false;
};
const touchmove = () => {
  state.isMove = false;
};
const touchend = (index) => {
  setTimeout(() => {
    state.isMove = true;
  }, state.durationTime);
};

需要的话,可以加上手写的播放按钮,点击播放控制,vue3的获取dom的写法是上面绑定了ref为audioPlay,用audioPlay.value.play()就是播放意思,来替代vue2的ref。

const plays = () => {
  //播放暂停控制
  state.status = !state.status;
  if (is_stop.value) {
    console.log("播放");
    audioPlay.value.play();
  } else {
    console.log("暂停");
    audioPlay.value.pause();
  }
  emit("handleNum", 1);
};

大概是这样,总结的不是很详细。