feat: 使用新的播放器库(施工中)

This commit is contained in:
Astrian Zheng 2025-08-31 16:32:05 +10:00
parent c57d7bc42d
commit fd6253e626
Signed by: Astrian
SSH Key Fingerprint: SHA256:rVnhx3DAKjujCwWE13aDl7uV6+9U1MvydLkNRXJrBiA
18 changed files with 254 additions and 985 deletions

6
package-lock.json generated
View File

@ -8,6 +8,7 @@
"name": "msr-mod",
"version": "0.0.0",
"dependencies": {
"@astrian/music-surge-revolution": "^0.0.0-20250831052313",
"@tailwindcss/vite": "^4.1.7",
"axios": "^1.9.0",
"gsap": "^3.13.0",
@ -42,6 +43,11 @@
"node": ">=6.0.0"
}
},
"node_modules/@astrian/music-surge-revolution": {
"version": "0.0.0-20250831055015",
"resolved": "https://registry.npmjs.org/@astrian/music-surge-revolution/-/music-surge-revolution-0.0.0-20250831055015.tgz",
"integrity": "sha512-joXpUDjez+5M90C4RoGsfHZifXdUBhqSHH+kW3v6TDQJQZwh/sdof1ro4qYXG3/8D8AkfWdhFV3O1C8nxG6syw=="
},
"node_modules/@babel/helper-string-parser": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",

View File

