如何在Vue3中播放mp3文件
How to play mp3 file in Vue3
下面是我的代码
audio.value?.play();
会导致 'paused on promise rejection' 在 chrome
<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
导致问题。
下面的代码将在 Vue 3 中使用 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.value?.play();
会导致 'paused on promise rejection' 在 chrome
<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
导致问题。
下面的代码将在 Vue 3 中使用 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>