1241 字
6 分钟
在 Astro 侧栏中添加本地音乐播放器
2025-07-15
D-K-Deng
/
Music-Player-to-Astro-Sidebar
注意

YouTube 在中国等部分地区可能无法访问,Bilibili 在美国等地区也可能无法使用。如果遇到问题,请选择合适的网络环境。

YouTube(英文)#

Bilibili(中文)#

在 Astro 侧栏中添加本地音乐播放器#

本教程会介绍如何在 Astro 项目的侧栏中添加本地音乐播放器。播放器支持多首曲目、专辑封面显示、播放控制与进度跟踪。

功能#

  • 播放器会自动加载并播放第一首曲目。
  • 曲目标题溢出时会横向滚动。
  • 点击专辑封面可以切换播放与暂停。
  • 支持 Tailwind 的 dark 类来设置深色模式样式。

技术栈#

  • Astro
  • Svelte,用于交互式播放器
  • Tailwind CSS,用于样式

功能概览#

侧栏中会出现一个紧凑的音乐播放器,其中包括:

  • 专辑封面,播放时带有动画
  • 带滚动效果的曲目标题
  • 时间显示与进度条
  • 上一首、下一首和播放按钮

第 1 步:准备音乐文件#

  1. 在 Astro 项目的 public/ 目录中创建一个名为 music 的文件夹。
  2. 将 .mp3 文件和对应的封面图片放入其中。
  3. 使用描述清楚的名称,以便辨认歌曲与图片。

目录结构示例:

public/music/
├── baby_girl.mp3
├── aiaiai.mp3
├── 3.mp3
├── cover.jpg
├── cover2.jpg
├── cover3.jpg

第 2 步:创建音乐播放器组件#

1. 创建 Music.astro#

路径:src/components/widget/Music.astro

---
import LocalPlayer from './LocalPlayer.svelte';
const audioList = [
{
name: 'Baby Girl - DKD',
src: '/music/baby_girl.mp3',
cover: '/music/cover.jpg'
},
{
name: '爱爱爱 - DKD',
src: '/music/aiaiai.mp3',
cover: '/music/cover2.jpg'
},
{
name: '歌手与模特儿 - DKD',
src: '/music/3.mp3',
cover: '/music/cover3.jpg'
}
];
---
<LocalPlayer client:load {audioList} />

2. 创建 LocalPlayer.svelte#

路径:src/components/widget/LocalPlayer.svelte

