这篇文章用了两个网易云音乐的接口(不清楚是否是官方的),附上官方接口链接: 网易云音乐API
/
本文所用接口:
1、http://musicapi.leanapp.cn/search
2、http://neteasecloudmusicapi.zhaoboy.com/song/url
效果图
相关代码如下
先用一个input和button来接收输入的内容,我用一个form来包起来,容易获取到输入的值
//index.wxml
<view>
<form bindsubmit="formsubmit"><view>请输入:<input type="text" name="input" /></view><button form-type="submit">搜索</button>
</form>
</view>
用接口来获取歌单
//index.js
Page({data: {},formsubmit:function(e){console.log(e.detail.value)wx.request({url: 'http://musicapi.leanapp.cn/search',data:{keywords: e.detail.value.input,//把输入框的值传给接口type: 1,limit: 100,//一次请求上限为100首,这里取最大offset:2},success:res =>{console.log(res)this.setData({list:res.data.result.songs//把获取到的歌曲名单赋给list})}})}})
获取到后把list遍历出来,同时获取歌曲的id,后面用来请求歌曲的播放链接
//index.wxml
<view wx:for="{{list}}" wx:key="list" data-id="{{item.id}}" bindtap="play">//此处data-id用来获取遍历中的item.id项
<view class="songs"><view>第{{index+1}}首:</view><view>{{item.artists[0].name}}</view><view>---</view><view>{{item.name}}</view>
</view>
</view>
//index.wxss
//写了个大概,不怎么美观
.songs{height: 40px;width: 100%;align-content: center;display:flex;flex-wrap: wrap;border: 1px solid wheat;
}
点击歌曲,获取到歌曲id,通过接口获取到链接
play:function(e){console.log(e.currentTarget.dataset.id)wx.request({url: 'http://neteasecloudmusicapi.zhaoboy.com/song/url',data:{id:e.currentTarget.dataset.id},success:function(res){console.log(res.data.data[0].url)//即歌曲播放链接}})}
获取到播放链接后即可调用微信自带的音频播放管理器wx.createInnerAudioContext()来实现点击播放
//在Page()外添加
const innerAudioContext = wx.createInnerAudioContext()
//在play方法里的调用函数success里添加
innerAudioContext.src = res.data.data[0].url//赋值播放链接
innerAudioContext.autoplay = true//实现在切歌时能自动播放
最后附上完整代码!
//index.wxml
<view>
<form bindsubmit="formsubmit"><view>请输入:<input type="text" name="input" /></view><button form-type="submit">搜索</button>
</form>
</view>
<view wx:for="{{list}}" wx:key="list" data-id="{{item.id}}" bindtap="play">
<view class="songs"><view>第{{index+1}}首:</view><view>{{item.artists[0].name}}</view><view>---</view><view>{{item.name}}</view>
</view>
</view>
//index.wxss
.songs{height: 40px;width: 100%;align-content: center;display:flex;flex-wrap: wrap;border: 1px solid wheat;
}
//index.js
const innerAudioContext = wx.createInnerAudioContext()
Page({data: {},formsubmit:function(e){console.log(e.detail.value)wx.request({url: 'http://musicapi.leanapp.cn/search',data:{keywords: e.detail.value.input,type: 1,limit: 100,offset:2},success:res =>{console.log(res)this.setData({list:res.data.result.songs})}})},play:function(e){console.log(e.currentTarget.dataset.id)wx.request({url: 'http://neteasecloudmusicapi.zhaoboy.com/song/url',data:{id:e.currentTarget.dataset.id},success:function(res){console.log(res.data.data[0].url)innerAudioContext.src = res.data.data[0].urlinnerAudioContext.autoplay = true}})}})