Home > Article > Web Front-end > How to introduce audio in vue
How to introduce audio in Vue
Introducing audio in Vue can add interactivity and immersion to your application. Here's how to do it:
Using the <audio>
element
The most straightforward way is to use HTML5 <audio>
elements. You can use this directly in your Vue template:
<code class="html"><template> <audio :src="audioUrl"></audio> </template> <script> export default { data() { return { audioUrl: 'path/to/audio.mp3' } } } </script></code>
src
attribute points to the location of the audio file.
Using the Vue Audio library
The Vue Audio library provides a more convenient way to deal with audio because it provides playback control and state management out of the box. To use it:
npm install vue-audio-component
Vue.use(VueAudio )
<code class="html"><template> <audio-player :src="audioUrl" controls></audio-player> </template></code>
audioUrl
property still points to the location of the audio file, controls
property is enabled Playback controls.
Controlling audio playback
Once the audio element is introduced, you can control its playback using JavaScript:
<code class="js">// 使用 `<audio>` 元素 const audioElement = document.querySelector('audio') audioElement.play() audioElement.pause() // 使用 Vue Audio 库 this.$refs.audioPlayer.play() this.$refs.audioPlayer.pause()</code>
Best Practices
The above is the detailed content of How to introduce audio in vue. For more information, please follow other related articles on the PHP Chinese website!