I am attempting to setup a basic button click in Vue 3 Composition API to trigger a sound effect. Currently, my setup function includes an mp3 sound effect imported from the assets folder then passed into a ref method with an HTMLAudioElement type, then assigned to a const called "play". After adding the "play" constant to the return, I then added "play" to a click handler in the button. I'm not getting errors in the console, but the button is still not triggering the sound effect. How can I go about configuring the setup function and button to trigger the sound effect? Here is my code:
<template>
<div div >
<button @click="play">Click</button>
</div>
</template>
<script>
import { ref } from 'vue'
import { trumpetSfx } from '../assets/demo_src_assets_fanfare.mp3'
export default {
name: 'Button',
components: {},
setup() {
const play = ref<HTMLAudioElement>(trumpetSfx);
return { play }
}
}
</script>
CodePudding user response:
You can use Audio API directly from javascript:
import trumpetSfx from '../assets/demo_src_assets_fanfare.mp3'
...
setup() {
const audio = new Audio(trumpetSfx);
function play() {
audio.play()
}
return { play }
}
...
CodePudding user response:
const trumpetSfx = require("../assets/demo_src_assets_fanfare.mp3");
export default {
setup() {
const audio = new Audio(trumpetSfx);
const handleClick = () => {
audio.play()
}
return { audio, handleClick }
}
}
