Compare commits

...

9 Commits

Author SHA1 Message Date
alger
573023600a 🌈 style: v3.7.2 2025-01-16 23:27:51 +08:00
Alger
041aad31b4 Merge pull request #47 from algerkong/fix/player-freeze-recovery-46
 feat: 优化播放体验 优化代码 优化歌词缓存
2025-01-16 23:20:57 +08:00
alger
f652932d71 feat: 优化播放体验 优化代码 优化歌词缓存 2025-01-16 23:19:16 +08:00
alger
7efeb9492b 🐞 fix: 修复类型错误 2025-01-16 00:58:57 +08:00
alger
055536eb5c 🌈 style: v3.7.1 2025-01-16 00:46:33 +08:00
Alger
14852fc8d3 Merge pull request #44 from algerkong/fix/minimize-on-space-after-restore-42
🐞 fix: 最小化点击后恢复窗口按空格会继续最小化
2025-01-16 00:43:05 +08:00
Alger
9866e772df Merge pull request #45 from algerkong/fix/repeat-sound-on-lyric-seek-43
🐞 fix: 修复单曲循环后点击歌词快进会有重复的声音播放
2025-01-16 00:42:50 +08:00
alger
87ca0836b1 🐞 fix: 修复单曲循环后点击歌词快进会有重复的声音播放 2025-01-16 00:40:44 +08:00
alger
fa07c5a40c 🐞 fix: 最小化点击后恢复窗口按空格会继续最小化
fixed #42
2025-01-16 00:38:47 +08:00
17 changed files with 428 additions and 3902 deletions

View File

@@ -1,14 +1,9 @@
# 更新日志
## v3.7.0
### ✨ 新功能
- 添加全局快捷键支持以及快捷键管理功能
- 优化设置页面样式以及布局
### 🐞 Bug修复
- 修复弹窗层级问题
- 修复夜间模式下 歌曲收藏样式无效问题
- 优化夜间模式播放按钮颜色
## v3.7.2
### ✨ 优化
- 优化歌词缓存
- 优化音乐播放体验 如果播放失败自动播放下一首
## 咖啡☕️

View File

