Sfoglia il codice sorgente

修复播放列表丢失的问题

chendeben 1 anno fa
parent
commit
5f1143d228

+ 12 - 12
entry/src/main/ets/common/service/DataPersistenceService.ets

@@ -213,7 +213,7 @@ export class DataPersistenceService implements IDataPersistenceService {
       // 如果context有效,尝试保存到PreferencesUtil
       if (this.context) {
         try {
-          await PreferencesUtil.put(key, JSON.stringify(progressData));
+          PreferencesUtil.putSync(key, JSON.stringify(progressData));
         } catch (error) {
           console.log(`Heanup2 DataPersistenceService: 保存播放进度到PreferencesUtil失败: ${error}`);
           LogUtils.getInstance().LOGI(`DataPersistenceService: Failed to save progress to PreferencesUtil: ${error}`);
@@ -255,7 +255,7 @@ export class DataPersistenceService implements IDataPersistenceService {
 
         while (retryCount < maxRetries) {
           try {
-            const progressStr = await PreferencesUtil.getString(key, '');
+            const progressStr = PreferencesUtil.getStringSync(key, '');
             if (progressStr) {
               try {
                 const parsedData = JSON.parse(progressStr) as PlaybackProgress;
@@ -309,7 +309,7 @@ export class DataPersistenceService implements IDataPersistenceService {
       const key = DataPersistenceService.KEYS.PROGRESS_PREFIX + songId;
 
       // 从PreferencesUtil删除
-      await PreferencesUtil.delete(key);
+      PreferencesUtil.deleteSync(key);
 
       // 从AppStorage删除
       AppStorage.delete(key);
@@ -339,7 +339,7 @@ export class DataPersistenceService implements IDataPersistenceService {
       }
 
       // 清空已完成列表
-      await PreferencesUtil.delete(DataPersistenceService.KEYS.COMPLETED_SONGS);
+       PreferencesUtil.deleteSync(DataPersistenceService.KEYS.COMPLETED_SONGS);
       AppStorage.delete(DataPersistenceService.KEYS.COMPLETED_SONGS);
 
       LogUtils.getInstance().LOGI(`DataPersistenceService: Cleared ${completedSongs.length} completed progress records`);
@@ -357,7 +357,7 @@ export class DataPersistenceService implements IDataPersistenceService {
       const completedSongs = await this.getCompletedSongs();
       if (!completedSongs.includes(songId)) {
         completedSongs.push(songId);
-        await PreferencesUtil.put(DataPersistenceService.KEYS.COMPLETED_SONGS, JSON.stringify(completedSongs));
+        PreferencesUtil.putSync(DataPersistenceService.KEYS.COMPLETED_SONGS, JSON.stringify(completedSongs));
         AppStorage.setOrCreate(DataPersistenceService.KEYS.COMPLETED_SONGS, completedSongs);
       }
     } catch (error) {
@@ -375,7 +375,7 @@ export class DataPersistenceService implements IDataPersistenceService {
 
       if (!completedSongs) {
         // 从PreferencesUtil获取
-        const completedStr = await PreferencesUtil.getString(DataPersistenceService.KEYS.COMPLETED_SONGS, '[]');
+        const completedStr = PreferencesUtil.getStringSync(DataPersistenceService.KEYS.COMPLETED_SONGS, '[]');
         try {
           const parsedData = JSON.parse(completedStr) as string[];
           completedSongs = parsedData;
@@ -423,7 +423,7 @@ export class DataPersistenceService implements IDataPersistenceService {
 
         while (retryCount < maxRetries) {
           try {
-            await PreferencesUtil.put(DataPersistenceService.KEYS.PLAYLIST, JSON.stringify(playlistData));
+             PreferencesUtil.putSync(DataPersistenceService.KEYS.PLAYLIST, JSON.stringify(playlistData));
             console.log(`Heanup2 DataPersistenceService: 已保存到PreferencesUtil (尝试 ${retryCount + 1}/${maxRetries})`);
             break; // 成功,跳出循环
           } catch (error) {
@@ -490,7 +490,7 @@ export class DataPersistenceService implements IDataPersistenceService {
 
         while (retryCount < maxRetries) {
           try {
-            const playlistStr = await PreferencesUtil.getString(DataPersistenceService.KEYS.PLAYLIST, '');
+            const playlistStr = PreferencesUtil.getStringSync(DataPersistenceService.KEYS.PLAYLIST, '');
             console.log(`Heanup2 DataPersistenceService: PreferencesUtil返回的字符串长度: ${playlistStr.length} (尝试 ${retryCount + 1}/${maxRetries})`);
 
             if (playlistStr) {
@@ -583,7 +583,7 @@ export class DataPersistenceService implements IDataPersistenceService {
 
         while (retryCount < maxRetries) {
           try {
-            await PreferencesUtil.put(DataPersistenceService.KEYS.PLAYER_STATE, JSON.stringify(stateData));
+            PreferencesUtil.putSync(DataPersistenceService.KEYS.PLAYER_STATE, JSON.stringify(stateData));
             console.log(`Heanup2 DataPersistenceService: 已保存播放状态到PreferencesUtil (尝试 ${retryCount + 1}/${maxRetries})`);
             break; // 成功,跳出循环
           } catch (error) {
@@ -650,7 +650,7 @@ export class DataPersistenceService implements IDataPersistenceService {
 
         while (retryCount < maxRetries) {
           try {
-            const stateStr = await PreferencesUtil.getString(DataPersistenceService.KEYS.PLAYER_STATE, '');
+            const stateStr = PreferencesUtil.getStringSync(DataPersistenceService.KEYS.PLAYER_STATE, '');
             console.log(`Heanup2 DataPersistenceService: PreferencesUtil返回的播放状态字符串长度: ${stateStr.length} (尝试 ${retryCount + 1}/${maxRetries})`);
 
             if (stateStr) {
@@ -721,11 +721,11 @@ export class DataPersistenceService implements IDataPersistenceService {
       }
 
       // 清除播放列表
-      await PreferencesUtil.delete(DataPersistenceService.KEYS.PLAYLIST);
+      PreferencesUtil.deleteSync(DataPersistenceService.KEYS.PLAYLIST);
       AppStorage.delete(DataPersistenceService.KEYS.PLAYLIST);
 
       // 清除播放状态
-      await PreferencesUtil.delete(DataPersistenceService.KEYS.PLAYER_STATE);
+      PreferencesUtil.deleteSync(DataPersistenceService.KEYS.PLAYER_STATE);
       AppStorage.delete(DataPersistenceService.KEYS.PLAYER_STATE);
 
       // 清除所有播放进度

+ 0 - 186
entry/src/main/ets/common/service/DataPersistenceServiceTest.ets

@@ -1,186 +0,0 @@
-import { DataPersistenceService, PlaylistSyncService } from './DataPersistenceService';
-import { VideoItem } from '../../viewmodel/VideoItem';
-import { PlayMode } from './PlayerStateModel';
-import { LogUtils } from '@ohos/ijkplayer';
-
-/**
- * DataPersistenceService 测试类
- * 用于验证数据持久化功能的正确性
- */
-export class DataPersistenceServiceTest {
-  private dataPersistence: DataPersistenceService;
-  private playlistSync: PlaylistSyncService;
-  
-  constructor() {
-    this.dataPersistence = DataPersistenceService.getInstance();
-    this.playlistSync = PlaylistSyncService.getInstance();
-  }
-  
-  /**
-   * 测试播放进度记忆功能
-   */
-  async testPlaybackProgressMemory(): Promise<boolean> {
-    try {
-      const testSongId = 'test_song_001';
-      const testFilePath = '/storage/test/song.mp3';
-      const testPosition = 120000; // 2分钟
-      const testDuration = 300000; // 5分钟
-      
-      // 测试保存播放进度
-      await this.dataPersistence.savePlaybackProgress(testSongId, testFilePath, testPosition, testDuration);
-      LogUtils.getInstance().LOGI('DataPersistenceServiceTest: Progress saved successfully');
-      
-      // 测试加载播放进度
-      const loadedProgress = await this.dataPersistence.loadPlaybackProgress(testSongId);
-      if (!loadedProgress) {
-        LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Failed to load progress');
-        return false;
-      }
-      
-      // 验证数据正确性
-      if (loadedProgress.position !== testPosition || 
-          loadedProgress.duration !== testDuration ||
-          loadedProgress.filePath !== testFilePath) {
-        LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Progress data mismatch');
-        return false;
-      }
-      
-      // 测试清除播放进度
-      await this.dataPersistence.clearPlaybackProgress(testSongId);
-      const clearedProgress = await this.dataPersistence.loadPlaybackProgress(testSongId);
-      if (clearedProgress !== null) {
-        LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Progress not cleared properly');
-        return false;
-      }
-      
-      LogUtils.getInstance().LOGI('DataPersistenceServiceTest: Playback progress memory test passed');
-      return true;
-    } catch (error) {
-      LogUtils.getInstance().LOGE(`DataPersistenceServiceTest: Progress memory test failed: ${error}`);
-      return false;
-    }
-  }
-  
-  /**
-   * 测试播放列表同步功能
-   */
-  async testPlaylistSync(): Promise<boolean> {
-    try {
-      // 创建测试播放列表
-      const testPlaylist: VideoItem[] = [
-        {
-          name: 'Test Song 1',
-          filePath: '/storage/test/song1.mp3',
-          artist: 'Test Artist 1',
-          album: 'Test Album',
-          pixelMapPath: ''
-        } as VideoItem,
-        {
-          name: 'Test Song 2', 
-          filePath: '/storage/test/song2.mp3',
-          artist: 'Test Artist 2',
-          album: 'Test Album',
-          pixelMapPath: ''
-        } as VideoItem
-      ];
-      
-      const testIndex = 1;
-      const testPlayMode = PlayMode.RANDOM;
-      
-      // 测试保存播放列表
-      await this.dataPersistence.savePlaylist(testPlaylist, testIndex, testPlayMode);
-      LogUtils.getInstance().LOGI('DataPersistenceServiceTest: Playlist saved successfully');
-      
-      // 测试加载播放列表
-      const loadedPlaylist = await this.dataPersistence.loadPlaylist();
-      if (!loadedPlaylist) {
-        LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Failed to load playlist');
-        return false;
-      }
-      
-      // 验证数据正确性
-      if (loadedPlaylist.songs.length !== testPlaylist.length ||
-          loadedPlaylist.currentIndex !== testIndex ||
-          loadedPlaylist.playMode !== testPlayMode) {
-        LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Playlist data mismatch');
-        return false;
-      }
-      
-      // 验证歌曲数据
-      for (let i = 0; i < testPlaylist.length; i++) {
-        if (loadedPlaylist.songs[i].name !== testPlaylist[i].name ||
-            loadedPlaylist.songs[i].filePath !== testPlaylist[i].filePath) {
-          LogUtils.getInstance().LOGE(`DataPersistenceServiceTest: Song ${i} data mismatch`);
-          return false;
-        }
-      }
-      
-      LogUtils.getInstance().LOGI('DataPersistenceServiceTest: Playlist sync test passed');
-      return true;
-    } catch (error) {
-      LogUtils.getInstance().LOGE(`DataPersistenceServiceTest: Playlist sync test failed: ${error}`);
-      return false;
-    }
-  }
-  
-  /**
-   * 测试双向同步功能
-   */
-  async testBidirectionalSync(): Promise<boolean> {
-    try {
-      const localPlaylist: VideoItem[] = [
-        {
-          name: 'Local Song',
-          filePath: '/storage/local/song.mp3',
-          artist: 'Local Artist',
-          album: 'Local Album',
-          pixelMapPath: ''
-        } as VideoItem
-      ];
-      
-      const localIndex = 0;
-      const localPlayMode = PlayMode.SEQUENCE;
-      
-      // 测试双向同步
-      const syncedData = await this.playlistSync.bidirectionalSync(localPlaylist, localIndex, localPlayMode);
-      
-      if (!syncedData) {
-        LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Bidirectional sync returned null');
-        return false;
-      }
-      
-      // 验证同步结果
-      if (syncedData.songs.length === 0) {
-        LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Synced playlist is empty');
-        return false;
-      }
-      
-      LogUtils.getInstance().LOGI('DataPersistenceServiceTest: Bidirectional sync test passed');
-      return true;
-    } catch (error) {
-      LogUtils.getInstance().LOGE(`DataPersistenceServiceTest: Bidirectional sync test failed: ${error}`);
-      return false;
-    }
-  }
-  
-  /**
-   * 运行所有测试
-   */
-  async runAllTests(): Promise<boolean> {
-    LogUtils.getInstance().LOGI('DataPersistenceServiceTest: Starting all tests...');
-    
-    const progressTest = await this.testPlaybackProgressMemory();
-    const playlistTest = await this.testPlaylistSync();
-    const syncTest = await this.testBidirectionalSync();
-    
-    const allPassed = progressTest && playlistTest && syncTest;
-    
-    if (allPassed) {
-      LogUtils.getInstance().LOGI('DataPersistenceServiceTest: All tests passed!');
-    } else {
-      LogUtils.getInstance().LOGE('DataPersistenceServiceTest: Some tests failed');
-    }
-    
-    return allPassed;
-  }
-}

+ 35 - 0
entry/src/main/ets/common/service/UnifiedPlayerService.ets

@@ -34,6 +34,10 @@ export interface IPlayerService {
   getPlaylist(): VideoItem[];
   getCurrentIndex(): number;
   
+  // 数据恢复状态
+  isDataRestorationCompleted(): boolean;
+  waitForDataRestoration(maxWaitMs?: number): Promise<boolean>;
+  
   // 播放模式控制 - 基于LocalMusic现有功能
   setPlayMode(mode: number): void;
   getPlayMode(): number;
@@ -73,6 +77,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
   private context: common.UIAbilityContext | null = null;
   private progressTimer: number = -1;
   private isInitialized: boolean = false;
+  private isDataRestored: boolean = false; // 新增:数据恢复完成标识
   private currentRetryCount: number = 0;
 
   private constructor() {
@@ -460,6 +465,24 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
     return this.playlistModel.getCurrentIndex();
   }
 
+  /**
+   * 检查数据是否已从持久化存储恢复
+   */
+  isDataRestorationCompleted(): boolean {
+    return this.isDataRestored;
+  }
+
+  /**
+   * 等待数据恢复完成
+   */
+  async waitForDataRestoration(maxWaitMs: number = 3000): Promise<boolean> {
+    const startTime = Date.now();
+    while (!this.isDataRestored && (Date.now() - startTime) < maxWaitMs) {
+      await new Promise<void>(resolve => setTimeout(resolve, 100));
+    }
+    return this.isDataRestored;
+  }
+
   // 播放模式控制
   setPlayMode(mode: number): void {
     const playMode = mode as PlayMode;
@@ -930,9 +953,15 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
       }
       
       console.log("Heanup2 UnifiedPlayerService: 持久化状态恢复完成");
+      
+      // 设置数据恢复完成标识
+      this.isDataRestored = true;
+      LogUtils.getInstance().LOGI('UnifiedPlayerService: Data restoration completed');
     } catch (error) {
       console.log(`Heanup2 UnifiedPlayerService: 恢复持久化状态时出错: ${error}`);
       LogUtils.getInstance().LOGI(`UnifiedPlayerService restorePersistedState error: ${error}`);
+      // 即使出错也设置为已恢复,避免无限等待
+      this.isDataRestored = true;
     }
   }
   
@@ -1005,6 +1034,12 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
         
         LogUtils.getInstance().LOGI('UnifiedPlayerService: Local playlist updated from storage');
       }
+      
+      // 更新数据恢复状态(如果还没有恢复的话)
+      if (!this.isDataRestored) {
+        this.isDataRestored = true;
+        LogUtils.getInstance().LOGI('UnifiedPlayerService: Data restoration completed via onPlaylistLoaded');
+      }
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService onPlaylistLoaded error: ${error}`);
     }

+ 141 - 11
entry/src/main/ets/view/LocalMusic.ets

@@ -445,12 +445,40 @@ export struct LocalMusic {
   }
 
   // 初始化统一播放器服务
-  private async initUnifiedPlayerService() {
+  private async initUnifiedPlayerService(): Promise<void> {
     try {
       await this.unifiedPlayerService.initialize(this.context);
       
-      // 设置播放列表(如果已有)
-      if (ArrayUtil.isNotEmpty(this.songList)) {
+      // 从UnifiedPlayerService恢复播放列表和状态
+      const restoredPlaylist = this.unifiedPlayerService.getPlaylist();
+      const restoredIndex = this.unifiedPlayerService.getCurrentIndex();
+      const restoredSong = this.unifiedPlayerService.getCurrentSong();
+      
+      if (ArrayUtil.isNotEmpty(restoredPlaylist)) {
+        // 恢复播放列表到LocalMusic
+        this.songList = restoredPlaylist;
+        this.curIndex = restoredIndex;
+        this.currentSong = restoredSong || undefined;
+        
+        // 同步到AppStorage
+        AppStorage.setOrCreate('songList', this.songList);
+        AppStorage.setOrCreate('currIndex', this.curIndex);
+        AppStorage.setOrCreate('currentSong', this.currentSong);
+        
+        // 更新UI数据源
+        this.sonDataSource.pushArrayData(this.songList);
+        
+        // 如果有当前歌曲,更新UI显示
+        if (this.currentSong) {
+          this.videoUrl = this.currentSong.filePath;
+          this.name = this.currentSong.name;
+          this.artist = this.currentSong.artist;
+          this.cover = this.currentSong.pixelMapPath;
+        }
+        
+        LogUtils.getInstance().LOGI(`LocalMusic: Restored playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}`);
+      } else if (ArrayUtil.isNotEmpty(this.songList)) {
+        // 如果LocalMusic有播放列表但UnifiedPlayerService没有,设置到服务中
         this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
       }
       
@@ -547,12 +575,81 @@ export struct LocalMusic {
       this.unifiedPlayerService.addStateListener(stateListener);
       
       LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService initialized successfully');
+      
+      // 初始化完成后,开始加载本地文件
+      this.loadLocalFilesAfterServiceInit();
     } catch (error) {
       LogUtils.getInstance().LOGI(`LocalMusic: Failed to initialize UnifiedPlayerService: ${error}`);
       ToastUtil.showToast('播放器服务初始化失败');
+      
+      // 即使服务初始化失败,也要加载本地文件
+      this.loadLocalFilesAfterServiceInit();
     }
   }
 
+  private loadLocalFilesAfterServiceInit() {
+    // 加载本地文件,然后恢复播放列表
+    this.getSortedFiles(this.rootPath).then(async () => {
+      this.isFavMusic = false;
+      
+      // 等待UnifiedPlayerService完成数据恢复
+      LogUtils.getInstance().LOGI('LocalMusic: Waiting for UnifiedPlayerService data restoration...');
+      const dataRestored: boolean = await this.unifiedPlayerService.waitForDataRestoration(3000);
+      
+      if (dataRestored) {
+        LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService data restoration completed');
+      } else {
+        LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService data restoration timeout, proceeding anyway');
+      }
+      
+      // 尝试从UnifiedPlayerService恢复播放列表
+      const unifiedPlaylist = this.unifiedPlayerService.getPlaylist();
+      const unifiedIndex = this.unifiedPlayerService.getCurrentIndex();
+      const unifiedSong = this.unifiedPlayerService.getCurrentSong();
+      
+      if (ArrayUtil.isNotEmpty(unifiedPlaylist)) {
+        // 使用UnifiedPlayerService的数据
+        this.songList = unifiedPlaylist;
+        this.curIndex = unifiedIndex;
+        this.currentSong = unifiedSong || undefined;
+        LogUtils.getInstance().LOGI(`LocalMusic: Using playlist from UnifiedPlayerService - ${this.songList.length} songs`);
+      } else {
+        // 回退到旧的存储方式
+        LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService playlist empty, falling back to legacy storage');
+        this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
+        this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
+        if (ArrayUtil.isEmpty(this.songList)) {
+          this.songList = this.getCurFileList()
+        } else {
+          this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
+        }
+        LogUtils.getInstance().LOGI(`LocalMusic: Using legacy playlist storage - ${this.songList.length} songs`);
+      }
+      
+      // 同步播放列表和当前索引到AppStorage,确保卡片能访问
+      AppStorage.setOrCreate('songList', this.songList);
+      AppStorage.setOrCreate('currIndex', this.curIndex);
+      
+      if (ArrayUtil.isNotEmpty(this.songList)) {
+        this.isFirstStartPlay = true
+        this.sonDataSource.pushArrayData(this.songList)
+        if (this.currentSong === undefined) {
+          this.isFirstStartPlay = false
+          this.currentSong = this.songList[0]
+        }
+        this.videoUrl = this.currentSong.filePath
+        this.name = this.currentSong.name
+        this.cover = this.currentSong.pixelMapPath
+        this.artist = this.currentSong.artist
+        
+        // 同步当前歌曲到AppStorage
+        AppStorage.setOrCreate('currentSong', this.currentSong);
+        
+        LogUtils.getInstance().LOGI(`LocalMusic: Playlist restored - ${this.songList.length} songs, current: ${this.currentSong.name}`);
+      }
+    });
+  }
+
   // 组件生命周期
   aboutToAppear() {
     if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
@@ -568,10 +665,12 @@ export struct LocalMusic {
     this.packName = AppUtil.getBundleName()
     this.loadCacheFromStorage(); // 加载缓存
 
-    // 初始化统一播放器服务
-    this.initUnifiedPlayerService();
+    // 初始化统一播放器服务,然后加载文件
+    this.initUnifiedPlayerService().then(() => {
+      this.mkDownLoadDir();
+    });
 
-    this.mkDownLoadDir()
+    // 注意:getSortedFiles的调用已经移到initUnifiedPlayerService完成后
 
     let eventMusic: emitter.InnerEvent = { eventId: 2 }
     // 监听广播事件(打开其他应用处理)
@@ -938,12 +1037,27 @@ export struct LocalMusic {
       //穿山甲
       // this.loadBannerAd(CSJUtil.getBannerID())
 
-      this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
-      this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
-      if (ArrayUtil.isEmpty(this.songList)) {
-        this.songList = this.getCurFileList()
+      // 优先从UnifiedPlayerService恢复播放列表,如果没有则从旧的存储恢复
+      const unifiedPlaylist = this.unifiedPlayerService.getPlaylist();
+      const unifiedIndex = this.unifiedPlayerService.getCurrentIndex();
+      const unifiedSong = this.unifiedPlayerService.getCurrentSong();
+      
+      if (ArrayUtil.isNotEmpty(unifiedPlaylist)) {
+        // 使用UnifiedPlayerService的数据
+        this.songList = unifiedPlaylist;
+        this.curIndex = unifiedIndex;
+        this.currentSong = unifiedSong || undefined;
+        LogUtils.getInstance().LOGI(`LocalMusic: Using playlist from UnifiedPlayerService - ${this.songList.length} songs`);
       } else {
-        this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
+        // 回退到旧的存储方式
+        this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
+        this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
+        if (ArrayUtil.isEmpty(this.songList)) {
+          this.songList = this.getCurFileList()
+        } else {
+          this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
+        }
+        LogUtils.getInstance().LOGI(`LocalMusic: Using legacy playlist storage - ${this.songList.length} songs`);
       }
       
       // 同步播放列表和当前索引到AppStorage,确保卡片能访问
@@ -1252,6 +1366,22 @@ export struct LocalMusic {
         }
       }
       this.dataSource.pushArrayData(this.videoLocalList)
+      
+      // 如果当前有播放列表,更新播放列表到统一播放器服务
+      if (ArrayUtil.isNotEmpty(this.songList)) {
+        const globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
+        if (ArrayUtil.isNotEmpty(globalVideoList)) {
+          this.songList = globalVideoList;
+          AppStorage.setOrCreate('songList', this.songList);
+          this.sonDataSource.pushArrayData(this.songList);
+          
+          // 同步到统一播放器服务进行持久化
+          this.syncPlaylistToService();
+          
+          LogUtils.getInstance().LOGI(`LocalMusic: updateListData - Updated playlist with ${this.songList.length} songs`);
+        }
+      }
+      
       animateTo({ duration: 888 }, () => {
         this.opacityItem = 1;
       });