Junichi模板调用全民K歌音乐源链

Author Avatar
云璃 2017年08月29日

通过调用全民 K 歌 API 直接使用全民 K 歌播放音乐。

编辑文件 header.php

musicSrc

<?php
/**
 * 调用全民K歌API获取playurl
 * @param  string $id 全民K歌歌曲id
 * @return string     歌曲直链
 */
function curlApi($id) {
    $url = "http://cgi.kg.qq.com/fcgi-bin/kg_ugc_getdetail?inCharset=GB2312&outCharset=utf-8&v=4&shareid=".$id."&callback=json";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($curl);
    curl_close($curl);
    $urlJson = json_decode(substr($ret,5,-1));
    return substr($urlJson->data->playurl,5);
}

/**
 * 组装url
 * @param  array|string $id 全民K歌歌曲id
 * @return array|string     歌曲直链
 */
function curlId($id) {
    if (is_array($id)) {
        foreach ($id as $k => $v) {
            $data[] = curlApi($v);
        }
        $data = implode(",", $data);
    } else {
        $data = curlApi($id);
    }
    return $data;
}

/**
 * 写入缓存
 * @param array|string  $id   全民K歌歌曲id
 * @param string  $cache_file 缓存路径
 * @param boolean $update     更新(true)/写入(flase)
 * @return string 歌曲直链组装字符串
 */
function setCache($id, $cache_file, $update = false) {
    if(isset($id)) {
        if (strpos($id, ",")) {
            $data[0] = curlId(explode(",", $id));
        } else {
            $data[0] = curlId($id);
        }
        $data[1] = $id;
        if($update) {
            unlink($cache_file);
        }
        file_put_contents($cache_file,serialize($data));
        return $data[0];
    }
}

//设置缓存路径及缓存时间
define('CACHE_ROOT', dirname(__FILE__).'/cache');
define('CACHE_LIFE', 3600);
define('CACHE_SUFFIX','.cache');
$file_name  = date("Y-m-d").CACHE_SUFFIX;
$cache_file = CACHE_ROOT.'/'.$file_name;

//存在缓存 && 缓存超时 && 修改歌曲设置 => 更新缓存
if (file_exists($cache_file)) {
    if (time()-filemtime($cache_file)<CACHE_LIFE) {
        $data = unserialize(file_get_contents($cache_file));
        if($data[1] !== $this->options->socialmusic) {
            echo setCache($this->options->socialmusic, $cache_file, true);
        } else {
            echo $data[0];
        }
    } else {
        echo setCache($this->options->socialmusic, $cache_file, true);
    }
} else {
    if (!file_exists(CACHE_ROOT)) {
            mkdir(CACHE_ROOT,0777);
            chmod(CACHE_ROOT,0777);
    }
    echo setCache($this->options->socialmusic, $cache_file);
}
?>

编辑文件 functions.php

$socialmusic = new Typecho_Widget_Helper_Form_Element_Text('socialmusic', NULL, NULL, _t('输入全民ID'), _t('在这里输入全民ID,多首以,隔开'));

本文链接:https://www.masterzc.cn/archives/25.html
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处

Title - Artist
0:00