html部分:
<!-- 此处省略 v-for循环音频的列表 -->
<!-- 点击两个图标进行切换播放状态-->
<div>
<img
class="pause_icon"
@click="handlePlayMusic(item.audioUrl)"
v-if="(musicSrc == item.audioUrl && !isPlay) || musicSrc !== item.audioUrl"
src="../../assets/voice/pause_icon.png"
alt=""
/>
<img
class="pause_icon"
@click="handleCloseMusic()"
v-if="musicSrc == item.audioUrl && isPlay"
src="../../assets/voice/play_icon.png"
alt=""
/>
</div>
<audio id="audio" ref="audio" class="aud" v-if="musicSrc">
<source :src="musicSrc" />
</audio>
js部分:
let musicSrc = ref(""); //当前选中音频文件的路径
let isPlay = ref(false); //当前音频是否在播放
const audio = ref(null);
// 播放音频
const handlePlayMusic = (path) => {
// path是列表中某项的音频路径
if (path !== musicSrc.value) {
musicSrc.value = "";
let timeout = setTimeout(() => {
musicSrc.value = path;
clearTimeout(timeout);
}, 100);
}
let platout = setTimeout(() => {
let dom = audio.value;
console.dir(dom);
dom.play();
isPlay.value = true;
clearTimeout(platout);
}, 300);
};
// 关闭音频
const handleCloseMusic = () => {
let dom = audio.value;
dom.pause();
isPlay.value = false;
musicSrc.value = "";
};
效果图:
注意:去切换音频文件的时候有100毫秒的延迟,一定要异步,因为有v-if,需要重新渲染,播放的时候也需要延迟执行。