一、項目簡介
Vue音樂播放器是一個基於Vue.js和Webpack構建的開源播放器項目。該項目實現了音樂歌曲的在線播放、列表循環、歌詞同步顯示等多種功能。該項目的啟動和運行十分簡單,只需幾個簡單的命令即可在本地搭建一個完整的音樂播放器系統。此外,該項目還可以方便地擴展和定製,可以滿足不同用戶的個性化需求。
二、安裝和配置
1、安裝依賴
npm install
2、配置環境變量
在.env文件中修改以下配置:
VUE_APP_BASE_API=/api # 接口地址
VUE_APP_MUSIC_API=/music # 音樂資源地址
三、實現功能
1、音樂播放
通過Vue.js的生命周期函數和第三方插件完成音樂播放功能。在網頁加載完成後,使用Vue-resource插件異步獲取歌曲資源並進行音樂播放。播放頁面的組件化設計輕鬆實現了歌曲播放頁的編寫和拓展。該項目還實現了歌曲的暫停、切換和拖拽等多種操作,提高了用戶體驗度。
// 在Vue模板中使用audio標籤實現音樂播放
<audio ref="audioControl" @timeupdate="handleTimeupdate">
<source :src="currentSong.url">
</audio>
// Vue.js的生命周期函數使用Vue-resource插件異步獲取歌曲資源
created() {
this.$http.get(this.$api.getUrl('/song/url'), {
params: { id: this.currentSong.id }
}).then(res => {
if (res.data['data'][0].url !== null) {
this.currentSong.url = res.data['data'][0].url
this.$store.commit('setCurrentSong', this.currentSong)
this.$refs.audioControl.play()
}
})
},
2、歌曲列表
通過使用Vue-router插件組件化的設計,可以輕鬆實現歌曲列表的拓展和查看。每次加載列表時,都會進行異步獲取數據的請求。通過包括歌曲名稱、歌手、專輯、時長等多種顯示方式來提高用戶體驗。各種操作按鈕如添加、刪除、播放等操作的實現,增強了系統的可用性和靈活性。
// 獲取歌曲列表數據
this.$http.get(this.$api.getUrl('/playlist/detail'), {
params: { id: this.playlistId }
}).then(res => {
this.songs = this.formatSongs(res.data.playlist.tracks)
...
})
// 列表展示歌曲信息
<tr v-for="(item, index) in songs">
<td><span class="item-number">{{ index + 1 }}</span></td>
<td><span class="item-name" @click="handlePlay(item)">{{ item.name }}</span></td>
<td><span class="item-singer">{{ item.singer }}</span></td>
<td><span class="item-album">{{ item.album }}</span></td>
<td><span class="item-time">{{ item.time }}</span></td>
<td><span class="item-operate">
<i class="iconfont icon-shanchu" @click="handleDelete(item)"></i>
</span></td>
</tr>
3、音樂搜索
使用Vue組件化的思想,通過異步Ajax請求並對數據進行處理,實現音樂搜索的高效和準確。通過對歌曲名、歌手等信息的搜索,方便愉快的獲取自己所喜歡的音樂。
// 發送異步請求獲取搜索結果
this.$http.get(this.$api.getUrl('/search/suggest'), {
params: { keywords: this.query }
}).then(res => {
this.suggestList = res.data.result.allMatch
...
})
// 列表展示搜索結果
<li v-for="item in suggestList" @click="handleSelect(item.keyword)">{{ item.keyword }}</li>
4、歌曲歌詞
該項目使用Vue.js提供的指令創造了字面意義上的雙向綁定,根據當前歌曲播放時間顯示相應的歌詞。歌詞樣式優美而穩定,保證了用戶使用的體驗。
// 獲取歌曲歌詞
this.$http.get(this.$api.getUrl('/lyric'), {
params: { id: this.currentSong.id }
}).then(res => {
if (res.data.lrc) {
this.oriLyric = res.data.lrc.lyric
this.lyricObj = this.parseLyric(this.oriLyric)
...
}
})
// 段落輸出歌詞內容,判斷當前播放時間和歌曲歌詞時間是否相等,達到同步效果
<p :class="{ 'lyric-current': isActive(index) }" v-for="(line, index) in lyricList">
{{ line.text }}
</p>
四、總結
該音樂播放器項目從多個方面實現了音樂播放的需求,通過Vue組件化思想的運用優化了用戶體驗,使整個項目具有更強的可維護性和拓展性。同時,該項目也涵蓋了項目開發中重要步驟的實現(如網絡請求、數據解析、組件化開發),適合初學者進行學習和實踐。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/252224.html