feat: 优化播放体验 优化代码 优化歌词缓存

This commit is contained in:
alger
2025-01-16 23:19:16 +08:00
parent 7efeb9492b
commit f652932d71
14 changed files with 440 additions and 3893 deletions
+48 -41
View File
@@ -1,24 +1,29 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ref } from 'vue';
// 定义表配置的泛型接口
export interface StoreConfig<T extends string> {
name: T;
keyPath?: string;
}
// 创建一个使用 IndexedDB 的组合函数
const useIndexedDB = () => {
const db = ref<IDBDatabase | null>(null); // 数据库引用
const useIndexedDB = async <T extends string, S extends Record<T, Record<string, any>>>(
dbName: string,
stores: StoreConfig<T>[],
version: number = 1
) => {
const db = ref<IDBDatabase | null>(null);
// 打开数据库并创建表
const initDB = (
dbName: string,
version: number,
stores: { name: string; keyPath?: string }[]
) => {
const initDB = () => {
return new Promise<void>((resolve, reject) => {
const request = indexedDB.open(dbName, version); // 打开数据库请求
const request = indexedDB.open(dbName, version);
request.onupgradeneeded = (event: any) => {
const db = event.target.result; // 获取数据库实例
const db = event.target.result;
stores.forEach((store) => {
if (!db.objectStoreNames.contains(store.name)) {
// 确保对象存储(表)创建
db.createObjectStore(store.name, {
keyPath: store.keyPath || 'id',
autoIncrement: true
@@ -28,39 +33,41 @@ const useIndexedDB = () => {
};
request.onsuccess = (event: any) => {
db.value = event.target.result; // 保存数据库实例
resolve(); // 成功时解析 Promise
db.value = event.target.result;
resolve();
};
request.onerror = (event: any) => {
reject(event.target.error); // 失败时拒绝 Promise
reject(event.target.error);
};
});
};
// 通用新增数据
const addData = (storeName: string, value: any) => {
return new Promise<void>((resolve, reject) => {
if (!db.value) return reject('数据库未初始化'); // 检查数据库是否已初始化
const tx = db.value.transaction(storeName, 'readwrite'); // 创建事务
const store = tx.objectStore(storeName); // 获取对象存储
await initDB();
const request = store.add(value); // 添加数据请求
// 通用新增数据
const addData = <K extends T>(storeName: K, value: S[K]) => {
return new Promise<void>((resolve, reject) => {
if (!db.value) return reject('数据库未初始化');
const tx = db.value.transaction(storeName, 'readwrite');
const store = tx.objectStore(storeName);
const request = store.add(value);
request.onsuccess = () => {
console.log('成功'); // 成功时输出
resolve(); // 解析 Promise
console.log('成功');
resolve();
};
request.onerror = (event) => {
console.error('新增失败:', (event.target as IDBRequest).error); // 输出错误
reject((event.target as IDBRequest).error); // 拒绝 Promise
console.error('新增失败:', (event.target as IDBRequest).error);
reject((event.target as IDBRequest).error);
};
});
};
// 通用保存数据(新增或更新)
const saveData = (storeName: string, value: any) => {
const saveData = <K extends T>(storeName: K, value: S[K]) => {
return new Promise<void>((resolve, reject) => {
if (!db.value) return reject('数据库未初始化');
const tx = db.value.transaction(storeName, 'readwrite');
@@ -79,8 +86,8 @@ const useIndexedDB = () => {
};
// 通用获取数据
const getData = (storeName: string, key: string | number) => {
return new Promise<any>((resolve, reject) => {
const getData = <K extends T>(storeName: K, key: string | number) => {
return new Promise<S[K]>((resolve, reject) => {
if (!db.value) return reject('数据库未初始化');
const tx = db.value.transaction(storeName, 'readonly');
const store = tx.objectStore(storeName);
@@ -101,7 +108,7 @@ const useIndexedDB = () => {
};
// 删除数据
const deleteData = (storeName: string, key: string | number) => {
const deleteData = <K extends T>(storeName: K, key: string | number) => {
return new Promise<void>((resolve, reject) => {
if (!db.value) return reject('数据库未初始化');
const tx = db.value.transaction(storeName, 'readwrite');
@@ -120,8 +127,8 @@ const useIndexedDB = () => {
};
// 查询所有数据
const getAllData = (storeName: string) => {
return new Promise<any[]>((resolve, reject) => {
const getAllData = <K extends T>(storeName: K) => {
return new Promise<S[K][]>((resolve, reject) => {
if (!db.value) return reject('数据库未初始化');
const tx = db.value.transaction(storeName, 'readonly');
const store = tx.objectStore(storeName);
@@ -142,29 +149,29 @@ const useIndexedDB = () => {
};
// 分页查询数据
const getDataWithPagination = (storeName: string, page: number, pageSize: number) => {
return new Promise<any[]>((resolve, reject) => {
const getDataWithPagination = <K extends T>(storeName: K, page: number, pageSize: number) => {
return new Promise<S[K][]>((resolve, reject) => {
if (!db.value) return reject('数据库未初始化');
const tx = db.value.transaction(storeName, 'readonly');
const store = tx.objectStore(storeName);
const request = store.openCursor(); // 打开游标请求
const results: any[] = []; // 存储结果的数组
let index = 0; // 当前索引
const skip = (page - 1) * pageSize; // 计算跳过的数量
const request = store.openCursor();
const results: S[K][] = [];
let index = 0;
const skip = (page - 1) * pageSize;
request.onsuccess = (event: any) => {
const cursor = event.target.result; // 获取游标
const cursor = event.target.result;
if (!cursor) {
resolve(results); // 如果没有更多数据,解析结果
resolve(results);
return;
}
if (index >= skip && results.length < pageSize) {
results.push(cursor.value); // 添加当前游标值到结果
results.push(cursor.value);
}
index++; // 增加索引
cursor.continue(); // 继续游标
index++;
cursor.continue();
};
request.onerror = (event: any) => {
+139 -49
View File
@@ -1,8 +1,9 @@
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import useIndexedDB from '@/hooks/IndexDBHook';
import { audioService } from '@/services/audioService';
import store from '@/store';
import type { ILyricText, SongResult } from '@/type/music';
import type { Artist, ILyricText, SongResult } from '@/type/music';
import { isElectron } from '@/utils';
import { getTextColors } from '@/utils/linearColor';
@@ -19,6 +20,15 @@ export const playMusic = computed(() => store.state.playMusic as SongResult); //
export const sound = ref<Howl | null>(audioService.getCurrentSound());
export const isLyricWindowOpen = ref(false); // 新增状态
export const textColors = ref<any>(getTextColors());
export const artistList = computed(
() => (store.state.playMusic.ar || store.state.playMusic?.song?.artists) as Artist[]
);
export const musicDB = await useIndexedDB('musicDB', [
{ name: 'music', keyPath: 'id' },
{ name: 'music_lyric', keyPath: 'id' },
{ name: 'api_cache', keyPath: 'id' }
]);
document.onkeyup = (e) => {
// 检查事件目标是否是输入框元素
@@ -43,10 +53,18 @@ document.onkeyup = (e) => {
watch(
() => store.state.playMusicUrl,
(newVal) => {
async (newVal) => {
if (newVal && playMusic.value) {
sound.value = audioService.play(newVal, playMusic.value);
setupAudioListeners();
try {
const newSound = await audioService.play(newVal, playMusic.value);
sound.value = newSound as Howl;
setupAudioListeners();
} catch (error) {
console.error('播放音频失败:', error);
store.commit('setPlayMusic', false);
// 下一首
store.commit('nextPlay');
}
}
}
);
@@ -72,26 +90,52 @@ watch(
const setupAudioListeners = () => {
let interval: any = null;
const clearInterval = () => {
if (interval) {
window.clearInterval(interval);
interval = null;
}
};
// 清理所有事件监听器
audioService.clearAllListeners();
// 监听播放
audioService.on('play', () => {
store.commit('setPlayMusic', true);
if (interval) clearInterval(interval);
interval = setInterval(() => {
nowTime.value = sound.value?.seek() as number;
allTime.value = sound.value?.duration() as number;
const newIndex = getLrcIndex(nowTime.value);
if (newIndex !== nowIndex.value) {
nowIndex.value = newIndex;
currentLrcProgress.value = 0;
clearInterval();
interval = window.setInterval(() => {
try {
const currentSound = sound.value;
if (!currentSound || typeof currentSound.seek !== 'function') {
console.error('Invalid sound object or seek function');
clearInterval();
return;
}
const currentTime = currentSound.seek() as number;
if (typeof currentTime !== 'number' || Number.isNaN(currentTime)) {
console.error('Invalid current time:', currentTime);
clearInterval();
return;
}
nowTime.value = currentTime;
allTime.value = currentSound.duration() as number;
const newIndex = getLrcIndex(nowTime.value);
if (newIndex !== nowIndex.value) {
nowIndex.value = newIndex;
currentLrcProgress.value = 0;
if (isElectron && isLyricWindowOpen.value) {
sendLyricToWin();
}
}
if (isElectron && isLyricWindowOpen.value) {
sendLyricToWin();
}
}
if (isElectron && isLyricWindowOpen.value) {
sendLyricToWin();
} catch (error) {
console.error('Error in interval:', error);
clearInterval();
}
}, 50);
});
@@ -99,10 +143,7 @@ const setupAudioListeners = () => {
// 监听暂停
audioService.on('pause', () => {
store.commit('setPlayMusic', false);
if (interval) {
clearInterval(interval);
interval = null;
}
clearInterval();
if (isElectron && isLyricWindowOpen.value) {
sendLyricToWin();
}
@@ -110,22 +151,28 @@ const setupAudioListeners = () => {
// 监听结束
audioService.on('end', () => {
if (interval) {
clearInterval(interval);
interval = null;
}
clearInterval();
if (store.state.playMode === 1) {
// 单曲循环模式
if (sound.value) {
sound.value.seek(0);
sound.value.play();
try {
sound.value.play();
} catch (error) {
console.error('Error replaying song:', error);
store.commit('nextPlay');
}
}
} else if (store.state.playMode === 2) {
// 随机播放模式
const { playList } = store.state;
if (playList.length <= 1) {
sound.value?.play();
try {
sound.value?.play();
} catch (error) {
console.error('Error replaying song:', error);
}
} else {
let randomIndex;
do {
@@ -140,14 +187,7 @@ const setupAudioListeners = () => {
}
});
// 监听上一曲/下一曲控制
audioService.on('previoustrack', () => {
store.commit('prevPlay');
});
audioService.on('nexttrack', () => {
store.commit('nextPlay');
});
return clearInterval;
};
export const play = () => {
@@ -212,20 +252,47 @@ export const useLyricProgress = () => {
let animationFrameId: number | null = null;
const updateProgress = () => {
if (!isPlaying.value) return;
if (!isPlaying.value) {
stopProgressAnimation();
return;
}
const currentSound = sound.value;
if (!currentSound) return;
if (!currentSound || typeof currentSound.seek !== 'function') {
console.error('Invalid sound object or seek function');
stopProgressAnimation();
return;
}
const { start, end } = currentLrcTiming.value;
const duration = end - start;
const elapsed = (currentSound.seek() as number) - start;
currentLrcProgress.value = Math.min(Math.max((elapsed / duration) * 100, 0), 100);
try {
const { start, end } = currentLrcTiming.value;
if (typeof start !== 'number' || typeof end !== 'number' || start === end) {
return;
}
const currentTime = currentSound.seek() as number;
if (typeof currentTime !== 'number' || Number.isNaN(currentTime)) {
console.error('Invalid current time:', currentTime);
return;
}
const elapsed = currentTime - start;
const duration = end - start;
const progress = (elapsed / duration) * 100;
// 确保进度在 0-100 之间
currentLrcProgress.value = Math.min(Math.max(progress, 0), 100);
} catch (error) {
console.error('Error updating progress:', error);
}
// 继续下一帧更新
animationFrameId = requestAnimationFrame(updateProgress);
};
const startProgressAnimation = () => {
if (!animationFrameId && isPlaying.value) {
stopProgressAnimation(); // 先停止之前的动画
if (isPlaying.value) {
updateProgress();
}
};
@@ -237,8 +304,30 @@ export const useLyricProgress = () => {
}
};
watch(isPlaying, (newIsPlaying) => {
if (newIsPlaying) {
// 监听播放状态变化
watch(
isPlaying,
(newIsPlaying) => {
if (newIsPlaying) {
startProgressAnimation();
} else {
stopProgressAnimation();
}
},
{ immediate: true }
);
// 监听当前歌词索引变化
watch(nowIndex, () => {
currentLrcProgress.value = 0;
if (isPlaying.value) {
startProgressAnimation();
}
});
// 监听音频对象变化
watch(sound, (newSound) => {
if (newSound && isPlaying.value) {
startProgressAnimation();
} else {
stopProgressAnimation();
@@ -377,12 +466,13 @@ if (isElectron) {
// 在组件挂载时设置监听器
onMounted(() => {
if (isPlaying.value) {
useLyricProgress();
}
});
const clearIntervalFn = setupAudioListeners();
useLyricProgress(); // 直接调用,不需要解构返回值
// 在组件卸载时清理
onUnmounted(() => {
audioService.stop();
// 在组件卸载时清理
onUnmounted(() => {
clearIntervalFn();
audioService.stop();
audioService.clearAllListeners();
});
});
+85 -30
View File
@@ -1,5 +1,6 @@
import { Howl } from 'howler';
import { cloneDeep } from 'lodash';
import { ref } from 'vue';
import { getMusicLrc, getMusicUrl, getParsingMusicUrl } from '@/api/music';
import { useMusicHistory } from '@/hooks/MusicHistoryHook';
@@ -63,43 +64,91 @@ export const useMusicListHook = () => {
fetchSongs(state, playListIndex + 1, playListIndex + 6);
};
const preloadingSounds = ref<Howl[]>([]);
// 用于预加载下一首歌曲的 MP3 数据
const preloadNextSong = (nextSongUrl: string) => {
const sound = new Howl({
src: [nextSongUrl],
html5: true,
preload: true,
autoplay: false
});
return sound;
try {
// 限制同时预加载的数量
if (preloadingSounds.value.length >= 2) {
const oldestSound = preloadingSounds.value.shift();
if (oldestSound) {
oldestSound.unload();
}
}
const sound = new Howl({
src: [nextSongUrl],
html5: true,
preload: true,
autoplay: false
});
preloadingSounds.value.push(sound);
// 添加加载错误处理
sound.on('loaderror', () => {
console.error('预加载音频失败:', nextSongUrl);
const index = preloadingSounds.value.indexOf(sound);
if (index > -1) {
preloadingSounds.value.splice(index, 1);
}
sound.unload();
});
return sound;
} catch (error) {
console.error('预加载音频出错:', error);
return null;
}
};
const fetchSongs = async (state: any, startIndex: number, endIndex: number) => {
const songs = state.playList.slice(
Math.max(0, startIndex),
Math.min(endIndex, state.playList.length)
);
try {
const songs = state.playList.slice(
Math.max(0, startIndex),
Math.min(endIndex, state.playList.length)
);
const detailedSongs = await Promise.all(
songs.map(async (song: SongResult) => {
// 如果歌曲详情已经存在,就不重复请求
if (!song.playMusicUrl) {
return await getSongDetail(song);
const detailedSongs = await Promise.all(
songs.map(async (song: SongResult) => {
try {
// 如果歌曲详情已经存在,就不重复请求
if (!song.playMusicUrl) {
return await getSongDetail(song);
}
return song;
} catch (error) {
console.error('获取歌曲详情失败:', error);
return song;
}
})
);
// 加载下一首的歌词
const nextSong = detailedSongs[0];
if (nextSong && !(nextSong.lyric && nextSong.lyric.lrcTimeArray.length > 0)) {
try {
nextSong.lyric = await loadLrc(nextSong.id);
} catch (error) {
console.error('加载歌词失败:', error);
}
return song;
})
);
// 加载下一首的歌词
const nextSong = detailedSongs[0];
if (!(nextSong.lyric && nextSong.lyric.lrcTimeArray.length > 0)) {
nextSong.lyric = await loadLrc(nextSong.id);
}
}
// 更新播放列表中的歌曲详情
detailedSongs.forEach((song, index) => {
state.playList[startIndex + index] = song;
});
preloadNextSong(nextSong.playMusicUrl);
// 更新播放列表中的歌曲详情
detailedSongs.forEach((song, index) => {
if (song && startIndex + index < state.playList.length) {
state.playList[startIndex + index] = song;
}
});
// 只预加载下一首歌曲
if (nextSong && nextSong.playMusicUrl) {
preloadNextSong(nextSong.playMusicUrl);
}
} catch (error) {
console.error('获取歌曲列表失败:', error);
}
};
const nextPlay = async (state: any) => {
@@ -153,7 +202,7 @@ export const useMusicListHook = () => {
const { lyrics, times } = parseLyrics(data.lrc.lyric);
const tlyric: Record<string, string> = {};
if (data.tlyric.lyric) {
if (data.tlyric && data.tlyric.lyric) {
const { lyrics: tLyrics, times: tTimes } = parseLyrics(data.tlyric.lyric);
tLyrics.forEach((lyric, index) => {
tlyric[tTimes[index].toString()] = lyric.text;
@@ -193,6 +242,12 @@ export const useMusicListHook = () => {
audioService.getCurrentSound()?.pause();
};
// 在组件卸载时清理预加载的音频
onUnmounted(() => {
preloadingSounds.value.forEach((sound) => sound.unload());
preloadingSounds.value = [];
});
return {
handlePlayMusic,
nextPlay,