feat: 更新网易云音乐 API 版本,添加 B站视频搜索功能和播放器组件

This commit is contained in:
alger
2025-03-29 23:19:51 +08:00
parent c5e50c9fd5
commit 280fec1990
12 changed files with 1630 additions and 125 deletions

View 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 VitalsLCP、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 个最可能的来源,将其与历史错误日志、相关系统状态和预期行为进行交叉验证。如果发现不一致,调整你的假设。
- 在添加日志时,确保它们被策略性地放置,以便同时确认或排除多个潜在原因。如果日志不支持你的假设,请先提出替代的调试策略,再继续深入分析。
- 在实施修复之前,先总结问题现象、经过验证的假设,以及预期的日志输出,以确认问题是否真正得到解决。

View File

@@ -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": {

View File

@@ -0,0 +1,128 @@
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站视频详情APIbvid:', 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站视频播放地址APIbvid:', 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)}`;
};

View File

@@ -0,0 +1,519 @@
<template>
<n-drawer
v-model:show="showModal"
class="bilibili-player-modal"
:mask-closable="true"
:auto-focus="false"
:to="`#layout-main`"
preset="card"
height="80%"
placement="bottom"
>
<div class="bilibili-player-wrapper">
<div class="bilibili-player-header">
<div class="title">{{ videoDetail?.title || '加载中...' }}</div>
<div class="actions">
<n-button quaternary circle @click="closePlayer">
<template #icon>
<i class="ri-close-line"></i>
</template>
</n-button>
</div>
</div>
<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">
<div class="bilibili-cover">
<n-image
:src="getBilibiliProxyUrl(videoDetail.pic)"
class="cover-image"
preview-disabled
/>
<div class="play-button" @click="playCurrentAudio">
<i class="ri-play-fill text-4xl"></i>
</div>
</div>
<div class="video-info">
<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">
<div class="parts-title">分P列表 ({{ videoDetail.pages.length }})</div>
<div class="parts-list">
<n-button
v-for="page in videoDetail.pages"
:key="page.cid"
:type="currentPage?.cid === page.cid ? 'primary' : 'default'"
size="small"
class="part-item"
@click="switchPage(page)"
>
{{ page.part }}
</n-button>
</div>
</div>
</div>
</n-drawer>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
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';
const props = defineProps<{
show: boolean;
bvid?: string;
}>();
const emit = defineEmits<{
(e: 'update:show', value: boolean): void;
(e: 'close'): void;
}>();
const playerStore = usePlayerStore();
const isLoading = ref(true);
const errorMessage = ref('');
const videoDetail = ref<IBilibiliVideoDetail | null>(null);
const currentPage = ref<IBilibiliPage | null>(null);
const audioList = ref<SongResult[]>([]);
const showModal = computed({
get: () => props.show,
set: (value) => {
emit('update:show', value);
if (!value) {
emit('close');
}
}
});
watch(
() => props.bvid,
async (newBvid) => {
if (newBvid) {
await loadVideoDetail(newBvid);
}
},
{ immediate: true }
);
watch(
() => props.show,
(newValue) => {
console.log('Modal show changed:', newValue);
if (newValue && props.bvid && !videoDetail.value) {
loadVideoDetail(props.bvid);
}
}
);
const closePlayer = () => {
showModal.value = false;
};
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;
}
};
const loadVideoSource = async () => {
if (!props.bvid || !currentPage.value?.cid) {
console.error('缺少必要参数:', { bvid: props.bvid, cid: currentPage.value?.cid });
return;
}
isLoading.value = true;
errorMessage.value = '';
try {
console.log('加载音频源:', props.bvid, 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: props.bvid,
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: props.bvid,
cid: currentPage.value.cid
}
} as SongResult;
};
const loadSongUrl = async (page: IBilibiliPage, songItem: SongResult) => {
if (songItem.playMusicUrl) return songItem; // 如果已有URL则直接返回
try {
console.log(`加载分P音频URL: ${page.part}, cid: ${page.cid}`);
const res = await getBilibiliPlayUrl(props.bvid!, 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) => {
console.log('切换到分P:', page.part);
currentPage.value = page;
// 查找对应的音频项
const audioItem = audioList.value.find((item) => item.bilibiliData?.cid === page.cid);
if (audioItem && !audioItem.playMusicUrl) {
// 如果该分P没有音频URL则先加载
try {
isLoading.value = true;
await loadSongUrl(page, audioItem);
} catch (error) {
console.error('切换分P时加载音频URL失败:', error);
errorMessage.value = '获取音频地址失败,请重试';
} finally {
isLoading.value = false;
}
}
};
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如果需要
if (!currentAudio.playMusicUrl) {
isLoading.value = true;
await loadSongUrl(currentPage.value!, currentAudio);
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 && !nextAudio.playMusicUrl) {
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);
// 关闭模态框
closePlayer();
} catch (error) {
console.error('播放音频失败:', error);
errorMessage.value = error instanceof Error ? error.message : '播放失败,请重试';
} finally {
isLoading.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();
};
</script>
<style scoped lang="scss">
.bilibili-player-modal {
width: 90vw;
max-width: 1000px;
}
.bilibili-player-wrapper {
@apply flex flex-col p-8 pt-4;
}
.bilibili-player-header {
@apply flex justify-between items-center mb-4;
.title {
@apply text-lg font-medium truncate;
}
.actions {
@apply flex items-center;
}
}
.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-button {
@apply absolute inset-0 flex items-center justify-center bg-black/40 text-white opacity-0 hover:opacity-100 transition-opacity cursor-pointer;
}
}
}
.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;
.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;
}
.parts-list {
@apply flex flex-wrap gap-2 max-h-60 overflow-y-auto pb-20;
.part-item {
@apply text-xs mb-2;
}
}
}
</style>

