vue3 在线播放语音 mp3
播放、暂停、停止
<template><div><button @click="togglePlay">{{ isPlaying ? "暂停" : "播放" }}</button><button @click="stopAudio">停止</button><p>播放进度:{{ Math.round(progress) }}%</p></div>
</template><script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import audioSrc from "@/assets/mp3/stop.mp3";// 音频对象
let audio = null;// 播放状态
const isPlaying = ref(false);// 播放进度(百分比)
const progress = ref(0);// 初始化音频
onMounted(() => {audio = new Audio(audioSrc);// 监听播放进度audio.addEventListener("timeupdate", () => {progress.value = (audio.currentTime / audio.duration) * 100;});
});// 切换播放/暂停
const togglePlay = () => {if (isPlaying.value) {audio.pause();} else {audio.play().catch(error => {console.error("播放被阻止:", error);// 处理自动播放策略限制(需用户交互后才能播放)});}isPlaying.value = !isPlaying.value;
};// 停止播放
const stopAudio = () => {audio.pause();audio.currentTime = 0;progress.value = 0;
};// 组件卸载时清理资源
onBeforeUnmount(() => {audio.pause();audio.removeEventListener("timeupdate");
});
</script>
有时间轴
<template><div><audio ref="audioPlayer" controls><source :src="safeAudioUrl.mp3" type="audio/mpeg" /></audio><button @click="togglePlay">{{ isPlaying ? "暂停" : "播放" }}</button><p v-if="error">{{ error }}</p></div>
</template><script setup>
import { ref, computed } from "vue";
// 直接导入音频文件
import notificationSound from "@/assets/mp3/alarm.mp3";const audioPlayer = ref(null);
const isPlaying = ref(false);
const error = ref(null);const safeAudioUrl = computed(() => ({mp3: notificationSound
}));const togglePlay = () => {if (!audioPlayer.value) return;if (isPlaying.value) {audioPlayer.value.pause();} else {audioPlayer.value.play().catch(err => {error.value = `播放失败: ${err.message}`;});}isPlaying.value = !isPlaying.value;
};audioPlayer.value?.addEventListener("error", e => {console.log("1111111111e: ", e);const errors = {1: "MEDIA_ERR_ABORTED - 用户中止",2: "MEDIA_ERR_NETWORK - 网络错误",3: "MEDIA_ERR_DECODE - 解码错误",4: "MEDIA_ERR_SRC_NOT_SUPPORTED - 格式不支持"};error.value = errors[audioPlayer.value.error?.code] || "未知错误";
});
</script>