最近写个人网站的时候有这个需求,然而 metting.js
支持不稳定,于是便想自己实现一个。由于我是拿 TS
进行开发的,故使用 APlayer.ts
。
首先 APlayer.ts
音乐是可以直接从远程获取的,请求网易云歌曲只需要请求 https://music.163.com/song/media/outer/url?id=${id}.mp3
。
比较麻烦的是获取歌曲信息和歌词,需要绕开跨域请求限制,考虑到我的网页在 Netlify
上部署,添加一个 netlify.toml
配置文件:
[[redirects]]
from = "/music/*"
to = "https://music.163.com/:splat"
status = 200
force = true
请求歌曲信息和歌词:
async fetchSongDetail(songId: number) {
try {
const response = await fetch(
`/music/api/song/detail/?id=${songId}&ids=%5B${songId}%5D`,
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.songs[0];
} catch (error) {
console.error('Error fetching song detail:', error);
return null;
}
}
async fetchSongLyric(songId: number) {
try {
const response = await fetch(
`/music/api/song/lyric?id=${songId}&lv=1&kv=1&tv=-1`,
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.lrc.lyric;
} catch (error) {
console.error('Error fetching song lyric:', error);
return null;
}
}
最后我单独注册了一个组件实现网易云音乐的播放:
import './music_player.scss';
import APlayer from 'aplayer-ts';
export class MusicPlayerElement extends HTMLElement {
constructor() {
super();
const id = parseInt(this.id);
this.fetchSongDetail(id).then((detail) => {
if (detail) {
this.fetchSongLyric(id).then((lyric) => {
if (lyric) {
try {
APlayer().init({
container: this,
lrcType: 1,
audio: [
{
name: detail.name,
artist: detail.artists
.map(
(artist: { name: any }) =>
artist.name,
)
.join(', '),
url: `https://music.163.com/song/media/outer/url?id=${id}.mp3`,
cover: detail.album.picUrl,
lrc: lyric,
},
],
});
} catch (err) {
console.error('Error initializing APlayer:', err);
}
}
});
}
});
}
async fetchSongDetail(songId: number) {
// ...
}
async fetchSongLyric(songId: number) {
// ...
}
}
customElements.define('music-player', MusicPlayerElement);
另外还有一个自建的暗色播放器样式:
@use '../styles/share.scss' as share;
@import url('aplayer-ts/src/css/base.css');
@media (prefers-color-scheme: dark) {
.aplayer {
.aplayer-body {
background: share.$main-color;
}
.aplayer-lrc {
&:before {
background: linear-gradient(180deg,
share.$main-color 0,
hsla(0, 0%, 100%, 0));
}
&:after {
background: linear-gradient(180deg,
hsla(0, 0%, 100%, 0) 0,
share.$main-color );
}
p {
color: white;
&.aplayer-lrc-current {
color: #66ccff;
}
}
}
.aplayer-info {
.aplayer-music {
.aplayer-author {
color: #66ccff;
}
}
}
}
.aplayer-title {
color: white;
}
@media (max-width: calc(#{share.$screen-limit} - 1px)) {
music-player {
display: none;
}
}
}
使用方法:
<music-player
server="netease"
type="song"
id="2151900715"
theme="#66ccff"
></music-player>
来源链接:https://www.cnblogs.com/expector/p/18726354/music_player_ts
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容