实现一个简单的基于APlayer.js/.ts的支持网易云远程音乐的音乐播放器
最近写个人网站的时候有这个需求,然而 metting.js 支持不稳定,于是便想自己实现一个。由于我是拿 TS 进行开发的,故使用 APlayer.ts 。首先 APlayer.ts 音乐是可以直接从远程获取的,请求网易云歌曲只需要请求 https://music.163.com/song/media/outer/url?id=${id}.mp3 。
比较麻烦的是获取歌曲信息和歌词,需要绕开跨域请求限制,考虑到我的网页在 Netlify 上部署,添加一个 netlify.toml 配置文件:
[]
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;
} 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;
}
}
}使用方法:
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]