网易云音乐API查询歌曲

   网易云音乐API查询歌曲_第1张图片

实际效果查看 https://music.fanglonger.com/#/

musicModel = Music::getInstance();
        $this->musicUserSearchModel = UserSearch::getInstance();
    }

    /**
     * 用户搜索
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->isMethod('get')){
            return view('admin.music.index');
        }
        //获取网易歌曲参数
        $validate = Validator::make($this->postArr,['search_type'=>'required','s'=>'required']);
        if ($validate->fails()){
            return ajax_return(Code::SUCCESS,'success','',$validate->errors()->first());
        }
        $data = array('type' =>'search', 'search_type' =>$this->postArr['search_type'], 'limit' =>$this->postArr['limit'], 'offset' =>$this->postArr['page'], 's' =>$this->postArr['s']);
        $sessionAdmin = $request->session()->get('admin');
        //查询关键词
        $userSearchData = array('s' =>$this->postArr['s'],
            'username' =>empty($sessionAdmin->username)?(empty($sessionAdmin->user)?'游客':$sessionAdmin->user):$sessionAdmin->username,
            'ip' =>$request->ip(), 's_type' =>$this->postArr['search_type'], 'status' =>'1');
        //用户搜索关键词插入数据库,进行同步数据
        $searchWhere[] = array('s','=',$this->postArr['s']);
        $searchWhere[] = array('s_type','=',$this->postArr['search_type']);
        $userSearch = $this->musicUserSearchModel->getResult($searchWhere);
        if (empty($userSearch)){
            $this->musicUserSearchModel->addResult($userSearchData);
        }
        switch ($this->postArr['form']){
            case 'api':
                return $this->search($data);
                break;
            case 'self':
                $result = $this->musicModel->getResultLists($this->postArr['s'],$this->postArr['page'],$this->postArr['limit']);
                foreach ($result['data'] as $item){
                    $item->search_type_name = $this->searchType($item->search_type);
                }
                return ajax_return(Code::SUCCESS,'success','',$result);
                break;
            default:
                return ajax_return(Code::ERROR,'error');
                break;
        }
    }

    /**
     * 获取
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function search($data)
    {
        $url = $this->rootUrl.http_build_query($data);
        $result = json_decode(http_curl($url,[],'get'),true);
        $arr = [];
        if ($result['code']!=200){
            return ajax_return($result['code'],'error');
        }
        $i = 0;
        foreach ($result['result']['songs'] as $item) {
            $i++;
            $music['music_id'] = $item['id'];
            $music['music_name'] = $item['name'];
            $music['music_time'] = sprintf("%.0f",$item['dt']/1000);
            $music['mv'] = $item['mv'];
            $music['singer_name'] = $item['ar'][0]['name'];
            $music['singer_id'] = $item['ar'][0]['id'];
            $music['pic_url'] = $item['al']['picUrl'];
            $music['s'] = $data['s'];
            $music['search_type'] = $data['search_type'];
            $music['search_type_name'] = $this->searchType($data['search_type']);
            $music['id'] = $i;
            $arr['data'][] = $music;
        }
        $arr['total'] = $result['result']['songCount'];
        return ajax_return(Code::SUCCESS,'success','',$arr);
    }

    /**
     * 获取歌曲详情
     * @param  Request $request
     * @return array
     */
    public function play(Request $request)
    {
        if ($request->isMethod('get')){
            return ajax_return(Code::METHOD_ERROR,'error');
        }
        $music = $this->musicModel->getResult('music_id',$this->postArr['music_id']);
        if (!empty($music->music_url) && strtotime('+1 day',strtotime($music->updated_at))>strtotime(date("Y-m-d 23:59:59")) && $this->postArr['form'] === 'mysql'){
            $arr['music_url'] = $music->music_url;
            return ajax_return(Code::SUCCESS,'success','',$arr);
        }
        $data = array('type' =>'song', 'id' =>$this->postArr['music_id']);
        $result = json_decode(http_curl($this->rootUrl,$data,'get'),true);
        if ($result['code']!=200){
            return ajax_return($result['code'],'error');
        }
        $arr['music_url'] = $result['data'][0]['url'];
        $this->postArr['br'] = $result['data'][0]['br'];
        $this->musicModel->updateResult($arr,'music_id',$this->postArr['music_id']);
        return ajax_return(Code::SUCCESS,'success','',$arr);
    }

    /**
     * 单曲类型
     * @param $s_type
     * @return mixed|array
     */
    protected function searchType($s_type='')
    {
        $arr = [1 =>'单曲',10=>'专辑',100=>'歌手',1000=>'歌单',1002=>'用户',1004=>'mv',1006=>'歌词',1009=>'主播电台'];
        if (!empty($s_type)){
            return $arr[$s_type];
        }
        return $arr;
    }
}
layui.define(['layer','laypage'],function (exports) {
    let layer = layui.layer,laypage=layui.laypage,layIndex;
    layIndex = layer.load(2,{time:0,shade:[0.7,'#fff']});
    function initPage(total,cur_page,limit)
    {
        laypage.render({
            elem:"page",
            curr:cur_page||1,
            count:total,
            limit:limit,
            layout: ['count', 'prev', 'page', 'next', 'skip'],
            limits:[10,30,50,100],
            jump:function (obj,first) {
                if(!first){
                    app.page=obj.curr;
                }
            }
        })
    }
    let app = new Vue({
        el:"#app",
        data:{
            list:[],
            page:1,
            limit:20,
            cgi:{
                index:window.location.pathname,
                play:'/admin/music/play'
            },
            search_type:1,
            s:'粤语',
            form:'self',
            headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            intVal:0,
            indexVal:0,
            playing:false  //是否播放
        },
        methods:{
            getLists:function (page,limit) {
                let __self = this;
                $.ajax({
                    type:'post',
                    url:__self.cgi.index,
                    data:{page:page,limit:limit,search_type:__self.search_type,s:__self.s,form:__self.form},
                    headers: __self.headers,
                    dataType:'json',
                    success:function (response) {
                        console.log(response);
                        if (response.code === 200){
                            layer.close(layIndex);
                            initPage(response.item.total,__self.page,__self.limit);
                            __self.list =response.item.data;
                        }
                    }
                })
            },
            /**
             * todo:播放音乐
             * @param index
             */
            play:function (index) {
                //关闭所有窗口
                layer.closeAll();
                let __self = this;
                __self.list[index].form = __self.form;
                $.ajax({
                    type:'post',
                    url:__self.cgi.play,
                    data:__self.list[index],
                    headers: __self.headers,
                    dataType:'json',
                    success:function (response) {
                        if (response.code === 200){
                            layer.open({
                                title:__self.list[index].music_name,
                                type:1,
                                content:'
' + '' + '' + '
', maxmin:true, shade: 0, shadeClose:false, closeBtn:false, area:['600px','400px'] }); __self.intVal = 0; __self.indexVal = index+1; __self.playing = true; }else{ layer.msg('获取歌曲失败,请重试~',{icon:5}); } console.log(response); } }) }, /** * todo:定时器 */ clock:function () { this.intVal++; if (this.list[this.indexVal-1] && this.intVal===parseInt(this.list[this.indexVal-1].music_time)) { if (this.indexVal === this.limit){ this.indexVal = 0; this.page++; this.getLists(this.page,this.limit); } this.play(this.indexVal); this.intVal = 0; } console.log('===当前页==='+this.page); console.log('===当前播放歌曲==='+this.indexVal); console.log('===当前歌曲播放时长==='+this.intVal); console.log('===当前歌曲播放状态==='+this.playing); }, /** * todo:歌曲搜索 */ searchMusic:function () { this.getLists(this.page,this.limit) } }, mounted:function(){ this.$nextTick(function () { this.getLists(this.page,this.limit); }) }, created () { setInterval(() => { if (false!==this.playing){ this.clock() } }, 1000) }, watch:{ page:function () { this.getLists(this.page,this.limit) } }, computed:{ is_null:function () { return this.list.length===0; } } }); exports('music'); });
{{--模板继承--}}
@extends('layouts.admin')
{{--@yield 设置  @section 当子页面继承布局之后,即可使用 @section 命令将内容注入于布局的 @section 区块中  --}}
@section('content')
    
ID 歌曲ID 歌曲名 图片 歌曲时长 歌手ID 歌手名 类型 关键词 操作
@{{music.music_time}} s
暂无数据
@endsection {{--js--}} @section('js') @endsection

更多详情参考 https://zhuanlan.zhihu.com/p/30246788

你可能感兴趣的:(Vue,Laravel)