How to play audio file with vue.js?

Member

by larissa , in category: Javascript , 6 months ago

How to play audio file with vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 4 months ago

@larissa 

To play an audio file with Vue.js, you can use the HTML5 <audio> element. Here's an example:

  1. Import the audio file into your Vue component:
1
import audioFile from '@/assets/audio/sample.mp3';


  1. In your HTML template, add the
1
2
3
<audio ref="audio" controls>
  <source :src="audioFile" type="audio/mp3">
</audio>


  1. Add the audioFile data property to your component's data function:
1
2
3
4
5
data() {
  return {
    audioFile: audioFile
  };
}


  1. Add a method to play the audio:
1
2
3
4
5
methods: {
  playAudio() {
    this.$refs.audio.play();
  }
}


  1. You can then call the playAudio method wherever you want to start playing the audio. For example, you can add a button that triggers the playAudio method:
1
<button @click="playAudio">Play</button>


Now when you click the "Play" button, the audio file will start playing.


Note: Make sure to replace '@/assets/audio/sample.mp3' with the correct path to your audio file. You may also need to adjust the type attribute of the <source> element based on the audio file format you are using.