<template> <div> <audio ref="audio" :src="audioSrc"></audio> <button @click="playAudio">播放</button> <button @click="changePlaybackRate(1.5)">加速</button> <button @click="changePlaybackRate(0.5)">减速</button> </div> </template> <script> export default { data() { return { audioSrc: "https://dashanbook.oss-cn-shenzhen.aliyuncs.com/av/2023/12/04/537a6f61f94344979789779e25ea5f61.mp3", endedListener: null, // 保存事件监听器 }; }, methods: { playAudio() { const audio = this.$refs.audio; audio.play(); // 如果存在旧的 ended 事件监听器,需要先将其移除 if (this.endedListener) { audio.removeEventListener("ended", this.endedListener); } // 保存新的事件监听器 this.endedListener = () => { // 音频播放完成后的操作,可以返回一个东西 // 使用 Promise 来返回结果 this.someFunction().then((result) => { console.log(result); }); // 移除事件监听器 audio.removeEventListener("ended", this.endedListener); }; // 在音频上添加事件监听器 audio.addEventListener("ended", this.endedListener); }, changePlaybackRate(rate) { this.$refs.audio.playbackRate = rate; }, someFunction() { return new Promise((resolve) => { // 在这里执行需要返回的操作(监听音频播放完成) resolve("返回的东西"); }); }, }, mounted() { // 在组件挂载时添加事件监听器 const audio = this.$refs.audio; audio.addEventListener("ended", this.endedListener); }, destroyed() { // 在组件销毁时移除事件监听器 const audio = this.$refs.audio; audio.removeEventListener("ended", this.endedListener); }, }; </script>