3

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>

shunze.chen
  • 309
  • 3
  • 10

2 Answers2

5

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>
shunze.chen
  • 309
  • 3
  • 10
0

The above is a helpful answer and I voted it up, but I wanted to point out a couple issues. You can't have an audio tag auto-play without a click event from the user. Also, instead of "audio.value.play" it should be "audio.play". Here's an example using a custom play/pause button:

<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>
Sam
  • 845
  • 7
  • 20