前期准备
1.所下载歌曲需网易云音乐有版权播放;
2.由于未找到歌曲搜索相关API,故歌曲ID由网易云音乐地址栏获取。
相关代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>网易云音乐下载</title>
</head>
<style>
* {
padding: 0;
margin: 0;
list-style: none;
text-decoration: none;
}
.box {
width: 500px;
height: 600px;
margin: 50px auto;
border: 1px solid red;
background: #c9c9c9;
}
.box1 {
border-bottom: 1px solid red;
}
.search {
width: 360px;
height: 40px;
margin: 20px auto;
text-align: center;
line-height: 40px;
}
.search > input {
float: left;
height: 30px;
margin-top: 3px;
outline: none;
opacity: 0.5;
}
.search > input:first-child {
margin-left: 20px;
margin-right: 10px;
padding-left: 10px;
width: 180px;
}
.search > input:nth-child(2) {
width: 70px;
margin-right: 10px;
}
#audio {
margin-top: 60px;
margin-left: 80px;
outline: none;
opacity: 0.5;
}
#ul {
color: red;
margin-top: 140px;
text-align: center;
}
#ul > li {
line-height: 25px;
font-weight: 900;
}
</style>
<body>
<div class="box" id="box">
<div class="box1">
<div class="search">
<input id="txt" type="text" title="search" placeholder="请输入想要下载的歌曲ID">
<input id="sub" type="submit" title="submit" value="搜素">
</div>
</div>
<audio id="audio" controls></audio>
<ul id="ul"></ul>
</div>
<script type="text/javascript">
let box = document.getElementById('box');
let txt = document.getElementById('txt');
let sub = document.getElementById('sub');
let audio = document.getElementById('audio');
let ul = document.getElementById('ul');
let detail = ""; // 歌曲信息
/* 点击搜索歌曲 */
sub.onclick = function () {
audio.pause(); // 暂停播放音乐
if (txt.value === '') {
alert('歌曲ID不能为空');
} else {
getDetail();
getSong();
}
};
/* 获取歌曲播放地址 */
function getSong() {
let xhr = new XMLHttpRequest();
xhr.open('get', 'https://api.imjad.cn/cloudmusic/?type=song&id=' + txt.value);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
let url = JSON.parse(xhr.response);
if (url.data[0].url === '') {
alert('搜索的歌曲ID不存在');
} else {
console.log(url.data[0].url);
audio.setAttribute("src", url.data[0].url);
playNum();
}
}
}
}
/* 获取歌曲信息(歌曲名称,歌手,专辑名,专辑图片等信息) */
function getDetail() {
detail = "";
let xhr1 = new XMLHttpRequest();
xhr1.open('get', 'https://api.imjad.cn/cloudmusic/?type=detail&id=' + txt.value);
xhr1.send();
xhr1.onreadystatechange = function () {
if (xhr1.status === 200 && xhr1.readyState === 4) {
let url1 = JSON.parse(xhr1.response);
if (url1.privileges[0].chargeInfoList !== null) {
detail += '<li>单曲: ' + url1.songs[0].name + '</li><li>第一歌手: ' + url1.songs[0].ar[0].name + '</li><li>所属专辑: ' + url1.songs[0].al.name + '</li>';
box.style.background = "url(" + url1.songs[0].al.picUrl + ")";
box.style.backgroundSize = "100% 100%";
ul.innerHTML = detail;
}
}
}
}
/* 控制播放次数(修改time的值进行控制) */
function playNum() {
let start = 0;
let times = 1;
audio.addEventListener("stopSong", function () {
audio.play();
start++;
if (start === times) {
audio.pause();
}
});
audio.play();
}
</script>
</body>
</html>