思路:将原audio标签通过css隐藏,在通过css的div实现语音条样式,获取到audio的ref,操作audio的play、pause方法即可
效果图:
<template>
<div style="display: none">
<audio
controls
ref="audioRef"
@loadedmetadata="handleLoadedMetadata"
@ended="audioEnded"
>
<!-- <source :src="audioSrc" /> -->
<source src="../../assets/aa.mp3" />
您的浏览器不支持语音播放。
</audio>
</div>
<div
:style="{ width: audioWidth }"
class="audio-detail-msg"
@click="playAudio"
>
<div
class="audio-style"
:class="{
'add-animation': isPlay,
}"
>
<div class="small"></div>
<div class="middle"></div>
<div class="large"></div>
</div>
<div style="margin-left: 10px">{{ duration }}</div>
</div>
</template>
<script lang="ts" setup>
import { ref, computed } from "vue";
// const props = defineProps<{
// audioUrl: string,
// }>()
const audioRef = ref(null); // 音频组件ref
const isPlay = ref(false); //语音条播放效果
const duration = ref(null); //音频时长
//播放/停止音频
function playAudio() {
if (isPlay.value) {
audioRef?.value?.pause();
isPlay.value = false;
} else {
// audioRef.value.src = audioUrl;
audioRef?.value?.play();
isPlay.value = true;
}
}
//语音条播放结束
function audioEnded() {
isPlay.value = false;
}
//获取音频时长
function handleLoadedMetadata() {
if (audioRef.value) {
// 音频时长可以通过 audioRef.value.duration 获取
duration.value = audioRef.value.duration.toFixed(0);
}
}
//动态计算语音条宽度
const audioWidth = computed(() => {
return `${duration.value * 5 + 50}px`; // 将秒数乘以 5 得到宽度
});
</script>
<style lang="scss" scoped>
// 语音条
.audio-detail-msg {
display: flex;
align-items: center;
cursor: pointer;
padding: 0px 10px 0px 5px;
background-color: #d7d7d7;
border-radius: 2px;
.audio-style {
display: flex;
align-items: center;
height: 32px;
border-radius: 4px;
.small {
border: 4px solid #4c4c4c;
border-top-color: transparent;
border-left-color: transparent;
border-bottom-color: transparent;
}
.middle {
width: 16px;
height: 16px;
margin-left: -11px;
opacity: 1;
}
.large {
width: 24px;
height: 24px;
margin-left: -19px;
opacity: 1;
}
&>div {
border: 2px solid #4c4c4c;
border-top-color: transparent;
border-left-color: transparent;
border-bottom-color: transparent;
border-radius: 50%;
box-sizing: border-box;
}
&.add-animation {
.middle {
animation: show2 1.2s ease-in-out infinite;
}
.large {
animation: show3 1.2s ease-in-out infinite;
}
}
}
.duration-seconds {
font-size: 12px;
margin: 0 8px;
}
// 语音播放动画
@keyframes show2 {
0% {
opacity: 0;
}
10% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes show3 {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
60% {
opacity: 0;
}
100% {
opacity: 0;
}
}
}
</style>
下面附上代码截图:
文章来源:https://www.toymoban.com/news/detail-841752.html
文章来源地址https://www.toymoban.com/news/detail-841752.html
到了这里,关于h5音频标签模拟实现语音条(VUE3)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!