From 2ffa4454133bb55d64cc97d8f8a90b06121ced00 Mon Sep 17 00:00:00 2001 From: Astrian Zheng Date: Sat, 24 May 2025 23:40:13 +1000 Subject: [PATCH] =?UTF-8?q?feat(Player):=20=E6=B7=BB=E5=8A=A0=E5=AA=92?= =?UTF-8?q?=E4=BD=93=E4=BC=9A=E8=AF=9D=E5=85=83=E6=95=B0=E6=8D=AE=E5=92=8C?= =?UTF-8?q?=E6=92=AD=E6=94=BE=E6=8E=A7=E5=88=B6=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为播放器组件添加了媒体会话元数据设置功能,包括歌曲标题、艺术家、专辑和封面信息。同时实现了上一曲和下一曲的播放控制逻辑,并优化了音频元素的交互事件处理。 --- src/components/Player.vue | 58 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/src/components/Player.vue b/src/components/Player.vue index d209f77..b8d78bd 100644 --- a/src/components/Player.vue +++ b/src/components/Player.vue @@ -7,17 +7,69 @@ const playQueueStore = usePlayQueueStore() const player = useTemplateRef('playerRef') watch(() => playQueueStore.isPlaying, (newValue) => { - if (newValue) { player.value?.play() } + if (newValue) { + player.value?.play() + setMetadata() + } else { player.value?.pause() } }) + +watch(() => playQueueStore.currentIndex, () => { + setMetadata() +}) + +function artistsOrganize(list: string[]) { + if (list.length === 0) { return '未知音乐人' } + return list.map((artist) => { + return artist + }).join(' / ') +} + +function setMetadata() { + if ('mediaSession' in navigator) { + navigator.mediaSession.metadata = new MediaMetadata({ + title: playQueueStore.list[playQueueStore.currentIndex].song.name, + artist: artistsOrganize(playQueueStore.list[playQueueStore.currentIndex].song.artists ?? []), + album: playQueueStore.list[playQueueStore.currentIndex].album?.name, + artwork: [ + { src: playQueueStore.list[playQueueStore.currentIndex].album?.coverUrl ?? '', sizes: '500x500', type: 'image/png' }, + ] + }) + + navigator.mediaSession.setActionHandler('previoustrack', playPrevious) + navigator.mediaSession.setActionHandler('nexttrack', playNext) + } +} + +function playNext() { + if (playQueueStore.currentIndex === playQueueStore.list.length - 1) { + playQueueStore.currentIndex = 0 + player.value?.pause() + } else { + playQueueStore.currentIndex++ + player.value?.play() + } +} + +function playPrevious() { + if (player.value && (player.value.currentTime ?? 0) < 5 && playQueueStore.currentIndex > 0) { + playQueueStore.currentIndex-- + player.value?.play() + } else { + if (player.value) { player.value.currentTime = 0 } + } +}