修复音频播放

This commit is contained in:
小朱
2025-07-11 15:53:37 +08:00
parent 95514e3af6
commit 6164e40fa0
2 changed files with 58 additions and 2 deletions

View File

@@ -117,6 +117,13 @@ const MusicPlayer: React.FC<MusicPlayerProps> = ({ className = '' }) => {
}
}, [currentTrack])
// 组件初始化时如果有持久化的currentTrack确保音频已加载
useEffect(() => {
if (currentTrack && audioRef.current && !audioRef.current.src) {
loadAudioFile(currentTrack)
}
}, [])
// 加载音频文件
const loadAudioFile = async (track: any) => {
if (!audioRef.current) return
@@ -147,7 +154,39 @@ const MusicPlayer: React.FC<MusicPlayerProps> = ({ className = '' }) => {
throw new Error('音频文件为空')
}
const blobUrl = URL.createObjectURL(blob)
// 根据文件扩展名强制设置正确的MIME类型
const extension = track.path.split('.').pop()?.toLowerCase()
let mimeType = 'audio/mpeg' // 默认
switch (extension) {
case 'mp3':
mimeType = 'audio/mpeg'
break
case 'wav':
mimeType = 'audio/wav'
break
case 'ogg':
mimeType = 'audio/ogg'
break
case 'm4a':
mimeType = 'audio/mp4'
break
case 'aac':
mimeType = 'audio/aac'
break
case 'wma':
mimeType = 'audio/x-ms-wma'
break
case 'flac':
mimeType = 'audio/flac'
break
}
console.log('设置MIME类型:', mimeType)
// 创建具有正确MIME类型的新blob
const audioBlob = new Blob([blob], { type: mimeType })
const blobUrl = URL.createObjectURL(audioBlob)
if (audioRef.current) {
audioRef.current.src = blobUrl

View File

@@ -1,4 +1,5 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { FileItem } from '@/types/file'
interface MusicFile extends FileItem {
@@ -36,7 +37,7 @@ interface MusicState {
previousTrack: () => void
}
export const useMusicStore = create<MusicState>((set, get) => ({
export const useMusicStore = create<MusicState>()(persist((set, get) => ({
playlist: [],
currentTrack: null,
currentIndex: 0,
@@ -200,4 +201,20 @@ export const useMusicStore = create<MusicState>((set, get) => ({
isPlaying: false // 让组件重新开始播放
})
}
}), {
name: 'gsm3-music-store',
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({
playlist: state.playlist,
currentTrack: state.currentTrack,
currentIndex: state.currentIndex,
volume: state.volume,
isMuted: state.isMuted,
isShuffled: state.isShuffled,
repeatMode: state.repeatMode,
// 不持久化播放状态和时间相关的数据
// isPlaying: false,
// currentTime: 0,
// duration: 0,
})
}))