View File

@@ -0,0 +1,410 @@
<template>
<div
class="music-bar-container"
:class="{ playing: playerStore.isPlay && playerStore.playMusicUrl }"
>
<div class="music-bar-left">
<div
class="music-cover"
:class="{ loading: playerStore.currentSong?.playLoading }"
@click="openDetailPlayer"
>
<n-image
v-if="playerStore.currentSong && playerStore.currentSong.picUrl"
class="cover-image"
:src="getSourcePic(playerStore.currentSong)"
preview-disabled
:object-fit="'cover'"
/>
<n-spin v-if="playerStore.currentSong?.playLoading" size="small" />
</div>
<div class="music-info">
<div class="music-title ellipsis-text">
{{ playerStore.currentSong ? playerStore.currentSong.name : '' }}
</div>
<div class="music-artist ellipsis-text">
{{ getArtistName(playerStore.currentSong) }}
</div>
</div>
</div>
<div class="music-bar-center">
<div class="player-controls">
<n-button quaternary circle class="control-button prev-button" @click="handlePrevClick">
<template #icon>
<i class="ri-skip-back-fill"></i>
</template>
</n-button>
<n-button
quaternary
circle
class="control-button play-button"
:disabled="!playerStore.currentSong.id"
@click="handlePlayClick"
>
<template #icon>
<i :class="playerStore.isPlay ? 'ri-pause-fill' : 'ri-play-fill'"></i>
</template>
</n-button>
<n-button quaternary circle class="control-button next-button" @click="handleNextClick">
<template #icon>
<i class="ri-skip-forward-fill"></i>
</template>
</n-button>
</div>
<div class="progress-container">
<div class="time-text">{{ formatTime(currentTime) }}</div>
<n-slider
class="progress-slider"
:value="playerProgress"
:step="0.1"
:max="duration"
:tooltip="false"
@update:value="handleProgressUpdate"
/>
<div class="time-text">{{ formatTime(duration) }}</div>
</div>
</div>
<div class="music-bar-right">
<n-button quaternary circle class="control-button mode-button" @click="togglePlayMode">
<template #icon>
<i v-if="playerStore.playMode === 0" class="ri-repeat-2-line" />
<i v-else-if="playerStore.playMode === 1" class="ri-repeat-one-line" />
<i v-else-if="playerStore.playMode === 2" class="ri-shuffle-line" />
</template>
</n-button>
<n-button quaternary circle class="control-button list-button" @click="togglePlayList">
<template #icon>
<i class="ri-play-list-line"></i>
</template>
</n-button>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { getBilibiliProxyUrl } from '@/api/bilibili';
import { usePlayerStore } from '@/store/modules/player';
import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils';
const router = useRouter();
const playerStore = usePlayerStore();
const currentTime = ref(0);
const duration = ref(0);
const playerProgress = ref(0);
const showPlayList = ref(false);
let audioPlayer: HTMLAudioElement | null = null;
// 计算播放进度
const progress = computed(() => {
if (duration.value === 0) return 0;
return (currentTime.value / duration.value) * 100;
});
// 监听播放状态
watch(
() => playerStore.isPlay,
(isPlay) => {
if (!audioPlayer) return;
if (isPlay) {
audioPlayer.play().catch((error) => {
console.error('播放失败:', error);
playerStore.setIsPlay(false);
});
} else {
audioPlayer.pause();
}
}
);
// 监听播放URL变化
watch(
() => playerStore.playMusicUrl,
(newUrl) => {
if (!audioPlayer) return;
if (newUrl) {
audioPlayer.src = newUrl;
if (playerStore.play) {
audioPlayer.play().catch((error) => {
console.error('播放失败:', error);
playerStore.setIsPlay(false);
});
}
}
}
);
// 初始化播放器
onMounted(() => {
audioPlayer = new Audio();
// 设置初始音频
if (playerStore.playMusicUrl) {
audioPlayer.src = playerStore.playMusicUrl;
// 如果应该自动播放
if (playerStore.play) {
audioPlayer.play().catch((error) => {
console.error('播放失败:', error);
playerStore.setIsPlay(false);
});
}
}
// 添加事件监听
audioPlayer.addEventListener('timeupdate', handleTimeUpdate);
audioPlayer.addEventListener('loadeddata', handleLoadedData);
audioPlayer.addEventListener('ended', handleEnded);
audioPlayer.addEventListener('pause', () => playerStore.setIsPlay(false));
audioPlayer.addEventListener('play', () => playerStore.setIsPlay(true));
audioPlayer.addEventListener('error', handleError);
});
// 处理播放时间更新
const handleTimeUpdate = () => {
if (!audioPlayer) return;
currentTime.value = audioPlayer.currentTime;
playerProgress.value = currentTime.value;
// 保存播放进度到localStorage
const playProgress = {
songId: playerStore.currentSong.id,
progress: currentTime.value
};
localStorage.setItem('playProgress', JSON.stringify(playProgress));
};
// 处理音频加载完成
const handleLoadedData = () => {
if (!audioPlayer) return;
duration.value = audioPlayer.duration;
// 如果有保存的播放进度,恢复到对应位置
if (playerStore.savedPlayProgress !== undefined) {
audioPlayer.currentTime = playerStore.savedPlayProgress;
playerStore.savedPlayProgress = undefined;
}
};
// 处理播放结束
const handleEnded = () => {
// 根据播放模式决定下一步操作
if (playerStore.playMode === 1) {
// 单曲循环
if (audioPlayer) {
audioPlayer.currentTime = 0;
audioPlayer.play().catch((error) => {
console.error('重新播放失败:', error);
playerStore.setIsPlay(false);
});
}
} else {
// 列表循环或随机播放
playerStore.nextPlay();
}
};
// 处理播放错误
const handleError = (e: Event) => {
console.error('音频播放出错:', e);
if (audioPlayer?.error) {
console.error('错误码:', audioPlayer.error.code);
// 如果是B站音频可能链接过期尝试重新获取
if (playerStore.currentSong.source === 'bilibili' && playerStore.currentSong.bilibiliData) {
console.log('B站音频播放错误可能链接过期');
// 这里可以添加重新获取B站音频链接的逻辑
}
}
};
// 处理播放/暂停按钮点击
const handlePlayClick = () => {
if (!playerStore.currentSong.id) return;
playerStore.setPlayMusic(!playerStore.isPlay);
};
// 处理上一曲按钮点击
const handlePrevClick = () => {
playerStore.prevPlay();
};
// 处理下一曲按钮点击
const handleNextClick = () => {
playerStore.nextPlay();
};
// 处理进度条更新
const handleProgressUpdate = (value: number) => {
if (!audioPlayer) return;
audioPlayer.currentTime = value;
currentTime.value = value;
};
// 切换播放模式
const togglePlayMode = () => {
playerStore.togglePlayMode();
};
// 切换播放列表显示
const togglePlayList = () => {
showPlayList.value = !showPlayList.value;
// 这里可以添加显示播放列表的逻辑
};
// 打开详情播放页
const openDetailPlayer = () => {
if (!playerStore.currentSong.id) return;
playerStore.setMusicFull(true);
// 根据来源打开不同的详情页
if (playerStore.currentSong.source === 'bilibili') {
// 打开B站详情页
if (playerStore.currentSong.bilibiliData?.bvid) {
// 这里可以跳转到B站详情页或显示B站播放器组件
}
} else {
// 打开网易云音乐详情页
router.push({ path: '/lyric' });
}
};
// 格式化时间
const formatTime = (time: number) => {
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};
// 获取艺术家名称
const getArtistName = (song?: SongResult) => {
if (!song) return '';
// B站视频
if (song.source === 'bilibili' && song.song?.ar?.[0]) {
return song.song.ar[0].name || 'B站UP主';
}
// 网易云音乐
if (song.song?.artists) {
return song.song.artists.map((artist: any) => artist.name).join('/');
}
if (song.song?.ar) {
return song.song.ar.map((artist: any) => artist.name).join('/');
}
return '';
};
// 根据来源获取封面图
const getSourcePic = (song: SongResult) => {
if (!song || !song.picUrl) return '';
// B站视频
if (song.source === 'bilibili') {
return song.picUrl; // B站封面已经在创建时使用getBilibiliProxyUrl处理过
}
// 网易云音乐
return getImgUrl(song.picUrl, '150y150');
};
</script>
<style scoped lang="scss">
.music-bar-container {
@apply flex items-center justify-between px-4 h-20 w-full bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700;
&.playing {
.music-cover {
animation: rotate 20s linear infinite;
}
}
}
.music-bar-left {
@apply flex items-center;
width: 25%;
.music-cover {
@apply relative w-12 h-12 rounded-lg overflow-hidden flex items-center justify-center cursor-pointer;
.cover-image {
@apply w-full h-full object-cover;
}
&.loading {
animation-play-state: paused;
}
}
.music-info {
@apply ml-2 flex flex-col;
max-width: calc(100% - 56px);
.music-title {
@apply text-sm font-medium;
}
.music-artist {
@apply text-xs text-gray-500 dark:text-gray-400;
}
}
}
.music-bar-center {
@apply flex flex-col items-center;
width: 50%;
.player-controls {
@apply flex items-center justify-center gap-2 mb-2;
.control-button {
@apply text-lg;
&.play-button {
@apply text-xl;
}
}
}
.progress-container {
@apply flex items-center w-full;
.time-text {
@apply text-xs px-2 text-gray-500 dark:text-gray-400 whitespace-nowrap;
}
.progress-slider {
@apply flex-1;
}
}
}
.music-bar-right {
@apply flex items-center justify-end;
width: 25%;
.control-button {
@apply text-lg;
}
}
.ellipsis-text {
@apply whitespace-nowrap overflow-hidden text-ellipsis;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>

View 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>

View File

@@ -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;

View File

@@ -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>

View File

@@ -24,13 +24,27 @@ 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);
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');
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 +59,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 +86,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 +126,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 +150,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 +166,6 @@ const preloadNextSong = (nextSongUrl: string) => {
preloadingSounds.value.push(sound);
// 添加加载错误处理
sound.on('loaderror', () => {
console.error('预加载音频失败:', nextSongUrl);
const index = preloadingSounds.value.indexOf(sound);
@@ -156,8 +189,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 +200,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 +209,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 +223,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 +232,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,7 +243,6 @@ 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);
@@ -227,24 +253,36 @@ export const usePlayerStore = defineStore('player', () => {
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));
@@ -303,12 +341,10 @@ 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;
}
@@ -344,7 +380,6 @@ export const usePlayerStore = defineStore('player', () => {
localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value));
};
// 初始化播放状态
const initializePlayState = async () => {
const settingStore = useSettingsStore();
const savedPlayList = getLocalStorageItem('playList', []);
@@ -390,16 +425,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;
@@ -414,12 +446,10 @@ export const usePlayerStore = defineStore('player', () => {
favoriteList.value = localList;
}
// 更新本地存储
localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value));
};
return {
// 状态
play,
isPlay,
playMusic,
@@ -431,13 +461,11 @@ export const usePlayerStore = defineStore('player', () => {
savedPlayProgress,
favoriteList,
// 计算属性
currentSong,
isPlaying,
currentPlayList,
currentPlayListIndex,
// 方法
setPlay,
setIsPlay,
nextPlay,

View File

@@ -13,23 +13,26 @@ 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;
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 +217,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;
}

View File

@@ -0,0 +1,111 @@
export interface IBilibiliSearchResult {
id: number;
bvid: string;
title: string;
pic: string;
duration: number | string;
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;
};
}
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;
}

