Compare commits

...

12 Commits

Author SHA1 Message Date
algerkong
f9c920008c feat: changelog 2025-05-12 08:59:42 +08:00
algerkong
ef778a172b 🔧 chore: 更新版本号至 4.6.0 2025-05-12 08:55:28 +08:00
algerkong
eff9328a23 feat: 添加定时关闭功能,支持按时间、歌曲数和播放列表结束自动停止播放 2025-05-03 23:46:28 +08:00
algerkong
5f63ab6b4a 🐞 fix: 优化远程控制页面HTML路径获取逻辑,支持开发环境与生产环境的路径区分 2025-05-02 22:53:29 +08:00
Alger
c2e08db2e4 Merge pull request #186 from algerkong/feat/bili-favorite
 feat: 添加 B站视频 ID 匹配逻辑,优化收藏功能以支持 B站视频,确保收藏列表一致性
2025-05-02 22:43:44 +08:00
algerkong
903389e4bf 🐞 fix: 优化收藏列表样式,添加条件类以支持组件最大宽度 2025-05-02 22:42:43 +08:00
algerkong
327384ace5 feat: 添加 B站视频 ID 匹配逻辑,优化收藏功能以支持 B站视频,确保收藏列表一致性 2025-05-02 22:39:47 +08:00
algerkong
6ffe4daed0 🐞 fix: 优化播放列表索引更新逻辑,避免与 nextPlay/prevPlay 冲突,确保歌曲预加载一致性 2025-05-02 19:54:58 +08:00
algerkong
2b8c9bf22a 🔧 chore: 更新 Electron 版本至 36.1.0,修改应用图标 2025-05-02 19:40:53 +08:00
algerkong
c7d586407e 🐞 fix: 移除不必要的 i18n 导入,优化 MusicHook 逻辑 2025-05-02 19:35:32 +08:00
algerkong
c5af89e51f 🐞 fix: 移除不必要的监听器,优化音频播放逻辑,添加音频就绪事件处理,改进操作锁机制以防止并发操作 2025-05-02 19:25:12 +08:00
algerkong
2d8770b074 🐞 fix: 更新二维码检查接口,添加 noCookie 参数以优化登录状态检查 2025-05-02 18:45:04 +08:00
17 changed files with 1368 additions and 220 deletions

View File

