我们需要用到的API(返回格式均为json)
1. url: 'https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=普通朋友&type=1&offset=0&total=true&limit=10', //API接口地址
该接口可以搜索到需要音乐的十条ID
2.url: 'https://api.vvhan.com/api/music?id={{我们获取到的音乐ID}}&type=song&media=netease', // API接口地址
该接口用与我们获取歌曲的信息
思路:通过输入框得到歌曲信息或者歌手名字通过第一个api获取查询出来的这些歌曲的id->然后使用第二个api通过循环将这些id分别查询出歌曲信息->然后在展示到搜索结果页面->然后点击歌曲再次传递id到后台继续操作->通过播放器将音乐播放
实现代码
前端
<van-search label="歌曲" placeholder="请输入搜索关键词" use-action-slot bind:change="onChange">
<view slot="action" bindtap="onClick" class="but">搜索</view>
</van-search>
后端
onClick: function () {
const keyword = this.data.value;
var that = this;
// 在这里执行搜索逻辑,可以跳转到搜索结果页,或显示搜索结果等
wx.request({
url: 'https://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=+' + keyword + '+&type=1&offset=0&total=true&limit=10', // API接口地址
success: (res) => {
const songs = res.data.result.songs; // 获取歌曲数据
for (let i = 0; i < songs.length; i++) {
const song = songs[i];
const songId = song.id;
wx.request({
url: 'https://api.vvhan.com/api/music?id=+' + songId + '+&type=song&media=netease', // API接口地址
success: (res) => {
songListks[i] = res.data; // 获取歌曲列表数据
},
});
}
that.setData({
songList: songListks
})
},
});
},
播放
playSong: function (e) {
var sgId = e.currentTarget.dataset.id
wx.request({
url: 'https://api.vvhan.com/api/music?id=+' + sgId + '+&type=song&media=netease', // 替换为你的API接口地址
success: (res) => {
this.setData({
poster: res.data.cover,
name: res.data.name,
author: res.data.author,
src: res.data.mp3url
});
},
});
},
谢谢大家的观看!再见!(初学者,代码仅供参考)