View File

@@ -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>
@@ -99,22 +118,29 @@
</template>
</div>
</n-layout>
<!-- 添加B站视频播放器组件 -->
<bilibili-player v-model:show="showBilibiliPlayer" :bvid="currentBvid" />
</div>
</template>
<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 { getBilibiliProxyUrl, searchBilibili } from '@/api/bilibili';
import { getHotSearch } from '@/api/home';
import { getSearch } from '@/api/search';
import BilibiliPlayer from '@/components/BilibiliPlayer.vue';
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({
@@ -190,6 +216,10 @@ onMounted(() => {
const hotKeyword = ref(route.query.keyword || t('search.title.searchList'));
// 显示B站视频播放器
const showBilibiliPlayer = ref(false);
const currentBvid = ref('');
const loadSearch = async (keywords: any, type: any = null, isLoadMore = false) => {
if (!keywords) return;
@@ -215,61 +245,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 ((type || searchType.value) === 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: type || searchType.value,
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) {
@@ -332,6 +399,12 @@ const handlePlay = () => {
const handleSearchHistory = (keyword: string) => {
loadSearch(keyword, 1);
};
// 处理B站视频播放
const handlePlayBilibili = (item: IBilibiliSearchResult) => {
currentBvid.value = item.bvid;
showBilibiliPlayer.value = true;
};
</script>
<style lang="scss" scoped>