Browse Source

修复时间进度显示异常

chendeben 1 year ago
parent
commit
a28ab66d90

+ 1 - 0
entry/src/main/ets/common/service/PlayerManager.ets

@@ -59,6 +59,7 @@ export class PlayerManager implements IPlayerManager {
   private audioInterruptCallback: ((event: InterruptEvent) => void) | null = null;
   private audioInterruptCallback: ((event: InterruptEvent) => void) | null = null;
   private stateCallback: PlayerStateCallback | null = null;
   private stateCallback: PlayerStateCallback | null = null;
   private isPaused: boolean = false; // 跟踪暂停状态
   private isPaused: boolean = false; // 跟踪暂停状态
+  private playType: number = 0; //0:连续播放  1:单片重复播放 2:正常播放 3:随机播放
   
   
   private constructor() {
   private constructor() {
     this.mIjkMediaPlayer = IjkMediaPlayer.getInstance();
     this.mIjkMediaPlayer = IjkMediaPlayer.getInstance();

+ 1 - 0
entry/src/main/ets/common/service/PlayerStateModel.ets

@@ -371,6 +371,7 @@ export class PlayerStateModel {
    */
    */
   private notifyStateChanged(): void {
   private notifyStateChanged(): void {
     const state = this.getState();
     const state = this.getState();
+    LogUtils.getInstance().LOGI(`通知状态变化:${state} - ${JSON.stringify(this.listeners)}`);
     this.listeners.forEach(listener => {
     this.listeners.forEach(listener => {
       try {
       try {
         listener.onStateChanged(state);
         listener.onStateChanged(state);

+ 17 - 31
entry/src/main/ets/common/service/UnifiedPlayerService.ets

@@ -14,6 +14,8 @@ import { EnhancedFormUpdateService, UpdateStats } from '../widget/EnhancedFormUp
 import { AvSessionController } from '../../controller/AvSessionController';
 import { AvSessionController } from '../../controller/AvSessionController';
 import { avSession } from '@kit.AVSessionKit';
 import { avSession } from '@kit.AVSessionKit';
 import json from '@ohos.util.json';
 import json from '@ohos.util.json';
+import { Utility } from '../util/Utility';
+import MediaTable from '../util/MediaTable';
 
 
 /**
 /**
  * 服务就绪状态详情接口
  * 服务就绪状态详情接口
@@ -257,6 +259,8 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
   private avSessionUpdateTimer: number = -1; // 新增:系统播控更新防抖定时器
   private avSessionUpdateTimer: number = -1; // 新增:系统播控更新防抖定时器
   private avMetadataUpdateTimer: number = -1; // 新增:元数据更新防抖定时器 
   private avMetadataUpdateTimer: number = -1; // 新增:元数据更新防抖定时器 
   private lastUpdateTime: number=0;
   private lastUpdateTime: number=0;
+  private favList: VideoItem[]=[];
+  table: undefined;
 
 
   private constructor() {
   private constructor() {
     this.playerManager = PlayerManager.getInstance();
     this.playerManager = PlayerManager.getInstance();
@@ -833,6 +837,18 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
   getCurrentSong(): VideoItem | null {
   getCurrentSong(): VideoItem | null {
     return this.playlistModel.getCurrentSong();
     return this.playlistModel.getCurrentSong();
   }
   }
+  getFav(): Array<VideoItem>{
+    this.getTable().queryByisFav(1, async (result: VideoItem[]) => {
+      this.favList = result
+    })
+    return this.favList;
+  }
+  private getTable():MediaTable{
+    if (this.table!=undefined) {
+      return this.table;
+    }
+    return new MediaTable(getContext(this))
+  }
 
 
   getPlaylist(): VideoItem[] {
   getPlaylist(): VideoItem[] {
     return this.playlistModel.getSongs();
     return this.playlistModel.getSongs();
@@ -1088,6 +1104,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
   setPlayMode(mode: number): void {
   setPlayMode(mode: number): void {
     const playMode = mode as PlayMode;
     const playMode = mode as PlayMode;
     this.stateModel.updatePlayMode(playMode);
     this.stateModel.updatePlayMode(playMode);
+
     LogUtils.getInstance().LOGI(`UnifiedPlayerService: Play mode set to ${mode}`);
     LogUtils.getInstance().LOGI(`UnifiedPlayerService: Play mode set to ${mode}`);
   }
   }
 
 
@@ -1316,43 +1333,12 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
           LogUtils.getInstance().LOGI(`AVSession seek command failed: ${error}`);
           LogUtils.getInstance().LOGI(`AVSession seek command failed: ${error}`);
         });
         });
       });
       });
-
-      // 循环模式设置监听
-      avSession.on('setLoopMode', (mode: avSession.LoopMode) => {
-        LogUtils.getInstance().LOGI(`UnifiedPlayerService: AVSession setLoopMode command received: ${mode}`);
-
-        const playMode = this.convertLoopModeToPlayMode(mode);
-        this.setPlayMode(playMode);
-      });
-
       LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession listeners set up successfully');
       LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession listeners set up successfully');
     } catch (error) {
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to set AVSession listeners: ${error}`);
       LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to set AVSession listeners: ${error}`);
     }
     }
   }
   }
 
 
-
-
-  /**
-   * 转换AVSession循环模式为播放模式
-   */
-  private convertLoopModeToPlayMode(loopMode: avSession.LoopMode): number {
-    switch (loopMode) {
-      case avSession.LoopMode.LOOP_MODE_SINGLE:
-        return PlayMode.SINGLE_REPEAT;
-      case avSession.LoopMode.LOOP_MODE_LIST:
-        return PlayMode.NORMAL;
-      case avSession.LoopMode.LOOP_MODE_SHUFFLE:
-        return PlayMode.RANDOM;
-      case avSession.LoopMode.LOOP_MODE_SEQUENCE:
-      default:
-        return PlayMode.SEQUENCE;
-    }
-  }
-
-
-  // ==================== 错误处理和恢复方法 ====================
-
   /**
   /**
    * 处理播放错误
    * 处理播放错误
    */
    */

+ 26 - 141
entry/src/main/ets/controller/AvSessionController.ets

@@ -20,8 +20,7 @@ import { avSession } from '@kit.AVSessionKit';
 import { BackgroundTaskManager } from '../common/util/BackgroundTaskManager';
 import { BackgroundTaskManager } from '../common/util/BackgroundTaskManager';
 import { VideoItem } from '../viewmodel/VideoItem';
 import { VideoItem } from '../viewmodel/VideoItem';
 import { ImageUtil, PreferencesUtil } from '@pura/harmony-utils';
 import { ImageUtil, PreferencesUtil } from '@pura/harmony-utils';
-import { image } from '@kit.ImageKit';
-import { Utility } from '../common/util/Utility';
+import { SettingPage } from '../pages/SettingPage';
 import LyricUtil from '../common/util/LyricUtil';
 import LyricUtil from '../common/util/LyricUtil';
 import ImageUtils from '../common/util/ImageUtils';
 import ImageUtils from '../common/util/ImageUtils';
 
 
@@ -46,7 +45,7 @@ export class AvSessionController {
 
 
   public initAvSession(isVideo:boolean) {
   public initAvSession(isVideo:boolean) {
     if(isVideo){
     if(isVideo){
-      let isBgPlayOpen = PreferencesUtil.getBooleanSync('isBgPlayOpen',true)
+      let isBgPlayOpen = PreferencesUtil.getBooleanSync(SettingPage.IS_BGPLAY_OPEN,true)
       if(!isBgPlayOpen)
       if(!isBgPlayOpen)
         return
         return
     }
     }
@@ -57,25 +56,17 @@ export class AvSessionController {
       return;
       return;
     }
     }
     let type: avSession.AVSessionType = isVideo ? 'video' : 'audio';
     let type: avSession.AVSessionType = isVideo ? 'video' : 'audio';
-    avSession.createAVSession(this.context, 'TTMusic_Session', type).then(async (avSession) => {
+    avSession.createAVSession(this.context, 'sessionName', type).then(async (avSession) => {
       this.avSession = avSession;
       this.avSession = avSession;
       hilog.info(0x0000, TAG, `session create successed : sessionId : ${this.avSession.sessionId}`);
       hilog.info(0x0000, TAG, `session create successed : sessionId : ${this.avSession.sessionId}`);
       BackgroundTaskManager.startContinuousTask(this.context);
       BackgroundTaskManager.startContinuousTask(this.context);
       this.setLaunchAbility();
       this.setLaunchAbility();
-      
-      // 设置扩展信息
+      this.avSession.activate();
       this.avSession.setExtras({
       this.avSession.setExtras({
         requireAbilityList: ['url-cast']
         requireAbilityList: ['url-cast']
       });
       });
-      
-      // 注册控制命令监听器 - 必须在激活前注册
-      this.registerControlCommands();
-      
-      hilog.info(0x0000, TAG, 'Control commands registered, AVSession ready for metadata and activation');
-      
     }).catch((error:Error) => {
     }).catch((error:Error) => {
       console.error('Failed to create AVSession:', error);
       console.error('Failed to create AVSession:', error);
-      hilog.error(0x0000, TAG, `Failed to create AVSession: ${error}`);
     });
     });
   }
   }
 
 
@@ -135,79 +126,48 @@ export class AvSessionController {
     }
     }
   }
   }
 
 
-  public async setAVMetadataMusic(curSource: VideoItem, duration: number, lyricContent?: string) {
+  public async setAVMetadataMusic(curSource: VideoItem, duration: number,lyricContent?:string) {
     if (curSource === undefined) {
     if (curSource === undefined) {
       hilog.error(0x0000, TAG, 'SetAVMetadata Error, curSource is null');
       hilog.error(0x0000, TAG, 'SetAVMetadata Error, curSource is null');
       return;
       return;
     }
     }
     try {
     try {
       BackgroundTaskManager.startContinuousTask(this.context);
       BackgroundTaskManager.startContinuousTask(this.context);
-      let pixelMapPath: string | undefined = curSource.pixelMapPath
+      let pixelMapPath:string|undefined = curSource.pixelMapPath
 
 
-      let imagePixMap: PixelMap | string;
-      if (pixelMapPath) {
+      let imagePixMap: PixelMap|string ;
+      if(pixelMapPath){
         imagePixMap = await ImageUtils.imagePathToPixelMap(pixelMapPath)
         imagePixMap = await ImageUtils.imagePathToPixelMap(pixelMapPath)
-      } else {
+      }else{
         imagePixMap = await ImageUtil.getPixelMapFromMedia($r('app.media.ic_avatar2'));
         imagePixMap = await ImageUtil.getPixelMapFromMedia($r('app.media.ic_avatar2'));
       }
       }
       let lyric = ''
       let lyric = ''
-      if (lyricContent)
+      if(lyricContent)
         lyric = LyricUtil.convertLyricToSimpleLrc(lyricContent)
         lyric = LyricUtil.convertLyricToSimpleLrc(lyricContent)
 
 
-      hilog.info(0x0000, TAG, 'Setting AVMetadata with required fields');
-      
-      // 验证duration是否有效
-      let validDuration = 0;
-      if (typeof duration === 'number' && !isNaN(duration) && duration > 0) {
-        validDuration = Math.floor(duration); // 确保是整数
-      } else {
-        hilog.warn(0x0000, TAG, `Invalid duration received: ${duration} (type: ${typeof duration}), using 0 instead`);
-      }
-      
-      // 按照官方文档要求,设置必要的元数据:标题、副标题/歌手、封面图
+      hilog.info(0x0000, TAG, 'onecold SetAVMetadata successfully curSource.pixelMapPath '+curSource.pixelMapPath);
       let metadata: avSession.AVMetadata = {
       let metadata: avSession.AVMetadata = {
         assetId: `${curSource.filePath}`,
         assetId: `${curSource.filePath}`,
-        title: curSource.name || '未知标题', // 必需:标题
-        artist: curSource.artist || '未知艺术家', // 必需:副标题/歌手
-        mediaImage: imagePixMap, // 必需:封面图
-        album: curSource.album || '未知专辑',
-        duration: validDuration, // 时长,单位:毫秒,确保是有效数字
-        lyric: lyric,
-        filter: avSession.ProtocolType.TYPE_CAST_PLUS_STREAM | avSession.ProtocolType.TYPE_DLNA,
+        title: curSource.name,
+        filter: avSession.ProtocolType.TYPE_CAST_PLUS_STREAM|avSession.ProtocolType.TYPE_DLNA,
+        artist: curSource.artist,
+        mediaImage: imagePixMap,
+        duration: duration,
+        lyric:lyric,
       };
       };
-      
-      hilog.info(0x0000, TAG, `Setting AVMetadata - Title: ${metadata.title}, Artist: ${metadata.artist}, Duration: ${validDuration}ms (original: ${duration}, type: ${typeof duration})`);
 
 
       if (this.avSession) {
       if (this.avSession) {
-        // 设置元数据
-        await this.avSession.setAVMetadata(metadata);
-        this.avSessionMetadata = metadata;
-        hilog.info(0x0000, TAG, 'AVMetadata set successfully');
-        
-        // 按照官方文档:激活接口要在元数据、控制命令注册完成之后再执行
-        // 直接激活AVSession
-        await this.avSession.activate();
-        hilog.info(0x0000, TAG, 'AVSession activated successfully - should now be visible in system media controls');
-        
-        // 设置初始播放状态 - 根据文档,这是必需的
-        const initialPlaybackState: avSession.AVPlaybackState = {
-          state: avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
-          position: {
-            elapsedTime: 0,
-            updateTime: Date.now()
-          },
-          bufferedTime: 0,
-          loopMode: avSession.LoopMode.LOOP_MODE_SEQUENCE,
-          isFavorite: false
-        };
-        
-        this.setAvSessionPlayState(initialPlaybackState);
-        hilog.info(0x0000, TAG, 'Initial playback state set - AVSession should now be visible in system controls');
+        this.avSession.setAVMetadata(metadata).then(() => {
+          this.avSessionMetadata = metadata;
+          hilog.info(0x0000, TAG, 'SetAVMetadata successfully');
+        }).catch((err: BusinessError) => {
+          hilog.error(0x0000, TAG, `SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
+        });
       }
       }
     } catch (error) {
     } catch (error) {
-      console.warn('setAVMetadataMusic error:', error.message);
-      hilog.error(0x0000, TAG, `SetAVMetadata error: ${error}`);
+      console.warn(' setAVMetadataMusic:', error.message);
     }
     }
+
   }
   }
 
 
   public setAvSessionPlayState(playbackState: avSession.AVPlaybackState) {
   public setAvSessionPlayState(playbackState: avSession.AVPlaybackState) {
@@ -217,84 +177,9 @@ export class AvSessionController {
         if (err) {
         if (err) {
           hilog.error(0x0000, TAG, `SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
           hilog.error(0x0000, TAG, `SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
         } else {
         } else {
-          hilog.info(0x0000, TAG, `SetAVPlaybackState successfully - State: ${playbackState.state}, Position: ${playbackState.position?.elapsedTime}ms`);
+          hilog.info(0x0000, TAG, 'SetAVPlaybackState successfully');
         }
         }
       });
       });
-    } else {
-      hilog.error(0x0000, TAG, 'Cannot set playback state: AVSession is null');
-    }
-  }
-
-  /**
-   * 注册控制命令监听器
-   * 根据官方文档,必须在激活前注册所有需要的控制命令
-   */
-  private registerControlCommands(): void {
-    if (!this.avSession) {
-      hilog.error(0x0000, TAG, 'Cannot register commands: AVSession is null');
-      return;
-    }
-
-    try {
-      // 注册播放命令
-      this.avSession.on('play', () => {
-        hilog.info(0x0000, TAG, 'AVSession: Received play command');
-        // 这里会通过UnifiedPlayerService的监听器处理
-      });
-
-      // 注册暂停命令
-      this.avSession.on('pause', () => {
-        hilog.info(0x0000, TAG, 'AVSession: Received pause command');
-        // 这里会通过UnifiedPlayerService的监听器处理
-      });
-
-      // 注册停止命令
-      this.avSession.on('stop', () => {
-        hilog.info(0x0000, TAG, 'AVSession: Received stop command');
-        // 这里会通过UnifiedPlayerService的监听器处理
-      });
-
-      // 注册下一首命令
-      this.avSession.on('playNext', () => {
-        hilog.info(0x0000, TAG, 'AVSession: Received playNext command');
-        // 这里会通过UnifiedPlayerService的监听器处理
-      });
-
-      // 注册上一首命令
-      this.avSession.on('playPrevious', () => {
-        hilog.info(0x0000, TAG, 'AVSession: Received playPrevious command');
-        // 这里会通过UnifiedPlayerService的监听器处理
-      });
-
-      // 注册进度控制命令
-      this.avSession.on('seek', (time: number) => {
-        hilog.info(0x0000, TAG, `AVSession: Received seek command to ${time}ms`);
-        // 这里会通过UnifiedPlayerService的监听器处理
-      });
-
-      // 注册循环模式命令
-      this.avSession.on('setLoopMode', (mode: avSession.LoopMode) => {
-        hilog.info(0x0000, TAG, `AVSession: Received setLoopMode command: ${mode}`);
-        // 这里会通过UnifiedPlayerService的监听器处理
-      });
-
-      hilog.info(0x0000, TAG, 'All control commands registered successfully');
-    } catch (error) {
-      hilog.error(0x0000, TAG, `Failed to register control commands: ${error}`);
-    }
-  }
-
-  /**
-   * 检查AVSession状态
-   */
-  public checkAvSessionStatus(): void {
-    if (this.avSession) {
-      hilog.info(0x0000, TAG, `AVSession status - ID: ${this.avSession.sessionId}`);
-      if (this.avSessionMetadata) {
-        hilog.info(0x0000, TAG, `AVSession metadata - Title: ${this.avSessionMetadata.title}, Artist: ${this.avSessionMetadata.artist}`);
-      }
-    } else {
-      hilog.warn(0x0000, TAG, 'AVSession is null');
     }
     }
   }
   }
 
 

+ 106 - 196
entry/src/main/ets/view/LocalMusic.ets

@@ -361,9 +361,9 @@ export struct LocalMusic {
     .setOnRightClickListener(() => {
     .setOnRightClickListener(() => {
       this.showSheelDialog()
       this.showSheelDialog()
     })
     })
-    // .setOnTitleClickListener(() => {
-    //   this.showPupDialog()
-    // })
+      // .setOnTitleClickListener(() => {
+      //   this.showPupDialog()
+      // })
     .setOnLeftClickListener(() => {
     .setOnLeftClickListener(() => {
       this.doSwipBack()
       this.doSwipBack()
     })
     })
@@ -434,36 +434,36 @@ export struct LocalMusic {
   private async initUnifiedPlayerService(): Promise<void> {
   private async initUnifiedPlayerService(): Promise<void> {
     try {
     try {
       await this.unifiedPlayerService.initialize(this.context);
       await this.unifiedPlayerService.initialize(this.context);
-      
+
       // 等待数据恢复完成后再获取播放列表
       // 等待数据恢复完成后再获取播放列表
       LogUtils.getInstance().LOGI('LocalMusic: Waiting for UnifiedPlayerService data restoration...');
       LogUtils.getInstance().LOGI('LocalMusic: Waiting for UnifiedPlayerService data restoration...');
       const dataRestored: boolean = await this.unifiedPlayerService.waitForDataRestoration(5000);
       const dataRestored: boolean = await this.unifiedPlayerService.waitForDataRestoration(5000);
-      
+
       if (!dataRestored) {
       if (!dataRestored) {
         LogUtils.getInstance().LOGI('LocalMusic: Data restoration timeout, but proceeding with initialization');
         LogUtils.getInstance().LOGI('LocalMusic: Data restoration timeout, but proceeding with initialization');
       } else {
       } else {
         LogUtils.getInstance().LOGI('LocalMusic: Data restoration completed successfully');
         LogUtils.getInstance().LOGI('LocalMusic: Data restoration completed successfully');
       }
       }
-      
+
       // 从UnifiedPlayerService恢复播放列表和状态
       // 从UnifiedPlayerService恢复播放列表和状态
       const restoredPlaylist = this.unifiedPlayerService.getPlaylist();
       const restoredPlaylist = this.unifiedPlayerService.getPlaylist();
       const restoredIndex = this.unifiedPlayerService.getCurrentIndex();
       const restoredIndex = this.unifiedPlayerService.getCurrentIndex();
       const restoredSong = this.unifiedPlayerService.getCurrentSong();
       const restoredSong = this.unifiedPlayerService.getCurrentSong();
-      
+
       if (ArrayUtil.isNotEmpty(restoredPlaylist)) {
       if (ArrayUtil.isNotEmpty(restoredPlaylist)) {
         // 恢复播放列表到LocalMusic
         // 恢复播放列表到LocalMusic
         this.songList = restoredPlaylist;
         this.songList = restoredPlaylist;
         this.curIndex = restoredIndex;
         this.curIndex = restoredIndex;
         this.currentSong = restoredSong || undefined;
         this.currentSong = restoredSong || undefined;
-        
+
         // 同步到AppStorage
         // 同步到AppStorage
         AppStorage.setOrCreate('songList', this.songList);
         AppStorage.setOrCreate('songList', this.songList);
         AppStorage.setOrCreate('currIndex', this.curIndex);
         AppStorage.setOrCreate('currIndex', this.curIndex);
         AppStorage.setOrCreate('currentSong', this.currentSong);
         AppStorage.setOrCreate('currentSong', this.currentSong);
-        
+
         // 更新UI数据源
         // 更新UI数据源
         this.sonDataSource.pushArrayData(this.songList);
         this.sonDataSource.pushArrayData(this.songList);
-        
+
         // 如果有当前歌曲,更新UI显示
         // 如果有当前歌曲,更新UI显示
         if (this.currentSong) {
         if (this.currentSong) {
           this.videoUrl = this.currentSong.filePath;
           this.videoUrl = this.currentSong.filePath;
@@ -471,7 +471,7 @@ export struct LocalMusic {
           this.artist = this.currentSong.artist;
           this.artist = this.currentSong.artist;
           this.cover = this.currentSong.pixelMapPath;
           this.cover = this.currentSong.pixelMapPath;
         }
         }
-        
+
         LogUtils.getInstance().LOGI(`LocalMusic: Restored playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
         LogUtils.getInstance().LOGI(`LocalMusic: Restored playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
       } else {
       } else {
         LogUtils.getInstance().LOGI('LocalMusic: No playlist restored from UnifiedPlayerService, songList length = ' + this.songList.length);
         LogUtils.getInstance().LOGI('LocalMusic: No playlist restored from UnifiedPlayerService, songList length = ' + this.songList.length);
@@ -481,25 +481,25 @@ export struct LocalMusic {
           LogUtils.getInstance().LOGI(`LocalMusic: Set existing playlist to UnifiedPlayerService - ${this.songList.length} songs`);
           LogUtils.getInstance().LOGI(`LocalMusic: Set existing playlist to UnifiedPlayerService - ${this.songList.length} songs`);
         }
         }
       }
       }
-      
+
       // 添加状态监听器,保持UI同步
       // 添加状态监听器,保持UI同步
       class LocalMusicStateListener implements PlayerStateListener {
       class LocalMusicStateListener implements PlayerStateListener {
         private localMusic: LocalMusic;
         private localMusic: LocalMusic;
-        
+
         constructor(localMusic: LocalMusic) {
         constructor(localMusic: LocalMusic) {
           this.localMusic = localMusic;
           this.localMusic = localMusic;
         }
         }
-        
+
         onStateChanged(state: PlayerState): void {
         onStateChanged(state: PlayerState): void {
           LogUtils.getInstance().LOGI(`LocalMusic: StateListener triggered - isPlaying: ${state.isPlaying}, isPaused: ${state.isPaused}`);
           LogUtils.getInstance().LOGI(`LocalMusic: StateListener triggered - isPlaying: ${state.isPlaying}, isPaused: ${state.isPaused}`);
-          
+
           // 直接使用状态模型的状态,这是最权威的状态源
           // 直接使用状态模型的状态,这是最权威的状态源
           const isPlaying = state.isPlaying;
           const isPlaying = state.isPlaying;
           const isPaused = state.isPaused;
           const isPaused = state.isPaused;
-          
+
           // 同步播放状态到LocalMusic的UI状态
           // 同步播放状态到LocalMusic的UI状态
           const previousStatus: PlayStatus = this.localMusic.CONTROL_PlayStatus;
           const previousStatus: PlayStatus = this.localMusic.CONTROL_PlayStatus;
-          
+
           // 根据状态模型确定UI状态
           // 根据状态模型确定UI状态
           if (isPlaying) {
           if (isPlaying) {
             this.localMusic.CONTROL_PlayStatus = PlayStatus.PLAY;
             this.localMusic.CONTROL_PlayStatus = PlayStatus.PLAY;
@@ -508,17 +508,17 @@ export struct LocalMusic {
           } else {
           } else {
             this.localMusic.CONTROL_PlayStatus = PlayStatus.INIT;
             this.localMusic.CONTROL_PlayStatus = PlayStatus.INIT;
           }
           }
-          
+
           // 更新播放状态相关的UI
           // 更新播放状态相关的UI
           this.localMusic.setIsPlaying(isPlaying);
           this.localMusic.setIsPlaying(isPlaying);
           this.localMusic.updateSessionPlayState(isPlaying);
           this.localMusic.updateSessionPlayState(isPlaying);
-          
+
           LogUtils.getInstance().LOGI(`LocalMusic: State sync - Previous: ${previousStatus}, New: ${this.localMusic.CONTROL_PlayStatus}, isPlaying: ${isPlaying}`);
           LogUtils.getInstance().LOGI(`LocalMusic: State sync - Previous: ${previousStatus}, New: ${this.localMusic.CONTROL_PlayStatus}, isPlaying: ${isPlaying}`);
-          
+
           // 强制触发UI更新,无论状态是否变化
           // 强制触发UI更新,无论状态是否变化
           this.localMusic.playChange();
           this.localMusic.playChange();
           this.localMusic.watchStatus();
           this.localMusic.watchStatus();
-          
+
           // 更新动画状态
           // 更新动画状态
           if (isPlaying) {
           if (isPlaying) {
             this.localMusic.animationState = AnimationStatus.Running;
             this.localMusic.animationState = AnimationStatus.Running;
@@ -527,22 +527,22 @@ export struct LocalMusic {
             this.localMusic.animationState = AnimationStatus.Paused;
             this.localMusic.animationState = AnimationStatus.Paused;
             this.localMusic.mDestroyPage = true;
             this.localMusic.mDestroyPage = true;
           }
           }
-          
+
           LogUtils.getInstance().LOGI(`LocalMusic: UI update completed - CONTROL_PlayStatus: ${this.localMusic.CONTROL_PlayStatus}, globalIsPlaying: ${this.localMusic.isPlaying}`);
           LogUtils.getInstance().LOGI(`LocalMusic: UI update completed - CONTROL_PlayStatus: ${this.localMusic.CONTROL_PlayStatus}, globalIsPlaying: ${this.localMusic.isPlaying}`);
-          
+
           // 同步播放模式
           // 同步播放模式
           if (this.localMusic.playType !== state.playMode) {
           if (this.localMusic.playType !== state.playMode) {
             this.localMusic.playType = state.playMode;
             this.localMusic.playType = state.playMode;
             this.localMusic.setCurrentPlayMode();
             this.localMusic.setCurrentPlayMode();
           }
           }
-          
+
           // 同步音量和速度
           // 同步音量和速度
           this.localMusic.volume = state.volume;
           this.localMusic.volume = state.volume;
           this.localMusic.playSpeed = state.speed;
           this.localMusic.playSpeed = state.speed;
-          
+
           LogUtils.getInstance().LOGI(`LocalMusic: State synchronized - isPlaying=${state.isPlaying}, mode=${state.playMode}`);
           LogUtils.getInstance().LOGI(`LocalMusic: State synchronized - isPlaying=${state.isPlaying}, mode=${state.playMode}`);
         }
         }
-        
+
         onSongChanged(song: VideoItem): void {
         onSongChanged(song: VideoItem): void {
           console.log(`Heanup onSongChanged - 开始处理歌曲切换: ${song.name}`);
           console.log(`Heanup onSongChanged - 开始处理歌曲切换: ${song.name}`);
           console.log(`Heanup onSongChanged - 切换前 oldSeconds: ${this.localMusic.oldSeconds}, currentTime: ${this.localMusic.currentTime}`);
           console.log(`Heanup onSongChanged - 切换前 oldSeconds: ${this.localMusic.oldSeconds}, currentTime: ${this.localMusic.currentTime}`);
@@ -716,6 +716,7 @@ export struct LocalMusic {
       this.saveVideoDatas([eventData.data?.message], true)
       this.saveVideoDatas([eventData.data?.message], true)
 
 
     });
     });
+    this.setAvSessionListener();
 
 
     //侧滑广播接收时间
     //侧滑广播接收时间
     let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
     let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
@@ -807,7 +808,7 @@ export struct LocalMusic {
     // 安全地注册窗口大小变化监听器
     // 安全地注册窗口大小变化监听器
     if (this.windowClass) {
     if (this.windowClass) {
       this.windowClass.on('windowSizeChange', (size) => {
       this.windowClass.on('windowSizeChange', (size) => {
-      LogUtil.info('onecold  windowSizeChange')
+        LogUtil.info('onecold  windowSizeChange')
         this.doChangeBarHeight()
         this.doChangeBarHeight()
         let viewWidth = px2vp(size.width);
         let viewWidth = px2vp(size.width);
         let viewHeight = px2vp(size.height);
         let viewHeight = px2vp(size.height);
@@ -1153,13 +1154,7 @@ export struct LocalMusic {
       }
       }
     }
     }
 
 
-    // 清理AvSession卡片监听器
-    try {
-      this.avSessionWidgetListener.destroy();
-      LogUtils.getInstance().LOGI('AvSession widget listener destroyed successfully');
-    } catch (error) {
-      LogUtils.getInstance().error(`Error during AvSession widget listener cleanup: ${error}`);
-    }
+    this.avSessionController.unregisterSessionListener();
   }
   }
 
 
   async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
   async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
@@ -2899,7 +2894,7 @@ export struct LocalMusic {
             Row() {
             Row() {
               Column(){
               Column(){
                 Text(item.md5Str?.includes('Lossless')?
                 Text(item.md5Str?.includes('Lossless')?
-                   Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
+                Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
                   .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
                   .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
                   .padding({ top: 3,right:6,left:6,bottom:3 })
                   .padding({ top: 3,right:6,left:6,bottom:3 })
                   .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
                   .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
@@ -3177,7 +3172,7 @@ export struct LocalMusic {
                     .padding({ top: 8 })
                     .padding({ top: 8 })
                     .maxLines(1)
                     .maxLines(1)
                     .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
                     .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
-                       this.videoLocalList[0].year.includes(this.UNKONWN)
+                    this.videoLocalList[0].year.includes(this.UNKONWN)
                       ?Visibility.None:Visibility.Visible)
                       ?Visibility.None:Visibility.Visible)
                     .fontWeight(FontWeight.Bold)
                     .fontWeight(FontWeight.Bold)
                     .fontColor($r('app.color.text_color'))
                     .fontColor($r('app.color.text_color'))
@@ -3843,7 +3838,7 @@ export struct LocalMusic {
       // if (this.isPhoneLan()) {
       // if (this.isPhoneLan()) {
       //   this.setBarHeightHide(offset)
       //   this.setBarHeightHide(offset)
       // } else
       // } else
-        if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
+      if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
         (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
         (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
           this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
           this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
         if (this.isScrollHide) {
         if (this.isScrollHide) {
@@ -3872,7 +3867,7 @@ export struct LocalMusic {
                   records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
                   records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
                 let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
                 let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
                 if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
                 if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
-                 ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
+                  ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
                   this.targetFile = fileUriUds.oriUri;
                   this.targetFile = fileUriUds.oriUri;
                   this.saveVideoDatas([this.targetFile])
                   this.saveVideoDatas([this.targetFile])
                   hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
                   hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
@@ -3987,7 +3982,7 @@ export struct LocalMusic {
                 }
                 }
                 .margin({ top: 2 ,right:6})
                 .margin({ top: 2 ,right:6})
                 .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
                 .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
-                     ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
+                  ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
                 Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
                 Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
                   .fontSize(11)
                   .fontSize(11)
                   .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
                   .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
@@ -4490,7 +4485,7 @@ export struct LocalMusic {
       // if (this.isPhoneLan()) {
       // if (this.isPhoneLan()) {
       //   this.setBarHeightHide(offset)
       //   this.setBarHeightHide(offset)
       // } else
       // } else
-        if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
+      if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
         (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
         (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
           this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
           this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
         if (this.isScrollHide) {
         if (this.isScrollHide) {
@@ -4507,7 +4502,7 @@ export struct LocalMusic {
       return { offsetRemain: offset };
       return { offsetRemain: offset };
     })
     })
 
 
-     //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
+    //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
     .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
     .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
     .onDrop((event?: DragEvent) => {
     .onDrop((event?: DragEvent) => {
       try {
       try {
@@ -6733,9 +6728,9 @@ export struct LocalMusic {
     let neiqianLrc = ''
     let neiqianLrc = ''
     let lyContent = this.currentSong?.lyricContent
     let lyContent = this.currentSong?.lyricContent
     if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
     if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
-       neiqianLrc = lyContent
+      neiqianLrc = lyContent
     }else{
     }else{
-       neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
+      neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
     }
     }
     if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
     if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
       console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
       console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
@@ -9946,7 +9941,7 @@ export struct LocalMusic {
         // 歌曲切换时,强制将播放位置重置为0,忽略服务报告的位置
         // 歌曲切换时,强制将播放位置重置为0,忽略服务报告的位置
         progress.currentPosition = 0;
         progress.currentPosition = 0;
         console.log(`Heanup 歌曲切换,强制progress.currentPosition为0`);
         console.log(`Heanup 歌曲切换,强制progress.currentPosition为0`);
-        
+
         // 立即返回,不更新进度,等待新歌曲开始播放
         // 立即返回,不更新进度,等待新歌曲开始播放
         return;
         return;
       }
       }
@@ -9957,7 +9952,7 @@ export struct LocalMusic {
         if (ijkPlayer && ijkPlayer.isPlaying()) {
         if (ijkPlayer && ijkPlayer.isPlaying()) {
           const currentPosition = ijkPlayer.getCurrentPosition();
           const currentPosition = ijkPlayer.getCurrentPosition();
           const duration = ijkPlayer.getDuration();
           const duration = ijkPlayer.getDuration();
-          
+
           if (duration > 0 && currentPosition >= 0) {
           if (duration > 0 && currentPosition >= 0) {
             // 更新进度条
             // 更新进度条
             this.slideEnable = true;
             this.slideEnable = true;
@@ -9977,7 +9972,7 @@ export struct LocalMusic {
             this.currentTime = this.stringForTime(currentPosition);
             this.currentTime = this.stringForTime(currentPosition);
             this.isCurrentTime = false;
             this.isCurrentTime = false;
             console.log(`Heanup 更新后 - oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`)
             console.log(`Heanup 更新后 - oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`)
-            
+
             // 继续执行后续的歌词更新等逻辑
             // 继续执行后续的歌词更新等逻辑
           }
           }
         }
         }
@@ -10098,10 +10093,10 @@ export struct LocalMusic {
         // 检查是否在切换后的冷却期内(切换后5秒内允许更大的时间跳跃)
         // 检查是否在切换后的冷却期内(切换后5秒内允许更大的时间跳跃)
         const timeSinceSwitch = this.lastSwitchTime ? Date.now() - this.lastSwitchTime : Number.MAX_VALUE;
         const timeSinceSwitch = this.lastSwitchTime ? Date.now() - this.lastSwitchTime : Number.MAX_VALUE;
         const isInCooldown = timeSinceSwitch < 5000; // 5秒冷却期
         const isInCooldown = timeSinceSwitch < 5000; // 5秒冷却期
-        
+
         // 如果时间差值过大,根据情况处理
         // 如果时间差值过大,根据情况处理
         const timeDiff = Math.abs(seconds - this.oldSeconds);
         const timeDiff = Math.abs(seconds - this.oldSeconds);
-        
+
         if (timeDiff > 10) {
         if (timeDiff > 10) {
           // 如果在冷却期内,允许更大的时间跳跃(可能是新歌曲开始播放)
           // 如果在冷却期内,允许更大的时间跳跃(可能是新歌曲开始播放)
           if (isInCooldown) {
           if (isInCooldown) {
@@ -10325,6 +10320,20 @@ export struct LocalMusic {
     this.setCurrentPlayMode()
     this.setCurrentPlayMode()
   }
   }
 
 
+  public async setAvSessionListener() {
+    if (!this.avSessionController) {
+      console.log('heanup setAvSessionListener error: avSessionController is null');
+      return;
+    }
+    this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
+    this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
+    this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
+    this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
+    console.log('heanup setAvSessionListener');
+    this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
+
+  }
+
   private sessionSetLoopModeCallback = (mode: number) => {
   private sessionSetLoopModeCallback = (mode: number) => {
     ToastUtil.showToast('当前播放模式:' + mode)
     ToastUtil.showToast('当前播放模式:' + mode)
     Logger.info('onecold 当前播放模式= ' + mode)
     Logger.info('onecold 当前播放模式= ' + mode)
@@ -10332,30 +10341,30 @@ export struct LocalMusic {
     if (hmPlayMode >= 4) {
     if (hmPlayMode >= 4) {
       hmPlayMode = 0
       hmPlayMode = 0
     }
     }
-      if (hmPlayMode === 1) {
-        this.setPlayModeViaService(1);
-        ToastUtil.showToast('单曲循环')
-      } else if (hmPlayMode === 0) {
-        this.setPlayModeViaService(2);
-        ToastUtil.showToast('单曲播完')
-      } else if (hmPlayMode === 3) {
-        this.setPlayModeViaService(3);
-        ToastUtil.showToast('随机播放')
-      } else if (hmPlayMode === 2) {
-        this.setPlayModeViaService(0);
-        ToastUtil.showToast('连续播放')
-      }
-      // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
-      let playBackState: avSession.AVPlaybackState = {
-        loopMode: hmPlayMode,
-      };
-      this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
-        console.info(`set setLoopMode AVPlaybackState successfully`);
-      }).catch((err: BusinessError) => {
-        console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
-      });
-
+    if (hmPlayMode === 1) {
+      this.setPlayModeViaService(1);
+      ToastUtil.showToast('单曲循环')
+    } else if (hmPlayMode === 0) {
+      this.setPlayModeViaService(2);
+      ToastUtil.showToast('单曲播完')
+    } else if (hmPlayMode === 3) {
+      this.setPlayModeViaService(3);
+      ToastUtil.showToast('随机播放')
+    } else if (hmPlayMode === 2) {
+      this.setPlayModeViaService(0);
+      ToastUtil.showToast('连续播放')
     }
     }
+    PreferencesUtil.putSync('musicPlayType', this.playType)
+    // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
+    let playBackState: avSession.AVPlaybackState = {
+      loopMode: hmPlayMode,
+    };
+    this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
+      console.info(`set setLoopMode AVPlaybackState successfully`);
+    }).catch((err: BusinessError) => {
+      console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
+    });
+  }
 
 
   setCurrentPlayMode() {
   setCurrentPlayMode() {
     if (!this.avSessionController) {
     if (!this.avSessionController) {
@@ -10399,11 +10408,12 @@ export struct LocalMusic {
       let playbackState: avSession.AVPlaybackState = {
       let playbackState: avSession.AVPlaybackState = {
         isFavorite: !this.isFac,
         isFavorite: !this.isFac,
       };
       };
-      this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
-        console.info(`SetAVPlaybackState successfully`);
-      }).catch((err: BusinessError) => {
-        console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
-      });
+      // this.avSessionController.setAvSessionPlayState(playbackState);
+      // this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
+      //   console.info(`SetAVPlaybackState successfully`+assetId+this.isFac);
+      // }).catch((err: BusinessError) => {
+      //   console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
+      // });
     }
     }
   }
   }
   private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
   private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
@@ -10629,21 +10639,6 @@ export struct LocalMusic {
     }
     }
   }
   }
 
 
-  private sessionPlayCallback = (): void => {
-    LogUtils.getInstance().LOGI("LocalMusic: System play button pressed");
-    // 直接调用UnifiedPlayerService的方法,而不是LocalMusic的playOrPause
-    this.unifiedPlayerService.startPlayOrResumePlay().catch((error: Error) => {
-      LogUtils.getInstance().LOGI(`LocalMusic: System play command failed: ${error}`);
-    });
-  };
-  private sessionPauseCallback = (): void => {
-    LogUtils.getInstance().LOGI("LocalMusic: System pause button pressed");
-    // 直接调用UnifiedPlayerService的方法,而不是LocalMusic的playOrPause
-    this.unifiedPlayerService.pause().catch((error: Error) => {
-      LogUtils.getInstance().LOGI(`LocalMusic: System pause command failed: ${error}`);
-    });
-  };
-
   private playOrPause() {
   private playOrPause() {
     if (!this.debounce()) {
     if (!this.debounce()) {
       return;
       return;
@@ -10657,15 +10652,6 @@ export struct LocalMusic {
     }
     }
   }
   }
 
 
-  private sessionPlayNextCallback = (): void => {
-    this.playNext()
-  };
-  private sessionPlayPreviousCallback = (): void => {
-    this.playPrevious()
-  };
-  private sessionStopCallback = (): void => {
-    this.stop()
-  };
   private sessionFastForwardCallback = (time?: number) => {
   private sessionFastForwardCallback = (time?: number) => {
     if (!time) {
     if (!time) {
       return;
       return;
@@ -10731,11 +10717,11 @@ export struct LocalMusic {
     if (seeTime < 0) {
     if (seeTime < 0) {
       seeTime = 0;
       seeTime = 0;
     } else if (seeTime > this.duration) {
     } else if (seeTime > this.duration) {
-        seeTime = this.duration;
-      }
-      Logger.info('onecold seeTime= ' + seeTime)
-      this.setSeekToActionProgress(seeTime)
-      this.seekTo(seeTime + "")
+      seeTime = this.duration;
+    }
+    Logger.info('onecold seeTime= ' + seeTime)
+    this.setSeekToActionProgress(seeTime)
+    this.seekTo(seeTime + "")
   };
   };
   private sessionSeekCallback = (seekTime: number) => {
   private sessionSeekCallback = (seekTime: number) => {
     const curPosition: number = this.unifiedPlayerService.getCurrentPosition()
     const curPosition: number = this.unifiedPlayerService.getCurrentPosition()
@@ -10968,18 +10954,18 @@ export struct LocalMusic {
           this.changeImageAnimation();
           this.changeImageAnimation();
 
 
         }
         }
-        
+
         LogUtils.getInstance().LOGI("LocalMusic: playNext completed via UnifiedPlayerService");
         LogUtils.getInstance().LOGI("LocalMusic: playNext completed via UnifiedPlayerService");
       }
       }
     } catch (error) {
     } catch (error) {
       LogUtils.getInstance().LOGI(`LocalMusic playNext error: ${error}`);
       LogUtils.getInstance().LOGI(`LocalMusic playNext error: ${error}`);
       ToastUtil.showToast(`切换下一首失败: ${error}`);
       ToastUtil.showToast(`切换下一首失败: ${error}`);
-      
+
       // 错误处理:回退到原有逻辑
       // 错误处理:回退到原有逻辑
       this.fallbackPlayNext();
       this.fallbackPlayNext();
     }
     }
   }
   }
-  
+
   // 回退到原有的playNext逻辑
   // 回退到原有的playNext逻辑
   private fallbackPlayNext() {
   private fallbackPlayNext() {
     if (ArrayUtil.isNotEmpty(this.songList)) {
     if (ArrayUtil.isNotEmpty(this.songList)) {
@@ -10988,10 +10974,10 @@ export struct LocalMusic {
       } else {
       } else {
         this.curIndex++;
         this.curIndex++;
       }
       }
-      
+
       AppStorage.setOrCreate('songList', this.songList);
       AppStorage.setOrCreate('songList', this.songList);
       AppStorage.setOrCreate('currIndex', this.curIndex);
       AppStorage.setOrCreate('currIndex', this.curIndex);
-      
+
       this.CONTROL_PlayStatus = PlayStatus.INIT;
       this.CONTROL_PlayStatus = PlayStatus.INIT;
       this.stop();
       this.stop();
       this.currentSong = this.songList[this.curIndex]
       this.currentSong = this.songList[this.curIndex]
@@ -11117,24 +11103,24 @@ export struct LocalMusic {
     if (!this.debounce()) {
     if (!this.debounce()) {
       return;
       return;
     }
     }
-    
+
     try {
     try {
       if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
       if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
         this.randomModePlayFromHistory()
         this.randomModePlayFromHistory()
         return;
         return;
       }
       }
-      
+
       if (ArrayUtil.isNotEmpty(this.songList)) {
       if (ArrayUtil.isNotEmpty(this.songList)) {
         // 确保播放列表已同步到UnifiedPlayerService
         // 确保播放列表已同步到UnifiedPlayerService
         this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
         this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
-        
+
         // 使用UnifiedPlayerService播放上一首
         // 使用UnifiedPlayerService播放上一首
         await this.unifiedPlayerService.playPrevious();
         await this.unifiedPlayerService.playPrevious();
-        
+
         // 更新本地状态以保持UI同步
         // 更新本地状态以保持UI同步
         const currentIndex = this.unifiedPlayerService.getCurrentIndex();
         const currentIndex = this.unifiedPlayerService.getCurrentIndex();
         const currentSong = this.unifiedPlayerService.getCurrentSong();
         const currentSong = this.unifiedPlayerService.getCurrentSong();
-        
+
         if (currentSong) {
         if (currentSong) {
           this.curIndex = currentIndex;
           this.curIndex = currentIndex;
           this.currentSong = currentSong;
           this.currentSong = currentSong;
@@ -11142,14 +11128,14 @@ export struct LocalMusic {
           this.name = currentSong.name;
           this.name = currentSong.name;
           this.artist = currentSong.artist;
           this.artist = currentSong.artist;
           this.cover = currentSong.pixelMapPath;
           this.cover = currentSong.pixelMapPath;
-          
+
           // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
           // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
           this.oldSeconds = 0;
           this.oldSeconds = 0;
           this.currentTime = "00:00";
           this.currentTime = "00:00";
           this.lastSongPath = currentSong.filePath;
           this.lastSongPath = currentSong.filePath;
           this.justSwitched = true; // 标记歌曲刚刚切换
           this.justSwitched = true; // 标记歌曲刚刚切换
           console.log(`Heanup playPrevious - 重置时间显示状态: oldSeconds=${this.oldSeconds}, currentTime=${this.currentTime}`);
           console.log(`Heanup playPrevious - 重置时间显示状态: oldSeconds=${this.oldSeconds}, currentTime=${this.currentTime}`);
-          
+
           // 同步到AppStorage,确保卡片能获取到最新状态
           // 同步到AppStorage,确保卡片能获取到最新状态
           AppStorage.setOrCreate('songList', this.songList);
           AppStorage.setOrCreate('songList', this.songList);
           AppStorage.setOrCreate('currIndex', this.curIndex);
           AppStorage.setOrCreate('currIndex', this.curIndex);
@@ -11158,17 +11144,17 @@ export struct LocalMusic {
           this.changeImageAnimation();
           this.changeImageAnimation();
         }
         }
       }
       }
-      
+
       LogUtils.getInstance().LOGI("LocalMusic: playPrevious completed via UnifiedPlayerService");
       LogUtils.getInstance().LOGI("LocalMusic: playPrevious completed via UnifiedPlayerService");
     } catch (error) {
     } catch (error) {
       LogUtils.getInstance().LOGI(`LocalMusic playPrevious error: ${error}`);
       LogUtils.getInstance().LOGI(`LocalMusic playPrevious error: ${error}`);
       ToastUtil.showToast(`切换上一首失败: ${error}`);
       ToastUtil.showToast(`切换上一首失败: ${error}`);
-      
+
       // 错误处理:回退到原有逻辑
       // 错误处理:回退到原有逻辑
       this.fallbackPlayPrevious();
       this.fallbackPlayPrevious();
     }
     }
   }
   }
-  
+
   // 回退到原有的playPrevious逻辑
   // 回退到原有的playPrevious逻辑
   private fallbackPlayPrevious() {
   private fallbackPlayPrevious() {
     if (this.curIndex == 0) {
     if (this.curIndex == 0) {
@@ -11610,82 +11596,6 @@ export struct LocalMusic {
     // this.status = "广告加载中..."
     // this.status = "广告加载中..."
   }
   }
 
 
-  /**
-   * 展示Banner广告
-   */
-  // showBannerAd() {
-  //   if (!this.bannerAd) {
-  //     return
-  //   }
-  //   this.isShowAd = true
-  //   this.status = "已展示"
-  // }
-
-  /**
-   * 穿山甲广告代码结束
-   */
-
-  /**
-   * 初始化AvSession卡片监听器
-   */
-  private initAvSessionWidgetListener(): void {
-    try {
-      // 不需要在这里注册监听器,因为我们直接通过updateWidgetData更新数据
-      // 避免循环调用和重复广播
-      LogUtils.getInstance().LOGI('AvSession widget listener initialized successfully (no circular listener)');
-    } catch (error) {
-      LogUtils.getInstance().error(`Failed to initialize AvSession widget listener: ${error}`);
-    }
-  }
-
-  /**
-   * 广播AvSession状态到卡片
-   */
-  private broadcastAvSessionStateToWidget(widgetData: WidgetData): void {
-    try {
-      // 广播播放状态变化
-      const statePublishInfo: commonEventManager.CommonEventPublishData = {
-        data: JSON.stringify(widgetData)
-      };
-
-      commonEventManager.publish(PLAYER_STATE_CHANGED_EVENT, statePublishInfo, (err) => {
-        if (err) {
-          LogUtils.getInstance().error(`Failed to broadcast AvSession state: ${JSON.stringify(err)}`);
-        } else {
-          LogUtils.getInstance().LOGI('AvSession state broadcasted to widget successfully');
-        }
-      });
-
-      // 如果有歌曲信息变化,也广播歌曲变化事件
-      if (widgetData.currentSong) {
-        const songPublishInfo: commonEventManager.CommonEventPublishData = {
-          data: JSON.stringify({ currentSong: widgetData.currentSong })
-        };
-
-        commonEventManager.publish(PLAYER_SONG_CHANGED_EVENT, songPublishInfo, (err) => {
-          if (err) {
-            LogUtils.getInstance().error(`Failed to broadcast song change: ${JSON.stringify(err)}`);
-          }
-        });
-      }
-
-      // 如果有进度信息变化,也广播进度变化事件
-      if (widgetData.progress) {
-        const progressPublishInfo: commonEventManager.CommonEventPublishData = {
-          data: JSON.stringify(widgetData.progress)
-        };
-
-        commonEventManager.publish(PLAYER_PROGRESS_CHANGED_EVENT, progressPublishInfo, (err) => {
-          if (err) {
-            LogUtils.getInstance().error(`Failed to broadcast progress change: ${JSON.stringify(err)}`);
-          }
-        });
-      }
-    } catch (error) {
-      LogUtils.getInstance().error(`Failed to broadcast AvSession state to widget: ${error}`);
-    }
-  }
-
   /**
   /**
    * 节流广播进度更新
    * 节流广播进度更新
    */
    */