diff --git a/src/store/audio.ts b/src/store/audio.ts index 52bbf6b..9ae4e51 100644 --- a/src/store/audio.ts +++ b/src/store/audio.ts @@ -94,30 +94,39 @@ const useAudioState = create()( // FM 模式,切换歌曲 const switchFMSong = async (diff: number) => { if (diff === 0) return; - const { playQueue, playList } = get(); + let { playQueue, playList } = get(); if (!playQueue) return; - const index = playQueue.findIndex((item) => item.id === get().audioId); - const nextIndex = index + diff; // 计算后的 index + // 获取当前播放歌曲, 在 Queue 中的 index,并计算出下一首歌曲的 index + const queueIndex = playQueue.findIndex((item) => item.id === get().audioId); + const listIndex = playList.findIndex((item) => item.id === get().audioId); + const nextQueueIndex = queueIndex + diff; + const nextListIndex = listIndex + diff; + // 播放 list 最后一首歌时,再加载30首 - if (nextIndex >= playList.length - 1) { + if (nextListIndex >= playList.length - 1) { await getFm(); + playQueue = get().playQueue; + playList = get().playList; } - // 判断 index 是否越界,计算音频 id + // 切换歌曲 let audioId = ''; - if (nextIndex < 0) { + if (nextQueueIndex < 0) { + // 在第一首歌点击上一首,切换到最后一首 audioId = playQueue[playQueue.length - 1].id; - } else if (nextIndex >= playQueue.length) { - const newQueue = [...playQueue, playList[nextIndex]]; + } else if (nextQueueIndex >= playQueue.length) { + // 在最后一首歌点击下一首,往 Queue 中 push 歌曲 + const newAudio = playList[nextListIndex]; set( produce((state) => { - state.playQueue = newQueue; + state.playQueue = [...playQueue, newAudio]; }), ); - audioId = newQueue[nextIndex].id; + audioId = newAudio.id; } else { - audioId = playQueue[nextIndex].id; + // 非越界切换 + audioId = playQueue[nextQueueIndex].id; } // 切换歌曲