Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play mp3 file in Vue3

below is my code

audio.value?.play();

will cause 'paused on promise rejection' in 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>

like image 896
shunze.chen Avatar asked Sep 14 '25 10:09

shunze.chen


1 Answers

I found why it dosen't work. the HTMLDivElement cause the problem. below code will work in Vue3 with 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>
like image 119
shunze.chen Avatar answered Sep 16 '25 22:09

shunze.chen