@@ -1,6 +1,6 @@
{
"name": "AlgerMusicPlayer",
"version": "3.7.0",
"version": "3.7.2",
"description": "Alger Music Player",
"author": "Alger <algerkc@qq.com>",
"main": "./out/main/index.js",

View File

@@ -3,7 +3,6 @@ import { app, ipcMain, nativeImage } from 'electron';
import { join } from 'path';
import { loadLyricWindow } from './lyric';
import { initializeCacheManager } from './modules/cache';
import { initializeConfig } from './modules/config';
import { initializeFileManager } from './modules/fileManager';
import { initializeShortcuts, registerShortcuts } from './modules/shortcuts';
@@ -27,8 +26,6 @@ let mainWindow: Electron.BrowserWindow;
function initialize() {
// 初始化配置管理
initializeConfig();
// 初始化缓存管理
initializeCacheManager();
// 初始化文件管理
initializeFileManager();
// 初始化窗口管理

View File

@@ -317,8 +317,8 @@ async function downloadMusic(
// 等待下载完成
await new Promise((resolve, reject) => {
writer!.on('finish', resolve);
writer!.on('error', reject);
writer!.on('finish', () => resolve(undefined));
writer!.on('error', (error) => reject(error));
response.data.pipe(writer!);
});

View File

@@ -1,9 +1,12 @@
import { musicDB } from '@/hooks/MusicHook';
import store from '@/store';
import type { ILyric } from '@/type/lyric';
import { isElectron } from '@/utils';
import request from '@/utils/request';
import requestMusic from '@/utils/request_music';
const { addData, getData, deleteData } = musicDB;
// 获取音乐音质详情
export const getMusicQualityDetail = (id: number) => {
return request.get('/song/music/detail', { params: { id } });
@@ -37,24 +40,31 @@ export const getMusicDetail = (ids: Array<number>) => {
// 根据音乐Id获取音乐歌词
export const getMusicLrc = async (id: number) => {
if (isElectron) {
// 先尝试从缓存获取
const cachedLyric = await window.api.invoke('get-cached-lyric', id);
console.log('cachedLyric', cachedLyric);
if (cachedLyric) {
return { data: cachedLyric };
const TEN_DAYS_MS = 10 * 24 * 60 * 60 * 1000; // 10天的毫秒数
try {
// 尝试获取缓存的歌词
const cachedLyric = await getData('music_lyric', id);
if (cachedLyric?.createTime && Date.now() - cachedLyric.createTime < TEN_DAYS_MS) {
return { ...cachedLyric };
}
// 获取新的歌词数据
const res = await request.get<ILyric>('/lyric', { params: { id } });
// 只有在成功获取新数据后才删除旧缓存并添加新缓存
if (res?.data) {
if (cachedLyric) {
await deleteData('music_lyric', id);
}
addData('music_lyric', { id, data: res.data, createTime: Date.now() });
}
return res;
} catch (error) {
console.error('获取歌词失败:', error);
throw error; // 向上抛出错误,让调用者处理
}
// 如果缓存中没有,则从服务器获取
const res = await request.get<ILyric>('/lyric', { params: { id } });
// 缓存完整的响应数据
if (isElectron && res) {
await window.api.invoke('cache-lyric', id, res.data);
}
return res;
};
export const getParsingMusicUrl = (id: number, data: any) => {

File diff suppressed because it is too large Load Diff

View File

@@ -106,8 +106,6 @@
</template>
<script setup lang="ts">
import 'animate.css';
import axios from 'axios';
import { computed, onActivated, onMounted, ref } from 'vue';

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) => {

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,22 +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);
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);
});
@@ -95,7 +143,7 @@ const setupAudioListeners = () => {
// 监听暂停
audioService.on('pause', () => {
store.commit('setPlayMusic', false);
clearInterval(interval);
clearInterval();
if (isElectron && isLyricWindowOpen.value) {
sendLyricToWin();
}
@@ -103,14 +151,28 @@ const setupAudioListeners = () => {
// 监听结束
audioService.on('end', () => {
clearInterval();
if (store.state.playMode === 1) {
// 单曲循环模式
sound.value?.play();
if (sound.value) {
sound.value.seek(0);
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 {
@@ -125,14 +187,7 @@ const setupAudioListeners = () => {
}
});
// 监听上一曲/下一曲控制
audioService.on('previoustrack', () => {
store.commit('prevPlay');
});
audioService.on('nexttrack', () => {
store.commit('nextPlay');
});
return clearInterval;
};
export const play = () => {
@@ -197,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();
}
};
@@ -222,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();
@@ -362,12 +466,13 @@ if (isElectron) {
// 在组件挂载时设置监听器
onMounted(() => {
if (isPlaying.value) {
useLyricProgress();
}
});
const clearIntervalFn = setupAudioListeners();
useLyricProgress(); // 直接调用,不需要解构返回值
// 在组件卸载时清理
onUnmounted(() => {
audioService.stop();
// 在组件卸载时清理
onUnmounted(() => {
clearIntervalFn();
audioService.stop();
audioService.clearAllListeners();
});
});

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,

View File

@@ -11,7 +11,12 @@
}
.n-slider-handle-indicator--top {
@apply bg-transparent dark:text-[#ffffffdd] text-[#000000dd] text-2xl px-2 py-1 shadow-none mb-0 !important;
@apply bg-transparent text-2xl px-2 py-1 shadow-none mb-0 dark:text-[#ffffffdd] text-[#000000dd] !important;
mix-blend-mode: difference !important;
}
.v-binder-follower-container:has(.n-slider-handle-indicator--top) {
z-index: 999999999 !important;
}
.text-el {
@@ -56,3 +61,11 @@
--text-color-300: #3d3d3d;
--primary-color: #22c55e;
}
:root {
--text-color: #000000dd;
}
:root[class='dark'] {
--text-color: #ffffffdd;
}

View File

@@ -28,7 +28,6 @@
<meta name="apple-mobile-web-app-title" content="网抑云音乐" />
<!-- 资源预加载 -->
<link rel="preload" href="./assets/icon/iconfont.css" as="style" />
<link rel="preload" href="./assets/css/animate.css" as="style" />
<link rel="preload" href="./assets/css/base.css" as="style" />
<!-- 样式表 -->

View File

@@ -5,6 +5,7 @@
placement="bottom"
:style="{ background: currentBackground || background }"
:to="`#layout-main`"
:z-index="9998"
>
<div id="drawer-target">
<div class="drawer-back"></div>
@@ -31,13 +32,13 @@
}"
>
<span
v-for="(item, index) in playMusic.ar || playMusic.song.artists"
v-for="(item, index) in artistList"
:key="index"
class="cursor-pointer hover:text-green-500"
@click="handleArtistClick(item.id)"
>
{{ item.name }}
{{ index < (playMusic.ar || playMusic.song.artists).length - 1 ? ' / ' : '' }}
{{ index < artistList.length - 1 ? ' / ' : '' }}
</span>
</n-ellipsis>
</div>
@@ -87,6 +88,7 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useStore } from 'vuex';
import {
artistList,
lrcArray,
nowIndex,
playMusic,
@@ -124,14 +126,18 @@ const isVisible = computed({
});
// 歌词滚动方法
const lrcScroll = (behavior = 'smooth') => {
const lrcScroll = (behavior = 'smooth', top: null | number = null) => {
const nowEl = document.querySelector(`#music-lrc-text-${nowIndex.value}`);
if (isVisible.value && !isMouse.value && nowEl && lrcContainer.value) {
const containerRect = lrcContainer.value.getBoundingClientRect();
const nowElRect = nowEl.getBoundingClientRect();
const relativeTop = nowElRect.top - containerRect.top;
const scrollTop = relativeTop - lrcSider.value.$el.getBoundingClientRect().height / 2;
lrcSider.value.scrollTo({ top: scrollTop, behavior });
if (top !== null) {
lrcSider.value.scrollTo({ top, behavior });
} else {
const containerRect = lrcContainer.value.getBoundingClientRect();
const nowElRect = nowEl.getBoundingClientRect();
const relativeTop = nowElRect.top - containerRect.top;
const scrollTop = relativeTop - lrcSider.value.$el.getBoundingClientRect().height / 2;
lrcSider.value.scrollTo({ top: scrollTop, behavior });
}
}
};

View File

@@ -1,7 +1,4 @@
<template>
<!-- 展开全屏 -->
<!-- 底部播放栏 -->
<div
class="music-play-bar"
:class="
@@ -60,13 +57,12 @@
}"
>
<span
v-for="(artists, artistsindex) in playMusic.ar || playMusic.song.artists"
v-for="(artists, artistsindex) in artistList"
:key="artistsindex"
class="cursor-pointer hover:text-green-500"
@click="handleArtistClick(artists.id)"
>
{{ artists.name
}}{{ artistsindex < (playMusic.ar || playMusic.song.artists).length - 1 ? ' / ' : '' }}
{{ artists.name }}{{ artistsindex < artistList.length - 1 ? ' / ' : '' }}
</span>
</n-ellipsis>
</div>
@@ -160,9 +156,11 @@ import { useStore } from 'vuex';
import SongItem from '@/components/common/SongItem.vue';
import {
allTime,
artistList,
isLyricWindowOpen,
nowTime,
openLyric,
playMusic,
sound,
textColors
} from '@/hooks/MusicHook';
@@ -174,12 +172,11 @@ import MusicFull from './MusicFull.vue';
const store = useStore();
// 播放的音乐信息
const playMusic = computed(() => store.state.playMusic as SongResult);
// 是否播放
const play = computed(() => store.state.play as boolean);
// 播放列表
const playList = computed(() => store.state.playList as SongResult[]);
// 背景颜色
const background = ref('#000');
watch(
@@ -190,7 +187,7 @@ watch(
{ immediate: true, deep: true }
);
// 使用 useThrottleFn 创建节流版本的 seek 函数
// 节流版本的 seek 函数
const throttledSeek = useThrottleFn((value: number) => {
if (!sound.value) return;
sound.value.seek(value);

View File

@@ -2,12 +2,12 @@
<div id="title-bar" @mousedown="drag">
<div id="title">Alger Music</div>
<div id="buttons">
<button @click="minimize">
<div class="button" @click="minimize">
<i class="iconfont icon-minisize"></i>
</button>
<button @click="close">
</div>
<div class="button" @click="close">
<i class="iconfont icon-close"></i>
</button>
</div>
</div>
</div>
@@ -107,7 +107,7 @@ const drag = (event: MouseEvent) => {
-webkit-app-region: no-drag;
}
button {
.button {
@apply text-gray-600 dark:text-gray-400 hover:text-green-500;
}

View File

@@ -121,52 +121,79 @@ class AudioService {
}
// 播放控制相关
play(url: string, track: SongResult) {
// Howler.unload();
if (this.currentSound) {
this.currentSound.unload();
}
this.currentSound = null;
this.currentTrack = track;
play(url: string, track: SongResult): Promise<Howl> {
return new Promise((resolve, reject) => {
let retryCount = 0;
const maxRetries = 3;
this.currentSound = new Howl({
src: [url],
html5: true,
autoplay: true,
volume: localStorage.getItem('volume')
? parseFloat(localStorage.getItem('volume') as string)
: 1
const tryPlay = () => {
if (this.currentSound) {
this.currentSound.unload();
}
this.currentSound = null;
this.currentTrack = track;
this.currentSound = new Howl({
src: [url],
html5: true,
autoplay: true,
volume: localStorage.getItem('volume')
? parseFloat(localStorage.getItem('volume') as string)
: 1,
onloaderror: () => {
console.error('Audio load error');
if (retryCount < maxRetries) {
retryCount++;
console.log(`Retrying playback (${retryCount}/${maxRetries})...`);
setTimeout(tryPlay, 1000 * retryCount);
} else {
reject(new Error('音频加载失败,请尝试切换其他歌曲'));
}
},
onplayerror: () => {
console.error('Audio play error');
if (retryCount < maxRetries) {
retryCount++;
console.log(`Retrying playback (${retryCount}/${maxRetries})...`);
setTimeout(tryPlay, 1000 * retryCount);
} else {
reject(new Error('音频播放失败,请尝试切换其他歌曲'));
}
}
});
// 更新媒体会话元数据
this.updateMediaSessionMetadata(track);
// 设置音频事件监听
this.currentSound.on('play', () => {
this.updateMediaSessionState(true);
this.emit('play');
});
this.currentSound.on('pause', () => {
this.updateMediaSessionState(false);
this.emit('pause');
});
this.currentSound.on('end', () => {
this.emit('end');
});
this.currentSound.on('seek', () => {
this.updateMediaSessionPositionState();
this.emit('seek');
});
this.currentSound.on('load', () => {
this.updateMediaSessionPositionState();
this.emit('load');
resolve(this.currentSound as Howl);
});
};
tryPlay();
});
// 更新媒体会话元数据
this.updateMediaSessionMetadata(track);
// 设置音频事件监听
this.currentSound.on('play', () => {
this.updateMediaSessionState(true);
this.emit('play');
});
this.currentSound.on('pause', () => {
this.updateMediaSessionState(false);
this.emit('pause');
});
this.currentSound.on('end', () => {
this.emit('end');
});
this.currentSound.on('seek', () => {
this.updateMediaSessionPositionState();
this.emit('seek');
});
this.currentSound.on('load', () => {
this.updateMediaSessionPositionState();
this.emit('load');
});
return this.currentSound;
}
getCurrentSound() {
@@ -202,6 +229,10 @@ class AudioService {
this.updateMediaSessionPositionState();
}
}
clearAllListeners() {
this.callbacks = {};
}
}
export const audioService = new AudioService();

View File

@@ -160,7 +160,7 @@ interface Album {
picId_str: string;
}
interface Artist {
export interface Artist {
name: string;
id: number;
picId: number;