mirror of
https://github.com/algerkong/AlgerMusicPlayer.git
synced 2026-04-15 07:20:49 +08:00
Merge pull request #102 from algerkong/feat/bilibili-play
添加 bilibili资源搜索播放
This commit is contained in:
90
.cursor/rules/music-vue-rule.mdc
Normal file
90
.cursor/rules/music-vue-rule.mdc
Normal file
@@ -0,0 +1,90 @@
|
||||
---
|
||||
description: 这个规则是项目描述
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
您是 TypeScript、Node.j、Vue3、Electron、naive-ui、VueUse 和 Tailwind 方面的专家。
|
||||
|
||||
项目结构
|
||||
- 这是 Electron 项目,使用 Vue3 和 Vuex 进行开发的第三方网易云音乐播放器。
|
||||
- 使用 Vue3 和 Vuex 进行开发。
|
||||
- 使用 Vuex 进行状态管理。
|
||||
- 使用 VueUse 进行状态管理。
|
||||
- 使用 naive-ui 进行 UI 设计。
|
||||
- 使用 Tailwind 进行样式设计。
|
||||
- 使用 remixicon 进行图标设计。
|
||||
- 使用 vite 进行项目构建。
|
||||
- 使用 electron-builder 进行项目打包。
|
||||
- 使用 electron-vite 进行项目开发。
|
||||
- 使用 netease-cloud-music-api 进行网易云音乐接口调用。
|
||||
- 使用 electron-store 进行本地数据存储。
|
||||
- 使用 axios 进行网络请求。
|
||||
- 使用 @unblockneteasemusic/server 进行网易云音乐解锁。
|
||||
- 使用 vue-i18n 进行国际化。目录为 src/i18n
|
||||
|
||||
代码风格和结构
|
||||
- 编写简洁、技术性的 TypeScript 代码,并提供准确示例。
|
||||
- 使用组合 API 和声明性编程模式;避免使用选项 API。
|
||||
- 优先使用迭代和模块化,而不是代码重复。
|
||||
- 使用带有助动词的描述性变量名称(例如 isLoading、hasError)。
|
||||
- 结构文件:导出的组件、可组合项、帮助程序、静态内容、类型。
|
||||
|
||||
命名约定
|
||||
- 使用带破折号的小写字母表示目录(例如 components/auth-wizard)。
|
||||
- 使用 PascalCase 表示组件名称(例如 AuthWizard.vue)。
|
||||
- 使用 camelCase 表示可组合项(例如 useAuthState.ts)。
|
||||
|
||||
TypeScript 用法
|
||||
- 对所有代码使用 TypeScript;优先使用类型而不是接口。
|
||||
- 避免使用枚举;改用 const 对象。
|
||||
- 将 Vue 3 与 TypeScript 结合使用,利用 defineComponent 和 PropType。
|
||||
|
||||
语法和格式
|
||||
- 对方法和计算属性使用箭头函数。
|
||||
- 避免在条件中使用不必要的花括号;对简单语句使用简洁的语法。
|
||||
- 使用模板语法进行声明式渲染。
|
||||
|
||||
UI 和样式
|
||||
- 使用 naive-ui 和 Tailwind 进行组件和样式设计。
|
||||
- 使用 Tailwind CSS 实现响应式设计;采用移动优先方法。
|
||||
|
||||
图标
|
||||
- 使用 remixicon 作为图标库。
|
||||
|
||||
性能优化
|
||||
- 对异步组件使用 Suspense。
|
||||
- 为路由和组件实现延迟加载。
|
||||
|
||||
关键约定
|
||||
- 对常见可组合项和实用函数使用 VueUse。
|
||||
- 使用 Vuex 进行状态管理。
|
||||
- 优化 Web Vitals(LCP、CLS、FID)。
|
||||
|
||||
|
||||
Vue 3 和 Composition API 最佳实践
|
||||
- 使用 <script setup lang="ts"> 语法进行简洁的组件定义。
|
||||
- 利用 ref、reactive 和 computed 进行反应状态管理。
|
||||
- 在适当的情况下使用 provide/inject 进行依赖注入。
|
||||
- 实现自定义可组合项以实现可重用逻辑。
|
||||
|
||||
|
||||
Electron 最佳实践
|
||||
- 使用 Electron 和 Vue.js 进行跨平台桌面应用程序开发。
|
||||
- 使用 Electron 的 API 和 Vue.js 的组合 API 进行开发。
|
||||
- 实现自定义可组合项以实现可重用逻辑。
|
||||
|
||||
|
||||
|
||||
组件导入
|
||||
- 使用 auto-import 进行组件导入。
|
||||
- naive-ui 组件自动导入 不需要手动导入。
|
||||
|
||||
关注官方 Electron 和 Vue.js 文档,了解有关数据获取、渲染和路由的最新最佳实践。
|
||||
|
||||
|
||||
|
||||
问题修复
|
||||
- 思考 5-7 种可能导致问题的来源,并根据可能性、对功能的影响以及在类似问题中的出现频率进行优先排序。仅考虑与错误日志、最近代码变更和系统约束相匹配的来源。忽略外部依赖,除非日志明确指向它们。
|
||||
- 一旦缩小到 1-2 个最可能的来源,将其与历史错误日志、相关系统状态和预期行为进行交叉验证。如果发现不一致,调整你的假设。
|
||||
- 在添加日志时,确保它们被策略性地放置,以便同时确认或排除多个潜在原因。如果日志不支持你的假设,请先提出替代的调试策略,再继续深入分析。
|
||||
- 在实施修复之前,先总结问题现象、经过验证的假设,以及预期的日志输出,以确认问题是否真正得到解决。
|
||||
@@ -27,7 +27,7 @@
|
||||
"electron-store": "^8.1.0",
|
||||
"electron-updater": "^6.1.7",
|
||||
"font-list": "^1.5.1",
|
||||
"netease-cloud-music-api-alger": "^4.25.0",
|
||||
"netease-cloud-music-api-alger": "^4.26.1",
|
||||
"vue-i18n": "9"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -106,7 +106,6 @@ if (!isSingleInstance) {
|
||||
|
||||
// 监听语言切换
|
||||
ipcMain.on('change-language', (_, locale: Language) => {
|
||||
console.log('locale',locale)
|
||||
// 更新主进程的语言设置
|
||||
i18n.global.locale = locale;
|
||||
// 更新托盘菜单
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { is } from '@electron-toolkit/utils';
|
||||
import { app, BrowserWindow, ipcMain, session, shell } from 'electron';
|
||||
import { app, BrowserWindow, globalShortcut, ipcMain, session, shell } from 'electron';
|
||||
import Store from 'electron-store';
|
||||
import { join } from 'path';
|
||||
|
||||
@@ -112,6 +112,11 @@ export function createMainWindow(icon: Electron.NativeImage): BrowserWindow {
|
||||
if (is.dev && process.env.ELECTRON_RENDERER_URL) {
|
||||
mainWindow.webContents.openDevTools({ mode: 'detach' });
|
||||
mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL);
|
||||
|
||||
// 注册快捷键 打开开发者工具
|
||||
globalShortcut.register('CommandOrControl+Shift+I', () => {
|
||||
mainWindow.webContents.openDevTools({ mode: 'detach' });
|
||||
});
|
||||
} else {
|
||||
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
|
||||
}
|
||||
|
||||
150
src/renderer/api/bilibili.ts
Normal file
150
src/renderer/api/bilibili.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import type { IBilibiliPlayUrl, IBilibiliVideoDetail } from '@/types/bilibili';
|
||||
import request from '@/utils/request';
|
||||
|
||||
interface ISearchParams {
|
||||
keyword: string;
|
||||
page?: number;
|
||||
pagesize?: number;
|
||||
search_type?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索B站视频
|
||||
* @param params 搜索参数
|
||||
*/
|
||||
export const searchBilibili = (params: ISearchParams) => {
|
||||
console.log('调用B站搜索API,参数:', params);
|
||||
return request.get('/bilibili/search', {
|
||||
params
|
||||
});
|
||||
};
|
||||
|
||||
interface IBilibiliResponse<T> {
|
||||
code: number;
|
||||
message: string;
|
||||
ttl: number;
|
||||
data: T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取B站视频详情
|
||||
* @param bvid B站视频BV号
|
||||
* @returns 视频详情响应
|
||||
*/
|
||||
export const getBilibiliVideoDetail = (
|
||||
bvid: string
|
||||
): Promise<IBilibiliResponse<IBilibiliVideoDetail>> => {
|
||||
console.log('调用B站视频详情API,bvid:', bvid);
|
||||
return new Promise((resolve, reject) => {
|
||||
request
|
||||
.get('/bilibili/video/detail', {
|
||||
params: { bvid }
|
||||
})
|
||||
.then((response) => {
|
||||
console.log('B站视频详情API响应:', response.status);
|
||||
|
||||
// 检查响应状态和数据格式
|
||||
if (response.status === 200 && response.data && response.data.data) {
|
||||
console.log('B站视频详情API成功,标题:', response.data.data.title);
|
||||
resolve(response.data);
|
||||
} else {
|
||||
console.error('B站视频详情API响应格式不正确:', response.data);
|
||||
reject(new Error('获取视频详情响应格式不正确'));
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('B站视频详情API错误:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取B站视频播放地址
|
||||
* @param bvid B站视频BV号
|
||||
* @param cid 视频分P的id
|
||||
* @param qn 视频质量,默认为0
|
||||
* @param fnval 视频格式标志,默认为80
|
||||
* @param fnver 视频格式版本,默认为0
|
||||
* @param fourk 是否允许4K视频,默认为1
|
||||
* @returns 视频播放地址响应
|
||||
*/
|
||||
export const getBilibiliPlayUrl = (
|
||||
bvid: string,
|
||||
cid: number,
|
||||
qn: number = 0,
|
||||
fnval: number = 80,
|
||||
fnver: number = 0,
|
||||
fourk: number = 1
|
||||
): Promise<IBilibiliResponse<IBilibiliPlayUrl>> => {
|
||||
console.log('调用B站视频播放地址API,bvid:', bvid, 'cid:', cid);
|
||||
return new Promise((resolve, reject) => {
|
||||
request
|
||||
.get('/bilibili/playurl', {
|
||||
params: {
|
||||
bvid,
|
||||
cid,
|
||||
qn,
|
||||
fnval,
|
||||
fnver,
|
||||
fourk
|
||||
}
|
||||
})
|
||||
.then((response) => {
|
||||
console.log('B站视频播放地址API响应:', response.status);
|
||||
|
||||
// 检查响应状态和数据格式
|
||||
if (response.status === 200 && response.data && response.data.data) {
|
||||
if (response.data.data.dash?.audio?.length > 0) {
|
||||
console.log(
|
||||
'B站视频播放地址API成功,获取到',
|
||||
response.data.data.dash.audio.length,
|
||||
'个音频地址'
|
||||
);
|
||||
} else if (response.data.data.durl?.length > 0) {
|
||||
console.log(
|
||||
'B站视频播放地址API成功,获取到',
|
||||
response.data.data.durl.length,
|
||||
'个播放地址'
|
||||
);
|
||||
}
|
||||
resolve(response.data);
|
||||
} else {
|
||||
console.error('B站视频播放地址API响应格式不正确:', response.data);
|
||||
reject(new Error('获取视频播放地址响应格式不正确'));
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('B站视频播放地址API错误:', error);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// `http://127.0.0.1:30666/bilibili/stream-proxy?url=${encodeURIComponent(`https:${item.pic}`)}`,
|
||||
export const getBilibiliProxyUrl = (url: string) => {
|
||||
const AUrl = url.startsWith('http') ? url : `https:${url}`;
|
||||
return `${import.meta.env.VITE_API}/bilibili/stream-proxy?url=${encodeURIComponent(AUrl)}`;
|
||||
};
|
||||
|
||||
export const getBilibiliAudioUrl = async (bvid: string, cid: number): Promise<string> => {
|
||||
console.log('获取B站音频URL', { bvid, cid });
|
||||
try {
|
||||
const res = await getBilibiliPlayUrl(bvid, cid);
|
||||
const playUrlData = res.data;
|
||||
let url = '';
|
||||
|
||||
if (playUrlData.dash && playUrlData.dash.audio && playUrlData.dash.audio.length > 0) {
|
||||
url = playUrlData.dash.audio[0].baseUrl;
|
||||
} else if (playUrlData.durl && playUrlData.durl.length > 0) {
|
||||
url = playUrlData.durl[0].url;
|
||||
} else {
|
||||
throw new Error('未找到可用的音频地址');
|
||||
}
|
||||
|
||||
return getBilibiliProxyUrl(url);
|
||||
} catch (error) {
|
||||
console.error('获取B站音频URL失败:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
117
src/renderer/components/common/BilibiliItem.vue
Normal file
117
src/renderer/components/common/BilibiliItem.vue
Normal file
@@ -0,0 +1,117 @@
|
||||
<template>
|
||||
<div class="bilibili-item" @click="handleClick">
|
||||
<div class="bilibili-item-img">
|
||||
<n-image class="w-full h-full" :src="item.pic" lazy preview-disabled />
|
||||
<div class="play">
|
||||
<i class="ri-play-fill text-4xl"></i>
|
||||
</div>
|
||||
<div class="duration">{{ formatDuration(item.duration) }}</div>
|
||||
</div>
|
||||
<div class="bilibili-item-info">
|
||||
<p class="bilibili-item-title" v-html="item.title"></p>
|
||||
<p class="bilibili-item-author"><i class="ri-user-line mr-1"></i>{{ item.author }}</p>
|
||||
<div class="bilibili-item-stats">
|
||||
<span><i class="ri-play-line mr-1"></i>{{ formatNumber(item.view) }}</span>
|
||||
<span><i class="ri-chat-1-line mr-1"></i>{{ formatNumber(item.danmaku) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { IBilibiliSearchResult } from '@/types/bilibili';
|
||||
|
||||
const props = defineProps<{
|
||||
item: IBilibiliSearchResult;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'play', item: IBilibiliSearchResult): void;
|
||||
}>();
|
||||
|
||||
const handleClick = () => {
|
||||
emit('play', props.item);
|
||||
};
|
||||
|
||||
/**
|
||||
* 格式化数字显示
|
||||
*/
|
||||
const formatNumber = (num?: number) => {
|
||||
if (!num) return '0';
|
||||
if (num >= 10000) {
|
||||
return `${(num / 10000).toFixed(1)}万`;
|
||||
}
|
||||
return num.toString();
|
||||
};
|
||||
|
||||
/**
|
||||
* 格式化视频时长
|
||||
*/
|
||||
const formatDuration = (duration?: number | string) => {
|
||||
if (!duration) return '00:00:00';
|
||||
|
||||
// 处理字符串格式 (例如 "4352:29")
|
||||
if (typeof duration === 'string') {
|
||||
// 检查是否是合法的格式
|
||||
if (/^\d+:\d+$/.test(duration)) {
|
||||
// 分解分钟和秒数
|
||||
const [minutes, seconds] = duration.split(':').map(Number);
|
||||
|
||||
// 转换为时:分:秒格式
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remainingMinutes = minutes % 60;
|
||||
|
||||
return `${hours.toString().padStart(2, '0')}:${remainingMinutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
return '00:00:00';
|
||||
}
|
||||
|
||||
// 数字处理逻辑 (秒数转为"时:分:秒"格式)
|
||||
const hours = Math.floor(duration / 3600);
|
||||
const minutes = Math.floor((duration % 3600) / 60);
|
||||
const seconds = duration % 60;
|
||||
|
||||
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.bilibili-item {
|
||||
@apply rounded-lg flex items-start hover:bg-light-200 dark:hover:bg-dark-200 p-3 transition cursor-pointer border-none;
|
||||
|
||||
&-img {
|
||||
@apply w-40 rounded-lg overflow-hidden relative mr-4;
|
||||
aspect-ratio: 16/9;
|
||||
|
||||
&:hover {
|
||||
.play {
|
||||
@apply opacity-80;
|
||||
}
|
||||
}
|
||||
|
||||
.play {
|
||||
@apply absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 opacity-0 transition-opacity text-white;
|
||||
}
|
||||
|
||||
.duration {
|
||||
@apply absolute bottom-1 right-1 text-xs text-white px-1 py-0.5 rounded-sm bg-black/60 backdrop-blur-sm;
|
||||
}
|
||||
}
|
||||
|
||||
&-info {
|
||||
@apply flex-1 overflow-hidden;
|
||||
}
|
||||
|
||||
&-title {
|
||||
@apply text-gray-800 dark:text-gray-200 text-sm font-medium mb-1 line-clamp-2 leading-tight;
|
||||
}
|
||||
|
||||
&-author {
|
||||
@apply text-gray-500 dark:text-gray-400 text-xs flex items-center mb-1;
|
||||
}
|
||||
|
||||
&-stats {
|
||||
@apply flex items-center text-xs text-gray-500 dark:text-gray-400 gap-3;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -140,7 +140,7 @@ const dropdownY = ref(0);
|
||||
|
||||
const isDownloading = ref(false);
|
||||
|
||||
const openPlaylistDrawer = inject<(songId: number) => void>('openPlaylistDrawer');
|
||||
const openPlaylistDrawer = inject<(songId: number | string) => void>('openPlaylistDrawer');
|
||||
|
||||
const { navigateToArtist } = useArtist();
|
||||
|
||||
@@ -285,7 +285,7 @@ const downloadMusic = async () => {
|
||||
try {
|
||||
isDownloading.value = true;
|
||||
|
||||
const data = (await getSongUrl(props.item.id, cloneDeep(props.item), true)) as any;
|
||||
const data = (await getSongUrl(props.item.id as number, cloneDeep(props.item), true)) as any;
|
||||
if (!data || !data.url) {
|
||||
throw new Error(t('songItem.message.getUrlFailed'));
|
||||
}
|
||||
@@ -358,6 +358,7 @@ const imageLoad = async () => {
|
||||
|
||||
// 播放音乐 设置音乐详情 打开音乐底栏
|
||||
const playMusicEvent = async (item: SongResult) => {
|
||||
// 如果是当前正在播放的音乐,则切换播放/暂停状态
|
||||
if (playMusic.value.id === item.id) {
|
||||
if (play.value) {
|
||||
playerStore.setPlayMusic(false);
|
||||
@@ -368,23 +369,37 @@ const playMusicEvent = async (item: SongResult) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
await playerStore.setPlay(item);
|
||||
playerStore.isPlay = true;
|
||||
emits('play', item);
|
||||
|
||||
try {
|
||||
// 使用store的setPlay方法,该方法已经包含了B站视频URL处理逻辑
|
||||
const result = await playerStore.setPlay(item);
|
||||
if (!result) {
|
||||
throw new Error('播放失败');
|
||||
}
|
||||
playerStore.isPlay = true;
|
||||
emits('play', item);
|
||||
} catch (error) {
|
||||
console.error('播放出错:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 判断是否已收藏
|
||||
const isFavorite = computed(() => {
|
||||
return playerStore.favoriteList.includes(props.item.id);
|
||||
// 将id转换为number,兼容B站视频ID
|
||||
const numericId = typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
|
||||
return playerStore.favoriteList.includes(numericId);
|
||||
});
|
||||
|
||||
// 切换收藏状态
|
||||
const toggleFavorite = async (e: Event) => {
|
||||
e.stopPropagation();
|
||||
// 将id转换为number,兼容B站视频ID
|
||||
const numericId = typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
|
||||
|
||||
if (isFavorite.value) {
|
||||
playerStore.removeFromFavorite(props.item.id);
|
||||
playerStore.removeFromFavorite(numericId);
|
||||
} else {
|
||||
playerStore.addToFavorite(props.item.id);
|
||||
playerStore.addToFavorite(numericId);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -45,6 +45,10 @@ export const SEARCH_TYPES = [
|
||||
{
|
||||
label: 'MV',
|
||||
key: 1004
|
||||
},
|
||||
{
|
||||
label: 'B站',
|
||||
key: 2000
|
||||
}
|
||||
// {
|
||||
// label: '歌词',
|
||||
@@ -63,3 +67,12 @@ export const SEARCH_TYPES = [
|
||||
// key: 1018,
|
||||
// },
|
||||
];
|
||||
|
||||
export const SEARCH_TYPE = {
|
||||
MUSIC: 1, // 单曲
|
||||
ALBUM: 10, // 专辑
|
||||
ARTIST: 100, // 歌手
|
||||
PLAYLIST: 1000, // 歌单
|
||||
MV: 1004, // MV
|
||||
BILIBILI: 2000 // B站视频
|
||||
} as const;
|
||||
|
||||
@@ -2,6 +2,7 @@ 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';
|
||||
import pinia, { usePlayerStore } from '@/store';
|
||||
@@ -235,6 +236,29 @@ watch(
|
||||
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;
|
||||
@@ -842,3 +866,97 @@ export const initAudioListeners = async () => {
|
||||
console.error('初始化音频监听器失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 监听URL过期事件,自动重新获取URL并恢复播放
|
||||
audioService.on('url_expired', async (expiredTrack) => {
|
||||
if (!expiredTrack) return;
|
||||
|
||||
console.log('检测到URL过期事件,准备重新获取URL', expiredTrack.name);
|
||||
|
||||
try {
|
||||
const currentPosition = nowTime.value; // 保存当前播放进度
|
||||
console.log('保存当前播放进度:', currentPosition);
|
||||
|
||||
// 处理B站视频
|
||||
if (expiredTrack.source === 'bilibili' && expiredTrack.bilibiliData) {
|
||||
console.log('重新获取B站视频URL');
|
||||
try {
|
||||
// 使用API中的函数获取B站音频URL
|
||||
const newUrl = await getBilibiliAudioUrl(
|
||||
expiredTrack.bilibiliData.bvid,
|
||||
expiredTrack.bilibiliData.cid
|
||||
);
|
||||
|
||||
console.log('成功获取新的B站URL:', newUrl);
|
||||
|
||||
// 更新存储
|
||||
(expiredTrack as any).playMusicUrl = newUrl;
|
||||
playerStore.playMusicUrl = newUrl;
|
||||
|
||||
// 重新播放并设置进度
|
||||
const newSound = await audioService.play(newUrl, expiredTrack);
|
||||
sound.value = newSound as Howl;
|
||||
|
||||
// 恢复播放进度
|
||||
if (currentPosition > 0) {
|
||||
newSound.seek(currentPosition);
|
||||
nowTime.value = currentPosition;
|
||||
console.log('恢复播放进度:', currentPosition);
|
||||
}
|
||||
|
||||
// 如果之前是播放状态,继续播放
|
||||
if (playerStore.play) {
|
||||
newSound.play();
|
||||
playerStore.setIsPlay(true);
|
||||
}
|
||||
|
||||
message.success('已自动恢复播放');
|
||||
} catch (error) {
|
||||
console.error('重新获取B站URL失败:', error);
|
||||
message.error('重新获取音频地址失败,请手动点击播放');
|
||||
}
|
||||
} else if (expiredTrack.source === 'netease') {
|
||||
// 处理网易云音乐,重新获取URL
|
||||
console.log('重新获取网易云音乐URL');
|
||||
try {
|
||||
const { getSongUrl } = await import('@/store/modules/player');
|
||||
const newUrl = await getSongUrl(expiredTrack.id, expiredTrack as any);
|
||||
|
||||
if (newUrl) {
|
||||
console.log('成功获取新的网易云URL:', newUrl);
|
||||
|
||||
// 更新存储
|
||||
(expiredTrack as any).playMusicUrl = newUrl;
|
||||
playerStore.playMusicUrl = newUrl;
|
||||
|
||||
// 重新播放并设置进度
|
||||
const newSound = await audioService.play(newUrl, expiredTrack);
|
||||
sound.value = newSound as Howl;
|
||||
|
||||
// 恢复播放进度
|
||||
if (currentPosition > 0) {
|
||||
newSound.seek(currentPosition);
|
||||
nowTime.value = currentPosition;
|
||||
console.log('恢复播放进度:', currentPosition);
|
||||
}
|
||||
|
||||
// 如果之前是播放状态,继续播放
|
||||
if (playerStore.play) {
|
||||
newSound.play();
|
||||
playerStore.setIsPlay(true);
|
||||
}
|
||||
|
||||
message.success('已自动恢复播放');
|
||||
} else {
|
||||
throw new Error('获取URL失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('重新获取网易云URL失败:', error);
|
||||
message.error('重新获取音频地址失败,请手动点击播放');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('处理URL过期事件失败:', error);
|
||||
message.error('恢复播放失败,请手动点击播放');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ import { getImageLinearBackground } from '@/utils/linearColor';
|
||||
const musicHistory = useMusicHistory();
|
||||
|
||||
// 获取歌曲url
|
||||
export const getSongUrl = async (id: number, songData: any, isDownloaded: boolean = false) => {
|
||||
export const getSongUrl = async (id: any, songData: any, isDownloaded: boolean = false) => {
|
||||
const { data } = await getMusicUrl(id, isDownloaded);
|
||||
let url = '';
|
||||
let songDetail = null;
|
||||
@@ -247,7 +247,7 @@ export const useMusicListHook = () => {
|
||||
};
|
||||
|
||||
// 异步加载歌词的方法
|
||||
const loadLrcAsync = async (state: any, playMusicId: number) => {
|
||||
const loadLrcAsync = async (state: any, playMusicId: any) => {
|
||||
if (state.playMusic.lyric && state.playMusic.lyric.lrcTimeArray.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
}
|
||||
|
||||
.n-slider-handle-indicator--top {
|
||||
@apply bg-transparent text-2xl px-2 py-1 shadow-none mb-0 dark:text-[#ffffffdd] text-[#000000dd] !important;
|
||||
@apply bg-transparent text-2xl px-2 py-1 shadow-none mb-0 text-white bg-dark-300 dark:bg-gray-800 bg-opacity-80 rounded-lg !important;
|
||||
mix-blend-mode: difference !important;
|
||||
}
|
||||
|
||||
|
||||
@@ -217,15 +217,15 @@ const scrollToPlayList = (val: boolean) => {
|
||||
|
||||
// 收藏功能
|
||||
const isFavorite = computed(() => {
|
||||
return playerStore.favoriteList.includes(playMusic.value.id);
|
||||
return playerStore.favoriteList.includes(playMusic.value.id as number);
|
||||
});
|
||||
|
||||
const toggleFavorite = () => {
|
||||
console.log('isFavorite.value', isFavorite.value);
|
||||
if (isFavorite.value) {
|
||||
playerStore.removeFromFavorite(playMusic.value.id);
|
||||
playerStore.removeFromFavorite(playMusic.value.id as number);
|
||||
} else {
|
||||
playerStore.addToFavorite(playMusic.value.id);
|
||||
playerStore.addToFavorite(playMusic.value.id as number);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@
|
||||
</div>
|
||||
|
||||
<!-- 无歌词 -->
|
||||
<div v-if="!lrcArray.length" class="music-lrc-text mt-40">
|
||||
<div v-if="!lrcArray.length" class="music-lrc-text">
|
||||
<span>{{ t('player.lrc.noLrc') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -25,6 +25,9 @@
|
||||
:max="allTime"
|
||||
:min="0"
|
||||
:format-tooltip="formatTooltip"
|
||||
:show-tooltip="showSliderTooltip"
|
||||
@mouseenter="showSliderTooltip = true"
|
||||
@mouseleave="showSliderTooltip = false"
|
||||
></n-slider>
|
||||
</div>
|
||||
<div class="play-bar-img-wrapper" @click="setMusicFull">
|
||||
@@ -183,6 +186,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useThrottleFn } from '@vueuse/core';
|
||||
import { useMessage } from 'naive-ui';
|
||||
import { computed, ref, useTemplateRef, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
@@ -211,6 +215,7 @@ import MusicFull from './MusicFull.vue';
|
||||
const playerStore = usePlayerStore();
|
||||
const settingsStore = useSettingsStore();
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
// 是否播放
|
||||
const play = computed(() => playerStore.isPlay);
|
||||
// 播放列表
|
||||
@@ -318,37 +323,48 @@ function handlePrev() {
|
||||
}
|
||||
|
||||
const MusicFullRef = ref<any>(null);
|
||||
const showSliderTooltip = ref(false);
|
||||
|
||||
// 播放暂停按钮事件
|
||||
const playMusicEvent = async () => {
|
||||
try {
|
||||
// 检查是否有有效的音乐对象和 URL
|
||||
if (!playMusic.value?.id || !playerStore.playMusicUrl) {
|
||||
console.warn('No valid music or URL available');
|
||||
playerStore.setPlay(playMusic.value);
|
||||
// 检查是否有有效的音乐对象
|
||||
if (!playMusic.value?.id) {
|
||||
console.warn('没有有效的播放对象');
|
||||
return;
|
||||
}
|
||||
|
||||
// 当前处于播放状态 -> 暂停
|
||||
if (play.value) {
|
||||
// 暂停播放
|
||||
if (audioService.getCurrentSound()) {
|
||||
audioService.pause();
|
||||
playerStore.setPlayMusic(false);
|
||||
}
|
||||
} else {
|
||||
// 开始播放
|
||||
if (audioService.getCurrentSound()) {
|
||||
// 如果已经有音频实例,直接播放
|
||||
audioService.play();
|
||||
} else {
|
||||
// 如果没有音频实例,重新创建并播放
|
||||
await audioService.play(playerStore.playMusicUrl, playMusic.value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 当前处于暂停状态 -> 播放
|
||||
// 有音频实例,直接播放
|
||||
if (audioService.getCurrentSound()) {
|
||||
audioService.play();
|
||||
playerStore.setPlayMusic(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// 没有音频实例,重新获取并播放(包括重新获取B站视频URL)
|
||||
try {
|
||||
// 复用当前播放对象,但强制重新获取URL
|
||||
const result = await playerStore.setPlay({ ...playMusic.value, playMusicUrl: undefined });
|
||||
if (result) {
|
||||
playerStore.setPlayMusic(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('重新获取播放链接失败:', error);
|
||||
message.error(t('player.playFailed'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('播放出错:', error);
|
||||
playerStore.nextPlay();
|
||||
message.error(t('player.playFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -373,15 +389,22 @@ const scrollToPlayList = (val: boolean) => {
|
||||
};
|
||||
|
||||
const isFavorite = computed(() => {
|
||||
return playerStore.favoriteList.includes(playMusic.value.id);
|
||||
// 将id转换为number,兼容B站视频ID
|
||||
const numericId =
|
||||
typeof playMusic.value.id === 'string' ? parseInt(playMusic.value.id, 10) : playMusic.value.id;
|
||||
return playerStore.favoriteList.includes(numericId);
|
||||
});
|
||||
|
||||
const toggleFavorite = async (e: Event) => {
|
||||
e.stopPropagation();
|
||||
// 将id转换为number,兼容B站视频ID
|
||||
const numericId =
|
||||
typeof playMusic.value.id === 'string' ? parseInt(playMusic.value.id, 10) : playMusic.value.id;
|
||||
|
||||
if (isFavorite.value) {
|
||||
playerStore.removeFromFavorite(playMusic.value.id);
|
||||
playerStore.removeFromFavorite(numericId);
|
||||
} else {
|
||||
playerStore.addToFavorite(playMusic.value.id);
|
||||
playerStore.addToFavorite(numericId);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -654,8 +677,16 @@ const handleDeleteSong = (song: SongResult) => {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
&:hover .n-slider-handle {
|
||||
opacity: 1;
|
||||
&:hover {
|
||||
.n-slider-handle {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 确保悬停时提示样式正确
|
||||
.n-slider-tooltip {
|
||||
@apply bg-gray-800 text-white text-xs py-1 px-2 rounded;
|
||||
z-index: 999999;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, onMounted, ref, watchEffect } from 'vue';
|
||||
import { computed, onMounted, ref, watch, watchEffect } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
@@ -191,6 +191,18 @@ const isDark = computed({
|
||||
|
||||
// 搜索词
|
||||
const searchValue = ref('');
|
||||
|
||||
// 使用 watch 代替 watchEffect 监听搜索值变化,确保深度监听
|
||||
watch(
|
||||
() => searchStore.searchValue,
|
||||
(newValue) => {
|
||||
if (newValue) {
|
||||
searchValue.value = newValue;
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
const search = () => {
|
||||
const { value } = searchValue;
|
||||
if (value === '') {
|
||||
@@ -215,7 +227,17 @@ const search = () => {
|
||||
const selectSearchType = (key: number) => {
|
||||
searchStore.searchType = key;
|
||||
if (searchValue.value) {
|
||||
search();
|
||||
if (router.currentRoute.value.path === '/search') {
|
||||
search();
|
||||
} else {
|
||||
router.push({
|
||||
path: '/search',
|
||||
query: {
|
||||
keyword: searchValue.value,
|
||||
type: key
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -42,6 +42,17 @@ const otherRouter = [
|
||||
back: true
|
||||
},
|
||||
component: () => import('@/views/artist/detail.vue')
|
||||
},
|
||||
{
|
||||
path: '/bilibili/:bvid',
|
||||
name: 'bilibiliPlayer',
|
||||
meta: {
|
||||
title: 'B站听书',
|
||||
keepAlive: true,
|
||||
showInMenu: false,
|
||||
back: true
|
||||
},
|
||||
component: () => import('@/views/bilibili/BilibiliPlayer.vue')
|
||||
}
|
||||
];
|
||||
export default otherRouter;
|
||||
|
||||
@@ -422,6 +422,8 @@ class AudioService {
|
||||
console.log(`Retrying playback (${retryCount}/${maxRetries})...`);
|
||||
setTimeout(tryPlay, 1000 * retryCount);
|
||||
} else {
|
||||
// 发送URL过期事件,通知外部需要重新获取URL
|
||||
this.emit('url_expired', this.currentTrack);
|
||||
reject(new Error('音频加载失败,请尝试切换其他歌曲'));
|
||||
}
|
||||
},
|
||||
@@ -432,6 +434,8 @@ class AudioService {
|
||||
console.log(`Retrying playback (${retryCount}/${maxRetries})...`);
|
||||
setTimeout(tryPlay, 1000 * retryCount);
|
||||
} else {
|
||||
// 发送URL过期事件,通知外部需要重新获取URL
|
||||
this.emit('url_expired', this.currentTrack);
|
||||
reject(new Error('音频播放失败,请尝试切换其他歌曲'));
|
||||
}
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ import { cloneDeep } from 'lodash';
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { getBilibiliAudioUrl } from '@/api/bilibili';
|
||||
import { getLikedList, getMusicLrc, getMusicUrl, getParsingMusicUrl } from '@/api/music';
|
||||
import { useMusicHistory } from '@/hooks/MusicHistoryHook';
|
||||
import type { ILyric, ILyricText, SongResult } from '@/type/music';
|
||||
@@ -24,13 +25,41 @@ function getLocalStorageItem<T>(key: string, defaultValue: T): T {
|
||||
}
|
||||
}
|
||||
|
||||
export const getSongUrl = async (id: number, songData: any, isDownloaded: boolean = false) => {
|
||||
const { data } = await getMusicUrl(id, isDownloaded);
|
||||
// 提取公共函数:获取B站视频URL
|
||||
|
||||
export const getSongUrl = async (
|
||||
id: string | number,
|
||||
songData: SongResult,
|
||||
isDownloaded: boolean = false
|
||||
) => {
|
||||
if (songData.playMusicUrl) {
|
||||
return songData.playMusicUrl;
|
||||
}
|
||||
|
||||
if (songData.source === 'bilibili' && songData.bilibiliData) {
|
||||
console.log('加载B站音频URL');
|
||||
if (!songData.playMusicUrl && songData.bilibiliData.bvid && songData.bilibiliData.cid) {
|
||||
try {
|
||||
songData.playMusicUrl = await getBilibiliAudioUrl(
|
||||
songData.bilibiliData.bvid,
|
||||
songData.bilibiliData.cid
|
||||
);
|
||||
return songData.playMusicUrl;
|
||||
} catch (error) {
|
||||
console.error('重启后获取B站音频URL失败:', error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
return songData.playMusicUrl || '';
|
||||
}
|
||||
|
||||
const numericId = typeof id === 'string' ? parseInt(id, 10) : id;
|
||||
const { data } = await getMusicUrl(numericId, isDownloaded);
|
||||
let url = '';
|
||||
let songDetail = null;
|
||||
try {
|
||||
if (data.data[0].freeTrialInfo || !data.data[0].url) {
|
||||
const res = await getParsingMusicUrl(id, songData);
|
||||
const res = await getParsingMusicUrl(numericId, cloneDeep(songData));
|
||||
url = res.data.data.url;
|
||||
songDetail = res.data.data;
|
||||
} else {
|
||||
@@ -45,6 +74,7 @@ export const getSongUrl = async (id: number, songData: any, isDownloaded: boolea
|
||||
url = url || data.data[0].url;
|
||||
return url;
|
||||
};
|
||||
|
||||
const parseTime = (timeString: string): number => {
|
||||
const [minutes, seconds] = timeString.split(':');
|
||||
return Number(minutes) * 60 + Number(seconds);
|
||||
@@ -71,9 +101,18 @@ const parseLyrics = (lyricsString: string): { lyrics: ILyricText[]; times: numbe
|
||||
return { lyrics, times };
|
||||
};
|
||||
|
||||
export const loadLrc = async (playMusicId: number): Promise<ILyric> => {
|
||||
export const loadLrc = async (id: string | number): Promise<ILyric> => {
|
||||
if (typeof id === 'string' && id.includes('--')) {
|
||||
console.log('B站音频,无需加载歌词');
|
||||
return {
|
||||
lrcTimeArray: [],
|
||||
lrcArray: []
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const { data } = await getMusicLrc(playMusicId);
|
||||
const numericId = typeof id === 'string' ? parseInt(id, 10) : id;
|
||||
const { data } = await getMusicLrc(numericId);
|
||||
const { lyrics, times } = parseLyrics(data.lrc.lyric);
|
||||
const tlyric: Record<string, string> = {};
|
||||
|
||||
@@ -102,8 +141,19 @@ export const loadLrc = async (playMusicId: number): Promise<ILyric> => {
|
||||
|
||||
const getSongDetail = async (playMusic: SongResult) => {
|
||||
playMusic.playLoading = true;
|
||||
const playMusicUrl =
|
||||
playMusic.playMusicUrl || (await getSongUrl(playMusic.id, cloneDeep(playMusic)));
|
||||
|
||||
if (playMusic.source === 'bilibili') {
|
||||
console.log('处理B站音频详情');
|
||||
const { backgroundColor, primaryColor } =
|
||||
playMusic.backgroundColor && playMusic.primaryColor
|
||||
? playMusic
|
||||
: await getImageLinearBackground(getImgUrl(playMusic?.picUrl, '30y30'));
|
||||
|
||||
playMusic.playLoading = false;
|
||||
return { ...playMusic, backgroundColor, primaryColor } as SongResult;
|
||||
}
|
||||
|
||||
const playMusicUrl = playMusic.playMusicUrl || (await getSongUrl(playMusic.id, playMusic));
|
||||
const { backgroundColor, primaryColor } =
|
||||
playMusic.backgroundColor && playMusic.primaryColor
|
||||
? playMusic
|
||||
@@ -115,7 +165,6 @@ const getSongDetail = async (playMusic: SongResult) => {
|
||||
|
||||
const preloadNextSong = (nextSongUrl: string) => {
|
||||
try {
|
||||
// 限制同时预加载的数量
|
||||
if (preloadingSounds.value.length >= 2) {
|
||||
const oldestSound = preloadingSounds.value.shift();
|
||||
if (oldestSound) {
|
||||
@@ -132,7 +181,6 @@ const preloadNextSong = (nextSongUrl: string) => {
|
||||
|
||||
preloadingSounds.value.push(sound);
|
||||
|
||||
// 添加加载错误处理
|
||||
sound.on('loaderror', () => {
|
||||
console.error('预加载音频失败:', nextSongUrl);
|
||||
const index = preloadingSounds.value.indexOf(sound);
|
||||
@@ -156,8 +204,7 @@ const fetchSongs = async (playList: SongResult[], startIndex: number, endIndex:
|
||||
const detailedSongs = await Promise.all(
|
||||
songs.map(async (song: SongResult) => {
|
||||
try {
|
||||
// 如果歌曲详情已经存在,就不重复请求
|
||||
if (!song.playMusicUrl) {
|
||||
if (!song.playMusicUrl || (song.source === 'netease' && !song.backgroundColor)) {
|
||||
return await getSongDetail(song);
|
||||
}
|
||||
return song;
|
||||
@@ -168,7 +215,6 @@ const fetchSongs = async (playList: SongResult[], startIndex: number, endIndex:
|
||||
})
|
||||
);
|
||||
|
||||
// 加载下一首的歌词
|
||||
const nextSong = detailedSongs[0];
|
||||
if (nextSong && !(nextSong.lyric && nextSong.lyric.lrcTimeArray.length > 0)) {
|
||||
try {
|
||||
@@ -178,14 +224,12 @@ const fetchSongs = async (playList: SongResult[], startIndex: number, endIndex:
|
||||
}
|
||||
}
|
||||
|
||||
// 更新播放列表中的歌曲详情
|
||||
detailedSongs.forEach((song, index) => {
|
||||
if (song && startIndex + index < playList.length) {
|
||||
playList[startIndex + index] = song;
|
||||
}
|
||||
});
|
||||
|
||||
// 只预加载下一首歌曲
|
||||
if (nextSong && nextSong.playMusicUrl) {
|
||||
preloadNextSong(nextSong.playMusicUrl);
|
||||
}
|
||||
@@ -194,7 +238,6 @@ const fetchSongs = async (playList: SongResult[], startIndex: number, endIndex:
|
||||
}
|
||||
};
|
||||
|
||||
// 异步加载歌词的方法
|
||||
const loadLrcAsync = async (playMusic: SongResult) => {
|
||||
if (playMusic.lyric && playMusic.lyric.lrcTimeArray.length > 0) {
|
||||
return;
|
||||
@@ -204,7 +247,6 @@ const loadLrcAsync = async (playMusic: SongResult) => {
|
||||
};
|
||||
|
||||
export const usePlayerStore = defineStore('player', () => {
|
||||
// 状态
|
||||
const play = ref(false);
|
||||
const isPlay = ref(false);
|
||||
const playMusic = ref<SongResult>(getLocalStorageItem('currentPlayMusic', {} as SongResult));
|
||||
@@ -216,39 +258,77 @@ export const usePlayerStore = defineStore('player', () => {
|
||||
const favoriteList = ref<number[]>(getLocalStorageItem('favoriteList', []));
|
||||
const savedPlayProgress = ref<number | undefined>();
|
||||
|
||||
// 计算属性
|
||||
const currentSong = computed(() => playMusic.value);
|
||||
const isPlaying = computed(() => isPlay.value);
|
||||
const currentPlayList = computed(() => playList.value);
|
||||
const currentPlayListIndex = computed(() => playListIndex.value);
|
||||
|
||||
const handlePlayMusic = async (music: SongResult, isPlay: boolean = true) => {
|
||||
// 处理B站视频,确保URL有效
|
||||
if (music.source === 'bilibili' && music.bilibiliData) {
|
||||
try {
|
||||
console.log('处理B站视频,检查URL有效性');
|
||||
// 清除之前的URL,强制重新获取
|
||||
music.playMusicUrl = undefined;
|
||||
|
||||
// 重新获取B站视频URL
|
||||
if (music.bilibiliData.bvid && music.bilibiliData.cid) {
|
||||
music.playMusicUrl = await getBilibiliAudioUrl(
|
||||
music.bilibiliData.bvid,
|
||||
music.bilibiliData.cid
|
||||
);
|
||||
console.log('获取B站URL成功:', music.playMusicUrl);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取B站音频URL失败:', error);
|
||||
throw error; // 向上抛出错误,让调用者处理
|
||||
}
|
||||
}
|
||||
|
||||
const updatedPlayMusic = await getSongDetail(music);
|
||||
playMusic.value = updatedPlayMusic;
|
||||
playMusicUrl.value = updatedPlayMusic.playMusicUrl as string;
|
||||
|
||||
// 记录当前设置的播放状态
|
||||
play.value = isPlay;
|
||||
|
||||
// 每次设置新歌曲时,立即更新 localStorage
|
||||
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
|
||||
localStorage.setItem('currentPlayMusicUrl', playMusicUrl.value);
|
||||
localStorage.setItem('isPlaying', play.value.toString());
|
||||
|
||||
// 设置网页标题
|
||||
document.title = `${updatedPlayMusic.name} - ${updatedPlayMusic?.song?.artists?.reduce((prev, curr) => `${prev}${curr.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}`;
|
||||
}
|
||||
|
||||
document.title = title;
|
||||
|
||||
loadLrcAsync(playMusic.value);
|
||||
|
||||
musicHistory.addMusic(playMusic.value);
|
||||
playListIndex.value = playList.value.findIndex((item: SongResult) => item.id === music.id);
|
||||
// 请求后续五首歌曲的详情
|
||||
|
||||
playListIndex.value = playList.value.findIndex(
|
||||
(item: SongResult) => item.id === music.id && item.source === music.source
|
||||
);
|
||||
|
||||
fetchSongs(playList.value, playListIndex.value + 1, playListIndex.value + 6);
|
||||
};
|
||||
|
||||
// 方法
|
||||
const setPlay = async (song: SongResult) => {
|
||||
await handlePlayMusic(song);
|
||||
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
|
||||
localStorage.setItem('currentPlayMusicUrl', playMusicUrl.value);
|
||||
try {
|
||||
await handlePlayMusic(song);
|
||||
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
|
||||
localStorage.setItem('currentPlayMusicUrl', playMusicUrl.value);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('设置播放失败:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const setIsPlay = (value: boolean) => {
|
||||
@@ -303,17 +383,26 @@ export const usePlayerStore = defineStore('player', () => {
|
||||
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;
|
||||
await handlePlayMusic(playList.value[playListIndex.value]);
|
||||
|
||||
// 获取下一首歌曲
|
||||
const nextSong = playList.value[playListIndex.value];
|
||||
|
||||
// 如果是B站视频,确保重新获取URL
|
||||
if (nextSong.source === 'bilibili' && nextSong.bilibiliData) {
|
||||
// 清除之前的URL,确保重新获取
|
||||
nextSong.playMusicUrl = undefined;
|
||||
console.log('下一首是B站视频,已清除URL强制重新获取');
|
||||
}
|
||||
|
||||
await handlePlayMusic(nextSong);
|
||||
};
|
||||
|
||||
const prevPlay = async () => {
|
||||
@@ -323,7 +412,18 @@ export const usePlayerStore = defineStore('player', () => {
|
||||
}
|
||||
const nowPlayListIndex =
|
||||
(playListIndex.value - 1 + playList.value.length) % playList.value.length;
|
||||
await handlePlayMusic(playList.value[nowPlayListIndex]);
|
||||
|
||||
// 获取上一首歌曲
|
||||
const prevSong = playList.value[nowPlayListIndex];
|
||||
|
||||
// 如果是B站视频,确保重新获取URL
|
||||
if (prevSong.source === 'bilibili' && prevSong.bilibiliData) {
|
||||
// 清除之前的URL,确保重新获取
|
||||
prevSong.playMusicUrl = undefined;
|
||||
console.log('上一首是B站视频,已清除URL强制重新获取');
|
||||
}
|
||||
|
||||
await handlePlayMusic(prevSong);
|
||||
await fetchSongs(playList.value, playListIndex.value - 5, nowPlayListIndex);
|
||||
};
|
||||
|
||||
@@ -372,8 +472,17 @@ export const usePlayerStore = defineStore('player', () => {
|
||||
|
||||
if (savedPlayMusic && Object.keys(savedPlayMusic).length > 0) {
|
||||
try {
|
||||
console.log('恢复上次播放的音乐:', savedPlayMusic.name);
|
||||
console.log('settingStore.setData', settingStore.setData);
|
||||
const isPlaying = settingStore.setData.autoPlay;
|
||||
|
||||
// 如果是B站视频,确保播放URL能够在重启后正确恢复
|
||||
if (savedPlayMusic.source === 'bilibili' && savedPlayMusic.bilibiliData) {
|
||||
console.log('恢复B站视频播放', savedPlayMusic.bilibiliData);
|
||||
// 清除之前可能存在的播放URL,确保重新获取
|
||||
savedPlayMusic.playMusicUrl = undefined;
|
||||
}
|
||||
|
||||
await handlePlayMusic({ ...savedPlayMusic, playMusicUrl: undefined }, isPlaying);
|
||||
|
||||
if (savedProgress) {
|
||||
@@ -405,16 +514,13 @@ export const usePlayerStore = defineStore('player', () => {
|
||||
|
||||
const initializeFavoriteList = async () => {
|
||||
const userStore = useUserStore();
|
||||
// 先获取本地收藏列表
|
||||
const localFavoriteList = localStorage.getItem('favoriteList');
|
||||
const localList: number[] = localFavoriteList ? JSON.parse(localFavoriteList) : [];
|
||||
|
||||
// 如果用户已登录,尝试获取服务器收藏列表并合并
|
||||
if (userStore.user && userStore.user.userId) {
|
||||
try {
|
||||
const res = await getLikedList(userStore.user.userId);
|
||||
if (res.data?.ids) {
|
||||
// 合并本地和服务器的收藏列表,去重
|
||||
const serverList = res.data.ids.reverse();
|
||||
const mergedList = Array.from(new Set([...localList, ...serverList]));
|
||||
favoriteList.value = mergedList;
|
||||
@@ -429,12 +535,10 @@ export const usePlayerStore = defineStore('player', () => {
|
||||
favoriteList.value = localList;
|
||||
}
|
||||
|
||||
// 更新本地存储
|
||||
localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value));
|
||||
};
|
||||
|
||||
return {
|
||||
// 状态
|
||||
play,
|
||||
isPlay,
|
||||
playMusic,
|
||||
@@ -446,13 +550,11 @@ export const usePlayerStore = defineStore('player', () => {
|
||||
savedPlayProgress,
|
||||
favoriteList,
|
||||
|
||||
// 计算属性
|
||||
currentSong,
|
||||
isPlaying,
|
||||
currentPlayList,
|
||||
currentPlayListIndex,
|
||||
|
||||
// 方法
|
||||
setPlay,
|
||||
setIsPlay,
|
||||
nextPlay,
|
||||
|
||||
@@ -13,23 +13,29 @@ export interface ILyric {
|
||||
}
|
||||
|
||||
export interface SongResult {
|
||||
id: number;
|
||||
type: number;
|
||||
id: string | number;
|
||||
name: string;
|
||||
copywriter?: any;
|
||||
picUrl: string;
|
||||
canDislike: boolean;
|
||||
trackNumberUpdateTime?: any;
|
||||
song: Song;
|
||||
alg: string;
|
||||
count?: number;
|
||||
playCount?: number;
|
||||
song?: any;
|
||||
copywriter?: string;
|
||||
type?: number;
|
||||
canDislike?: boolean;
|
||||
program?: any;
|
||||
alg?: string;
|
||||
ar: Artist[];
|
||||
al: Album;
|
||||
count: number;
|
||||
playMusicUrl?: string;
|
||||
playLoading?: boolean;
|
||||
ar?: Artist[];
|
||||
al?: Album;
|
||||
lyric?: ILyric;
|
||||
backgroundColor?: string;
|
||||
primaryColor?: string;
|
||||
playMusicUrl?: string;
|
||||
lyric?: ILyric;
|
||||
bilibiliData?: {
|
||||
bvid: string;
|
||||
cid: number;
|
||||
};
|
||||
source?: 'netease' | 'bilibili';
|
||||
}
|
||||
|
||||
export interface Song {
|
||||
@@ -214,3 +220,16 @@ interface FreeTrialPrivilege {
|
||||
resConsumable: boolean;
|
||||
userConsumable: boolean;
|
||||
}
|
||||
|
||||
export interface IArtists {
|
||||
id: number;
|
||||
name: string;
|
||||
picUrl: string | null;
|
||||
alias: string[];
|
||||
albumSize: number;
|
||||
picId: number;
|
||||
fansGroup: null;
|
||||
img1v1Url: string;
|
||||
img1v1: number;
|
||||
trans: null;
|
||||
}
|
||||
|
||||
114
src/renderer/types/bilibili.ts
Normal file
114
src/renderer/types/bilibili.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
export interface IBilibiliSearchResult {
|
||||
id: number;
|
||||
bvid: string;
|
||||
title: string;
|
||||
pic: string;
|
||||
duration: number | string;
|
||||
pubdate: number;
|
||||
ctime: number;
|
||||
author: string;
|
||||
view: number;
|
||||
danmaku: number;
|
||||
owner: {
|
||||
mid: number;
|
||||
name: string;
|
||||
face: string;
|
||||
};
|
||||
stat: {
|
||||
view: number;
|
||||
danmaku: number;
|
||||
reply: number;
|
||||
favorite: number;
|
||||
coin: number;
|
||||
share: number;
|
||||
like: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IBilibiliVideoDetail {
|
||||
aid: number;
|
||||
bvid: string;
|
||||
title: string;
|
||||
pic: string;
|
||||
desc: string;
|
||||
duration: number;
|
||||
pubdate: number;
|
||||
ctime: number;
|
||||
owner: {
|
||||
mid: number;
|
||||
name: string;
|
||||
face: string;
|
||||
};
|
||||
stat: {
|
||||
view: number;
|
||||
danmaku: number;
|
||||
reply: number;
|
||||
favorite: number;
|
||||
coin: number;
|
||||
share: number;
|
||||
like: number;
|
||||
};
|
||||
pages: IBilibiliPage[];
|
||||
}
|
||||
|
||||
export interface IBilibiliPage {
|
||||
cid: number;
|
||||
page: number;
|
||||
part: string;
|
||||
duration: number;
|
||||
dimension: {
|
||||
width: number;
|
||||
height: number;
|
||||
rotate: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IBilibiliPlayUrl {
|
||||
durl?: {
|
||||
order: number;
|
||||
length: number;
|
||||
size: number;
|
||||
ahead: string;
|
||||
vhead: string;
|
||||
url: string;
|
||||
backup_url: string[];
|
||||
}[];
|
||||
dash?: {
|
||||
duration: number;
|
||||
minBufferTime: number;
|
||||
min_buffer_time: number;
|
||||
video: IBilibiliDashItem[];
|
||||
audio: IBilibiliDashItem[];
|
||||
};
|
||||
support_formats: {
|
||||
quality: number;
|
||||
format: string;
|
||||
new_description: string;
|
||||
display_desc: string;
|
||||
}[];
|
||||
accept_quality: number[];
|
||||
accept_description: string[];
|
||||
quality: number;
|
||||
format: string;
|
||||
timelength: number;
|
||||
high_format: string;
|
||||
}
|
||||
|
||||
export interface IBilibiliDashItem {
|
||||
id: number;
|
||||
baseUrl: string;
|
||||
base_url: string;
|
||||
backupUrl: string[];
|
||||
backup_url: string[];
|
||||
bandwidth: number;
|
||||
mimeType: string;
|
||||
mime_type: string;
|
||||
codecs: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
frameRate?: string;
|
||||
frame_rate?: string;
|
||||
startWithSap?: number;
|
||||
start_with_sap?: number;
|
||||
codecid: number;
|
||||
}
|
||||
614
src/renderer/views/bilibili/BilibiliPlayer.vue
Normal file
614
src/renderer/views/bilibili/BilibiliPlayer.vue
Normal file
@@ -0,0 +1,614 @@
|
||||
<template>
|
||||
<div class="bilibili-player-page">
|
||||
<n-scrollbar class="content-scrollbar">
|
||||
<div class="content-wrapper">
|
||||
<div v-if="isLoading" class="loading-wrapper">
|
||||
<n-spin size="large" />
|
||||
<p>听书加载中...</p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="errorMessage" class="error-wrapper">
|
||||
<i class="ri-error-warning-line text-4xl text-red-500"></i>
|
||||
<p>{{ errorMessage }}</p>
|
||||
<n-button type="primary" @click="loadVideoSource">重试</n-button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="videoDetail" class="bilibili-info-wrapper" :class="mainContentAnimation">
|
||||
<div class="bilibili-cover">
|
||||
<n-image
|
||||
:src="getBilibiliProxyUrl(videoDetail.pic)"
|
||||
class="cover-image"
|
||||
preview-disabled
|
||||
/>
|
||||
<!-- 悬浮的播放按钮 -->
|
||||
<div class="play-overlay">
|
||||
<div class="play-icon-bg" @click="playCurrentAudio">
|
||||
<i class="ri-play-fill"></i>
|
||||
</div>
|
||||
<!-- 固定在右下角的大型播放按钮 -->
|
||||
<n-button
|
||||
type="primary"
|
||||
size="large"
|
||||
class="corner-play-button"
|
||||
:loading="partLoading"
|
||||
@click="playCurrentAudio"
|
||||
>
|
||||
<template #icon>
|
||||
<i class="ri-play-fill"></i>
|
||||
</template>
|
||||
立即播放
|
||||
</n-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="video-info">
|
||||
<div class="title">{{ videoDetail?.title || '加载中...' }}</div>
|
||||
|
||||
<div class="author">
|
||||
<i class="ri-user-line mr-1"></i>
|
||||
<span>{{ videoDetail.owner?.name }}</span>
|
||||
</div>
|
||||
<div class="stats">
|
||||
<span
|
||||
><i class="ri-play-line mr-1"></i>{{ formatNumber(videoDetail.stat?.view) }}</span
|
||||
>
|
||||
<span
|
||||
><i class="ri-chat-1-line mr-1"></i
|
||||
>{{ formatNumber(videoDetail.stat?.danmaku) }}</span
|
||||
>
|
||||
<span
|
||||
><i class="ri-thumb-up-line mr-1"></i
|
||||
>{{ formatNumber(videoDetail.stat?.like) }}</span
|
||||
>
|
||||
</div>
|
||||
<div class="description">
|
||||
<p>{{ videoDetail.desc }}</p>
|
||||
</div>
|
||||
<div class="duration">
|
||||
<p>总时长: {{ formatTotalDuration(videoDetail.duration) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="videoDetail?.pages && videoDetail.pages.length > 1"
|
||||
class="video-parts"
|
||||
:class="partsListAnimation"
|
||||
>
|
||||
<div class="parts-title">
|
||||
分P列表 (共{{ videoDetail.pages.length }}集)
|
||||
<n-spin v-if="partLoading" size="small" class="ml-2" />
|
||||
</div>
|
||||
<div class="parts-list">
|
||||
<n-button
|
||||
v-for="page in videoDetail.pages"
|
||||
:key="page.cid"
|
||||
:type="isCurrentPlayingPage(page) ? 'primary' : 'default'"
|
||||
:disabled="partLoading"
|
||||
size="small"
|
||||
class="part-item"
|
||||
@click="switchPage(page)"
|
||||
>
|
||||
{{ page.part }}
|
||||
</n-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部留白 -->
|
||||
<div class="pb-20"></div>
|
||||
</div>
|
||||
</n-scrollbar>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useMessage } from 'naive-ui';
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
|
||||
import { getBilibiliPlayUrl, getBilibiliProxyUrl, getBilibiliVideoDetail } from '@/api/bilibili';
|
||||
import { usePlayerStore } from '@/store/modules/player';
|
||||
import type { SongResult } from '@/type/music';
|
||||
import type { IBilibiliPage, IBilibiliVideoDetail } from '@/types/bilibili';
|
||||
import { setAnimationClass } from '@/utils';
|
||||
|
||||
defineOptions({
|
||||
name: 'BilibiliPlayer'
|
||||
});
|
||||
|
||||
// 使用路由获取参数
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const playerStore = usePlayerStore();
|
||||
|
||||
// 从路由参数获取bvid
|
||||
const bvid = computed(() => route.params.bvid as string);
|
||||
|
||||
const isLoading = ref(true); // 初始加载状态
|
||||
const partLoading = ref(false); // 分P加载状态,仅影响分P选择
|
||||
const errorMessage = ref('');
|
||||
const videoDetail = ref<IBilibiliVideoDetail | null>(null);
|
||||
const currentPage = ref<IBilibiliPage | null>(null);
|
||||
const audioList = ref<SongResult[]>([]);
|
||||
|
||||
// 只在初始加载时应用动画
|
||||
const initialLoadDone = ref(false);
|
||||
const mainContentAnimation = computed(() => {
|
||||
if (!initialLoadDone.value) {
|
||||
return setAnimationClass('animate__fadeInDown');
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
const partsListAnimation = computed(() => {
|
||||
if (!initialLoadDone.value) {
|
||||
return setAnimationClass('animate__fadeInUp');
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
// 监听bvid变化
|
||||
watch(
|
||||
() => bvid.value,
|
||||
async (newBvid) => {
|
||||
if (newBvid) {
|
||||
// 新的视频ID,重置初始加载状态
|
||||
initialLoadDone.value = false;
|
||||
await loadVideoDetail(newBvid);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// 组件挂载时加载数据
|
||||
onMounted(async () => {
|
||||
if (bvid.value) {
|
||||
await loadVideoDetail(bvid.value);
|
||||
} else {
|
||||
message.error('视频ID无效');
|
||||
router.back();
|
||||
}
|
||||
});
|
||||
|
||||
const loadVideoDetail = async (bvid: string) => {
|
||||
if (!bvid) return;
|
||||
|
||||
isLoading.value = true;
|
||||
errorMessage.value = '';
|
||||
audioList.value = [];
|
||||
|
||||
try {
|
||||
console.log('加载B站视频详情:', bvid);
|
||||
const res = await getBilibiliVideoDetail(bvid);
|
||||
console.log('B站视频详情数据:', res.data);
|
||||
|
||||
// 确保响应式数据更新
|
||||
videoDetail.value = JSON.parse(JSON.stringify(res.data));
|
||||
|
||||
// 默认加载第一个分P
|
||||
if (videoDetail.value?.pages && videoDetail.value.pages.length > 0) {
|
||||
console.log('视频有多个分P,共', videoDetail.value.pages.length, '个');
|
||||
const [firstPage] = videoDetail.value.pages;
|
||||
currentPage.value = firstPage;
|
||||
await loadVideoSource();
|
||||
} else {
|
||||
console.log('视频无分P或分P数据为空');
|
||||
errorMessage.value = '无法加载视频分P信息';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取视频详情失败', error);
|
||||
errorMessage.value = '获取视频详情失败';
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
// 标记初始加载完成
|
||||
initialLoadDone.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const loadVideoSource = async () => {
|
||||
if (!bvid.value || !currentPage.value?.cid) {
|
||||
console.error('缺少必要参数:', { bvid: bvid.value, cid: currentPage.value?.cid });
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading.value = true;
|
||||
errorMessage.value = '';
|
||||
|
||||
try {
|
||||
console.log('加载音频源:', bvid.value, currentPage.value.cid);
|
||||
|
||||
// 将当前视频转换为音频格式加入播放列表
|
||||
const tempAudio = createSongFromBilibiliVideo(); // 创建一个临时对象,还没有URL
|
||||
|
||||
// 加载当前分P的音频URL
|
||||
const currentAudio = await loadSongUrl(currentPage.value, tempAudio);
|
||||
|
||||
// 将所有分P添加到播放列表
|
||||
if (videoDetail.value?.pages) {
|
||||
audioList.value = videoDetail.value.pages.map((page, index) => {
|
||||
// 第一个分P直接使用已获取的音频URL
|
||||
if (index === 0 && currentPage.value?.cid === page.cid) {
|
||||
return currentAudio;
|
||||
}
|
||||
|
||||
// 其他分P创建占位对象,稍后按需加载
|
||||
return {
|
||||
id: `${videoDetail.value!.aid}--${page.cid}`, // 使用aid+cid作为唯一ID
|
||||
name: `${page.part || ''} - ${videoDetail.value!.title}`,
|
||||
picUrl: getBilibiliProxyUrl(videoDetail.value!.pic),
|
||||
type: 0,
|
||||
canDislike: false,
|
||||
alg: '',
|
||||
source: 'bilibili', // 设置来源为B站
|
||||
song: {
|
||||
name: `${page.part || ''} - ${videoDetail.value!.title}`,
|
||||
id: `${videoDetail.value!.aid}--${page.cid}`,
|
||||
ar: [
|
||||
{
|
||||
name: videoDetail.value!.owner.name,
|
||||
id: videoDetail.value!.owner.mid
|
||||
}
|
||||
],
|
||||
al: {
|
||||
picUrl: getBilibiliProxyUrl(videoDetail.value!.pic)
|
||||
}
|
||||
} as any,
|
||||
bilibiliData: {
|
||||
bvid: bvid.value,
|
||||
cid: page.cid
|
||||
}
|
||||
} as SongResult;
|
||||
});
|
||||
console.log('已生成音频列表,共', audioList.value.length, '首');
|
||||
|
||||
// 预加载下一集
|
||||
if (audioList.value.length > 1) {
|
||||
const nextIndex = 1; // 默认加载第二个分P
|
||||
const nextPage = videoDetail.value.pages[nextIndex];
|
||||
const nextAudio = audioList.value[nextIndex];
|
||||
loadSongUrl(nextPage, nextAudio).catch((e) => console.warn('预加载下一个分P失败:', e));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取音频播放地址失败', error);
|
||||
errorMessage.value = '获取音频播放地址失败';
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const createSongFromBilibiliVideo = (): SongResult => {
|
||||
if (!videoDetail.value || !currentPage.value) {
|
||||
throw new Error('视频详情未加载');
|
||||
}
|
||||
|
||||
const pageName = currentPage.value.part || '';
|
||||
const title = `${pageName} - ${videoDetail.value.title}`;
|
||||
|
||||
return {
|
||||
id: `${videoDetail.value.aid}--${currentPage.value.cid}`, // 使用aid+cid作为唯一ID
|
||||
name: title,
|
||||
picUrl: getBilibiliProxyUrl(videoDetail.value.pic),
|
||||
type: 0,
|
||||
canDislike: false,
|
||||
alg: '',
|
||||
// 设置来源为B站
|
||||
source: 'bilibili',
|
||||
// playMusicUrl属性稍后通过loadSongUrl函数添加
|
||||
song: {
|
||||
name: title,
|
||||
id: `${videoDetail.value.aid}--${currentPage.value.cid}`,
|
||||
ar: [
|
||||
{
|
||||
name: videoDetail.value.owner.name,
|
||||
id: videoDetail.value.owner.mid
|
||||
}
|
||||
],
|
||||
al: {
|
||||
picUrl: getBilibiliProxyUrl(videoDetail.value.pic)
|
||||
}
|
||||
} as any,
|
||||
bilibiliData: {
|
||||
bvid: bvid.value,
|
||||
cid: currentPage.value.cid
|
||||
}
|
||||
} as SongResult;
|
||||
};
|
||||
|
||||
const loadSongUrl = async (
|
||||
page: IBilibiliPage,
|
||||
songItem: SongResult,
|
||||
forceRefresh: boolean = false
|
||||
) => {
|
||||
if (songItem.playMusicUrl && !forceRefresh) return songItem; // 如果已有URL且不强制刷新则直接返回
|
||||
|
||||
try {
|
||||
console.log(`加载分P音频URL: ${page.part}, cid: ${page.cid}`);
|
||||
const res = await getBilibiliPlayUrl(bvid.value, page.cid);
|
||||
const playUrlData = res.data;
|
||||
let url = '';
|
||||
|
||||
// 尝试获取音频URL
|
||||
if (playUrlData.dash && playUrlData.dash.audio && playUrlData.dash.audio.length > 0) {
|
||||
url = playUrlData.dash.audio[0].baseUrl;
|
||||
console.log('获取到dash音频URL:', url);
|
||||
} else if (playUrlData.durl && playUrlData.durl.length > 0) {
|
||||
url = playUrlData.durl[0].url;
|
||||
console.log('获取到durl音频URL:', url);
|
||||
} else {
|
||||
throw new Error('未找到可用的音频地址');
|
||||
}
|
||||
|
||||
// 设置代理URL
|
||||
songItem.playMusicUrl = getBilibiliProxyUrl(url);
|
||||
return songItem;
|
||||
} catch (error) {
|
||||
console.error(`加载分P音频URL失败: ${page.part}`, error);
|
||||
return songItem;
|
||||
}
|
||||
};
|
||||
|
||||
const switchPage = async (page: IBilibiliPage) => {
|
||||
if (partLoading.value || currentPage.value?.cid === page.cid) return;
|
||||
|
||||
console.log('切换到分P:', page.part);
|
||||
// 立即更新UI选中状态
|
||||
currentPage.value = page;
|
||||
|
||||
// 查找对应的音频项
|
||||
const audioItem = audioList.value.find((item) => item.bilibiliData?.cid === page.cid);
|
||||
|
||||
if (audioItem) {
|
||||
// 设置局部加载状态
|
||||
try {
|
||||
partLoading.value = true;
|
||||
// 每次切换分P都强制重新加载音频URL,以解决之前的URL可能失效的问题
|
||||
await loadSongUrl(page, audioItem, true);
|
||||
// 切换后自动播放
|
||||
playCurrentAudio();
|
||||
} catch (error) {
|
||||
console.error('切换分P时加载音频URL失败:', error);
|
||||
message.error('获取音频地址失败,请重试');
|
||||
} finally {
|
||||
partLoading.value = false;
|
||||
}
|
||||
} else {
|
||||
console.error('未找到对应的音频项');
|
||||
message.error('未找到对应的音频,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
const playCurrentAudio = async () => {
|
||||
if (audioList.value.length === 0) {
|
||||
console.error('音频列表为空');
|
||||
errorMessage.value = '音频列表为空,请重试';
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取当前分P的音频
|
||||
const currentIndex = audioList.value.findIndex(
|
||||
(item) => item.bilibiliData?.cid === currentPage.value?.cid
|
||||
);
|
||||
|
||||
if (currentIndex === -1) {
|
||||
console.error('未找到当前分P的音频');
|
||||
errorMessage.value = '未找到当前分P的音频';
|
||||
return;
|
||||
}
|
||||
|
||||
const currentAudio = audioList.value[currentIndex];
|
||||
console.log('准备播放当前选中的分P:', currentAudio.name);
|
||||
|
||||
try {
|
||||
// 每次播放前都强制重新加载当前分P的音频URL(解决可能的URL失效问题)
|
||||
partLoading.value = true;
|
||||
await loadSongUrl(currentPage.value!, currentAudio, true);
|
||||
|
||||
if (!currentAudio.playMusicUrl) {
|
||||
throw new Error('获取音频URL失败');
|
||||
}
|
||||
|
||||
// 预加载下一个分P的音频URL(如果有)
|
||||
const nextIndex = (currentIndex + 1) % audioList.value.length;
|
||||
if (nextIndex !== currentIndex) {
|
||||
const nextAudio = audioList.value[nextIndex];
|
||||
const nextPage = videoDetail.value!.pages.find((p) => p.cid === nextAudio.bilibiliData?.cid);
|
||||
|
||||
if (nextPage) {
|
||||
console.log('预加载下一个分P:', nextPage.part);
|
||||
loadSongUrl(nextPage, nextAudio).catch((e) => console.warn('预加载下一个分P失败:', e));
|
||||
}
|
||||
}
|
||||
|
||||
// 将B站音频列表设置为播放列表
|
||||
playerStore.setPlayList(audioList.value);
|
||||
|
||||
// 播放当前选中的分P
|
||||
console.log('播放当前选中的分P:', currentAudio.name, '音频URL:', currentAudio.playMusicUrl);
|
||||
playerStore.setPlayMusic(currentAudio);
|
||||
|
||||
// 播放后通知用户已开始播放
|
||||
message.success('已开始播放');
|
||||
} catch (error) {
|
||||
console.error('播放音频失败:', error);
|
||||
errorMessage.value = error instanceof Error ? error.message : '播放失败,请重试';
|
||||
} finally {
|
||||
partLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 格式化总时长
|
||||
*/
|
||||
const formatTotalDuration = (seconds?: number) => {
|
||||
if (!seconds) return '00:00:00';
|
||||
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
const remainingSeconds = seconds % 60;
|
||||
|
||||
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 格式化数字显示
|
||||
*/
|
||||
const formatNumber = (num?: number) => {
|
||||
if (!num) return '0';
|
||||
if (num >= 10000) {
|
||||
return `${(num / 10000).toFixed(1)}万`;
|
||||
}
|
||||
return num.toString();
|
||||
};
|
||||
|
||||
// 判断是否是当前正在播放的分P
|
||||
const isCurrentPlayingPage = (page: IBilibiliPage) => {
|
||||
// 只根据播放器状态判断,不再使用UI选中状态
|
||||
const currentPlayingMusic = playerStore.playMusic as any;
|
||||
if (
|
||||
currentPlayingMusic &&
|
||||
typeof currentPlayingMusic === 'object' &&
|
||||
currentPlayingMusic.bilibiliData
|
||||
) {
|
||||
// 比较当前播放的音频的cid与此分P的cid
|
||||
return (
|
||||
currentPlayingMusic.bilibiliData.cid === page.cid &&
|
||||
currentPlayingMusic.bilibiliData.bvid === bvid.value
|
||||
);
|
||||
}
|
||||
|
||||
// 如果没有正在播放的音乐,则使用UI选择状态
|
||||
return currentPage.value?.cid === page.cid;
|
||||
};
|
||||
|
||||
// 监听播放器状态变化,保持分P列表选中状态同步
|
||||
watch(
|
||||
() => playerStore.playMusic,
|
||||
(newMusic: any) => {
|
||||
if (
|
||||
newMusic &&
|
||||
typeof newMusic === 'object' &&
|
||||
newMusic.bilibiliData &&
|
||||
newMusic.bilibiliData.bvid === bvid.value
|
||||
) {
|
||||
// 查找对应的分P
|
||||
const playingPage = videoDetail.value?.pages?.find(
|
||||
(p) => p.cid === newMusic.bilibiliData.cid
|
||||
);
|
||||
|
||||
// 无条件更新UI状态以确保UI状态与播放状态一致
|
||||
if (playingPage) {
|
||||
currentPage.value = playingPage;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.bilibili-player-page {
|
||||
@apply h-full flex flex-col;
|
||||
|
||||
.content-scrollbar {
|
||||
@apply flex-1 overflow-hidden;
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
@apply flex flex-col p-4;
|
||||
}
|
||||
}
|
||||
|
||||
.bilibili-info-wrapper {
|
||||
@apply flex flex-col md:flex-row gap-4 w-full;
|
||||
|
||||
.bilibili-cover {
|
||||
@apply relative w-full md:w-1/3 aspect-video rounded-lg overflow-hidden;
|
||||
|
||||
.cover-image {
|
||||
@apply w-full h-full object-cover;
|
||||
}
|
||||
|
||||
.play-overlay {
|
||||
@apply absolute inset-0;
|
||||
|
||||
.play-icon-bg {
|
||||
@apply absolute inset-0 flex items-center justify-center bg-black/40 text-white opacity-0 hover:opacity-100 transition-opacity cursor-pointer;
|
||||
|
||||
i {
|
||||
@apply text-4xl;
|
||||
}
|
||||
}
|
||||
|
||||
.corner-play-button {
|
||||
@apply absolute right-3 bottom-3 shadow-lg flex items-center gap-1 px-4 py-1 text-sm transition-all duration-200;
|
||||
|
||||
&:hover {
|
||||
@apply transform scale-110;
|
||||
}
|
||||
|
||||
i {
|
||||
@apply text-xl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.loading-wrapper,
|
||||
.error-wrapper {
|
||||
@apply w-full flex flex-col items-center justify-center py-16 rounded-lg bg-gray-100 dark:bg-gray-800;
|
||||
aspect-ratio: 16/9;
|
||||
|
||||
p {
|
||||
@apply mt-4 text-gray-600 dark:text-gray-400;
|
||||
}
|
||||
}
|
||||
|
||||
.error-wrapper {
|
||||
button {
|
||||
@apply mt-4;
|
||||
}
|
||||
}
|
||||
|
||||
.video-info {
|
||||
@apply flex-1 p-4 rounded-lg bg-gray-100 dark:bg-gray-800;
|
||||
|
||||
.title {
|
||||
@apply text-lg font-medium mb-4 text-gray-900 dark:text-white;
|
||||
}
|
||||
|
||||
.author {
|
||||
@apply flex items-center text-sm mb-2;
|
||||
}
|
||||
|
||||
.stats {
|
||||
@apply flex gap-4 text-xs text-gray-500 dark:text-gray-400 mb-3;
|
||||
}
|
||||
|
||||
.description {
|
||||
@apply text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap mb-3;
|
||||
max-height: 100px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.duration {
|
||||
@apply text-sm text-gray-600 dark:text-gray-400;
|
||||
}
|
||||
}
|
||||
|
||||
.video-parts {
|
||||
@apply mt-4;
|
||||
|
||||
.parts-title {
|
||||
@apply text-sm font-medium mb-2 flex items-center;
|
||||
}
|
||||
|
||||
.parts-list {
|
||||
@apply flex flex-wrap gap-2 max-h-60 overflow-y-auto pb-4;
|
||||
|
||||
.part-item {
|
||||
@apply text-xs mb-2;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -63,7 +63,7 @@
|
||||
:class="setAnimationClass('animate__bounceInLeft')"
|
||||
:style="getItemAnimationDelay(index)"
|
||||
:selectable="isSelecting"
|
||||
:selected="selectedSongs.includes(song.id)"
|
||||
:selected="selectedSongs.includes(song.id as number)"
|
||||
@play="handlePlay"
|
||||
@select="handleSelect"
|
||||
/>
|
||||
@@ -319,7 +319,7 @@ const isIndeterminate = computed(() => {
|
||||
// 处理全选/取消全选
|
||||
const handleSelectAll = (checked: boolean) => {
|
||||
if (checked) {
|
||||
selectedSongs.value = favoriteSongs.value.map((song) => song.id);
|
||||
selectedSongs.value = favoriteSongs.value.map((song) => song.id as number);
|
||||
} else {
|
||||
selectedSongs.value = [];
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ const getHistorySongs = async () => {
|
||||
const endIndex = startIndex + pageSize;
|
||||
const currentPageItems = musicList.value.slice(startIndex, endIndex);
|
||||
|
||||
const currentIds = currentPageItems.map((item) => item.id);
|
||||
const currentIds = currentPageItems.map((item) => item.id as number);
|
||||
const res = await getMusicDetail(currentIds);
|
||||
|
||||
if (res.data.songs) {
|
||||
|
||||
@@ -40,33 +40,52 @@
|
||||
</div>
|
||||
<div v-loading="searchDetailLoading" class="search-list-box">
|
||||
<template v-if="searchDetail">
|
||||
<div
|
||||
v-for="(item, index) in searchDetail?.songs"
|
||||
:key="item.id"
|
||||
:class="setAnimationClass('animate__bounceInRight')"
|
||||
:style="setAnimationDelay(index, 50)"
|
||||
>
|
||||
<song-item :item="item" @play="handlePlay" />
|
||||
</div>
|
||||
<template v-for="(list, key) in searchDetail">
|
||||
<template v-if="key.toString() !== 'songs'">
|
||||
<div
|
||||
v-for="(item, index) in list"
|
||||
:key="item.id"
|
||||
class="mb-3"
|
||||
:class="setAnimationClass('animate__bounceInRight')"
|
||||
:style="setAnimationDelay(index, 50)"
|
||||
>
|
||||
<search-item :item="item" />
|
||||
</div>
|
||||
</template>
|
||||
<!-- B站视频搜索结果 -->
|
||||
<template v-if="searchType === SEARCH_TYPE.BILIBILI">
|
||||
<div
|
||||
v-for="(item, index) in searchDetail?.bilibili"
|
||||
:key="item.bvid"
|
||||
:class="setAnimationClass('animate__bounceInRight')"
|
||||
:style="setAnimationDelay(index, 50)"
|
||||
>
|
||||
<bilibili-item :item="item" @play="handlePlayBilibili" />
|
||||
</div>
|
||||
<div v-if="isLoadingMore" class="loading-more">
|
||||
<n-spin size="small" />
|
||||
<span class="ml-2">{{ t('search.loading.more') }}</span>
|
||||
</div>
|
||||
<div v-if="!hasMore && searchDetail" class="no-more">{{ t('search.noMore') }}</div>
|
||||
</template>
|
||||
<!-- 原有音乐搜索结果 -->
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="(item, index) in searchDetail?.songs"
|
||||
:key="item.id"
|
||||
:class="setAnimationClass('animate__bounceInRight')"
|
||||
:style="setAnimationDelay(index, 50)"
|
||||
>
|
||||
<song-item :item="item" @play="handlePlay" />
|
||||
</div>
|
||||
<template v-for="(list, key) in searchDetail">
|
||||
<template v-if="key.toString() !== 'songs'">
|
||||
<div
|
||||
v-for="(item, index) in list"
|
||||
:key="item.id"
|
||||
class="mb-3"
|
||||
:class="setAnimationClass('animate__bounceInRight')"
|
||||
:style="setAnimationDelay(index, 50)"
|
||||
>
|
||||
<search-item :item="item" />
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="isLoadingMore" class="loading-more">
|
||||
<n-spin size="small" />
|
||||
<span class="ml-2">{{ t('search.loading.more') }}</span>
|
||||
</div>
|
||||
<div v-if="!hasMore && searchDetail" class="no-more">{{ t('search.noMore') }}</div>
|
||||
</template>
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="isLoadingMore" class="loading-more">
|
||||
<n-spin size="small" />
|
||||
<span class="ml-2">{{ t('search.loading.more') }}</span>
|
||||
</div>
|
||||
<div v-if="!hasMore && searchDetail" class="no-more">{{ t('search.noMore') }}</div>
|
||||
</template>
|
||||
<!-- 搜索历史 -->
|
||||
<template v-else>
|
||||
@@ -92,7 +111,7 @@
|
||||
@click="handleSearchHistory(item)"
|
||||
@close="handleCloseSearchHistory(item)"
|
||||
>
|
||||
{{ item }}
|
||||
{{ item.keyword }}
|
||||
</n-tag>
|
||||
</div>
|
||||
</div>
|
||||
@@ -104,17 +123,21 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useDateFormat } from '@vueuse/core';
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
|
||||
import { getBilibiliProxyUrl, searchBilibili } from '@/api/bilibili';
|
||||
import { getHotSearch } from '@/api/home';
|
||||
import { getSearch } from '@/api/search';
|
||||
import BilibiliItem from '@/components/common/BilibiliItem.vue';
|
||||
import SearchItem from '@/components/common/SearchItem.vue';
|
||||
import SongItem from '@/components/common/SongItem.vue';
|
||||
import { SEARCH_TYPE } from '@/const/bar-const';
|
||||
import { usePlayerStore } from '@/store/modules/player';
|
||||
import { useSearchStore } from '@/store/modules/search';
|
||||
import type { IHotSearch } from '@/type/search';
|
||||
import type { IBilibiliSearchResult } from '@/types/bilibili';
|
||||
import { isMobile, setAnimationClass, setAnimationDelay } from '@/utils';
|
||||
|
||||
defineOptions({
|
||||
@@ -123,13 +146,14 @@ defineOptions({
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const playerStore = usePlayerStore();
|
||||
const searchStore = useSearchStore();
|
||||
|
||||
const searchDetail = ref<any>();
|
||||
const searchType = computed(() => searchStore.searchType as number);
|
||||
const searchDetailLoading = ref(false);
|
||||
const searchHistory = ref<string[]>([]);
|
||||
const searchHistory = ref<Array<{ keyword: string; type: number }>>([]);
|
||||
|
||||
// 添加分页相关的状态
|
||||
const ITEMS_PER_PAGE = 30; // 每页数量
|
||||
@@ -144,17 +168,17 @@ const loadSearchHistory = () => {
|
||||
searchHistory.value = history ? JSON.parse(history) : [];
|
||||
};
|
||||
|
||||
// 保存搜索历史
|
||||
const saveSearchHistory = (keyword: string) => {
|
||||
// 保存搜索历史,改为保存关键词和类型
|
||||
const saveSearchHistory = (keyword: string, type: number) => {
|
||||
if (!keyword) return;
|
||||
const history = searchHistory.value;
|
||||
// 移除重复的关键词
|
||||
const index = history.indexOf(keyword);
|
||||
const index = history.findIndex((item) => item.keyword === keyword);
|
||||
if (index > -1) {
|
||||
history.splice(index, 1);
|
||||
}
|
||||
// 添加到开头
|
||||
history.unshift(keyword);
|
||||
history.unshift({ keyword, type });
|
||||
// 只保留最近的20条记录
|
||||
if (history.length > 20) {
|
||||
history.pop();
|
||||
@@ -170,8 +194,8 @@ const clearSearchHistory = () => {
|
||||
};
|
||||
|
||||
// 删除搜索历史
|
||||
const handleCloseSearchHistory = (keyword: string) => {
|
||||
searchHistory.value = searchHistory.value.filter((item) => item !== keyword);
|
||||
const handleCloseSearchHistory = (item: { keyword: string; type: number }) => {
|
||||
searchHistory.value = searchHistory.value.filter((h) => h.keyword !== item.keyword);
|
||||
localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
|
||||
};
|
||||
|
||||
@@ -185,7 +209,7 @@ const loadHotSearch = async () => {
|
||||
onMounted(() => {
|
||||
loadHotSearch();
|
||||
loadSearchHistory();
|
||||
loadSearch(route.query.keyword);
|
||||
// 注意:路由参数的处理已经在 watch route.query 中处理了
|
||||
});
|
||||
|
||||
const hotKeyword = ref(route.query.keyword || t('search.title.searchList'));
|
||||
@@ -193,21 +217,26 @@ const hotKeyword = ref(route.query.keyword || t('search.title.searchList'));
|
||||
const loadSearch = async (keywords: any, type: any = null, isLoadMore = false) => {
|
||||
if (!keywords) return;
|
||||
|
||||
// 使用传入的类型或当前类型
|
||||
const searchTypeToUse = type !== null ? type : searchType.value;
|
||||
|
||||
if (!isLoadMore) {
|
||||
hotKeyword.value = keywords;
|
||||
searchDetail.value = undefined;
|
||||
page.value = 0;
|
||||
hasMore.value = true;
|
||||
currentKeyword.value = keywords;
|
||||
|
||||
// 保存搜索历史
|
||||
saveSearchHistory(keywords, searchTypeToUse);
|
||||
|
||||
// 始终更新搜索框内容和类型
|
||||
searchStore.searchType = searchTypeToUse;
|
||||
searchStore.searchValue = keywords;
|
||||
} else if (isLoadingMore.value || !hasMore.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 保存搜索历史
|
||||
if (!isLoadMore) {
|
||||
saveSearchHistory(keywords);
|
||||
}
|
||||
|
||||
if (isLoadMore) {
|
||||
isLoadingMore.value = true;
|
||||
} else {
|
||||
@@ -215,61 +244,98 @@ const loadSearch = async (keywords: any, type: any = null, isLoadMore = false) =
|
||||
}
|
||||
|
||||
try {
|
||||
const { data } = await getSearch({
|
||||
keywords: currentKeyword.value,
|
||||
type: type || searchType.value,
|
||||
limit: ITEMS_PER_PAGE,
|
||||
offset: page.value * ITEMS_PER_PAGE
|
||||
});
|
||||
// B站搜索
|
||||
if (searchTypeToUse === SEARCH_TYPE.BILIBILI) {
|
||||
const response = await searchBilibili({
|
||||
keyword: currentKeyword.value,
|
||||
page: page.value + 1,
|
||||
pagesize: ITEMS_PER_PAGE
|
||||
});
|
||||
console.log('response', response);
|
||||
|
||||
const songs = data.result.songs || [];
|
||||
const albums = data.result.albums || [];
|
||||
const mvs = (data.result.mvs || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.cover,
|
||||
playCount: item.playCount,
|
||||
desc: item.artists.map((artist: any) => artist.name).join('/'),
|
||||
type: 'mv'
|
||||
}));
|
||||
const bilibiliVideos = response.data.data.result.map((item: any) => ({
|
||||
id: item.aid,
|
||||
bvid: item.bvid,
|
||||
title: item.title,
|
||||
author: item.author,
|
||||
pic: getBilibiliProxyUrl(item.pic),
|
||||
duration: item.duration,
|
||||
pubdate: item.pubdate,
|
||||
description: item.description,
|
||||
view: item.play,
|
||||
danmaku: item.video_review
|
||||
}));
|
||||
|
||||
const playlists = (data.result.playlists || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.coverImgUrl,
|
||||
playCount: item.playCount,
|
||||
desc: item.creator.nickname,
|
||||
type: 'playlist'
|
||||
}));
|
||||
if (isLoadMore && searchDetail.value) {
|
||||
// 合并数据
|
||||
searchDetail.value.bilibili = [...searchDetail.value.bilibili, ...bilibiliVideos];
|
||||
} else {
|
||||
searchDetail.value = {
|
||||
bilibili: bilibiliVideos
|
||||
};
|
||||
}
|
||||
|
||||
// songs map 替换属性
|
||||
songs.forEach((item: any) => {
|
||||
item.picUrl = item.al.picUrl;
|
||||
item.artists = item.ar;
|
||||
});
|
||||
albums.forEach((item: any) => {
|
||||
item.desc = `${item.artist.name} ${item.company} ${dateFormat(item.publishTime)}`;
|
||||
});
|
||||
|
||||
if (isLoadMore && searchDetail.value) {
|
||||
// 合并数据
|
||||
searchDetail.value.songs = [...searchDetail.value.songs, ...songs];
|
||||
searchDetail.value.albums = [...searchDetail.value.albums, ...albums];
|
||||
searchDetail.value.mvs = [...searchDetail.value.mvs, ...mvs];
|
||||
searchDetail.value.playlists = [...searchDetail.value.playlists, ...playlists];
|
||||
} else {
|
||||
searchDetail.value = {
|
||||
songs,
|
||||
albums,
|
||||
mvs,
|
||||
playlists
|
||||
};
|
||||
// 判断是否还有更多数据
|
||||
hasMore.value = bilibiliVideos.length === ITEMS_PER_PAGE;
|
||||
}
|
||||
// 音乐搜索
|
||||
else {
|
||||
const { data } = await getSearch({
|
||||
keywords: currentKeyword.value,
|
||||
type: searchTypeToUse,
|
||||
limit: ITEMS_PER_PAGE,
|
||||
offset: page.value * ITEMS_PER_PAGE
|
||||
});
|
||||
|
||||
// 判断是否还有更多数据
|
||||
hasMore.value =
|
||||
songs.length === ITEMS_PER_PAGE ||
|
||||
albums.length === ITEMS_PER_PAGE ||
|
||||
mvs.length === ITEMS_PER_PAGE ||
|
||||
playlists.length === ITEMS_PER_PAGE;
|
||||
const songs = data.result.songs || [];
|
||||
const albums = data.result.albums || [];
|
||||
const mvs = (data.result.mvs || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.cover,
|
||||
playCount: item.playCount,
|
||||
desc: item.artists.map((artist: any) => artist.name).join('/'),
|
||||
type: 'mv'
|
||||
}));
|
||||
|
||||
const playlists = (data.result.playlists || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.coverImgUrl,
|
||||
playCount: item.playCount,
|
||||
desc: item.creator.nickname,
|
||||
type: 'playlist'
|
||||
}));
|
||||
|
||||
// songs map 替换属性
|
||||
songs.forEach((item: any) => {
|
||||
item.picUrl = item.al.picUrl;
|
||||
item.artists = item.ar;
|
||||
});
|
||||
albums.forEach((item: any) => {
|
||||
item.desc = `${item.artist.name} ${item.company} ${dateFormat(item.publishTime)}`;
|
||||
});
|
||||
|
||||
if (isLoadMore && searchDetail.value) {
|
||||
// 合并数据
|
||||
searchDetail.value.songs = [...searchDetail.value.songs, ...songs];
|
||||
searchDetail.value.albums = [...searchDetail.value.albums, ...albums];
|
||||
searchDetail.value.mvs = [...searchDetail.value.mvs, ...mvs];
|
||||
searchDetail.value.playlists = [...searchDetail.value.playlists, ...playlists];
|
||||
} else {
|
||||
searchDetail.value = {
|
||||
songs,
|
||||
albums,
|
||||
mvs,
|
||||
playlists
|
||||
};
|
||||
}
|
||||
|
||||
// 判断是否还有更多数据
|
||||
hasMore.value =
|
||||
songs.length === ITEMS_PER_PAGE ||
|
||||
albums.length === ITEMS_PER_PAGE ||
|
||||
mvs.length === ITEMS_PER_PAGE ||
|
||||
playlists.length === ITEMS_PER_PAGE;
|
||||
}
|
||||
|
||||
page.value++;
|
||||
} catch (error) {
|
||||
@@ -315,12 +381,21 @@ const handleScroll = (e: any) => {
|
||||
};
|
||||
|
||||
watch(
|
||||
() => route.path,
|
||||
async (path) => {
|
||||
if (path === '/search') {
|
||||
searchStore.searchValue = route.query.keyword as string;
|
||||
() => route.query,
|
||||
(query) => {
|
||||
if (route.path === '/search' && query.keyword) {
|
||||
const routeKeyword = query.keyword as string;
|
||||
const routeType = query.type ? Number(query.type) : searchType.value;
|
||||
|
||||
// 更新搜索类型和值
|
||||
searchStore.searchType = routeType;
|
||||
searchStore.searchValue = routeKeyword;
|
||||
|
||||
// 加载搜索结果
|
||||
loadSearch(routeKeyword, routeType);
|
||||
}
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
const handlePlay = () => {
|
||||
@@ -329,8 +404,19 @@ const handlePlay = () => {
|
||||
};
|
||||
|
||||
// 点击搜索历史
|
||||
const handleSearchHistory = (keyword: string) => {
|
||||
loadSearch(keyword, 1);
|
||||
const handleSearchHistory = (item: { keyword: string; type: number }) => {
|
||||
// 更新搜索类型
|
||||
searchStore.searchType = item.type;
|
||||
// 先更新搜索值到 store
|
||||
searchStore.searchValue = item.keyword;
|
||||
// 使用关键词和类型加载搜索
|
||||
loadSearch(item.keyword, item.type);
|
||||
};
|
||||
|
||||
// 处理B站视频播放
|
||||
const handlePlayBilibili = (item: IBilibiliSearchResult) => {
|
||||
// 使用路由导航到B站播放页面
|
||||
router.push(`/bilibili/${item.bvid}`);
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user