| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775 |
- import { VideoItem } from '../../viewmodel/VideoItem';
- import { PlayerManager, IPlayerManager, PlayerStateCallback } from './PlayerManager';
- import { PlayerStateModel, PlayerState, PlayerStateListener, PlayMode, PlayerError, PlayerErrorType } from './PlayerStateModel';
- import { PlaylistModel } from './PlaylistModel';
- import { PlayProgress, WidgetData, WidgetSize, WidgetTheme } from '../widget/WidgetTypes';
- import { IjkMediaPlayer, LogUtils } from '@ohos/ijkplayer';
- import { common } from '@kit.AbilityKit';
- import { PreferencesUtil, StrUtil } from '@pura/harmony-utils';
- import { DataPersistenceService, PlaylistSyncService, PlaylistSyncListener, IDataPersistenceService, PlaylistData,
- PlayerStateData } from './DataPersistenceService';
- import { StateSyncService, IStateSyncService, StateChangeCallback, WidgetControlCallback } from './StateSyncService';
- import { ErrorRecoveryStrategy, IErrorRecoveryStrategy, ErrorContext, ErrorRecoveryAction } from './ErrorRecoveryStrategy';
- import { EnhancedFormUpdateService, UpdateStats } from '../widget/EnhancedFormUpdateService';
- import { AvSessionController } from '../../controller/AvSessionController';
- import { avSession } from '@kit.AVSessionKit';
- import json from '@ohos.util.json';
- import { Utility } from '../util/Utility';
- import MediaTable from '../util/MediaTable';
- /**
- * 服务就绪状态详情接口
- */
- export interface ServiceReadinessDetails {
- initialized: boolean;
- hasPlayerInstance: boolean;
- hasContext: boolean;
- dataRestored: boolean;
- playlistSize: number;
- currentIndex: number;
- }
- /**
- * 服务就绪信息接口
- */
- export interface ServiceReadinessInfo {
- isReady: boolean;
- details: ServiceReadinessDetails;
- }
- /**
- * 初始化验证结果接口
- */
- export interface InitializationValidation {
- isValid: boolean;
- errors: string[];
- warnings: string[];
- }
- /**
- * 统一播放器服务接口
- * 提供统一的播放控制接口,替代LocalMusic中的播放器逻辑
- */
- export interface IPlayerService {
- /**
- * 启动播放或恢复播放
- * @returns
- */
- startPlayOrResumePlay(): Promise<void>;
- /**
- * 暂停播放
- * @returns
- */
- pause(): Promise<void>;
- /**
- * 停止播放
- * @returns
- */
- stop(): Promise<void>;
- /**
- * 跳转到指定位置
- * @param position
- * @returns
- */
- seekTo(position: string): Promise<void>;
- // 播放列表控制 - 基于LocalMusic现有方法
- /**
- * 播放下一首
- * @returns
- */
- playNext(): Promise<void>;
- /**
- * 播放上一首
- */
- playPrevious(): Promise<void>;
- /**
- * 播放指定索引的歌
- * @param index
- * @returns
- */
- playSongAtIndex(index: number): Promise<void>;
- /**
- * 获取播放器状态
- * @returns
- */
- getCurrentState(): PlayerState;
- /**
- * 获取实际播放状态
- * @returns 实际播放状态
- */
- getActualPlayingState(): boolean;
- /**
- * 获取当前播放歌曲
- * @returns
- */
- getCurrentSong(): VideoItem | null;
- /**
- * 获取播放列表
- * @returns
- */
- getPlaylist(): VideoItem[];
- /**
- * 获取当前播放索引
- * @returns
- */
- getCurrentIndex(): number;
- /**
- * 获取当前播放进度
- * @returns 当前播放进度
- */
- getCurrentPosition(): number;
- /**
- * 获取播放器实例
- * @returns 播放器实例
- */
- getIjkPlayer(): IjkMediaPlayer | null;
- /**
- * 是否数据恢复完成
- * @returns 是否数据恢复完成
- * */
- isDataRestorationCompleted(): boolean;
- /**
- * 等待数据恢复完成
- * @param maxWaitMs 最大等待时间(毫秒),默认为-1(无限等待)
- * @returns 是否恢复完成
- */
- waitForDataRestoration(maxWaitMs?: number): Promise<boolean>;
- /**
- * 强制数据恢复
- * @returns 是否恢复成功
- */
- forceDataRestoration(): Promise<boolean>;
- /**
- * 是否就绪
- * @returns
- */
- isAllServicesReady(): boolean;
- /**
- * 等待服务就绪
- * @param maxWaitMs 最大等待时间(毫秒),默认为-1(无限等待)
- * @param checkDataRestore 是否检查数据恢复状态,默认为true
- * @returns 是否就绪
- */
- waitForAllServicesReady(maxWaitMs?: number, checkDataRestore?: boolean): Promise<boolean>;
- /**
- * 获取服务就绪信息
- * @returns 服务就绪信息
- */
- getServiceReadinessInfo(): ServiceReadinessInfo;
- /**
- * 初始化验证
- * @returns 初始化验证结果
- */
- validateInitialization(): InitializationValidation;
- /**
- * 设置播放模式
- * @param mode
- */
- setPlayMode(mode: number): void;
- /**
- * 获取播放模式
- * @returns 播放模式
- */
- getPlayMode(): number;
- /**
- * 设置音量
- * @param volume
- */
- setVolume(volume: number): void;
- /**
- * 设置播放速度
- * @param speed
- */
- setPlaybackSpeed(speed: number): void;
- // 播放列表管理
- /**
- * 设置播放列表
- * @param songs
- * @param currentIndex
- */
- setPlaylist(songs: VideoItem[], currentIndex?: number): void;
- /**
- * 添加歌曲到播放列表
- * @param song
- * @param index
- */
- addToPlaylist(song: VideoItem, index?: number): void;
- /**
- * 移除播放列表中的歌曲
- * @param index
- * @returns 移除的歌曲
- */
- removeFromPlaylist(index: number): VideoItem | null;
- // 事件监听
- /**
- * 添加播放器状态监听
- * @param listener
- */
- addStateListener(listener: PlayerStateListener): void;
- /**
- * 移除播放器状态监听
- * @param listener
- */
- removeStateListener(listener: PlayerStateListener): void;
- /**
- * 初始化
- * @param context
- * @returns
- */
- initialize(context: common.UIAbilityContext): Promise<void>;
- /**
- * 释放资源
- */
- release(): void;
- }
- /**
- * 统一播放器服务实现
- * 整合PlayerManager、PlayerStateModel和PlaylistModel
- */
- export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListener, StateChangeCallback, WidgetControlCallback, PlayerStateCallback {
- private static instance: UnifiedPlayerService | null = null;
- private playerManager: IPlayerManager;
- private stateModel: PlayerStateModel;
- private playlistModel: PlaylistModel;
- private dataPersistence: IDataPersistenceService;
- private playlistSync: PlaylistSyncService;
- private stateSync: IStateSyncService;
- private errorRecovery: IErrorRecoveryStrategy;
- private widgetUpdateService: EnhancedFormUpdateService;
- private avSessionController: AvSessionController | null = null;
- private context: common.UIAbilityContext | null = null;
- private progressTimer: number = -1;
- private isInitialized: boolean = false;
- private isDataRestored: boolean = false; // 新增:数据恢复完成标识
- private isPlayerPreparedForCurrentSong: boolean = false; // 新增:播放器是否已为当前歌曲准备就绪
- private currentRetryCount: number = 0;
- private lastAvSessionUpdate: number = 0;
- private lastAvMetadataUpdate: number = 0; // 新增:上次元数据更新时间
- private avSessionUpdateTimer: number = -1; // 新增:系统播控更新防抖定时器
- private avMetadataUpdateTimer: number = -1; // 新增:元数据更新防抖定时器
- private lastUpdateTime: number=0;
- private favList: VideoItem[]=[];
- table: undefined;
- private lastAutoPlayTime: number = 0; // 新增:上次自动播放时间,用于防抖
- private autoPlayDebounceMs: number = 1000; // 自动播放防抖间隔(毫秒)
- private constructor() {
- this.playerManager = PlayerManager.getInstance();
- this.stateModel = new PlayerStateModel();
- this.playlistModel = new PlaylistModel();
- this.dataPersistence = DataPersistenceService.getInstance();
- this.playlistSync = PlaylistSyncService.getInstance();
- this.stateSync = StateSyncService.getInstance();
- this.errorRecovery = ErrorRecoveryStrategy.getInstance();
- this.widgetUpdateService = EnhancedFormUpdateService.getInstance();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Instance created');
- }
- public static getInstance(): UnifiedPlayerService {
- if (!UnifiedPlayerService.instance) {
- UnifiedPlayerService.instance = new UnifiedPlayerService();
- }
- return UnifiedPlayerService.instance;
- }
- async initialize(context: common.UIAbilityContext): Promise<void> {
- if (this.isInitialized && this.context === context) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService已经初始化过了');
- return;
- }
- try {
- console.log("Heanup2 UnifiedPlayerService: 开始快速初始化服务");
- this.context = context;
- // 快速初始化核心组件
- this.playerManager.setStateCallback(this);
- this.widgetUpdateService.setAppContext(context);
- // 设置同步监听器
- this.playlistSync.addSyncListener(this);
- this.stateSync.subscribeToStateChanges(this);
- this.stateSync.subscribeToWidgetControl(this);
- // 设置状态模型监听器,自动广播状态变化
- class StateListenerImpl implements PlayerStateListener {
- private stateSync: IStateSyncService;
- private unifiedService: UnifiedPlayerService;
- constructor(stateSync: IStateSyncService, unifiedService: UnifiedPlayerService) {
- this.stateSync = stateSync;
- this.unifiedService = unifiedService;
- }
- onStateChanged(state: PlayerState): void {
- this.stateSync.broadcastState(state);
- // 使用防抖机制更新系统播控,避免频繁更新
- this.unifiedService.updateSessionPlayState();
- // 状态变化时更新卡片
- this.unifiedService.updateWidgetsForStateChange();
- }
- onSongChanged(song: VideoItem): void {
- this.stateSync.broadcastSongChange(song);
- // 使用防抖机制更新系统播控元数据,避免频繁更新
- this.unifiedService.updateAvSessionMetadata(song);
- // 歌曲变化时更新卡片
- this.unifiedService.updateWidgetsForSongChange(song);
- }
- onProgressChanged(progress: PlayProgress): void {
- this.stateSync.broadcastProgress(progress);
- // 进度变化时更新卡片(防抖处理)
- this.unifiedService.updateWidgetsForProgressChange(progress);
- }
- onError(error: PlayerError): void {
- LogUtils.getInstance().LOGI(`Player error: ${error.message}`);
- }
- }
- const stateListener = new StateListenerImpl(this.stateSync, this);
- this.stateModel.addStateListener(stateListener);
- this.setupProgressTimer();
- this.isInitialized = true;
- // 异步初始化耗时组件,避免阻塞
- this.initializeHeavyComponentsAsync(context);
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Core initialization completed');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService initialization error: ${error}`);
- throw new Error(`初始化失败: ${error}`);
- }
- }
- /**
- * 异步初始化耗时组件
- */
- private initializeHeavyComponentsAsync(context: common.UIAbilityContext): void {
- setTimeout(async () => {
- try {
- console.log("Heanup2 UnifiedPlayerService: 开始异步初始化耗时组件");
- // 并行初始化各个服务以提高效率
- const initPromises = [
- this.playerManager.initialize(context),
- this.dataPersistence.initialize(context),
- this.playlistSync.initialize(context),
- this.stateSync.initialize(context)
- ];
- await Promise.all(initPromises);
- // 立即尝试快速恢复关键数据(从AppStorage)
- await this.fastRestoreFromMemory();
- this.initializeAvSession();
- // 完整的数据恢复(从持久化存储)
- await this.restorePersistedState();
- console.log("Heanup2 UnifiedPlayerService: 异步组件初始化完成");
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Heavy components initialized');
- } catch (error) {
- console.log(`Heanup2 UnifiedPlayerService: 异步组件初始化失败: ${error}`);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService heavy components init error: ${error}`);
- // 即使失败也设置数据恢复完成,避免无限等待
- this.isDataRestored = true;
- }
- }, 10); // 缩短延迟,让数据恢复更快开始
- }
- // 播放控制方法
- async startPlayOrResumePlay(): Promise<void> {
- try {
- console.log("Heanup2 UnifiedPlayerService: 开始恢复播放");
- // 统一的服务就绪检查 - 这是最核心的检查
- if (!this.isAllServicesReady()) {
- console.log("Heanup2 UnifiedPlayerService: 服务未就绪,等待服务初始化完成");
- const isReady = await this.waitForAllServicesReady(3000, false);
- if (!isReady) {
- const error = new Error('Services not ready for playback');
- await this.handlePlaybackError(error, PlayerErrorType.INITIALIZATION_ERROR);
- return;
- }
- }
- // 获取当前歌曲 - 如果没有就尝试恢复
- let currentSong = this.playlistModel.getCurrentSong();
- if (!currentSong) {
- console.log("Heanup2 UnifiedPlayerService: 没有可播放的歌曲,尝试恢复持久化状态");
- await this.restorePersistedState();
- currentSong = this.playlistModel.getCurrentSong();
- if (!currentSong) {
- console.log("Heanup2 UnifiedPlayerService: 恢复后仍然没有可播放的歌曲");
- await this.handlePlaybackError(new Error('No song to play'), PlayerErrorType.PLAYBACK_ERROR);
- return;
- }
- console.log("Heanup2 UnifiedPlayerService: 恢复成功,当前歌曲信息:"+json.stringify(currentSong));
- }
- this.stateModel.updateLoadingState(true);
- // 简化的播放器状态检查 - 检查是否可以从暂停恢复
- const ijkPlayer = this.playerManager.getIjkPlayer()!; // 服务就绪后播放器一定存在
- const shouldResumeFromPause = this.canResumeFromPause(ijkPlayer);
- if (shouldResumeFromPause) {
- console.log("Heanup2 UnifiedPlayerService: 从暂停状态恢复播放");
- return await this.resumeFromPause();
- }
- // 新歌播放前的必要检查
- await this.validateSongForPlayback(currentSong);
- // 设置播放器并开始播放
- await this.setupAndStartPlayback(currentSong);
- } catch (error) {
- this.stateModel.updateLoadingState(false);
- this.stateModel.updatePlayingState(false);
- await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
- }
- }
- /**
- * 检查是否可以从暂停状态恢复播放
- */
- private canResumeFromPause(ijkPlayer: IjkMediaPlayer): boolean {
- const isPausedByManager = this.playerManager.isPausedState();
- const isCurrentlyPlaying = ijkPlayer.isPlaying();
- const playerDuration = ijkPlayer.getDuration();
- const hasValidMedia = playerDuration > 0;
- // 如果认为是暂停但没有有效媒体,清除假暂停状态
- if (isPausedByManager && !hasValidMedia) {
- console.log("Heanup2 UnifiedPlayerService: 检测到假暂停状态,清除暂停标记");
- this.playerManager.clearPausedState();
- this.isPlayerPreparedForCurrentSong = false;
- return false;
- }
- // 如果播放器正在播放,同步状态
- if (isCurrentlyPlaying) {
- this.syncPlayingState();
- return false; // 不需要恢复,已经在播放
- }
- // 检查是否可以从暂停恢复
- const canResume = isPausedByManager &&
- !isCurrentlyPlaying &&
- hasValidMedia &&
- this.isPlayerPreparedForCurrentSong;
- console.log(`Heanup2 UnifiedPlayerService: 暂停恢复检查 - canResume: ${canResume}`);
- return canResume;
- }
- /**
- * 同步播放状态
- */
- private syncPlayingState(): void {
- console.log("Heanup2 UnifiedPlayerService: 播放器正在播放,同步状态");
- this.stateModel.updateLoadingState(false);
- this.stateModel.updatePlayingState(true);
- this.playerManager.clearPausedState();
- this.startProgressTimer();
- this.updateSessionPlayState();
- this.updateWidgetsForStateChange();
- }
- /**
- * 从暂停状态恢复播放
- */
- private async resumeFromPause(): Promise<void> {
- try {
- console.log("Heanup2 UnifiedPlayerService: 直接从暂停状态恢复播放");
- this.stateModel.updateLoadingState(false);
- await this.playerManager.startPlayOrResumePlay();
- this.stateModel.updatePlayingState(true);
- this.startProgressTimer();
- setTimeout(() => this.updateProgress(), 100);
- this.saveCurrentState();
- this.updateSessionPlayState();
- await this.updateWidgetsForPlayStateChange();
- } catch (error) {
- throw new Error(`Resume from pause failed: ${error}`);
- }
- }
- /**
- * 验证歌曲是否可以播放
- */
- private async validateSongForPlayback(song: VideoItem): Promise<void> {
- // 检查文件是否存在(对于本地文件)
- if (!song.filePath.startsWith('http')) {
- const fileExists = await this.checkFileExists(song.filePath);
- if (!fileExists) {
- throw new Error(`File not found: ${song.filePath}`);
- }
- } else {
- // 检查网络连接(对于网络资源)
- const networkAvailable = await this.checkNetworkConnection();
- if (!networkAvailable) {
- throw new Error('Network not available');
- }
- }
- }
- /**
- * 设置播放器并开始播放
- */
- private async setupAndStartPlayback(song: VideoItem): Promise<void> {
- console.log(`Heanup2 UnifiedPlayerService: 设置播放器并开始播放: ${song.name}`);
- // 设置播放源和配置
- await this.setupPlayerForSong(song);
- // 准备播放器(实际播放会在 onPrepared 回调中开始)
- const preparedPlayer = this.playerManager.getIjkPlayer();
- if (preparedPlayer) {
- preparedPlayer.prepareAsync();
- }
- // 立即更新基础元数据(使用解析的duration),后续在播放器准备好后会用实际duration更新
- await this.updateAvSessionMetadata(song);
- this.restorePlaybackPosition(song);
- this.currentRetryCount = 0;
- }
- /**
- * 直接播放新歌曲,避免恢复逻辑干扰
- * 专为 playNext/playPrevious 设计
- */
- private async playNewSongDirectly(song: VideoItem | null): Promise<void> {
- if (!song) {
- throw new Error('No song provided for direct play');
- }
- 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) {
- preparedPlayer.prepareAsync();
- // 注意:实际播放和状态更新会在 onPrepared 回调中开始
- }
- // 重置重试计数
- this.currentRetryCount = 0;
- }
- async pause(): Promise<void> {
- try {
- // 检查服务是否已准备就绪
- if (!this.isAllServicesReady()) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: pause - 服务未就绪');
- // 对于暂停操作,如果服务未就绪,可以尝试简单的状态更新
- this.stateModel.updatePlayingState(false);
- return;
- }
- // 保存当前播放位置
- this.savePlaybackPosition();
- // 暂停播放器 - 确保先暂停播放器
- this.playerManager.pausePlayback();
- // 立即更新状态模型为暂停状态,确保状态同步
- this.stateModel.updatePlayingState(false);
- // 停止进度定时器
- this.stopProgressTimer();
- // 等待一小段时间确保播放器状态稳定
- await new Promise<void>(resolve => setTimeout(resolve, 50));
- // 保存播放状态变化
- this.saveCurrentState();
- this.updateSessionPlayState();
- // 更新卡片显示暂停状态
- await this.updateWidgetsForPlayStateChange();
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService pause error: ${error}`);
- }
- }
- async stop(): Promise<void> {
- try {
- this.savePlaybackPosition();
- this.playerManager.stopPlayback();
- this.stateModel.updatePlayingState(false);
- this.stateModel.updateProgress(0, 0);
- this.stopProgressTimer();
- // 更新卡片显示暂停状态
- await this.updateWidgetsForPlayStateChange();
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService stop error: ${error}`);
- throw new Error;
- }
- }
- /**
- * 静默停止播放,不触发状态变化通知(用于歌曲切换)
- */
- private async stopSilently(): Promise<void> {
- try {
- this.savePlaybackPosition();
- this.playerManager.stopPlayback();
- this.stopProgressTimer();
- // 不调用 updatePlayingState,避免触发状态变化通知
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService stopSilently error: ${error}`);
- throw new Error;
- }
- }
- async seekTo(position: string): Promise<void> {
- try {
- const currentSong = this.playlistModel.getCurrentSong();
- if (!currentSong) {
- throw new Error('No song to seek');
- }
- // 检查是否支持拖动(wma格式不支持)
- if (StrUtil.isNotEmpty(currentSong.filePath) &&
- currentSong.filePath.toLowerCase().endsWith('.wma')) {
- throw new Error('WMA format does not support seeking');
- }
- await this.playerManager.seekToPosition(position);
- } catch (error) {
- throw new Error(`Failed to seek to position: ${error}`);
- }
- }
- // 播放列表控制方法
- async playNext(): Promise<void> {
- try {
- // 首先检查服务是否已准备就绪
- if (!this.isAllServicesReady()) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: playNext - 服务未就绪,等待服务初始化完成');
- // 在自动播放场景下,减少等待时间避免阻塞
- const isReady = await this.waitForAllServicesReady(500, false);
- if (!isReady) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Services not ready for playNext, skipping');
- return; // 直接返回,不抛出错误
- }
- }
- const playMode = this.stateModel.getState().playMode;
- if (!this.playlistModel.hasNext(playMode)) {
- return;
- }
- const moved = this.playlistModel.moveToNext(playMode);
- if (!moved) {
- return;
- }
- // 更新状态模型的索引
- const newIndex = this.playlistModel.getCurrentIndex();
- const newSong = this.playlistModel.getCurrentSong();
- this.stateModel.updateCurrentIndex(newIndex);
- if (newSong) {
- this.stateModel.updateCurrentSong(newSong);
- }
- // 静默停止当前播放(不触发状态变化通知)
- await this.stopSilently();
- // 直接播放新歌曲,不调用通用的恢复逻辑
- await this.playNewSongDirectly(newSong);
- // 更新状态模型中的播放列表状态
- this.updatePlaylistStateInModel();
- // 强制更新卡片显示新歌曲(重要事件)
- if (newSong) {
- await this.updateWidgetsForSongChange(newSong, true);
- }
- } catch (error) {
- await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
- }
- }
- async playPrevious(): Promise<void> {
- try {
- // 首先检查服务是否已准备就绪
- if (!this.isAllServicesReady()) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: playPrevious - 服务未就绪,等待服务初始化完成');
- const isReady = await this.waitForAllServicesReady(500, false);
- if (!isReady) {
- const error = new Error('Services not ready for playPrevious');
- await this.handlePlaybackError(error, PlayerErrorType.INITIALIZATION_ERROR);
- return;
- }
- }
- const playMode = this.stateModel.getState().playMode;
- if (!this.playlistModel.hasPrevious(playMode)) {
- return;
- }
- // 先获取当前歌曲信息用于日志
- const currentSong = this.playlistModel.getCurrentSong();
- const currentIndex = this.playlistModel.getCurrentIndex();
- const moved = this.playlistModel.moveToPrevious(playMode);
- if (!moved) {
- return;
- }
- // 更新状态模型的索引
- const newIndex = this.playlistModel.getCurrentIndex();
- const newSong = this.playlistModel.getCurrentSong();
- this.stateModel.updateCurrentIndex(newIndex);
- if (newSong) {
- this.stateModel.updateCurrentSong(newSong);
- }
- // 静默停止当前播放(不触发状态变化通知)
- await this.stopSilently();
- // 直接播放新歌曲,不调用通用的恢复逻辑
- await this.playNewSongDirectly(newSong);
- // 更新状态模型中的播放列表状态
- this.updatePlaylistStateInModel();
- // 强制更新卡片显示新歌曲(重要事件)
- if (newSong) {
- await this.updateWidgetsForSongChange(newSong, true);
- }
- } catch (error) {
- await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
- }
- }
- async playSongAtIndex(index: number): Promise<void> {
- try {
- const success = this.playlistModel.playSongAtIndex(index);
- if (!success) {
- throw new Error(`Invalid song index: ${index}`);
- }
- this.stateModel.updateCurrentIndex(index);
- // 静默停止当前播放并开始新歌曲(不触发状态变化通知)
- await this.stopSilently();
- await this.startPlayOrResumePlay();
- // 更新状态模型中的播放列表状态
- this.updatePlaylistStateInModel();
- // 通知歌曲变化
- const currentSong = this.playlistModel.getCurrentSong();
- if (currentSong) {
- this.stateModel.updateCurrentSong(currentSong);
- }
- } catch (error) {
- throw new Error;
- }
- }
- // 状态查询方法
- getCurrentState(): PlayerState {
- return this.stateModel.getState();
- }
- /**
- * 获取播放器实际播放状态(最准确)
- * 直接从ijkPlayer获取,不依赖状态模型
- */
- getActualPlayingState(): boolean {
- try {
- const ijkPlayer = this.playerManager?.getIjkPlayer();
- if (ijkPlayer) {
- return ijkPlayer.isPlaying();
- }
- return false;
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to get actual playing state: ${error}`);
- return false;
- }
- }
- getCurrentSong(): VideoItem | null {
- 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[] {
- return this.playlistModel.getSongs();
- }
- getCurrentIndex(): number {
- 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;
- }
- /**
- * 强制触发数据恢复(用于桌面卡片冷启动场景)
- */
- async forceDataRestoration(): Promise<boolean> {
- try {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Force data restoration started');
- // 如果数据已经恢复,直接返回
- if (this.isDataRestored) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Data already restored');
- return true;
- }
- // 强制执行数据恢复
- await this.restorePersistedState();
- // 如果播放列表仍为空,尝试从内存快速恢复
- if (this.playlistModel.getTotalCount() === 0) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Playlist empty, trying memory restore');
- await this.fastRestoreFromMemory();
- }
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Force restoration completed, playlist size: ${this.playlistModel.getTotalCount()}`);
- return this.isDataRestored;
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Force data restoration failed: ${error}`);
- return false;
- }
- }
- /**
- * 检查所有相关服务是否已准备就绪
- * 用于桌面卡片控制等场景,确保在执行播放控制前服务状态正常
- */
- isAllServicesReady(): boolean {
- try {
- // 检查基本初始化状态
- if (!this.isInitialized) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Service not initialized');
- return false;
- }
- // 检查核心组件是否就绪
- if (!this.playerManager || !this.stateModel || !this.playlistModel) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Core components not ready');
- return false;
- }
- // 检查 PlayerManager 是否已经初始化
- const playerInstance = this.playerManager.getIjkPlayer();
- if (!playerInstance) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Player instance not ready');
- return false;
- }
- // 检查上下文是否可用
- if (!this.context) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Context not available');
- return false;
- }
- LogUtils.getInstance().LOGI('UnifiedPlayerService: All services ready');
- return true;
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Service readiness check failed: ${error}`);
- return false;
- }
- }
- /**
- * 验证初始化完整性
- * 在应用启动后调用,确保所有关键组件都已正确初始化
- */
- validateInitialization(): InitializationValidation {
- const errors: string[] = [];
- const warnings: string[] = [];
- try {
- // 检查基础初始化
- if (!this.isInitialized) {
- errors.push('Service not initialized');
- }
- // 检查核心组件
- if (!this.playerManager) {
- errors.push('PlayerManager not available');
- } else {
- const playerInstance = this.playerManager.getIjkPlayer();
- if (!playerInstance) {
- warnings.push('Player instance not ready (may initialize later)');
- }
- }
- if (!this.stateModel) {
- errors.push('StateModel not available');
- }
- if (!this.playlistModel) {
- errors.push('PlaylistModel not available');
- }
- if (!this.context) {
- warnings.push('Context not set (may be set later)');
- }
- // 检查数据持久化服务
- if (!this.dataPersistence) {
- errors.push('DataPersistence service not available');
- }
- // 检查同步服务
- if (!this.stateSync) {
- errors.push('StateSync service not available');
- }
- if (!this.playlistSync) {
- errors.push('PlaylistSync service not available');
- }
- // 检查卡片更新服务
- if (!this.widgetUpdateService) {
- warnings.push('WidgetUpdate service not available');
- }
- // 检查错误恢复策略
- if (!this.errorRecovery) {
- warnings.push('ErrorRecovery strategy not available');
- }
- const isValid = errors.length === 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService validation: ${isValid ? 'VALID' : 'INVALID'}, errors: ${errors.length}, warnings: ${warnings.length}`);
- const result: InitializationValidation = {
- isValid,
- errors,
- warnings
- };
- return result;
- } catch (error) {
- errors.push(`Validation failed with exception: ${error}`);
- const result: InitializationValidation = {
- isValid: false,
- errors,
- warnings
- };
- return result;
- }
- }
- /**
- * 获取服务就绪状态的详细信息
- * 用于调试和用户反馈
- */
- getServiceReadinessInfo(): ServiceReadinessInfo {
- const playerInstance = this.playerManager?.getIjkPlayer();
- const playlistSize = this.playlistModel?.getTotalCount() || 0;
- const currentIndex = this.playlistModel?.getCurrentIndex() || -1;
- const details: ServiceReadinessDetails = {
- initialized: this.isInitialized,
- hasPlayerInstance: !!playerInstance,
- hasContext: !!this.context,
- dataRestored: this.isDataRestored,
- playlistSize: playlistSize,
- currentIndex: currentIndex
- };
- const isReady = this.isAllServicesReady();
- LogUtils.getInstance().LOGI(`UnifiedPlayerService readiness: ${JSON.stringify(details)}`);
- const result: ServiceReadinessInfo = { isReady, details };
- return result;
- }
- /**
- * 等待所有服务准备就绪
- * @param maxWaitMs 最大等待时间(毫秒)
- * @param checkDataRestore 是否同时等待数据恢复完成
- */
- async waitForAllServicesReady(maxWaitMs: number = 5000, checkDataRestore: boolean = true): Promise<boolean> {
- const startTime = Date.now();
- const checkInterval = 100; // 每100ms检查一次
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Waiting for services ready (maxWait: ${maxWaitMs}ms, checkDataRestore: ${checkDataRestore})`);
- while ((Date.now() - startTime) < maxWaitMs) {
- // 检查基础服务就绪状态
- if (this.isAllServicesReady()) {
- // 如果不需要检查数据恢复,直接返回成功
- if (!checkDataRestore) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: All services ready (data restore check skipped)');
- return true;
- }
- // 检查数据恢复状态
- if (this.isDataRestored) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: All services ready and data restored');
- return true;
- }
- // 检查播放列表是否有数据(即使数据恢复标识未设置)
- const playlistSize = this.playlistModel.getTotalCount();
- if (playlistSize > 0) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Services ready with playlist data (${playlistSize} songs)`);
- return true;
- }
- }
- // 短暂等待后继续检查
- await new Promise<void>(resolve => setTimeout(resolve, checkInterval));
- }
- // 超时检查最终状态
- const finalCheck = this.isAllServicesReady();
- const playlistSize = this.playlistModel?.getTotalCount() || 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Service readiness timeout - finalCheck: ${finalCheck}, playlistSize: ${playlistSize}, dataRestored: ${this.isDataRestored}`);
- return finalCheck;
- }
- // 播放模式控制
- setPlayMode(mode: number): void {
- const playMode = mode as PlayMode;
- this.stateModel.updatePlayMode(playMode);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Play mode set to ${mode}`);
- }
- getPlayMode(): number {
- return this.stateModel.getState().playMode;
- }
- // 音量和速度控制
- setVolume(volume: number): void {
- const volumeStr = volume.toString();
- this.playerManager.setVolume(volumeStr, volumeStr);
- this.stateModel.updateVolume(volume);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Volume set to ${volume}`);
- }
- setPlaybackSpeed(speed: number): void {
- const speedStr = speed.toString() + 'f';
- this.playerManager.setPlaybackSpeed(speedStr);
- this.stateModel.updateSpeed(speed);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Speed set to ${speed}`);
- }
- // 播放列表管理
- 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);
- // 更新状态模型中的播放列表状态
- this.updatePlaylistStateInModel();
- // 更新当前歌曲
- const currentSong = this.playlistModel.getCurrentSong();
- this.stateModel.updateCurrentSong(currentSong);
- // 同步到持久化存储
- this.syncPlaylistToStorage();
- // 更新卡片显示播放列表变化
- this.updateWidgetsForPlaylistChange();
- 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 {
- this.playlistModel.addSong(song, index);
- // 更新状态模型中的播放列表状态
- this.updatePlaylistStateInModel();
- // 同步到持久化存储
- this.syncPlaylistToStorage();
- // 更新卡片显示播放列表变化
- this.updateWidgetsForPlaylistChange();
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Song added to playlist`);
- }
- removeFromPlaylist(index: number): VideoItem | null {
- const removedSong = this.playlistModel.removeSong(index);
- if (removedSong) {
- this.stateModel.updateCurrentIndex(this.playlistModel.getCurrentIndex());
- // 更新状态模型中的播放列表状态
- this.updatePlaylistStateInModel();
- // 更新当前歌曲
- const currentSong = this.playlistModel.getCurrentSong();
- this.stateModel.updateCurrentSong(currentSong);
- // 同步到持久化存储
- this.syncPlaylistToStorage();
- // 更新卡片显示播放列表变化
- this.updateWidgetsForPlaylistChange();
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Song removed from playlist at index ${index}`);
- }
- return removedSong;
- }
- // 事件监听
- addStateListener(listener: PlayerStateListener): void {
- this.stateModel.addStateListener(listener);
- }
- removeStateListener(listener: PlayerStateListener): void {
- this.stateModel.removeStateListener(listener);
- }
- // 清理资源
- release(): void {
- try {
- this.stopProgressTimer();
- // 清理防抖定时器
- if (this.avSessionUpdateTimer !== -1) {
- clearTimeout(this.avSessionUpdateTimer);
- this.avSessionUpdateTimer = -1;
- }
- if (this.avMetadataUpdateTimer !== -1) {
- clearTimeout(this.avMetadataUpdateTimer);
- this.avMetadataUpdateTimer = -1;
- }
- // 保存当前状态
- this.saveCurrentState();
- if (this.avSessionController) {
- this.avSessionController.unregisterSessionListener();
- this.avSessionController = null;
- }
- // 清理同步监听器
- this.playlistSync.removeSyncListener(this);
- this.playlistSync.release();
- this.stateSync.unsubscribeFromStateChanges(this);
- this.stateSync.unsubscribeFromWidgetControl(this);
- this.stateSync.release();
- this.playerManager.release();
- this.playlistModel.clear();
- this.isInitialized = false;
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Resources released');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService release error: ${error}`);
- }
- }
- /**
- * 初始化AVSession
- * 按照官方文档的要求:创建 -> 注册控制命令 -> 设置元数据 -> 激活
- */
- private initializeAvSession(): void {
- try {
- this.avSessionController = AvSessionController.getInstance(false);
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession controller created');
- setTimeout(() => {
- this.setAvSessionListener();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession listeners configured');
- }, 500);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to initialize AVSession: ${error}`);
- }
- }
- /**
- * 设置AVSession监听器
- * 注意:控制命令已在AvSessionController中注册,这里设置实际的处理逻辑
- */
- private setAvSessionListener(): void {
- if (!this.avSessionController) {
- return;
- }
- const avSession = this.avSessionController.getAvSession();
- if (!avSession) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession not available for listener setup');
- return;
- }
- try {
- // 播放事件监听
- avSession.on('play', () => {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession play command received');
- this.startPlayOrResumePlay().catch((error: Error) => {
- LogUtils.getInstance().LOGI(`AVSession play command failed: ${error}`);
- });
- });
- // 暂停事件监听
- avSession.on('pause', () => {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession pause command received');
- this.pause().catch((error: Error) => {
- LogUtils.getInstance().LOGI(`AVSession pause command failed: ${error}`);
- });
- });
- // 停止事件监听
- avSession.on('stop', () => {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession stop command received');
- this.stop().catch((error: Error) => {
- LogUtils.getInstance().LOGI(`AVSession stop command failed: ${error}`);
- });
- });
- // 下一首事件监听
- avSession.on('playNext', () => {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession playNext command received');
- this.playNext().catch((error: Error) => {
- LogUtils.getInstance().LOGI(`AVSession playNext command failed: ${error}`);
- });
- });
- // 上一首事件监听
- avSession.on('playPrevious', () => {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession playPrevious command received');
- this.playPrevious().catch((error: Error) => {
- LogUtils.getInstance().LOGI(`AVSession playPrevious command failed: ${error}`);
- });
- });
- // 拖拽进度事件监听
- avSession.on('seek', (time: number) => {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: AVSession seek command received: ${time}ms`);
- this.seekTo(time.toString()).catch((error: Error) => {
- LogUtils.getInstance().LOGI(`AVSession seek command failed: ${error}`);
- });
- });
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession listeners set up successfully');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to set AVSession listeners: ${error}`);
- }
- }
- /**
- * 处理播放错误
- */
- private async handlePlaybackError(error: Error, errorType: PlayerErrorType = PlayerErrorType.PLAYBACK_ERROR): Promise<void> {
- try {
- // 创建播放器错误对象
- const playerError = new PlayerError(errorType, error.message);
- playerError.retryCount = this.currentRetryCount;
- // 创建错误上下文
- const context: ErrorContext = {
- currentSong: this.playlistModel.getCurrentSong(),
- playlist: this.playlistModel.getSongs(),
- currentIndex: this.playlistModel.getCurrentIndex(),
- retryCount: this.currentRetryCount,
- isNetworkAvailable: true // 这里可以实际检查网络状态
- };
- // 获取恢复策略
- const recoveryAction = await this.errorRecovery.handleError(playerError, context);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error recovery action: ${recoveryAction}`);
- // 执行恢复动作
- await this.executeRecoveryAction(recoveryAction, playerError, context);
- } catch (recoveryError) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error recovery failed: ${recoveryError}`);
- this.stateModel.notifyError(new PlayerError(PlayerErrorType.PLAYBACK_ERROR, `Recovery failed: ${recoveryError.message}`));
- }
- }
- /**
- * 执行错误恢复动作
- */
- private async executeRecoveryAction(action: ErrorRecoveryAction, error: PlayerError, context: ErrorContext): Promise<void> {
- switch (action) {
- case ErrorRecoveryAction.RETRY:
- await this.retryCurrentOperation(error);
- break;
- case ErrorRecoveryAction.SKIP_TO_NEXT:
- await this.skipToNextSong();
- break;
- case ErrorRecoveryAction.STOP_PLAYBACK:
- await this.stop();
- this.stateModel.notifyError(error);
- break;
- case ErrorRecoveryAction.WAIT_AND_RETRY:
- await this.waitAndRetry(error);
- break;
- case ErrorRecoveryAction.SHOW_ERROR:
- this.stateModel.notifyError(error);
- break;
- default:
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Unknown recovery action: ${action}`);
- this.stateModel.notifyError(error);
- }
- }
- /**
- * 重试当前操作
- */
- private async retryCurrentOperation(error: PlayerError): Promise<void> {
- try {
- this.currentRetryCount++;
- const delay = this.errorRecovery.getRetryDelay(this.currentRetryCount);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Retrying operation in ${delay}ms (attempt ${this.currentRetryCount})`);
- // 等待指定时间后重试
- setTimeout(async () => {
- try {
- await this.startPlayOrResumePlay();
- this.currentRetryCount = 0; // 重试成功,重置计数
- } catch (retryError) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Retry failed: ${retryError}`);
- await this.handlePlaybackError(retryError as Error, error.type);
- }
- }, delay);
- } catch (retryError) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Retry setup failed: ${retryError}`);
- await this.skipToNextSong();
- }
- }
- /**
- * 跳到下一首歌曲
- */
- private async skipToNextSong(): Promise<void> {
- try {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Skipping to next song due to error');
- // 重置重试计数
- this.currentRetryCount = 0;
- // 检查是否有下一首
- const playMode = this.stateModel.getState().playMode;
- if (this.playlistModel.hasNext(playMode)) {
- await this.playNext();
- } else {
- // 没有下一首,停止播放
- await this.stop();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: No next song available, stopping playback');
- }
- } catch (skipError) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to skip to next song: ${skipError}`);
- await this.stop();
- }
- }
- /**
- * 等待后重试
- */
- private async waitAndRetry(error: PlayerError): Promise<void> {
- try {
- this.currentRetryCount++;
- const delay = this.errorRecovery.getRetryDelay(this.currentRetryCount);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Waiting ${delay}ms before retry (network error)`);
- // 更新状态为加载中
- this.stateModel.updateLoadingState(true);
- setTimeout(async () => {
- try {
- await this.startPlayOrResumePlay();
- this.currentRetryCount = 0; // 重试成功,重置计数
- } catch (retryError) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Network retry failed: ${retryError}`);
- await this.handlePlaybackError(retryError as Error, PlayerErrorType.NETWORK_ERROR);
- }
- }, delay);
- } catch (waitError) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Wait and retry setup failed: ${waitError}`);
- await this.skipToNextSong();
- }
- }
- /**
- * 检查文件是否存在
- */
- private async checkFileExists(filePath: string): Promise<boolean> {
- try {
- // 这里可以添加文件存在性检查逻辑
- // 暂时返回true,实际实现需要使用文件系统API
- return true;
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: File check failed: ${error}`);
- return false;
- }
- }
- /**
- * 检查网络连接
- */
- private async checkNetworkConnection(): Promise<boolean> {
- try {
- // 这里可以添加网络连接检查逻辑
- // 暂时返回true,实际实现需要使用网络API
- return true;
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Network check failed: ${error}`);
- return false;
- }
- }
- // 私有辅助方法
- /**
- * 检查播放器是否需要重新设置
- */
- private async needsPlayerSetup(song: VideoItem): Promise<boolean> {
- try {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- if (!ijkPlayer) {
- console.log("Heanup2 UnifiedPlayerService: 播放器不存在,需要设置");
- return true;
- }
- // 检查播放器是否有数据源
- const duration = ijkPlayer.getDuration();
- if (duration <= 0) {
- console.log("Heanup2 UnifiedPlayerService: 播放器无数据源或时长无效,需要设置");
- return true;
- }
- // 检查当前数据源是否匹配(这里我们通过检查当前歌曲信息来判断)
- const currentSong = this.playlistModel.getCurrentSong();
- if (!currentSong || currentSong.filePath !== song.filePath) {
- console.log(`Heanup2 UnifiedPlayerService: 歌曲文件路径不匹配,需要重新设置 (当前: ${currentSong?.filePath}, 目标: ${song.filePath})`);
- return true;
- }
- console.log(`Heanup2 UnifiedPlayerService: 播放器已设置正确的数据源,无需重新设置 (时长: ${duration}ms)`);
- return false;
- } catch (error) {
- console.log(`Heanup2 UnifiedPlayerService: 检查播放器设置状态时出错: ${error},默认需要设置`);
- return true;
- }
- }
- private async setupPlayerForSong(song: VideoItem): Promise<void> {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- if (!ijkPlayer) {
- throw new Error('Player not initialized');
- }
- console.log("Heanup2 UnifiedPlayerService: 开始重新设置播放器,这会重置所有状态");
- // 标记播放器未准备(因为要重新设置)
- this.isPlayerPreparedForCurrentSong = false;
- // 重置播放器 - 这会清除所有状态包括播放位置
- ijkPlayer.reset();
- // 重新设置音频模式 - 重置后需要重新设置
- ijkPlayer.setAudioId('unifiedPlayer');
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Reset audio mode for ${song.name}`);
- // 重新设置配置
- this.playerManager.setupIjkPlayerOptions();
- // 设置音量(针对dsf格式特殊处理)
- const volume = this.stateModel.getState().volume;
- if (song.filePath.toLowerCase().endsWith('.dsf')) {
- this.playerManager.setVolume('1', '1');
- } else {
- this.playerManager.setVolume(volume.toString(), volume.toString());
- }
- // 设置数据源
- ijkPlayer.setDataSource(song.filePath);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Set data source to ${song.filePath}`);
- // 设置HTTP请求头
- const headers = new Map([
- ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
- ["referer", "https://www.bilibili.com"]
- ]);
- ijkPlayer.setDataSourceHeader(headers);
- // 设置播放速度
- const speed = this.stateModel.getState().speed;
- this.playerManager.setPlaybackSpeed(speed.toString() + 'f');
- // 设置消息监听器(重要:用于处理播放器内部事件)
- ijkPlayer.setMessageListener();
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Player setup for song ${song.name}`);
- console.log("Heanup2 UnifiedPlayerService: 播放器重新设置完成,准备开始新的播放");
- }
- private setupProgressTimer(): void {
- this.progressTimer = setInterval(() => {
- this.updateProgress();
- }, 1000); // 每秒更新一次进度
- }
- private startProgressTimer(): void {
- // 先停止现有的定时器,避免重复启动
- this.stopProgressTimer();
- // 启动新的定时器
- this.setupProgressTimer();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Progress timer started');
- }
- private stopProgressTimer(): void {
- if (this.progressTimer !== -1) {
- clearInterval(this.progressTimer);
- this.progressTimer = -1;
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Progress timer stopped');
- }
- }
- private updateProgress(): void {
- try {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- const currentState = this.stateModel.getState();
- // 只有在播放器存在、正在播放且已准备好时才更新进度
- if (!ijkPlayer || !currentState.isPlaying || !this.isPlayerPreparedForCurrentSong) {
- return;
- }
- const currentPosition = ijkPlayer.getCurrentPosition();
- const duration = ijkPlayer.getDuration();
- // 确保获取到有效的位置信息
- if (currentPosition >= 0 && duration > 0) {
- this.stateModel.updateProgress(currentPosition, duration);
- this.updateSessionPlayState();
- }
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService updateProgress error: ${error}`);
- }
- }
- getCurrentPosition(): number {
- try {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- if (!ijkPlayer) {
- return 0;
- }
- return ijkPlayer.getCurrentPosition();
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService getCurrentPosition error: ${error}`);
- return 0;
- }
- }
- getIjkPlayer(): IjkMediaPlayer | null {
- try {
- return this.playerManager.getIjkPlayer();
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService getIjkPlayer error: ${error}`);
- return null;
- }
- }
- private savePlaybackPosition(): void {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- if (ijkPlayer!= null){
- const position = ijkPlayer.getCurrentPosition();
- // ToastUtil.showToast('保存记忆播放 = ' + position)
- const duration = ijkPlayer.getDuration();
- const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
- // 如果播放位置接近视频末尾,则保存 position 为 0
- const playbackPosition = (duration - position < threshold) ? 0 : position;
- const currentSong = this.playlistModel.getCurrentSong();
- if (currentSong!=null) {
- PreferencesUtil.putSync(currentSong.filePath, playbackPosition);
- }
- }
- }
- private async restorePlaybackPosition(song: VideoItem): Promise<void> {
- // const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
- // // ToastUtil.showToast('position = ' + position)
- // if (this.mIjkMediaPlayer != null && position > 0) {
- // // ToastUtil.showToast('seekTo = ' + position)
- // this.seekTo(position + "");
- //
- // }
- if (song!= null){
- const position = PreferencesUtil.getNumberSync(song.filePath, 0);
- if (position > 0) {
- await this.playerManager.seekToPosition(position.toString());
- }
- }
- // try {
- // // 使用DataPersistenceService恢复播放进度
- // const progressData = await this.dataPersistence.loadPlaybackProgress(song.filePath);
- // if (progressData && progressData.position > 0 && !progressData.completed) {
- // await this.playerManager.seekToPosition(progressData.position.toString());
- // LogUtils.getInstance().LOGI(`UnifiedPlayerService: Restored playback position ${progressData.position}ms for ${song.name}`);
- // }
- // } catch (error) {
- // LogUtils.getInstance().LOGI(`UnifiedPlayerService restorePlaybackPosition error: ${error}`);
- // }
- }
- // ==================== 数据持久化和同步方法 ====================
- /**
- * 恢复持久化的状态
- */
- /**
- * 快速从内存中恢复关键数据(AppStorage)
- */
- private async fastRestoreFromMemory(): Promise<void> {
- try {
- console.log("Heanup2 UnifiedPlayerService: 开始从内存快速恢复关键数据");
- // 从AppStorage快速获取播放列表数据
- const playlistData = AppStorage.get<PlaylistData>('player_playlist');
- if (playlistData && playlistData.songs.length > 0) {
- console.log(`Heanup2 UnifiedPlayerService: 从内存快速恢复播放列表,歌曲数量=${playlistData.songs.length}`);
- this.playlistModel.replaceSongs(playlistData.songs, playlistData.currentIndex);
- 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}`);
- }
- }
- // 从AppStorage快速获取播放状态数据
- const stateData = AppStorage.get<PlayerStateData>('player_state') as PlayerStateData;
- if (stateData) {
- console.log(`Heanup2 UnifiedPlayerService: 从内存快速恢复播放状态 - playing: ${stateData.isPlaying}, index: ${stateData.currentIndex}`);
- this.stateModel.updateVolume(stateData.volume);
- this.stateModel.updateSpeed(stateData.speed);
- this.stateModel.updatePlayMode(stateData.playMode);
- this.stateModel.updatePlayingState(stateData.isPlaying || false);
- if (stateData.currentIndex >= 0) {
- this.stateModel.updateCurrentIndex(stateData.currentIndex);
- }
- }
- console.log("Heanup2 UnifiedPlayerService: 内存数据快速恢复完成");
- // 设置一个临时的数据恢复完成标识,允许快速响应
- this.isDataRestored = true;
- } catch (error) {
- console.log(`Heanup2 UnifiedPlayerService: 快速恢复内存数据失败: ${error}`);
- }
- }
- private async restorePersistedState(): Promise<void> {
- try {
- console.log("Heanup2 UnifiedPlayerService: 开始快速恢复持久化状态");
- // 并行加载播放列表和播放状态,提高效率
- const loadResults = await Promise.all([
- this.dataPersistence.loadPlaylist().catch(() => null),
- this.dataPersistence.loadPlayerState().catch(() => null)
- ]);
- const playlistData = loadResults[0];
- const stateData = loadResults[1];
- // 恢复播放列表
- if (playlistData && playlistData.songs.length > 0) {
- console.log(`Heanup2 UnifiedPlayerService: 恢复播放列表,歌曲数量=${playlistData.songs.length}, 当前索引=${playlistData.currentIndex}`);
- this.playlistModel.replaceSongs(playlistData.songs, playlistData.currentIndex);
- 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: 没有找到保存的播放列表或播放列表为空");
- }
- // 恢复播放状态
- if (stateData) {
- console.log(`Heanup2 UnifiedPlayerService: 加载到的播放状态 - playing: ${stateData.isPlaying}, paused: ${stateData.isPaused}, index: ${stateData.currentIndex}`);
- // 批量更新状态,减少回调次数
- this.stateModel.updateVolume(stateData.volume);
- this.stateModel.updateSpeed(stateData.speed);
- this.stateModel.updatePlayMode(stateData.playMode);
- // 恢复播放状态(UI会使用实际播放器状态,所以这里可以恢复逻辑状态)
- this.stateModel.updatePlayingState(stateData.isPlaying || false);
- // 恢复当前播放索引
- if (stateData.currentIndex >= 0) {
- this.stateModel.updateCurrentIndex(stateData.currentIndex);
- }
- console.log("Heanup2 UnifiedPlayerService: 播放状态恢复完成");
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Restored player state - playing: ${stateData.isPlaying}, paused: ${stateData.isPaused}, index: ${stateData.currentIndex}`);
- } else {
- console.log("Heanup2 UnifiedPlayerService: 没有找到保存的播放状态");
- }
- 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;
- }
- }
- /**
- * 保存当前状态
- */
- private saveCurrentState(): void {
- try {
- // 保存播放状态
- const currentState = this.stateModel.getState();
- this.dataPersistence.savePlayerState(currentState)
- // 保存播放进度
- this.savePlaybackPosition();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Current state saved');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService saveCurrentState error: ${error}`);
- }
- }
- /**
- * 同步播放列表到存储
- */
- private syncPlaylistToStorage(): void {
- try {
- const playlist = this.playlistModel.getSongs();
- const currentIndex = this.playlistModel.getCurrentIndex();
- const playMode = this.stateModel.getState().playMode;
- this.playlistSync.syncPlaylistToStorage(playlist, currentIndex, playMode);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService syncPlaylistToStorage error: ${error}`);
- }
- }
- // ==================== PlaylistSyncListener 接口实现 ====================
- /**
- * 播放列表同步完成回调
- */
- onPlaylistSynced(playlist: VideoItem[], currentIndex: number, playMode: PlayMode): void {
- try {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playlist synced - ${playlist.length} songs, index ${currentIndex}`);
- // 播放列表同步完成,无需额外通知
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onPlaylistSynced error: ${error}`);
- }
- }
- /**
- * 播放列表加载完成回调
- */
- onPlaylistLoaded(playlistData: PlaylistData): void {
- try {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playlist loaded from storage - ${playlistData.songs.length} songs`);
- // 检查是否需要更新本地播放列表
- const currentPlaylist = this.playlistModel.getSongs();
- const currentIndex = this.playlistModel.getCurrentIndex();
- // 如果存储的数据更新,更新本地播放列表
- if (playlistData.songs.length !== currentPlaylist.length ||
- playlistData.currentIndex !== currentIndex) {
- this.playlistModel.replaceSongs(playlistData.songs, playlistData.currentIndex);
- this.stateModel.updateCurrentIndex(playlistData.currentIndex);
- this.stateModel.updatePlayMode(playlistData.playMode);
- 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}`);
- }
- }
- /**
- * 自动同步执行回调
- */
- onAutoSyncPerformed(): void {
- try {
- // 定期保存当前状态
- this.saveCurrentState();
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onAutoSyncPerformed error: ${error}`);
- }
- }
- /**
- * 同步错误回调
- */
- onSyncError(error: Error): void {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService sync error: ${error.message}`);
- }
- // ==================== 公共数据访问方法 ====================
- /**
- * 获取数据持久化服务实例
- */
- getDataPersistenceService(): IDataPersistenceService {
- return this.dataPersistence;
- }
- /**
- * 获取播放列表同步服务实例
- */
- getPlaylistSyncService(): PlaylistSyncService {
- return this.playlistSync;
- }
- // ==================== StateChangeCallback 接口实现 ====================
- /**
- * 状态变化回调(来自StateSyncService的本地通知)
- */
- onStateChanged?(state: PlayerState): void {
- try {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Received state change notification - isPlaying=${state.isPlaying}`);
- // 这里可以处理来自其他组件的状态变化通知
- // 通常情况下,状态变化是由本服务发起的,所以这里主要用于调试和监控
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onStateChanged error: ${error}`);
- }
- }
- /**
- * 歌曲变化回调(来自StateSyncService的本地通知)
- */
- onSongChanged?(song: VideoItem): void {
- try {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Received song change notification - ${song.name}`);
- // 这里可以处理来自其他组件的歌曲变化通知
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onSongChanged error: ${error}`);
- }
- }
- /**
- * 进度变化回调(来自StateSyncService的本地通知)
- */
- onProgressChanged?(progress: PlayProgress): void {
- try {
- // LogUtils.getInstance().LOGI(`UnifiedPlayerService: Received progress change notification - ${progress.percentage.toFixed(1)}%`);
- // 这里可以处理来自其他组件的进度变化通知
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onProgressChanged error: ${error}`);
- }
- }
- // ==================== WidgetControlCallback 接口实现 ====================
- /**
- * 处理来自卡片的播放/暂停命令
- */
- async onPlayPause?(): Promise<void> {
- try {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Received play/pause command from widget');
- // 优先检查播放器的实际状态,而不是状态模型
- const ijkPlayer = this.playerManager.getIjkPlayer();
- const isActuallyPlaying = ijkPlayer ? ijkPlayer.isPlaying() : false;
- const stateModelPlaying = this.getCurrentState().isPlaying;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Widget playPause - StateModel: ${stateModelPlaying}, ActualPlayer: ${isActuallyPlaying}`);
- // 如果播放器实际在播放,则暂停;否则开始/恢复播放
- if (isActuallyPlaying) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Player is actually playing, will pause');
- await this.pause();
- } else {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Player is not playing, will start/resume play');
- await this.startPlayOrResumePlay();
- }
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Play/pause command executed successfully');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onPlayPause error: ${error}`);
- throw new Error;
- }
- }
- /**
- * 处理来自卡片的下一首命令
- */
- async onNextSong?(): Promise<void> {
- try {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Received next song command from widget');
- await this.playNext();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Next song command executed successfully');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onNextSong error: ${error}`);
- throw new Error;
- }
- }
- /**
- * 处理来自卡片的上一首命令
- */
- async onPreviousSong?(): Promise<void> {
- try {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Received previous song command from widget');
- await this.playPrevious();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Previous song command executed successfully');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onPreviousSong error: ${error}`);
- throw new Error;
- }
- }
- /**
- * 处理来自卡片的拖动进度命令
- */
- async onSeekTo?(position: number): Promise<void> {
- try {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Received seek to command from widget - position: ${position}`);
- await this.seekTo(position.toString());
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Seek to command executed successfully');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onSeekTo error: ${error}`);
- throw new Error;
- }
- }
- /**
- * 处理来自卡片的状态请求命令
- */
- async onStateRequest?(): Promise<void> {
- try {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Received state request from widget');
- await this.broadcastCurrentState();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: State request handled successfully');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService onStateRequest error: ${error}`);
- throw new Error;
- }
- }
- // ==================== 状态同步服务访问方法 ====================
- /**
- * 获取状态同步服务实例
- */
- getStateSyncService(): IStateSyncService {
- return this.stateSync;
- }
- /**
- * 手动广播当前状态(用于响应卡片的状态请求)
- */
- async broadcastCurrentState(): Promise<void> {
- try {
- const currentState = this.getCurrentState();
- await this.stateSync.broadcastState(currentState);
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Current state broadcasted manually');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService broadcastCurrentState error: ${error}`);
- throw new Error;
- }
- }
- // ==================== 私有辅助方法 ====================
- /**
- * 更新状态模型中的播放列表状态
- */
- private updatePlaylistStateInModel(): void {
- try {
- const currentIndex = this.playlistModel.getCurrentIndex();
- const totalCount = this.playlistModel.getTotalCount();
- const playMode = this.stateModel.getState().playMode;
- const hasNext = this.playlistModel.hasNext(playMode);
- const hasPrevious = this.playlistModel.hasPrevious(playMode);
- this.stateModel.updatePlaylistState(hasNext, hasPrevious, totalCount);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playlist state updated - hasNext=${hasNext}, hasPrevious=${hasPrevious}, totalCount=${totalCount}`);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService updatePlaylistStateInModel error: ${error}`);
- }
- }
- // ==================== PlayerStateCallback 实现 ====================
- onPrepared(): void {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Player prepared');
- this.stateModel.updateLoadingState(false);
- // 标记播放器已为当前歌曲准备就绪
- this.isPlayerPreparedForCurrentSong = true;
- console.log("Heanup2 UnifiedPlayerService: onPrepared - 播放器已为当前歌曲准备就绪");
- setTimeout(() => {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- const isActuallyPlaying = ijkPlayer ? ijkPlayer.isPlaying() : false;
- console.log(`Heanup2 UnifiedPlayerService: onPrepared - 实际播放状态: ${isActuallyPlaying}`);
- // 强制同步状态模型
- this.stateModel.updatePlayingState(isActuallyPlaying);
- }, 100);
- // 播放器准备完成时更新卡片(移除加载状态)
- this.updateWidgetsForStateChange();
- }
- onPlaybackStarted(): void {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Playback started (new song)');
- // 这个回调只应该在新歌曲开始播放时被调用(通过onPrepared触发)
- // 不应该在暂停恢复时被调用
- // 立即更新播放状态
- this.stateModel.updatePlayingState(true);
- // 启动进度定时器
- this.startProgressTimer();
- // 保存播放状态变化
- this.saveCurrentState();
- // 延迟更新系统播控,避免与其他更新冲突
- setTimeout(() => {
- // 使用防抖机制更新系统播控(主要更新播放状态)
- this.updateSessionPlayState();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession state updated for new song playback');
- }, 600); // 增加延迟,避免与onPrepared的更新冲突
- // 播放开始时更新卡片显示播放状态
- this.updateWidgetsForPlayStateChange();
- LogUtils.getInstance().LOGI('UnifiedPlayerService: New song playback started successfully');
- }
- onPlaybackCompleted(): void {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Playback completed');
- this.stateModel.updatePlayingState(false);
- this.stopProgressTimer();
- // 保存播放状态变化
- this.saveCurrentState();
- this.updateSessionPlayState();
- // 更新卡片显示播放完成状态
- this.updateWidgetsForPlayStateChange();
- // 异步处理自动播放逻辑,避免阻塞主线程
- setTimeout(() => {
- this.handleAutoPlayOnCompletion().catch(() => {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Auto-play error`);
- });
- }, 100); // 延迟100ms执行,确保当前回调完成
- }
- /**
- * 处理歌曲播放完成后的自动播放逻辑
- */
- private async handleAutoPlayOnCompletion(): Promise<void> {
- try {
- // 防抖检查:避免快速连续的自动播放调用
- const currentTime = Date.now();
- if (currentTime - this.lastAutoPlayTime < this.autoPlayDebounceMs) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Auto-play debounced, skipping');
- return;
- }
- this.lastAutoPlayTime = currentTime;
- // 检查服务状态,避免在服务未就绪时执行自动播放
- if (!this.isAllServicesReady()) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Services not ready for auto-play, skipping');
- return;
- }
- const currentState = this.stateModel.getState();
- const playMode = currentState.playMode;
-
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Handling auto-play, mode: ${playMode}`);
- switch (playMode) {
- case PlayMode.SEQUENCE: // 0: 顺序播放/列表循环
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Auto-playing next song in sequence mode');
- // 检查是否有下一首歌曲
- if (this.playlistModel.hasNext(playMode)) {
- await this.playNext();
- } else {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: No next song available in sequence mode');
- }
- break;
-
- case PlayMode.SINGLE_REPEAT: // 1: 单曲循环
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Repeating current song');
- // 重新播放当前歌曲
- await this.startPlayOrResumePlay();
- break;
-
- case PlayMode.NORMAL: // 2: 正常播放,播完停止
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Normal mode - stopping after completion');
- // 不做任何操作,保持停止状态
- break;
-
- case PlayMode.RANDOM: // 3: 随机播放
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Auto-playing random next song');
- await this.playRandomNext();
- break;
-
- default:
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Unknown play mode: ${playMode}`);
- break;
- }
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error in auto-play handling: ${error}`);
- // 在自动播放失败时,简单记录错误但不触发复杂的错误处理流程
- // 这样可以避免错误处理过程中的潜在阻塞
- this.stateModel.updatePlayingState(false);
- this.stateModel.updateLoadingState(false);
- }
- }
- /**
- * 随机播放下一首歌曲
- */
- private async playRandomNext(): Promise<void> {
- try {
- const playlist = this.playlistModel.getSongs();
- if (playlist.length <= 1) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Not enough songs for random play');
- return;
- }
- const currentIndex = this.playlistModel.getCurrentIndex();
- let randomIndex: number;
-
- // 确保随机选择的不是当前歌曲
- do {
- randomIndex = Math.floor(Math.random() * playlist.length);
- } while (randomIndex === currentIndex);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playing random song at index ${randomIndex}`);
- await this.playSongAtIndex(randomIndex);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error in random play: ${error}`);
- // 不再抛出异常,而是通过错误处理机制处理
- await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
- }
- }
- onPlaybackError(what: number, extra: number): void {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playback error - what: ${what}, extra: ${extra}`);
- this.stateModel.updateLoadingState(false);
- this.stateModel.updatePlayingState(false);
- this.stopProgressTimer();
- // 保存播放状态变化
- this.saveCurrentState();
- // 创建播放器错误对象
- const playbackError = new PlayerError(
- PlayerErrorType.PLAYBACK_ERROR,
- `Playback error: what=${what}, extra=${extra}`,
- what
- );
- playbackError.recoverable = what !== -1004 && what !== -1007; // 某些错误码可恢复
- playbackError.retryCount = 0;
- // 创建错误上下文
- const errorContext: ErrorContext = {
- currentSong: this.getCurrentSong(),
- playlist: this.getPlaylist(),
- currentIndex: this.getCurrentIndex(),
- retryCount: 0,
- isNetworkAvailable: true // 这里可以实际检查网络状态
- };
- // 使用错误恢复策略处理错误
- this.errorRecovery.handleError(playbackError, errorContext).then((action: ErrorRecoveryAction) => {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error recovery action: ${action}`);
- // 这里可以根据 action 执行相应的恢复操作
- }).catch((recoveryError: Error) => {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error recovery failed: ${recoveryError}`);
- });
- }
- // ========== 卡片更新相关方法 ==========
- /**
- * 创建当前的卡片数据
- */
- private createWidgetData(): WidgetData {
- const currentState = this.stateModel.getState();
- const currentSong = this.playlistModel.getCurrentSong();
- const currentIndex = this.playlistModel.getCurrentIndex();
- const totalCount = this.playlistModel.getTotalCount();
- const playMode = currentState.playMode;
- return {
- playState: {
- isPlaying: currentState.isPlaying,
- isPaused: currentState.isPaused,
- isLoading: currentState.isLoading
- },
- currentSong: {
- id: currentSong?.id || '',
- title: currentSong?.name || '暂无播放',
- artist: currentSong?.artist || '未知艺术家',
- album: currentSong?.album || '未知专辑',
- coverImagePath: currentSong?.pixelMapPath || '',
- duration: this.parseDuration(currentSong?.duration || '0')
- },
- progress: {
- currentPosition: currentState.currentPosition,
- duration: currentState.duration,
- percentage: currentState.duration > 0 ? (currentState.currentPosition / currentState.duration) * 100 : 0,
- currentTimeText: this.formatTime(currentState.currentPosition),
- totalTimeText: this.formatTime(currentState.duration)
- },
- playlist: {
- hasNext: this.playlistModel.hasNext(playMode),
- hasPrevious: this.playlistModel.hasPrevious(playMode),
- currentIndex: currentIndex,
- totalCount: totalCount
- },
- config: {
- size: WidgetSize.MEDIUM, // 默认尺寸,实际会根据卡片尺寸适配
- theme: WidgetTheme.AUTO,
- showProgress: true,
- showCover: true
- }
- };
- }
- /**
- * 播放状态变化时更新卡片
- */
- private async updateWidgetsForPlayStateChange(): Promise<void> {
- try {
- const widgetData = this.createWidgetData();
- await this.widgetUpdateService.updateAllForms(widgetData);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Widgets updated for play state change`);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update widgets for play state change: ${error}`);
- }
- }
- /**
- * 歌曲变化时更新卡片
- */
- private async updateWidgetsForSongChange(song: VideoItem, forceUpdate: boolean = false): Promise<void> {
- try {
- const widgetData = this.createWidgetData();
- if (forceUpdate) {
- // 强制更新(忽略防抖),用于重要事件如歌曲切换
- await this.widgetUpdateService.forceUpdateAllForms(widgetData);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Widgets force updated for song change: ${song.name}`);
- } else {
- await this.widgetUpdateService.updateAllForms(widgetData);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Widgets updated for song change: ${song.name}`);
- }
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update widgets for song change: ${error}`);
- }
- }
- /**
- * 进度变化时更新卡片(防抖处理)
- */
- private async updateWidgetsForProgressChange(progress: PlayProgress): Promise<void> {
- try {
- // 进度更新很频繁,让防抖机制发挥作用
- const widgetData = this.createWidgetData();
- await this.widgetUpdateService.updateAllForms(widgetData);
- // 不记录日志,避免过多输出
- } catch (error) {
- // 进度更新失败不影响播放,只记录错误
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update widgets for progress change: ${error}`);
- }
- }
- /**
- * 状态变化时更新卡片
- */
- public async updateWidgetsForStateChange(): Promise<void> {
- try {
- const widgetData = this.createWidgetData();
- await this.widgetUpdateService.updateAllForms(widgetData);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Widgets updated for state change`);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update widgets for state change: ${error}`);
- }
- }
- /**
- * 播放列表变化时更新卡片
- */
- private async updateWidgetsForPlaylistChange(): Promise<void> {
- try {
- const widgetData = this.createWidgetData();
- await this.widgetUpdateService.updateAllForms(widgetData);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Widgets updated for playlist change`);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update widgets for playlist change: ${error}`);
- }
- }
- /**
- * 应用启动时初始化卡片显示
- */
- public async initializeWidgetDisplay(): Promise<void> {
- try {
- const widgetData = this.createWidgetData();
- await this.widgetUpdateService.forceUpdateAllForms(widgetData);
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Widget display initialized');
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to initialize widget display: ${error}`);
- }
- }
- /**
- * 获取卡片更新统计信息
- */
- public getWidgetUpdateStats(): UpdateStats {
- return this.widgetUpdateService.getUpdateStats();
- }
- /**
- * 重置卡片更新统计
- */
- public resetWidgetUpdateStats(): void {
- this.widgetUpdateService.resetStats();
- }
- /**
- * 格式化时间为 MM:SS 格式
- */
- private formatTime(timeInMs: number): string {
- const totalSeconds = Math.floor(timeInMs / 1000);
- const minutes = Math.floor(totalSeconds / 60);
- const seconds = totalSeconds % 60;
- return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
- }
- /**
- * 解析时长字符串为毫秒数
- */
- private parseDuration(durationStr: string): number {
- if (!durationStr || durationStr === '0') {
- return 0;
- }
- try {
- // 如果是纯数字,假设是秒数
- const numValue = parseFloat(durationStr);
- if (!isNaN(numValue)) {
- const result = Math.floor(numValue * 1000); // 转换为毫秒
- return result;
- }
- // 如果包含冒号,解析为 MM:SS 或 HH:MM:SS 格式
- if (durationStr.includes(':')) {
- const parts = durationStr.split(':').map(part => parseInt(part, 10));
- let totalSeconds = 0;
- if (parts.length === 2) {
- // MM:SS 格式
- totalSeconds = parts[0] * 60 + parts[1];
- } else if (parts.length === 3) {
- // HH:MM:SS 格式
- totalSeconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
- }
- const result = totalSeconds * 1000; // 转换为毫秒
- return result;
- }
- return 0;
- } catch (error) {
- return 0;
- }
- }
- // ==================== PlayerStateCallback 实现 ====================
- /**
- * 转换播放模式为AVSession循环模式
- */
- private convertPlayModeToLoopMode(playMode: number): avSession.LoopMode {
- switch (playMode) {
- case PlayMode.SINGLE_REPEAT:
- return avSession.LoopMode.LOOP_MODE_SINGLE;
- case PlayMode.NORMAL:
- return avSession.LoopMode.LOOP_MODE_LIST;
- case PlayMode.RANDOM:
- return avSession.LoopMode.LOOP_MODE_SHUFFLE;
- case PlayMode.SEQUENCE:
- default:
- return avSession.LoopMode.LOOP_MODE_SEQUENCE;
- }
- }
- /**
- * 更新AVSession播放状态(带防抖)
- */
- private updateSessionPlayState(): void {
- // 清除之前的定时器
- if (this.avSessionUpdateTimer !== -1) {
- clearTimeout(this.avSessionUpdateTimer);
- }
- // 增加防抖延迟到500ms,减少频繁更新
- this.avSessionUpdateTimer = setTimeout(() => {
- this.doUpdateSessionPlayState();
- }, 500);
- }
- /**
- * 实际执行AVSession播放状态更新
- */
- private doUpdateSessionPlayState(): void {
- try {
- if (!this.avSessionController) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession controller not initialized');
- return;
- }
- // 避免过于频繁的更新(最小间隔500ms)
- const now = Date.now();
- if (now - this.lastAvSessionUpdate < 500) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Skipping AVSession update due to rate limit');
- return;
- }
- const currentSong = this.playlistModel.getCurrentSong();
- const currentPosition = this.getCurrentPosition();
- // 优先从播放器获取实际duration
- let duration = 0;
- const ijkPlayer = this.playerManager.getIjkPlayer();
- if (ijkPlayer) {
- duration = ijkPlayer.getDuration();
- }
- if (duration <= 0 && currentSong?.duration) {
- duration = this.parseDuration(currentSong.duration);
- }
- const currentState = this.stateModel.getState();
- // 按照官方文档要求设置完整的播放状态
- const playbackState: avSession.AVPlaybackState = {
- // 播放状态
- state: ijkPlayer?.isPlaying() ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
- // 播放速度
- speed: currentState.speed || 1.0,
- // 循环模式
- loopMode: this.convertPlayModeToLoopMode(currentState.playMode),
- // 收藏状态
- isFavorite: false // 可以根据实际收藏状态设置
- };
- // 只有当duration > 0时才设置位置信息,避免进度条显示问题
- if (duration > 0) {
- playbackState.position = {
- elapsedTime: Math.max(0, currentPosition), // 已播放时间(毫秒)
- updateTime: Date.now() // 更新时间戳
- };
- playbackState.bufferedTime = Math.max(currentPosition, 0);
- } else {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Skipping position info due to invalid duration: ${duration}ms`);
- }
- this.avSessionController.setAvSessionPlayState(playbackState);
- // 记录上次更新时间
- this.lastAvSessionUpdate = now;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: AVSession play state updated successfully`);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update AVSession play state: ${error}`);
- }
- }
- /**
- * 设置当前播放模式到AVSession
- */
- private setCurrentPlayMode(): void {
- try {
- if (!this.avSessionController) {
- return;
- }
- const currentSong = this.playlistModel.getCurrentSong();
- if (!currentSong) {
- return;
- }
- // 修复duration转换问题 - 优先从播放器获取实际duration
- let duration = 0;
- try {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- if (ijkPlayer) {
- const playerDuration = ijkPlayer.getDuration();
- if (playerDuration > 0) {
- duration = playerDuration;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Using player duration: ${duration}ms`);
- } else {
- // 备用方案:解析VideoItem中的duration
- duration = currentSong.duration ? this.parseDuration(currentSong.duration) : 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Using parsed duration: ${duration}ms from '${currentSong.duration}'`);
- }
- } else {
- duration = currentSong.duration ? this.parseDuration(currentSong.duration) : 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: No player available, using parsed duration: ${duration}ms`);
- }
- } catch (error) {
- duration = currentSong.duration ? this.parseDuration(currentSong.duration) : 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error getting player duration, using parsed: ${duration}ms, error: ${error}`);
- }
- // 获取歌词内容(如果有的话)
- const lyricContent = ''; // 这里可以根据需要获取歌词内容
- this.avSessionController.setAVMetadataMusic(currentSong, duration, lyricContent);
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: AVSession metadata updated for ${currentSong.name} with duration ${duration}ms`);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to set current play mode: ${error}`);
- }
- }
- /**
- * 更新AVSession元数据(带防抖和智能更新)
- */
- private async updateAvSessionMetadata(song: VideoItem): Promise<void> {
- // 清除之前的定时器
- if (this.avMetadataUpdateTimer !== -1) {
- clearTimeout(this.avMetadataUpdateTimer);
- }
- const now = Date.now();
- if (now - this.lastUpdateTime < 1000) {
- return;
- }
- this.lastUpdateTime = now;
- // 如果播放器还没准备好,延迟更新等待播放器准备完成
- const ijkPlayer = this.playerManager.getIjkPlayer();
- const playerDuration = ijkPlayer ? ijkPlayer.getDuration() : 0;
- const shouldWaitForPlayer = playerDuration <= 0 && this.isPlayerPreparedForCurrentSong === false;
- this.avMetadataUpdateTimer = setTimeout(() => {
- this.doUpdateAvSessionMetadata(song);
- }, 800);
- if (shouldWaitForPlayer) {
- // 播放器还没准备好,延迟更新
- this.avMetadataUpdateTimer = setTimeout(() => {
- this.doUpdateAvSessionMetadata(song);
- }, 800);
- } else {
- // 播放器已准备好或者不需要等待,稍微延迟更新
- this.avMetadataUpdateTimer = setTimeout(() => {
- this.doUpdateAvSessionMetadata(song);
- }, 800);
- }
- }
- /**
- * 实际执行AVSession元数据更新
- */
- private async doUpdateAvSessionMetadata(song: VideoItem): Promise<void> {
- try {
- if (!this.avSessionController) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession controller not initialized');
- return;
- }
- // 避免过于频繁的元数据更新(最小间隔600ms)
- const now = Date.now();
- if (now - this.lastAvMetadataUpdate < 600) {
- LogUtils.getInstance().LOGI('UnifiedPlayerService: Skipping AVSession metadata update due to rate limit');
- return;
- }
- // 调试:打印VideoItem的duration字段
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: VideoItem duration field - value: '${song.duration}', type: ${typeof song.duration}`);
- // 智能获取最准确的duration
- let duration = 0;
- try {
- const ijkPlayer = this.playerManager.getIjkPlayer();
- if (ijkPlayer && this.isPlayerPreparedForCurrentSong) {
- const playerDuration = ijkPlayer.getDuration();
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Player getDuration() returned: ${playerDuration}ms`);
- if (playerDuration > 0) {
- duration = playerDuration;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Using player duration: ${duration}ms`);
- } else {
- // 备用方案:解析VideoItem中的duration
- duration = song.duration ? this.parseDuration(song.duration) : 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Player duration invalid, using parsed duration: ${duration}ms from '${song.duration}'`);
- }
- } else {
- duration = song.duration ? this.parseDuration(song.duration) : 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Player not ready, using parsed duration: ${duration}ms from '${song.duration}'`);
- }
- } catch (error) {
- duration = song.duration ? this.parseDuration(song.duration) : 0;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error getting player duration, using parsed: ${duration}ms from '${song.duration}', error: ${error}`);
- }
- // 最终验证duration
- if (isNaN(duration) || duration <= 0) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Final duration is invalid (${duration}), setting to 0`);
- duration = 0;
- }
- // 获取歌词内容(如果有的话)
- const lyricContent = song.lyricContent || '';
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: About to call setAVMetadataMusic with duration: ${duration}ms (type: ${typeof duration})`);
- await this.avSessionController.setAVMetadataMusic(song, duration, lyricContent);
- // 记录更新时间
- this.lastAvMetadataUpdate = now;
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: AVSession metadata updated for ${song.name} with duration ${duration}ms`);
- } catch (error) {
- LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update AVSession metadata: ${error}`);
- }
- }
- // ==================== 辅助方法 ====================
- }
|