---
<script>
import { onMount, onDestroy, tick } from 'svelte';
export let audioList = [];
let audio;
let currentIndex = 0;
let playing = false;
let duration = 0;
let current = 0;
let timer;
let offset = 0;
let dir = 1;
let scrollDistance = 0;
let scrollInterval;
let titleEl;
let containerEl;
function formatTime(t) {
const m = Math.floor(t / 60).toString().padStart(2, '0');
const s = Math.floor(t % 60).toString().padStart(2, '0');
return `${m}:${s}`;
}
function togglePlay() {
if (!audio) return;
if (playing) {
audio.pause();
} else {
audio.play();
}
playing = !playing;
}
function playCurrent() {
const track = audioList[currentIndex];
if (!track || !audio) return;
audio.src = track.src;
audio.play().then(() => { playing = true; });
setupScroll();
}
function prev() {
if (audioList.length === 0) return;
currentIndex = (currentIndex - 1 + audioList.length) % audioList.length;
playCurrent();
}
function next() {
if (audioList.length === 0) return;
currentIndex = (currentIndex + 1) % audioList.length;
playCurrent();
}
function seek(e) {
if (audio) {
audio.currentTime = +e.target.value;
current = audio.currentTime;
}
}
onMount(async () => {
audio = new Audio();
audio.loop = false;
audio.addEventListener('loadedmetadata', () => (duration = audio.duration));
audio.addEventListener('timeupdate', () => (current = audio.currentTime));
audio.addEventListener('ended', () => next());
playCurrent();
timer = setInterval(() => { if (audio) current = audio.currentTime; }, 200);
await tick();
setupScroll();
});
onDestroy(() => {
clearInterval(timer);
clearInterval(scrollInterval);
if (audio) {
audio.pause();
audio.src = '';
audio = null;
}
});
async function setupScroll() {
clearInterval(scrollInterval);
offset = 0;
dir = 1;
await tick();
if (titleEl && containerEl) {
const sw = titleEl.scrollWidth;
const cw = containerEl.clientWidth;
scrollDistance = sw - cw;
if (scrollDistance > 0) {
scrollInterval = setInterval(() => {
offset += dir;
if (offset >= scrollDistance || offset <= 0) dir = -dir;
}, 100);
}
}
}
</script>
<div class="player">
<img
src={audioList[currentIndex]?.cover}
alt={audioList[currentIndex]?.name}
class="cover"
class:spinning={playing}
on:click={togglePlay}
/>
<div class="info">
<div bind:this={containerEl} class="title-container">
<div
bind:this={titleEl}
class="title"
style="transform: translateX(-{offset}px);"
>
{audioList[currentIndex]?.name}
</div>
</div>
<div class="time">{formatTime(current)} / {formatTime(duration)}</div>
<input
type="range"
min="0"
max={duration}
step="0.01"
bind:value={current}
on:input={seek}
class="progress"
/>
</div>
<div class="controls">
<button on:click={prev} aria-label="Last" class="ctrl">
<svg viewBox="0 0 24 24"><path d="M16 5v14l-11-7z"/></svg>
</button>
<button on:click={togglePlay} aria-label="Play/Pause" class="ctrl play-pause">
{#if playing}
<svg viewBox="0 0 24 24">
<rect x="6" y="5" width="4" height="14" rx="1"/>
<rect x="14" y="5" width="4" height="14" rx="1"/>
</svg>
{:else}
<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
{/if}
</button>
<button on:click={next} aria-label="Next" class="ctrl">
<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
</button>
</div>
</div>
<style>
/* Light mode */
.player {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
box-sizing: border-box;
width: 100%;
color: #333;
}
.time { font-size: 0.75rem; color: #666; }
.progress { background: #ddd; }
.ctrl { background: #f2ebfd; }
/* Dark mode via Tailwind's .dark class */
:global(html.dark) .player { color: #eee; }
:global(html.dark) .time { color: #aaa; }
:global(html.dark) .progress { background: #555; }
:global(html.dark) .ctrl { background: #bc98f8; }
.cover {
width: 50px;
height: 50px;
border-radius: 50%;
object-fit: cover;
cursor: pointer;
flex-shrink: 0;
}
.spinning { animation: spin 10s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.title-container {
overflow: hidden;
width: 100%;
}
.title {
display: inline-block;
white-space: nowrap;
}
.progress {
width: 100%;
height: 4px;
border-radius: 2px;
appearance: none;
cursor: pointer;
}
.progress::-webkit-slider-thumb {
appearance: none;
width: 12px;
height: 12px;
background: currentColor;
border-radius: 50%;
cursor: pointer;
}
.controls {
display: flex;
gap: 0.25rem;
flex-shrink: 0;
}
.ctrl {
width: 32px;
height: 32px;
border: none;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
padding: 0;
}
.ctrl svg { width: 16px; height: 16px; fill: currentColor; }
</style>

第 3 步:把音乐播放器添加到侧栏#

修改 Sidebar.astro#

路径:src/components/widget/Sidebar.astro

  1. 在文件顶部导入 Music 组件:
import Music from "./Music.astro";
  1. 在 <Tag> 组件下方插入音乐播放器区块:
<div id="music" class="flex flex-col w-full gap-4">
<Music></Music>
</div>
  1. 最终 Sidebar.astro 的相关部分应如下所示:
<div id="sidebar" class:list={[className, "w-full"]}>
<div class="flex flex-col w-full gap-4 mb-4">
<Profile></Profile>
</div>
<div id="sidebar-sticky" class="transition-all duration-700 flex flex-col w-full gap-4 top-4 sticky top-4">
<div id="series" class="flex flex-col w-full gap-4">
{ series && <Series series={ series }></Series> }
</div>
<Categories class="onload-animation" style="animation-delay: 150ms"></Categories>
<Tag class="onload-animation" style="animation-delay: 200ms"></Tag>
<div id="music" class="flex flex-col w-full gap-4">
<Music></Music>
</div>
</div>
</div>

完整代码总结#

  • public/music/ 存放音频文件与封面图片
  • src/components/widget/Music.astro 加载曲目列表并渲染播放器
  • src/components/widget/LocalPlayer.svelte 处理播放逻辑
  • Sidebar.astro 将 <Music /> 组件加入布局

完成后,Astro 侧栏中就会拥有一个功能完整、可以自定义的音乐播放器。

在 Astro 侧栏中添加本地音乐播放器
https://d-k-deng.github.io/zh-cn/posts/musicplayer/
作者
Zhaowen Deng
发布于
2025-07-15
许可协议
CC BY-NC-SA 4.0