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 } + } +}