UnifiedPlayerService.ets 157 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451
  1. import { VideoItem } from '../../viewmodel/VideoItem';
  2. import { PlayerManager, IPlayerManager, PlayerStateCallback } from './PlayerManager';
  3. import { MD5 } from '@pura/harmony-utils';
  4. import {
  5. PlayerStateModel,
  6. PlayerState,
  7. PlayerStateListener,
  8. PlayMode,
  9. PlayerError,
  10. PlayerErrorType
  11. } from './PlayerStateModel';
  12. import { PlaylistModel } from './PlaylistModel';
  13. import { IjkMediaPlayer, LogUtils, InterruptEvent, InterruptHintType } from '@ohos/ijkplayer';
  14. import { common, Context } from '@kit.AbilityKit';
  15. import { PreferencesUtil as PuraPreferencesUtil, StrUtil } from '@pura/harmony-utils';
  16. import {
  17. DataPersistenceService,
  18. PlaylistSyncService,
  19. PlaylistSyncListener,
  20. IDataPersistenceService,
  21. PlaylistData,
  22. PlayerStateData
  23. } from './DataPersistenceService';
  24. import {
  25. ErrorRecoveryStrategy,
  26. IErrorRecoveryStrategy,
  27. ErrorContext,
  28. ErrorRecoveryAction
  29. } from './ErrorRecoveryStrategy';
  30. import { AvSessionController } from '../../controller/AvSessionController';
  31. import { avSession } from '@kit.AVSessionKit';
  32. import { formProvider, formBindingData } from '@kit.FormKit';
  33. import { fileIo } from '@kit.CoreFileKit';
  34. import { http } from '@kit.NetworkKit';
  35. import { util } from '@kit.ArkTS';
  36. import json from '@ohos.util.json';
  37. import MediaTable from '../util/MediaTable';
  38. import { Utility } from '../util/Utility';
  39. import { FormRdbHelper } from '../../database/FormRdbHelper';
  40. import { FormInfo } from '../../viewmodel/FormInfo';
  41. import { WidgetDataRdbHelper } from '../../database/WidgetDataRdbHelper';
  42. import { WidgetDataInfo } from '../../viewmodel/WidgetDataInfo';
  43. import { PreferencesUtil, IWidgetData } from '../utils/PreferencesUtil';
  44. import { SettingPage } from '../../pages/SettingPage';
  45. /**
  46. * 跳过设置接口
  47. */
  48. interface JumpSettings {
  49. isEnabled: boolean;
  50. jumpTopTime: number;
  51. jumpEndTime: number;
  52. }
  53. /**
  54. * 存储方式枚举
  55. */
  56. enum WidgetDataStorageType {
  57. DATABASE = 'database', // 使用数据库存储
  58. PREFERENCES = 'preferences' // 使用Preferences存储
  59. }
  60. /**
  61. * 控制WidgetData存储方式的配置
  62. * 可以通过修改这个值来切换存储方式
  63. */
  64. const WIDGET_DATA_STORAGE_TYPE: WidgetDataStorageType = WidgetDataStorageType.DATABASE;
  65. /**
  66. * 服务就绪状态详情接口
  67. */
  68. export interface ServiceReadinessDetails {
  69. initialized: boolean;
  70. hasPlayerInstance: boolean;
  71. hasContext: boolean;
  72. dataRestored: boolean;
  73. playlistSize: number;
  74. currentIndex: number;
  75. }
  76. /**
  77. * 服务就绪信息接口
  78. */
  79. export interface ServiceReadinessInfo {
  80. isReady: boolean;
  81. details: ServiceReadinessDetails;
  82. }
  83. /**
  84. * 初始化验证结果接口
  85. */
  86. export interface InitializationValidation {
  87. isValid: boolean;
  88. errors: string[];
  89. warnings: string[];
  90. }
  91. /**
  92. * 卡片播放状态数据接口
  93. */
  94. export interface WidgetPlayerState {
  95. isPlaying: boolean;
  96. isPaused: boolean;
  97. isLoading: boolean;
  98. currentPosition: number;
  99. duration: number;
  100. hasNext: boolean;
  101. hasPrevious: boolean;
  102. playMode: number;
  103. }
  104. /**
  105. * 卡片播放列表信息接口
  106. */
  107. export interface WidgetPlaylistInfo {
  108. currentIndex: number;
  109. totalCount: number;
  110. }
  111. /**
  112. * 卡片时间信息接口
  113. */
  114. export interface WidgetTimeInfo {
  115. currentTimeText: string;
  116. totalTimeText: string;
  117. progressPercentage: number;
  118. }
  119. /**
  120. * 缓存文件信息接口
  121. */
  122. export interface CacheFileInfo {
  123. path: string;
  124. size: number;
  125. mtime: number;
  126. }
  127. /**
  128. * 卡片数据接口
  129. */
  130. export interface WidgetFormData {
  131. // VideoItem数据
  132. id: string;
  133. name: string;
  134. artist: string;
  135. album: string;
  136. pixelMapPath: string;
  137. duration: number;
  138. filePath: string;
  139. // 扩展数据
  140. imgName: string;
  141. imageColorHex: string;
  142. // 状态数据
  143. playerState: WidgetPlayerState;
  144. playlistInfo: WidgetPlaylistInfo;
  145. timeInfo: WidgetTimeInfo;
  146. // 卡片图片显示必填字段
  147. formImages: Record<string, number>;
  148. }
  149. /**
  150. * 缓存的静态卡片数据接口
  151. * 用于缓存不会随播放状态改变的数据,避免重复计算和IO
  152. */
  153. interface CachedWidgetData {
  154. // 歌曲的基本信息
  155. id: string;
  156. name: string;
  157. artist: string;
  158. album: string;
  159. pixelMapPath: string; // 原始封面路径
  160. duration: number;
  161. filePath: string;
  162. imageColorHex: string;
  163. // 处理后的最终图片路径(本地或缓存),用于快速打开
  164. finalImagePath: string | null;
  165. }
  166. interface ImageCacheInfo {
  167. path: string;
  168. imgName: string;
  169. }
  170. /**
  171. * 统一播放器服务接口
  172. * 提供统一的播放控制接口,替代LocalMusic中的播放器逻辑
  173. */
  174. export interface IPlayerService {
  175. /**
  176. * 启动播放或恢复播放
  177. * @returns
  178. */
  179. startPlayOrResumePlay(): Promise<void>;
  180. /**
  181. * 暂停播放
  182. * @returns
  183. */
  184. pause(): Promise<void>;
  185. /**
  186. * 停止播放
  187. * @returns
  188. */
  189. stop(): Promise<void>;
  190. /**
  191. * 跳转到指定位置
  192. * @param position
  193. * @returns
  194. */
  195. seekTo(position: string): Promise<void>;
  196. // 播放列表控制 - 基于LocalMusic现有方法
  197. /**
  198. * 播放下一首
  199. * @returns
  200. */
  201. playNext(): Promise<void>;
  202. /**
  203. * 播放上一首
  204. */
  205. playPrevious(): Promise<void>;
  206. /**
  207. * 播放指定索引的歌
  208. * @param index
  209. * @returns
  210. */
  211. playSongAtIndex(index: number): Promise<void>;
  212. /**
  213. * 获取播放器状态
  214. * @returns
  215. */
  216. getCurrentState(): PlayerState;
  217. /**
  218. * 获取实际播放状态
  219. * @returns 实际播放状态
  220. */
  221. getActualPlayingState(): boolean;
  222. /**
  223. * 获取当前播放歌曲
  224. * @returns
  225. */
  226. getCurrentSong(): VideoItem | null;
  227. /**
  228. * 获取播放列表
  229. * @returns
  230. */
  231. getPlaylist(): VideoItem[];
  232. /**
  233. * 获取当前播放索引
  234. * @returns
  235. */
  236. getCurrentIndex(): number;
  237. /**
  238. * 获取当前播放进度
  239. * @returns 当前播放进度
  240. */
  241. getCurrentPosition(): number;
  242. /**
  243. * 获取播放器实例
  244. * @returns 播放器实例
  245. */
  246. getIjkPlayer(): IjkMediaPlayer | null;
  247. /**
  248. * 是否数据恢复完成
  249. * @returns 是否数据恢复完成
  250. * */
  251. isDataRestorationCompleted(): boolean;
  252. /**
  253. * 等待数据恢复完成
  254. * @param maxWaitMs 最大等待时间(毫秒),默认为-1(无限等待)
  255. * @returns 是否恢复完成
  256. */
  257. waitForDataRestoration(maxWaitMs?: number): Promise<boolean>;
  258. /**
  259. * 强制数据恢复
  260. * @returns 是否恢复成功
  261. */
  262. forceDataRestoration(): Promise<boolean>;
  263. /**
  264. * 是否就绪
  265. * @returns
  266. */
  267. isAllServicesReady(): boolean;
  268. /**
  269. * 处理音频中断事件
  270. * @param event 音频中断事件
  271. */
  272. handleAudioInterrupt(event: InterruptEvent): Promise<void>;
  273. /**
  274. * 等待服务就绪
  275. * @param maxWaitMs 最大等待时间(毫秒),默认为-1(无限等待)
  276. * @param checkDataRestore 是否检查数据恢复状态,默认为true
  277. * @returns 是否就绪
  278. */
  279. waitForAllServicesReady(maxWaitMs?: number, checkDataRestore?: boolean): Promise<boolean>;
  280. /**
  281. * 获取服务就绪信息
  282. * @returns 服务就绪信息
  283. */
  284. getServiceReadinessInfo(): ServiceReadinessInfo;
  285. /**
  286. * 初始化验证
  287. * @returns 初始化验证结果
  288. */
  289. validateInitialization(): InitializationValidation;
  290. /**
  291. * 设置播放模式
  292. * @param mode
  293. */
  294. setPlayMode(mode: number): void;
  295. /**
  296. * 获取播放模式
  297. * @returns 播放模式
  298. */
  299. getPlayMode(): number;
  300. /**
  301. * 设置音量
  302. * @param volume
  303. */
  304. setVolume(volume: number): void;
  305. /**
  306. * 设置播放速度
  307. * @param speed
  308. */
  309. setPlaybackSpeed(speed: number): void;
  310. // 播放列表管理
  311. /**
  312. * 设置播放列表
  313. * @param songs
  314. * @param currentIndex
  315. */
  316. setPlaylist(songs: VideoItem[], currentIndex?: number): void;
  317. /**
  318. * 添加歌曲到播放列表
  319. * @param song
  320. * @param index
  321. */
  322. addToPlaylist(song: VideoItem, index?: number): void;
  323. /**
  324. * 移除播放列表中的歌曲
  325. * @param index
  326. * @returns 移除的歌曲
  327. */
  328. removeFromPlaylist(index: number): VideoItem | null;
  329. // 事件监听
  330. /**
  331. * 添加播放器状态监听
  332. * @param listener
  333. */
  334. addStateListener(listener: PlayerStateListener): void;
  335. /**
  336. * 移除播放器状态监听
  337. * @param listener
  338. */
  339. removeStateListener(listener: PlayerStateListener): void;
  340. /**
  341. * 初始化
  342. * @param context
  343. * @returns
  344. */
  345. initialize(context: common.UIAbilityContext): Promise<void>;
  346. /**
  347. * 释放资源
  348. */
  349. release(): void;
  350. /**
  351. * 更新收藏列表
  352. */
  353. updateFavoriteList(): Promise<void>;
  354. /**
  355. * 强制刷新收藏状态(用于收藏/取消收藏操作后)
  356. */
  357. refreshFavoriteStatus(): Promise<void>;
  358. /**
  359. * 获取收藏列表
  360. * @returns 收藏列表
  361. */
  362. getFav(): Array<VideoItem>;
  363. syncPlaylistToService(songList: VideoItem[], currentIndex: number, playType: PlayMode): void
  364. }
  365. /**
  366. * 统一播放器服务实现
  367. * 整合PlayerManager、PlayerStateModel和PlaylistModel
  368. */
  369. interface widgeData {
  370. // VideoItem数据平铺
  371. id: string;
  372. name: string;
  373. artist: string;
  374. album: string;
  375. pixelMapPath: string;
  376. duration: number;
  377. filePath: string;
  378. imgName: string;
  379. imageColorHex: string;
  380. isFavorite: boolean;
  381. // PlayerState数据平铺
  382. isPlaying: boolean;
  383. isPaused: boolean;
  384. isLoading: boolean;
  385. currentPosition: number;
  386. hasNext: boolean;
  387. hasPrevious: boolean;
  388. playMode: number;
  389. // 播放列表信息平铺
  390. currentIndex: number;
  391. totalCount: number;
  392. // 时间信息平铺
  393. currentTimeText: string;
  394. totalTimeText: string;
  395. progressPercentage: number;
  396. // 保持嵌套结构兼容性
  397. playerState: WidgetPlayerState;
  398. playlistInfo: WidgetPlaylistInfo;
  399. timeInfo: WidgetTimeInfo;
  400. // 卡片图片显示必填字段
  401. formImages: Record<string, number>;
  402. }
  403. interface PlayPauseInterface {
  404. widgetIsPlaying?: boolean;
  405. }
  406. export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListener, PlayerStateCallback {
  407. private static instance: UnifiedPlayerService | null = null;
  408. private playerManager: IPlayerManager;
  409. private stateModel: PlayerStateModel;
  410. private playlistModel: PlaylistModel;
  411. private dataPersistence: IDataPersistenceService;
  412. private playlistSync: PlaylistSyncService;
  413. private errorRecovery: IErrorRecoveryStrategy;
  414. private avSessionController: AvSessionController | null = null;
  415. private context: common.UIAbilityContext | null = null;
  416. // 防重复调用机制
  417. private isUpdatingForms: boolean = false;
  418. private lastAvSessionUpdateTime: number = 0;
  419. private progressTimer: number = -1;
  420. private initialized: boolean = false;
  421. private isDataRestored: boolean = false; // 新增:数据恢复完成标识
  422. private isPlayerPreparedForCurrentSong: boolean = false; // 新增:播放器是否已为当前歌曲准备就绪
  423. private currentRetryCount: number = 0;
  424. private lastAvSessionUpdate: number = 0;
  425. private lastAvMetadataUpdate: number = 0; // 新增:上次元数据更新时间
  426. private avSessionUpdateTimer: number = -1; // 新增:系统播控更新防抖定时器
  427. private avMetadataUpdateTimer: number = -1; // 新增:元数据更新防抖定时器
  428. private favList: VideoItem[] = [];
  429. private table: MediaTable | undefined = undefined;
  430. private lastAutoPlayTime: number = 0; // 新增:上次自动播放时间,用于防抖
  431. private autoPlayDebounceMs: number = 1000; // 自动播放防抖间隔(毫秒)
  432. private isPausingInProgress: boolean = false; // 新增:标记是否正在执行暂停操作
  433. private isManualSongChange: boolean = false; // 新增:是否正在进行手动歌曲切换
  434. // 图片缓存相关属性
  435. private imageCacheDir: string = ''; // 图片缓存目录
  436. private lastImageCache: ImageCacheInfo | null = null; // 图片缓存优化
  437. private lastFormUpdateTime: number = 0; // 上次卡片更新时间,用于防抖
  438. private readonly CACHE_EXPIRY_DAYS: number = 7; // 缓存有效期:7天
  439. private readonly MAX_CACHE_SIZE_MB: number = 50; // 最大缓存大小:50MB
  440. private hasChecked: boolean=false;
  441. // 卡片数据缓存
  442. private widgetDataCache: CachedWidgetData | null = null;
  443. private constructor() {
  444. this.playerManager = PlayerManager.getInstance();
  445. this.stateModel = new PlayerStateModel();
  446. this.playlistModel = new PlaylistModel();
  447. this.dataPersistence = DataPersistenceService.getInstance();
  448. this.playlistSync = PlaylistSyncService.getInstance();
  449. this.errorRecovery = ErrorRecoveryStrategy.getInstance();
  450. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Instance created');
  451. }
  452. public static getInstance(): UnifiedPlayerService {
  453. if (!UnifiedPlayerService.instance) {
  454. UnifiedPlayerService.instance = new UnifiedPlayerService();
  455. }
  456. return UnifiedPlayerService.instance;
  457. }
  458. async initialize(context: common.UIAbilityContext): Promise<void> {
  459. if (this.initialized && this.context === context) {
  460. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService已经初始化过了');
  461. return;
  462. }
  463. try {
  464. console.log("Heanup2 UnifiedPlayerService: 开始快速初始化服务");
  465. this.context = context;
  466. // 初始化图片缓存目录
  467. await this.initImageCacheDirectory();
  468. // 快速初始化核心组件
  469. this.playerManager.setStateCallback(this);
  470. // 初始化PlaylistModel的MediaTable
  471. this.playlistModel.initializeMediaTable(context);
  472. // 设置音频中断监听
  473. // 音频中断处理已移至LocalMusic中,响应更快
  474. // this.setupAudioInterruptListener();
  475. // 设置同步监听器
  476. this.playlistSync.addSyncListener(this);
  477. // 设置状态模型监听器,自动广播状态变化
  478. this.setupProgressTimer();
  479. this.initialized = true;
  480. // 异步初始化耗时组件,避免阻塞
  481. this.initializeHeavyComponentsAsync(context);
  482. // 清理无效的Form ID
  483. this.cleanupInvalidFormIds();
  484. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Core initialization completed');
  485. } catch (error) {
  486. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService initialization error: ${error}`);
  487. throw new Error(`初始化失败: ${error}`);
  488. }
  489. }
  490. /**
  491. * 为卡片进程设置context
  492. * 卡片进程是独立的,需要单独设置context
  493. */
  494. setFormContext(context: common.UIAbilityContext | common.FormExtensionContext): void {
  495. try {
  496. this.context = context as common.UIAbilityContext;
  497. // 同时设置到AppStorage,确保卡片进程中其他地方能访问
  498. AppStorage.setOrCreate('context', context);
  499. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Form context set successfully');
  500. } catch (error) {
  501. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to set form context: ${error}`);
  502. }
  503. }
  504. /**
  505. * 获取当前context
  506. */
  507. getContext(): common.UIAbilityContext | null {
  508. // 优先返回实例的context
  509. if (this.context) {
  510. return this.context;
  511. }
  512. // 尝试从AppStorage获取
  513. try {
  514. const appStorageContext = AppStorage.get('context') as common.UIAbilityContext;
  515. if (appStorageContext) {
  516. this.context = appStorageContext;
  517. return appStorageContext;
  518. }
  519. } catch (error) {
  520. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to get context from AppStorage: ${error}`);
  521. }
  522. return null;
  523. }
  524. /**
  525. * 异步初始化耗时组件
  526. */
  527. private initializeHeavyComponentsAsync(context: common.UIAbilityContext): void {
  528. setTimeout(async () => {
  529. try {
  530. console.log("Heanup2 UnifiedPlayerService: 开始异步初始化耗时组件");
  531. // 并行初始化各个服务以提高效率
  532. const initPromises = [
  533. this.playerManager.initialize(context),
  534. this.dataPersistence.initialize(context),
  535. this.playlistSync.initialize(context),
  536. ];
  537. await Promise.all(initPromises);
  538. // 立即尝试快速恢复关键数据(从AppStorage)
  539. await this.fastRestoreFromMemory();
  540. this.initializeAvSession();
  541. // 并行初始化收藏列表和恢复数据,提高效率
  542. const initPromises2 = [
  543. this.restorePersistedState(),
  544. this.initializeFavoriteList()
  545. ];
  546. await Promise.all(initPromises2);
  547. // 数据恢复完成后,同步播放器状态到UI
  548. setTimeout(async () => {
  549. try {
  550. this.saveCurrentState()
  551. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Player state synced to UI after initialization');
  552. } catch (error) {
  553. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to sync player state after initialization: ${error}`);
  554. }
  555. }, 500); // 延迟500ms确保初始化完全完成
  556. console.log("Heanup2 UnifiedPlayerService: 异步组件初始化完成");
  557. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Heavy components initialized');
  558. } catch (error) {
  559. console.log(`Heanup2 UnifiedPlayerService: 异步组件初始化失败: ${error}`);
  560. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService heavy components init error: ${error}`);
  561. // 即使失败也设置数据恢复完成,避免无限等待
  562. this.isDataRestored = true;
  563. }
  564. }, 10); // 缩短延迟,让数据恢复更快开始
  565. }
  566. // 播放控制方法
  567. async startPlayOrResumePlay(): Promise<void> {
  568. try {
  569. console.log("Heanup2 UnifiedPlayerService: 开始恢复播放");
  570. // 优化的服务就绪检查 - 支持冷启动场景
  571. if (!this.isAllServicesReady()) {
  572. console.log("Heanup2 UnifiedPlayerService: 服务未就绪,等待服务初始化完成");
  573. const isReady = await this.waitForAllServicesReady(5000, true); // 增加等待时间并启用数据恢复检查
  574. if (!isReady) {
  575. console.log("Heanup2 UnifiedPlayerService: 服务等待超时,尝试强制数据恢复...");
  576. // 尝试强制数据恢复作为最后手段
  577. const forceRestored = await this.forceDataRestoration();
  578. if (!forceRestored) {
  579. const error = new Error('Services not ready for playback after force restoration');
  580. await this.handlePlaybackError(error, PlayerErrorType.INITIALIZATION_ERROR);
  581. return;
  582. }
  583. console.log("Heanup2 UnifiedPlayerService: 强制数据恢复成功,继续播放流程");
  584. }
  585. }
  586. // 关键修复:在执行任何操作之前,首先检查播放器的实际状态。
  587. // 如果播放器已经在播放,只需同步状态并立即返回,避免不必要的重置。
  588. const ijkPlayer = this.playerManager.getIjkPlayer()!; // 服务就绪后播放器一定存在
  589. if (ijkPlayer.isPlaying()) {
  590. console.log("Heanup2 UnifiedPlayerService: 检测到播放器已在播放。同步状态并退出。");
  591. this.syncPlayingState();
  592. return;
  593. }
  594. // 获取当前歌曲 - 如果没有就尝试恢复
  595. let currentSong = this.playlistModel.getCurrentSong();
  596. if (!currentSong) {
  597. console.log("Heanup2 UnifiedPlayerService: 没有可播放的歌曲,尝试恢复持久化状态");
  598. await this.restorePersistedState();
  599. currentSong = this.playlistModel.getCurrentSong();
  600. if (!currentSong) {
  601. console.log("Heanup2 UnifiedPlayerService: 恢复后仍然没有可播放的歌曲");
  602. // 冷启动优化:播放列表为空时的友好处理
  603. await this.handleEmptyPlaylistScenario();
  604. return;
  605. }
  606. console.log("Heanup2 UnifiedPlayerService: 恢复成功,当前歌曲信息:" + JSON.stringify(currentSong));
  607. }
  608. this.stateModel.updateLoadingState(true);
  609. // 简化的播放器状态检查 - 检查是否可以从暂停恢复
  610. const shouldResumeFromPause = this.canResumeFromPause(ijkPlayer);
  611. if (shouldResumeFromPause) {
  612. console.log("Heanup2 UnifiedPlayerService: 从暂停状态恢复播放");
  613. return await this.resumeFromPause();
  614. }
  615. // 新歌播放前的必要检查
  616. await this.validateSongForPlayback(currentSong);
  617. // 设置播放器并开始播放
  618. await this.setupAndStartPlayback(currentSong);
  619. await this.doUpdateAvSessionMetadata(currentSong)
  620. } catch (error) {
  621. this.stateModel.updateLoadingState(false);
  622. this.stateModel.updatePlayingState(false);
  623. await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
  624. }
  625. }
  626. /**
  627. * 处理空播放列表场景(冷启动优化)
  628. */
  629. private async handleEmptyPlaylistScenario(): Promise<void> {
  630. try {
  631. console.log("Heanup2 UnifiedPlayerService: 处理空播放列表场景");
  632. // 停止加载状态
  633. this.stateModel.updateLoadingState(false);
  634. this.stateModel.updatePlayingState(false);
  635. // 尝试从数据库快速加载一些歌曲(如果有)
  636. const quickSongs = await this.loadQuickPlaylistFromDatabase();
  637. if (quickSongs && quickSongs.length > 0) {
  638. console.log(`Heanup2 UnifiedPlayerService: 从数据库快速加载${quickSongs.length}首歌曲`);
  639. this.setPlaylist(quickSongs, 0);
  640. // 再次尝试播放
  641. const currentSong = this.playlistModel.getCurrentSong();
  642. if (currentSong) {
  643. await this.validateSongForPlayback(currentSong);
  644. await this.setupAndStartPlayback(currentSong);
  645. return;
  646. }
  647. }
  648. // 如果仍然没有歌曲,提供友好的用户提示
  649. console.log("Heanup2 UnifiedPlayerService: 无可播放的歌曲,等待用户添加歌曲");
  650. // 更新widget显示空状态
  651. await this.updateAllForms();
  652. } catch (error) {
  653. console.log(`Heanup2 UnifiedPlayerService: 处理空播放列表场景失败: ${error}`);
  654. }
  655. }
  656. /**
  657. * 从数据库快速加载播放列表(用于冷启动场景)
  658. */
  659. private async loadQuickPlaylistFromDatabase(): Promise<VideoItem[] | null> {
  660. try {
  661. if (!this.context) {
  662. return null;
  663. }
  664. // 尝试从数据库加载最近播放的歌曲
  665. const table = this.getTable();
  666. return new Promise<VideoItem[]>((resolve) => {
  667. table.queryRecentPlayedRecords(10, (songs: VideoItem[]) => {
  668. if (songs && songs.length > 0) {
  669. console.log(`Heanup2 UnifiedPlayerService: 从数据库加载到${songs.length}首最近播放的歌曲`);
  670. resolve(songs);
  671. } else {
  672. // 如果没有最近播放,尝试加载任意歌曲
  673. table.query(0, (allSongs: VideoItem[]) => {
  674. console.log(`Heanup2 UnifiedPlayerService: 从数据库加载到${allSongs?.length || 0}首所有歌曲`);
  675. resolve(allSongs || []);
  676. }, true);
  677. }
  678. });
  679. });
  680. } catch (error) {
  681. console.log(`Heanup2 UnifiedPlayerService: 从数据库加载播放列表失败: ${error}`);
  682. return null;
  683. }
  684. }
  685. /**
  686. * 检查是否可以从暂停状态恢复播放
  687. */
  688. private canResumeFromPause(ijkPlayer: IjkMediaPlayer): boolean {
  689. const isPausedByManager = this.playerManager.isPausedState();
  690. const isCurrentlyPlaying = ijkPlayer.isPlaying();
  691. const playerDuration = ijkPlayer.getDuration();
  692. const hasValidMedia = playerDuration > 0;
  693. // 如果认为是暂停但没有有效媒体,清除假暂停状态
  694. if (isPausedByManager && !hasValidMedia) {
  695. console.log("Heanup2 UnifiedPlayerService: 检测到假暂停状态,清除暂停标记");
  696. this.playerManager.clearPausedState();
  697. this.isPlayerPreparedForCurrentSong = false;
  698. return false;
  699. }
  700. // 如果播放器正在播放,同步状态
  701. if (isCurrentlyPlaying) {
  702. this.syncPlayingState();
  703. return false; // 不需要恢复,已经在播放
  704. }
  705. // 检查是否可以从暂停恢复
  706. const canResume = isPausedByManager &&
  707. !isCurrentlyPlaying &&
  708. hasValidMedia &&
  709. this.isPlayerPreparedForCurrentSong;
  710. console.log(`Heanup2 UnifiedPlayerService: 暂停恢复检查 - canResume: ${canResume}`);
  711. return canResume;
  712. }
  713. /**
  714. * 同步播放状态
  715. */
  716. private syncPlayingState(): void {
  717. console.log("Heanup2 UnifiedPlayerService: 播放器正在播放,同步状态");
  718. this.stateModel.updateLoadingState(false);
  719. this.stateModel.updatePlayingState(true);
  720. this.playerManager.clearPausedState();
  721. // 关键修复:确保播放器准备状态标记被正确设置
  722. this.isPlayerPreparedForCurrentSong = true;
  723. console.log("Heanup2 UnifiedPlayerService: 设置播放器准备状态为true,确保进度更新正常");
  724. this.startProgressTimer();
  725. this.updateSessionPlayState();
  726. this.updateWidgetsForStateChange();
  727. // 关键修复:使用强制更新确保状态同步时卡片立即更新
  728. this.updateAllForms(true);
  729. }
  730. public async toggleFavorite(): Promise<void> {
  731. let isFav = 0
  732. let item = this.getCurrentSong() as VideoItem;
  733. if (Utility.getIsFav(this.getFav(), item)) {
  734. isFav = 0
  735. } else {
  736. isFav = 1
  737. }
  738. return new Promise<void>((resolve) => {
  739. this.getTable().updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  740. if (result) {
  741. // 刷新UnifiedPlayerService的收藏状态,这会自动更新AVSession
  742. console.log("Heanup2 UnifiedPlayerService toggleFavorite: 收藏状态切换");
  743. await this.refreshFavoriteStatus();
  744. // 立即更新桌面卡片状态,确保收藏图标正确显示
  745. await this.updateAllForms(true);
  746. console.log("Heanup2 UnifiedPlayerService toggleFavorite: 收藏状态和卡片状态更新完成");
  747. }
  748. resolve();
  749. })
  750. });
  751. }
  752. /**
  753. * 从暂停状态恢复播放
  754. */
  755. private async resumeFromPause(): Promise<void> {
  756. try {
  757. console.log("Heanup2 UnifiedPlayerService: 直接从暂停状态恢复播放");
  758. this.stateModel.updateLoadingState(false);
  759. await this.playerManager.startPlayOrResumePlay();
  760. this.stateModel.updatePlayingState(true);
  761. this.startProgressTimer();
  762. setTimeout(() => this.updateProgress(), 100);
  763. this.saveCurrentState();
  764. this.updateSessionPlayState();
  765. await this.updateWidgetsForPlayStateChange();
  766. // 关键修复:使用强制更新确保卡片状态立即同步
  767. await this.updateAllForms(true);
  768. } catch (error) {
  769. throw new Error(`Resume from pause failed: ${error}`);
  770. }
  771. }
  772. /**
  773. * 验证歌曲是否可以播放
  774. */
  775. private async validateSongForPlayback(song: VideoItem): Promise<void> {
  776. // 检查文件是否存在(对于本地文件)
  777. if (!song.filePath.startsWith('http')) {
  778. const fileExists = await this.checkFileExists(song.filePath);
  779. if (!fileExists) {
  780. throw new Error(`File not found: ${song.filePath}`);
  781. }
  782. } else {
  783. // 检查网络连接(对于网络资源)
  784. const networkAvailable = await this.checkNetworkConnection();
  785. if (!networkAvailable) {
  786. throw new Error('Network not available');
  787. }
  788. }
  789. }
  790. /**
  791. * 设置播放器并开始播放
  792. */
  793. private async setupAndStartPlayback(song: VideoItem): Promise<void> {
  794. console.log(`Heanup2 UnifiedPlayerService: 设置播放器并开始播放: ${song.name}`);
  795. // 在随机播放模式下,确保播放历史被正确维护
  796. const playMode = this.stateModel.getState().playMode;
  797. if (playMode === PlayMode.RANDOM) {
  798. await this.playlistModel.ensureCurrentSongInHistory();
  799. }
  800. // 设置播放源和配置
  801. await this.setupPlayerForSong(song);
  802. // 准备播放器(实际播放会在 onPrepared 回调中开始)
  803. const preparedPlayer = this.playerManager.getIjkPlayer();
  804. if (preparedPlayer) {
  805. preparedPlayer.prepareAsync();
  806. }
  807. // 立即更新基础元数据(使用解析的duration),后续在播放器准备好后会用实际duration更新
  808. await this.updateAvSessionMetadata(song);
  809. // 注释掉此处的记忆播放恢复,统一在onPrepared中处理
  810. // this.restorePlaybackPosition(song);
  811. this.currentRetryCount = 0;
  812. }
  813. /**
  814. * 直接播放新歌曲,避免恢复逻辑干扰
  815. * 专为 playNext/playPrevious 设计
  816. */
  817. private async playNewSongDirectly(song: VideoItem | null, shouldAutoPlay: boolean = true): Promise<void> {
  818. if (!song) {
  819. throw new Error('No song provided for direct play');
  820. }
  821. this.stateModel.updateLoadingState(true);
  822. const playerInstance = this.playerManager.getIjkPlayer();
  823. if (!playerInstance) {
  824. throw new Error('Player not initialized');
  825. }
  826. // 检查文件是否存在(对于本地文件)
  827. if (!song.filePath.startsWith('http')) {
  828. const fileExists = await this.checkFileExists(song.filePath);
  829. if (!fileExists) {
  830. throw new Error(`File not found: ${song.filePath}`);
  831. }
  832. }
  833. // 在随机播放模式下,确保播放历史被正确维护
  834. const playMode = this.stateModel.getState().playMode;
  835. if (playMode === PlayMode.RANDOM) {
  836. await this.playlistModel.ensureCurrentSongInHistory();
  837. }
  838. // 关键修复:设置播放器的自动播放状态
  839. this.playerManager.setShouldAutoPlay(shouldAutoPlay);
  840. // 如果需要自动播放,清除暂停状态,确保播放器能正常启动
  841. if (shouldAutoPlay) {
  842. this.playerManager.clearPausedState();
  843. LogUtils.getInstance().LOGI(`UnifiedPlayerService: playNewSongDirectly - cleared paused state for auto-play`);
  844. }
  845. LogUtils.getInstance().LOGI(`UnifiedPlayerService: playNewSongDirectly - shouldAutoPlay: ${shouldAutoPlay}`);
  846. // 设置播放源和配置
  847. await this.setupPlayerForSong(song);
  848. // 准备播放器
  849. const preparedPlayer = this.playerManager.getIjkPlayer();
  850. if (preparedPlayer) {
  851. preparedPlayer.prepareAsync();
  852. // 注意:实际播放和状态更新会在 onPrepared 回调中开始
  853. }
  854. // 重置重试计数
  855. this.currentRetryCount = 0;
  856. }
  857. async pause(): Promise<void> {
  858. try {
  859. // 设置暂停进行中标志,避免状态不匹配误判
  860. this.isPausingInProgress = true;
  861. // 保存当前播放位置
  862. const currentSong = this.playlistModel.getCurrentSong();
  863. if (currentSong) {
  864. this.savePlaybackPosition(currentSong);
  865. }
  866. // 暂停播放器 - 确保先暂停播放器
  867. this.playerManager.pausePlayback();
  868. // 立即更新状态模型为暂停状态,确保状态同步
  869. this.stateModel.updatePlayingState(false);
  870. // 停止进度定时器
  871. this.stopProgressTimer();
  872. // 等待一小段时间确保播放器状态稳定
  873. // await new Promise<void>(resolve => setTimeout(resolve, 50));
  874. // 强制更新AVSession状态,确保播控中心显示正确的暂停状态
  875. // 注意:在保存状态之前更新AVSession,避免状态不匹配检测的干扰
  876. this.updateSessionPlayState(true);
  877. // 保存播放状态变化
  878. this.saveCurrentState();
  879. // 更新卡片显示暂停状态
  880. await this.updateWidgetsForPlayStateChange();
  881. // 关键修复:使用强制更新确保卡片状态立即同步
  882. await this.updateAllForms(true);
  883. } catch (error) {
  884. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService pause error: ${error}`);
  885. } finally {
  886. // 清除暂停进行中标志
  887. this.isPausingInProgress = false;
  888. }
  889. }
  890. async stop(): Promise<void> {
  891. try {
  892. // 保存当前歌曲的播放位置
  893. const currentSong = this.playlistModel.getCurrentSong();
  894. if (currentSong) {
  895. this.savePlaybackPosition(currentSong);
  896. }
  897. this.playerManager.stopPlayback();
  898. // 重要:停止时应该清除所有播放状态,不是暂停状态
  899. this.stateModel.updatePlayingState(false);
  900. // this.stateModel.state.isPaused = false; // 停止不是暂停
  901. this.stateModel.updateProgress(0, 0);
  902. this.stopProgressTimer();
  903. // 通知状态变化
  904. this.stateModel.notifySongChanged(this.getCurrentSong() as VideoItem);
  905. // 更新卡片显示停止状态
  906. await this.updateWidgetsForPlayStateChange();
  907. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Stop completed, all states cleared');
  908. } catch (error) {
  909. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService stop error: ${error}`);
  910. throw new Error;
  911. }
  912. }
  913. /**
  914. * 静默停止播放,不触发状态变化通知(用于歌曲切换)
  915. */
  916. private async stopSilently(): Promise<void> {
  917. try {
  918. // 静默停止播放,不保存播放位置(位置已经在外部保存)
  919. this.playerManager.stopPlayback();
  920. this.stopProgressTimer();
  921. // 不调用 updatePlayingState,避免触发状态变化通知
  922. } catch (error) {
  923. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService stopSilentlyWithoutSave error: ${error}`);
  924. throw new Error;
  925. }
  926. }
  927. private async stopSilentlyWithoutSave(): Promise<void> {
  928. try {
  929. // 静默停止播放,不保存播放位置(位置已经在外部保存),也不触发回调
  930. this.playerManager.stopPlaybackSilently();
  931. this.stopProgressTimer();
  932. // 不调用 updatePlayingState,避免触发状态变化通知
  933. } catch (error) {
  934. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService stopSilentlyWithoutSave error: ${error}`);
  935. throw new Error;
  936. }
  937. }
  938. async seekTo(position: string): Promise<void> {
  939. try {
  940. const currentSong = this.playlistModel.getCurrentSong();
  941. if (!currentSong) {
  942. throw new Error('No song to seek');
  943. }
  944. // 检查是否支持拖动(wma格式不支持)
  945. if (StrUtil.isNotEmpty(currentSong.filePath) &&
  946. currentSong.filePath.toLowerCase().endsWith('.wma')) {
  947. throw new Error('WMA format does not support seeking');
  948. }
  949. await this.playerManager.seekToPosition(position);
  950. } catch (error) {
  951. throw new Error(`Failed to seek to position: ${error}`);
  952. }
  953. }
  954. // 播放列表控制方法
  955. async playNext(): Promise<void> {
  956. return this.changeTrack('next');
  957. }
  958. async playPrevious(): Promise<void> {
  959. return this.changeTrack('previous');
  960. }
  961. /**
  962. * 切换歌曲(下一首或上一首)
  963. * @param direction - 切换方向,'next' 或 'previous'
  964. */
  965. async changeTrack(direction: 'next' | 'previous'): Promise<void> {
  966. try {
  967. // 1. 设置手动歌曲切换标志,防止自动播放等逻辑干扰
  968. this.isManualSongChange = true;
  969. // 关键修复:切歌操作应该总是开始播放新歌曲,无论之前是什么状态
  970. // 这是用户的明确意图:切换到新歌曲并播放
  971. const shouldAutoPlayNewSong = true;
  972. LogUtils.getInstance().LOGI(`UnifiedPlayerService: changeTrack - will auto-play new song: ${shouldAutoPlayNewSong}`);
  973. // 2. 检查服务是否已准备就绪
  974. if (!this.isAllServicesReady()) {
  975. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: ${direction} - 服务未就绪,等待服务初始化完成`);
  976. const isReady = await this.waitForAllServicesReady(500, false);
  977. if (!isReady) {
  978. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Services not ready for ${direction}, skipping`);
  979. // 统一处理方式:在服务未就绪时直接返回,避免抛出错误中断用户体验
  980. this.isManualSongChange = false;
  981. return;
  982. }
  983. }
  984. // **关键修复:在移动播放列表位置之前先获取并保存当前歌曲的播放位置**
  985. const oldSong = this.playlistModel.getCurrentSong();
  986. if (oldSong) {
  987. this.savePlaybackPosition(oldSong);
  988. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能 Saved old song position before track change: ${oldSong.name}`);
  989. }
  990. const playMode = this.stateModel.getState().playMode;
  991. let moved = false;
  992. // 3. 根据 direction 参数执行不同的逻辑
  993. if (direction === 'next') {
  994. if (this.playlistModel.hasNext(playMode)) {
  995. moved = this.playlistModel.moveToNext(playMode);
  996. }
  997. } else { // direction === 'previous'
  998. if (await this.playlistModel.hasPrevious(playMode)) {
  999. // 注意:'previous' 相关的操作是异步的,需要 await
  1000. moved = await this.playlistModel.moveToPrevious(playMode);
  1001. }
  1002. }
  1003. // 如果没有成功移动(列表到头/尾,或移动失败),则直接返回
  1004. if (!moved) {
  1005. this.isManualSongChange = false;
  1006. return;
  1007. }
  1008. const newIndex = this.playlistModel.getCurrentIndex();
  1009. const newSong = this.playlistModel.getCurrentSong();
  1010. this.stateModel.updateCurrentIndex(newIndex);
  1011. if (newSong) {
  1012. this.stateModel.updateCurrentSong(newSong);
  1013. }
  1014. // 静默停止当前播放(不再保存位置,因为已经在上面保存了)
  1015. await this.stopSilentlyWithoutSave();
  1016. // 直接播放新歌曲,切歌操作总是自动播放
  1017. await this.playNewSongDirectly(newSong, shouldAutoPlayNewSong);
  1018. // 更新播放列表状态
  1019. await this.updatePlaylistStateInModel();
  1020. // 优化:立即更新卡片状态,使用微任务调度避免阻塞
  1021. Promise.resolve().then(async () => {
  1022. try {
  1023. // 确保播放列表状态是最新的
  1024. this.updatePlaylistStateInModelSync();
  1025. // 强制更新所有桌面卡片状态(微任务优先级高于宏任务)
  1026. await this.updateAllForms(true);
  1027. // 移除此处的AVSession更新,避免与onPrepared中的更新冲突
  1028. // AVSession会在onPrepared回调中正确更新
  1029. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Widget state updated after track change');
  1030. } catch (error) {
  1031. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to update widgets after track change: ${error}`);
  1032. }
  1033. });
  1034. } catch (error) {
  1035. await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
  1036. } finally {
  1037. // 5. 在任何情况下都清除手动切换标志
  1038. setTimeout(() => {
  1039. this.isManualSongChange = false;
  1040. }, 1000); // 延迟1秒清除,确保播放器状态稳定
  1041. }
  1042. }
  1043. async playSongAtIndex(index: number): Promise<void> {
  1044. console.log("Heanup 开始执行playSongAtIndex方法,播放指定索引的歌:"+index)
  1045. try {
  1046. // 设置手动歌曲切换标志,防止自动播放干扰
  1047. this.isManualSongChange = true;
  1048. const success = this.playlistModel.playSongAtIndex(index);
  1049. if (!success) {
  1050. this.isManualSongChange = false;
  1051. throw new Error(`Invalid song index: ${index}`);
  1052. }
  1053. this.stateModel.updateCurrentIndex(index);
  1054. // 静默停止当前播放并开始新歌曲(不触发状态变化通知)
  1055. await this.stopSilently();
  1056. // 在随机播放模式下,确保当前歌曲被添加到播放历史
  1057. const playMode = this.stateModel.getState().playMode;
  1058. if (playMode === PlayMode.RANDOM) {
  1059. await this.playlistModel.ensureCurrentSongInHistory();
  1060. }
  1061. // 直接播放新歌曲,而不是恢复播放
  1062. const newCurrentSong = this.playlistModel.getCurrentSong();
  1063. await this.playNewSongDirectly(newCurrentSong, true); // 直接点击播放,应该自动开始
  1064. // 更新状态模型中的播放列表状态
  1065. await this.updatePlaylistStateInModel();
  1066. // 通知歌曲变化
  1067. if (newCurrentSong) {
  1068. this.stateModel.updateCurrentSong(newCurrentSong);
  1069. }
  1070. // 异步预缓存相邻歌曲的卡片数据
  1071. setTimeout(() => {
  1072. this.updateAllForms();
  1073. }, 0);
  1074. } catch (error) {
  1075. throw new Error;
  1076. } finally {
  1077. // 确保在任何情况下都清除手动切换标志
  1078. setTimeout(() => {
  1079. this.isManualSongChange = false;
  1080. }, 1000); // 延迟1秒清除,确保播放器状态稳定
  1081. }
  1082. }
  1083. // 状态查询方法
  1084. getCurrentState(): PlayerState {
  1085. return this.stateModel.getState();
  1086. }
  1087. /**
  1088. * 获取播放器实际播放状态(最准确)
  1089. * 直接从ijkPlayer获取,不依赖状态模型
  1090. */
  1091. getActualPlayingState(): boolean {
  1092. try {
  1093. const ijkPlayer = this.playerManager?.getIjkPlayer();
  1094. if (ijkPlayer) {
  1095. return ijkPlayer.isPlaying();
  1096. }
  1097. return false;
  1098. } catch (error) {
  1099. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to get actual playing state: ${error}`);
  1100. return false;
  1101. }
  1102. }
  1103. getCurrentSong(): VideoItem | null {
  1104. return this.playlistModel.getCurrentSong();
  1105. }
  1106. getFav(): Array<VideoItem> {
  1107. if (this.favList.length > 0) {
  1108. return this.favList;
  1109. }
  1110. // 如果缓存为空,异步更新但返回空数组,避免阻塞
  1111. this.getTable().queryByisFav(1, async (result: VideoItem[]) => {
  1112. this.favList = result;
  1113. // 更新收藏列表后,重新更新AVSession状态以反映正确的收藏状态
  1114. if (result.length > 0) {
  1115. setTimeout(() => {
  1116. this.updateSessionPlayState();
  1117. }, 100);
  1118. }
  1119. })
  1120. return this.favList;
  1121. }
  1122. /**
  1123. * 获取当前歌曲的收藏状态
  1124. */
  1125. private getCurrentSongFavoriteState(): boolean {
  1126. try {
  1127. let currentSong = this.playlistModel.getCurrentSong();
  1128. if (!currentSong) {
  1129. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: 当前歌曲为空`);
  1130. return false;
  1131. }
  1132. let favList = this.getFav();
  1133. if (!favList || favList.length === 0) {
  1134. // 如果收藏列表为空,可能还在加载中,先返回false
  1135. // 但不记录为错误,因为这是正常的初始化状态
  1136. return false;
  1137. }
  1138. // 检查当前歌曲是否在收藏列表中
  1139. for (let i = 0; i < favList.length; i++) {
  1140. if (favList[i].filePath === currentSong.filePath && favList[i].isFav === 1) {
  1141. return true;
  1142. }
  1143. }
  1144. return false;
  1145. } catch (error) {
  1146. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to get favorite state: ${error}`);
  1147. return false;
  1148. }
  1149. }
  1150. /**
  1151. * 初始化收藏列表
  1152. */
  1153. private async initializeFavoriteList(): Promise<void> {
  1154. try {
  1155. return new Promise<void>((resolve) => {
  1156. this.getTable().queryByisFav(1, (result: VideoItem[]) => {
  1157. this.favList = result;
  1158. LogUtils.getInstance()
  1159. .LOGI(`Heanup UnifiedPlayerService: Favorite list initialized with ${this.favList.length} items`);
  1160. resolve();
  1161. });
  1162. });
  1163. } catch (error) {
  1164. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to initialize favorite list: ${error}`);
  1165. }
  1166. }
  1167. /**
  1168. * 更新收藏列表
  1169. */
  1170. public async updateFavoriteList(): Promise<void> {
  1171. try {
  1172. return new Promise<void>((resolve) => {
  1173. this.getTable().queryByisFav(1, (result: VideoItem[]) => {
  1174. this.favList = result;
  1175. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Favorite list updated with ${this.favList.length} items`);
  1176. // 更新收藏列表后,立即更新AVSession状态以反映正确的收藏状态
  1177. setTimeout(() => {
  1178. this.updateSessionPlayState();
  1179. this.updateAllForms();
  1180. }, 100);
  1181. resolve();
  1182. });
  1183. });
  1184. } catch (error) {
  1185. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to update favorite list: ${error}`);
  1186. }
  1187. }
  1188. /**
  1189. * 强制刷新收藏状态(用于收藏/取消收藏操作后)
  1190. */
  1191. public async refreshFavoriteStatus(): Promise<void> {
  1192. try {
  1193. // 清空缓存,强制重新加载
  1194. this.favList = [];
  1195. await this.updateFavoriteList();
  1196. // 触发状态变化通知,确保LocalMusic UI能收到收藏状态变化
  1197. this.stateModel.forceNotifyStateChanged();
  1198. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Favorite status refreshed and state change notified');
  1199. } catch (error) {
  1200. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to refresh favorite status: ${error}`);
  1201. }
  1202. }
  1203. private getTable(): MediaTable {
  1204. if (this.table) {
  1205. return this.table;
  1206. }
  1207. if (this.context) {
  1208. this.table = new MediaTable(this.context);
  1209. return this.table;
  1210. }
  1211. return new MediaTable(getContext(this) as common.UIAbilityContext);
  1212. }
  1213. getPlaylist(): VideoItem[] {
  1214. return this.playlistModel.getSongs();
  1215. }
  1216. getCurrentIndex(): number {
  1217. return this.playlistModel.getCurrentIndex();
  1218. }
  1219. /**
  1220. * 检查数据是否已从持久化存储恢复
  1221. */
  1222. isDataRestorationCompleted(): boolean {
  1223. return this.isDataRestored;
  1224. }
  1225. /**
  1226. * 等待数据恢复完成
  1227. */
  1228. async waitForDataRestoration(maxWaitMs: number = 3000): Promise<boolean> {
  1229. const startTime = Date.now();
  1230. while (!this.isDataRestored && (Date.now() - startTime) < maxWaitMs) {
  1231. await new Promise<void>(resolve => setTimeout(resolve, 100));
  1232. }
  1233. return this.isDataRestored;
  1234. }
  1235. /**
  1236. * 强制触发数据恢复(用于桌面卡片冷启动场景)
  1237. */
  1238. async forceDataRestoration(): Promise<boolean> {
  1239. try {
  1240. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Force data restoration started');
  1241. // 如果数据已经恢复,直接返回
  1242. if (this.isDataRestored) {
  1243. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Data already restored');
  1244. return true;
  1245. }
  1246. // 强制执行数据恢复
  1247. await this.restorePersistedState();
  1248. // 如果播放列表仍为空,尝试从内存快速恢复
  1249. if (this.playlistModel.getTotalCount() === 0) {
  1250. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Playlist empty, trying memory restore');
  1251. await this.fastRestoreFromMemory();
  1252. }
  1253. LogUtils.getInstance()
  1254. .LOGI(`Heanup UnifiedPlayerService: Force restoration completed, playlist size: ${this.playlistModel.getTotalCount()}`);
  1255. return this.isDataRestored;
  1256. } catch (error) {
  1257. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Force data restoration failed: ${error}`);
  1258. return false;
  1259. }
  1260. }
  1261. /**
  1262. * 检查服务是否已初始化
  1263. */
  1264. isServiceInitialized(): boolean {
  1265. return this.initialized;
  1266. }
  1267. /**
  1268. * 检查所有相关服务是否已准备就绪
  1269. * 用于桌面卡片控制等场景,确保在执行播放控制前服务状态正常
  1270. */
  1271. isAllServicesReady(): boolean {
  1272. if (this.hasChecked){
  1273. return true;
  1274. }else {
  1275. this.hasChecked = true;
  1276. try {
  1277. // 检查基本初始化状态
  1278. if (!this.initialized) {
  1279. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Service not initialized');
  1280. return false;
  1281. }
  1282. // 检查核心组件是否就绪
  1283. if (!this.playerManager || !this.stateModel || !this.playlistModel) {
  1284. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Core components not ready');
  1285. return false;
  1286. }
  1287. // 检查 PlayerManager 是否已经初始化
  1288. const playerInstance = this.playerManager.getIjkPlayer();
  1289. if (!playerInstance) {
  1290. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Player instance not ready');
  1291. return false;
  1292. }
  1293. // 检查上下文是否可用
  1294. if (!this.context) {
  1295. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Context not available');
  1296. return false;
  1297. }
  1298. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: All services ready');
  1299. return true;
  1300. } catch (error) {
  1301. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Service readiness check failed: ${error}`);
  1302. return false;
  1303. }
  1304. }
  1305. }
  1306. /**
  1307. * 验证初始化完整性
  1308. * 在应用启动后调用,确保所有关键组件都已正确初始化
  1309. */
  1310. validateInitialization(): InitializationValidation {
  1311. const errors: string[] = [];
  1312. const warnings: string[] = [];
  1313. try {
  1314. // 检查基础初始化
  1315. if (!this.initialized) {
  1316. errors.push('Service not initialized');
  1317. }
  1318. // 检查核心组件
  1319. if (!this.playerManager) {
  1320. errors.push('PlayerManager not available');
  1321. } else {
  1322. const playerInstance = this.playerManager.getIjkPlayer();
  1323. if (!playerInstance) {
  1324. warnings.push('Player instance not ready (may initialize later)');
  1325. }
  1326. }
  1327. if (!this.stateModel) {
  1328. errors.push('StateModel not available');
  1329. }
  1330. if (!this.playlistModel) {
  1331. errors.push('PlaylistModel not available');
  1332. }
  1333. if (!this.context) {
  1334. warnings.push('Context not set (may be set later)');
  1335. }
  1336. // 检查数据持久化服务
  1337. if (!this.dataPersistence) {
  1338. errors.push('DataPersistence service not available');
  1339. }
  1340. if (!this.playlistSync) {
  1341. errors.push('PlaylistSync service not available');
  1342. }
  1343. // 检查错误恢复策略
  1344. if (!this.errorRecovery) {
  1345. warnings.push('ErrorRecovery strategy not available');
  1346. }
  1347. const isValid = errors.length === 0;
  1348. LogUtils.getInstance()
  1349. .LOGI(`Heanup UnifiedPlayerService validation: ${isValid ? 'VALID' :
  1350. 'INVALID'}, errors: ${errors.length}, warnings: ${warnings.length}`);
  1351. const result: InitializationValidation = {
  1352. isValid,
  1353. errors,
  1354. warnings
  1355. };
  1356. return result;
  1357. } catch (error) {
  1358. errors.push(`Validation failed with exception: ${error}`);
  1359. const result: InitializationValidation = {
  1360. isValid: false,
  1361. errors,
  1362. warnings
  1363. };
  1364. return result;
  1365. }
  1366. }
  1367. /**
  1368. * 获取服务就绪状态的详细信息
  1369. * 用于调试和用户反馈
  1370. */
  1371. getServiceReadinessInfo(): ServiceReadinessInfo {
  1372. const playerInstance = this.playerManager?.getIjkPlayer();
  1373. const playlistSize = this.playlistModel?.getTotalCount() || 0;
  1374. const currentIndex = this.playlistModel?.getCurrentIndex() || -1;
  1375. const details: ServiceReadinessDetails = {
  1376. initialized: this.initialized,
  1377. hasPlayerInstance: !!playerInstance,
  1378. hasContext: !!this.context,
  1379. dataRestored: this.isDataRestored,
  1380. playlistSize: playlistSize,
  1381. currentIndex: currentIndex
  1382. };
  1383. const isReady = this.isAllServicesReady();
  1384. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService readiness: ${JSON.stringify(details)}`);
  1385. const result: ServiceReadinessInfo = { isReady, details };
  1386. return result;
  1387. }
  1388. /**
  1389. * 等待所有服务准备就绪
  1390. * @param maxWaitMs 最大等待时间(毫秒)
  1391. * @param checkDataRestore 是否同时等待数据恢复完成
  1392. */
  1393. async waitForAllServicesReady(maxWaitMs: number = 5000, checkDataRestore: boolean = true): Promise<boolean> {
  1394. const startTime = Date.now();
  1395. const checkInterval = 100; // 每100ms检查一次
  1396. LogUtils.getInstance()
  1397. .LOGI(`Heanup UnifiedPlayerService: Waiting for services ready (maxWait: ${maxWaitMs}ms, checkDataRestore: ${checkDataRestore})`);
  1398. while ((Date.now() - startTime) < maxWaitMs) {
  1399. // 检查基础服务就绪状态
  1400. if (this.isAllServicesReady()) {
  1401. // 如果不需要检查数据恢复,直接返回成功
  1402. if (!checkDataRestore) {
  1403. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: All services ready (data restore check skipped)');
  1404. return true;
  1405. }
  1406. // 检查数据恢复状态
  1407. if (this.isDataRestored) {
  1408. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: All services ready and data restored');
  1409. return true;
  1410. }
  1411. // 检查播放列表是否有数据(即使数据恢复标识未设置)
  1412. const playlistSize = this.playlistModel.getTotalCount();
  1413. if (playlistSize > 0) {
  1414. LogUtils.getInstance()
  1415. .LOGI(`Heanup UnifiedPlayerService: Services ready with playlist data (${playlistSize} songs)`);
  1416. return true;
  1417. }
  1418. }
  1419. // 短暂等待后继续检查
  1420. await new Promise<void>(resolve => setTimeout(resolve, checkInterval));
  1421. }
  1422. // 超时检查最终状态
  1423. const finalCheck = this.isAllServicesReady();
  1424. const playlistSize = this.playlistModel?.getTotalCount() || 0;
  1425. LogUtils.getInstance()
  1426. .LOGI(`Heanup UnifiedPlayerService: Service readiness timeout - finalCheck: ${finalCheck}, playlistSize: ${playlistSize}, dataRestored: ${this.isDataRestored}`);
  1427. return finalCheck;
  1428. }
  1429. // 播放模式控制
  1430. setPlayMode(mode: number): void {
  1431. const playMode = mode as PlayMode;
  1432. this.stateModel.updatePlayMode(playMode);
  1433. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Play mode set to ${mode}`);
  1434. }
  1435. getPlayMode(): number {
  1436. return this.stateModel.getState().playMode;
  1437. }
  1438. // 音量和速度控制
  1439. setVolume(volume: number): void {
  1440. const volumeStr = volume.toString();
  1441. this.playerManager.setVolume(volumeStr, volumeStr);
  1442. this.stateModel.updateVolume(volume);
  1443. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Volume set to ${volume}`);
  1444. }
  1445. setPlaybackSpeed(speed: number): void {
  1446. const speedStr = speed.toString() + 'f';
  1447. this.playerManager.setPlaybackSpeed(speedStr);
  1448. this.stateModel.updateSpeed(speed);
  1449. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Speed set to ${speed}`);
  1450. }
  1451. // 播放列表管理
  1452. setPlaylist(songs: VideoItem[], currentIndex: number = 0): void {
  1453. // 记录调用栈信息以便调试
  1454. const stack = new Error().stack || 'No stack available';
  1455. const caller = stack.split('\n')[2] || 'Unknown caller';
  1456. this.playlistModel.replaceSongs(songs, currentIndex);
  1457. this.stateModel.updateCurrentIndex(currentIndex);
  1458. // 更新状态模型中的播放列表状态
  1459. this.updatePlaylistStateInModelSync();
  1460. // 更新当前歌曲
  1461. const currentSong = this.playlistModel.getCurrentSong();
  1462. this.stateModel.updateCurrentSong(currentSong);
  1463. // 同步到持久化存储(异步执行,不阻塞主线程)
  1464. this.syncPlaylistToStorage().catch((error:Error) => {
  1465. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService setPlaylist syncPlaylistToStorage error: ${error}`);
  1466. });
  1467. // 更新卡片显示播放列表变化
  1468. this.updateWidgetsForPlaylistChange();
  1469. LogUtils.getInstance()
  1470. .LOGI(`Heanup UnifiedPlayerService: Playlist set with ${songs.length} songs, caller: ${caller.trim()}`);
  1471. // 如果设置的是小播放列表,记录更多信息
  1472. if (songs.length <= 20) {
  1473. LogUtils.getInstance()
  1474. .LOGI(`Heanup UnifiedPlayerService: Small playlist detected, caller stack: ${stack.substring(0, 500)}`);
  1475. }
  1476. }
  1477. addToPlaylist(song: VideoItem, index?: number): void {
  1478. this.playlistModel.addSong(song, index);
  1479. // 更新状态模型中的播放列表状态
  1480. this.updatePlaylistStateInModelSync();
  1481. // 同步到持久化存储(异步执行,不阻塞主线程)
  1482. this.syncPlaylistToStorage().catch((error:Error) => {
  1483. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService addToPlaylist syncPlaylistToStorage error: ${error}`);
  1484. });
  1485. // 更新卡片显示播放列表变化
  1486. this.updateWidgetsForPlaylistChange();
  1487. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Song added to playlist`);
  1488. }
  1489. removeFromPlaylist(index: number): VideoItem | null {
  1490. const removedSong = this.playlistModel.removeSong(index);
  1491. if (removedSong) {
  1492. this.stateModel.updateCurrentIndex(this.playlistModel.getCurrentIndex());
  1493. // 更新状态模型中的播放列表状态
  1494. this.updatePlaylistStateInModelSync();
  1495. // 更新当前歌曲
  1496. const currentSong = this.playlistModel.getCurrentSong();
  1497. this.stateModel.updateCurrentSong(currentSong);
  1498. // 同步到持久化存储(异步执行,不阻塞主线程)
  1499. this.syncPlaylistToStorage().catch((error:Error) => {
  1500. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService removeFromPlaylist syncPlaylistToStorage error: ${error}`);
  1501. });
  1502. // 更新卡片显示播放列表变化
  1503. this.updateWidgetsForPlaylistChange();
  1504. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Song removed from playlist at index ${index}`);
  1505. }
  1506. return removedSong;
  1507. }
  1508. /**
  1509. * 同步播放列表到服务
  1510. * 从LocalMusic迁移的方法,用于统一调用
  1511. */
  1512. syncPlaylistToService(songList: VideoItem[], currentIndex: number, playType: PlayMode): void {
  1513. try {
  1514. if (songList && songList.length > 0) {
  1515. // 记录调用栈信息以便调试
  1516. const stack = new Error().stack || 'No stack available';
  1517. const caller = stack.split('\n')[2] || 'Unknown caller';
  1518. this.setPlaylist(songList, currentIndex);
  1519. // 同步播放模式到UnifiedPlayerService
  1520. this.setPlayMode(playType);
  1521. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Playlist and play mode synced - ${songList.length} songs, mode: ${playType}, caller: ${caller.trim()}`);
  1522. // 如果同步的是小播放列表,记录更多信息
  1523. if (songList.length <= 20) {
  1524. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Small playlist sync detected, first few songs: ${songList.slice(0, 5).map(s => s.name).join(', ')}`);
  1525. }
  1526. } else {
  1527. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: syncPlaylistToService - No songs to sync');
  1528. }
  1529. } catch (error) {
  1530. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService syncPlaylistToService error: ${error}`);
  1531. }
  1532. }
  1533. // 事件监听
  1534. addStateListener(listener: PlayerStateListener): void {
  1535. this.stateModel.addStateListener(listener);
  1536. }
  1537. removeStateListener(listener: PlayerStateListener): void {
  1538. this.stateModel.removeStateListener(listener);
  1539. }
  1540. // 清理资源
  1541. async release(): Promise<void> {
  1542. try {
  1543. this.stopProgressTimer();
  1544. // 清理防抖定时器
  1545. if (this.avSessionUpdateTimer !== -1) {
  1546. clearTimeout(this.avSessionUpdateTimer);
  1547. this.avSessionUpdateTimer = -1;
  1548. }
  1549. if (this.avMetadataUpdateTimer !== -1) {
  1550. clearTimeout(this.avMetadataUpdateTimer);
  1551. this.avMetadataUpdateTimer = -1;
  1552. }
  1553. // 关键修复:先保存当前状态,再清理资源
  1554. // 这样可以确保播放列表在应用被杀掉时不会丢失
  1555. await this.saveCurrentState();
  1556. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Current state saved before resource cleanup');
  1557. // 重要修复:确保在应用销毁时将播放状态设置为停止
  1558. try {
  1559. // 强制设置为停止状态,防止卡片显示错误的播放状态
  1560. this.stateModel.updatePlayingState(false);
  1561. this.stateModel.updateLoadingState(false);
  1562. // 确保播放器也停止
  1563. if (this.playerManager) {
  1564. this.playerManager.release() ;
  1565. }
  1566. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Forced stop state before release');
  1567. } catch (error) {
  1568. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to force stop state: ${error}`);
  1569. }
  1570. if (this.avSessionController) {
  1571. this.avSessionController.unregisterSessionListener();
  1572. this.avSessionController = null;
  1573. }
  1574. // 清理同步监听器
  1575. this.playlistSync.removeSyncListener(this);
  1576. this.playlistSync.release();
  1577. // 最后清理播放列表模型,确保在此之前状态已经保存
  1578. this.playlistModel.clear();
  1579. this.initialized = false;
  1580. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Resources released');
  1581. } catch (error) {
  1582. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService release error: ${error}`);
  1583. }
  1584. }
  1585. /**
  1586. * 初始化AVSession
  1587. * 按照官方文档的要求:创建 -> 注册控制命令 -> 设置元数据 -> 激活
  1588. */
  1589. private initializeAvSession(): void {
  1590. try {
  1591. this.avSessionController = AvSessionController.getInstance(false);
  1592. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession controller created');
  1593. setTimeout(() => {
  1594. this.setAvSessionListener();
  1595. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession listeners configured');
  1596. }, 500);
  1597. } catch (error) {
  1598. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to initialize AVSession: ${error}`);
  1599. }
  1600. }
  1601. /**
  1602. * 设置AVSession监听器
  1603. * 注意:控制命令已在AvSessionController中注册,这里设置实际的处理逻辑
  1604. */
  1605. private setAvSessionListener(): void {
  1606. if (!this.avSessionController) {
  1607. return;
  1608. }
  1609. const avSession = this.avSessionController.getAvSession();
  1610. if (!avSession) {
  1611. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession not available for listener setup');
  1612. return;
  1613. }
  1614. try {
  1615. // 播放事件监听
  1616. avSession.on('play', () => {
  1617. this.startPlayOrResumePlay().catch((error: Error) => {
  1618. LogUtils.getInstance().LOGI(`AVSession play command failed: ${error}`);
  1619. });
  1620. });
  1621. // 暂停事件监听
  1622. avSession.on('pause', () => {
  1623. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession pause command received');
  1624. this.pause().catch((error: Error) => {
  1625. LogUtils.getInstance().LOGI(`AVSession pause command failed: ${error}`);
  1626. });
  1627. });
  1628. // 停止事件监听
  1629. avSession.on('stop', () => {
  1630. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession stop command received');
  1631. this.stop().catch((error: Error) => {
  1632. LogUtils.getInstance().LOGI(`AVSession stop command failed: ${error}`);
  1633. });
  1634. });
  1635. // 下一首事件监听
  1636. avSession.on('playNext', () => {
  1637. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession playNext command received');
  1638. this.playNext().catch((error: Error) => {
  1639. LogUtils.getInstance().LOGI(`AVSession playNext command failed: ${error}`);
  1640. });
  1641. });
  1642. // 上一首事件监听
  1643. avSession.on('playPrevious', () => {
  1644. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession playPrevious command received');
  1645. this.playPrevious().catch((error: Error) => {
  1646. LogUtils.getInstance().LOGI(`AVSession playPrevious command failed: ${error}`);
  1647. });
  1648. });
  1649. // 拖拽进度事件监听
  1650. avSession.on('seek', (time: number) => {
  1651. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: AVSession seek command received: ${time}ms`);
  1652. this.seekTo(time.toString()).catch((error: Error) => {
  1653. LogUtils.getInstance().LOGI(`AVSession seek command failed: ${error}`);
  1654. });
  1655. });
  1656. // 播放模式设置监听
  1657. avSession.on('setLoopMode', (mode: number) => {
  1658. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: AVSession setLoopMode command received: ${mode}`);
  1659. try {
  1660. this.setPlayMode(mode);
  1661. // 更新AvSession播放状态以反映新的播放模式
  1662. this.updateSessionPlayState();
  1663. // 同步更新桌面卡片
  1664. this.updateAllForms();
  1665. } catch (error) {
  1666. LogUtils.getInstance().LOGI(`AVSession setLoopMode command failed: ${error}`);
  1667. }
  1668. });
  1669. // 收藏事件监听
  1670. avSession.on('toggleFavorite', () => {
  1671. this.toggleFavorite() ;
  1672. });
  1673. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession listeners set up successfully');
  1674. } catch (error) {
  1675. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to set AVSession listeners: ${error}`);
  1676. }
  1677. }
  1678. /**
  1679. * 处理播放错误
  1680. */
  1681. private async handlePlaybackError(error: Error,
  1682. errorType: PlayerErrorType = PlayerErrorType.PLAYBACK_ERROR): Promise<void> {
  1683. try {
  1684. // 创建播放器错误对象
  1685. const playerError = new PlayerError(errorType, error.message);
  1686. playerError.retryCount = this.currentRetryCount;
  1687. // 创建错误上下文
  1688. const context: ErrorContext = {
  1689. currentSong: this.playlistModel.getCurrentSong(),
  1690. playlist: this.playlistModel.getSongs(),
  1691. currentIndex: this.playlistModel.getCurrentIndex(),
  1692. retryCount: this.currentRetryCount,
  1693. isNetworkAvailable: true // 这里可以实际检查网络状态
  1694. };
  1695. // 获取恢复策略
  1696. const recoveryAction = await this.errorRecovery.handleError(playerError, context);
  1697. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error recovery action: ${recoveryAction}`);
  1698. // 执行恢复动作
  1699. await this.executeRecoveryAction(recoveryAction, playerError, context);
  1700. } catch (recoveryError) {
  1701. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error recovery failed: ${recoveryError}`);
  1702. this.stateModel.notifyError(new PlayerError(PlayerErrorType.PLAYBACK_ERROR,
  1703. `Recovery failed: ${(recoveryError as Error).message}`));
  1704. }
  1705. }
  1706. /**
  1707. * 执行错误恢复动作
  1708. */
  1709. private async executeRecoveryAction(action: ErrorRecoveryAction, error: PlayerError,
  1710. context: ErrorContext): Promise<void> {
  1711. switch (action) {
  1712. case ErrorRecoveryAction.RETRY:
  1713. await this.retryCurrentOperation(error);
  1714. break;
  1715. case ErrorRecoveryAction.SKIP_TO_NEXT:
  1716. await this.skipToNextSong();
  1717. break;
  1718. case ErrorRecoveryAction.STOP_PLAYBACK:
  1719. await this.stop();
  1720. this.stateModel.notifyError(error);
  1721. break;
  1722. case ErrorRecoveryAction.WAIT_AND_RETRY:
  1723. await this.waitAndRetry(error);
  1724. break;
  1725. case ErrorRecoveryAction.SHOW_ERROR:
  1726. this.stateModel.notifyError(error);
  1727. break;
  1728. default:
  1729. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Unknown recovery action: ${action}`);
  1730. this.stateModel.notifyError(error);
  1731. }
  1732. }
  1733. /**
  1734. * 重试当前操作
  1735. */
  1736. private async retryCurrentOperation(error: PlayerError): Promise<void> {
  1737. try {
  1738. this.currentRetryCount++;
  1739. const delay = this.errorRecovery.getRetryDelay(this.currentRetryCount);
  1740. LogUtils.getInstance()
  1741. .LOGI(`Heanup UnifiedPlayerService: Retrying operation in ${delay}ms (attempt ${this.currentRetryCount})`);
  1742. // 等待指定时间后重试
  1743. setTimeout(async () => {
  1744. try {
  1745. await this.startPlayOrResumePlay();
  1746. this.currentRetryCount = 0; // 重试成功,重置计数
  1747. } catch (retryError) {
  1748. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Retry failed: ${retryError}`);
  1749. await this.handlePlaybackError(retryError as Error, error.type);
  1750. }
  1751. }, delay);
  1752. } catch (retryError) {
  1753. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Retry setup failed: ${retryError}`);
  1754. await this.skipToNextSong();
  1755. }
  1756. }
  1757. /**
  1758. * 跳到下一首歌曲
  1759. */
  1760. private async skipToNextSong(): Promise<void> {
  1761. try {
  1762. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Skipping to next song due to error');
  1763. // 重置重试计数
  1764. this.currentRetryCount = 0;
  1765. // 检查是否有下一首
  1766. const playMode = this.stateModel.getState().playMode;
  1767. if (this.playlistModel.hasNext(playMode)) {
  1768. await this.playNext();
  1769. } else {
  1770. // 没有下一首,停止播放
  1771. await this.stop();
  1772. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: No next song available, stopping playback');
  1773. }
  1774. } catch (skipError) {
  1775. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to skip to next song: ${skipError}`);
  1776. await this.stop();
  1777. }
  1778. }
  1779. /**
  1780. * 等待后重试
  1781. */
  1782. private async waitAndRetry(error: PlayerError): Promise<void> {
  1783. try {
  1784. this.currentRetryCount++;
  1785. const delay = this.errorRecovery.getRetryDelay(this.currentRetryCount);
  1786. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Waiting ${delay}ms before retry (network error)`);
  1787. // 更新状态为加载中
  1788. this.stateModel.updateLoadingState(true);
  1789. setTimeout(async () => {
  1790. try {
  1791. await this.startPlayOrResumePlay();
  1792. this.currentRetryCount = 0; // 重试成功,重置计数
  1793. } catch (retryError) {
  1794. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Network retry failed: ${retryError}`);
  1795. await this.handlePlaybackError(retryError as Error, PlayerErrorType.NETWORK_ERROR);
  1796. }
  1797. }, delay);
  1798. } catch (waitError) {
  1799. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Wait and retry setup failed: ${waitError}`);
  1800. await this.skipToNextSong();
  1801. }
  1802. }
  1803. /**
  1804. * 检查文件是否存在
  1805. */
  1806. private async checkFileExists(filePath: string): Promise<boolean> {
  1807. try {
  1808. // 这里可以添加文件存在性检查逻辑
  1809. // 暂时返回true,实际实现需要使用文件系统API
  1810. return true;
  1811. } catch (error) {
  1812. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: File check failed: ${error}`);
  1813. return false;
  1814. }
  1815. }
  1816. /**
  1817. * 检查网络连接
  1818. */
  1819. private async checkNetworkConnection(): Promise<boolean> {
  1820. try {
  1821. // 这里可以添加网络连接检查逻辑
  1822. // 暂时返回true,实际实现需要使用网络API
  1823. return true;
  1824. } catch (error) {
  1825. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Network check failed: ${error}`);
  1826. return false;
  1827. }
  1828. }
  1829. // 私有辅助方法
  1830. /**
  1831. * 检查播放器是否需要重新设置
  1832. */
  1833. private async needsPlayerSetup(song: VideoItem): Promise<boolean> {
  1834. try {
  1835. const ijkPlayer = this.playerManager.getIjkPlayer();
  1836. if (!ijkPlayer) {
  1837. console.log("Heanup2 UnifiedPlayerService: 播放器不存在,需要设置");
  1838. return true;
  1839. }
  1840. // 检查播放器是否有数据源
  1841. const duration = ijkPlayer.getDuration();
  1842. if (duration <= 0) {
  1843. console.log("Heanup2 UnifiedPlayerService: 播放器无数据源或时长无效,需要设置");
  1844. return true;
  1845. }
  1846. // 检查当前数据源是否匹配(这里我们通过检查当前歌曲信息来判断)
  1847. const currentSong = this.playlistModel.getCurrentSong();
  1848. if (!currentSong || currentSong.filePath !== song.filePath) {
  1849. console.log(`Heanup2 UnifiedPlayerService: 歌曲文件路径不匹配,需要重新设置 (当前: ${currentSong?.filePath}, 目标: ${song.filePath})`);
  1850. return true;
  1851. }
  1852. console.log(`Heanup2 UnifiedPlayerService: 播放器已设置正确的数据源,无需重新设置 (时长: ${duration}ms)`);
  1853. return false;
  1854. } catch (error) {
  1855. console.log(`Heanup2 UnifiedPlayerService: 检查播放器设置状态时出错: ${error},默认需要设置`);
  1856. return true;
  1857. }
  1858. }
  1859. // 缓存播放器是否已初始化配置,避免重复设置
  1860. private isPlayerConfigured: boolean = false;
  1861. private async setupPlayerForSong(song: VideoItem): Promise<void> {
  1862. const ijkPlayer = this.playerManager.getIjkPlayer();
  1863. if (!ijkPlayer) {
  1864. throw new Error('Player not initialized');
  1865. }
  1866. console.log("Heanup2 UnifiedPlayerService: 开始重新设置播放器,这会重置所有状态");
  1867. // 标记播放器未准备(因为要重新设置)
  1868. this.isPlayerPreparedForCurrentSong = false;
  1869. // 重置播放器 - 这会清除所有状态包括播放位置
  1870. ijkPlayer.reset();
  1871. // 清空当前加载的歌曲记录
  1872. this.currentlyLoadedSong = null;
  1873. // 重新设置音频模式 - 重置后需要重新设置
  1874. ijkPlayer.setAudioId('unifiedPlayer');
  1875. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Reset audio mode for ${song.name}`);
  1876. // 优化:只在首次或配置变更时重新设置所有选项
  1877. if (!this.isPlayerConfigured) {
  1878. this.playerManager.setupIjkPlayerOptions();
  1879. this.isPlayerConfigured = true;
  1880. } else {
  1881. // 快速重置关键配置项,避免完整重新配置
  1882. this.setupEssentialPlayerOptions();
  1883. }
  1884. // 设置音量(针对dsf格式特殊处理)
  1885. const volume = this.stateModel.getState().volume;
  1886. if (song.filePath.toLowerCase().endsWith('.dsf')) {
  1887. this.playerManager.setVolume('1', '1');
  1888. } else {
  1889. this.playerManager.setVolume(volume.toString(), volume.toString());
  1890. }
  1891. // 设置数据源
  1892. ijkPlayer.setDataSource(song.filePath);
  1893. // 记录当前播放器加载的歌曲
  1894. this.currentlyLoadedSong = song;
  1895. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Set data source to ${song.filePath}`);
  1896. // 优化:异步设置HTTP请求头,不阻塞主流程
  1897. Promise.resolve().then(() => {
  1898. // 设置HTTP请求头
  1899. const headers = new Map([
  1900. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  1901. ["referer", "https://www.bilibili.com"]
  1902. ]);
  1903. ijkPlayer.setDataSourceHeader(headers);
  1904. // 设置播放速度
  1905. const speed = this.stateModel.getState().speed;
  1906. this.playerManager.setPlaybackSpeed(speed.toString() + 'f');
  1907. });
  1908. // 设置消息监听器(重要:用于处理播放器内部事件)
  1909. ijkPlayer.setMessageListener();
  1910. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Player setup for song ${song.name}`);
  1911. console.log("Heanup2 UnifiedPlayerService: 播放器重新设置完成,准备开始新的播放");
  1912. }
  1913. /**
  1914. * 快速设置关键播放器选项,避免完整重新配置的性能开销
  1915. */
  1916. private setupEssentialPlayerOptions(): void {
  1917. const ijkPlayer = this.playerManager.getIjkPlayer();
  1918. if (!ijkPlayer) return;
  1919. // 仅设置切换歌曲时必须重置的关键选项
  1920. ijkPlayer.native_setup(); // 音频模式初始化
  1921. ijkPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "0");
  1922. ijkPlayer.setScreenOnWhilePlaying(true);
  1923. // 关键修复:确保变速播放配置在每次歌曲切换时都被设置
  1924. ijkPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  1925. LogUtils.getInstance().LOGI('UnifiedPlayerService: Essential soundtouch configured for speed control');
  1926. }
  1927. private setupProgressTimer(): void {
  1928. this.progressTimer = setInterval(() => {
  1929. this.updateProgress();
  1930. }, 1000); // 每秒更新一次进度
  1931. }
  1932. private startProgressTimer(): void {
  1933. // 先停止现有的定时器,避免重复启动
  1934. this.stopProgressTimer();
  1935. // 启动新的定时器
  1936. this.setupProgressTimer();
  1937. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Progress timer started');
  1938. }
  1939. /**
  1940. * 停止进度定时器
  1941. */
  1942. private stopProgressTimer(): void {
  1943. if (this.progressTimer !== -1) {
  1944. clearInterval(this.progressTimer);
  1945. this.progressTimer = -1;
  1946. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Progress timer stopped');
  1947. }
  1948. }
  1949. private updateProgress(): void {
  1950. try {
  1951. const ijkPlayer = this.playerManager.getIjkPlayer();
  1952. const currentState = this.stateModel.getState();
  1953. // 只有在播放器存在、正在播放且已准备好时才更新进度
  1954. if (!ijkPlayer || !currentState.isPlaying || !this.isPlayerPreparedForCurrentSong) {
  1955. return;
  1956. }
  1957. const currentPosition = ijkPlayer.getCurrentPosition();
  1958. const duration = ijkPlayer.getDuration();
  1959. // 确保获取到有效的位置信息
  1960. if (currentPosition >= 0 && duration > 0) {
  1961. this.stateModel.updateProgress(currentPosition, duration);
  1962. this.updateSessionPlayState();
  1963. }
  1964. } catch (error) {
  1965. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService updateProgress error: ${error}`);
  1966. }
  1967. }
  1968. getCurrentPosition(): number {
  1969. try {
  1970. const ijkPlayer = this.playerManager.getIjkPlayer();
  1971. if (!ijkPlayer) {
  1972. return 0;
  1973. }
  1974. return ijkPlayer.getCurrentPosition();
  1975. } catch (error) {
  1976. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService getCurrentPosition error: ${error}`);
  1977. return 0;
  1978. }
  1979. }
  1980. getIjkPlayer(): IjkMediaPlayer | null {
  1981. try {
  1982. return this.playerManager.getIjkPlayer();
  1983. } catch (error) {
  1984. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService getIjkPlayer error: ${error}`);
  1985. return null;
  1986. }
  1987. }
  1988. // 记录当前播放器实际加载的歌曲
  1989. private currentlyLoadedSong: VideoItem | null = null;
  1990. private savePlaybackPosition(targetSong?: VideoItem): void {
  1991. try {
  1992. // 检查用户是否启用了记忆播放功能
  1993. const isMusicMemoryPlay = PuraPreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false);
  1994. if (!isMusicMemoryPlay) {
  1995. return; // 用户未启用,直接返回
  1996. }
  1997. const ijkPlayer = this.playerManager.getIjkPlayer();
  1998. let currentSong = targetSong;
  1999. // 如果没有传入具体歌曲,优先使用播放器当前加载的歌曲
  2000. if (!currentSong) {
  2001. currentSong = this.currentlyLoadedSong || this.playlistModel.getCurrentSong()!;
  2002. }
  2003. if (ijkPlayer != null && currentSong != null) {
  2004. const position = ijkPlayer.getCurrentPosition();
  2005. const duration = ijkPlayer.getDuration();
  2006. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  2007. // 如果播放位置接近视频末尾,则保存 position 为 0
  2008. const playbackPosition = (duration - position < threshold) ? 0 : position;
  2009. // 使用filePath作为键,确保与恢复时一致
  2010. PuraPreferencesUtil.putSync(currentSong.filePath, playbackPosition);
  2011. // 同时保存到AppStorage,确保卡片也能访问(使用相同的键)
  2012. AppStorage.setOrCreate(`playback_${currentSong.filePath}`, playbackPosition);
  2013. // 获取调用栈信息用于调试
  2014. const stack = new Error().stack;
  2015. const caller = stack?.split('\n')[2]?.trim() || 'Unknown caller';
  2016. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能 Saved playback position: ${playbackPosition}ms for ${currentSong.name} (filePath: ${currentSong.filePath}) - Called from: ${caller}`);
  2017. }
  2018. } catch (error) {
  2019. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能 savePlaybackPosition error: ${error}`);
  2020. }
  2021. }
  2022. private async restorePlaybackPosition(song: VideoItem): Promise<void> {
  2023. // const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  2024. // // ToastUtil.showToast('position = ' + position)
  2025. // if (this.mIjkMediaPlayer != null && position > 0) {
  2026. // // ToastUtil.showToast('seekTo = ' + position)
  2027. // this.seekTo(position + "");
  2028. //
  2029. // }
  2030. if (song != null) {
  2031. const position: number = PuraPreferencesUtil.getNumberSync(song.filePath, 0);
  2032. if (position > 0) {
  2033. await this.playerManager.seekToPosition(position.toString());
  2034. }
  2035. }
  2036. // try {
  2037. // // 使用DataPersistenceService恢复播放进度
  2038. // const progressData = await this.dataPersistence.loadPlaybackProgress(song.filePath);
  2039. // if (progressData && progressData.position > 0 && !progressData.completed) {
  2040. // await this.playerManager.seekToPosition(progressData.position.toString());
  2041. // LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Restored playback position ${progressData.position}ms for ${song.name}`);
  2042. // }
  2043. // } catch (error) {
  2044. // LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService restorePlaybackPosition error: ${error}`);
  2045. // }
  2046. }
  2047. // ==================== 数据持久化和同步方法 ====================
  2048. /**
  2049. * 恢复持久化的状态
  2050. */
  2051. /**
  2052. * 快速从内存中恢复关键数据(AppStorage)
  2053. */
  2054. private async fastRestoreFromMemory(): Promise<void> {
  2055. try {
  2056. console.log("Heanup2 UnifiedPlayerService: 开始从内存快速恢复关键数据");
  2057. // 从AppStorage快速获取播放列表数据
  2058. const playlistData = AppStorage.get<PlaylistData>('player_playlist');
  2059. if (playlistData && playlistData.songs.length > 0) {
  2060. console.log(`Heanup2 UnifiedPlayerService: 从内存快速恢复播放列表,歌曲数量=${playlistData.songs.length}`);
  2061. this.playlistModel.replaceSongs(playlistData.songs, playlistData.currentIndex);
  2062. this.stateModel.updateCurrentIndex(playlistData.currentIndex);
  2063. this.stateModel.updatePlayMode(playlistData.playMode);
  2064. // 恢复当前歌曲
  2065. const currentSong = this.playlistModel.getCurrentSong();
  2066. if (currentSong) {
  2067. this.stateModel.updateCurrentSong(currentSong);
  2068. console.log(`Heanup2 UnifiedPlayerService: 快速恢复当前歌曲: ${currentSong.name}`);
  2069. }
  2070. }
  2071. // 从AppStorage快速获取播放状态数据
  2072. const stateData = AppStorage.get<PlayerStateData>('player_state') as PlayerStateData;
  2073. if (stateData) {
  2074. console.log(`Heanup2 UnifiedPlayerService: 从内存快速恢复播放状态 - playing: ${stateData.isPlaying}, index: ${stateData.currentIndex}`);
  2075. this.stateModel.updateVolume(stateData.volume);
  2076. this.stateModel.updateSpeed(stateData.speed);
  2077. this.stateModel.updatePlayMode(stateData.playMode);
  2078. this.stateModel.updatePlayingState(stateData.isPlaying || false);
  2079. if (stateData.currentIndex >= 0) {
  2080. this.stateModel.updateCurrentIndex(stateData.currentIndex);
  2081. }
  2082. }
  2083. console.log("Heanup2 UnifiedPlayerService: 内存数据快速恢复完成");
  2084. // 设置一个临时的数据恢复完成标识,允许快速响应
  2085. this.isDataRestored = true;
  2086. // 立即更新播放列表状态,确保上一首/下一首状态正确
  2087. this.updatePlaylistStateInModelSync();
  2088. } catch (error) {
  2089. console.log(`Heanup2 UnifiedPlayerService: 快速恢复内存数据失败: ${error}`);
  2090. }
  2091. }
  2092. private async restorePersistedState(): Promise<void> {
  2093. try {
  2094. console.log("Heanup2 UnifiedPlayerService: 开始快速恢复持久化状态");
  2095. // 并行加载播放列表和播放状态,提高效率
  2096. const loadResults = await Promise.all([
  2097. this.dataPersistence.loadPlaylist().catch(() => null),
  2098. this.dataPersistence.loadPlayerState().catch(() => null)
  2099. ]);
  2100. const playlistData = loadResults[0];
  2101. const stateData = loadResults[1];
  2102. // 恢复播放列表
  2103. if (playlistData && playlistData.songs.length > 0) {
  2104. console.log(`Heanup2 UnifiedPlayerService: 恢复播放列表,歌曲数量=${playlistData.songs.length}, 当前索引=${playlistData.currentIndex}`);
  2105. this.playlistModel.replaceSongs(playlistData.songs, playlistData.currentIndex);
  2106. this.stateModel.updateCurrentIndex(playlistData.currentIndex);
  2107. this.stateModel.updatePlayMode(playlistData.playMode);
  2108. // 恢复当前歌曲到状态模型
  2109. const currentSong = this.playlistModel.getCurrentSong();
  2110. if (currentSong) {
  2111. this.stateModel.updateCurrentSong(currentSong);
  2112. console.log(`Heanup2 UnifiedPlayerService: 恢复当前歌曲: ${currentSong.name}`);
  2113. }
  2114. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Restored playlist with ${playlistData.songs.length} songs`);
  2115. // 立即更新播放列表状态,确保上一首/下一首状态正确
  2116. this.updatePlaylistStateInModelSync();
  2117. } else {
  2118. console.log("Heanup2 UnifiedPlayerService: 没有找到保存的播放列表或播放列表为空");
  2119. }
  2120. // 恢复播放状态
  2121. if (stateData) {
  2122. console.log(`Heanup2 UnifiedPlayerService: 加载到的播放状态 - playing: ${stateData.isPlaying}, paused: ${stateData.isPaused}, index: ${stateData.currentIndex}`);
  2123. // 批量更新状态,减少回调次数
  2124. this.stateModel.updateVolume(stateData.volume);
  2125. this.stateModel.updateSpeed(stateData.speed);
  2126. this.stateModel.updatePlayMode(stateData.playMode);
  2127. // 恢复播放状态(UI会使用实际播放器状态,所以这里可以恢复逻辑状态)
  2128. this.stateModel.updatePlayingState(stateData.isPlaying || false);
  2129. // 恢复当前播放索引
  2130. if (stateData.currentIndex >= 0) {
  2131. this.stateModel.updateCurrentIndex(stateData.currentIndex);
  2132. }
  2133. console.log("Heanup2 UnifiedPlayerService: 播放状态恢复完成");
  2134. LogUtils.getInstance()
  2135. .LOGI(`Heanup UnifiedPlayerService: Restored player state - playing: ${stateData.isPlaying}, paused: ${stateData.isPaused}, index: ${stateData.currentIndex}`);
  2136. } else {
  2137. console.log("Heanup2 UnifiedPlayerService: 没有找到保存的播放状态");
  2138. }
  2139. console.log("Heanup2 UnifiedPlayerService: 持久化状态快速恢复完成");
  2140. // 设置数据恢复完成标识
  2141. this.isDataRestored = true;
  2142. // 立即更新播放列表状态,确保上一首/下一首状态正确
  2143. this.updatePlaylistStateInModelSync();
  2144. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Data restoration completed');
  2145. } catch (error) {
  2146. console.log(`Heanup2 UnifiedPlayerService: 恢复持久化状态时出错: ${error}`);
  2147. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService restorePersistedState error: ${error}`);
  2148. // 即使出错也设置为已恢复,避免无限等待
  2149. this.isDataRestored = true;
  2150. }
  2151. }
  2152. /**
  2153. * 保存当前状态
  2154. */
  2155. private async saveCurrentState(): Promise<void> {
  2156. try {
  2157. // 获取当前状态
  2158. const currentState = this.stateModel.getState();
  2159. // 验证播放器实际状态,确保状态模型与实际播放器状态一致
  2160. try {
  2161. const ijkPlayer = this.playerManager.getIjkPlayer();
  2162. const actualPlaying = ijkPlayer ? ijkPlayer.isPlaying() : false;
  2163. // 如果状态不一致,以实际播放器状态为准
  2164. // 但在暂停操作期间跳过检测,避免误判
  2165. if (currentState.isPlaying !== actualPlaying && !this.isPausingInProgress) {
  2166. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: State mismatch detected during save - StateModel: ${currentState.isPlaying}, Actual: ${actualPlaying}`);
  2167. this.stateModel.updatePlayingState(actualPlaying);
  2168. // 重新获取修正后的状态
  2169. const correctedState = this.stateModel.getState();
  2170. this.dataPersistence.savePlayerState(correctedState);
  2171. } else {
  2172. if (this.isPausingInProgress && currentState.isPlaying !== actualPlaying) {
  2173. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Skipping state mismatch check during pause operation - StateModel: ${currentState.isPlaying}, Actual: ${actualPlaying}`);
  2174. }
  2175. this.dataPersistence.savePlayerState(currentState);
  2176. }
  2177. } catch (playerError) {
  2178. // 如果获取播放器状态失败,默认保存为停止状态
  2179. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to get actual player state, saving as stopped: ${playerError}`);
  2180. this.stateModel.updatePlayingState(false);
  2181. const stoppedState = this.stateModel.getState();
  2182. this.dataPersistence.savePlayerState(stoppedState);
  2183. }
  2184. // 修复:只在播放位置有意义时才保存,避免在歌曲刚开始时覆盖记忆播放位置
  2185. const ijkPlayer = this.playerManager.getIjkPlayer();
  2186. if (ijkPlayer && this.isPlayerPreparedForCurrentSong) {
  2187. const currentPosition = ijkPlayer.getCurrentPosition();
  2188. // 只有当播放位置大于2秒时才保存,避免覆盖记忆播放位置
  2189. if (currentPosition > 2000) {
  2190. const currentSong = this.playlistModel.getCurrentSong();
  2191. if (currentSong) {
  2192. this.savePlaybackPosition(currentSong);
  2193. }
  2194. } else {
  2195. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Skipping playback position save - position too small (${currentPosition}ms)`);
  2196. }
  2197. }
  2198. await this.syncPlaylistToStorage();
  2199. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Current state saved successfully`);
  2200. } catch (error) {
  2201. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService saveCurrentState error: ${error}`);
  2202. }
  2203. }
  2204. /**
  2205. * 外部调用保存当前状态的方法(供EntryAbility使用)
  2206. */
  2207. public async saveCurrentStateExternal(): Promise<void> {
  2208. await this.saveCurrentState();
  2209. }
  2210. /**
  2211. * 同步播放列表到存储
  2212. */
  2213. private async syncPlaylistToStorage(): Promise<void> {
  2214. try {
  2215. const playlist = this.playlistModel.getSongs();
  2216. const currentIndex = this.playlistModel.getCurrentIndex();
  2217. const playMode = this.stateModel.getState().playMode;
  2218. // 获取调用栈信息用于调试
  2219. const stack = new Error().stack;
  2220. const caller = stack?.split('\n')[2]?.trim() || 'Unknown caller';
  2221. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: syncPlaylistToStorage called - playlist length: ${playlist?.length || 0}, currentIndex: ${currentIndex}, playMode: ${playMode}, caller: ${caller}`);
  2222. // 总是尝试保存播放列表状态,包括空播放列表的情况
  2223. // 这样可以确保用户关闭应用时的真实状态被正确保存
  2224. await this.playlistSync.syncPlaylistToStorage(playlist || [], currentIndex, playMode);
  2225. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: syncPlaylistToStorage completed successfully`);
  2226. } catch (error) {
  2227. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService syncPlaylistToStorage error: ${error}`);
  2228. }
  2229. }
  2230. // ==================== PlaylistSyncListener 接口实现 ====================
  2231. /**
  2232. * 播放列表同步完成回调
  2233. */
  2234. onPlaylistSynced(playlist: VideoItem[], currentIndex: number, playMode: PlayMode): void {
  2235. }
  2236. /**
  2237. * 播放列表加载完成回调
  2238. */
  2239. onPlaylistLoaded(playlistData: PlaylistData): void {
  2240. try {
  2241. LogUtils.getInstance()
  2242. .LOGI(`Heanup UnifiedPlayerService: Playlist loaded from storage - ${playlistData.songs.length} songs`);
  2243. // 检查是否需要更新本地播放列表
  2244. const currentPlaylist = this.playlistModel.getSongs();
  2245. const currentIndex = this.playlistModel.getCurrentIndex();
  2246. // 如果存储的数据更新,更新本地播放列表
  2247. if (playlistData.songs.length !== currentPlaylist.length ||
  2248. playlistData.currentIndex !== currentIndex) {
  2249. this.playlistModel.replaceSongs(playlistData.songs, playlistData.currentIndex);
  2250. this.stateModel.updateCurrentIndex(playlistData.currentIndex);
  2251. this.stateModel.updatePlayMode(playlistData.playMode);
  2252. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Local playlist updated from storage');
  2253. }
  2254. // 更新数据恢复状态(如果还没有恢复的话)
  2255. if (!this.isDataRestored) {
  2256. this.isDataRestored = true;
  2257. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Data restoration completed via onPlaylistLoaded');
  2258. }
  2259. } catch (error) {
  2260. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onPlaylistLoaded error: ${error}`);
  2261. }
  2262. }
  2263. /**
  2264. * 自动同步执行回调
  2265. */
  2266. onAutoSyncPerformed(): void {
  2267. try {
  2268. // 定期保存当前状态(异步执行,不等待完成)
  2269. this.saveCurrentState().catch((error:Error) => {
  2270. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onAutoSyncPerformed saveCurrentState error: ${error}`);
  2271. });
  2272. } catch (error) {
  2273. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onAutoSyncPerformed error: ${error}`);
  2274. }
  2275. }
  2276. /**
  2277. * 同步错误回调
  2278. */
  2279. onSyncError(error: Error): void {
  2280. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService sync error: ${error.message}`);
  2281. }
  2282. // ==================== 公共数据访问方法 ====================
  2283. /**
  2284. * 获取数据持久化服务实例
  2285. */
  2286. getDataPersistenceService(): IDataPersistenceService {
  2287. return this.dataPersistence;
  2288. }
  2289. /**
  2290. * 获取播放列表同步服务实例
  2291. */
  2292. getPlaylistSyncService(): PlaylistSyncService {
  2293. return this.playlistSync;
  2294. }
  2295. // ==================== StateChangeCallback 接口实现 ====================
  2296. /**
  2297. * 歌曲变化回调(来自StateSyncService的本地通知)
  2298. */
  2299. onSongChanged?(song: VideoItem): void {
  2300. try {
  2301. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Received song change notification - ${song.name}`);
  2302. // 这里可以处理来自其他组件的歌曲变化通知
  2303. } catch (error) {
  2304. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onSongChanged error: ${error}`);
  2305. }
  2306. }
  2307. // ==================== WidgetControlCallback 接口实现 ====================
  2308. /**
  2309. * 处理来自卡片的播放/暂停命令
  2310. * @param params 包含卡片当前UI状态的对象
  2311. */
  2312. public async onPlayPause(params?: PlayPauseInterface): Promise<void> {
  2313. try {
  2314. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Received play/pause command from widget');
  2315. const widgetIsPlaying = params?.widgetIsPlaying;
  2316. if (widgetIsPlaying !== undefined) {
  2317. // 新逻辑:信任卡片传递的状态
  2318. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Using widget state - widgetIsPlaying=${widgetIsPlaying}`);
  2319. if (widgetIsPlaying) {
  2320. // 卡片显示的是暂停按钮(UI为播放状态),所以执行暂停
  2321. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Widget state is PLAYING, will pause.');
  2322. await this.pause();
  2323. } else {
  2324. // 卡片显示的是播放按钮(UI为暂停/停止状态),所以执行播放
  2325. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Widget state is PAUSED, will play.');
  2326. await this.startPlayOrResumePlay();
  2327. // 关键修复:播放开始后,确保播放器准备状态正确设置
  2328. const ijkPlayer = this.playerManager.getIjkPlayer();
  2329. if (ijkPlayer && ijkPlayer.isPlaying()) {
  2330. this.isPlayerPreparedForCurrentSong = true;
  2331. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Widget play success - set player prepared state to true');
  2332. }
  2333. }
  2334. } else {
  2335. // 向后兼容的旧逻辑:根据播放器实际状态切换
  2336. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: widgetIsPlaying not provided, using fallback logic.');
  2337. const isActuallyPlaying = this.getActualPlayingState();
  2338. if (isActuallyPlaying) {
  2339. await this.pause();
  2340. } else {
  2341. await this.startPlayOrResumePlay();
  2342. }
  2343. }
  2344. } catch (error) {
  2345. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onPlayPause error: ${error}`);
  2346. }
  2347. }
  2348. /**
  2349. * 处理来自卡片的下一首命令
  2350. */
  2351. async onNextSong?(): Promise<void> {
  2352. try {
  2353. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Received next song command from widget');
  2354. await this.playNext();
  2355. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Next song command executed successfully');
  2356. } catch (error) {
  2357. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onNextSong error: ${error}`);
  2358. throw new Error;
  2359. }
  2360. }
  2361. /**
  2362. * 处理来自卡片的上一首命令
  2363. */
  2364. async onPreviousSong?(): Promise<void> {
  2365. try {
  2366. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Received previous song command from widget');
  2367. await this.playPrevious();
  2368. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Previous song command executed successfully');
  2369. } catch (error) {
  2370. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onPreviousSong error: ${error}`);
  2371. throw new Error;
  2372. }
  2373. }
  2374. /**
  2375. * 处理来自卡片的拖动进度命令
  2376. */
  2377. async onSeekTo?(position: number): Promise<void> {
  2378. try {
  2379. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Received seek to command from widget - position: ${position}`);
  2380. await this.seekTo(position.toString());
  2381. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Seek to command executed successfully');
  2382. } catch (error) {
  2383. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onSeekTo error: ${error}`);
  2384. throw new Error;
  2385. }
  2386. }
  2387. /**
  2388. * 处理来自卡片的状态请求命令
  2389. */
  2390. async onStateRequest?(): Promise<void> {
  2391. try {
  2392. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Received state request from widget');
  2393. await this.broadcastCurrentState();
  2394. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: State request handled successfully');
  2395. } catch (error) {
  2396. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService onStateRequest error: ${error}`);
  2397. throw new Error;
  2398. }
  2399. }
  2400. /**
  2401. * 手动广播当前状态(用于响应卡片的状态请求)
  2402. */
  2403. async broadcastCurrentState(): Promise<void> {
  2404. try {
  2405. // 确保播放列表状态是最新的
  2406. this.updatePlaylistStateInModelSync();
  2407. // 触发状态监听器通知
  2408. this.stateModel.forceNotifyStateChanged();
  2409. // 更新桌面卡片
  2410. await this.updateAllForms(true); // 强制更新
  2411. } catch (error) {
  2412. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService broadcastCurrentState error: ${error}`);
  2413. throw new Error;
  2414. }
  2415. }
  2416. // ==================== 私有辅助方法 ====================
  2417. /**
  2418. * 设置音频中断监听器
  2419. */
  2420. private setupAudioInterruptListener(): void {
  2421. try {
  2422. const ijkPlayer = this.playerManager.getIjkPlayer();
  2423. if (ijkPlayer) {
  2424. ijkPlayer.on('audioInterrupt', (event: InterruptEvent) => {
  2425. this.handleAudioInterrupt(event);
  2426. });
  2427. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Audio interrupt listener set up successfully');
  2428. } else {
  2429. LogUtils.getInstance()
  2430. .LOGI('Heanup UnifiedPlayerService: Failed to set up audio interrupt listener - no player instance');
  2431. }
  2432. } catch (error) {
  2433. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error setting up audio interrupt listener: ${(error as Error).message}`);
  2434. }
  2435. }
  2436. /**
  2437. * 处理音频中断事件
  2438. */
  2439. async handleAudioInterrupt(event: InterruptEvent): Promise<void> {
  2440. try {
  2441. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  2442. // 首先保存当前播放位置
  2443. const currentSong = this.playlistModel.getCurrentSong();
  2444. if (currentSong) {
  2445. this.savePlaybackPosition(currentSong);
  2446. }
  2447. switch (event.hintType) {
  2448. case InterruptHintType.INTERRUPT_HINT_PAUSE:
  2449. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Audio interrupt - pausing playback');
  2450. await this.pause();
  2451. break;
  2452. case InterruptHintType.INTERRUPT_HINT_RESUME:
  2453. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Audio interrupt - resuming playback');
  2454. await this.startPlayOrResumePlay();
  2455. break;
  2456. case InterruptHintType.INTERRUPT_HINT_STOP:
  2457. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Audio interrupt - stopping playback');
  2458. await this.stop();
  2459. break;
  2460. case InterruptHintType.INTERRUPT_HINT_DUCK:
  2461. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Audio interrupt - ducking (lowering volume)');
  2462. // 可以实现音量降低逻辑
  2463. break;
  2464. case InterruptHintType.INTERRUPT_HINT_UNDUCK:
  2465. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Audio interrupt - unducking (restoring volume)');
  2466. // 可以实现音量恢复逻辑
  2467. break;
  2468. default:
  2469. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Unknown audio interrupt hint type: ${event.hintType}`);
  2470. break;
  2471. }
  2472. // 通知状态变化
  2473. await this.updatePlaylistStateInModel();
  2474. await this.broadcastCurrentState();
  2475. } catch (error) {
  2476. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error handling audio interrupt: ${(error as Error).message}`);
  2477. await this.handlePlaybackError(error as Error, PlayerErrorType.AUDIO_INTERRUPT_ERROR);
  2478. }
  2479. }
  2480. /**
  2481. * 更新状态模型中的播放列表状态
  2482. */
  2483. private async updatePlaylistStateInModel(): Promise<void> {
  2484. try {
  2485. const currentIndex = this.playlistModel.getCurrentIndex();
  2486. const totalCount = this.playlistModel.getTotalCount();
  2487. const playMode = this.stateModel.getState().playMode;
  2488. // 在随机播放模式下,确保当前歌曲在播放历史中
  2489. if (playMode === PlayMode.RANDOM) {
  2490. await this.playlistModel.ensureCurrentSongInHistory();
  2491. // 输出播放历史调试信息
  2492. const debugInfo = this.playlistModel.getPlayHistoryDebugInfo();
  2493. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Random mode play history - ${debugInfo}`);
  2494. }
  2495. const hasNext = this.playlistModel.hasNext(playMode);
  2496. const hasPrevious = await this.playlistModel.hasPrevious(playMode);
  2497. this.stateModel.updatePlaylistState(hasNext, hasPrevious, totalCount);
  2498. LogUtils.getInstance()
  2499. .LOGI(`Heanup UnifiedPlayerService: Playlist state updated - hasNext=${hasNext}, hasPrevious=${hasPrevious}, totalCount=${totalCount}, playMode=${playMode}`);
  2500. } catch (error) {
  2501. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService updatePlaylistStateInModel error: ${error}`);
  2502. }
  2503. }
  2504. /**
  2505. * 更新状态模型中的播放列表状态(同步版本)- 优化防抖
  2506. */
  2507. private updatePlaylistStateInModelSync(): void {
  2508. try {
  2509. const currentIndex = this.playlistModel.getCurrentIndex();
  2510. const totalCount = this.playlistModel.getTotalCount();
  2511. const playMode = this.stateModel.getState().playMode;
  2512. const hasNext = this.playlistModel.hasNext(playMode);
  2513. const hasPrevious = this.playlistModel.hasPreviousSync(playMode);
  2514. // 检查状态是否真的发生了变化,避免频繁的无效更新
  2515. const currentState = this.stateModel.getState();
  2516. const stateChanged = (
  2517. currentState.hasNext !== hasNext ||
  2518. currentState.hasPrevious !== hasPrevious ||
  2519. currentState.totalCount !== totalCount
  2520. );
  2521. if (stateChanged) {
  2522. this.stateModel.updatePlaylistState(hasNext, hasPrevious, totalCount);
  2523. LogUtils.getInstance()
  2524. .LOGI(`Heanup UnifiedPlayerService: Playlist state updated sync - hasNext=${hasNext}, hasPrevious=${hasPrevious}, totalCount=${totalCount}, playMode=${playMode}`);
  2525. }
  2526. } catch (error) {
  2527. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService updatePlaylistStateInModelSync error: ${error}`);
  2528. }
  2529. }
  2530. // ==================== PlayerStateCallback 实现 ====================
  2531. onPrepared(): void {
  2532. // 标记播放器已为当前歌曲准备就绪
  2533. this.isPlayerPreparedForCurrentSong = true;
  2534. console.log("Heanup2 UnifiedPlayerService: onPrepared - 播放器已为当前歌曲准备就绪");
  2535. setTimeout(() => {
  2536. // 执行跳过片头和记忆播放恢复逻辑
  2537. this.checkAndHandleOnPreparedLogic();
  2538. this.stateModel.updateLoadingState(false);
  2539. const ijkPlayer = this.playerManager.getIjkPlayer();
  2540. const isActuallyPlaying = ijkPlayer ? ijkPlayer.isPlaying() : false;
  2541. console.log(`Heanup2 UnifiedPlayerService: onPrepared - 实际播放状态: ${isActuallyPlaying}`);
  2542. // 强制同步状态模型
  2543. this.stateModel.updatePlayingState(isActuallyPlaying);
  2544. // 确保播放列表状态是最新的
  2545. this.updatePlaylistStateInModelSync();
  2546. // 更新 AVSession 状态
  2547. if (isActuallyPlaying) {
  2548. // 优化:确保使用最新的歌曲数据
  2549. let currentSong = this.playlistModel.getCurrentSong();
  2550. if (currentSong) {
  2551. console.log(`Heanup2 UnifiedPlayerService: onPrepared - updateAvSessionMetadata: ${json.stringify(currentSong)}`);
  2552. // 立即更新,避免延迟导致的状态不一致
  2553. this.updateAvSessionMetadata(currentSong);
  2554. }
  2555. this.updateSessionPlayState(true); // 强制更新,不使用防抖
  2556. }
  2557. // 延迟更新卡片,确保状态已同步
  2558. setTimeout(() => {
  2559. this.updateWidgetsForStateChange();
  2560. }, 50);
  2561. }, 100);
  2562. // 播放器准备完成时立即更新卡片(移除加载状态)
  2563. this.updateWidgetsForStateChange();
  2564. }
  2565. /**
  2566. * 播放器准备完成后的特殊逻辑处理
  2567. * 包括跳过片头和记忆播放恢复
  2568. */
  2569. private checkAndHandleOnPreparedLogic(): void {
  2570. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: 跳过片头和记忆播放恢复 Checking onPrepared logic');
  2571. try {
  2572. const currentSong = this.playlistModel.getCurrentSong();
  2573. if (!currentSong) {
  2574. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: No current song, skipping onPrepared logic');
  2575. return;
  2576. }
  2577. const videoUrl = currentSong.filePath;
  2578. const duration = this.playerManager.getIjkPlayer()?.getDuration() || 0;
  2579. // 检查跳过片头功能
  2580. const jumpSettings = this.loadJumpSettings(currentSong);
  2581. if (jumpSettings.isEnabled && jumpSettings.jumpTopTime > 0) {
  2582. console.log(`Heanup UnifiedPlayerService: Jump settings enabled: ${jumpSettings.jumpTopTime}s`)
  2583. if (jumpSettings.jumpTopTime * 1000 <= duration) {
  2584. // 需要跳过片头
  2585. if (videoUrl && !videoUrl.toLowerCase().endsWith('.ts')) {
  2586. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Jumping to intro end: ${jumpSettings.jumpTopTime}s`);
  2587. this.seekTo((jumpSettings.jumpTopTime * 1000).toString());
  2588. }
  2589. } else {
  2590. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Jump time exceeds video duration');
  2591. }
  2592. } else {
  2593. // 没有跳过片头,检查记忆播放
  2594. this.handleMemoryPlayback(currentSong, videoUrl);
  2595. }
  2596. } catch (error) {
  2597. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error in checkAndHandleOnPreparedLogic: ${error}`);
  2598. }
  2599. }
  2600. /**
  2601. * 加载跳过头尾设置
  2602. */
  2603. private loadJumpSettings(currentSong: VideoItem): JumpSettings {
  2604. try {
  2605. // 这里应该根据播放模式来获取设置,但因为我们在 UnifiedPlayerService 中,
  2606. // 暂时从当前歌曲的文件路径获取文件夹设置
  2607. const parentPath = this.getParentPath(currentSong.filePath);
  2608. const jumpTopTime: number = PuraPreferencesUtil.getNumberSync(parentPath + 'jumpTopTime', 0);
  2609. const jumpEndTime: number = PuraPreferencesUtil.getNumberSync(parentPath + 'jumpEndTime', 0);
  2610. const isEnabled: boolean = PuraPreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false);
  2611. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Loaded jump settings - enabled: ${isEnabled}, top: ${jumpTopTime}s, end: ${jumpEndTime}s`);
  2612. const settings: JumpSettings = { isEnabled, jumpTopTime, jumpEndTime };
  2613. return settings;
  2614. } catch (error) {
  2615. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error loading jump settings: ${error}`);
  2616. const defaultSettings: JumpSettings = { isEnabled: false, jumpTopTime: 0, jumpEndTime: 0 };
  2617. return defaultSettings;
  2618. }
  2619. }
  2620. /**
  2621. * 处理记忆播放
  2622. */
  2623. private handleMemoryPlayback(currentSong: VideoItem, videoUrl: string): void {
  2624. try {
  2625. console.log(`Heanup 记忆播放功能: 处理记忆播放 for ${currentSong.name}`)
  2626. // 检查用户是否启用了记忆播放功能
  2627. const isMusicMemoryPlay: boolean = PuraPreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false);
  2628. const isMemoryLastPlay: boolean = PuraPreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false);
  2629. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能: Settings - isMusicMemoryPlay: ${isMusicMemoryPlay}, isMemoryLastPlay: ${isMemoryLastPlay}`);
  2630. // 只在首次启动时检查 isMemoryLastPlay
  2631. if (!isMusicMemoryPlay && !isMemoryLastPlay) {
  2632. LogUtils.getInstance().LOGI('Heanup 记忆播放功能 : Memory play disabled, skipping restore');
  2633. return;
  2634. }
  2635. if (currentSong && currentSong.filePath && !currentSong.filePath.toLowerCase().endsWith('.ts')) {
  2636. // 使用 currentSong.filePath 作为键,确保与保存时一致
  2637. let position = PuraPreferencesUtil.getNumberSync(currentSong.filePath, 0);
  2638. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能: Retrieved position ${position}ms from key: ${currentSong.filePath}`);
  2639. if (position > 0) {
  2640. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能 : Restoring playback position: ${position}ms for ${currentSong.name}`);
  2641. this.seekTo(position.toString());
  2642. } else {
  2643. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能 : No saved position found for ${currentSong.name} (key: ${currentSong.filePath})`);
  2644. }
  2645. } else {
  2646. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能: Skipping restore - invalid song or .ts file: ${currentSong?.filePath}`);
  2647. }
  2648. } catch (error) {
  2649. LogUtils.getInstance().LOGI(`Heanup 记忆播放功能 : Error in handleMemoryPlayback: ${error}`);
  2650. }
  2651. }
  2652. /**
  2653. * 获取文件的父目录路径
  2654. */
  2655. private getParentPath(filePath: string): string {
  2656. try {
  2657. const lastSlashIndex = filePath.lastIndexOf('/');
  2658. if (lastSlashIndex > 0) {
  2659. return filePath.substring(0, lastSlashIndex + 1);
  2660. }
  2661. return filePath;
  2662. } catch (error) {
  2663. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Error getting parent path: ${error}`);
  2664. return filePath;
  2665. }
  2666. }
  2667. onPlaybackStarted(): void {
  2668. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Playback started (new song)');
  2669. // 这个回调只应该在新歌曲开始播放时被调用(通过onPrepared触发)
  2670. // 不应该在暂停恢复时被调用
  2671. // 在随机播放模式下,确保当前歌曲在播放历史中
  2672. const playMode = this.stateModel.getState().playMode;
  2673. if (playMode === PlayMode.RANDOM) {
  2674. this.playlistModel.ensureCurrentSongInHistory();
  2675. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Ensured current song in play history for random mode');
  2676. }
  2677. // 立即更新播放状态
  2678. this.stateModel.updatePlayingState(true);
  2679. // 启动进度定时器
  2680. this.startProgressTimer();
  2681. // 保存播放状态变化
  2682. this.saveCurrentState();
  2683. // 立即更新系统播控状态,确保与播放状态同步
  2684. this.updateSessionPlayState(true); // 强制更新,不使用防抖
  2685. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession state updated for new song playback');
  2686. // 播放开始时更新卡片显示播放状态
  2687. this.updateWidgetsForPlayStateChange();
  2688. // 同步更新所有桌面卡片状态
  2689. this.updateAllForms();
  2690. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: New song playback started successfully');
  2691. }
  2692. onPlaybackCompleted(): void {
  2693. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Playback completed');
  2694. // **关键修复:在手动切换歌曲时,不要保存播放位置,因为已经在 changeTrack 中保存了**
  2695. if (!this.isManualSongChange) {
  2696. // 只有在非手动切换时才保存当前歌曲的播放位置(如自然播放完成)
  2697. const completedSong = this.playlistModel.getCurrentSong();
  2698. if (completedSong) {
  2699. this.savePlaybackPosition(completedSong);
  2700. }
  2701. } else {
  2702. LogUtils.getInstance().LOGI('Heanup 记忆播放功能: Skipping save in onPlaybackCompleted due to manual song change');
  2703. }
  2704. this.stateModel.updatePlayingState(false);
  2705. this.stopProgressTimer();
  2706. // 保存播放状态变化
  2707. this.saveCurrentState();
  2708. this.updateSessionPlayState();
  2709. // 更新卡片显示播放完成状态
  2710. this.updateWidgetsForPlayStateChange();
  2711. // 同步更新所有桌面卡片状态
  2712. this.updateAllForms();
  2713. // 异步处理自动播放逻辑,避免阻塞主线程
  2714. setTimeout(() => {
  2715. this.handleAutoPlayOnCompletion().catch(() => {
  2716. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Auto-play error`);
  2717. });
  2718. }, 100); // 延迟100ms执行,确保当前回调完成
  2719. }
  2720. /**
  2721. * 处理歌曲播放完成后的自动播放逻辑
  2722. */
  2723. private async handleAutoPlayOnCompletion(): Promise<void> {
  2724. try {
  2725. // 检查是否正在进行手动歌曲切换,如果是则跳过自动播放
  2726. if (this.isManualSongChange) {
  2727. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Manual song change in progress, skipping auto-play');
  2728. return;
  2729. }
  2730. // 防抖检查:避免快速连续的自动播放调用
  2731. const currentTime = Date.now();
  2732. if (currentTime - this.lastAutoPlayTime < this.autoPlayDebounceMs) {
  2733. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Auto-play debounced, skipping');
  2734. return;
  2735. }
  2736. this.lastAutoPlayTime = currentTime;
  2737. // 检查服务状态,避免在服务未就绪时执行自动播放
  2738. if (!this.isAllServicesReady()) {
  2739. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Services not ready for auto-play, skipping');
  2740. return;
  2741. }
  2742. const currentState = this.stateModel.getState();
  2743. const playMode = currentState.playMode;
  2744. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Handling auto-play, mode: ${playMode}`);
  2745. switch (playMode) {
  2746. case PlayMode.SEQUENCE: // 0: 顺序播放/列表循环
  2747. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Auto-playing next song in sequence mode');
  2748. // 检查是否有下一首歌曲
  2749. if (this.playlistModel.hasNext(playMode)) {
  2750. await this.playNext();
  2751. } else {
  2752. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: No next song available in sequence mode');
  2753. }
  2754. break;
  2755. case PlayMode.SINGLE_REPEAT: // 1: 单曲循环
  2756. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Repeating current song');
  2757. // 重新播放当前歌曲
  2758. await this.startPlayOrResumePlay();
  2759. break;
  2760. case PlayMode.NORMAL: // 2: 正常播放,播完停止
  2761. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Normal mode - stopping after completion');
  2762. // 不做任何操作,保持停止状态
  2763. break;
  2764. case PlayMode.RANDOM: // 3: 随机播放
  2765. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Auto-playing random next song');
  2766. await this.playRandomNext();
  2767. break;
  2768. default:
  2769. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Unknown play mode: ${playMode}`);
  2770. break;
  2771. }
  2772. } catch (error) {
  2773. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error in auto-play handling: ${error}`);
  2774. // 在自动播放失败时,简单记录错误但不触发复杂的错误处理流程
  2775. // 这样可以避免错误处理过程中的潜在阻塞
  2776. this.stateModel.updatePlayingState(false);
  2777. this.stateModel.updateLoadingState(false);
  2778. }
  2779. }
  2780. /**
  2781. * 随机播放下一首歌曲
  2782. */
  2783. private async playRandomNext(): Promise<void> {
  2784. try {
  2785. const playlist = this.playlistModel.getSongs();
  2786. if (playlist.length <= 1) {
  2787. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Not enough songs for random play');
  2788. return;
  2789. }
  2790. const currentIndex = this.playlistModel.getCurrentIndex();
  2791. let randomIndex: number;
  2792. // 确保随机选择的不是当前歌曲
  2793. do {
  2794. randomIndex = Math.floor(Math.random() * playlist.length);
  2795. } while (randomIndex === currentIndex);
  2796. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Playing random song at index ${randomIndex}`);
  2797. await this.playSongAtIndex(randomIndex);
  2798. } catch (error) {
  2799. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error in random play: ${error}`);
  2800. // 不再抛出异常,而是通过错误处理机制处理
  2801. await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
  2802. }
  2803. }
  2804. onPlaybackError(what: number, extra: number): void {
  2805. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Playback error - what: ${what}, extra: ${extra}`);
  2806. this.stateModel.updateLoadingState(false);
  2807. this.stateModel.updatePlayingState(false);
  2808. this.stopProgressTimer();
  2809. // 保存播放状态变化
  2810. this.saveCurrentState();
  2811. // 创建播放器错误对象
  2812. const playbackError = new PlayerError(
  2813. PlayerErrorType.PLAYBACK_ERROR,
  2814. `Playback error: what=${what}, extra=${extra}`,
  2815. what
  2816. );
  2817. playbackError.recoverable = what !== -1004 && what !== -1007; // 某些错误码可恢复
  2818. playbackError.retryCount = 0;
  2819. // 创建错误上下文
  2820. const errorContext: ErrorContext = {
  2821. currentSong: this.getCurrentSong(),
  2822. playlist: this.getPlaylist(),
  2823. currentIndex: this.getCurrentIndex(),
  2824. retryCount: 0,
  2825. isNetworkAvailable: true // 这里可以实际检查网络状态
  2826. };
  2827. // 使用错误恢复策略处理错误
  2828. this.errorRecovery.handleError(playbackError, errorContext).then((action: ErrorRecoveryAction) => {
  2829. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error recovery action: ${action}`);
  2830. // 这里可以根据 action 执行相应的恢复操作
  2831. }).catch((recoveryError: Error) => {
  2832. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error recovery failed: ${recoveryError}`);
  2833. });
  2834. }
  2835. // ========== 卡片更新相关方法 ==========
  2836. /**
  2837. * 播放状态变化时更新卡片
  2838. */
  2839. private async updateWidgetsForPlayStateChange(): Promise<void> {
  2840. try {
  2841. this.updateAllForms();
  2842. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Widgets updated for play state change`);
  2843. } catch (error) {
  2844. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to update widgets for play state change: ${error}`);
  2845. }
  2846. }
  2847. /**
  2848. * 更新所有桌面卡片状态(优化为UI优先响应)
  2849. * 将VideoItem和PlayerState数据传入桌面卡片,控制卡片的显示
  2850. */
  2851. async updateAllForms(forceUpdate: boolean = false) {
  2852. // 优化防抖逻辑:缩短防抖时间,提高响应速度
  2853. const now = Date.now();
  2854. const debounceTime = forceUpdate ? 0 : 100; // 强制更新无防抖,普通更新减少到100ms
  2855. if (!forceUpdate && this.lastFormUpdateTime && (now - this.lastFormUpdateTime < debounceTime)) {
  2856. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService updateAllForms: Skipping due to debounce protection (${debounceTime}ms)`);
  2857. return;
  2858. }
  2859. // 防抖和重入保护,防止短时间内重复执行更新
  2860. if (this.isUpdatingForms && !forceUpdate) {
  2861. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService updateAllForms: Update already in progress, skipping.');
  2862. return;
  2863. }
  2864. this.lastFormUpdateTime = now;
  2865. try {
  2866. this.isUpdatingForms = true;
  2867. const context = this.getContext();
  2868. if (!context) {
  2869. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService updateAllForms: No context available');
  2870. return;
  2871. }
  2872. // 优化:异步获取Form列表,不阻塞UI更新
  2873. const formInfoListPromise = this.getFormInfoListAsync(context);
  2874. // 优化:立即获取卡片数据,优先响应UI
  2875. const widgetData = await this.getWidgetFormData();
  2876. if (!widgetData) {
  2877. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService updateAllForms: Failed to get widget data.');
  2878. return;
  2879. }
  2880. const bindingData = formBindingData.createFormBindingData(widgetData);
  2881. // 等待Form列表获取完成
  2882. const formInfoList = await formInfoListPromise;
  2883. if (formInfoList.length === 0) {
  2884. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService updateAllForms: No forms found');
  2885. return;
  2886. }
  2887. // 优化:并行更新所有卡片,使用批量更新提高效率
  2888. const updatePromises = formInfoList.map(formInfo => {
  2889. // 每个卡片更新都是异步的,避免阻塞
  2890. return formProvider.updateForm(formInfo.formId, bindingData).catch((error: Error) => {
  2891. LogUtils.getInstance().LOGI(`Failed to update form ${formInfo.formId}: ${error.message}`);
  2892. });
  2893. });
  2894. await Promise.all(updatePromises);
  2895. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: All forms updated for ${formInfoList.length} forms.`);
  2896. // 异步保存数据到数据库,不阻塞UI
  2897. setTimeout(() => {
  2898. const currentSong = this.getCurrentSong();
  2899. if (currentSong) {
  2900. this.saveWidgetDataToDatabase(widgetData, currentSong);
  2901. }
  2902. }, 0);
  2903. } catch (error) {
  2904. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService updateAllForms error: ${error}`);
  2905. } finally {
  2906. this.isUpdatingForms = false;
  2907. }
  2908. }
  2909. /**
  2910. * 异步获取FormInfo列表(优化方法)
  2911. */
  2912. private async getFormInfoListAsync(context: Context): Promise<FormInfo[]> {
  2913. try {
  2914. if (WIDGET_DATA_STORAGE_TYPE === WidgetDataStorageType.DATABASE) {
  2915. return await FormRdbHelper.getInstance(context).queryAllForms();
  2916. } else {
  2917. return await this.getFormInfoListFromPreferences(context);
  2918. }
  2919. } catch (error) {
  2920. LogUtils.getInstance().LOGI(`Failed to get form info list: ${error}`);
  2921. return [];
  2922. }
  2923. }
  2924. public async getWidgetFormData(loadImage: boolean = true): Promise<widgeData | undefined> {
  2925. this.updatePlaylistStateInModelSync();
  2926. const formData: VideoItem = this.getCurrentSong()!; // VideoItem
  2927. const songState: PlayerState = this.getCurrentState(); // PlayerState
  2928. let imgMap: Record<string, number> = {};
  2929. // 从持久化存储获取所有formId - 使用新的getContext方法
  2930. let context = this.getContext();
  2931. // 如果还是没有context,尝试从AppStorage获取
  2932. if (!context) {
  2933. context = AppStorage.get('context') as common.UIAbilityContext;
  2934. }
  2935. // 1. 准备动态数据 (这部分总是实时的)
  2936. // 构建卡片数据,包含VideoItem和PlayerState信息
  2937. const widgetPlayerState: WidgetPlayerState = {
  2938. isPlaying: songState.isPlaying || false,
  2939. isPaused: songState.isPaused || true,
  2940. isLoading: songState.isLoading || false,
  2941. currentPosition: songState.currentPosition || 0,
  2942. duration: songState.duration || 0,
  2943. hasNext: songState.hasNext || false,
  2944. hasPrevious: songState.hasPrevious || false,
  2945. playMode: songState.playMode || 0
  2946. };
  2947. const widgetPlaylistInfo: WidgetPlaylistInfo = {
  2948. currentIndex: this.getCurrentIndex(),
  2949. totalCount: this.getPlaylist().length
  2950. };
  2951. const widgetTimeInfo: WidgetTimeInfo = {
  2952. currentTimeText: this.formatTimeDisplay(Math.floor((songState.currentPosition || 0) / 1000)),
  2953. totalTimeText: this.formatTimeDisplay(Math.floor((songState.duration || 0) / 1000)),
  2954. progressPercentage: this.calculateProgressPercentage(songState.currentPosition || 0, songState.duration || 0)
  2955. };
  2956. if (!formData) {
  2957. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService getWidgetFormData: No current song, returning default data.');
  2958. const defaultData: widgeData = {
  2959. id: '',
  2960. name: '未知歌曲',
  2961. artist: '未知艺术家',
  2962. album: '未知专辑',
  2963. pixelMapPath: '',
  2964. duration: 0,
  2965. filePath: '',
  2966. imgName: '',
  2967. imageColorHex: '2A2A2A',
  2968. isPlaying: false,
  2969. isPaused: true,
  2970. isLoading: false,
  2971. hasNext: false,
  2972. hasPrevious: false,
  2973. isFavorite: false,
  2974. currentPosition: 0,
  2975. playMode: 0,
  2976. currentIndex: 0,
  2977. totalCount: 0,
  2978. currentTimeText: '',
  2979. totalTimeText: '',
  2980. progressPercentage: 0,
  2981. playerState: widgetPlayerState,
  2982. playlistInfo: widgetPlaylistInfo,
  2983. timeInfo: widgetTimeInfo,
  2984. formImages: imgMap
  2985. }
  2986. return defaultData;
  2987. }
  2988. // 2. 处理静态数据(利用缓存)
  2989. // 如果歌曲已切换,则清空缓存
  2990. if (this.widgetDataCache?.filePath !== formData.filePath) {
  2991. this.widgetDataCache = null;
  2992. }
  2993. if (!this.widgetDataCache) {
  2994. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Cache miss for [${formData.name}], generating static data.`);
  2995. // 缓存未命中,生成并缓存静态数据
  2996. let finalImagePath: string | null = null;
  2997. if (loadImage && formData.pixelMapPath && formData.pixelMapPath.trim() !== '') {
  2998. if (formData.pixelMapPath.startsWith('http')) {
  2999. // 网络图片,走缓存/下载逻辑
  3000. if (this.imageCacheDir) {
  3001. const cacheFileName = this.generateCacheFileName(formData.pixelMapPath);
  3002. const cacheFilePath = `${this.imageCacheDir}/${cacheFileName}`;
  3003. if (await this.isCacheValid(cacheFilePath)) {
  3004. finalImagePath = cacheFilePath;
  3005. } else {
  3006. const downloadSuccess = await this.downloadImageToCache(formData.pixelMapPath, cacheFilePath);
  3007. if (downloadSuccess) {
  3008. finalImagePath = cacheFilePath;
  3009. }
  3010. }
  3011. }
  3012. } else {
  3013. // 本地图片
  3014. finalImagePath = formData.pixelMapPath;
  3015. }
  3016. }
  3017. this.widgetDataCache = {
  3018. id: formData.id || '',
  3019. name: formData.name || '',
  3020. artist: formData.artist || '',
  3021. album: formData.album || '',
  3022. pixelMapPath: formData.pixelMapPath || '',
  3023. duration: typeof formData.duration === 'string' ? parseInt(formData.duration || '0') : (formData.duration || 0),
  3024. filePath: formData.filePath || '',
  3025. imageColorHex: '2A2A2A', // 默认颜色,UI侧会根据图片重新提取
  3026. finalImagePath: finalImagePath
  3027. };
  3028. } else {
  3029. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Cache hit for [${formData.name}].`);
  3030. }
  3031. // 3. 组合静态和动态数据,并处理图片文件描述符
  3032. const cachedData = this.widgetDataCache;
  3033. let imgName: string = '';
  3034. if (cachedData.finalImagePath) {
  3035. try {
  3036. // 优化:复用已缓存的图片文件描述符,避免重复文件操作
  3037. const currentSongPath = cachedData.finalImagePath;
  3038. const cacheKey = `img_${currentSongPath.replace(/[^a-zA-Z0-9]/g, '_')}`;
  3039. // 检查是否有缓存的图片名称,避免重复生成
  3040. if (this.lastImageCache && this.lastImageCache.path === currentSongPath && this.lastImageCache.imgName) {
  3041. imgName = this.lastImageCache.imgName;
  3042. const file = fileIo.openSync(currentSongPath, fileIo.OpenMode.READ_ONLY);
  3043. imgMap[imgName] = file.fd;
  3044. } else {
  3045. // 仅在图片真正改变时才重新打开文件
  3046. const file = fileIo.openSync(currentSongPath, fileIo.OpenMode.READ_ONLY);
  3047. imgName = `songCover_${cacheKey}`;
  3048. imgMap[imgName] = file.fd;
  3049. // 缓存当前图片信息
  3050. this.lastImageCache = {
  3051. path: currentSongPath,
  3052. imgName: imgName
  3053. } as ImageCacheInfo;
  3054. }
  3055. } catch (error) {
  3056. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to open image file [${cachedData.finalImagePath}]: ${JSON.stringify(error)}`);
  3057. imgMap = {};
  3058. imgName = '';
  3059. }
  3060. }
  3061. // 4. 构建最终的完整数据对象
  3062. const widgetData: widgeData = {
  3063. // 从缓存读取静态数据
  3064. id: cachedData.id,
  3065. name: cachedData.name,
  3066. artist: cachedData.artist,
  3067. album: cachedData.album,
  3068. pixelMapPath: cachedData.pixelMapPath,
  3069. duration: cachedData.duration,
  3070. filePath: cachedData.filePath,
  3071. imgName: imgName,
  3072. imageColorHex: cachedData.imageColorHex,
  3073. // PlayerState数据平铺 (实时)
  3074. isPlaying: widgetPlayerState.isPlaying,
  3075. isPaused: widgetPlayerState.isPaused,
  3076. isLoading: widgetPlayerState.isLoading,
  3077. currentPosition: widgetPlayerState.currentPosition,
  3078. hasNext: widgetPlayerState.hasNext,
  3079. hasPrevious: widgetPlayerState.hasPrevious,
  3080. playMode: widgetPlayerState.playMode,
  3081. // 播放列表信息平铺 (实时)
  3082. currentIndex: widgetPlaylistInfo.currentIndex,
  3083. totalCount: widgetPlaylistInfo.totalCount,
  3084. // 时间信息平铺 (实时)
  3085. currentTimeText: widgetTimeInfo.currentTimeText,
  3086. totalTimeText: widgetTimeInfo.totalTimeText,
  3087. progressPercentage: widgetTimeInfo.progressPercentage,
  3088. isFavorite: this.getCurrentSongFavoriteState(), // 收藏状态 (实时)
  3089. // 保持嵌套结构兼容性
  3090. playerState: widgetPlayerState,
  3091. playlistInfo: widgetPlaylistInfo,
  3092. timeInfo: widgetTimeInfo,
  3093. // 卡片图片显示必填字段
  3094. formImages: imgMap,
  3095. };
  3096. // 将widgetData存入数据库
  3097. this.saveWidgetDataToDatabase(widgetData, formData);
  3098. return widgetData;
  3099. }
  3100. /**
  3101. * 计算播放进度百分比
  3102. */
  3103. private calculateProgressPercentage(current: number, total: number): number {
  3104. if (total <= 0) {
  3105. return 0;
  3106. }
  3107. return Math.min(100, Math.max(0, (current / total) * 100));
  3108. }
  3109. /**
  3110. * 格式化时间显示
  3111. */
  3112. private formatTimeDisplay(seconds: number): string {
  3113. const mins = Math.floor(seconds / 60);
  3114. const secs = Math.floor(seconds % 60);
  3115. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  3116. }
  3117. /**
  3118. * 将widgetData存入存储中
  3119. * 根据配置选择数据库或Preferences存储
  3120. */
  3121. private async saveWidgetDataToDatabase(widgetData: widgeData, formData: VideoItem): Promise<void> {
  3122. try {
  3123. // 从getContext方法获取context
  3124. let context = this.getContext();
  3125. // 如果还是没有context,尝试从AppStorage获取
  3126. if (!context) {
  3127. context = AppStorage.get('context') as common.UIAbilityContext;
  3128. }
  3129. if (!context) {
  3130. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService saveWidgetDataToDatabase: No context available');
  3131. return;
  3132. }
  3133. if (!formData || !formData.id) {
  3134. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService saveWidgetDataToDatabase: No valid current song');
  3135. return;
  3136. }
  3137. const widgetDataInfo = new WidgetDataInfo();
  3138. // 基本信息
  3139. widgetDataInfo.songId = formData.id;
  3140. widgetDataInfo.name = formData.name || '';
  3141. widgetDataInfo.artist = formData.artist || '';
  3142. widgetDataInfo.album = formData.album || '';
  3143. widgetDataInfo.pixelMapPath = formData.pixelMapPath || '';
  3144. widgetDataInfo.duration = typeof formData.duration === 'string' ? parseInt(formData.duration || '0') : (formData.duration || 0);
  3145. widgetDataInfo.filePath = formData.filePath || '';
  3146. widgetDataInfo.imgName = widgetData.imgName || '';
  3147. widgetDataInfo.imageColorHex = widgetData.imageColorHex || '2A2A2A';
  3148. widgetDataInfo.isFavorite = widgetData.isFavorite || false;
  3149. // 播放状态信息
  3150. widgetDataInfo.isPlaying = widgetData.isPlaying;
  3151. widgetDataInfo.isPaused = widgetData.isPaused;
  3152. widgetDataInfo.isLoading = widgetData.isLoading;
  3153. widgetDataInfo.currentPosition = widgetData.currentPosition;
  3154. widgetDataInfo.hasNext = widgetData.hasNext;
  3155. widgetDataInfo.hasPrevious = widgetData.hasPrevious;
  3156. widgetDataInfo.playMode = widgetData.playMode;
  3157. // 播放列表信息
  3158. widgetDataInfo.currentIndex = widgetData.currentIndex;
  3159. widgetDataInfo.totalCount = widgetData.totalCount;
  3160. // 时间信息
  3161. widgetDataInfo.currentTimeText = widgetData.currentTimeText;
  3162. widgetDataInfo.totalTimeText = widgetData.totalTimeText;
  3163. widgetDataInfo.progressPercentage = widgetData.progressPercentage;
  3164. // 根据配置选择存储方式
  3165. if (WIDGET_DATA_STORAGE_TYPE === WidgetDataStorageType.DATABASE) {
  3166. await WidgetDataRdbHelper.getInstance(context).insertOrUpdateWidgetData(widgetDataInfo);
  3167. LogUtils.getInstance().LOGI(`UnifiedPlayerService saveWidgetDataToDatabase: Widget data saved to database for song: ${formData.name}`);
  3168. } else {
  3169. await this.saveWidgetDataToPreferences(widgetDataInfo, context);
  3170. LogUtils.getInstance().LOGI(`UnifiedPlayerService saveWidgetDataToDatabase: Widget data saved to preferences for song: ${formData.name}`);
  3171. }
  3172. } catch (error) {
  3173. LogUtils.getInstance().LOGI(`UnifiedPlayerService saveWidgetDataToDatabase: Failed to save widget data to storage: ${error}`);
  3174. }
  3175. }
  3176. /**
  3177. * 将widgetData保存到Preferences
  3178. */
  3179. private async saveWidgetDataToPreferences(widgetDataInfo: WidgetDataInfo, context: Context): Promise<void> {
  3180. try {
  3181. const preferencesUtil = PreferencesUtil.getInstance();
  3182. const prefs = await preferencesUtil.getPreferences(context);
  3183. // 将WidgetDataInfo转换为IWidgetData接口格式
  3184. const widgetData: IWidgetData = {
  3185. songId: widgetDataInfo.songId,
  3186. name: widgetDataInfo.name,
  3187. artist: widgetDataInfo.artist,
  3188. album: widgetDataInfo.album,
  3189. pixelMapPath: widgetDataInfo.pixelMapPath,
  3190. duration: widgetDataInfo.duration,
  3191. filePath: widgetDataInfo.filePath,
  3192. imgName: widgetDataInfo.imgName,
  3193. imageColorHex: widgetDataInfo.imageColorHex,
  3194. isFavorite: widgetDataInfo.isFavorite,
  3195. isPlaying: widgetDataInfo.isPlaying,
  3196. isPaused: widgetDataInfo.isPaused,
  3197. isLoading: widgetDataInfo.isLoading,
  3198. currentPosition: widgetDataInfo.currentPosition,
  3199. hasNext: widgetDataInfo.hasNext,
  3200. hasPrevious: widgetDataInfo.hasPrevious,
  3201. playMode: widgetDataInfo.playMode,
  3202. currentIndex: widgetDataInfo.currentIndex,
  3203. totalCount: widgetDataInfo.totalCount,
  3204. currentTimeText: widgetDataInfo.currentTimeText,
  3205. totalTimeText: widgetDataInfo.totalTimeText,
  3206. progressPercentage: widgetDataInfo.progressPercentage,
  3207. createTime: widgetDataInfo.createTime,
  3208. updateTime: widgetDataInfo.updateTime
  3209. };
  3210. await preferencesUtil.saveWidgetData(prefs, widgetData);
  3211. LogUtils.getInstance().LOGI(`UnifiedPlayerService saveWidgetDataToPreferences: Widget data saved to preferences for song: ${widgetDataInfo.name}`);
  3212. } catch (error) {
  3213. LogUtils.getInstance().LOGI(`UnifiedPlayerService saveWidgetDataToPreferences: Failed to save widget data to preferences: ${error}`);
  3214. }
  3215. }
  3216. /**
  3217. * 从Preferences获取FormInfo列表
  3218. */
  3219. private async getFormInfoListFromPreferences(context: Context): Promise<FormInfo[]> {
  3220. try {
  3221. const preferencesUtil = PreferencesUtil.getInstance();
  3222. const prefs = await preferencesUtil.getPreferences(context);
  3223. const formInfoDataList = await preferencesUtil.getAllFormInfos(prefs);
  3224. // 将IFormInfo转换为FormInfo类型
  3225. const formInfoList: FormInfo[] = formInfoDataList.map(data => {
  3226. const formInfo = new FormInfo();
  3227. formInfo.formId = data.formId;
  3228. formInfo.formName = data.formName;
  3229. formInfo.formDimension = data.formDimension;
  3230. formInfo.createTime = data.createTime;
  3231. formInfo.updateTime = data.updateTime;
  3232. return formInfo;
  3233. });
  3234. LogUtils.getInstance().LOGI(`UnifiedPlayerService getFormInfoListFromPreferences: Found ${formInfoList.length} forms in preferences`);
  3235. LogUtils.getInstance().LOGI(`UnifiedPlayerService getFormInfoListFromPreferences: Using context: ${context ? 'Available' : 'NULL'}, Process: ${AppStorage.get('processName') || 'Unknown'}`);
  3236. return formInfoList;
  3237. } catch (error) {
  3238. LogUtils.getInstance().LOGI(`UnifiedPlayerService getFormInfoListFromPreferences: Failed to get forms from preferences: ${error}`);
  3239. return [];
  3240. }
  3241. }
  3242. /**
  3243. * 状态变化时更新卡片
  3244. */
  3245. public async updateWidgetsForStateChange(): Promise<void> {
  3246. try {
  3247. await this.updateAllForms(true); // 强制更新,因为状态确实发生了变化
  3248. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Widgets updated for state change`);
  3249. } catch (error) {
  3250. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to update widgets for state change: ${error}`);
  3251. }
  3252. }
  3253. /**
  3254. * 播放列表变化时更新卡片
  3255. */
  3256. private async updateWidgetsForPlaylistChange(): Promise<void> {
  3257. try {
  3258. this.updateAllForms();
  3259. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Widgets updated for playlist change`);
  3260. } catch (error) {
  3261. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to update widgets for playlist change: ${error}`);
  3262. }
  3263. }
  3264. /**
  3265. * 应用启动时初始化卡片显示
  3266. */
  3267. public async initializeWidgetDisplay(): Promise<void> {
  3268. try {
  3269. this.updateAllForms();
  3270. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Widget display initialized');
  3271. } catch (error) {
  3272. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to initialize widget display: ${error}`);
  3273. }
  3274. }
  3275. /**
  3276. * 解析时长字符串为毫秒数
  3277. */
  3278. private parseDuration(durationStr: string): number {
  3279. if (!durationStr || durationStr === '0') {
  3280. return 0;
  3281. }
  3282. try {
  3283. // 如果是纯数字,假设是秒数
  3284. const numValue = parseFloat(durationStr);
  3285. if (!isNaN(numValue)) {
  3286. const result = Math.floor(numValue * 1000); // 转换为毫秒
  3287. return result;
  3288. }
  3289. // 如果包含冒号,解析为 MM:SS 或 HH:MM:SS 格式
  3290. if (durationStr.includes(':')) {
  3291. const parts = durationStr.split(':').map(part => parseInt(part, 10));
  3292. let totalSeconds = 0;
  3293. if (parts.length === 2) {
  3294. // MM:SS 格式
  3295. totalSeconds = parts[0] * 60 + parts[1];
  3296. } else if (parts.length === 3) {
  3297. // HH:MM:SS 格式
  3298. totalSeconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  3299. }
  3300. const result = totalSeconds * 1000; // 转换为毫秒
  3301. return result;
  3302. }
  3303. return 0;
  3304. } catch (error) {
  3305. return 0;
  3306. }
  3307. }
  3308. // ==================== PlayerStateCallback 实现 ====================
  3309. /**
  3310. * 转换播放模式为AVSession循环模式
  3311. */
  3312. private convertPlayModeToLoopMode(playMode: number): avSession.LoopMode {
  3313. switch (playMode) {
  3314. case PlayMode.SINGLE_REPEAT:
  3315. return avSession.LoopMode.LOOP_MODE_SINGLE;
  3316. case PlayMode.NORMAL:
  3317. return avSession.LoopMode.LOOP_MODE_LIST;
  3318. case PlayMode.RANDOM:
  3319. return avSession.LoopMode.LOOP_MODE_SHUFFLE;
  3320. case PlayMode.SEQUENCE:
  3321. default:
  3322. return avSession.LoopMode.LOOP_MODE_SEQUENCE;
  3323. }
  3324. }
  3325. /**
  3326. * 更新AVSession播放状态(带防抖)
  3327. */
  3328. private updateSessionPlayState(force: boolean = false): void {
  3329. // 清除之前的定时器
  3330. if (this.avSessionUpdateTimer !== -1) {
  3331. clearTimeout(this.avSessionUpdateTimer);
  3332. }
  3333. if (force) {
  3334. // 强制更新,立即执行,绕过频率限制
  3335. this.doUpdateSessionPlayState(true);
  3336. } else {
  3337. // 增加防抖延迟到500ms,减少频繁更新
  3338. this.avSessionUpdateTimer = setTimeout(() => {
  3339. this.doUpdateSessionPlayState(false);
  3340. }, 500);
  3341. }
  3342. }
  3343. /**
  3344. * 实际执行AVSession播放状态更新
  3345. * @param force 是否强制更新,绕过频率限制
  3346. */
  3347. private doUpdateSessionPlayState(force: boolean = false): void {
  3348. try {
  3349. if (!this.avSessionController) {
  3350. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession controller not initialized');
  3351. return;
  3352. }
  3353. // 避免过于频繁的更新(最小间隔300ms,保证关键操作响应性)
  3354. // 强制更新时绕过频率限制
  3355. const now = Date.now();
  3356. if (!force && now - this.lastAvSessionUpdate < 300) {
  3357. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Skipping AVSession update due to rate limit');
  3358. return;
  3359. }
  3360. // 优化:确保使用最新的歌曲数据,避免状态不一致
  3361. const currentSong = this.playlistModel.getCurrentSong();
  3362. const currentPosition = this.getCurrentPosition();
  3363. // 添加数据一致性检查
  3364. if (!currentSong) {
  3365. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: No current song available for AVSession update');
  3366. return;
  3367. }
  3368. // 优先从播放器获取实际duration
  3369. let duration = 0;
  3370. const ijkPlayer = this.playerManager.getIjkPlayer();
  3371. if (ijkPlayer) {
  3372. duration = ijkPlayer.getDuration();
  3373. }
  3374. if (duration <= 0 && currentSong?.duration) {
  3375. duration = this.parseDuration(currentSong.duration);
  3376. }
  3377. const currentState = this.stateModel.getState();
  3378. // 按照官方文档要求设置完整的播放状态
  3379. const playbackState: avSession.AVPlaybackState = {
  3380. // 播放状态 - 修复:确保播放状态正确反映当前状态
  3381. state: currentState.isPlaying ? avSession.PlaybackState.PLAYBACK_STATE_PLAY :
  3382. avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  3383. // 播放速度
  3384. speed: currentState.speed || 1.0,
  3385. // 循环模式
  3386. loopMode: this.convertPlayModeToLoopMode(currentState.playMode),
  3387. // 收藏状态
  3388. isFavorite: this.getCurrentSongFavoriteState()
  3389. };
  3390. // 只有当duration > 0时才设置位置信息,避免进度条显示问题
  3391. if (duration > 0) {
  3392. playbackState.position = {
  3393. elapsedTime: Math.max(0, currentPosition), // 已播放时间(毫秒)
  3394. updateTime: Date.now() // 更新时间戳
  3395. };
  3396. playbackState.bufferedTime = Math.max(currentPosition, 0);
  3397. } else {
  3398. LogUtils.getInstance()
  3399. .LOGI(`Heanup UnifiedPlayerService: Skipping position info due to invalid duration: ${duration}ms`);
  3400. }
  3401. this.avSessionController.setAvSessionPlayState(playbackState);
  3402. // 记录上次更新时间
  3403. this.lastAvSessionUpdate = now;
  3404. // 添加调试日志,便于问题排查
  3405. const updateType = force ? "FORCED" : "NORMAL";
  3406. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: AVSession state updated (${updateType}) - isPlaying: ${currentState.isPlaying}, position: ${Math.max(0, currentPosition)}ms, duration: ${duration}ms`);
  3407. } catch (error) {
  3408. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to update AVSession play state: ${error}`);
  3409. }
  3410. }
  3411. /**
  3412. * 更新AVSession元数据(优化防抖逻辑,修复竞态条件)
  3413. */
  3414. private async updateAvSessionMetadata(song: VideoItem): Promise<void> {
  3415. // 清除之前的定时器,避免重复更新
  3416. if (this.avMetadataUpdateTimer !== -1) {
  3417. clearTimeout(this.avMetadataUpdateTimer);
  3418. this.avMetadataUpdateTimer = -1;
  3419. }
  3420. // 优化:减少防抖时间,提高响应速度
  3421. const now = Date.now();
  3422. if (now - this.lastAvSessionUpdateTime < 500) {
  3423. // 如果更新过于频繁,延迟到下一个时间窗口
  3424. this.avMetadataUpdateTimer = setTimeout(() => {
  3425. this.doUpdateAvSessionMetadata(song);
  3426. }, 500 - (now - this.lastAvSessionUpdateTime));
  3427. return;
  3428. }
  3429. this.lastAvSessionUpdateTime = now;
  3430. // 检查播放器状态,决定更新时机
  3431. const ijkPlayer = this.playerManager.getIjkPlayer();
  3432. const playerDuration = ijkPlayer ? ijkPlayer.getDuration() : 0;
  3433. const shouldWaitForPlayer = playerDuration <= 0 && this.isPlayerPreparedForCurrentSong === false;
  3434. if (shouldWaitForPlayer) {
  3435. // 播放器还没准备好,适当延迟
  3436. this.avMetadataUpdateTimer = setTimeout(() => {
  3437. this.doUpdateAvSessionMetadata(song);
  3438. }, 300);
  3439. } else {
  3440. // 播放器已准备好,立即更新
  3441. this.avMetadataUpdateTimer = setTimeout(() => {
  3442. this.doUpdateAvSessionMetadata(song);
  3443. }, 50);
  3444. }
  3445. }
  3446. /**
  3447. * 实际执行AVSession元数据更新
  3448. */
  3449. private async doUpdateAvSessionMetadata(song: VideoItem): Promise<void> {
  3450. try {
  3451. if (!this.avSessionController) {
  3452. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: AVSession controller not initialized');
  3453. return;
  3454. }
  3455. // 关键修复:验证歌曲数据的一致性,确保使用最新的歌曲信息
  3456. const currentSong = this.playlistModel.getCurrentSong();
  3457. if (!currentSong || currentSong.filePath !== song.filePath) {
  3458. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Song data inconsistency detected. Current: ${currentSong?.name}, Provided: ${song.name}`);
  3459. // 使用最新的歌曲数据
  3460. if (currentSong) {
  3461. song = currentSong;
  3462. LogUtils.getInstance().LOGI(`UnifiedPlayerService: Using latest song data: ${song.name}`);
  3463. } else {
  3464. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: No current song available, skipping metadata update');
  3465. return;
  3466. }
  3467. }
  3468. // 减少防抖时间,提高响应速度
  3469. const now = Date.now();
  3470. if (now - this.lastAvMetadataUpdate < 300) {
  3471. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: Skipping AVSession metadata update due to rate limit');
  3472. return;
  3473. }
  3474. // 调试:打印VideoItem的duration字段
  3475. LogUtils.getInstance()
  3476. .LOGI(`Heanup UnifiedPlayerService: VideoItem duration field - value: '${song.duration}', type: ${typeof song.duration}`);
  3477. // 智能获取最准确的duration
  3478. let duration = 0;
  3479. try {
  3480. const ijkPlayer = this.playerManager.getIjkPlayer();
  3481. if (ijkPlayer && this.isPlayerPreparedForCurrentSong) {
  3482. const playerDuration = ijkPlayer.getDuration();
  3483. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Player getDuration() returned: ${playerDuration}ms`);
  3484. if (playerDuration > 0) {
  3485. duration = playerDuration;
  3486. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Using player duration: ${duration}ms`);
  3487. } else {
  3488. // 备用方案:解析VideoItem中的duration
  3489. duration = song.duration ? this.parseDuration(song.duration) : 0;
  3490. LogUtils.getInstance()
  3491. .LOGI(`Heanup UnifiedPlayerService: Player duration invalid, using parsed duration: ${duration}ms from '${song.duration}'`);
  3492. }
  3493. } else {
  3494. duration = song.duration ? this.parseDuration(song.duration) : 0;
  3495. LogUtils.getInstance()
  3496. .LOGI(`Heanup UnifiedPlayerService: Player not ready, using parsed duration: ${duration}ms from '${song.duration}'`);
  3497. }
  3498. } catch (error) {
  3499. duration = song.duration ? this.parseDuration(song.duration) : 0;
  3500. LogUtils.getInstance()
  3501. .LOGI(`Heanup UnifiedPlayerService: Error getting player duration, using parsed: ${duration}ms from '${song.duration}', error: ${error}`);
  3502. }
  3503. // 最终验证duration
  3504. if (isNaN(duration) || duration <= 0) {
  3505. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Final duration is invalid (${duration}), setting to 0`);
  3506. duration = 0;
  3507. }
  3508. // 获取歌词内容(如果有的话)
  3509. const lyricContent = song.lyricContent || '';
  3510. LogUtils.getInstance()
  3511. .LOGI(`Heanup UnifiedPlayerService: About to call setAVMetadataMusic with duration: ${duration}ms (type: ${typeof duration})`);
  3512. await this.avSessionController.setAVMetadataMusic(song, duration, lyricContent);
  3513. // 记录更新时间
  3514. this.lastAvMetadataUpdate = now;
  3515. LogUtils.getInstance()
  3516. .LOGI(`Heanup UnifiedPlayerService: AVSession metadata updated for ${song.name} with duration ${duration}ms`);
  3517. } catch (error) {
  3518. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to update AVSession metadata: ${error}`);
  3519. }
  3520. }
  3521. // ==================== 辅助方法 ====================
  3522. /**
  3523. * 初始化图片缓存目录
  3524. */
  3525. private async initImageCacheDirectory(): Promise<void> {
  3526. try {
  3527. if (this.context) {
  3528. const cacheDir = this.context.getApplicationContext().cacheDir;
  3529. this.imageCacheDir = cacheDir + '/cover_images';
  3530. // 创建缓存目录
  3531. if (!fileIo.accessSync(this.imageCacheDir)) {
  3532. fileIo.mkdirSync(this.imageCacheDir);
  3533. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Created image cache directory: ${this.imageCacheDir}`);
  3534. }
  3535. // 清理过期缓存
  3536. await this.cleanExpiredCache();
  3537. }
  3538. } catch (error) {
  3539. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to initialize image cache directory: ${error}`);
  3540. }
  3541. }
  3542. /**
  3543. * 生成图片URL的哈希值作为缓存文件名
  3544. */
  3545. private generateCacheFileName(url: string): string {
  3546. try {
  3547. const textEncoder = new util.TextEncoder();
  3548. const data = textEncoder.encodeInto(url);
  3549. // 使用URL的简单哈希算法
  3550. let hash = 0;
  3551. for (let i = 0; i < data.byteLength; i++) {
  3552. const char = data[i];
  3553. hash = ((hash << 5) - hash) + char;
  3554. hash = hash & hash; // 转换为32位整数
  3555. }
  3556. return Math.abs(hash).toString(16) + '.jpg';
  3557. } catch (error) {
  3558. // 如果哈希生成失败,使用URL的简单替换方案
  3559. return url.replace(/[^a-zA-Z0-9]/g, '_').substring(0, 50) + '.jpg';
  3560. }
  3561. }
  3562. /**
  3563. * 检查缓存文件是否存在且未过期
  3564. */
  3565. private async isCacheValid(cacheFilePath: string): Promise<boolean> {
  3566. try {
  3567. if (!fileIo.accessSync(cacheFilePath)) {
  3568. return false;
  3569. }
  3570. const stat = fileIo.statSync(cacheFilePath);
  3571. const fileAge = Date.now() - stat.mtime;
  3572. const maxAge = this.CACHE_EXPIRY_DAYS * 24 * 60 * 60 * 1000; // 转换为毫秒
  3573. return fileAge < maxAge;
  3574. } catch (error) {
  3575. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to check cache validity: ${error}`);
  3576. return false;
  3577. }
  3578. }
  3579. /**
  3580. * 下载网络图片到缓存
  3581. */
  3582. private async downloadImageToCache(url: string, cacheFilePath: string): Promise<boolean> {
  3583. try {
  3584. const httpRequest = http.createHttp();
  3585. try {
  3586. const response = await httpRequest.request(url, {
  3587. method: http.RequestMethod.GET,
  3588. connectTimeout: 10000, // 10秒超时
  3589. readTimeout: 10000
  3590. });
  3591. if (response.responseCode === http.ResponseCode.OK && response.result) {
  3592. const tempFile = fileIo.openSync(cacheFilePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  3593. try {
  3594. await fileIo.write(tempFile.fd, response.result as ArrayBuffer);
  3595. fileIo.closeSync(tempFile.fd);
  3596. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Downloaded image to cache: ${cacheFilePath}`);
  3597. return true;
  3598. } catch (writeError) {
  3599. fileIo.closeSync(tempFile.fd);
  3600. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Write error: ${writeError}`);
  3601. return false;
  3602. }
  3603. } else {
  3604. LogUtils.getInstance()
  3605. .LOGI(`Heanup UnifiedPlayerService: Failed to download image ${url}: HTTP ${response.responseCode}`);
  3606. return false;
  3607. }
  3608. } finally {
  3609. httpRequest.destroy();
  3610. }
  3611. } catch (error) {
  3612. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Error downloading image to cache: ${error}`);
  3613. return false;
  3614. }
  3615. }
  3616. /**
  3617. * 清理过期缓存
  3618. */
  3619. private async cleanExpiredCache(): Promise<void> {
  3620. try {
  3621. if (!this.imageCacheDir || !fileIo.accessSync(this.imageCacheDir)) {
  3622. return;
  3623. }
  3624. const files = fileIo.listFileSync(this.imageCacheDir);
  3625. const maxAge = this.CACHE_EXPIRY_DAYS * 24 * 60 * 60 * 1000;
  3626. let totalSize = 0;
  3627. const fileInfos: Array<CacheFileInfo> = [];
  3628. // 收集文件信息
  3629. for (const file of files) {
  3630. const filePath = this.imageCacheDir + '/' + file;
  3631. try {
  3632. const stat = fileIo.statSync(filePath);
  3633. totalSize += stat.size;
  3634. const fileInfo: CacheFileInfo = {
  3635. path: filePath,
  3636. size: stat.size,
  3637. mtime: stat.mtime
  3638. };
  3639. fileInfos.push(fileInfo);
  3640. } catch (error) {
  3641. // 忽略无法读取的文件
  3642. }
  3643. }
  3644. // 删除过期文件
  3645. const now = Date.now();
  3646. for (const fileInfo of fileInfos) {
  3647. if (now - fileInfo.mtime > maxAge) {
  3648. try {
  3649. fileIo.unlinkSync(fileInfo.path);
  3650. totalSize -= fileInfo.size;
  3651. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Deleted expired cache file: ${fileInfo.path}`);
  3652. } catch (error) {
  3653. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to delete expired cache file: ${error}`);
  3654. }
  3655. }
  3656. }
  3657. // 如果缓存大小超限,删除最旧的文件
  3658. const maxSizeBytes = this.MAX_CACHE_SIZE_MB * 1024 * 1024;
  3659. if (totalSize > maxSizeBytes) {
  3660. const sortedFiles = fileInfos
  3661. .filter(f => fileIo.accessSync(f.path))// 只保留仍存在的文件
  3662. .sort((a, b) => a.mtime - b.mtime); // 按修改时间排序,最旧的在前
  3663. for (const fileInfo of sortedFiles) {
  3664. if (totalSize <= maxSizeBytes) {
  3665. break;
  3666. }
  3667. try {
  3668. fileIo.unlinkSync(fileInfo.path);
  3669. totalSize -= fileInfo.size;
  3670. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Deleted cache file due to size limit: ${fileInfo.path}`);
  3671. } catch (error) {
  3672. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to delete cache file: ${error}`);
  3673. }
  3674. }
  3675. }
  3676. LogUtils.getInstance()
  3677. .LOGI(`Heanup UnifiedPlayerService: Cache cleanup completed, total size: ${(totalSize / 1024 / 1024).toFixed(2)}MB`);
  3678. } catch (error) {
  3679. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to clean expired cache: ${error}`);
  3680. }
  3681. }
  3682. /**
  3683. * 清理无效的Form ID
  3684. * 应用启动时调用,验证所有保存的Form ID是否仍然有效
  3685. */
  3686. private async cleanupInvalidFormIds(): Promise<void> {
  3687. try {
  3688. if (!this.context) {
  3689. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: No context for cleanup invalid form IDs');
  3690. return;
  3691. }
  3692. // 根据存储配置读取所有Form信息
  3693. let formInfoList: FormInfo[] = [];
  3694. try {
  3695. if (WIDGET_DATA_STORAGE_TYPE === WidgetDataStorageType.DATABASE) {
  3696. formInfoList = await FormRdbHelper.getInstance(this.context).queryAllForms();
  3697. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService cleanupInvalidFormIds: Found ${formInfoList.length} forms in database`);
  3698. } else {
  3699. formInfoList = await this.getFormInfoListFromPreferences(this.context);
  3700. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService cleanupInvalidFormIds: Found ${formInfoList.length} forms in preferences`);
  3701. }
  3702. } catch (error) {
  3703. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService cleanupInvalidFormIds: Failed to query forms: ${error}`);
  3704. return;
  3705. }
  3706. if (formInfoList.length === 0) {
  3707. LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService cleanupInvalidFormIds: No forms found');
  3708. return;
  3709. }
  3710. // 记录更新统计
  3711. const invalidFormIds: string[] = [];
  3712. let flatWidgetData = await this.getWidgetFormData();
  3713. // 逐个更新所有卡片,根据卡片类型进行个性化处理
  3714. for (const formInfo of formInfoList) {
  3715. try {
  3716. const formBindingDataInstance = formBindingData.createFormBindingData(flatWidgetData);
  3717. await formProvider.updateForm(formInfo.formId, formBindingDataInstance);
  3718. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService cleanupInvalidFormIds: Successfully updated form ${formInfo.formId} (${formInfo.formName})`);
  3719. } catch (error) {
  3720. const errorStr: string = error?.toString() || '';
  3721. invalidFormIds.push(formInfo.formId);
  3722. LogUtils.getInstance()
  3723. .LOGI(`Heanup UnifiedPlayerService cleanupInvalidFormIds: Form ${formInfo.formId} (${formInfo.formName}) - ${errorStr}}`);
  3724. }
  3725. }
  3726. // 自动清理无效的Form ID
  3727. if (invalidFormIds.length > 0) {
  3728. try {
  3729. for (const invalidFormId of invalidFormIds) {
  3730. await FormRdbHelper.getInstance(this.context).deleteForm(invalidFormId);
  3731. }
  3732. LogUtils.getInstance()
  3733. .LOGI(`Heanup UnifiedPlayerService cleanupInvalidFormIds: Removed ${invalidFormIds.length} invalid form IDs from database: ${invalidFormIds.join(', ')}`);
  3734. } catch (error) {
  3735. LogUtils.getInstance()
  3736. .LOGI(`Heanup UnifiedPlayerService cleanupInvalidFormIds: Failed to clean invalid form IDs from database: ${error}`);
  3737. }
  3738. }
  3739. // const preferencesUtil = PreferencesUtil.getInstance();
  3740. // const prefs = await preferencesUtil.getPreferences(this.context);
  3741. // const formIds = await preferencesUtil.getFormIds(prefs);
  3742. //
  3743. // if (formIds.length === 0) {
  3744. // LogUtils.getInstance().LOGI('Heanup UnifiedPlayerService: No form IDs to cleanup');
  3745. // return;
  3746. // }
  3747. //
  3748. // const invalidFormIds: string[] = [];
  3749. //
  3750. // // 逐个验证Form ID的有效性
  3751. // for (const formId of formIds) {
  3752. // try {
  3753. // // 尝试更新卡片来验证其有效性
  3754. // const flatWidgetData = await this.getWidgetFormData();
  3755. // if (flatWidgetData) {
  3756. // const formBindingDataInstance = formBindingData.createFormBindingData(flatWidgetData);
  3757. // await formProvider.updateForm(formId, formBindingDataInstance);
  3758. // }
  3759. // } catch (error) {
  3760. // // 如果更新失败,说明这个Form ID无效
  3761. // invalidFormIds.push(formId);
  3762. // LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Invalid form ID detected: ${formId}, error: ${error}`);
  3763. // }
  3764. // }
  3765. //
  3766. // // 移除无效的Form ID
  3767. // if (invalidFormIds.length > 0) {
  3768. //
  3769. //
  3770. // LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Cleaned up ${invalidFormIds.length} invalid form IDs: ${invalidFormIds.join(', ')}`);
  3771. // } else {
  3772. // LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: All ${formIds.length} form IDs are valid`);
  3773. // }
  3774. } catch (error) {
  3775. LogUtils.getInstance().LOGI(`Heanup UnifiedPlayerService: Failed to cleanup invalid form IDs: ${error}`);
  3776. }
  3777. }
  3778. }