![](/img/trans.png)
[英]How to send mp3 file from Java Backend to frontend and play the file in the Vue.js frontend
[英]How to play mp3 file in Vue3
下面是我的代码
audio.value?.play();
将导致 chrome 中的“在 promise 拒绝时暂停”
<template>
<div>
<audio
hidden="true"
ref="audio"
src="../../../assets/music/boom.mp3"
>
</audio>
</div>
</template>
<script lang='ts'>
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
name: "CommunicateVoice",
setup() {
const audio = ref<HTMLDivElement>();
onMounted(() => {
audio.value?.play();
});
return {
audio,
};
},
});
</script>
我找到了为什么它不起作用。 HTMLDivElement
导致问题。 下面的代码将在 Vue3 中使用 ts
<template>
<div>
<audio
hidden="true"
ref="audio"
>
<source src="../../../assets/music/boom.mp3" type="audio/mpeg">
</audio>
</div>
</template>
<script lang='ts'>
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
name: "CommunicateVoice",
setup() {
const audio = ref<HTMLAudioElement>();
onMounted(() => {
console.log(audio);
//@ts-ignore
audio.value?.play()
});
return {
audio,
};
},
});
</script>
<style scoped>
</style>
以上是一个有用的答案,我投了赞成票,但我想指出几个问题。 如果没有来自用户的点击事件,您将无法自动播放音频标签。 此外,应该是“audio.play”而不是“audio.value.play”。 这是使用自定义播放/暂停按钮的示例:
<template>
<div>
<button v-on:click="togglePlaying"></button>
<audio
hidden="true"
ref="audio"
>
<source src="../../../assets/music/boom.mp3" type="audio/mpeg">
</audio>
</div>
</template>
<script lang='ts'>
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "CommunicateVoice",
data() {
return {
playing: false
}
},
setup() {
const audio = ref<HTMLAudioElement>();
return {
audio,
};
},
methods: {
toggleAudio() {
this.playing = !this.playing
if (this.playing) {
this.audio.play()
} else {
this.audio.pause()
}
}
}
});
</script>
<style scoped>
</style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.