@@ -1,25 +1,27 @@
# 更新日志
## v4.5.0
## 更新时间 2025 年 4 月 29 日 23:50
## v4.6.0
> 如果更新遇到问题,请前往 <a href="http://donate.alger.fun/download" target="_blank">下载 AlgerMusicPlayer</a>
> 帮我点个 star <a href="https://github.com/algerkong/AlgerMusicPlayer" target="_blank">github star</a>
> 请我喝咖啡(支持作者) ☕️ <a href="http://donate.alger.fun/donate" target="_blank" style="color: red; font-weight: bold;">赏你</a>
> 帮我点个 star <a href="https://github.com/algerkong/AlgerMusicPlayer" target="_blank">github star</a>
> QQ群 976962720
### ✨ 新功能
- 添加远程控制功能,支持使用局域网链接地址远程控制音乐播放操作(默认关闭需要在设置中开启) ([c82ffd0](https://github.com/algerkong/AlgerMusicPlayer/commit/c82ffd0))#169
- 更新歌手数据加载逻辑,首页添加周杰伦歌手信息常驻 ([3069514](https://github.com/algerkong/AlgerMusicPlayer/commit/3069514))
- 增加音源重新解析功能 ([82a69d0](https://github.com/algerkong/AlgerMusicPlayer/commit/82a69d0))
- 搜索列表添加下一首播放功能,修改播放逻辑搜索的歌曲点击播放不重新覆盖播放列表,添加全部播放功能 ([31640bb](https://github.com/algerkong/AlgerMusicPlayer/commit/31640bb)) (#216)
- 增加windows和linux对arm64架构的支持([9f125f8](https://github.com/algerkong/AlgerMusicPlayer/commit/9f125f8))
- 添加"收藏"功能至托盘菜单 ([3c1a144](https://github.com/algerkong/AlgerMusicPlayer/commit/3c1a144))
- 修改将歌单列表改为页面 ([e2527c3](https://github.com/algerkong/AlgerMusicPlayer/commit/e2527c3))
### 🐛 Bug 修复
- 修复音乐播放重复声音的问题,添加锁机制,添加防抖机制,优化音频服务和快捷键处理逻辑 ([159dd03](https://github.com/algerkong/AlgerMusicPlayer/commit/159dd03)) (#173)
- 修复歌手页面数据加载不全问题 ([57424f9](https://github.com/algerkong/AlgerMusicPlayer/commit/57424f9)) (#165)
- 修复歌曲加入歌单失败问题 ([8045034](https://github.com/algerkong/AlgerMusicPlayer/commit/8045034))
### 🎨 优化
- 优化应用图标,更新应用图标资源 ([0128662](https://github.com/algerkong/AlgerMusicPlayer/commit/0128662))
- 优化设置页面,拆分组件 ([c98fa20](https://github.com/algerkong/AlgerMusicPlayer/commit/c98fa20))
- 优化设置模块,合并默认设置与存储设置,初始化时读取设置 ([0a22c7b](https://github.com/algerkong/AlgerMusicPlayer/commit/0a22c7b))
- 优化播放器逻辑,改进播放失败处理,支持保持当前索引并增加重试机制,优化操作锁逻辑,添加超时检查机制,确保操作锁在超时后自动释放,增加超时处理([8ed13d4](https://github.com/algerkong/AlgerMusicPlayer/commit/8ed13d4))、([cb58abb](https://github.com/algerkong/AlgerMusicPlayer/commit/cb58abb)) ([9cc064c](https://github.com/algerkong/AlgerMusicPlayer/commit/9cc064c))
- 更新 Electron 版本至 36.2.0,优化歌词视图的悬停效果 ([44f9709](https://github.com/algerkong/AlgerMusicPlayer/commit/44f9709))
- 更新音乐源设置([618c345](https://github.com/algerkong/AlgerMusicPlayer/commit/618c345))
- 修改 MiniPlayBar 组件,调整音量滑块的样式和交互方式,优化悬停效果 ([31ea3b7](https://github.com/algerkong/AlgerMusicPlayer/commit/31ea3b7))
- 优化 MvPlayer 组件的关闭逻辑,简化音频暂停处理 ([b3de2ae](https://github.com/algerkong/AlgerMusicPlayer/commit/b3de2ae))、([15f4ea4](https://github.com/algerkong/AlgerMusicPlayer/commit/15f4ea4))

View File

@@ -1,6 +1,6 @@
{
"name": "AlgerMusicPlayer",
"version": "4.5.0",
"version": "4.6.0",
"description": "Alger Music Player",
"author": "Alger <algerkc@qq.com>",
"main": "./out/main/index.js",
@@ -56,7 +56,7 @@
"autoprefixer": "^10.4.20",
"axios": "^1.7.7",
"cross-env": "^7.0.3",
"electron": "^36.0.0",
"electron": "^36.1.0",
"electron-builder": "^25.1.8",
"electron-vite": "^3.1.0",
"eslint": "^9.0.0",

View File

@@ -73,5 +73,27 @@ export default {
acoustic: 'Acoustic',
custom: 'Custom'
}
},
// Sleep timer related
sleepTimer: {
title: 'Sleep Timer',
cancel: 'Cancel Timer',
timeMode: 'By Time',
songsMode: 'By Songs',
playlistEnd: 'After Playlist',
afterPlaylist: 'After Playlist Ends',
activeUntilEnd: 'Active until end of playlist',
minutes: 'min',
hours: 'hr',
songs: 'songs',
set: 'Set',
timerSetSuccess: 'Timer set for {minutes} minutes',
songsSetSuccess: 'Timer set for {songs} songs',
playlistEndSetSuccess: 'Timer set to end after playlist',
timerCancelled: 'Sleep timer cancelled',
timerEnded: 'Sleep timer ended',
playbackStopped: 'Music playback stopped',
minutesRemaining: '{minutes} min remaining',
songsRemaining: '{count} songs remaining'
}
};

View File

@@ -74,5 +74,27 @@ export default {
acoustic: '原声',
custom: '自定义'
}
},
// 定时关闭功能相关
sleepTimer: {
title: '定时关闭',
cancel: '取消定时',
timeMode: '按时间关闭',
songsMode: '按歌曲数关闭',
playlistEnd: '播放完列表后关闭',
afterPlaylist: '播放完列表后关闭',
activeUntilEnd: '播放至列表结束',
minutes: '分钟',
hours: '小时',
songs: '首歌',
set: '设置',
timerSetSuccess: '已设置{minutes}分钟后关闭',
songsSetSuccess: '已设置播放{songs}首歌后关闭',
playlistEndSetSuccess: '已设置播放完列表后关闭',
timerCancelled: '已取消定时关闭',
timerEnded: '定时关闭已触发',
playbackStopped: '音乐播放已停止',
minutesRemaining: '剩余{minutes}分钟',
songsRemaining: '剩余{count}首歌'
}
};

View File

@@ -21,9 +21,7 @@ const iconPath = join(__dirname, '../../resources');
const icon = nativeImage.createFromPath(
process.platform === 'darwin'
? join(iconPath, 'icon.icns')
: process.platform === 'win32'
? join(iconPath, 'favicon.ico')
: join(iconPath, 'icon.png')
: join(iconPath, 'icon.png')
);
let mainWindow: Electron.BrowserWindow;

View File

@@ -213,7 +213,9 @@ function setupRoutes(app: express.Application) {
app.get('/', (_, res) => {
try {
const resourcesPath = process.resourcesPath || '';
const finalPath = path.join(resourcesPath, 'html', 'remote-control.html');
const isDev = process.env.NODE_ENV === 'development';
const htmlPath = path.join(process.cwd(), 'resources', 'html', 'remote-control.html');
const finalPath = isDev ? htmlPath : path.join(resourcesPath, 'html', 'remote-control.html');
if (fs.existsSync(finalPath)) {
res.sendFile(finalPath);

View File

@@ -15,7 +15,7 @@ export function createQr(key: any) {
// 获取二维码状态
// /login/qr/check
export function checkQr(key: any) {
return request.get('/login/qr/check', { params: { key } });
return request.get('/login/qr/check', { params: { key, noCookie: true } });
}
// 获取登录状态

View File

@@ -123,7 +123,7 @@ import SongItem from '@/components/common/SongItem.vue';
import { allTime, artistList, nowTime, playMusic } from '@/hooks/MusicHook';
import { useArtist } from '@/hooks/useArtist';
import { audioService } from '@/services/audioService';
import { usePlayerStore, useSettingsStore } from '@/store';
import { isBilibiliIdMatch, usePlayerStore, useSettingsStore } from '@/store';
import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils';
@@ -185,20 +185,31 @@ const mute = () => {
// 收藏相关
const isFavorite = computed(() => {
const numericId =
typeof playMusic.value.id === 'string' ? parseInt(playMusic.value.id, 10) : playMusic.value.id;
return playerStore.favoriteList.includes(numericId);
// 对于B站视频使用ID匹配函数
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
return playerStore.favoriteList.some(id => isBilibiliIdMatch(id, playMusic.value.id));
}
// 非B站视频直接比较ID
return playerStore.favoriteList.includes(playMusic.value.id);
});
const toggleFavorite = async (e: Event) => {
e.stopPropagation();
const numericId =
typeof playMusic.value.id === 'string' ? parseInt(playMusic.value.id, 10) : playMusic.value.id;
// 处理B站视频的收藏ID
let favoriteId = playMusic.value.id;
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
// 如果当前播放的是B站视频且已有ID不包含--格式则需要构造完整ID
if (!String(favoriteId).includes('--')) {
favoriteId = `${playMusic.value.bilibiliData.bvid}--${playMusic.value.song?.ar?.[0]?.id || 0}--${playMusic.value.bilibiliData.cid}`;
}
}
if (isFavorite.value) {
playerStore.removeFromFavorite(numericId);
playerStore.removeFromFavorite(favoriteId);
} else {
playerStore.addToFavorite(numericId);
playerStore.addToFavorite(favoriteId);
}
};

View File

@@ -87,6 +87,9 @@
</div>
</n-popover>
</div>
<!-- 定时关闭按钮 -->
<SleepTimerPopover mode="mobile" />
</template>
<!-- Mini模式 - 在musicFullVisible为false时显示 -->
@@ -152,6 +155,7 @@ import { useThrottleFn } from '@vueuse/core';
import { computed, ref, watch } from 'vue';
import SongItem from '@/components/common/SongItem.vue';
import SleepTimerPopover from '@/components/player/SleepTimerPopover.vue';
import { allTime, artistList, nowTime, playMusic, sound, textColors } from '@/hooks/MusicHook';
import MusicFull from '@/layout/components/MusicFull.vue';
import { audioService } from '@/services/audioService';

View File

@@ -144,6 +144,8 @@
</template>
<eq-control />
</n-popover>
<!-- 定时关闭功能 -->
<sleep-timer-popover mode="desktop" />
<n-popover
trigger="click"
:z-index="99999999"
@@ -194,6 +196,7 @@ import { useI18n } from 'vue-i18n';
import SongItem from '@/components/common/SongItem.vue';
import EqControl from '@/components/EQControl.vue';
import SleepTimerPopover from '@/components/player/SleepTimerPopover.vue';
import {
allTime,
artistList,
@@ -206,7 +209,10 @@ import {
import { useArtist } from '@/hooks/useArtist';
import MusicFull from '@/layout/components/MusicFull.vue';
import { audioService } from '@/services/audioService';
import { usePlayerStore } from '@/store/modules/player';
import {
isBilibiliIdMatch,
usePlayerStore
} from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings';
import type { SongResult } from '@/type/music';
import { getImgUrl, isElectron, isMobile, secondToMinute, setAnimationClass } from '@/utils';
@@ -417,22 +423,32 @@ const scrollToPlayList = (val: boolean) => {
};
const isFavorite = computed(() => {
// 将id转换为number兼容B站视频ID
const numericId =
typeof playMusic.value.id === 'string' ? parseInt(playMusic.value.id, 10) : playMusic.value.id;
return playerStore.favoriteList.includes(numericId);
// 对于B站视频使用ID匹配函数
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
return playerStore.favoriteList.some(id => isBilibiliIdMatch(id, playMusic.value.id));
}
// 非B站视频直接比较ID
return playerStore.favoriteList.includes(playMusic.value.id);
});
const toggleFavorite = async (e: Event) => {
console.log('playMusic.value', playMusic.value);
e.stopPropagation();
// 将id转换为number兼容B站视频ID
const numericId =
typeof playMusic.value.id === 'string' ? parseInt(playMusic.value.id, 10) : playMusic.value.id;
// 处理B站视频的收藏ID
let favoriteId = playMusic.value.id;
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
// 如果当前播放的是B站视频且已有ID不包含--格式则需要构造完整ID
if (!String(favoriteId).includes('--')) {
favoriteId = `${playMusic.value.bilibiliData.bvid}--${playMusic.value.song?.ar?.[0]?.id || 0}--${playMusic.value.bilibiliData.cid}`;
}
}
if (isFavorite.value) {
playerStore.removeFromFavorite(numericId);
playerStore.removeFromFavorite(favoriteId);
} else {
playerStore.addToFavorite(numericId);
playerStore.addToFavorite(favoriteId);
}
};

View File

@@ -0,0 +1,478 @@
<template>
<n-popover
trigger="click"
:z-index="99999999"
content-class="sleep-timer"
raw
:show-arrow="false"
placement="top"
display-directive="show"
>
<template #trigger>
<n-tooltip trigger="hover" :z-index="9999999">
<template #trigger>
<div class="control-btn timer" :class="{ 'mobile-timer': mode === 'mobile' }">
<i
class="iconfont ri-time-line"
:class="{ 'text-green-500': hasTimerActive }"
></i>
</div>
</template>
{{ t('player.sleepTimer.title') }}
</n-tooltip>
</template>
<div class="sleep-timer-container" :class="{ 'mobile-sleep-timer-container': mode === 'mobile' }">
<div class="sleep-timer-back"></div>
<div class="sleep-timer-content">
<div class="sleep-timer-title">{{ t('player.sleepTimer.title') }}</div>
<div v-if="hasTimerActive" class="sleep-timer-active">
<div class="timer-status">
<template v-if="timerType === 'time'">
<div class="timer-value countdown-timer">{{ formattedRemainingTime }}</div>
<div class="timer-label">{{ t('player.sleepTimer.minutesRemaining', { minutes: Math.ceil(remainingMinutes/60) }) }}</div>
</template>
<template v-else-if="timerType === 'songs'">
<div class="timer-value">{{ remainingSongs }}</div>
<div class="timer-label">{{ t('player.sleepTimer.songsRemaining', { count: remainingSongs }) }}</div>
</template>
<template v-else-if="timerType === 'end'">
<div class="timer-value">{{ t('player.sleepTimer.activeUntilEnd') }}</div>
<div class="timer-label">{{ t('player.sleepTimer.afterPlaylist') }}</div>
</template>
</div>
<n-button type="error" class="cancel-timer-btn" @click="handleCancelTimer" round>
{{ t('player.sleepTimer.cancel') }}
</n-button>
</div>
<div v-else class="sleep-timer-options">
<!-- 按时间定时 -->
<div class="option-section">
<h4 class="option-title">{{ t('player.sleepTimer.timeMode') }}</h4>
<div class="time-options">
<n-button
v-for="minutes in [15, 30, 60, 90]"
:key="minutes"
size="small"
class="time-option-btn"
@click="handleSetTimeTimer(minutes)"
round
>
{{ minutes }}{{ t('player.sleepTimer.minutes') }}
</n-button>
<div class="custom-time">
<n-input-number
v-model:value="customMinutes"
:min="1"
:max="300"
size="small"
class="custom-time-input"
round
/>
<n-button
size="small"
type="primary"
class="custom-time-btn"
:disabled="!customMinutes"
@click="handleSetTimeTimer(customMinutes)"
round
>
{{ t('player.sleepTimer.set') }}
</n-button>
</div>
</div>
</div>
<!-- 按歌曲数定时 -->
<div class="option-section">
<h4 class="option-title">{{ t('player.sleepTimer.songsMode') }}</h4>
<div class="songs-options">
<n-button
v-for="songs in [1, 3, 5, 10]"
:key="songs"
size="small"
class="songs-option-btn"
@click="handleSetSongsTimer(songs)"
round
>
{{ songs }}{{ t('player.sleepTimer.songs') }}
</n-button>
<div class="custom-songs">
<n-input-number
v-model:value="customSongs"
:min="1"
:max="50"
size="small"
class="custom-songs-input"
round
/>
<n-button
size="small"
type="primary"
class="custom-songs-btn"
:disabled="!customSongs"
@click="handleSetSongsTimer(customSongs)"
round
>
{{ t('player.sleepTimer.set') }}
</n-button>
</div>
</div>
</div>
<!-- 播放完列表后关闭 -->
<div class="option-section playlist-end-section">
<n-button block class="playlist-end-btn" @click="handleSetPlaylistEndTimer" round>
{{ t('player.sleepTimer.playlistEnd') }}
</n-button>
</div>
</div>
</div>
</div>
</n-popover>
</template>
<script lang="ts" setup>
import { computed, ref, onMounted, onUnmounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';
import { usePlayerStore } from '@/store/modules/player';
// 组件接收一个mode参数用于标识是移动端还是桌面端
defineProps({
mode: {
type: String,
default: 'desktop' // 'desktop' 或 'mobile'
}
});
const { t } = useI18n();
const playerStore = usePlayerStore();
// 从store获取所有相关状态
const { sleepTimer} = storeToRefs(playerStore);
// 本地状态用于UI展示
const customMinutes = ref(30);
const customSongs = ref(5);
// 添加一个刷新触发变量,用于强制更新倒计时
const refreshTrigger = ref(0);
// 计算属性,判断定时器状态
const hasTimerActive = computed(() => {
return playerStore.hasSleepTimerActive;
});
const timerType = computed(() => {
return sleepTimer.value.type;
});
// 剩余时间(分钟)
const remainingMinutes = computed(() => {
return playerStore.sleepTimerRemainingTime;
});
// 剩余歌曲数
const remainingSongs = computed(() => {
return playerStore.sleepTimerRemainingSongs;
});
// 处理设置时间定时器
function handleSetTimeTimer(minutes: number) {
playerStore.setSleepTimerByTime(minutes);
}
// 处理设置歌曲数定时器
function handleSetSongsTimer(songs: number) {
playerStore.setSleepTimerBySongs(songs);
}
// 处理设置播放列表结束定时器
function handleSetPlaylistEndTimer() {
playerStore.setSleepTimerAtPlaylistEnd();
}
// 处理取消定时器
function handleCancelTimer() {
playerStore.clearSleepTimer();
}
// 格式化剩余时间为 HH:MM:SS
const formattedRemainingTime = computed(() => {
// 依赖刷新触发器强制更新
void refreshTrigger.value;
if (timerType.value !== 'time' || !sleepTimer.value.endTime) {
return '00:00:00';
}
const remaining = Math.max(0, sleepTimer.value.endTime - Date.now());
const totalSeconds = Math.floor(remaining / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = Math.floor(totalSeconds % 60);
const formattedHours = hours.toString().padStart(2, '0');
const formattedMinutes = minutes.toString().padStart(2, '0');
const formattedSeconds = seconds.toString().padStart(2, '0');
return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
});
// 监听剩余时间变化
let timerInterval: number | null = null;
onMounted(() => {
// 如果当前有定时器开始更新UI
if (hasTimerActive.value && timerType.value === 'time') {
startTimerUpdate();
}
// 监听定时器状态变化
watch(
() => [hasTimerActive.value, timerType.value],
([newHasTimer, newType]) => {
if (newHasTimer && newType === 'time') {
startTimerUpdate();
} else {
stopTimerUpdate();
}
}
);
});
// 启动定时器更新UI
function startTimerUpdate() {
stopTimerUpdate(); // 先停止之前的计时器
// 每秒更新UI
timerInterval = window.setInterval(() => {
// 更新刷新触发器,强制重新计算
refreshTrigger.value = Date.now();
}, 500) as unknown as number;
}
// 停止定时器更新UI
function stopTimerUpdate() {
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
}
onUnmounted(() => {
stopTimerUpdate();
});
</script>
<style lang="scss" scoped>
.control-btn.timer {
@apply cursor-pointer;
.iconfont {
@apply text-2xl m-4 transition-all duration-300 ease-in-out;
&:hover {
@apply text-green-500 transform scale-110;
}
}
&.mobile-timer {
@apply flex items-center justify-center;
height: 56px;
width: 56px;
}
}
// 主容器样式
.sleep-timer-container {
width: 380px;
height: auto;
@apply relative overflow-hidden;
border-radius: 16px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15), 0 0 1px rgba(0, 0, 0, 0.1);
transform-origin: top center;
animation: popoverEnter 0.2s cubic-bezier(0.3, 0, 0.2, 1);
// 入场动画
@keyframes popoverEnter {
from {
opacity: 0;
transform: translateY(-10px) scale(0.98);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
// 移动端样式
&.mobile-sleep-timer-container {
width: 92vw;
max-width: 400px;
@apply rounded-t-2xl;
max-height: 500px;
}
// 背景毛玻璃效果
.sleep-timer-back {
@apply absolute top-0 left-0 w-full h-full dark:bg-gray-900 dark:bg-opacity-75 dark:border-gray-700;
backdrop-filter: blur(25px);
-webkit-backdrop-filter: blur(25px);
background-color: rgba(255, 255, 255, 0.75);
border: 1px solid rgba(255, 255, 255, 0.2);
}
// 内容区域
.sleep-timer-content {
@apply p-6 relative z-10;
// 标题
.sleep-timer-title {
@apply text-xl font-bold text-center mb-6 text-gray-800 dark:text-gray-100;
letter-spacing: 0.5px;
}
// 激活状态显示
.sleep-timer-active {
@apply flex flex-col items-center;
// 定时状态卡片
.timer-status {
@apply flex flex-col items-center justify-center p-8 mb-5 w-full rounded-2xl dark:bg-gray-800 dark:bg-opacity-40 dark:shadow-gray-900/20;
background-color: rgba(255, 255, 255, 0.5);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
// 定时值显示
.timer-value {
@apply text-4xl font-semibold mb-2 text-green-500;
&.countdown-timer {
font-variant-numeric: tabular-nums;
letter-spacing: 2px;
}
}
// 标签文本
.timer-label {
@apply text-base text-gray-600 dark:text-gray-300;
}
}
// 取消按钮
.cancel-timer-btn {
@apply w-full py-3 text-base rounded-full transition-all duration-200;
&:hover {
@apply transform scale-105 shadow-md;
}
&:active {
@apply transform scale-95;
}
}
}
// 定时器选项区域
.sleep-timer-options {
@apply flex flex-col;
// 选项部分
.option-section {
@apply mb-7;
// 选项标题
.option-title {
@apply text-base font-medium mb-4 text-gray-700 dark:text-gray-200;
letter-spacing: 0.3px;
}
// 时间/歌曲选项容器
.time-options, .songs-options {
@apply flex flex-wrap gap-2;
// 选项按钮共享样式
.time-option-btn, .songs-option-btn {
@apply px-4 py-2 rounded-full text-gray-800 dark:text-gray-200 transition-all duration-200;
background-color: rgba(255, 255, 255, 0.5);
@apply dark:bg-gray-800 dark:bg-opacity-40 hover:bg-white dark:hover:bg-gray-700;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(255, 255, 255, 0.1);
@apply dark:shadow-gray-900/20;
&:hover {
@apply transform scale-105 shadow-md;
}
&:active {
@apply transform scale-95;
}
}
// 自定义输入区域
.custom-time, .custom-songs {
@apply flex items-center space-x-2 mt-4 w-full;
// 输入框
.custom-time-input, .custom-songs-input {
@apply flex-1;
:deep(.n-input) {
@apply rounded-full dark:bg-gray-800 dark:bg-opacity-40 dark:border-gray-700;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
background-color: rgba(255, 255, 255, 0.5);
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
&:hover, &:focus {
box-shadow: 0 0 0 2px rgba(34, 197, 94, 0.2);
}
}
}
// 设置按钮
.custom-time-btn, .custom-songs-btn {
@apply py-2 px-4 rounded-full transition-all duration-200;
&:hover {
@apply transform scale-105 shadow-md;
}
&:active {
@apply transform scale-95;
}
}
}
}
}
// 播放列表结束选项
.playlist-end-section {
@apply mt-2;
.playlist-end-btn {
@apply py-3 text-base rounded-full text-gray-800 dark:text-gray-200 transition-all duration-200;
background-color: rgba(255, 255, 255, 0.5);
@apply dark:bg-gray-800 dark:bg-opacity-40 hover:bg-white dark:hover:bg-gray-700;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(255, 255, 255, 0.1);
@apply dark:shadow-gray-900/20;
&:hover {
@apply transform scale-105 shadow-md;
}
&:active {
@apply transform scale-95;
}
}
}
}
}
}
</style>

View File

@@ -2,7 +2,6 @@ import { cloneDeep } from 'lodash';
import { createDiscreteApi } from 'naive-ui';
import { computed, nextTick, onUnmounted, ref, watch } from 'vue';
import i18n from '@/../i18n/renderer';
import { getBilibiliAudioUrl } from '@/api/bilibili';
import useIndexedDB from '@/hooks/IndexDBHook';
import { audioService } from '@/services/audioService';
@@ -235,70 +234,8 @@ const initProgressAnimation = () => {
// 初始化进度动画
initProgressAnimation();
// 简化后的 watch 函数,只保留核心逻辑
watch(
() => playerStore.playMusicUrl,
async (newVal) => {
if (newVal && playMusic.value) {
try {
// 保存当前播放状态
const shouldPlay = playerStore.play;
// 检查是否有保存的进度
let initialPosition = 0;
const savedProgress = JSON.parse(localStorage.getItem('playProgress') || '{}');
if (savedProgress.songId === playMusic.value.id) {
initialPosition = savedProgress.progress;
}
// 对于B站视频检查URL是否有效
if (playMusic.value.source === 'bilibili' && (!newVal || newVal === 'undefined')) {
console.log('B站视频URL无效尝试重新获取');
// 需要重新获取B站视频URL
if (playMusic.value.bilibiliData) {
try {
const proxyUrl = await getBilibiliAudioUrl(
playMusic.value.bilibiliData.bvid,
playMusic.value.bilibiliData.cid
);
// 设置URL到播放器状态
(playMusic.value as any).playMusicUrl = proxyUrl;
playerStore.playMusicUrl = proxyUrl;
newVal = proxyUrl;
} catch (error) {
console.error('获取B站音频URL失败:', error);
return;
}
}
}
// 播放新音频,传递是否应该播放的状态
const newSound = await audioService.play(newVal, playMusic.value, shouldPlay);
sound.value = newSound as Howl;
// 如果有保存的进度,设置播放位置
if (initialPosition > 0) {
newSound.seek(initialPosition);
// 同时更新进度条显示
nowTime.value = initialPosition;
}
setupAudioListeners();
// 确保状态与 localStorage 同步
localStorage.setItem('currentPlayMusic', JSON.stringify(playerStore.playMusic));
localStorage.setItem('currentPlayMusicUrl', newVal);
} catch (error) {
console.error('播放音频失败:', error);
// store.commit('setPlayMusic', false);
playerStore.setPlayMusic(false);
message.error(i18n.global.t('player.playFailed'));
}
}
}
);
// 移除对 playerStore.playMusicUrl 的监听,因为播放逻辑已经在 player.ts 中处理
// 保留 watch 对 playerStore.playMusic 的监听以更新歌词数据
watch(
() => playerStore.playMusic,
@@ -1009,3 +946,27 @@ audioService.on('url_expired', async (expiredTrack) => {
message.error('恢复播放失败,请手动点击播放');
}
});
// 添加音频就绪事件监听器
window.addEventListener('audio-ready', ((event: CustomEvent) => {
try {
const { sound: newSound } = event.detail;
if (newSound) {
// 更新本地 sound 引用
sound.value = newSound as Howl;
// 设置音频监听器
setupAudioListeners();
// 获取当前播放位置并更新显示
const currentPosition = newSound.seek() as number;
if (typeof currentPosition === 'number' && !Number.isNaN(currentPosition)) {
nowTime.value = currentPosition;
}
console.log('音频就绪,已设置监听器并更新进度显示');
}
} catch (error) {
console.error('处理音频就绪事件出错:', error);
}
}) as EventListener);

View File

@@ -43,6 +43,8 @@ class AudioService {
// 添加操作锁防止并发操作
private operationLock = false;
private operationLockTimer: NodeJS.Timeout | null = null;
private operationLockTimeout = 5000; // 5秒超时
constructor() {
if ('mediaSession' in navigator) {
@@ -359,16 +361,47 @@ class AudioService {
}
}
// 设置操作锁,带超时自动释放
private setOperationLock(): boolean {
if (this.operationLock) {
return false;
}
this.operationLock = true;
// 清除之前的定时器
if (this.operationLockTimer) {
clearTimeout(this.operationLockTimer);
}
// 设置超时自动释放锁
this.operationLockTimer = setTimeout(() => {
console.warn('操作锁超时自动释放');
this.operationLock = false;
this.operationLockTimer = null;
}, this.operationLockTimeout);
return true;
}
// 释放操作锁
private releaseOperationLock(): void {
this.operationLock = false;
if (this.operationLockTimer) {
clearTimeout(this.operationLockTimer);
this.operationLockTimer = null;
}
}
// 播放控制相关
play(url?: string, track?: SongResult, isPlay: boolean = true): Promise<Howl> {
// 如果操作锁已激活,说明有操作正在进行中,直接返回
if (this.operationLock) {
if (!this.setOperationLock()) {
console.log('audioService: 操作锁激活,忽略当前播放请求');
return Promise.reject(new Error('操作锁激活,请等待当前操作完成'));
}
this.operationLock = true;
// 如果没有提供新的 URL 和 track且当前有音频实例则继续播放
if (this.currentSound && !url && !track) {
// 如果有进行中的seek操作等待其完成
@@ -377,13 +410,13 @@ class AudioService {
this.seekLock = false;
}
this.currentSound.play();
this.operationLock = false;
this.releaseOperationLock();
return Promise.resolve(this.currentSound);
}
// 如果没有提供必要的参数,返回错误
if (!url || !track) {
this.operationLock = false;
this.releaseOperationLock();
return Promise.reject(new Error('Missing required parameters: url and track'));
}
@@ -520,7 +553,7 @@ class AudioService {
}
} catch (error) {
console.error('Error creating audio instance:', error);
this.operationLock = false;
this.releaseOperationLock();
reject(error);
}
};
@@ -528,7 +561,7 @@ class AudioService {
tryPlay();
}).finally(() => {
// 无论成功或失败都解除操作锁
this.operationLock = false;
this.releaseOperationLock();
});
}
@@ -541,12 +574,10 @@ class AudioService {
}
stop() {
if (this.operationLock) {
if (!this.setOperationLock()) {
console.log('audioService: 操作锁激活,忽略当前停止请求');
return;
}
this.operationLock = true;
if (this.currentSound) {
try {
@@ -569,7 +600,7 @@ class AudioService {
}
this.disposeEQ();
this.operationLock = false;
this.releaseOperationLock();
}
setVolume(volume: number) {
@@ -580,12 +611,10 @@ class AudioService {
}
seek(time: number) {
if (this.operationLock) {
if (!this.setOperationLock()) {
console.log('audioService: 操作锁激活忽略当前seek请求');
return;
}
this.operationLock = true;
if (this.currentSound) {
try {
@@ -599,16 +628,14 @@ class AudioService {
}
}
this.operationLock = false;
this.releaseOperationLock();
}
pause() {
if (this.operationLock) {
if (!this.setOperationLock()) {
console.log('audioService: 操作锁激活,忽略当前暂停请求');
return;
}
this.operationLock = true;
if (this.currentSound) {
try {
@@ -623,7 +650,7 @@ class AudioService {
}
}
this.operationLock = false;
this.releaseOperationLock();
}
clearAllListeners() {

View File

@@ -2,17 +2,21 @@ import { cloneDeep } from 'lodash';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import i18n from '@/../i18n/renderer';
import { getBilibiliAudioUrl } from '@/api/bilibili';
import { getLikedList, getMusicLrc, getMusicUrl, getParsingMusicUrl } from '@/api/music';
import { useMusicHistory } from '@/hooks/MusicHistoryHook';
import { audioService } from '@/services/audioService';
import type { ILyric, ILyricText, SongResult } from '@/type/music';
import { getImgUrl } from '@/utils';
import { getImageLinearBackground } from '@/utils/linearColor';
import { createDiscreteApi } from 'naive-ui';
import { useSettingsStore } from './settings';
import { useUserStore } from './user';
const musicHistory = useMusicHistory();
const { message } = createDiscreteApi(['message']);
const preloadingSounds = ref<Howl[]>([]);
@@ -25,6 +29,50 @@ function getLocalStorageItem<T>(key: string, defaultValue: T): T {
}
}
// 比较B站视频ID的辅助函数
export const isBilibiliIdMatch = (id1: string | number, id2: string | number): boolean => {
const str1 = String(id1);
const str2 = String(id2);
// 如果两个ID都不包含--分隔符,直接比较
if (!str1.includes('--') && !str2.includes('--')) {
return str1 === str2;
}
// 处理B站视频ID
if (str1.includes('--') || str2.includes('--')) {
// 尝试从ID中提取bvid和cid
const extractBvIdAndCid = (str: string) => {
if (!str.includes('--')) return { bvid: '', cid: '' };
const parts = str.split('--');
if (parts.length >= 3) {
// bvid--pid--cid格式
return { bvid: parts[0], cid: parts[2] };
} else if (parts.length === 2) {
// 旧格式或其他格式
return { bvid: '', cid: parts[1] };
}
return { bvid: '', cid: '' };
};
const { bvid: bvid1, cid: cid1 } = extractBvIdAndCid(str1);
const { bvid: bvid2, cid: cid2 } = extractBvIdAndCid(str2);
// 如果两个ID都有bvid比较bvid和cid
if (bvid1 && bvid2) {
return bvid1 === bvid2 && cid1 === cid2;
}
// 其他情况只比较cid部分
if (cid1 && cid2) {
return cid1 === cid2;
}
}
// 默认情况直接比较完整ID
return str1 === str2;
};
// 提取公共函数获取B站视频URL
export const getSongUrl = async (
@@ -275,6 +323,23 @@ const loadLrcAsync = async (playMusic: SongResult) => {
playMusic.lyric = lyrics;
};
// 定时关闭类型
export enum SleepTimerType {
NONE = 'none', // 没有定时
TIME = 'time', // 按时间定时
SONGS = 'songs', // 按歌曲数定时
PLAYLIST_END = 'end' // 播放列表播放完毕定时
}
// 定时关闭信息
export interface SleepTimerInfo {
type: SleepTimerType;
value: number; // 对于TIME类型值以分钟为单位对于SONGS类型值为歌曲数量
endTime?: number; // 何时结束仅TIME类型
startSongIndex?: number; // 开始时的歌曲索引对于SONGS类型
remainingSongs?: number; // 剩余歌曲数对于SONGS类型
}
export const usePlayerStore = defineStore('player', () => {
const play = ref(false);
const isPlay = ref(false);
@@ -284,9 +349,40 @@ export const usePlayerStore = defineStore('player', () => {
const playListIndex = ref(getLocalStorageItem('playListIndex', 0));
const playMode = ref(getLocalStorageItem('playMode', 0));
const musicFull = ref(false);
const favoriteList = ref<number[]>(getLocalStorageItem('favoriteList', []));
const favoriteList = ref<Array<number | string>>(getLocalStorageItem('favoriteList', []));
const savedPlayProgress = ref<number | undefined>();
// 定时关闭相关状态
const sleepTimer = ref<SleepTimerInfo>(getLocalStorageItem('sleepTimer', {
type: SleepTimerType.NONE,
value: 0
}));
const timerInterval = ref<number | null>(null);
// 当前定时关闭状态
const currentSleepTimer = computed(() => sleepTimer.value);
// 判断是否有活跃的定时关闭
const hasSleepTimerActive = computed(() => sleepTimer.value.type !== SleepTimerType.NONE);
// 获取剩余时间用于UI显示
const sleepTimerRemainingTime = computed(() => {
if (sleepTimer.value.type === SleepTimerType.TIME && sleepTimer.value.endTime) {
const remaining = Math.max(0, sleepTimer.value.endTime - Date.now());
return Math.ceil(remaining / 60000); // 转换为分钟并向上取整
}
return 0;
});
// 获取剩余歌曲数用于UI显示
const sleepTimerRemainingSongs = computed(() => {
if (sleepTimer.value.type === SleepTimerType.SONGS) {
return sleepTimer.value.remainingSongs || 0;
}
return 0;
});
const currentSong = computed(() => playMusic.value);
const isPlaying = computed(() => isPlay.value);
const currentPlayList = computed(() => playList.value);
@@ -310,50 +406,97 @@ export const usePlayerStore = defineStore('player', () => {
}
} catch (error) {
console.error('获取B站音频URL失败:', error);
throw error; // 向上抛出错误,让调用者处理
message.error(i18n.global.t('player.playFailed'));
return false; // 返回失败状态
}
}
const updatedPlayMusic = await getSongDetail(music);
playMusic.value = updatedPlayMusic;
playMusicUrl.value = updatedPlayMusic.playMusicUrl as string;
try {
const updatedPlayMusic = await getSongDetail(music);
playMusic.value = updatedPlayMusic;
playMusicUrl.value = updatedPlayMusic.playMusicUrl as string;
play.value = isPlay;
play.value = isPlay;
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
localStorage.setItem('currentPlayMusicUrl', playMusicUrl.value);
localStorage.setItem('isPlaying', play.value.toString());
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
localStorage.setItem('currentPlayMusicUrl', playMusicUrl.value);
localStorage.setItem('isPlaying', play.value.toString());
let title = updatedPlayMusic.name;
let title = updatedPlayMusic.name;
if (updatedPlayMusic.source === 'netease' && updatedPlayMusic?.song?.artists) {
title += ` - ${updatedPlayMusic.song.artists.reduce(
(prev: string, curr: any) => `${prev}${curr.name}/`,
''
)}`;
} else if (updatedPlayMusic.source === 'bilibili' && updatedPlayMusic?.song?.ar?.[0]) {
title += ` - ${updatedPlayMusic.song.ar[0].name}`;
if (updatedPlayMusic.source === 'netease' && updatedPlayMusic?.song?.artists) {
title += ` - ${updatedPlayMusic.song.artists.reduce(
(prev: string, curr: any) => `${prev}${curr.name}/`,
''
)}`;
} else if (updatedPlayMusic.source === 'bilibili' && updatedPlayMusic?.song?.ar?.[0]) {
title += ` - ${updatedPlayMusic.song.ar[0].name}`;
}
document.title = title;
loadLrcAsync(playMusic.value);
musicHistory.addMusic(playMusic.value);
// 找到歌曲在播放列表中的索引,如果是通过 nextPlay/prevPlay 调用的,不会更新 playListIndex
const songIndex = playList.value.findIndex(
(item: SongResult) => item.id === music.id && item.source === music.source
);
// 只有在 songIndex 有效,并且与当前 playListIndex 不同时才更新
// 这样可以避免与 nextPlay/prevPlay 中的索引更新冲突
if (songIndex !== -1 && songIndex !== playListIndex.value) {
console.log('歌曲索引不匹配,更新为:', songIndex);
playListIndex.value = songIndex;
}
// 无论如何都预加载更多歌曲
if (songIndex !== -1) {
fetchSongs(playList.value, songIndex + 1, songIndex + 3);
} else {
console.warn('当前歌曲未在播放列表中找到');
}
// 使用标记防止循环调用
let playInProgress = false;
// 直接调用 playAudio 方法播放音频,不需要依赖外部监听
try {
if (playInProgress) {
console.warn('播放操作正在进行中,避免重复调用');
return true;
}
playInProgress = true;
// 因为调用 playAudio 前我们已经设置了 play.value所以不需要额外传递 shouldPlay 参数
const result = await playAudio();
playInProgress = false;
return !!result;
} catch (error) {
console.error('自动播放音频失败:', error);
playInProgress = false;
return false;
}
} catch (error) {
console.error('处理播放音乐失败:', error);
message.error(i18n.global.t('player.playFailed'));
return false;
}
document.title = title;
loadLrcAsync(playMusic.value);
musicHistory.addMusic(playMusic.value);
playListIndex.value = playList.value.findIndex(
(item: SongResult) => item.id === music.id && item.source === music.source
);
fetchSongs(playList.value, playListIndex.value + 1, playListIndex.value + 3);
};
const setPlay = async (song: SongResult) => {
try {
await handlePlayMusic(song);
// 直接调用 handlePlayMusic,它会处理索引更新和播放逻辑
const success = await handlePlayMusic(song);
// 记录到本地存储,保持一致性
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
localStorage.setItem('currentPlayMusicUrl', playMusicUrl.value);
return true;
return success;
} catch (error) {
console.error('设置播放失败:', error);
return false;
@@ -404,57 +547,315 @@ export const usePlayerStore = defineStore('player', () => {
setPlayList(list);
};
const nextPlay = async () => {
if (playList.value.length === 0) {
play.value = true;
// 睡眠定时器功能
const setSleepTimerByTime = (minutes: number) => {
// 清除现有定时器
clearSleepTimer();
if (minutes <= 0) {
return;
}
let nowPlayListIndex: number;
if (playMode.value === 2) {
do {
nowPlayListIndex = Math.floor(Math.random() * playList.value.length);
} while (nowPlayListIndex === playListIndex.value && playList.value.length > 1);
} else {
nowPlayListIndex = (playListIndex.value + 1) % playList.value.length;
const endTime = Date.now() + minutes * 60 * 1000;
sleepTimer.value = {
type: SleepTimerType.TIME,
value: minutes,
endTime
};
// 保存到本地存储
localStorage.setItem('sleepTimer', JSON.stringify(sleepTimer.value));
// 设置定时器检查
timerInterval.value = window.setInterval(() => {
checkSleepTimer();
}, 1000) as unknown as number; // 每秒检查一次
console.log(`设置定时关闭: ${minutes}分钟后`);
return true;
};
// 睡眠定时器功能
const setSleepTimerBySongs = (songs: number) => {
// 清除现有定时器
clearSleepTimer();
if (songs <= 0) {
return;
}
playListIndex.value = nowPlayListIndex;
// 获取下一首歌曲
const nextSong = playList.value[playListIndex.value];
// 如果是B站视频确保重新获取URL
if (nextSong.source === 'bilibili' && nextSong.bilibiliData) {
// 清除之前的URL确保重新获取
nextSong.playMusicUrl = undefined;
console.log('下一首是B站视频已清除URL强制重新获取');
sleepTimer.value = {
type: SleepTimerType.SONGS,
value: songs,
startSongIndex: playListIndex.value,
remainingSongs: songs
};
// 保存到本地存储
localStorage.setItem('sleepTimer', JSON.stringify(sleepTimer.value));
console.log(`设置定时关闭: 再播放${songs}首歌后`);
return true;
};
// 睡眠定时器功能
const setSleepTimerAtPlaylistEnd = () => {
// 清除现有定时器
clearSleepTimer();
sleepTimer.value = {
type: SleepTimerType.PLAYLIST_END,
value: 0
};
// 保存到本地存储
localStorage.setItem('sleepTimer', JSON.stringify(sleepTimer.value));
console.log('设置定时关闭: 播放列表结束时');
return true;
};
// 取消定时关闭
const clearSleepTimer = () => {
if (timerInterval.value) {
window.clearInterval(timerInterval.value);
timerInterval.value = null;
}
sleepTimer.value = {
type: SleepTimerType.NONE,
value: 0
};
// 保存到本地存储
localStorage.setItem('sleepTimer', JSON.stringify(sleepTimer.value));
console.log('取消定时关闭');
return true;
};
// 检查定时关闭是否应该触发
const checkSleepTimer = () => {
if (sleepTimer.value.type === SleepTimerType.NONE) {
return;
}
if (sleepTimer.value.type === SleepTimerType.TIME && sleepTimer.value.endTime) {
if (Date.now() >= sleepTimer.value.endTime) {
// 时间到,停止播放
stopPlayback();
}
} else if (sleepTimer.value.type === SleepTimerType.PLAYLIST_END) {
// 播放列表结束定时由nextPlay方法处理
}
};
// 停止播放并清除定时器
const stopPlayback = () => {
console.log('定时器触发:停止播放');
if (isPlaying.value) {
setIsPlay(false);
audioService.pause();
}
// 如果使用Electron发送通知
if (window.electron?.ipcRenderer) {
window.electron.ipcRenderer.send('show-notification', {
title: i18n.global.t('player.sleepTimer.timerEnded'),
body: i18n.global.t('player.sleepTimer.playbackStopped')
});
}
// 清除定时器
clearSleepTimer();
};
// 监听歌曲变化,处理按歌曲数定时和播放列表结束定时
const handleSongChange = () => {
console.log('歌曲已切换,检查定时器状态:', sleepTimer.value);
// 处理按歌曲数定时
if (sleepTimer.value.type === SleepTimerType.SONGS && sleepTimer.value.remainingSongs !== undefined) {
sleepTimer.value.remainingSongs--;
console.log(`剩余歌曲数: ${sleepTimer.value.remainingSongs}`);
// 保存到本地存储
localStorage.setItem('sleepTimer', JSON.stringify(sleepTimer.value));
if (sleepTimer.value.remainingSongs <= 0) {
// 歌曲数到达,停止播放
console.log('已播放完设定的歌曲数,停止播放');
stopPlayback()
setTimeout(() => {
stopPlayback();
}, 1000);
}
}
// 处理播放列表结束定时
if (sleepTimer.value.type === SleepTimerType.PLAYLIST_END) {
// 检查是否到达播放列表末尾
const isLastSong = (playListIndex.value === playList.value.length - 1);
// 如果是列表最后一首歌且不是循环模式,则设置为在这首歌结束后停止
if (isLastSong && playMode.value !== 1) { // 1 是循环模式
console.log('已到达播放列表末尾,将在当前歌曲结束后停止播放');
// 转换为按歌曲数定时剩余1首
sleepTimer.value = {
type: SleepTimerType.SONGS,
value: 1,
remainingSongs: 1
};
// 保存到本地存储
localStorage.setItem('sleepTimer', JSON.stringify(sleepTimer.value));
}
}
};
await handlePlayMusic(nextSong);
// 修改nextPlay方法加入定时关闭检查逻辑
const nextPlay = async () => {
// 静态标志,防止多次调用造成递归
if ((nextPlay as any).isRunning) {
console.log('下一首播放正在执行中,忽略重复调用');
return;
}
try {
(nextPlay as any).isRunning = true;
if (playList.value.length === 0) {
play.value = true;
(nextPlay as any).isRunning = false;
return;
}
// 检查是否是播放列表的最后一首且设置了播放列表结束定时
if (playMode.value === 0 && playListIndex.value === playList.value.length - 1 &&
sleepTimer.value.type === SleepTimerType.PLAYLIST_END) {
// 已是最后一首且为顺序播放模式,触发停止
stopPlayback();
(nextPlay as any).isRunning = false;
return;
}
// 在切换前保存当前播放状态
const shouldPlayNext = play.value;
console.log('切换到下一首,当前播放状态:', shouldPlayNext ? '播放' : '暂停');
let nowPlayListIndex: number;
if (playMode.value === 2) {
do {
nowPlayListIndex = Math.floor(Math.random() * playList.value.length);
} while (nowPlayListIndex === playListIndex.value && playList.value.length > 1);
} else {
nowPlayListIndex = (playListIndex.value + 1) % playList.value.length;
}
// 重要:首先更新当前播放索引
playListIndex.value = nowPlayListIndex;
// 获取下一首歌曲
const nextSong = playList.value[nowPlayListIndex];
// 如果是B站视频确保重新获取URL
if (nextSong.source === 'bilibili' && nextSong.bilibiliData) {
// 清除之前的URL确保重新获取
nextSong.playMusicUrl = undefined;
console.log('下一首是B站视频已清除URL强制重新获取');
}
// 尝试播放,并明确传递应该播放的状态
const success = await handlePlayMusic(nextSong, shouldPlayNext);
if (!success) {
console.error('播放下一首失败,将从播放列表中移除此歌曲');
// 从播放列表中移除失败的歌曲
const newPlayList = [...playList.value];
newPlayList.splice(nowPlayListIndex, 1);
if (newPlayList.length > 0) {
// 更新播放列表后,重新尝试播放下一首
setPlayList(newPlayList);
// 延迟一点时间再尝试下一首,避免立即触发可能导致的无限循环
setTimeout(() => {
(nextPlay as any).isRunning = false;
nextPlay();
}, 300);
return;
}
}
// 歌曲切换成功,触发歌曲变更处理(用于定时关闭功能)
handleSongChange();
} catch (error) {
console.error('切换下一首出错:', error);
} finally {
(nextPlay as any).isRunning = false;
}
};
const prevPlay = async () => {
if (playList.value.length === 0) {
play.value = true;
// 静态标志,防止多次调用造成递归
if ((prevPlay as any).isRunning) {
console.log('上一首播放正在执行中,忽略重复调用');
return;
}
const nowPlayListIndex =
(playListIndex.value - 1 + playList.value.length) % playList.value.length;
try {
(prevPlay as any).isRunning = true;
if (playList.value.length === 0) {
play.value = true;
(prevPlay as any).isRunning = false;
return;
}
const nowPlayListIndex =
(playListIndex.value - 1 + playList.value.length) % playList.value.length;
// 获取上一首歌曲
const prevSong = playList.value[nowPlayListIndex];
// 重要:首先更新当前播放索引
playListIndex.value = nowPlayListIndex;
// 获取上一首歌曲
const prevSong = playList.value[nowPlayListIndex];
// 如果是B站视频确保重新获取URL
if (prevSong.source === 'bilibili' && prevSong.bilibiliData) {
// 清除之前的URL确保重新获取
prevSong.playMusicUrl = undefined;
console.log('上一首是B站视频已清除URL强制重新获取');
// 如果是B站视频确保重新获取URL
if (prevSong.source === 'bilibili' && prevSong.bilibiliData) {
// 清除之前的URL确保重新获取
prevSong.playMusicUrl = undefined;
console.log('上一首是B站视频已清除URL强制重新获取');
}
// 尝试播放如果失败会返回false
const success = await handlePlayMusic(prevSong);
if (success) {
await fetchSongs(playList.value, playListIndex.value - 3, nowPlayListIndex);
} else {
console.error('播放上一首失败,将从播放列表中移除此歌曲');
// 从播放列表中移除失败的歌曲
const newPlayList = [...playList.value];
newPlayList.splice(nowPlayListIndex, 1);
if (newPlayList.length > 0) {
// 更新播放列表后,重新尝试播放上一首
setPlayList(newPlayList);
// 延迟一点时间再尝试上一首,避免立即触发可能导致的无限循环
setTimeout(() => {
(prevPlay as any).isRunning = false;
prevPlay();
}, 300);
return;
}
}
} catch (error) {
console.error('切换上一首出错:', error);
} finally {
(prevPlay as any).isRunning = false;
}
await handlePlayMusic(prevSong);
await fetchSongs(playList.value, playListIndex.value - 3, nowPlayListIndex);
};
const togglePlayMode = () => {
@@ -462,19 +863,31 @@ export const usePlayerStore = defineStore('player', () => {
localStorage.setItem('playMode', JSON.stringify(playMode.value));
};
const addToFavorite = async (id: number) => {
if (!favoriteList.value.includes(id)) {
const addToFavorite = async (id: number | string) => {
// 检查是否已存在相同的ID或内容相同的B站视频
const isAlreadyInList = favoriteList.value.some(existingId =>
typeof id === 'string' && id.includes('--')
? isBilibiliIdMatch(existingId, id)
: existingId === id
);
if (!isAlreadyInList) {
favoriteList.value.push(id);
localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value));
}
};
const removeFromFavorite = async (id: number) => {
favoriteList.value = favoriteList.value.filter((item) => item !== id);
const removeFromFavorite = async (id: number | string) => {
// 对于B站视频需要根据bvid和cid来匹配
if (typeof id === 'string' && id.includes('--')) {
favoriteList.value = favoriteList.value.filter(existingId => !isBilibiliIdMatch(existingId, id));
} else {
favoriteList.value = favoriteList.value.filter(existingId => existingId !== id);
}
localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value));
};
const removeFromPlayList = (id: number) => {
const removeFromPlayList = (id: number | string) => {
const index = playList.value.findIndex((item) => item.id === id);
if (index === -1) return;
@@ -568,6 +981,90 @@ export const usePlayerStore = defineStore('player', () => {
localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value));
};
// 修改:处理音频播放的方法,使用事件触发机制
const playAudio = async () => {
if (!playMusicUrl.value || !playMusic.value) return null;
try {
// 保存当前播放状态
const shouldPlay = play.value;
console.log('播放音频,当前播放状态:', shouldPlay ? '播放' : '暂停');
// 检查是否有保存的进度
let initialPosition = 0;
const savedProgress = JSON.parse(localStorage.getItem('playProgress') || '{}');
if (savedProgress.songId === playMusic.value.id) {
initialPosition = savedProgress.progress;
}
// 对于B站视频检查URL是否有效
if (playMusic.value.source === 'bilibili' && (!playMusicUrl.value || playMusicUrl.value === 'undefined')) {
console.log('B站视频URL无效尝试重新获取');
// 需要重新获取B站视频URL
if (playMusic.value.bilibiliData) {
try {
const proxyUrl = await getBilibiliAudioUrl(
playMusic.value.bilibiliData.bvid,
playMusic.value.bilibiliData.cid
);
// 设置URL到播放器状态
(playMusic.value as any).playMusicUrl = proxyUrl;
playMusicUrl.value = proxyUrl;
} catch (error) {
console.error('获取B站音频URL失败:', error);
message.error(i18n.global.t('player.playFailed'));
return null;
}
}
}
// 播放新音频,传递是否应该播放的状态
console.log('调用audioService.play播放状态:', shouldPlay);
const newSound = await audioService.play(playMusicUrl.value, playMusic.value, shouldPlay);
// 如果有保存的进度,设置播放位置
if (initialPosition > 0) {
newSound.seek(initialPosition);
}
// 发布音频就绪事件,让 MusicHook.ts 来处理设置监听器
window.dispatchEvent(new CustomEvent('audio-ready', { detail: { sound: newSound, shouldPlay } }));
// 确保状态与 localStorage 同步
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
localStorage.setItem('currentPlayMusicUrl', playMusicUrl.value);
return newSound;
} catch (error) {
console.error('播放音频失败:', error);
setPlayMusic(false);
// 避免直接调用 nextPlay改用延时避免无限循环
// 检查错误是否是由于操作锁引起的
const errorMsg = error instanceof Error ? error.message : String(error);
if (errorMsg.includes('操作锁激活')) {
console.log('由于操作锁正在使用将在500ms后重试');
// 操作锁错误,延迟后再尝试
setTimeout(() => {
// 检查当前播放列表是否有下一首
if (playList.value.length > 1) {
nextPlay();
}
}, 500);
} else {
// 其他错误,延迟更短时间后切换
setTimeout(() => {
nextPlay();
}, 100);
}
message.error(i18n.global.t('player.playFailed'));
return null;
}
};
return {
play,
isPlay,
@@ -579,6 +1076,17 @@ export const usePlayerStore = defineStore('player', () => {
musicFull,
savedPlayProgress,
favoriteList,
// 定时关闭相关
sleepTimer,
currentSleepTimer,
hasSleepTimerActive,
sleepTimerRemainingTime,
sleepTimerRemainingSongs,
setSleepTimerByTime,
setSleepTimerBySongs,
setSleepTimerAtPlaylistEnd,
clearSleepTimer,
currentSong,
isPlaying,
@@ -598,6 +1106,7 @@ export const usePlayerStore = defineStore('player', () => {
initializeFavoriteList,
addToFavorite,
removeFromFavorite,
removeFromPlayList
removeFromPlayList,
playAudio
};
});

View File

@@ -233,7 +233,7 @@ const loadVideoSource = async () => {
// 其他分P创建占位对象稍后按需加载
return {
id: `${videoDetail.value!.aid}--${page.cid}`, // 使用aid+cid作为唯一ID
id: `${bvid.value}--${page.page}--${page.cid}`, // 使用bvid--pid--cid作为唯一ID
name: `${page.part || ''} - ${videoDetail.value!.title}`,
picUrl: getBilibiliProxyUrl(videoDetail.value!.pic),
type: 0,
@@ -242,7 +242,7 @@ const loadVideoSource = async () => {
source: 'bilibili', // 设置来源为B站
song: {
name: `${page.part || ''} - ${videoDetail.value!.title}`,
id: `${videoDetail.value!.aid}--${page.cid}`,
id: `${bvid.value}--${page.page}--${page.cid}`,
ar: [
{
name: videoDetail.value!.owner.name,
@@ -286,7 +286,7 @@ const createSongFromBilibiliVideo = (): SongResult => {
const title = `${pageName} - ${videoDetail.value.title}`;
return {
id: `${videoDetail.value.aid}--${currentPage.value.cid}`, // 使用aid+cid作为唯一ID
id: `${bvid.value}--${currentPage.value.page}--${currentPage.value.cid}`, // 使用bvid--pid--cid作为唯一ID
name: title,
picUrl: getBilibiliProxyUrl(videoDetail.value.pic),
type: 0,
@@ -297,7 +297,7 @@ const createSongFromBilibiliVideo = (): SongResult => {
// playMusicUrl属性稍后通过loadSongUrl函数添加
song: {
name: title,
id: `${videoDetail.value.aid}--${currentPage.value.cid}`,
id: `${bvid.value}--${currentPage.value.page}--${currentPage.value.cid}`,
ar: [
{
name: videoDetail.value.owner.name,

View File

@@ -54,12 +54,12 @@
<div v-if="favoriteList.length === 0" class="empty-tip">
<n-empty :description="t('favorite.emptyTip')" />
</div>
<div v-else class="favorite-list">
<div v-else class="favorite-list" :class="{ 'max-w-[400px]': isComponent }">
<song-item
v-for="(song, index) in favoriteSongs"
:key="song.id"
:item="song"
:favorite="!isComponent"
:favorite="false"
:class="setAnimationClass('animate__bounceInLeft')"
:style="getItemAnimationDelay(index)"
:selectable="isSelecting"
@@ -90,6 +90,7 @@ import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { getMusicDetail } from '@/api/music';
import { getBilibiliProxyUrl, getBilibiliVideoDetail } from '@/api/bilibili';
import SongItem from '@/components/common/SongItem.vue';
import { getSongUrl } from '@/hooks/MusicListHook';
import { usePlayerStore } from '@/store';
@@ -231,6 +232,7 @@ const props = defineProps({
const getCurrentPageIds = () => {
const startIndex = (currentPage.value - 1) * pageSize;
const endIndex = startIndex + pageSize;
// 返回原始ID不进行类型转换
return favoriteList.value.slice(startIndex, endIndex);
};
@@ -248,23 +250,117 @@ const getFavoriteSongs = async () => {
loading.value = true;
try {
const currentIds = getCurrentPageIds();
const res = await getMusicDetail(currentIds);
if (res.data.songs) {
const newSongs = res.data.songs.map((song: SongResult) => ({
...song,
picUrl: song.al?.picUrl || ''
}));
// 追加新数据而不是替换
if (currentPage.value === 1) {
favoriteSongs.value = newSongs;
} else {
favoriteSongs.value = [...favoriteSongs.value, ...newSongs];
console.log('currentIds', currentIds);
// 分离网易云音乐ID和B站视频ID
const musicIds = currentIds.filter((id) => typeof id === 'number') as number[];
// B站ID可能是字符串格式包含"--"或特定数字ID如113911642789603
const bilibiliIds = currentIds.filter((id) => typeof id === 'string');
console.log('处理数据:', {
musicIds,
bilibiliIds
});
// 处理网易云音乐数据
let neteaseSongs: SongResult[] = [];
if (musicIds.length > 0) {
const res = await getMusicDetail(musicIds);
if (res.data.songs) {
neteaseSongs = res.data.songs.map((song: SongResult) => ({
...song,
picUrl: song.al?.picUrl || '',
source: 'netease'
}));
}
// 判断是否还有更多数据
noMore.value = favoriteSongs.value.length >= favoriteList.value.length;
}
// 处理B站视频数据
const bilibiliSongs: SongResult[] = [];
for (const biliId of bilibiliIds) {
const strBiliId = String(biliId);
console.log(`处理B站ID: ${strBiliId}`);
if (strBiliId.includes('--')) {
// 从ID中提取B站视频信息 (bvid--pid--cid格式)
try {
const [bvid, pid, cid] = strBiliId.split('--');
if (!bvid || !pid || !cid) {
console.warn(`B站ID格式错误: ${strBiliId}, 正确格式应为 bvid--pid--cid`);
continue;
}
const res = await getBilibiliVideoDetail(bvid);
const videoDetail = res.data;
// 找到对应的分P
const page = videoDetail.pages.find(p => p.cid === Number(cid));
if (!page) {
console.warn(`未找到对应的分P: cid=${cid}`);
continue;
}
const songData = {
id: strBiliId,
name: `${page.part || ''} - ${videoDetail.title}`,
picUrl: getBilibiliProxyUrl(videoDetail.pic),
ar: [
{
name: videoDetail.owner.name,
id: videoDetail.owner.mid
}
],
al: {
name: videoDetail.title,
picUrl: getBilibiliProxyUrl(videoDetail.pic)
},
source: 'bilibili',
bilibiliData: {
bvid,
cid: Number(cid)
}
} as SongResult;
bilibiliSongs.push(songData);
} catch (error) {
console.error(`获取B站视频详情失败 (${strBiliId}):`, error);
}
}
}
console.log('获取数据统计:', {
neteaseSongs: neteaseSongs.length,
bilibiliSongs: bilibiliSongs.length
});
// 合并数据,保持原有顺序
const newSongs = currentIds
.map(id => {
const strId = String(id);
// 查找B站视频
if (typeof id === 'string') {
const found = bilibiliSongs.find(song => String(song.id) === strId);
if (found) return found;
}
// 查找网易云音乐
const found = neteaseSongs.find(song => String(song.id) === strId);
return found;
})
.filter((song): song is SongResult => !!song);
console.log(`最终歌曲列表: ${newSongs.length}`);
// 追加新数据而不是替换
if (currentPage.value === 1) {
favoriteSongs.value = newSongs;
} else {
favoriteSongs.value = [...favoriteSongs.value, ...newSongs];
}
// 判断是否还有更多数据
noMore.value = favoriteSongs.value.length >= favoriteList.value.length;
} catch (error) {
console.error('获取收藏歌曲失败:', error);
} finally {

View File

@@ -109,7 +109,7 @@ const getHistorySongs = async () => {
if (!page) continue;
bilibiliSongs.push({
id: `${videoDetail.aid}--${page.cid}`,
id: `${bvid}--${page.page}--${page.cid}`,
name: `${page.part || ''} - ${videoDetail.title}`,
picUrl: getBilibiliProxyUrl(videoDetail.pic),
ar: [