@ -20,6 +20,7 @@
"prebuild:safari": "node scripts/prebuild-safari.js"
},
"dependencies": {
"@astrian/music-surge-revolution": "^0.0.0-20250831052313",
"@tailwindcss/vite": "^4.1.7",
"axios": "^1.9.0",
"gsap": "^3.13.0",

View File

@ -1,6 +1,5 @@
<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import Player from './components/Player.vue'
import PreferencePanel from './components/PreferencePanel.vue'
import { ref } from 'vue'
@ -73,7 +72,6 @@ watch(() => presentPreferencePanel, (value) => {
<CorgIcon :size="4" />
</button>
<Player />
</div>
</div>
</div>

View File

@ -8,7 +8,7 @@ import { ref, watch, nextTick } from 'vue'
import { gsap } from 'gsap'
import apis from '../apis'
import { artistsOrganize } from '../utils'
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import { usePlayStore } from '../stores/usePlayStore'
import TrackItem from './TrackItem.vue'
import LoadingIndicator from '../assets/icons/loadingindicator.vue'
@ -17,9 +17,7 @@ const props = defineProps<{
present: boolean
}>()
const emit = defineEmits<{
(e: 'dismiss'): void
}>()
const emit = defineEmits<(e: 'dismiss') => void>()
const album = ref<Album>()
const dialogBackdrop = ref<HTMLElement>()
@ -28,7 +26,7 @@ const closeButton = ref<HTMLElement>()
// Animation functions
const animateIn = async () => {
if (!dialogBackdrop.value || !dialogContent.value || !closeButton.value) return
if (!dialogBackdrop.value || !dialogContent.value || !closeButton.value) {return}
// Set initial states
gsap.set(dialogBackdrop.value, { opacity: 0 })
@ -59,7 +57,7 @@ const animateIn = async () => {
}
const animateOut = () => {
if (!dialogBackdrop.value || !dialogContent.value || !closeButton.value) return
if (!dialogBackdrop.value || !dialogContent.value || !closeButton.value) {return}
const tl = gsap.timeline({
onComplete: () => emit('dismiss')
@ -85,6 +83,7 @@ const animateOut = () => {
}, "-=0.1")
}
// biome-ignore lint/correctness/noUnusedVariables: used inside <template>
const handleClose = () => {
animateOut()
}
@ -100,9 +99,9 @@ watch(() => props.albumCid, async () => {
console.log("AlbumDetailDialog mounted with albumCid:", props.albumCid)
album.value = undefined // Reset album when cid changes
try {
let res = await apis.getAlbum(props.albumCid)
const res = await apis.getAlbum(props.albumCid)
for (const track in res.songs) {
res.songs[parseInt(track)] = await apis.getSong(res.songs[parseInt(track)].cid)
res.songs[Number.parseInt(track, 10)] = await apis.getSong(res.songs[Number.parseInt(track, 10)].cid)
}
album.value = res
} catch (error) {
@ -110,15 +109,16 @@ watch(() => props.albumCid, async () => {
}
})
const playQueue = usePlayQueueStore()
const playQueue = usePlayStore()
function playTheAlbum(from: number = 0) {
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function playTheAlbum(from = 0) {
if (playQueue.queueReplaceLock) {
if (!confirm("当前操作会将你的播放队列清空、放入这张专辑所有曲目,并从头播放。继续吗?")) { return }
playQueue.queueReplaceLock = false
}
let newPlayQueue = []
const newPlayQueue = []
for (const track of album.value?.songs ?? []) {
console.log(track)
newPlayQueue.push({
@ -126,21 +126,21 @@ function playTheAlbum(from: number = 0) {
album: album.value
})
}
playQueue.list = newPlayQueue
playQueue.currentIndex = from
playQueue.isPlaying = true
playQueue.isBuffering = true
playQueue.replaceQueue(newPlayQueue)
// playQueue.currentIndex = from
playQueue.togglePlay(true)
}
// biome-ignore lint/correctness/noUnusedVariables: used inside <template>
function shuffle() {
playTheAlbum()
playQueue.shuffleCurrent = true
playQueue.playMode.shuffle = false
setTimeout(() => {
playQueue.playMode.shuffle = true
playQueue.isPlaying = true
playQueue.isBuffering = true
}, 100)
// playTheAlbum()
// playQueue.shuffleCurrent = true
// playQueue.playMode.shuffle = false
// setTimeout(() => {
// playQueue.playMode.shuffle = true
// playQueue.isPlaying = true
// playQueue.isBuffering = true
// }, 100)
}
</script>

View File

@ -0,0 +1,20 @@
<script setup lang="ts">
import { usePlayStore } from '../stores/usePlayStore'
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const playQueue = usePlayStore()
</script>
<template>
<RouterLink to="/playroom" v-if="playQueue.currentTrack">
<div
class="h-9 w-52 bg-neutral-800/80 border border-[#ffffff39] rounded-full backdrop-blur-3xl flex items-center justify-between select-none overflow-hidden">
<div class="flex items-center gap-2">
<div class="rounded-full w-9 h-9 bg-gray-600 overflow-hidden">
<img :src="playQueue.currentTrack.metadata?.artwork?.[0].src ?? ''" />
</div>
<div class="text-white">{{playQueue.currentTrack.metadata?.title ?? "未知歌曲"}}</div>
</div>
</div>
</RouterLink>
</template>

View File

@ -5,18 +5,19 @@ import { useFavourites } from '../stores/useFavourites'
import StarSlashIcon from '../assets/icons/starslash.vue'
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const favourites = useFavourites()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const hover = ref(false)
defineProps<{
item: QueueItem
item: InternalQueueItem
index: number
}>()
const emit = defineEmits<{
(e: 'play', index: number): void
}>()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const emit = defineEmits<(e: 'play', index: number) => void>()
</script>
<template>

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import { usePlayStore } from '../stores/usePlayStore'
import { artistsOrganize, supportsWebAudioVisualization } from '../utils'
import XIcon from '../assets/icons/x.vue'
@ -10,18 +10,21 @@ import SoundwaveIcon from '../assets/icons/soundwave.vue'
import { ref } from 'vue'
const props = defineProps<{
queueItem: QueueItem
queueItem: InternalQueueItem
isCurrent: boolean
index: number
}>()
const playQueueStore = usePlayQueueStore()
const playStore = usePlayStore()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const hover = ref(false)
//
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const isAudioVisualizationSupported = supportsWebAudioVisualization()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function moveUp() {
if (props.index === 0) return
@ -58,6 +61,7 @@ function moveUp() {
}
}
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function moveDown() {
const listLength = playQueueStore.playMode.shuffle ? playQueueStore.shuffleList.length : playQueueStore.list.length
if (props.index === listLength - 1) return
@ -95,6 +99,7 @@ function moveDown() {
}
}
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function removeItem() {
playQueueStore.queueReplaceLock = true
@ -152,8 +157,8 @@ function removeItem() {
<template>
<button class="p-4 w-full rounded-md hover:bg-white/5 first:mt-2 flex gap-2 items-center" @click="() => {
if (isCurrent) { return }
playQueueStore.currentIndex = index
playQueueStore.isPlaying = true
// playStore.currentIndex = index
// playStore.isPlaying = true
}" @mouseenter="hover = true" @mouseleave="hover = false">
<div class="flex gap-2 flex-auto w-0">
<div class="relative w-12 h-12 rounded-md shadow-xl overflow-hidden">
@ -162,7 +167,7 @@ function removeItem() {
v-if="isCurrent">
<!-- 在支持的浏览器上显示可视化否则显示音波图标 -->
<div v-if="isAudioVisualizationSupported" style="height: 1rem;" class="flex justify-center items-center gap-[.125rem]">
<div class="bg-white w-[.125rem] rounded-full" v-for="(bar, index) in playQueueStore.visualizer"
<div class="bg-white w-[.125rem] rounded-full" v-for="(bar, index) in playStore.visualizer"
:key="index" :style="{
height: `${Math.max(10, bar)}%`
}" />
@ -189,8 +194,8 @@ function removeItem() {
<button
class="text-white/90 w-4 h-4 hover:scale-110 hover:text-white active:scale-95 active:text-white/85 transition-all"
@click.stop="moveDown"
:disabled="index === (playQueueStore.playMode.shuffle ? playQueueStore.shuffleList.length : playQueueStore.list.length) - 1"
v-if="index !== (playQueueStore.playMode.shuffle ? playQueueStore.shuffleList.length : playQueueStore.list.length) - 1">
:disabled="index === (playStore.playMode.shuffle ? playStore.shuffleList.length : playStore.list.length) - 1"
v-if="index !== (playStore.playMode.shuffle ? playStore.shuffleList.length : playStore.list.length) - 1">
<DownHyphenIcon :size="4" />
</button>

View File

@ -1,535 +0,0 @@
<!-- Player.vue - 添加预加载功能 -->
<script setup lang="ts">
import { computed, nextTick, ref, useTemplateRef, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useFavourites } from '../stores/useFavourites'
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import LoadingIndicator from '../assets/icons/loadingindicator.vue'
import PlayIcon from '../assets/icons/play.vue'
import PauseIcon from '../assets/icons/pause.vue'
import { audioVisualizer, checkAndRefreshSongResource, supportsWebAudioVisualization } from '../utils'
const playQueueStore = usePlayQueueStore()
const favourites = useFavourites()
const route = useRoute()
const player = useTemplateRef('playerRef')
// [] store
console.log('[Player] 检查 store 方法:', {
preloadNext: typeof playQueueStore.preloadNext,
getPreloadedAudio: typeof playQueueStore.getPreloadedAudio,
clearPreloadedAudio: typeof playQueueStore.clearPreloadedAudio,
})
//
const currentTrack = computed(() => {
if (
playQueueStore.playMode.shuffle &&
playQueueStore.shuffleList.length > 0
) {
return playQueueStore.list[
playQueueStore.shuffleList[playQueueStore.currentIndex]
]
}
return playQueueStore.list[playQueueStore.currentIndex]
})
//
const currentAudioSrc = computed(() => {
const track = currentTrack.value
return track ? track.song.sourceUrl : ''
})
watch(
() => playQueueStore.isPlaying,
(newValue) => {
if (newValue) {
player.value?.play()
setMetadata()
} else {
player.value?.pause()
}
},
)
//
watch(
() => playQueueStore.currentIndex,
async () => {
console.log('[Player] 当前索引变化:', playQueueStore.currentIndex)
// 使
const track = currentTrack.value
if (track) {
const songId = track.song.cid
try {
//
console.log('[Player] 检查当前歌曲资源:', track.song.name)
const updatedSong = await checkAndRefreshSongResource(
track.song,
(updated) => {
//
// currentIndex shuffleList
// shuffleList[currentIndex] list
const actualIndex =
playQueueStore.playMode.shuffle &&
playQueueStore.shuffleList.length > 0
? playQueueStore.shuffleList[playQueueStore.currentIndex]
: playQueueStore.currentIndex
if (playQueueStore.list[actualIndex]) {
playQueueStore.list[actualIndex].song = updated
}
//
favourites.updateSongInFavourites(songId, updated)
},
)
// 使
const preloadedAudio = playQueueStore.getPreloadedAudio(songId)
if (preloadedAudio && updatedSong.sourceUrl === track.song.sourceUrl) {
console.log(`[Player] 使用预加载的音频: ${track.song.name}`)
// 使
if (player.value) {
//
player.value.src = preloadedAudio.src
player.value.currentTime = 0
// 使
playQueueStore.clearPreloadedAudio(songId)
//
if (playQueueStore.isPlaying) {
await nextTick()
player.value.play().catch(console.error)
}
playQueueStore.isBuffering = false
}
} else {
console.log(`[Player] 正常加载音频: ${track.song.name}`)
playQueueStore.isBuffering = true
//
if (updatedSong.sourceUrl !== track.song.sourceUrl) {
playQueueStore.clearPreloadedAudio(songId)
}
}
} catch (error) {
console.error('[Player] 处理预加载音频时出错:', error)
playQueueStore.isBuffering = true
}
}
setMetadata()
//
setTimeout(async () => {
try {
console.log('[Player] 尝试预加载下一首歌')
//
if (typeof playQueueStore.preloadNext === 'function') {
await playQueueStore.preloadNext()
//
playQueueStore.list.forEach((item) => {
if (favourites.isFavourite(item.song.cid)) {
favourites.updateSongInFavourites(item.song.cid, item.song)
}
})
playQueueStore.limitPreloadCache()
} else {
console.error('[Player] preloadNext 不是一个函数')
}
} catch (error) {
console.error('[Player] 预加载失败:', error)
}
}, 1000)
},
)
function artistsOrganize(list: string[]) {
if (list.length === 0) {
return '未知音乐人'
}
return list
.map((artist) => {
return artist
})
.join(' / ')
}
function setMetadata() {
if ('mediaSession' in navigator) {
const current = currentTrack.value
if (!current) return
navigator.mediaSession.metadata = new MediaMetadata({
title: current.song.name,
artist: artistsOrganize(current.song.artists ?? []),
album: current.album?.name,
artwork: [
{
src: current.album?.coverUrl ?? '',
sizes: '500x500',
type: 'image/png',
},
],
})
navigator.mediaSession.setActionHandler('previoustrack', playPrevious)
navigator.mediaSession.setActionHandler('nexttrack', playNext)
playQueueStore.duration = player.value?.duration ?? 0
playQueueStore.currentTime = player.value?.currentTime ?? 0
}
watch(
() => playQueueStore.updatedCurrentTime,
(newValue) => {
if (newValue === null) {
return
}
if (player.value) player.value.currentTime = newValue
playQueueStore.updatedCurrentTime = null
},
)
}
function playNext() {
if (playQueueStore.currentIndex === playQueueStore.list.length - 1) {
console.log('at the bottom, pause')
playQueueStore.currentIndex = 0
if (playQueueStore.playMode.repeat === 'all') {
playQueueStore.currentIndex = 0
playQueueStore.isPlaying = true
} else {
player.value?.pause()
playQueueStore.isPlaying = false
}
} else {
playQueueStore.currentIndex++
playQueueStore.isPlaying = true
}
}
function playPrevious() {
if (
player.value &&
(player.value.currentTime ?? 0) < 5 &&
playQueueStore.currentIndex > 0
) {
playQueueStore.currentIndex--
playQueueStore.isPlaying = true
} else {
if (player.value) {
player.value.currentTime = 0
}
}
}
function updateCurrentTime() {
playQueueStore.currentTime = player.value?.currentTime ?? 0
//
if (playQueueStore.duration > 0) {
const progress = playQueueStore.currentTime / playQueueStore.duration
const remainingTime = playQueueStore.duration - playQueueStore.currentTime
// localStorage 使
const config = JSON.parse(localStorage.getItem('preloadConfig') || '{}')
const preloadTrigger = (config.preloadTrigger || 50) / 100 //
const remainingTimeThreshold = config.remainingTimeThreshold || 30
if (
(progress > preloadTrigger || remainingTime < remainingTimeThreshold) &&
!playQueueStore.isPreloading
) {
try {
if (typeof playQueueStore.preloadNext === 'function') {
playQueueStore.preloadNext()
} else {
console.error('[Player] preloadNext 不是一个函数')
}
} catch (error) {
console.error('[Player] 智能预加载失败:', error)
}
}
}
}
//
const isAudioVisualizationSupported = supportsWebAudioVisualization()
console.log('[Player] 音频可视化支持状态:', isAudioVisualizationSupported)
//
let barHeights = ref<number[]>([0, 0, 0, 0, 0, 0])
let connectAudio = (_audio: HTMLAudioElement) => {}
let isAnalyzing = ref(false)
let error = ref<string | null>(null)
if (isAudioVisualizationSupported) {
console.log('[Player] 初始化 audioVisualizer')
const visualizer = audioVisualizer({
sensitivity: 1.5,
barCount: 6,
maxDecibels: -10,
bassBoost: 0.8,
midBoost: 1.2,
trebleBoost: 1.4,
threshold: 0,
})
barHeights = visualizer.barHeights
connectAudio = visualizer.connectAudio
isAnalyzing = visualizer.isAnalyzing
error = visualizer.error
console.log('[Player] audioVisualizer 返回值:', {
barHeights: barHeights.value,
isAnalyzing: isAnalyzing.value,
})
} else {
console.log('[Player] 音频可视化被禁用Safari 或不支持的浏览器)')
}
//
watch(
() => playQueueStore.list.length,
async (newLength) => {
console.log('[Player] 播放列表长度变化:', newLength)
if (newLength === 0) {
console.log('[Player] 播放列表为空,跳过连接')
return
}
// audio
await nextTick()
if (player.value) {
if (isAudioVisualizationSupported) {
console.log('[Player] 连接音频元素到可视化器')
console.log('[Player] 音频元素状态:', {
src: player.value.src?.substring(0, 50) + '...',
readyState: player.value.readyState,
paused: player.value.paused,
})
connectAudio(player.value)
} else {
console.log('[Player] 跳过音频可视化连接(不支持的浏览器)')
}
} else {
console.log('[Player] ❌ 音频元素不存在')
}
playQueueStore.visualizer = barHeights.value
//
setTimeout(() => {
playQueueStore.preloadNext()
}, 2000)
//
if (player.value) {
initializeVolume()
}
},
)
//
watch(
() => player.value,
(audioElement) => {
if (audioElement && playQueueStore.list.length > 0 && isAudioVisualizationSupported) {
connectAudio(audioElement)
}
},
)
//
watch(
() => barHeights.value,
(newHeights) => {
playQueueStore.visualizer = newHeights
},
{ deep: true },
)
//
watch(
() => error.value,
(newError) => {
if (newError) {
console.error('[Player] 可视化器错误:', newError)
}
},
)
//
watch(
() => playQueueStore.playMode.shuffle,
(isShuffle) => {
if (isShuffle) {
const currentIndex = playQueueStore.currentIndex
const trackCount = playQueueStore.list.length
// 1.
let shuffledList = [...Array(currentIndex).keys()]
// 2.
const shuffleSpace = [...Array(trackCount).keys()].filter((index) =>
playQueueStore.shuffleCurrent
? index >= currentIndex
: index > currentIndex,
)
// 3.
shuffleSpace.sort(() => Math.random() - 0.5)
// 4. currentIndex
if (!playQueueStore.shuffleCurrent) {
shuffledList.push(currentIndex)
}
// 5. + +
shuffledList = shuffledList.concat(shuffleSpace)
// 6. shuffleList
playQueueStore.shuffleList = shuffledList
// shuffleCurrent
playQueueStore.shuffleCurrent = undefined
} else {
// 退
playQueueStore.currentIndex =
playQueueStore.shuffleList[playQueueStore.currentIndex]
}
//
setTimeout(() => {
playQueueStore.clearAllPreloadedAudio()
playQueueStore.preloadNext()
}, 500)
},
)
function getCurrentTrack() {
return currentTrack.value
}
//
function initializeVolume() {
if (player.value) {
const savedVolume = localStorage.getItem('audioVolume')
if (savedVolume) {
const volumeValue = Number.parseFloat(savedVolume)
player.value.volume = volumeValue
console.log('[Player] 初始化音量:', volumeValue)
} else {
//
player.value.volume = 1
localStorage.setItem('audioVolume', '1')
}
}
}
//
function handleVolumeChange(event: Event) {
const target = event.target as HTMLAudioElement
if (target) {
// localStorage
localStorage.setItem('audioVolume', target.volume.toString())
console.log('[Player] 音量变化:', target.volume)
}
}
// localStorage
function syncVolumeFromStorage() {
if (player.value) {
const savedVolume = localStorage.getItem('audioVolume')
if (savedVolume) {
const volumeValue = Number.parseFloat(savedVolume)
if (player.value.volume !== volumeValue) {
player.value.volume = volumeValue
}
}
}
}
// 使storage
setInterval(syncVolumeFromStorage, 100)
//
// onUnmounted(() => {
// playQueueStore.clearAllPreloadedAudio()
// })
</script>
<template>
<div>
<audio :src="currentAudioSrc" ref="playerRef" :autoplay="playQueueStore.isPlaying"
v-if="playQueueStore.list.length !== 0" @volumechange="handleVolumeChange" @ended="() => {
if (playQueueStore.playMode.repeat === 'single') { playQueueStore.isPlaying = true }
else { playNext() }
}" @pause="playQueueStore.isPlaying = false" @play="playQueueStore.isPlaying = true" @playing="() => {
console.log('[Player] 音频开始播放事件')
playQueueStore.isBuffering = false
setMetadata()
initializeVolume()
}" @waiting="playQueueStore.isBuffering = true" @loadeddata="() => {
console.log('[Player] 音频数据加载完成')
playQueueStore.isBuffering = false
initializeVolume()
}" @canplay="() => {
console.log('[Player] 音频可以播放')
playQueueStore.isBuffering = false
}" @error="(e) => {
console.error('[Player] 音频错误:', e)
playQueueStore.isBuffering = false
}" crossorigin="anonymous" @timeupdate="updateCurrentTime">
</audio>
<!-- 预加载进度指示器可选显示 -->
<!-- <div v-if="playQueueStore.isPreloading"
class="fixed top-4 right-4 bg-black/80 text-white px-3 py-1 rounded text-xs z-50">
预加载中... {{ Math.round(playQueueStore.preloadProgress) }}%
</div> -->
<div
class="text-white h-9 bg-neutral-800/80 border border-[#ffffff39] rounded-full text-center backdrop-blur-3xl flex gap-2 overflow-hidden select-none"
v-if="playQueueStore.list.length !== 0 && route.path !== '/playroom'">
<RouterLink to="/playroom">
<img :src="getCurrentTrack()?.album?.coverUrl ?? ''" class="rounded-full h-8 w-8 mt-[.0625rem]" />
</RouterLink>
<RouterLink to="/playroom">
<div class="flex items-center w-32 h-9">
<span class="truncate text-xs">{{ getCurrentTrack()?.song.name }}</span>
</div>
</RouterLink>
<button class="h-9 w-12 flex justify-center items-center" @click.stop="() => {
playQueueStore.isPlaying = !playQueueStore.isPlaying
}">
<div v-if="playQueueStore.isPlaying">
<LoadingIndicator v-if="playQueueStore.isBuffering === true" :size="4" />
<!-- 在支持的浏览器上显示可视化否则显示暂停图标 -->
<div v-else-if="isAudioVisualizationSupported" class="h-4 flex justify-center items-center gap-[.125rem]">
<div class="bg-white/75 w-[.125rem] rounded-full" v-for="(bar, index) in playQueueStore.visualizer"
:key="index" :style="{
height: `${Math.max(10, bar)}%`
}" />
</div>
<PauseIcon v-else :size="4" />
</div>
<PlayIcon v-else :size="4" />
</button>
</div>
</div>
</template>

View File

@ -89,7 +89,7 @@
import { onMounted, ref, watch, nextTick, computed, onUnmounted } from 'vue'
import axios from 'axios'
import gsap from 'gsap'
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import { usePlayStore } from '../stores/usePlayStore'
//
interface LyricsLine {
@ -106,7 +106,7 @@ interface GapLine {
duration?: number
}
const playQueueStore = usePlayQueueStore()
const playStore = usePlayStore()
//
const parsedLyrics = ref<(LyricsLine | GapLine)[]>([])
@ -121,7 +121,7 @@ const lyricsWrapper = ref<HTMLElement>()
const lineRefs = ref<(HTMLElement | null)[]>([])
const controlPanel = ref<HTMLElement>()
const loadingIndicator = ref<HTMLElement>()
const noLyricsIndicator = ref<HTMLElement>()
//const noLyricsIndicator = ref<HTMLElement>()
// GSAP
let scrollTween: gsap.core.Tween | null = null
@ -135,12 +135,13 @@ const props = defineProps<{
//
const scrollIndicatorHeight = computed(() => {
if (parsedLyrics.value.length === 0) return 0
if (parsedLyrics.value.length === 0) {return 0}
return Math.max(10, 100 / parsedLyrics.value.length * 5) // 5
})
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const scrollIndicatorPosition = computed(() => {
if (parsedLyrics.value.length === 0 || currentLineIndex.value < 0) return 0
if (parsedLyrics.value.length === 0 || currentLineIndex.value < 0) {return 0}
const progress = currentLineIndex.value / (parsedLyrics.value.length - 1)
const containerHeight = lyricsContainer.value?.clientHeight || 400
const indicatorTrackHeight = containerHeight / 2 //
@ -148,6 +149,7 @@ const scrollIndicatorPosition = computed(() => {
})
//
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function setLineRef(el: HTMLElement | null, index: number) {
if (el) {
lineRefs.value[index] = el
@ -155,15 +157,17 @@ function setLineRef(el: HTMLElement | null, index: number) {
}
//
function parseLyrics(lrcText: string, minGapDuration: number = 5): (LyricsLine | GapLine)[] {
if (!lrcText) return [
{
type: 'lyric',
time: 0,
text: '',
originalTime: '[00:00]'
}
]
function parseLyrics(lrcText: string, minGapDuration = 5): (LyricsLine | GapLine)[] {
if (!lrcText) {
return [
{
type: 'lyric',
time: 0,
text: '',
originalTime: '[00:00]'
}
]
}
const lines = lrcText.split('\n')
const tempParsedLines: (LyricsLine | GapLine)[] = []
@ -172,14 +176,14 @@ function parseLyrics(lrcText: string, minGapDuration: number = 5): (LyricsLine |
for (const line of lines) {
const matches = [...line.matchAll(timeRegex)]
if (matches.length === 0) continue
if (matches.length === 0) {continue}
const text = line.replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?\]/g, '').trim()
for (const match of matches) {
const minutes = parseInt(match[1])
const seconds = parseInt(match[2])
const milliseconds = match[3] ? parseInt(match[3].padEnd(3, '0')) : 0
const minutes = Number.parseInt(match[1])
const seconds = Number.parseInt(match[2])
const milliseconds = match[3] ? Number.parseInt(match[3].padEnd(3, '0')) : 0
const totalSeconds = minutes * 60 + seconds + milliseconds / 1000
@ -206,7 +210,7 @@ function parseLyrics(lrcText: string, minGapDuration: number = 5): (LyricsLine |
const lyricLines = tempParsedLines.filter(line => line.type === 'lyric') as LyricsLine[]
const gapLines = tempParsedLines.filter(line => line.type === 'gap') as GapLine[]
if (lyricLines.length === 0) return tempParsedLines
if (lyricLines.length === 0) {return tempParsedLines}
for (let i = 0; i < gapLines.length; i++) {
const gapLine = gapLines[i]
@ -236,9 +240,9 @@ function parseLyrics(lrcText: string, minGapDuration: number = 5): (LyricsLine |
//
function findCurrentLineIndex(time: number): number {
if (parsedLyrics.value.length === 0) return -1
if (parsedLyrics.value.length === 0) {return -1}
// 0
if (time < parsedLyrics.value[1]?.time) return 0
if (time < parsedLyrics.value[1]?.time) {return 0}
let index = 0
for (let i = 1; i < parsedLyrics.value.length; i++) {
if (time >= parsedLyrics.value[i].time) {
@ -252,7 +256,7 @@ function findCurrentLineIndex(time: number): number {
// 使 GSAP
function scrollToLine(lineIndex: number, smooth = true) {
if (!lyricsContainer.value || !lyricsWrapper.value || !lineRefs.value[lineIndex]) return
if (!lyricsContainer.value || !lyricsWrapper.value || !lineRefs.value[lineIndex]) {return}
const container = lyricsContainer.value
const wrapper = lyricsWrapper.value
@ -288,7 +292,7 @@ function scrollToLine(lineIndex: number, smooth = true) {
//
function highlightCurrentLine(lineIndex: number) {
if (!lineRefs.value[lineIndex]) return
if (!lineRefs.value[lineIndex]) {return}
const lineElement = lineRefs.value[lineIndex]
@ -322,10 +326,11 @@ function highlightCurrentLine(lineIndex: number) {
}
//
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function handleWheel(event: WheelEvent) {
event.preventDefault()
if (!lyricsWrapper.value || !lyricsContainer.value) return
if (!lyricsWrapper.value || !lyricsContainer.value) {return}
userScrolling.value = true
autoScroll.value = false
@ -365,6 +370,7 @@ function handleWheel(event: WheelEvent) {
}
//
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function handleLineClick(line: LyricsLine | GapLine, index: number) {
if (line.type === 'lyric') {
console.log('Jump to time:', line.time)
@ -418,11 +424,11 @@ function toggleAutoScroll() {
//
function resetScroll() {
if (!lyricsWrapper.value) return
if (!lyricsWrapper.value) {return}
//
if (scrollTween) scrollTween.kill()
if (highlightTween) highlightTween.kill()
if (scrollTween) {scrollTween.kill()}
if (highlightTween) {highlightTween.kill()}
//
gsap.to(lyricsWrapper.value, {
@ -456,12 +462,13 @@ function resetScroll() {
}
// gap
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function getGapDotOpacities(line: GapLine) {
// gap
const duration = line.duration ?? 0
if (duration <= 0) return [0.3, 0.3, 0.3]
if (duration <= 0) {return [0.3, 0.3, 0.3]}
//
const now = playQueueStore.currentTime
const now = playStore.progress.currentTime
// gap
const start = line.time
//
@ -474,7 +481,7 @@ function getGapDotOpacities(line: GapLine) {
}
//
watch(() => playQueueStore.currentTime, (time) => {
watch(() => playStore.progress.currentTime, (time) => {
const newIndex = findCurrentLineIndex(time)
if (newIndex !== currentLineIndex.value && newIndex >= 0) {
@ -500,8 +507,8 @@ watch(() => props.lrcSrc, async (newSrc) => {
lineRefs.value = []
//
if (scrollTween) scrollTween.kill()
if (highlightTween) highlightTween.kill()
if (scrollTween) {scrollTween.kill()}
if (highlightTween) {highlightTween.kill()}
if (newSrc) {
loading.value = true
@ -552,12 +559,12 @@ function setupPageFocusHandlers() {
handleVisibilityChange = () => {
if (document.hidden) {
//
if (scrollTween) scrollTween.pause()
if (highlightTween) highlightTween.pause()
if (scrollTween) {scrollTween.pause()}
if (highlightTween) {highlightTween.pause()}
} else {
//
if (scrollTween && scrollTween.paused()) scrollTween.resume()
if (highlightTween && highlightTween.paused()) highlightTween.resume()
if (scrollTween?.paused()) {scrollTween.resume()}
if (highlightTween?.paused()) {highlightTween.resume()}
//
nextTick(() => {
@ -605,9 +612,9 @@ onMounted(() => {
//
onUnmounted(() => {
if (scrollTween) scrollTween.kill()
if (highlightTween) highlightTween.kill()
if (userScrollTimeout) clearTimeout(userScrollTimeout)
if (scrollTween) {scrollTween.kill()}
if (highlightTween) {highlightTween.kill()}
if (userScrollTimeout) {clearTimeout(userScrollTimeout)}
//
if (handleVisibilityChange) {

View File

@ -1,8 +1,7 @@
<script setup lang="ts">
import { artistsOrganize } from '../utils'
import { ref } from 'vue'
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import { useToast } from 'vue-toast-notification'
import { usePlayStore } from '../stores/usePlayStore'
import { useFavourites } from '../stores/useFavourites'
import QueueAddIcon from '../assets/icons/queueadd.vue'
@ -16,24 +15,18 @@ const props = defineProps<{
playfrom: (index: number) => void,
}>()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const hover = ref(false)
const playQueueStore = usePlayQueueStore()
const toast = useToast()
const playStore = usePlayStore()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const favourites = useFavourites()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function appendToQueue() {
console.log('aaa')
let queue = playQueueStore.list
queue.push({
playStore.appendItem({
song: props.track,
album: props.album,
} as QueueItem)
playQueueStore.list = queue
playQueueStore.queueReplaceLock = true
toast.success('已添加到播放队列末尾', {
position: 'top-right',
duration: 1000,
})
}
</script>

View File

@ -7,13 +7,11 @@ import 'vue-toast-notification/dist/theme-default.css'
import App from './App.vue'
import HomePage from './pages/Home.vue'
import AlbumDetailView from './pages/AlbumDetail.vue'
import Playroom from './pages/Playroom.vue'
import Library from './pages/Library.vue'
const routes = [
{ path: '/', component: HomePage },
{ path: '/albums/:albumId', component: AlbumDetailView },
{ path: '/playroom', component: Playroom },
{ path: '/library', component: Library }
]

View File

@ -1,107 +0,0 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import apis from '../apis'
import { useRoute } from 'vue-router'
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import { artistsOrganize } from '../utils'
import TrackItem from '../components/TrackItem.vue'
import PlayIcon from '../assets/icons/play.vue'
import StarEmptyIcon from '../assets/icons/starempty.vue'
import ShuffleIcon from '../assets/icons/shuffle.vue'
const album = ref<Album>()
const route = useRoute()
const albumId = route.params.albumId
const playQueue = usePlayQueueStore()
onMounted(async () => {
try {
let res = await apis.getAlbum(albumId as string)
for (const track in res.songs) {
res.songs[parseInt(track)] = await apis.getSong(res.songs[parseInt(track)].cid)
}
album.value = res
console.log(res)
} catch (error) {
console.log(error)
}
})
function playTheAlbum(from: number = 0) {
if (playQueue.queueReplaceLock) {
if (!confirm("当前操作会将你的播放队列清空、放入这张专辑所有曲目,并从头播放。继续吗?")) { return }
playQueue.queueReplaceLock = false
}
let newPlayQueue = []
for (const track of album.value?.songs ?? []) {
console.log(track)
newPlayQueue.push({
song: track,
album: album.value
})
}
playQueue.playMode.shuffle = false
playQueue.list = newPlayQueue
playQueue.currentIndex = from
playQueue.isPlaying = true
playQueue.isBuffering = true
}
</script>
<template>
<div class="px-4 md:px-8 flex gap-8 flex-col md:flex-row select-none mt-[6.625rem]">
<div class="mx-auto md:mx-0 md:w-72">
<div class="md:sticky md:top-[6.625rem] flex flex-col gap-8">
<div
class="border border-[#5b5b5b] rounded-md overflow-hidden shadow-2xl bg-neutral-800 sticky w-48 mx-auto md:w-72">
<img :src="album?.coverUrl" class="md:w-72 md:h-72 w-48 h-48 object-contain" />
</div>
<div class="flex flex-col gap-2 text-center md:text-left">
<div class="text-white text-2xl font-semibold">{{ album?.name }}</div>
<div class="text-sky-200 text-xl">{{ artistsOrganize(album?.artistes ?? []) }}</div>
<div class="text-white/50 text-sm">{{ album?.intro }}</div>
</div>
</div>
</div>
<div class="flex-1 flex flex-col gap-8 mb-2">
<div class="flex justify-between items-center">
<div class="flex gap-2">
<button
class="bg-sky-500/20 hover:bg-sky-500/30 active:bg-sky-600/30 active:shadow-inner border border-[#ffffff39] rounded-full w-56 h-10 text-base text-white flex justify-center items-center gap-2"
@click="playTheAlbum()">
<PlayIcon :size="4" />
<div>播放专辑</div>
</button>
<button
class="text-white w-10 h-10 bg-white/5 border border-[#ffffff39] rounded-full flex justify-center items-center"
@click="() => {
playTheAlbum()
playQueue.shuffleCurrent = true
playQueue.playMode.shuffle = true
}">
<ShuffleIcon :size="4" />
</button>
<button
class="text-white w-10 h-10 bg-white/5 border border-[#ffffff39] rounded-full flex justify-center items-center">
<StarEmptyIcon :size="4" />
</button>
</div>
<div class="text-sm text-gray-500 font-medium">
{{ album?.songs?.length ?? '' }} 首曲目
</div>
</div>
<div class="flex flex-col gap-2">
<TrackItem v-for="(track, index) in album?.songs" :key="track.cid" :album="album" :track="track" :index="index"
:playfrom="playTheAlbum" />
</div>
</div>
</div>
</template>

View File

@ -6,21 +6,21 @@ import ShuffleIcon from '../assets/icons/shuffle.vue'
import { useFavourites } from '../stores/useFavourites'
import { ref } from 'vue'
import PlayListItem from '../components/PlayListItem.vue'
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import { usePlayStore } from '../stores/usePlayStore'
const favourites = useFavourites()
const playQueueStore = usePlayQueueStore()
const playQueueStore = usePlayStore()
const currentList = ref<'favourites' | number>('favourites')
function playTheList(list: 'favourites' | number, playFrom: number = 0) {
if (playFrom < 0 || playFrom >= favourites.favouritesCount) { playFrom = 0 }
function playTheList(list: 'favourites' | number, playFrom = 0) {
let actualPlayFrom = playFrom
if (playFrom < 0 || playFrom >= favourites.favouritesCount) { actualPlayFrom = 0 }
if (usePlayQueueStore().queueReplaceLock) {
if (playQueueStore.queueReplaceLock) {
if (!confirm("当前操作会将你的播放队列清空、放入这张歌单所有曲目,并从头播放。继续吗?")) { return }
usePlayQueueStore().queueReplaceLock = false
playQueueStore.queueReplaceLock = false
}
playQueueStore.list = []
if (list === 'favourites') {
if (favourites.favouritesCount === 0) return
@ -29,25 +29,25 @@ function playTheList(list: 'favourites' | number, playFrom: number = 0) {
song: item.song,
album: item.album
}))
playQueueStore.list = newPlayQueue.slice().reverse()
playQueueStore.currentIndex = playFrom
playQueueStore.playMode.shuffle = false
playQueueStore.isPlaying = true
playQueueStore.isBuffering = true
// playQueueStore.list = newPlayQueue.slice().reverse()
// playQueueStore.currentIndex = playFrom
// playQueueStore.playMode.shuffle = false
// playQueueStore.isPlaying = true
// playQueueStore.isBuffering = true
} else {
// Handle other lists if needed
}
}
function shuffle(list: 'favourites' | number) {
playTheList(list)
playQueueStore.shuffleCurrent = true
playQueueStore.playMode.shuffle = false
setTimeout(() => {
playQueueStore.playMode.shuffle = true
playQueueStore.isPlaying = true
playQueueStore.isBuffering = true
}, 100)
// playTheList(list)
// playQueueStore.shuffleCurrent = true
// playQueueStore.playMode.shuffle = false
// setTimeout(() => {
// playQueueStore.playMode.shuffle = true
// playQueueStore.isPlaying = true
// playQueueStore.isBuffering = true
// }, 100)
}
</script>

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import { usePlayQueueStore } from '../stores/usePlayQueueStore'
import { usePlayStore } from '../stores/usePlayStore'
import { artistsOrganize } from '../utils'
import gsap from 'gsap'
import { Draggable } from "gsap/Draggable"
@ -30,8 +30,9 @@ import SpeakerIcon from '../assets/icons/speaker.vue'
import MuscialNoteSparklingIcon from '../assets/icons/musicalnotesparkling.vue'
import CastEmptyIcon from '../assets/icons/castempty.vue'
const playQueueStore = usePlayQueueStore()
const playStore = usePlayStore()
const preferences = usePreferences()
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const favourites = useFavourites()
gsap.registerPlugin(Draggable)
@ -52,6 +53,7 @@ const volumeSliderContainer = useTemplateRef('volumeSliderContainer')
const presentQueueListDialog = ref(false)
const presentLyrics = ref(false)
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
const showLyricsTooltip = ref(false)
const showMoreOptions = ref(false)
const presentVolumeControl = ref(false)
@ -66,8 +68,8 @@ onMounted(async () => {
onDrag: function () {
const thumbPosition = this.x
const containerWidth = progressBarContainer.value?.clientWidth || 0
const newTime = (thumbPosition / containerWidth) * playQueueStore.duration
playQueueStore.updatedCurrentTime = newTime
const newTime = (thumbPosition / containerWidth) * playStore.progress.duration
playStore.updateCurrentTime(newTime)
}
})
@ -77,7 +79,7 @@ onMounted(async () => {
// localStorage
const savedVolume = localStorage.getItem('audioVolume')
if (savedVolume) {
volume.value = parseFloat(savedVolume)
volume.value = Number.parseFloat(savedVolume)
}
thumbUpdate()
@ -88,6 +90,7 @@ onMounted(async () => {
setupPageFocusHandlers()
})
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function timeFormatter(time: number) {
const timeInSeconds = Math.floor(time)
if (timeInSeconds < 0) { return '-:--' }
@ -98,12 +101,12 @@ function timeFormatter(time: number) {
}
//
watch(() => playQueueStore.currentTime, () => {
watch(() => playStore.progress.currentTime, () => {
thumbUpdate()
})
function thumbUpdate() {
const progress = playQueueStore.currentTime / playQueueStore.duration
const progress = playStore.progress.percentage
const containerWidth = progressBarContainer.value?.clientWidth || 0
const thumbWidth = progressBarThumb.value?.clientWidth || 0
const newPosition = (containerWidth - thumbWidth) * progress
@ -117,6 +120,7 @@ function volumeThumbUpdate() {
gsap.to(volumeSliderThumb.value, { x: newPosition, duration: 0.1 })
}
// biome-ignore lint/correctness/noUnusedVariables: used in <template>
function toggleVolumeControl() {
if (!presentVolumeControl.value) {
presentVolumeControl.value = true

View File

@ -9,13 +9,13 @@ declare global {
}
export const useFavourites = defineStore('favourites', () => {
const favourites = ref<QueueItem[]>([])
const favourites = ref<InternalQueueItem[]>([])
const isLoaded = ref(false)
const storageType = ref<'chrome' | 'localStorage' | 'memory'>('chrome')
// 默认收藏列表
const defaultFavourites: QueueItem[] = []
const defaultFavourites: InternalQueueItem[] = []
// 检测可用的 API
const detectAvailableAPIs = () => {
@ -128,7 +128,7 @@ export const useFavourites = defineStore('favourites', () => {
}
// 数据验证和规范化函数
const normalizeFavourites = (data: any[]): QueueItem[] => {
const normalizeFavourites = (data: any[]): InternalQueueItem[] => {
if (!Array.isArray(data)) return []
return data.map(item => {
@ -167,7 +167,7 @@ export const useFavourites = defineStore('favourites', () => {
} : undefined
return { song, album }
}).filter(Boolean) as QueueItem[]
}).filter(Boolean) as InternalQueueItem[]
}
// 获取收藏列表
@ -191,7 +191,7 @@ export const useFavourites = defineStore('favourites', () => {
}
// 添加到收藏
const addToFavourites = async (queueItem: QueueItem) => {
const addToFavourites = async (queueItem: InternalQueueItem) => {
if (!isFavourite(queueItem.song.cid)) {
favourites.value.push(queueItem)
if (isLoaded.value) {
@ -224,7 +224,7 @@ export const useFavourites = defineStore('favourites', () => {
}
// 切换收藏状态
const toggleFavourite = async (queueItem: QueueItem) => {
const toggleFavourite = async (queueItem: InternalQueueItem) => {
if (isFavourite(queueItem.song.cid)) {
await removeFromFavourites(queueItem.song.cid)
} else {

View File

@ -1,217 +0,0 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { checkAndRefreshSongResource } from '../utils'
export const usePlayQueueStore = defineStore('queue', () => {
const list = ref<QueueItem[]>([])
const currentIndex = ref<number>(0)
const isPlaying = ref<boolean>(false)
const queueReplaceLock = ref<boolean>(false)
const isBuffering = ref<boolean>(false)
const currentTime = ref<number>(0)
const duration = ref<number>(0)
const updatedCurrentTime = ref<number | null>(null)
const visualizer = ref<number[]>([0, 0, 0, 0, 0, 0])
const shuffleList = ref<number[]>([])
const playMode = ref<{
shuffle: boolean
repeat: 'off' | 'single' | 'all'
}>({
shuffle: false,
repeat: 'off',
})
const shuffleCurrent = ref<boolean | undefined>(undefined)
// 预加载相关状态
const preloadedAudio = ref<Map<string, HTMLAudioElement>>(new Map())
const isPreloading = ref<boolean>(false)
const preloadProgress = ref<number>(0)
// 获取下一首歌的索引
const getNextIndex = computed(() => {
if (list.value.length === 0) return -1
if (playMode.value.repeat === 'single') {
return currentIndex.value
}
if (playMode.value.shuffle && shuffleList.value.length > 0) {
// 当前在 shuffleList 中的位置
const currentShuffleIndex = currentIndex.value
if (currentShuffleIndex < shuffleList.value.length - 1) {
// 返回下一个位置对应的原始 list 索引
return shuffleList.value[currentShuffleIndex + 1]
} else if (playMode.value.repeat === 'all') {
// 返回第一个位置对应的原始 list 索引
return shuffleList.value[0]
}
return -1
}
if (currentIndex.value < list.value.length - 1) {
return currentIndex.value + 1
} else if (playMode.value.repeat === 'all') {
return 0
}
return -1
})
// 预加载下一首歌
const preloadNext = async () => {
const nextIndex = getNextIndex.value
if (nextIndex === -1) {
return
}
// 获取下一首歌曲对象
// nextIndex 已经是原始 list 中的索引
const nextSong = list.value[nextIndex]
if (!nextSong || !nextSong.song) {
return
}
const songId = nextSong.song.cid
// 如果已经预加载过,跳过
if (preloadedAudio.value.has(songId)) {
return
}
// 检查是否有有效的音频源
if (!nextSong.song.sourceUrl) {
return
}
try {
isPreloading.value = true
preloadProgress.value = 0
// 在预加载前检查和刷新资源
console.log('[Store] 预加载前检查资源:', nextSong.song.name)
const updatedSong = await checkAndRefreshSongResource(
nextSong.song,
(updated) => {
// 更新播放队列中的歌曲信息
// nextIndex 已经是原始 list 中的索引
if (list.value[nextIndex]) {
list.value[nextIndex].song = updated
}
// 如果歌曲在收藏夹中,也更新收藏夹
// 注意:这里不直接导入 favourites store 以避免循环依赖
// 改为触发一个事件或者在调用方处理
console.log('[Store] 预加载时需要更新收藏夹:', updated.name)
},
)
const audio = new Audio()
audio.preload = 'auto'
audio.crossOrigin = 'anonymous'
// 监听加载进度
audio.addEventListener('progress', () => {
if (audio.buffered.length > 0) {
const buffered = audio.buffered.end(0)
const total = audio.duration || 1
preloadProgress.value = (buffered / total) * 100
}
})
// 监听加载完成
audio.addEventListener('canplaythrough', () => {
preloadedAudio.value.set(songId, audio)
isPreloading.value = false
preloadProgress.value = 100
console.log('[Store] 预加载完成:', updatedSong.name)
})
// 监听加载错误
audio.addEventListener('error', (e) => {
console.error(`[Store] 预加载音频失败: ${updatedSong.name}`, e)
isPreloading.value = false
preloadProgress.value = 0
})
// 使用更新后的音频源
audio.src = updatedSong.sourceUrl!
} catch (error) {
console.error('[Store] 预加载过程出错:', error)
isPreloading.value = false
}
}
// 获取预加载的音频对象
const getPreloadedAudio = (songId: string): HTMLAudioElement | null => {
const audio = preloadedAudio.value.get(songId) || null
return audio
}
// 清理预加载的音频
const clearPreloadedAudio = (songId: string) => {
const audio = preloadedAudio.value.get(songId)
if (audio) {
audio.pause()
audio.src = ''
preloadedAudio.value.delete(songId)
}
}
// 清理所有预加载的音频
const clearAllPreloadedAudio = () => {
preloadedAudio.value.forEach((_audio, songId) => {
clearPreloadedAudio(songId)
})
preloadedAudio.value.clear()
}
// 限制预加载缓存大小最多保留3首歌
const limitPreloadCache = () => {
while (preloadedAudio.value.size > 3) {
const oldestKey = preloadedAudio.value.keys().next().value
if (oldestKey) {
clearPreloadedAudio(oldestKey)
} else {
break
}
}
}
// 调试函数:打印当前状态
const debugPreloadState = () => {
console.log('[Store] 预加载状态:', {
isPreloading: isPreloading.value,
progress: preloadProgress.value,
cacheSize: preloadedAudio.value.size,
cachedSongs: Array.from(preloadedAudio.value.keys()),
nextIndex: getNextIndex.value,
})
}
return {
list,
currentIndex,
isPlaying,
queueReplaceLock,
isBuffering,
currentTime,
duration,
updatedCurrentTime,
visualizer,
shuffleList,
playMode,
shuffleCurrent,
// 预加载相关 - 确保所有函数都在返回对象中
preloadedAudio,
isPreloading,
preloadProgress,
getNextIndex,
preloadNext,
getPreloadedAudio,
clearPreloadedAudio,
clearAllPreloadedAudio,
limitPreloadCache,
debugPreloadState,
}
})

View File

@ -0,0 +1,95 @@
import { Player } from '@astrian/music-surge-revolution'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { artistsOrganize } from '../utils'
export const usePlayStore = defineStore('player', () => {
const player = ref(new Player())
const queueReplaceLock = ref(false)
const visualizer = ref([0,0,0,0,0,0])
const progress = ref({
currentTime: 0,
duration: 0,
percentage: 0
})
const currentTrack = ref<{
url: string
metadata?: {
title?: string
artist?: string
artwork?: {
src: string
sizes?: string
type?: string
}[]
}
}>()
const replaceQueue = (queue: {
song: Song
album: Album | undefined
}[]) => {
const newQueue = []
for (const item of queue) {
newQueue.push({
url: item.song.sourceUrl ?? "",
metadata: {
title: item.song.name,
artist: artistsOrganize(item.song.artists ?? item.song.artistes ?? []),
artwork: [{
src: item.album?.coverUrl ?? "",
sizes: "500x500",
type: ((item.album?.coverUrl ?? "").split(".").at(-1) === "jpg" ? 'image/jpeg' : 'image/png') as "image/jpeg" | "image/png"
}]
}
})
}
player.value.replaceQueue(newQueue)
}
const togglePlay = (play?: boolean) => {
player.value.togglePlaying(play)
}
const appendItem = (item: {
song: Song
album: Album | undefined
}) => {
player.value.appendTrack({
url: item.song.sourceUrl ?? "",
metadata: {
title: item.song.name,
artist: artistsOrganize(item.song.artistes ?? item.song.artists ?? []),
artwork: [{
src: item.album?.coverUrl ?? "",
sizes: "500x500",
type: ((item.album?.coverUrl ?? "").split(".").at(-1) === "jpg" ? 'image/jpeg' : 'image/png') as "image/jpeg" | "image/png"
}]
}
})
}
player.value.onProgressChange(params => {
progress.value = params
})
player.value.onCurrentPlayingChange(params => {
currentTrack.value = params
})
const updateCurrentTime = (time: number) => {
player.value.seekTo(time)
}
return {
queueReplaceLock,
togglePlay,
visualizer,
appendItem,
progress,
currentTrack,
updateCurrentTime,
replaceQueue
}
})

2
src/vite-env.d.ts vendored
View File

@ -35,7 +35,7 @@ interface ApiResponse {
data: unknown
}
interface QueueItem {
interface InternalQueueItem {
song: Song
album?: Album
}