用vue做一个简单的音乐播放器
时间: 2023-07-20 13:38:39 浏览: 69
好的,以下是一个基于 Vue 的简单音乐播放器示例:
```html
<template>
<div class="music-player">
<div class="player-controls">
<button @click="prevTrack">Prev</button>
<button @click="togglePlay">{{ isPlaying ? 'Pause' : 'Play' }}</button>
<button @click="nextTrack">Next</button>
</div>
<div class="track-info">
<h2>{{ currentTrack.title }}</h2>
<p>{{ currentTrack.artist }}</p>
</div>
<audio ref="audio" :src="currentTrack.source" @ended="nextTrack"></audio>
</div>
</template>
<script>
export default {
data() {
return {
tracks: [
{
title: 'Track 1',
artist: 'Artist 1',
source: '/path/to/track1.mp3'
},
{
title: 'Track 2',
artist: 'Artist 2',
source: '/path/to/track2.mp3'
}
],
currentTrackIndex: 0,
isPlaying: false
}
},
computed: {
currentTrack() {
return this.tracks[this.currentTrackIndex];
}
},
methods: {
prevTrack() {
this.currentTrackIndex = (this.currentTrackIndex - 1 + this.tracks.length) % this.tracks.length;
this.playTrack();
},
nextTrack() {
this.currentTrackIndex = (this.currentTrackIndex + 1) % this.tracks.length;
this.playTrack();
},
togglePlay() {
if (this.isPlaying) {
this.pauseTrack();
} else {
this.playTrack();
}
},
playTrack() {
this.$refs.audio.play();
this.isPlaying = true;
},
pauseTrack() {
this.$refs.audio.pause();
this.isPlaying = false;
}
}
}
</script>
<style>
.music-player {
display: flex;
flex-direction: column;
align-items: center;
}
.player-controls {
display: flex;
justify-content: space-between;
width: 200px;
}
audio {
display: none;
}
</style>
```
在这个示例中,我们定义了一个包含两个音轨的音乐播放器。通过 `currentTrackIndex` 数据属性来跟踪当前播放的音轨,以及 `isPlaying` 来记录播放状态。我们使用 `computed` 计算属性来获取当前正在播放的音轨对象。我们通过 `ref` 属性来获取音频元素的引用,并在 `methods` 中定义了一些方法来控制播放器的行为。最后,我们使用了一些简单的 CSS 来布局和样式化播放器。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)