本次介绍的是音乐播放器APlayer结合WebAPI的使用,先给各位看下效果:
![](https://i-blog.csdnimg.cn/blog_migrate/7f94e2a86b92b9e7b9e8a2b602fec148.png)
上面就是APlayer的效果,然后这插件的地址是
下面是项目内容:
![](https://i-blog.csdnimg.cn/blog_migrate/742a7d1ce9a5394f6482047f8ee87244.png)
APlayerAndWebApi是处理APlayer的,而WebAPI则是生成音乐列表数据的json数据
1.前期准备(WebAPI跨域配置,在WebApi项目里配置):
本次调用的WEBAPI项目我把它设置在不同的项目了,因此会涉及到跨域的问题,因此要在NuGet里引用(技术支援:
http://www.cnblogs.com/landeanfen/p/5177176.html)
microsoft.aspnet.webapi.cors
然后在App_Start文件夹下面的WebApiConfig.cs文件夹配置跨域
//跨域配置
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
我们暂定三个“*”号,当然,在项目中使用的时候一般需要指定对哪个域名可以跨域、跨域的操作有哪些等等,请参照上面的技术支援地址,目前为了方便调试,全开放了。
2.WebApi音乐列表代码获取:
建立名为MusicModel的实体
namespace WebApi.Models
{
public class MusicModel
{
public string title { get; set; }
public string author { get; set; }
public string url { get; set; }
public string pic { get; set; }
}
}
然后就是获取音乐列表的接口
public class ValuesController : ApiController
{
[HttpGet]
[Route("api/GetMusicList")]
public IHttpActionResult GetMusicList()
{
//获取传过来的
List<MusicModel> musiclist = new List<MusicModel>();
MusicModel model = new MusicModel { title = "Wishing", url = "http://p2.music.126.net/SSbLcrSgYE8WnjDB8R-hEw==/1423867572602074.mp3", pic = "http://p3.music.126.net/AAq1qOhfyrClGK1mg3mGYQ==/18776360067593424.jpg", author = "水瀬いのり" };
musiclist.Add(model);
//这里先建立两个对象,加入到音乐列表
model = new MusicModel { title = "Stay Alive", url = "http://p2.music.126.net/HBaT8T5zNfeOs3moefyDSQ==/18766464462962331.mp3", pic = "http://p3.music.126.net/AAq1qOhfyrClGK1mg3mGYQ==/18776360067593424.jpg", author = "高橋李依" };
musiclist.Add(model);
return Json(musiclist);
}
}
3.APlayerAndWebApi里配置APlayer
HTML:
<div id="musicplayer" class="aplayer"></div>
<script src="~/js/APlayer/APlayer.min.js"></script>
<script src="~/js/APlayer/custom.js"></script>
JS代码:
jQuery.support.cors = true;
var postlink = "http://localhost:58982/";
$(function () {
initMusicList();
});
var initMusicList = function () {
var link = postlink + "api/getmusiclist";//调用WebAPI的接口获取音乐列表数据
var param = { };
$.ajax({
type: "GET",
url: link,
cache: false, //禁用缓存
data: param, //传入组装的参数
dataType: "json",
success: function (data) {
if (data != null) {
var musicData = data;
var apmusic = new APlayer({
element: document.getElementById('musicplayer'),
narrow: false,
autoplay: false,
showlrc: false,
mutex: true,
theme: '#ad7a86',
music: musicData
});
apmusic.volume(0.3);
apmusic.on('play', function () {
//此处为记录动作,比如用户点击了播放,用户自定义,详细查看API
});
}
},
error: function (ex) {
//alert(ex);
}
});
}
最后大功告成了。
附下载地址