Explorar el Código

修复歌曲列表错乱

chendeben hace 1 año
padre
commit
ab7a3aba29

+ 57 - 7
entry/src/main/ets/common/service/PlaylistModel.ets

@@ -181,6 +181,10 @@ export class PlaylistModel {
    * 播放列表操作:替换整个播放列表
    */
   replaceSongs(songs: VideoItem[], currentIndex: number = 0): void {
+    // 记录调用栈信息以便调试
+    const stack = new Error().stack || 'No stack available';
+    const caller = stack.split('\n')[2] || 'Unknown caller';
+    
     this.songs = [];
     for (const song of songs) {
       this.songs.push(song);
@@ -188,7 +192,21 @@ export class PlaylistModel {
     this.currentIndex = Math.max(0, Math.min(currentIndex, songs.length - 1));
     this.playedIndices.clear();
     this.playHistory = [];
-    LogUtils.getInstance().LOGI(`PlaylistModel: Playlist replaced with ${songs.length} songs, index ${this.currentIndex}`);
+    
+    // 添加验证日志,包含调用源信息
+    const currentSong = this.getCurrentSong();
+    LogUtils.getInstance().LOGI(`PlaylistModel: Playlist replaced with ${songs.length} songs, index ${this.currentIndex}, current song: ${currentSong?.name || 'null'}, caller: ${caller.trim()}`);
+    
+    // 如果播放列表突然变小,记录更详细的信息
+    if (songs.length <= 20) {
+      LogUtils.getInstance().LOGI(`PlaylistModel: Small playlist detected (${songs.length} songs), caller stack: ${stack.substring(0, 500)}`);
+      LogUtils.getInstance().LOGI(`PlaylistModel: First few songs: ${songs.slice(0, 5).map(s => s.name).join(', ')}`);
+    }
+    
+    // 如果索引无效,记录警告
+    if (currentIndex >= 0 && currentIndex < songs.length && this.currentIndex !== currentIndex) {
+      LogUtils.getInstance().LOGI(`PlaylistModel: Warning - requested index ${currentIndex} adjusted to ${this.currentIndex}`);
+    }
   }
 
   /**
@@ -329,21 +347,53 @@ export class PlaylistModel {
    * 导航操作:移动到下一首
    */
   moveToNext(playMode: PlayMode = PlayMode.SEQUENCE): boolean {
-    const nextSong = this.getNext(playMode);
-    if (!nextSong) return false;
+    if (this.isEmpty()) return false;
     
-    // 添加当前歌曲到播放历史
+    let nextIndex = this.currentIndex;
+    
+    // 添加当前歌曲到播放历史(随机模式)
     const currentSong = this.getCurrentSong();
     if (currentSong && playMode === PlayMode.RANDOM) {
       this.addToPlayHistory(currentSong);
       this.playedIndices.add(this.currentIndex);
     }
     
+    // 直接计算下一个索引,而不依赖getNext方法
+    switch (playMode) {
+      case PlayMode.SINGLE_REPEAT:
+        // 单曲循环,索引不变
+        LogUtils.getInstance().LOGI(`PlaylistModel: Single repeat mode, staying at index ${this.currentIndex}`);
+        return true;
+      case PlayMode.SEQUENCE:
+        // 顺序播放,循环到开头
+        nextIndex = (this.currentIndex + 1) % this.songs.length;
+        break;
+      case PlayMode.NORMAL:
+        // 正常播放,不循环
+        if (this.currentIndex < this.songs.length - 1) {
+          nextIndex = this.currentIndex + 1;
+        } else {
+          LogUtils.getInstance().LOGI('PlaylistModel: Already at last song in normal mode');
+          return false; // 已经是最后一首
+        }
+        break;
+      case PlayMode.RANDOM:
+        // 随机播放
+        nextIndex = this.getRandomNextIndex();
+        if (nextIndex === -1) {
+          LogUtils.getInstance().LOGI('PlaylistModel: No available random song');
+          return false;
+        }
+        break;
+      default:
+        return false;
+    }
+    
     // 更新索引
-    const nextIndex = this.songs.findIndex(song => song.filePath === nextSong.filePath);
-    if (nextIndex !== -1) {
+    if (nextIndex >= 0 && nextIndex < this.songs.length) {
+      const oldIndex = this.currentIndex;
       this.currentIndex = nextIndex;
-      LogUtils.getInstance().LOGI(`PlaylistModel: Moved to next song at index ${this.currentIndex}`);
+      LogUtils.getInstance().LOGI(`PlaylistModel: Moved to next song from index ${oldIndex} to ${this.currentIndex}`);
       return true;
     }
     

+ 106 - 51
entry/src/main/ets/common/service/UnifiedPlayerService.ets

@@ -287,6 +287,52 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
     }
   }
 
+  /**
+   * 直接播放新歌曲,避免恢复逻辑干扰
+   * 专为 playNext/playPrevious 设计
+   */
+  private async playNewSongDirectly(song: VideoItem | null): Promise<void> {
+    if (!song) {
+      throw new Error('No song provided for direct play');
+    }
+    
+    LogUtils.getInstance().LOGI(`UnifiedPlayerService: Starting direct play for ${song.name}`);
+    
+    this.stateModel.updateLoadingState(true);
+    
+    const playerInstance = this.playerManager.getIjkPlayer();
+    if (!playerInstance) {
+      throw new Error('Player not initialized');
+    }
+
+    // 检查文件是否存在(对于本地文件)
+    if (!song.filePath.startsWith('http')) {
+      const fileExists = await this.checkFileExists(song.filePath);
+      if (!fileExists) {
+        throw new Error(`File not found: ${song.filePath}`);
+      }
+    }
+
+    // 设置播放源和配置
+    await this.setupPlayerForSong(song);
+    
+    // 准备播放器
+    const preparedPlayer = this.playerManager.getIjkPlayer();
+    if (preparedPlayer) {
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService: Preparing async for ${song.name}`);
+      preparedPlayer.prepareAsync();
+      // 注意:实际播放和状态更新会在 onPrepared 回调中开始
+    }
+    
+    // 新歌曲不需要恢复播放位置,从头开始播放
+    // this.restorePlaybackPosition(song); // 注释掉这行
+    
+    // 重置重试计数
+    this.currentRetryCount = 0;
+    
+    LogUtils.getInstance().LOGI(`UnifiedPlayerService: Started direct playing ${song.name}`);
+  }
+
   async pause(): Promise<void> {
     try {
       this.savePlaybackPosition();
@@ -352,27 +398,39 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
         return;
       }
 
+      // 先获取当前歌曲信息用于日志
+      const currentSong = this.playlistModel.getCurrentSong();
+      const currentIndex = this.playlistModel.getCurrentIndex();
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService: Moving from index ${currentIndex} (${currentSong?.name || 'unknown'})`);
+
       const moved = this.playlistModel.moveToNext(playMode);
       if (!moved) {
         LogUtils.getInstance().LOGI('UnifiedPlayerService: Failed to move to next song');
         return;
       }
 
-      this.stateModel.updateCurrentIndex(this.playlistModel.getCurrentIndex());
+      // 更新状态模型的索引
+      const newIndex = this.playlistModel.getCurrentIndex();
+      const newSong = this.playlistModel.getCurrentSong();
+      this.stateModel.updateCurrentIndex(newIndex);
       
-      // 停止当前播放并开始新歌曲
+      if (newSong) {
+        LogUtils.getInstance().LOGI(`UnifiedPlayerService: Moved to index ${newIndex} (${newSong.name})`);
+        this.stateModel.updateCurrentSong(newSong);
+      }
+      
+      // 停止当前播放
       await this.stop();
-      await this.startPlayOrResumePlay();
+      
+      // 直接播放新歌曲,不调用通用的恢复逻辑
+      await this.playNewSongDirectly(newSong);
       
       // 更新状态模型中的播放列表状态
       this.updatePlaylistStateInModel();
       
-      // 通知歌曲变化
-      const currentSong = this.playlistModel.getCurrentSong();
-      if (currentSong) {
-        this.stateModel.updateCurrentSong(currentSong);
-        // 强制更新卡片显示新歌曲(重要事件)
-        await this.updateWidgetsForSongChange(currentSong, true);
+      // 强制更新卡片显示新歌曲(重要事件)
+      if (newSong) {
+        await this.updateWidgetsForSongChange(newSong, true);
       }
       
       LogUtils.getInstance().LOGI('UnifiedPlayerService: Moved to next song');
@@ -391,27 +449,39 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
         return;
       }
 
+      // 先获取当前歌曲信息用于日志
+      const currentSong = this.playlistModel.getCurrentSong();
+      const currentIndex = this.playlistModel.getCurrentIndex();
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService: Moving from index ${currentIndex} (${currentSong?.name || 'unknown'})`);
+
       const moved = this.playlistModel.moveToPrevious(playMode);
       if (!moved) {
         LogUtils.getInstance().LOGI('UnifiedPlayerService: Failed to move to previous song');
         return;
       }
 
-      this.stateModel.updateCurrentIndex(this.playlistModel.getCurrentIndex());
+      // 更新状态模型的索引
+      const newIndex = this.playlistModel.getCurrentIndex();
+      const newSong = this.playlistModel.getCurrentSong();
+      this.stateModel.updateCurrentIndex(newIndex);
       
-      // 停止当前播放并开始新歌曲
+      if (newSong) {
+        LogUtils.getInstance().LOGI(`UnifiedPlayerService: Moved to index ${newIndex} (${newSong.name})`);
+        this.stateModel.updateCurrentSong(newSong);
+      }
+      
+      // 停止当前播放
       await this.stop();
-      await this.startPlayOrResumePlay();
+      
+      // 直接播放新歌曲,不调用通用的恢复逻辑
+      await this.playNewSongDirectly(newSong);
       
       // 更新状态模型中的播放列表状态
       this.updatePlaylistStateInModel();
       
-      // 通知歌曲变化
-      const currentSong = this.playlistModel.getCurrentSong();
-      if (currentSong) {
-        this.stateModel.updateCurrentSong(currentSong);
-        // 强制更新卡片显示新歌曲(重要事件)
-        await this.updateWidgetsForSongChange(currentSong, true);
+      // 强制更新卡片显示新歌曲(重要事件)
+      if (newSong) {
+        await this.updateWidgetsForSongChange(newSong, true);
       }
       
       LogUtils.getInstance().LOGI('UnifiedPlayerService: Moved to previous song');
@@ -511,6 +581,10 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
   }  
   // 播放列表管理
   setPlaylist(songs: VideoItem[], currentIndex: number = 0): void {
+    // 记录调用栈信息以便调试
+    const stack = new Error().stack || 'No stack available';
+    const caller = stack.split('\n')[2] || 'Unknown caller';
+    
     this.playlistModel.replaceSongs(songs, currentIndex);
     this.stateModel.updateCurrentIndex(currentIndex);
     
@@ -527,7 +601,12 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
     // 更新卡片显示播放列表变化
     this.updateWidgetsForPlaylistChange();
     
-    LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playlist set with ${songs.length} songs`);
+    LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playlist set with ${songs.length} songs, caller: ${caller.trim()}`);
+    
+    // 如果设置的是小播放列表,记录更多信息
+    if (songs.length <= 20) {
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService: Small playlist detected, caller stack: ${stack.substring(0, 500)}`);
+    }
   }
 
   addToPlaylist(song: VideoItem, index?: number): void {
@@ -928,6 +1007,13 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
         this.stateModel.updateCurrentIndex(playlistData.currentIndex);
         this.stateModel.updatePlayMode(playlistData.playMode);
         
+        // 恢复当前歌曲到状态模型
+        const currentSong = this.playlistModel.getCurrentSong();
+        if (currentSong) {
+          this.stateModel.updateCurrentSong(currentSong);
+          console.log(`Heanup2 UnifiedPlayerService: 恢复当前歌曲: ${currentSong.name}`);
+        }
+        
         LogUtils.getInstance().LOGI(`UnifiedPlayerService: Restored playlist with ${playlistData.songs.length} songs`);
       } else {
         console.log("Heanup2 UnifiedPlayerService: 没有找到保存的播放列表或播放列表为空");
@@ -1092,37 +1178,6 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
   getPlaylistSyncService(): PlaylistSyncService {
     return this.playlistSync;
   }
-  
-  /**
-   * 手动触发数据同步
-   */
-  async manualSync(): Promise<void> {
-    try {
-      const playlist = this.playlistModel.getSongs();
-      const currentIndex = this.playlistModel.getCurrentIndex();
-      const playMode = this.stateModel.getState().playMode;
-      
-      // 执行双向同步
-      const syncedData = await this.playlistSync.bidirectionalSync(playlist, currentIndex, playMode);
-      
-      // 如果同步后的数据与本地不同,更新本地数据
-      if (syncedData.songs.length !== playlist.length || 
-          syncedData.currentIndex !== currentIndex ||
-          syncedData.playMode !== playMode) {
-        
-        this.playlistModel.replaceSongs(syncedData.songs, syncedData.currentIndex);
-        this.stateModel.updateCurrentIndex(syncedData.currentIndex);
-        this.stateModel.updatePlayMode(syncedData.playMode);
-        
-        LogUtils.getInstance().LOGI('UnifiedPlayerService: Manual sync completed with data update');
-      } else {
-        LogUtils.getInstance().LOGI('UnifiedPlayerService: Manual sync completed - no changes');
-      }
-    } catch (error) {
-      LogUtils.getInstance().LOGI(`UnifiedPlayerService manualSync error: ${error}`);
-      throw new  Error;
-    }
-  }
 
   // ==================== StateChangeCallback 接口实现 ====================
   
@@ -1156,7 +1211,7 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
    */
   onProgressChanged?(progress: PlayProgress): void {
     try {
-      LogUtils.getInstance().LOGI(`UnifiedPlayerService: Received progress change notification - ${progress.percentage.toFixed(1)}%`);
+      // LogUtils.getInstance().LOGI(`UnifiedPlayerService: Received progress change notification - ${progress.percentage.toFixed(1)}%`);
       // 这里可以处理来自其他组件的进度变化通知
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService onProgressChanged error: ${error}`);

+ 1 - 0
entry/src/main/ets/common/widget/EnhancedFormUpdateService.ets

@@ -169,6 +169,7 @@ export class EnhancedFormUpdateService {
       // 并行更新所有卡片
       const updatePromises = formIds.map((formId, index) => {
         hilog.info(0x0000, TAG, `🎯 Creating update task ${index + 1}/${formIds.length} for form: ${formId}`);
+        hilog.info(0x0000, TAG, "更新的卡片数据: "+JSON.stringify(data));
         return this.updateSingleFormWithRetry(formId, data, prefs);
       });
 

+ 85 - 64
entry/src/main/ets/view/LocalMusic.ets

@@ -440,6 +440,16 @@ export struct LocalMusic {
     try {
       await this.unifiedPlayerService.initialize(this.context);
       
+      // 等待数据恢复完成后再获取播放列表
+      LogUtils.getInstance().LOGI('LocalMusic: Waiting for UnifiedPlayerService data restoration...');
+      const dataRestored: boolean = await this.unifiedPlayerService.waitForDataRestoration(5000);
+      
+      if (!dataRestored) {
+        LogUtils.getInstance().LOGI('LocalMusic: Data restoration timeout, but proceeding with initialization');
+      } else {
+        LogUtils.getInstance().LOGI('LocalMusic: Data restoration completed successfully');
+      }
+      
       // 从UnifiedPlayerService恢复播放列表和状态
       const restoredPlaylist = this.unifiedPlayerService.getPlaylist();
       const restoredIndex = this.unifiedPlayerService.getCurrentIndex();
@@ -467,10 +477,14 @@ export struct LocalMusic {
           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);
+        LogUtils.getInstance().LOGI(`LocalMusic: Restored playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
+      } else {
+        LogUtils.getInstance().LOGI('LocalMusic: No playlist restored from UnifiedPlayerService, songList length = ' + this.songList.length);
+        if (ArrayUtil.isNotEmpty(this.songList)) {
+          // 如果LocalMusic有播放列表但UnifiedPlayerService没有,设置到服务中
+          this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
+          LogUtils.getInstance().LOGI(`LocalMusic: Set existing playlist to UnifiedPlayerService - ${this.songList.length} songs`);
+        }
       }
       
       // 添加状态监听器,保持UI同步
@@ -578,15 +592,8 @@ export struct LocalMusic {
     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');
-      }
+      // 数据恢复已在initUnifiedPlayerService中完成,直接获取播放列表
+      LogUtils.getInstance().LOGI('LocalMusic: Getting playlist from UnifiedPlayerService after file loading');
       
       // 尝试从UnifiedPlayerService恢复播放列表
       const unifiedPlaylist = this.unifiedPlayerService.getPlaylist();
@@ -598,18 +605,22 @@ export struct LocalMusic {
         this.songList = unifiedPlaylist;
         this.curIndex = unifiedIndex;
         this.currentSong = unifiedSong || undefined;
-        LogUtils.getInstance().LOGI(`LocalMusic: Using playlist from UnifiedPlayerService - ${this.songList.length} songs`);
+        LogUtils.getInstance().LOGI(`LocalMusic: Using playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
       } 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()
+          const currentFileList = this.getCurFileList();
+          LogUtils.getInstance().LOGI(`LocalMusic: No legacy playlist found, current directory has ${currentFileList.length} songs`);
+          LogUtils.getInstance().LOGI(`LocalMusic: Current path: ${this.currentPath}, Root path: ${this.rootPath}`);
+          this.songList = currentFileList;
+          LogUtils.getInstance().LOGI(`LocalMusic: Using current file list as fallback - ${this.songList.length} songs`);
         } else {
           this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
+          LogUtils.getInstance().LOGI(`LocalMusic: Using legacy playlist storage - ${this.songList.length} songs, index ${this.curIndex}`);
         }
-        LogUtils.getInstance().LOGI(`LocalMusic: Using legacy playlist storage - ${this.songList.length} songs`);
       }
       
       // 同步播放列表和当前索引到AppStorage,确保卡片能访问
@@ -1008,48 +1019,28 @@ export struct LocalMusic {
       //穿山甲
       // this.loadBannerAd(CSJUtil.getBannerID())
 
-      // 优先从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.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);
+      LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - Files loaded, skipping playlist restoration (already done in initUnifiedPlayerService)');
       
+      // 播放列表恢复逻辑已经在 initUnifiedPlayerService 中完成,这里不需要重复
+      // 只需要确保UI状态是最新的
       if (ArrayUtil.isNotEmpty(this.songList)) {
         this.isFirstStartPlay = true
         this.sonDataSource.pushArrayData(this.songList)
-        if (this.currentSong === undefined) {
+        if (this.currentSong === undefined && this.songList.length > 0) {
           this.isFirstStartPlay = false
           this.currentSong = this.songList[0]
         }
-        this.videoUrl = this.currentSong.filePath
-        this.name = this.currentSong.name
-        this.cover = this.currentSong.pixelMapPath
-        AppStorage.setOrCreate('currentSong',this.currentSong) ;
+        if (this.currentSong) {
+          this.videoUrl = this.currentSong.filePath
+          this.name = this.currentSong.name
+          this.cover = this.currentSong.pixelMapPath
+          AppStorage.setOrCreate('currentSong',this.currentSong);
+        }
         
-
+        LogUtils.getInstance().LOGI(`LocalMusic: mkDownLoadDir - UI updated with existing playlist: ${this.songList.length} songs`);
       } else {
         this.name = '空空如也'
+        LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - No playlist available, showing empty state');
       }
     })
 
@@ -1332,10 +1323,13 @@ 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)) {
+        
+        // 只有在没有现有播放列表时,才使用当前目录的文件列表
+        // 避免在文件列表更新时破坏用户的播放列表
+        if (ArrayUtil.isEmpty(this.songList) && ArrayUtil.isNotEmpty(globalVideoList)) {
           this.songList = globalVideoList;
           AppStorage.setOrCreate('songList', this.songList);
           this.sonDataSource.pushArrayData(this.songList);
@@ -1343,7 +1337,9 @@ export struct LocalMusic {
           // 同步到统一播放器服务进行持久化
           this.syncPlaylistToService();
           
-          LogUtils.getInstance().LOGI(`LocalMusic: updateListData - Updated playlist with ${this.songList.length} songs`);
+          LogUtils.getInstance().LOGI(`LocalMusic: updateListData - Created initial playlist with ${this.songList.length} songs`);
+        } else {
+          LogUtils.getInstance().LOGI(`LocalMusic: updateListData - Preserving existing playlist with ${this.songList.length} songs, current directory has ${globalVideoList.length} songs`);
         }
       }
       
@@ -4745,13 +4741,27 @@ export struct LocalMusic {
           if (index !== undefined) {
             this.curIndex = index
           }
+          LogUtils.getInstance().LOGI(`LocalMusic: doPlay from playlist - song: ${item.name}, index: ${index}`);
         } else {
+          // 点击文件列表中的歌曲,需要判断是否要创建新的播放列表
           let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
           this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
-          this.songList = globalVideoList
-
-          this.sonDataSource.pushArrayData(this.songList)
-          this.currentSong = globalVideoList[this.curIndex]
+          
+          // 检查当前播放列表是否包含这首歌
+          const currentSongIndex = this.songList.findIndex(song => song.filePath === item.filePath);
+          
+          if (currentSongIndex >= 0 && ArrayUtil.isNotEmpty(this.songList)) {
+            // 如果当前播放列表已经包含这首歌,使用现有播放列表
+            this.curIndex = currentSongIndex;
+            this.currentSong = this.songList[this.curIndex];
+            LogUtils.getInstance().LOGI(`LocalMusic: doPlay - Found song in existing playlist at index ${this.curIndex}, keeping playlist with ${this.songList.length} songs`);
+          } else {
+            // 如果当前播放列表不包含这首歌,或者没有播放列表,则创建新的
+            this.songList = globalVideoList;
+            this.sonDataSource.pushArrayData(this.songList);
+            this.currentSong = globalVideoList[this.curIndex];
+            LogUtils.getInstance().LOGI(`LocalMusic: doPlay - Created new playlist with ${this.songList.length} songs, current song: ${this.currentSong.name}`);
+          }
         }
 
         AppStorage.setOrCreate('currentSong',this.currentSong) ;
@@ -9795,8 +9805,19 @@ export struct LocalMusic {
   private syncPlaylistToService() {
     try {
       if (ArrayUtil.isNotEmpty(this.songList)) {
+        // 记录调用栈信息以便调试
+        const stack = new Error().stack || 'No stack available';
+        const caller = stack.split('\n')[2] || 'Unknown caller';
+        
         this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
-        LogUtils.getInstance().LOGI(`LocalMusic: Playlist synced to UnifiedPlayerService - ${this.songList.length} songs`);
+        LogUtils.getInstance().LOGI(`LocalMusic: Playlist synced to UnifiedPlayerService - ${this.songList.length} songs, caller: ${caller.trim()}`);
+        
+        // 如果同步的是小播放列表,记录更多信息
+        if (this.songList.length <= 20) {
+          LogUtils.getInstance().LOGI(`LocalMusic: Small playlist sync detected, current path: ${this.currentPath}, first few songs: ${this.songList.slice(0, 5).map(s => s.name).join(', ')}`);
+        }
+      } else {
+        LogUtils.getInstance().LOGI('LocalMusic: syncPlaylistToService - No songs to sync');
       }
     } catch (error) {
       LogUtils.getInstance().LOGI(`LocalMusic syncPlaylistToService error: ${error}`);
@@ -10691,14 +10712,14 @@ export struct LocalMusic {
       if (ArrayUtil.isNotEmpty(this.songList)) {
         // 确保播放列表已同步到UnifiedPlayerService
         this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
-        
+
         // 使用UnifiedPlayerService播放下一首
         await this.unifiedPlayerService.playNext();
-        
+
         // 更新本地状态以保持UI同步
         const currentIndex = this.unifiedPlayerService.getCurrentIndex();
         const currentSong = this.unifiedPlayerService.getCurrentSong();
-        
+
         if (currentSong) {
           this.curIndex = currentIndex;
           this.currentSong = currentSong;
@@ -10706,12 +10727,12 @@ export struct LocalMusic {
           this.artist = currentSong.artist;
           this.name = currentSong.name;
           this.cover = currentSong.pixelMapPath;
-          
+
           // 同步到AppStorage,确保卡片能获取到最新状态
-          AppStorage.setOrCreate('songList', this.songList);
-          AppStorage.setOrCreate('currIndex', this.curIndex);
-          AppStorage.setOrCreate('currentSong', currentSong);
-          
+          // AppStorage.setOrCreate('songList', this.songList);
+          // AppStorage.setOrCreate('currIndex', this.curIndex);
+          // AppStorage.setOrCreate('currentSong', currentSong);
+
           this.changeImageAnimation();
 
         }