You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.5 KiB

import musicApi from '../../api/music'
Page({
data: {
banners: [],
recommendPlaylists: [],
newSongs: [],
loading: false
},
onLoad() {
this.loadBanners()
this.loadRecommendPlaylists()
this.loadNewSongs()
},
onShow() {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 0 // 发现音乐 tab 索引为 0
})
}
},
async loadBanners() {
try {
const res = await musicApi.getBanners()
if (res.data.code === 200) {
this.setData({
banners: res.data.banners
})
}
} catch (error) {
console.error('加载轮播图失败:', error)
}
},
async loadRecommendPlaylists() {
try {
const res = await musicApi.getRecommendPlaylists()
if (res.data.code === 200) {
this.setData({
recommendPlaylists: res.data.result
})
}
} catch (error) {
console.error('加载推荐歌单失败:', error)
}
},
async loadNewSongs() {
try {
const res = await musicApi.getNewSongs()
if (res.data.code === 200) {
// 转换数据格式以匹配歌曲列表组件的要求
const songs = res.data.result.map(item => ({
id: item.id,
name: item.name,
ar: item.song.artists,
al: item.song.album
}))
this.setData({
newSongs: songs
})
}
} catch (error) {
console.error('加载新歌失败:', error)
}
},
handlePlaylistClick(e) {
const { id } = e.currentTarget.dataset
wx.navigateTo({
url: `/pages/playlist/index?id=${id}`
})
},
async handlePlay(e) {
const { song } = e.detail
if (!song || !song.id) return
try {
const res = await musicApi.getSongUrl(song.id)
if (res.data.code === 200 && res.data.data && res.data.data[0]) {
const url = res.data.data[0].url
if (url) {
const bgAudio = wx.getBackgroundAudioManager()
bgAudio.title = song.name
bgAudio.singer = song.ar?.map(a => a.name).join('/') || '未知歌手'
bgAudio.coverImgUrl = song.al?.picUrl || ''
bgAudio.src = url
// 更新播放器组件状态
this.selectComponent('#player-bar').setData({ song })
}
}
} catch (error) {
console.error('播放失败:', error)
wx.showToast({
title: '播放失败',
icon: 'none'
})
}
}
})