使用Audio 第一种 使用标签方式
<audio src="./tests.mp3" ref="audio"></audio><el-button @click="audioPlay()">播放Audio</el-button>audioPlay() {this.$refs.audio.currentTime = 0;this.$refs.audio.play();// this.$refs.audio.pause(); //暂停},
使用Audio 第二种 利用js构建Audio对象
audioJs() {var audio = new Audio();var url = require("./tests.mp3");audio.src = url;// audio.loop = true; //设置循环播放audio.play();// audio.pause(); //暂停
},
使用AudioContext播放
<template><div><el-button @click="playAudio()" v-show="!hasPlay">播放</el-button><el-button @click="resumeAudio()" v-show="hasPlay">{{isPause ? "继续" : "暂停"}}</el-button><el-button @click="stopAudio()" v-show="hasPlay">结束</el-button></div>
</template><script>
export default {data() {return {ctx: null,source: null,loop: false, //是否循环hasPlay: false, //是否播放 助变量 可忽略辅isPause: false, //是否暂停 助变量 可忽略辅};},methods: {// 播放async playAudio() {this.ctx = new (window.AudioContext || window.webkitAudioContext())();this.source = this.ctx.createBufferSource(); // 创建音频源头姐点const audioBuffer = await this.loadAudio();this.playSound(audioBuffer);},async loadAudio() {// const audioUrl = require("./test.mp3");const audioUrl = require("./tests.mp3");const res = await fetch(audioUrl);const arrayBuffer = await res.arrayBuffer(); // byte array字节数组const audioBuffer = await this.ctx.decodeAudioData(arrayBuffer,function (decodeData) {return decodeData;});return audioBuffer;},async playSound(audioBuffer) {this.source.buffer = audioBuffer; // 设置数据this.source.loop = this.loop; //设置,循环播放this.source.connect(this.ctx.destination); // 头尾相连// 可以对音频做任何控制this.source.start(0); //立即播放this.hasPlay = true;},// 暂停async resumeAudio() {if (this.ctx.state === "running") {this.ctx.suspend();this.isPause = true;} else if (this.ctx.state === "suspended") {this.ctx.resume();this.isPause = false;}},// 结束async stopAudio() {this.source.stop();this.hasPlay = false;this.isPause = false;},},
};
</script>
需要注意的是,以谷歌播放器为例,用户还没有跟document产生交互时,不允许播放器执行播放操作的,具体解决方案可另行查询,这边建议做一个类似弹窗的东西,引导用户产生交互动作。以上三个例子均由点击事件触发播放,因此不存在上述问题。