LocalMusic.ets 339 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167
  1. import TitleBar from './TitleBar'
  2. import { curves, display, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import {
  5. AppUtil,
  6. ArrayUtil,
  7. Base64Util,
  8. DateUtil,
  9. DeviceUtil,
  10. DisplayUtil,
  11. FileUtil,
  12. ImageUtil,
  13. LogUtil,
  14. MD5,
  15. PreferencesUtil,
  16. RandomUtil,
  17. StrUtil,
  18. ToastUtil
  19. } from '@pura/harmony-utils';
  20. import { CommonConstants } from '../common/constants/CommonConstants';
  21. import Logger from '../common/util/Logger';
  22. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  23. import { Utility } from '../common/util/Utility';
  24. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  25. import { uniformTypeDescriptor } from '@kit.ArkData';
  26. import { BubbleBean } from '../viewmodel/BubbleBean';
  27. import { PopupPosition, XPopup } from '@chinalike/popup';
  28. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  29. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  30. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  31. import { MessageEvents, util, worker,ErrorEvent } from '@kit.ArkTS';
  32. import { Verify } from './Verify';
  33. import { RotatingCover } from './RotatingCover';
  34. import { PlayConstants } from '../common/constants/PlayConstants';
  35. import { effectKit } from '@kit.ArkGraphics2D';
  36. import { ColorConversion } from '../common/util/ColorConversion';
  37. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  38. import { AvSessionController } from '../controller/AvSessionController';
  39. import {
  40. // DeviceChangeReason,
  41. IjkMediaPlayer,
  42. InterruptEvent,
  43. InterruptHintType,
  44. LogUtils,
  45. OnBufferingUpdateListener,
  46. OnCompletionListener,
  47. OnErrorListener,
  48. OnInfoListener,
  49. OnPreparedListener,
  50. OnSeekCompleteListener,
  51. OnTimedTextListener,
  52. OnVideoSizeChangedListener
  53. } from '@ohos/ijkplayer';
  54. import { PlayStatus } from '../common/PlayStatus';
  55. import fs from '@ohos.file.fs';
  56. import { image } from '@kit.ImageKit';
  57. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  58. import * as chardet from '@changwei/chardet';
  59. import { SettingPage } from '../pages/SettingPage';
  60. import { secondToTime } from '../common/util/CommUtils';
  61. import { CommonConstants2 } from '../common/util/CommonConstants2';
  62. import { hilog } from '@kit.PerformanceAnalysisKit';
  63. import { LazyDataSource } from '../common/util/LazyDataSource';
  64. import MediaTable from '../common/util/MediaTable';
  65. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  66. import ImageUtils from '../common/util/ImageUtils';
  67. import { ringtone } from '@kit.RingtoneKit';
  68. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  69. import { resourceManager } from '@kit.LocalizationKit';
  70. import { deviceInfo } from '@kit.BasicServicesKit';
  71. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  72. import { LrcParser } from '@sgaolei/lrc_parser';
  73. import app from '@system.app';
  74. import { TextNodeController } from './PipLyricTextBuilder';
  75. import { IndexerView } from './IndexerView';
  76. import { KeyCode } from '@kit.InputKit';
  77. const TAG = 'LocalMusic';
  78. const DEFAULT_INDEX = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  79. //排序类型
  80. function getTypeOrder(type: number) {
  81. switch (type) {
  82. case CommonConstants.TYPE_IS_DIR:
  83. return 1; // First
  84. case CommonConstants.TYPE_IS_CSJAD:
  85. return 2; // Middle
  86. case CommonConstants.TYPE_LOCAL:
  87. return 3; // Last
  88. default:
  89. return 4; // Unknown types, if any, go last
  90. }
  91. }
  92. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  93. interface GeneratedObjectLiteralInterface_1 {
  94. assetId: string;
  95. title: string;
  96. artist: string;
  97. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  98. mediaUri: string;
  99. // 该字段大写,音频'AUDIO',视频'VIDEO'
  100. mediaType: string;
  101. mediaSize: number;
  102. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  103. startPosition: number;
  104. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  105. duration: number;
  106. albumCoverUri: string;
  107. albumTitle: string;
  108. appName: string;
  109. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  110. drmScheme: string;
  111. }
  112. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  113. const ITEM_HEIGHT: number = 58; // 列表项中高度
  114. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  115. //功能强大的音乐播放器
  116. @Preview
  117. @Component
  118. export struct LocalMusic {
  119. @Consume mType: number;
  120. @StorageProp('themeColor') themeColor: string = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  121. themeMode: number=0;
  122. @State titleName: string = '首页'
  123. @State textStr: string = ''
  124. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  125. // private download_path: string = '';
  126. @Consume rootPath: string //音频根目录
  127. @Consume currentPath: string
  128. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  129. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  130. @State lockPath: string = ''
  131. @State favPath: string = ''
  132. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  133. @State historyPath: string = ''
  134. @State historyList: Array<VideoItem> = []
  135. @Consume isHistory: boolean
  136. static readonly HISTORY_MUSIC: string = 'music_historyList';
  137. private table: MediaTable = new MediaTable(getContext(this))
  138. @State isZero: boolean = false
  139. @State fileList: Array<string> = []
  140. @State dirList: Array<VideoItem> = []
  141. @Consume videoLocalList: Array<VideoItem>
  142. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  143. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  144. @State artistList: Array<VideoItem> = []; //艺术家文件
  145. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  146. @State albumList: Array<VideoItem> = []; //专辑文件
  147. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  148. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  149. @State imageOpacities: number[] = [];
  150. @Consume isCanBack: boolean
  151. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  152. @State showSingleLyric: boolean = false
  153. @State sortType: number = 4 //默认排序方式
  154. @State isShowSimi:boolean = false //是否显示私密音频
  155. @State isShowFAV:boolean = true //是否显示我的收藏
  156. @State isShowTitleBar: boolean = true //是否显示分类导航条
  157. @State isShowAllBar: boolean = true //是否显示播放全部条
  158. @State isShowHistory:boolean = true //是否显示最近播放
  159. @State isCustomizeBg: boolean = false //自定义背景界面
  160. @State isGridMusic: boolean = false //是否网格布局
  161. @State isCircleBtn: boolean = false //是否圆形播放按钮
  162. @State twoFingerType: number = 3 //双支放大缩小的类型
  163. @State isScrollHide: boolean = false //是否滚动隐藏
  164. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  165. @State isStartAutoPlay: boolean = false //启动后自动播放
  166. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  167. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  168. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  169. @State isCoverTopBig: boolean = false//顶部大封面部分手机显示会和播放控制页重叠
  170. @State customizeBgPath: string | undefined = '';
  171. @State isDarkMode: boolean = false
  172. @State lyricTextWeight: number = 400
  173. @State lyricTextWeightPip: number = 400
  174. @State currentSwiperIndex: number = 0
  175. @State blurValue: number = 0 //背景模糊
  176. @State bgBrightness: number = 0 //背景亮度
  177. private listScroller: ListScroller = new ListScroller()
  178. private playListScroller: Scroller = new Scroller()
  179. @StorageProp('isLandscape') isLandscape: boolean = false;
  180. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  181. private listArea: Area = {
  182. width: 0,
  183. height: 0,
  184. position: {},
  185. globalPosition: {}
  186. }
  187. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  188. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  189. onColorModeChange() {
  190. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  191. if(this.isCustomizeBg){
  192. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  193. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  194. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  195. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  196. }else{
  197. if (!this.isDarkMode) {
  198. this.titleBarModel.setTitleBarBackground(this.themeColor)
  199. this.titleBarModel .setTitleBarBottomLineColor(this.themeColor)
  200. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  201. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  202. }else {
  203. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  204. this.titleBarModel .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  205. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  206. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  207. }
  208. }
  209. }
  210. onModeChange() {
  211. this.isFavMusic = false
  212. if (this.modeType === 2 || this.modeType === 3) {
  213. this.titleBarModel.setRightIcon(null)
  214. } else {
  215. this.titleBarModel.setRightIcon(($r('app.media.add')))
  216. }
  217. LogUtil.info('onecold onModeChange = ' + this.modeType)
  218. switch (this.modeType) {
  219. case 0:
  220. this.getSortedFiles(this.currentPath)
  221. break
  222. case 1:
  223. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  224. this.updateListData(this.mediaKuList)
  225. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  226. break
  227. case 2:
  228. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  229. this.updateListData(this.artistList)
  230. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  231. break
  232. case 3:
  233. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  234. this.updateListData(this.albumList)
  235. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  236. break
  237. }
  238. }
  239. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  240. // @StorageLink('isPlay') isPlay: boolean = false;
  241. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  242. @StorageProp('windowHeight') windowHeight: number = 0;
  243. @StorageLink('songList') songList: Array<VideoItem> = [];
  244. @State translateY: number = 0;
  245. @State isShowSheet: boolean = false;
  246. @State isShowSheetView: boolean = false;
  247. @State isShowTimeCloseView: boolean = false;
  248. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  249. @StorageLink('currIndex') curIndex: number = 0;
  250. @Consume isShowDrawer: boolean;
  251. @Consume offsetX: number;
  252. @State isFac: boolean = false;
  253. @State favList: Array<VideoItem>= []
  254. @Consume isFavMusic:boolean
  255. @State isClickedPLayAll: boolean = false;
  256. private scrollerForlist: ListScroller = new ListScroller();
  257. imagesF: ImageFrameInfo[] = [
  258. { src: $r("app.media.app_loading0") },
  259. { src: $r("app.media.app_loading1") },
  260. { src: $r("app.media.app_loading2") },
  261. { src: $r("app.media.app_loading3") },
  262. ]
  263. @State animationState: AnimationStatus = AnimationStatus.Initial
  264. // 缓存机制
  265. private cache: Map<string, Array<VideoItem>> = new Map();
  266. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  267. // 持久化缓存
  268. private async saveCacheToStorage() {
  269. const cacheArray = Array.from(this.cache.entries());
  270. const stringCacheArray = Array.from(this.stringCache.entries());
  271. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  272. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  273. }
  274. // 载入缓存
  275. private async loadCacheFromStorage() {
  276. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  277. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  278. if (cacheString) {
  279. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  280. this.cache = new Map(cacheArray);
  281. }
  282. if (stringCacheString) {
  283. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  284. this.stringCache = new Map(stringCacheArray);
  285. }
  286. }
  287. // 查找缓存
  288. private findCache(key: string): Array<VideoItem> | undefined {
  289. return this.cache.get(key);
  290. }
  291. // 查找字符串缓存
  292. private findStringCache(key: string): string | undefined {
  293. return this.stringCache.get(key);
  294. }
  295. // 添加缓存
  296. private addCache(key: string, value: Array<VideoItem>) {
  297. this.cache.set(key, value);
  298. }
  299. // 添加字符串缓存
  300. private addStringCache(key: string, value: string) {
  301. this.stringCache.set(key, value);
  302. }
  303. // 删除缓存
  304. private deleteCache(key: string) {
  305. this.cache.delete(key);
  306. this.saveCacheToStorage()
  307. }
  308. // 删除字符串缓存
  309. private deleteStringCache(key: string) {
  310. this.stringCache.delete(key);
  311. }
  312. // 多选机制
  313. @State selectedFiles: Array<VideoItem> = [];
  314. @State isMultiSelect: boolean = false;
  315. @State isAllSelected: boolean = false;
  316. @State appName: string = ''
  317. @State isHasDir: boolean = false
  318. @State packName: string = ''
  319. context = getContext(this);
  320. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  321. .setTitleTextStyle(FontStyle.Normal)
  322. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  323. .setLeftIcon($r('app.media.menu'))
  324. .setLeftIconWidth(25)
  325. .setLeftIconHeight(25)
  326. .setTitleName('首页')
  327. .setTitleFontSize(18)
  328. .setTitleFontColor(Color.White)
  329. .setTitleBarBackground(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor)
  330. .setTitleBarBottomLineColor(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor)
  331. .setLeftTitleStateNormalStyleColor(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor)
  332. .setRightIcon($r('app.media.add'))
  333. .setOnRightClickListener(() => {
  334. this.showSheelDialog()
  335. })
  336. .setOnTitleClickListener(() => {
  337. this.showPupDialog()
  338. })
  339. .setOnLeftClickListener(() => {
  340. this.doSwipBack()
  341. })
  342. doSwipBack() {
  343. if (this.modeType !== 0 && this.isCanBack) {
  344. this.onModeChange()
  345. this.isCanBack = false
  346. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  347. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  348. setTimeout(() => {
  349. if(this.modeType ==2){
  350. if (this.isGridMusic) {
  351. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  352. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  353. } else {
  354. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  355. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  356. }
  357. }else if(this.modeType ==3){
  358. if (this.isGridMusic) {
  359. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  360. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  361. } else {
  362. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  363. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  364. }
  365. }
  366. }, 200)
  367. return
  368. }
  369. if (this.isHistory||this.isFavMusic) {
  370. this.isHistory = false
  371. this.getSortedFiles(this.currentPath)
  372. return
  373. }
  374. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  375. animateTo({ duration: 555 }, () => {
  376. // 动画闭包内控制Image组件的出现和消失
  377. this.isShowDrawer = !this.isShowDrawer
  378. this.offsetX = 0
  379. })
  380. return
  381. }
  382. this.currentPath = Utility.getParentDirectory(this.currentPath)
  383. Logger.info('this.currentPath2 = ' + this.currentPath)
  384. this.getSortedFiles(this.currentPath)
  385. }
  386. // 组件生命周期
  387. aboutToAppear() {
  388. this.initSetting()
  389. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  390. Utility.getAppName(getContext(this)).then((appName: string) => {
  391. this.appName = appName
  392. })
  393. this.packName = AppUtil.getBundleName()
  394. this.loadCacheFromStorage(); // 加载缓存
  395. this.mkDownLoadDir()
  396. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  397. // 监听广播事件(打开其他应用处理)
  398. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  399. this.saveVideoDatas([eventData.data?.message], true)
  400. });
  401. //侧滑广播接收时间
  402. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  403. // 监听广播事件(打开其他应用处理)
  404. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  405. this.doSwipBack()
  406. });
  407. //ScanFilePage广播接收时间
  408. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  409. // 监听ScanFilePage广播事件(更新数据库)
  410. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  411. this.doUpdateData()
  412. });
  413. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  414. // 监听广播事件(通用设置配置更新)
  415. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  416. this.doChangeSetting()
  417. });
  418. let event: Callback<InterruptEvent> = (event) => {
  419. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  420. this.savePlaybackPosition()
  421. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  422. this.pause();
  423. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  424. this.startPlayOrResumePlay();
  425. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  426. this.stop();
  427. }
  428. }
  429. this.mIjkMediaPlayer.on('audioInterrupt', event);
  430. // 音频设备断连回调处理
  431. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  432. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  433. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  434. // this.pause();
  435. // }
  436. // }
  437. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  438. this.makeWorker()
  439. //折叠屏的屏幕显示模式变化
  440. display.on('foldDisplayModeChange', (data) => {
  441. this.doChangeBarHeight()
  442. });
  443. display.on('foldStatusChange', (data) => {
  444. Logger.info('onecold foldStatusChange ')
  445. });
  446. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, false)
  447. // 读取 themeMode 并同步 currentColorMode
  448. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  449. this.applyThemeMode(this.themeMode)
  450. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  451. AppStorage.setOrCreate('themeColor', themeColor);
  452. this.themeColor = themeColor;
  453. this.doChangeSetting()
  454. this.windowClass.on('windowSizeChange', (size) => {
  455. // LogUtil.info('onecold windowSizeChange')
  456. this.doChangeBarHeight()
  457. let viewWidth = px2vp(size.width);
  458. let viewHeight = px2vp(size.height);
  459. if (viewWidth > viewHeight) {
  460. this.isLandscape = true;
  461. this.startAutoHide()
  462. // Logger.info('onecold 横屏 windowSizeChange isLandscape = ' + this.isLandscape)
  463. }else{
  464. this.isLandscape = false;
  465. this.isAutoHide = false
  466. // Logger.info('onecold 竖屏 windowSizeChange isLandscape = ' + this.isLandscape)
  467. }
  468. });
  469. this.eventHub.on('onStateChange', (fg: boolean) => {
  470. if (fg && this.curState === 'STARTED') {
  471. this.stopPip();
  472. }
  473. });
  474. }
  475. startAutoHide(){
  476. setTimeout(() => {
  477. this.isAutoHide = true
  478. }, 4000)
  479. }
  480. applyThemeMode(mode: number) {
  481. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  482. if (mode === 1) {
  483. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  484. } else if (mode === 2) {
  485. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  486. }
  487. AppStorage.setOrCreate('currentColorMode', colorMode)
  488. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  489. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  490. AppStorage.setOrCreate('themeMode', mode)
  491. this.isDarkMode=colorMode===ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  492. // 只有强制浅色/深色时才主动设置
  493. const context = getContext(this) as common.UIAbilityContext
  494. context.getApplicationContext().setColorMode(colorMode)
  495. }
  496. initSetting(){
  497. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  498. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  499. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  500. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  501. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  502. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  503. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  504. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  505. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  506. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  507. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  508. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  509. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  510. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  511. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  512. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, false)
  513. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, false)
  514. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  515. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  516. if (this.isSavePlayMode) {
  517. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  518. }
  519. if(this.isCustomizeBg){
  520. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  521. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  522. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  523. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  524. }else{
  525. if (!this.isDarkMode) {
  526. this.titleBarModel.setTitleBarBackground(this.themeColor)
  527. this.titleBarModel .setTitleBarBottomLineColor(this.themeColor)
  528. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  529. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  530. }else {
  531. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  532. this.titleBarModel .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  533. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  534. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  535. }
  536. }
  537. }
  538. doChangeSetting(){
  539. this.initSetting()
  540. this.deleteCache(this.currentPath)
  541. if (this.modeType === 0) {
  542. this.getSortedFiles(this.currentPath)
  543. }
  544. }
  545. doChangeBarHeight() {
  546. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  547. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  548. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  549. this.setBarHeightNormal()
  550. }
  551. }
  552. onPageShow() {
  553. app.setImageCacheCount(100);
  554. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  555. app.setImageRawDataCacheSize(104857600);
  556. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  557. }
  558. //开启线程查看各个数据库
  559. makeWorker() {
  560. setTimeout(() => {
  561. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  562. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  563. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  564. // workerInstance.postMessage({
  565. // code: 1,
  566. // data1: this.context,
  567. // data2: this.rootPath,
  568. // data3: this.lockPath,
  569. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  570. // });
  571. PreferencesUtil.putSync('isFirstApp', false)
  572. } else {
  573. workerInstance.postMessage({ code: 2, data: this.context });
  574. workerInstance.postMessage({ code: 3, data: this.context });
  575. workerInstance.postMessage({ code: 4, data: this.context });
  576. this.getHistoryList(false)
  577. }
  578. }, 1000)
  579. workerInstance.onmessage = (e: MessageEvents): void => {
  580. switch (e.data.code) {
  581. case 101: //第一次扫描文件夹入库
  582. ToastUtil.showToast('刷新同步数据库成功!')
  583. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  584. this.doUpdateData()
  585. break;
  586. case 102: //查询媒体库列表
  587. this.mediaKuList = e.data.data
  588. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  589. Utility.doSortListAscending(this.mediaKuList)
  590. if (this.modeType === 1) {
  591. this.updateListData(this.mediaKuList)
  592. }
  593. break;
  594. case 103: //收到查询艺术家列表
  595. this.artistMap = e.data.data1;
  596. this.artistList = e.data.data2;
  597. break;
  598. case 104: //收到查询专辑列表
  599. this.albumMap = e.data.data1;
  600. this.albumList = e.data.data2
  601. //查询完毕在启动是否自动播放
  602. if(this.isStartAutoPlay){
  603. this.startPlayOrResumePlay()
  604. }
  605. break;
  606. }
  607. };
  608. // 在调用terminate后,执行onexit
  609. workerInstance.onexit = (code) => {
  610. console.log("main thread terminate");
  611. }
  612. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  613. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  614. workerInstance.onerror = (err: ErrorEvent) => {
  615. console.log("onerror" + err.message);
  616. }
  617. }
  618. @State isFirstStartPlay:boolean = false
  619. //获取download_path
  620. async mkDownLoadDir() {
  621. const documentViewPicker = new picker.DocumentViewPicker()
  622. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  623. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  624. // this.rootPath = this.download_path
  625. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  626. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  627. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  628. Logger.info('onecold rootPath = ' + this.rootPath)
  629. Logger.info('onecold lockPath = ' + this.lockPath)
  630. if (!FileUtil.accessSync(this.lockPath)) {
  631. FileUtil.mkdirSync(this.lockPath)
  632. }
  633. if (!FileUtil.accessSync(this.favPath)) {
  634. FileUtil.mkdirSync(this.favPath)
  635. }
  636. if (!FileUtil.accessSync(this.historyPath)) {
  637. FileUtil.mkdirSync(this.historyPath)
  638. }
  639. this.getSortedFiles(this.rootPath).then(() => {
  640. this.isFavMusic = false
  641. //穿山甲
  642. // this.loadBannerAd(CSJUtil.getBannerID())
  643. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  644. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  645. if (ArrayUtil.isEmpty(this.songList)) {
  646. this.songList = this.getCurFileList()
  647. } else {
  648. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  649. }
  650. if (ArrayUtil.isNotEmpty(this.songList)) {
  651. this.isFirstStartPlay = true
  652. this.sonDataSource.pushArrayData(this.songList)
  653. if (this.currentSong === undefined) {
  654. this.isFirstStartPlay = false
  655. this.currentSong = this.songList[0]
  656. }
  657. this.videoUrl = this.currentSong.filePath
  658. this.name = this.currentSong.name
  659. this.cover = this.currentSong.pixelMapPath
  660. } else {
  661. this.name = '空空如也'
  662. }
  663. })
  664. this.getFavList(false)
  665. }
  666. getFavList(isFavRefresh:boolean){
  667. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  668. this.favList = result
  669. if(isFavRefresh||this.isFavMusic){//如果是我的收藏,更新我的收藏数据
  670. this.videoLocalList = this.favList
  671. this.updateListData(this.videoLocalList)
  672. }
  673. })
  674. }
  675. getHistoryList(isRefresh:boolean){
  676. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  677. this.historyList = result
  678. // for (let i = 0; i < this.historyList.length; i++) {
  679. //
  680. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  681. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  682. // }
  683. if(isRefresh){
  684. this.videoLocalList = this.historyList
  685. this.updateListData(this.videoLocalList,true)
  686. }
  687. })
  688. }
  689. // 组件消失生命周期
  690. aboutToDisappear() {
  691. console.info('LifeCycleComponent aboutToDisappear');
  692. emitter.off(2);
  693. emitter.off(101);
  694. emitter.off(888);
  695. emitter.off(333);
  696. this.mDestroyPage = true;
  697. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  698. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  699. this.stop();
  700. }
  701. this.mIjkMediaPlayer.off('audioInterrupt');
  702. if (workerInstance) {
  703. workerInstance.terminate();
  704. }
  705. this.stopPip();
  706. this.destroyPipController()
  707. }
  708. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  709. this.isFavMusic = false
  710. if (isWorkerPost) {
  711. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  712. }
  713. if (this.modeType !== 0) {
  714. return
  715. }
  716. this.isCanBack = false
  717. this.currentPath = curPath
  718. this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
  719. if (curPath === this.rootPath) {
  720. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  721. } else {
  722. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  723. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  724. }
  725. }
  726. // Get the current file list and calculate its hash
  727. this.fileList = FileUtil.listFileSync(curPath);
  728. const currentHash = simpleHash(this.fileList);
  729. // Check cache
  730. const cachedValue = this.findCache(curPath);
  731. Logger.info('onecold cachedValue = ' + cachedValue)
  732. const cachedHash = this.findStringCache(curPath + '_hash');
  733. const cachedDirList = this.findCache(curPath + "_dirList");
  734. if (cachedValue !== undefined) {
  735. // this.videoLocalList = cachedValue;
  736. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  737. this.updateListData(cachedValue)
  738. }
  739. if (cachedDirList !== undefined) {
  740. this.dirList = cachedDirList
  741. }
  742. //通过当前hash值和缓存hash判断list有没有变化
  743. if (cachedValue && cachedHash === currentHash) {
  744. return;
  745. }
  746. this.fileList = FileUtil.listFileSync(curPath)
  747. let directories: Array<VideoItem> = [];
  748. let files: Array<VideoItem> = [];
  749. for (let i = 0; i < this.fileList.length; i++) {
  750. console.info(`The name of file: ${this.fileList[i]}`);
  751. let path = curPath + '/' + this.fileList[i]
  752. if (FileUtil.isDirectory(path)) {
  753. let item: VideoItem =
  754. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  755. '')
  756. if(this.isShowDir(item.name)){
  757. directories.push(item);
  758. }
  759. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  760. // Utility.doSortListAscending(directories)
  761. } else {
  762. if (this.currentPath === this.lockPath) {
  763. let item: VideoItem =
  764. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  765. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  766. files.push(item);
  767. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  768. // this.doSortListAscending(files)
  769. }
  770. }
  771. }
  772. }
  773. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  774. if (this.currentPath !== this.lockPath) {
  775. files = result;
  776. }
  777. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  778. Utility.doSortListAscending(files)
  779. if (this.currentPath === this.rootPath) {
  780. this.dirList = directories
  781. this.addCache(curPath + "_dirList", this.dirList);
  782. }
  783. //插入广告先注释掉
  784. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  785. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  786. // directories.push(adItem)
  787. // }
  788. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  789. this.videoLocalList = directories.concat(files);
  790. this.updateListData(this.videoLocalList)
  791. if (ArrayUtil.isNotEmpty(files)) {
  792. // 缓存结果
  793. this.addCache(curPath, this.videoLocalList);
  794. await this.saveCacheToStorage(); // 保存缓存至本地存储
  795. this.addStringCache(curPath + '_hash', currentHash);
  796. }
  797. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  798. // for (let i = 0; i < this.videoLocalList.length; i++) {
  799. //
  800. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  801. //
  802. // }
  803. // this.setButtonStatus()
  804. if (isOpen) {
  805. if (destPath === undefined) {
  806. // 处理 destPath 为 undefined 的情况
  807. return
  808. }
  809. if (destPath.endsWith('.lrc')) {
  810. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  811. if (StrUtil.isNotEmpty(this.videoUrl)) {
  812. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  813. this.initLyric(lyricPath);
  814. }
  815. return
  816. }
  817. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  818. this.doPlay(item2)
  819. }
  820. });
  821. }
  822. //扫描文件夹入库
  823. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  824. const files = FileUtil.listFileSync(curPath);
  825. let mediaItems: VideoItem[] = [];
  826. Logger.info('onecold scanDirectory start ')
  827. for (const file of files) {
  828. const fPath = `${curPath}/${file}`;
  829. if (fPath === this.lockPath) {
  830. Logger.info(`Skipping locked path: ${fPath}`);
  831. continue;
  832. }
  833. if (FileUtil.isDirectory(fPath)) {
  834. // Recursively scan subdirectories
  835. const subDirItems = await this.scanDirectory(fPath);
  836. mediaItems = mediaItems.concat(subDirItems);
  837. } else {
  838. Logger.info('onecold scanDirectory filePath = ' + fPath)
  839. // Process media files
  840. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  841. let mediaItem: VideoItem =
  842. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  843. mediaItems.push(mediaItem);
  844. this.table.insert(mediaItem, (id: number) => {
  845. });
  846. }
  847. }
  848. }
  849. return mediaItems;
  850. }
  851. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  852. animateTo({ duration: 888 }, () => {
  853. this.opacityItem = 0;
  854. });
  855. setTimeout(() => {
  856. this.videoLocalList = mList;
  857. if (!noSort) {
  858. if (this.modeType === 0 || this.modeType === 1) {
  859. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  860. this.doSortType(this.sortType)
  861. }
  862. }
  863. this.dataSource.pushArrayData(this.videoLocalList)
  864. animateTo({ duration: 888 }, () => {
  865. this.opacityItem = 1;
  866. });
  867. this.setButtonStatus()
  868. }, 200);
  869. }
  870. //获取视频缩略图头像
  871. async updatePixelMaps(curPath: string) {
  872. console.info('updatePixelMaps: ', curPath);
  873. const updatedList = [...this.videoLocalList]; // 创建一个新的列表
  874. for (const videoItem of updatedList) {
  875. if (videoItem.type === CommonConstants.TYPE_LOCAL) {
  876. let pixelMap: image.PixelMap | undefined = undefined;
  877. const uri = videoItem.filePath;
  878. // 获取缩略图
  879. // if (Utility.isVideoByExtension(uri)) {
  880. // pixelMap = await Utility.getFetchFrameByTime(uri);
  881. // } else {
  882. // pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri);
  883. // }
  884. let name = await MD5.digestSync(uri)
  885. let imagePath = this.context.filesDir + FileUtil.separator + name
  886. console.info('onecold release success. name= ' + name);
  887. imagePath = fileUri.getUriFromPath(imagePath)
  888. videoItem.pixelMapPath = imagePath
  889. // videoItem.pixelMap = pixelMap;
  890. // videoItem.pixelMapToString = pixelMap ? await ImageUtil.pixelMapToBase64StrBig(pixelMap) : undefined;
  891. }
  892. }
  893. // console.info('updatePixelMaps完毕: ', updatedList.length);
  894. this.updateListData(updatedList)
  895. // this.videoLocalList = updatedList; // 重新赋值以触发更新
  896. // 缓存结果
  897. this.addCache(curPath, updatedList);
  898. await this.saveCacheToStorage(); // 保存缓存至本地存储
  899. }
  900. //排序模式和多选模式
  901. showPupDialog() {
  902. if (this.modeType === 2 || this.modeType === 3) {
  903. this.titleBarModel.setRightIcon(null)
  904. } else {
  905. this.titleBarModel.setRightIcon(($r('app.media.add')))
  906. }
  907. let dataBean = new BubbleBean()
  908. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  909. dataBean.color = this.themeColor
  910. dataBean.modeType = this.modeType
  911. dataBean.imageRes =
  912. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  913. $r('app.media.refresh')]
  914. let pup: XPopup;
  915. if (this.isDarkMode) {
  916. pup = XPopup.Builder()
  917. .setPopupPosition(PopupPosition.BOTTOM)
  918. .atView('pup_positon_music')
  919. .setBackgroundColor(Color.Black)
  920. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  921. .show()
  922. }else {
  923. pup = XPopup.Builder()
  924. .setPopupPosition(PopupPosition.BOTTOM)
  925. .atView('pup_positon_music')
  926. .setBackgroundColor(Color.White)
  927. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  928. .show()
  929. }
  930. dataBean.onItemClick = (i) => {
  931. XPopup.dismissTop()
  932. switch (i) {
  933. case 0: //首页
  934. this.modeType = 0
  935. this.getSortedFiles(this.currentPath)
  936. break
  937. case 1:
  938. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  939. this.modeType = 1
  940. this.updateListData(this.mediaKuList)
  941. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  942. break
  943. case 2:
  944. this.modeType = 2
  945. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  946. this.updateListData(this.artistList)
  947. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  948. break
  949. case 3:
  950. this.modeType = 3
  951. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  952. this.updateListData(this.albumList)
  953. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  954. break
  955. case 4: //同步数据
  956. this.asyncCurrentPathData()
  957. break
  958. }
  959. }
  960. }
  961. getCurFileList(): Array<VideoItem> {
  962. let files: Array<VideoItem> = [];
  963. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  964. for (let i = 0; i < this.videoLocalList.length; i++) {
  965. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  966. files.push(this.videoLocalList[i]);
  967. }
  968. }
  969. }
  970. return files
  971. }
  972. setButtonStatus() {
  973. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  974. this.isZero = false
  975. } else {
  976. this.isZero = true
  977. }
  978. if (this.currentPath !== this.rootPath &&
  979. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  980. this.isHasDir = true //不为空,说明有子文件夹
  981. } else {
  982. this.isHasDir = false
  983. }
  984. }
  985. showRankDialog() {
  986. if (this.modeType === 2 || this.modeType === 3) {
  987. //动作面板
  988. DialogHelper.showBottomSheetDialog({
  989. title: "请选择排序模式",
  990. maskColor: Color.Transparent,
  991. // sheets: ["按名称升序", "按名称降序"],
  992. sheets:[
  993. {value:'按名称升序',fontColor: $r('app.color.text_color') },
  994. {value:'按名称降序',fontColor: $r('app.color.text_color') },
  995. ],
  996. backgroundColor:$r('app.color.bg_card'),
  997. height: '30%',
  998. transition: AnimationHelper.transitionInDown(555),
  999. onAction: (index) => {
  1000. switch (index) {
  1001. case 0:
  1002. Utility.doSortListAscending(this.videoLocalList)
  1003. break;
  1004. case 1:
  1005. Utility.doSortListDescending(this.videoLocalList)
  1006. break;
  1007. }
  1008. this.updateListData(this.videoLocalList)
  1009. }
  1010. })
  1011. return
  1012. }
  1013. //动作面板
  1014. DialogHelper.showBottomSheetDialog({
  1015. title: "请选择排序模式",
  1016. maskColor: Color.Transparent,
  1017. height: '75%',
  1018. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1019. sheets:[
  1020. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1021. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1022. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1023. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1024. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1025. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1026. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1027. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1028. ],
  1029. backgroundColor: $r('app.color.bg_card'),
  1030. transition: AnimationHelper.transitionInDown(555),
  1031. onAction: (index) => {
  1032. this.doSortType(index)
  1033. this.updateListData(this.videoLocalList, true)
  1034. }
  1035. })
  1036. }
  1037. doSortType(index: number) {
  1038. switch (index) {
  1039. case 0:
  1040. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1041. // 类型排序优先级
  1042. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1043. if (typeOrder !== 0) {
  1044. return typeOrder;
  1045. }
  1046. // 处理艺术家可能为undefined的字符串比较
  1047. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1048. const artistB = b.artist?.trim() || '';
  1049. return artistA.localeCompare(artistB);
  1050. });
  1051. break;
  1052. case 1:
  1053. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1054. // 类型排序优先级
  1055. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1056. if (typeOrder !== 0) {
  1057. return typeOrder;
  1058. }
  1059. // 处理艺术家可能为undefined的字符串比较
  1060. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1061. const artistB = b.artist?.trim() || '';
  1062. return artistB.localeCompare(artistA);
  1063. });
  1064. break;
  1065. case 2:
  1066. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1067. // 类型排序优先级
  1068. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1069. if (typeOrder !== 0) {
  1070. return typeOrder;
  1071. }
  1072. // 处理专辑可能为undefined的字符串比较
  1073. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1074. const albumB = b.album?.trim() || '';
  1075. return albumA.localeCompare(albumB);
  1076. });
  1077. break;
  1078. case 3:
  1079. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1080. // 类型排序优先级
  1081. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1082. if (typeOrder !== 0) {
  1083. return typeOrder;
  1084. }
  1085. // 处理专辑可能为undefined的字符串比较
  1086. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1087. const albumB = b.album?.trim() || '';
  1088. return albumB.localeCompare(albumA);
  1089. });
  1090. break;
  1091. case 4:
  1092. Utility.doSortListAscending(this.videoLocalList)
  1093. break;
  1094. case 5:
  1095. Utility.doSortListDescending(this.videoLocalList)
  1096. break;
  1097. case 6:
  1098. this.videoLocalList.sort((a, b) => {
  1099. // First, sort by type
  1100. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1101. if (typeOrder !== 0) {
  1102. return typeOrder;
  1103. }
  1104. // If types are the same, sort by cTime in ascending order
  1105. return a.cTime.localeCompare(b.cTime);
  1106. });
  1107. break;
  1108. case 7:
  1109. this.videoLocalList.sort((a, b) => {
  1110. // First, sort by type
  1111. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1112. if (typeOrder !== 0) {
  1113. return typeOrder;
  1114. }
  1115. // If types are the same, sort by cTime in descending order
  1116. return b.cTime.localeCompare(a.cTime);
  1117. });
  1118. break;
  1119. }
  1120. }
  1121. showSheelDialog() {
  1122. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1123. // this.showTips()
  1124. // return
  1125. // }
  1126. this.showAddDialog()
  1127. }
  1128. showAddDialog() {
  1129. if (this.modeType === 2 || this.modeType === 3) {
  1130. return
  1131. }
  1132. DialogHelper.showActionSheetDialog({
  1133. title: "请选择添加方式(建议歌词文件一起导入)",
  1134. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1135. sheets:[
  1136. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1137. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1138. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1139. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1140. ],
  1141. maskColor: Color.Transparent,
  1142. backgroundColor: $r('app.color.bg_card'),
  1143. transition: AnimationHelper.transitionInDown(555),
  1144. onAction: (index) => {
  1145. switch (index) {
  1146. case 0:
  1147. if (this.modeType === 0) {
  1148. this.showMkDialog()
  1149. } else {
  1150. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1151. }
  1152. break;
  1153. case 1:
  1154. this.callFilePickerSelectFile()
  1155. break;
  1156. case 2:
  1157. this.showTips()
  1158. break;
  1159. case 3:
  1160. this.goSelectMusic()
  1161. break;
  1162. }
  1163. }
  1164. })
  1165. }
  1166. //拉起音频
  1167. goSelectMusic(){
  1168. if(DeviceUtil.getDeviceType()== resourceManager.DeviceType.DEVICE_TYPE_TABLET||
  1169. DeviceUtil.getDeviceType()== resourceManager.DeviceType.DEVICE_TYPE_PC||
  1170. DeviceUtil.getDeviceType()== resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1171. ){
  1172. ToastUtil.showToast('暂时不支持该设备')
  1173. return
  1174. }
  1175. try {
  1176. let documentSelectOptions = new picker.DocumentSelectOptions();
  1177. documentSelectOptions.authMode = true
  1178. documentSelectOptions.multiAuthMode = true
  1179. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1180. let documentPicker = new picker.DocumentViewPicker(this.context);
  1181. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1182. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1183. this.saveVideoDatas(documentSelectResult)
  1184. }
  1185. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' + JSON.stringify(documentSelectResult));
  1186. }).catch((err: BusinessError) => {
  1187. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1188. });
  1189. } catch (error) {
  1190. let err: BusinessError = error as BusinessError;
  1191. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1192. }
  1193. }
  1194. async showTips() {
  1195. DialogHelper.showTipsDialog({
  1196. title: '使用提示:自动导入教程',
  1197. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1198. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1199. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1200. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1201. onAction: (action) => {
  1202. if (action == DialogAction.TWO) {
  1203. PreferencesUtil.putSync('isFirstMusic', false)
  1204. router.pushUrl({
  1205. url: 'pages/ScanFilePage'
  1206. });
  1207. }
  1208. }
  1209. })
  1210. }
  1211. showMkDialog() {
  1212. DialogHelper.showTextInputDialog({
  1213. title: '新建歌单',
  1214. maskColor: Color.Transparent,
  1215. text: '',
  1216. transition: AnimationHelper.transitionInDown(666),
  1217. onChange: (text) => {
  1218. console.error("onChange: " + text);
  1219. },
  1220. onAction: (action, dialogId, content) => {
  1221. // ToastUtil.showToast('content = ' +content)
  1222. if (action == DialogAction.TWO) {
  1223. const newName = content
  1224. const newPath = this.currentPath + '/' + newName
  1225. FileUtil.mkdir(newPath, true).then(() => {
  1226. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1227. this.getSortedFiles(this.currentPath)
  1228. }).catch((error: BusinessError) => {
  1229. console.error(error.message);
  1230. });
  1231. }
  1232. }
  1233. })
  1234. }
  1235. @State progress: number = 0;
  1236. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1237. if (ArrayUtil.isEmpty(uris)) {
  1238. return;
  1239. }
  1240. let newUris: string[] = [];
  1241. this.progress = 0
  1242. DialogHelper.showLoadingProgress({
  1243. progress: this.progress,
  1244. backCancel: false,
  1245. autoCancel: false,
  1246. loadColor: this.themeColor,
  1247. fontColor: this.themeColor
  1248. });
  1249. // 计算所有文件的总大小
  1250. let totalSize = 0;
  1251. for (let uri of uris) {
  1252. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1253. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1254. await fileIo.close(sourceFile.fd);
  1255. }
  1256. let totalRead = 0;
  1257. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1258. Logger.info(TAG, 'destPath uri: ' + destPath);
  1259. for (let i = 0; i < uris.length; i++) {
  1260. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1261. Logger.info(TAG, 'filePath uri: ' + filePath);
  1262. newUris.push(filePath);
  1263. try {
  1264. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1265. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1266. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1267. const buffer = new ArrayBuffer(buffSize);
  1268. let len = await fileIo.read(sourceFile.fd, buffer);
  1269. while (len > 0) {
  1270. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1271. totalRead += len;
  1272. // 计算总进度
  1273. this.progress = Math.floor((totalRead / totalSize) * 100);
  1274. DialogHelper.updateLoading('正在导入', this.progress);
  1275. len = await fileIo.read(sourceFile.fd, buffer);
  1276. }
  1277. await fileIo.close(sourceFile.fd);
  1278. await fileIo.close(destFile.fd);
  1279. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1280. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1281. let mediaItem: VideoItem =
  1282. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1283. this.table.insert(mediaItem, (id: number) => {
  1284. // 删除目标路径缓存
  1285. this.cache.delete(this.currentPath);
  1286. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1287. });
  1288. }
  1289. }
  1290. } catch (error) {
  1291. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1292. }
  1293. }
  1294. DialogHelper.closeLoading()
  1295. this.isZero = false
  1296. // setTimeout(() => {
  1297. // // 删除目标路径缓存
  1298. // this.cache.delete(this.currentPath);
  1299. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1300. // }, 500);
  1301. Logger.info(TAG, 'scan select video result:' + newUris)
  1302. }
  1303. //拉起音频
  1304. // goSelectMusic(){
  1305. //
  1306. // try {
  1307. // let audioSelectOptions = new picker.AudioSelectOptions();
  1308. // let audioPicker = new picker.AudioViewPicker(this.context);
  1309. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1310. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1311. // this.saveVideoDatas(audioSelectResult)
  1312. // }
  1313. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1314. // }).catch((err: BusinessError) => {
  1315. //
  1316. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1317. // });
  1318. // } catch (error) {
  1319. // let err: BusinessError = error as BusinessError;
  1320. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1321. // }
  1322. //
  1323. //
  1324. //
  1325. // }
  1326. goSelectImage(item:VideoItem) {
  1327. if (!item) {
  1328. return
  1329. }
  1330. let selectUris: Array<string> = [];
  1331. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1332. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1333. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1334. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1335. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1336. //用一个全局变量存储返回的uri
  1337. selectUris = photoSelectResult.photoUris;
  1338. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1339. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1340. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1341. console.info('file fd: ' + file.fd);
  1342. let name = await MD5.digestSync(this.videoUrl)
  1343. let imagePath = this.context.filesDir + FileUtil.separator + name
  1344. imagePath = fileUri.getUriFromPath(imagePath)
  1345. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1346. fileIo.copyFileSync(file.fd, file2.fd)
  1347. fileIo.closeSync(file);
  1348. fileIo.closeSync(file2);
  1349. if(item.filePath==this.currentSong?.filePath){
  1350. this.cover = imagePath
  1351. }
  1352. if (item) {
  1353. item.pixelMapPath = imagePath
  1354. }
  1355. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1356. if (success) {
  1357. this.doUpdateData()
  1358. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1359. } else {
  1360. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1361. }
  1362. });
  1363. LogUtil.debug("onecold this.cover =" + this.cover)
  1364. }).catch((err: BusinessError) => {
  1365. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1366. })
  1367. }
  1368. // 拉起picker选择文件管理器
  1369. async callFilePickerSelectFile(): Promise<void> {
  1370. try {
  1371. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1372. if(DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE){
  1373. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1374. }else{
  1375. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1376. }
  1377. let documentPicker = new picker.DocumentViewPicker();
  1378. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1379. Logger.info(TAG,
  1380. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1381. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1382. this.saveVideoDatas(DocumentSelectResult)
  1383. }
  1384. }).catch((err: BusinessError) => {
  1385. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1386. });
  1387. } catch (err) {
  1388. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1389. }
  1390. }
  1391. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1392. //操作确认类弹出框
  1393. DialogHelper.showAlertDialog({
  1394. maskColor: Color.Transparent,
  1395. content: "确定要删除这个文件吗?",
  1396. backgroundColor: Color.Grey,
  1397. transition: AnimationHelper.transitionInUp(555),
  1398. onAction: (action) => {
  1399. if (action == DialogAction.ONE) {
  1400. // ToastUtil.showToast(`您点击了取消按钮`);
  1401. } else if (action == DialogAction.TWO) {
  1402. // ToastUtil.showToast(`您点击了确认按钮`);
  1403. this.doDelete(item, index + '', filePath)
  1404. }
  1405. }
  1406. })
  1407. }
  1408. //删除单个索引index的视频
  1409. doDelete(item: VideoItem, index: string, filePath: string) {
  1410. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1411. Logger.info(TAG, 'delete filePath = ' + filePath);
  1412. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1413. //旧文件删除
  1414. this.table.deleteDataForParentPath(item.filePath, () => {
  1415. FileUtil.rmdir(filePath).then(() => {
  1416. this.videoLocalList.splice(Number(index), 1)
  1417. this.deleteCache(this.currentPath)
  1418. this.getSortedFiles(this.currentPath, true)
  1419. }).catch((error: BusinessError) => {
  1420. console.error(error.message);
  1421. });
  1422. });
  1423. } else {
  1424. this.table.deleteData(item, () => {
  1425. FileUtil.unlink(filePath)
  1426. .catch((error: BusinessError) => {
  1427. console.error(error.message);
  1428. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1429. })
  1430. .finally(() => {
  1431. this.videoLocalList.splice(Number(index), 1)
  1432. this.deleteCache(this.currentPath)
  1433. this.getSortedFiles(this.currentPath, true)
  1434. });
  1435. });
  1436. }
  1437. }
  1438. }
  1439. //重命名的对话框
  1440. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1441. DialogHelper.showTextInputDialog({
  1442. title: '重命名',
  1443. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1444. maskColor: Color.Transparent,
  1445. backgroundColor: Color.Grey,
  1446. transition: AnimationHelper.transitionInDown(666),
  1447. onChange: (text) => {
  1448. console.error("onChange: " + text);
  1449. },
  1450. onAction: (action, dialogId, content) => {
  1451. // ToastUtil.showToast('content = ' +content)
  1452. if (action == DialogAction.TWO) {
  1453. const newName = content
  1454. const newPath = this.currentPath + '/' + newName
  1455. console.log("onecold item = " + item.type);
  1456. this.doReName(index, newName, filePath, newPath, item)
  1457. }
  1458. }
  1459. })
  1460. }
  1461. //剪切 移动到另个文件夹的对话框
  1462. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1463. Logger.info('onecold showCutDialog')
  1464. let mList: Array<string> = []
  1465. let rPath = this.rootPath
  1466. if (isCurrent) {
  1467. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1468. rPath = this.currentPath
  1469. } else {
  1470. mList = Utility.getNameList(this.dirList);
  1471. rPath = this.rootPath
  1472. }
  1473. let dataBean = new BubbleBean()
  1474. dataBean.data = mList
  1475. dataBean.color = this.themeColor
  1476. dataBean.onItemClick = (i) => {
  1477. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1478. Logger.info('newPath = ' + newPath)
  1479. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1480. ToastUtil.showToast('移动成功')
  1481. this.table.deleteData(item, () => {
  1482. });
  1483. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1484. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1485. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1486. CommonConstants.TYPE_LOCAL, true);
  1487. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1488. this.table.insert(newItem, (id: number) => {
  1489. //加入数据库
  1490. });
  1491. }
  1492. this.cache.delete(this.currentPath); // 删除原路径缓存
  1493. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1494. this.getSortedFiles(this.currentPath, true)
  1495. }).catch((error: BusinessError) => {
  1496. console.error(error.message);
  1497. });
  1498. XPopup.dismissTop()
  1499. }
  1500. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1501. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1502. popupPosition = PopupPosition.TOP
  1503. }
  1504. if (index <= 3) {
  1505. popupPosition = PopupPosition.BOTTOM
  1506. }
  1507. let pup:XPopup
  1508. if(this.isDarkMode){
  1509. pup = XPopup.Builder()
  1510. .setPopupPosition(popupPosition)
  1511. .atView(id)
  1512. // .setHeight(this.isCoverOpacity()?100:420)
  1513. .setBackgroundColor(Color.Black)
  1514. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1515. .show()
  1516. }else {
  1517. pup = XPopup.Builder()
  1518. .setPopupPosition(popupPosition)
  1519. .atView(id)
  1520. // .setHeight(this.isCoverOpacity()?280:420)
  1521. .setBackgroundColor(Color.White)
  1522. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1523. .show()
  1524. }
  1525. }
  1526. //复制 到另个文件夹的对话框
  1527. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1528. Logger.info('onecoldv showCopyDialog')
  1529. let mList: Array<string> = []
  1530. let rPath = this.rootPath
  1531. if (isCurrent) {
  1532. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1533. rPath = this.currentPath
  1534. } else {
  1535. mList = Utility.getNameList(this.dirList);
  1536. rPath = this.rootPath
  1537. }
  1538. let dataBean = new BubbleBean()
  1539. dataBean.data = mList
  1540. dataBean.isCopy = true
  1541. dataBean.color = this.themeColor
  1542. dataBean.onItemClick = (i) => {
  1543. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1544. Logger.info('newPath = ' + newPath)
  1545. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1546. ToastUtil.showToast('复制成功')
  1547. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1548. this.getSortedFiles(this.currentPath)
  1549. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1550. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1551. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1552. CommonConstants.TYPE_LOCAL, true);
  1553. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1554. this.table.insert(newItem, (id: number) => {
  1555. //加入数据库
  1556. });
  1557. }
  1558. }).catch((error: BusinessError) => {
  1559. console.error(error.message);
  1560. });
  1561. XPopup.dismissTop()
  1562. }
  1563. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1564. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1565. popupPosition = PopupPosition.TOP
  1566. }
  1567. if (index <= 3) {
  1568. popupPosition = PopupPosition.BOTTOM
  1569. }
  1570. let pup:XPopup
  1571. if (this.isDarkMode) {
  1572. pup = XPopup.Builder()
  1573. .setPopupPosition(popupPosition)
  1574. .atView(id)
  1575. .setMaxHeight('60%')
  1576. .setBackgroundColor(Color.Black)
  1577. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1578. .show();
  1579. }else {
  1580. pup = XPopup.Builder()
  1581. .setPopupPosition(popupPosition)
  1582. .atView(id)
  1583. .setMaxHeight('60%')
  1584. .setBackgroundColor(Color.White)
  1585. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1586. .show();
  1587. }
  1588. }
  1589. //重命名索引index的视频
  1590. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1591. FileUtil.rename(oldPath, newPath).then(async () => {
  1592. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1593. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1594. //如果是文件夹先删除源数据,再添加新数据
  1595. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1596. if (success) {
  1597. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1598. } else {
  1599. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1600. }
  1601. });
  1602. this.scanDirectory(newPath)
  1603. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1604. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1605. if (success) {
  1606. console.log(" onecold 重命名成功,数据库已同步");
  1607. } else {
  1608. console.error(" onecold 重命名数据库失败原因: " + error);
  1609. }
  1610. });
  1611. }
  1612. let mediaItem: VideoItem =
  1613. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1614. this.videoLocalList[index] = mediaItem;
  1615. }
  1616. this.cache.delete(this.currentPath)
  1617. this.getSortedFiles(this.currentPath, true)
  1618. }).catch((error: BusinessError) => {
  1619. console.error(error.message);
  1620. });
  1621. }
  1622. build() {
  1623. Scroll() {
  1624. Column() {
  1625. Column(){
  1626. Line().width('100%').height('100%')
  1627. }
  1628. .height(this.topRectHeight)
  1629. .backgroundColor(this.isCustomizeBg?Color.Transparent:(this.isDarkMode?$r('app.color.title_bar_bg'):this.themeColor))
  1630. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1631. TitleBar({ model: $titleBarModel })
  1632. .id('pup_positon_music')
  1633. Stack() {
  1634. Column() {
  1635. XComponent({
  1636. id: 'xcomponentId',
  1637. type: 'surface',
  1638. libraryname: 'ijkplayer_napi',
  1639. controller: this.xcomponentController
  1640. })
  1641. .onLoad((event?: object) => {
  1642. if (!!event) {
  1643. this.initDelayPlay(event);
  1644. }
  1645. })
  1646. .onLoad((event?: object) => {
  1647. if (!!event) {
  1648. this.initDelayPlay(event);
  1649. }
  1650. })
  1651. .onKeyEvent((event?: KeyEvent) => {
  1652. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1653. if (!event || event.type !== KeyType.Down) {
  1654. return;
  1655. }
  1656. //空格键 Space key controls pause/play
  1657. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1658. this.playOrPause()
  1659. }
  1660. // Right-click to fast forward
  1661. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1662. this.sessionFastForwardCallback(15);
  1663. }
  1664. // Left-click to rewind
  1665. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1666. this.sessionRewindCallback(15);
  1667. }
  1668. })
  1669. .onDestroy(() => {
  1670. })
  1671. .width('100%')// .width(this.videoWidth)
  1672. .aspectRatio(this.videoAspectRatio)
  1673. }
  1674. .aspectRatio(this.videoAspectRatio)
  1675. .justifyContent(FlexAlign.Center)
  1676. .backgroundColor(Color.Transparent)
  1677. .visibility(Visibility.Hidden)
  1678. .height(CommonConstants.FULL_PERCENT)
  1679. .width(CommonConstants.FULL_PERCENT)
  1680. Stack() {
  1681. Row() {
  1682. Blank()
  1683. .layoutWeight(1)
  1684. IndexerView(
  1685. {
  1686. indexArray: DEFAULT_INDEX,
  1687. selectedIndex: this.selectedIndex,
  1688. textSize: 12,
  1689. selectedColor: "#ff419ee5",
  1690. normalColor: "#ffa0a0a0",
  1691. floatSelectedTextColor: "#ffffff",
  1692. floatSelectedViewColor: "#ff419ee5",
  1693. onIndexChanged: (index) => {
  1694. this.listScroller.scrollToIndex(index)
  1695. }
  1696. })
  1697. .width(24)
  1698. .height("50%")
  1699. }.visibility(Visibility.None)
  1700. Column() {
  1701. this.tabTitle()
  1702. this.listViewTitle()
  1703. if(this.isGridMusic){
  1704. this.getGridView()
  1705. }else {
  1706. this.getListView()
  1707. }
  1708. }
  1709. .layoutWeight(1)
  1710. .height('100%')
  1711. }
  1712. .layoutWeight(1)
  1713. .height('100%')
  1714. Row() {
  1715. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1716. .width('35%')
  1717. .height(60)
  1718. .margin({ top: 10, bottom: 10, right: 6 })
  1719. .backgroundColor(this.themeColor)
  1720. .clickEffect({level:ClickEffectLevel.HEAVY})
  1721. .onClick(() => {
  1722. if (this.isAllSelected) {
  1723. // 全不选
  1724. this.selectedFiles = [];
  1725. } else {
  1726. // 全选
  1727. this.selectedFiles = [...this.getCurFileList()];
  1728. }
  1729. this.isAllSelected = !this.isAllSelected;
  1730. })
  1731. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1732. .width('35%')
  1733. .height(60)
  1734. .id('music_cut')
  1735. .margin({ top: 10, bottom: 10, right: 6 })
  1736. .clickEffect({level:ClickEffectLevel.HEAVY})
  1737. .backgroundColor(this.themeColor)
  1738. .onClick(() => {
  1739. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1740. })
  1741. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1742. .width('35%')
  1743. .height(60)
  1744. .id('music_cut_current')
  1745. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1746. .margin({ top: 10, bottom: 10, right: 6 })
  1747. .backgroundColor(this.themeColor)
  1748. .clickEffect({level:ClickEffectLevel.HEAVY})
  1749. .onClick(() => {
  1750. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1751. })
  1752. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1753. .width('35%')
  1754. .height(60)
  1755. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1756. .margin({ top: 10, bottom: 10, right: 6 })
  1757. .backgroundColor(this.themeColor)
  1758. .clickEffect({level:ClickEffectLevel.HEAVY})
  1759. .onClick(() => {
  1760. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1761. })
  1762. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1763. .width('35%')
  1764. .height(60)
  1765. .margin({ top: 10, bottom: 10, right: 6 })
  1766. .visibility(this.isFavMusic?Visibility.None:Visibility.Visible)
  1767. .backgroundColor(this.themeColor)
  1768. .clickEffect({level:ClickEffectLevel.HEAVY})
  1769. .onClick(() => {
  1770. this.showWarnIsDelete()
  1771. })
  1772. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1773. .width('35%')
  1774. .height(60)
  1775. .margin({ top: 10, bottom: 10, right: 6 })
  1776. .backgroundColor(this.themeColor)
  1777. .clickEffect({level:ClickEffectLevel.HEAVY})
  1778. .onClick(() => {
  1779. this.selectedFiles = [];
  1780. this.isAllSelected = false
  1781. this.isMultiSelect = false
  1782. })
  1783. }
  1784. .width('100%')
  1785. .justifyContent(FlexAlign.Center)
  1786. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1787. .opacity(this.isMultiSelect ? 1 : 0)
  1788. .animation({
  1789. duration: 666,
  1790. curve: 'ease-in-out' // 可选动画曲线
  1791. })
  1792. .position({ bottom:this.isPhoneLan()?130: 168 }) // 将 Row 固定在底部
  1793. if(this.modeType==0){
  1794. Column() {
  1795. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1796. .width(130)
  1797. .height(50)
  1798. .margin({ top: 50, bottom: 40 })
  1799. .backgroundColor(this.themeColor)
  1800. .onClick(() => {
  1801. this.asyncCurrentPathData()
  1802. })
  1803. }
  1804. .height('60%')
  1805. .justifyContent(FlexAlign.Center)
  1806. .opacity(this.isZero ? 1 : 0)
  1807. .visibility(this.isZero&&!this.isFavMusic&&!this.isHistory
  1808. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1809. .animation({
  1810. duration: 666,
  1811. curve: 'ease-in-out' // 可选动画曲线
  1812. })
  1813. .width('100%')
  1814. }
  1815. }
  1816. .width('100%')
  1817. .height('100%')
  1818. .alignContent(Alignment.Top)
  1819. Column() {
  1820. this.PlayController()
  1821. }
  1822. .hitTestBehavior(HitTestMode.Transparent)
  1823. .position({ bottom: 0 }) // 将 Row 固定在底部
  1824. .opacity(this.barBottomOpacity)
  1825. }
  1826. .width('100%')
  1827. .height('100%')
  1828. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.bottom_control_background'))
  1829. .backgroundImageSize(this.isCoverOpacity()?{width:'100%'}:{ height: '100%'})
  1830. .backgroundImagePosition(Alignment.Center)
  1831. .backdropBlur(this.blurValue)
  1832. .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
  1833. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1834. }
  1835. }
  1836. asyncCurrentPathData(){
  1837. if(this.modeType==0){
  1838. workerInstance.postMessage({
  1839. code: 1,
  1840. data1: this.context,
  1841. data2: this.currentPath,
  1842. data3: this.lockPath,
  1843. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1844. });
  1845. }
  1846. }
  1847. // 处理文件选择的函数
  1848. handleFileSelection(item: VideoItem, checked: boolean) {
  1849. if (checked) {
  1850. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1851. this.selectedFiles.push(item);
  1852. }
  1853. } else {
  1854. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1855. if (index > -1) {
  1856. this.selectedFiles.splice(index, 1);
  1857. }
  1858. }
  1859. }
  1860. showWarnIsDelete() {
  1861. //操作确认类弹出框
  1862. DialogHelper.showAlertDialog({
  1863. content: "确定要删除这些文件吗?",
  1864. transition: AnimationHelper.transitionInUp(666),
  1865. maskColor: Color.Transparent,
  1866. backgroundColor: Color.Grey,
  1867. onAction: (action) => {
  1868. if (action == DialogAction.ONE) {
  1869. // ToastUtil.showToast(`您点击了取消按钮`);
  1870. } else if (action == DialogAction.TWO) {
  1871. // ToastUtil.showToast(`您点击了确认按钮`);
  1872. this.deleteMultipleFiles()
  1873. }
  1874. }
  1875. })
  1876. }
  1877. //多选删除文件
  1878. deleteMultipleFiles() {
  1879. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1880. this.selectedFiles.forEach((item) => {
  1881. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1882. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1883. this.table.deleteDataForParentPath(item.filePath, () => {
  1884. FileUtil.rmdir(item.filePath).then(() => {
  1885. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1886. this.selectedFiles = [];
  1887. this.isMultiSelect = false
  1888. this.isAllSelected = false
  1889. this.cache.delete(this.currentPath);
  1890. this.getSortedFiles(this.currentPath, true);
  1891. }).catch((error: Error) => {
  1892. console.error(error.message);
  1893. });
  1894. });
  1895. } else {
  1896. this.table.deleteData(item, () => {
  1897. FileUtil.unlink(item.filePath).catch((error: Error) => {
  1898. console.error(error.message);
  1899. }).finally(()=>{
  1900. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1901. this.selectedFiles = [];
  1902. this.isMultiSelect = false
  1903. this.isAllSelected = false
  1904. this.cache.delete(this.currentPath);
  1905. this.getSortedFiles(this.currentPath, true);
  1906. });
  1907. });
  1908. }
  1909. });
  1910. }
  1911. }
  1912. //多选移动文件
  1913. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1914. Logger.info('onecold showCutDialogForMultipleFiles')
  1915. let mList: Array<string> = []
  1916. let rPath = this.rootPath
  1917. if (isCurrent) {
  1918. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1919. rPath = this.currentPath
  1920. } else {
  1921. mList = Utility.getNameList(this.dirList);
  1922. rPath = this.rootPath
  1923. }
  1924. let dataBean = new BubbleBean();
  1925. dataBean.data = mList;
  1926. dataBean.color = this.themeColor
  1927. dataBean.onItemClick = (i) => {
  1928. const newDirPath = rPath + '/' + mList[i];
  1929. // Logger.info('newDirPath = ' + newDirPath)
  1930. this.selectedFiles.forEach((item) => {
  1931. const newPath = newDirPath + '/' + item.fileName;
  1932. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1933. ToastUtil.showToast('移动成功');
  1934. this.table.deleteData(item, () => {
  1935. this.cache.delete(this.currentPath); // 删除原路径缓存
  1936. this.cache.delete(newDirPath); // 删除目标路径缓存
  1937. this.getSortedFiles(this.currentPath, true);
  1938. });
  1939. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1940. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1941. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1942. CommonConstants.TYPE_LOCAL, true);
  1943. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1944. this.table.insert(newItem, (id: number) => {
  1945. //加入数据库
  1946. });
  1947. }
  1948. }).catch((error: Error) => {
  1949. console.error(error.message);
  1950. });
  1951. });
  1952. this.isMultiSelect = false
  1953. this.selectedFiles = [];
  1954. this.isAllSelected = false
  1955. XPopup.dismissTop();
  1956. };
  1957. let pup:XPopup
  1958. if (this.isDarkMode) {
  1959. pup = XPopup.Builder()
  1960. .setPopupPosition(PopupPosition.TOP)
  1961. .atView(viewId)
  1962. .setBackgroundColor(Color.Black)
  1963. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1964. .show();
  1965. }else {
  1966. pup = XPopup.Builder()
  1967. .setPopupPosition(PopupPosition.TOP)
  1968. .atView(viewId)
  1969. .setBackgroundColor(Color.White)
  1970. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1971. .show();
  1972. }
  1973. }
  1974. doFav(item:VideoItem){
  1975. LogUtil.info('onecold doFav isFav=' +item.isFav)
  1976. let isFav = 0
  1977. if(Utility.getIsFav(this.favList,item)){
  1978. isFav = 0
  1979. }else{
  1980. isFav = 1
  1981. }
  1982. this.table.updateIsFavByFilePath(item.filePath,isFav, async (result: boolean) => {
  1983. if(result){
  1984. if(isFav===1){
  1985. ToastUtil.showToast('收藏成功');
  1986. }else{
  1987. ToastUtil.showToast('取消收藏成功');
  1988. }
  1989. this.deleteCache(this.currentPath)
  1990. this.getFavList(false)
  1991. if(this.modeType===0&&!this.isFavMusic){
  1992. LogUtil.info('onecold doFav currentPath ='+ this.currentPath)
  1993. this.getSortedFiles(this.currentPath)
  1994. }
  1995. workerInstance.postMessage({ code: 2, data: this.context });
  1996. workerInstance.postMessage({ code: 3, data: this.context });
  1997. workerInstance.postMessage({ code: 4, data: this.context });
  1998. }
  1999. })
  2000. }
  2001. //多选复制文件
  2002. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2003. console.log('onecold showCopyDialogForMultipleFiles');
  2004. let mList: Array<string> = []
  2005. let rPath = this.rootPath
  2006. if (isCurrent) {
  2007. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2008. rPath = this.currentPath
  2009. } else {
  2010. mList = Utility.getNameList(this.dirList);
  2011. rPath = this.rootPath
  2012. }
  2013. let dataBean = new BubbleBean();
  2014. dataBean.data = mList;
  2015. dataBean.isCopy = true
  2016. dataBean.color = this.themeColor
  2017. dataBean.onItemClick = (i) => {
  2018. const newDirPath = rPath + '/' + mList[i];
  2019. // Logger.info('newDirPath = ' + newDirPath)
  2020. this.selectedFiles.forEach((item) => {
  2021. const newPath = newDirPath + '/' + item.fileName;
  2022. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2023. ToastUtil.showToast('复制成功');
  2024. this.cache.delete(newDirPath); // 删除目标路径缓存
  2025. this.getSortedFiles(this.currentPath);
  2026. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2027. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2028. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2029. CommonConstants.TYPE_LOCAL, true);
  2030. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2031. this.table.insert(newItem, (id: number) => {
  2032. //加入数据库
  2033. });
  2034. }
  2035. }).catch((error: Error) => {
  2036. console.error(error.message);
  2037. });
  2038. });
  2039. this.isMultiSelect = false
  2040. this.selectedFiles = [];
  2041. this.isAllSelected = false
  2042. XPopup.dismissTop();
  2043. };
  2044. let pup:XPopup
  2045. if (this.isDarkMode) {
  2046. pup = XPopup.Builder()
  2047. .setPopupPosition(PopupPosition.TOP)
  2048. .atView(viewId)
  2049. .setBackgroundColor(Color.Black)
  2050. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2051. .show();
  2052. }else {
  2053. pup = XPopup.Builder()
  2054. .setPopupPosition(PopupPosition.TOP)
  2055. .atView(viewId)
  2056. .setBackgroundColor(Color.White)
  2057. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2058. .show();
  2059. }
  2060. }
  2061. @Builder
  2062. private DirItem(item: VideoItem, index?: number) {
  2063. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2064. Row() {
  2065. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2066. $r('app.media.music_group'))
  2067. .height(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2068. .width(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2069. .fillColor(this.themeColor)
  2070. // .fontSize(33)
  2071. .alt($r('app.media.music_group'))
  2072. .borderRadius('100%')
  2073. .clip(true)
  2074. .margin({ left: 20, top: 8, bottom: 8 })
  2075. Column() {
  2076. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2077. .fontSize(this.twoFingerType==1?12:this.twoFingerType==2?15:18)
  2078. .maxLines(1)// .width('88%')
  2079. .animation({
  2080. duration: 555,
  2081. curve: 'ease-in-out',
  2082. })
  2083. .transition({
  2084. type: TransitionType.Insert,
  2085. opacity: 0,
  2086. translate: { x: 160 }
  2087. })
  2088. .margin({ left: 10, right: 20 })
  2089. .fontColor($r('app.color.text_color'))
  2090. Row() {
  2091. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2092. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2093. .padding({ top: 8 })
  2094. .visibility(this.modeType === 2? Visibility.Visible : Visibility.None)
  2095. .fontColor($r('app.color.text_color'))
  2096. .margin({ left: 10 })
  2097. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2098. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2099. .padding({ top: 8 })
  2100. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2101. .fontColor($r('app.color.text_color'))
  2102. .margin({ left: 10 })
  2103. Blank()
  2104. }
  2105. }
  2106. .height('100%')
  2107. .layoutWeight(1)
  2108. .justifyContent(FlexAlign.Center)
  2109. .alignItems(HorizontalAlign.Start)
  2110. Blank()
  2111. Image($r('app.media.arrow_right'))
  2112. .height(25)
  2113. .margin({ right: 10 })
  2114. .alignSelf(ItemAlign.Center)
  2115. .id(item.filePath)
  2116. }
  2117. }
  2118. .backgroundColor(Color.Transparent)
  2119. .height(this.twoFingerType==3?ITEM_HEIGHT_BIG:this.twoFingerType==2?ITEM_HEIGHT:ITEM_HEIGHT_SMALL)
  2120. .width('100%')
  2121. .visibility(this.isShowDir(item.name)?Visibility.Visible:Visibility.None)
  2122. .opacity(this.opacityItem) // 绑定透明度
  2123. }
  2124. isShowDir(dirName:string){
  2125. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2126. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2127. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2128. if(dirName ===undefined)
  2129. return true
  2130. if(dirName === LocalMusic.STR_LOCK_VIDEO){
  2131. return this.isShowSimi
  2132. }
  2133. if(dirName === LocalMusic.STR_FAC_VIDEO){
  2134. return this.isShowFAV
  2135. }
  2136. if(dirName === LocalMusic.STR_HISTORY_MUSIC){
  2137. return this.isShowHistory
  2138. }
  2139. return true
  2140. }
  2141. @State opacityItem: number = 1; // 控制透明度的状态变量
  2142. @Builder
  2143. private MusicItem(item: VideoItem, index?: number) {
  2144. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2145. Row() {
  2146. Stack() {
  2147. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2148. .fillColor(this.themeColor)
  2149. .height(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2150. .width(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  2151. .alt($r('app.media.music_red'))
  2152. .borderRadius('100%')
  2153. .clip(true)
  2154. .opacity(this.opacityItem)// 绑定透明度
  2155. .margin({ left: 20 })
  2156. }
  2157. Column() {
  2158. Column() {
  2159. Text(item.name)
  2160. .fontSize(this.twoFingerType==1?12:this.twoFingerType==2?15:18)
  2161. .maxLines(1)
  2162. .animation({
  2163. duration: 555,
  2164. curve: 'Linear',
  2165. })
  2166. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2167. $r('app.color.text_color'))
  2168. .margin({ left:this.twoFingerType==3?18: 10 })
  2169. Row() {
  2170. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2171. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2172. .padding({ top: 8 })
  2173. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2174. $r('app.color.text_color'))
  2175. .margin({ left:this.twoFingerType==3?18: 10})
  2176. Blank()
  2177. Text(item.size)
  2178. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  2179. .padding({ top: 8 })
  2180. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2181. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2182. $r('app.color.text_color'))
  2183. .margin({ left: 10 })
  2184. }
  2185. }
  2186. .height('100%')
  2187. .width('100%')
  2188. .justifyContent(FlexAlign.Center)
  2189. .alignItems(HorizontalAlign.Start)
  2190. }
  2191. .height('100%')
  2192. .width('65%')
  2193. Column() {
  2194. Checkbox({ name: 'checkbox' + index })
  2195. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2196. .selectedColor(this.themeColor)
  2197. .shape(CheckBoxShape.CIRCLE)
  2198. .opacity(this.isMultiSelect ? 1 : 0)
  2199. .animation({
  2200. duration: 666,
  2201. curve: 'Smooth' // 可选动画曲线
  2202. })
  2203. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2204. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2205. .margin({ left: 20, top: 8, bottom: 8 })
  2206. .width(22)
  2207. .height(22)
  2208. ImageAnimator()
  2209. .images(this.imagesF)// 动画数组
  2210. .duration(1000)// 持续
  2211. .state(this.animationState)// 动画状态
  2212. .fillMode(FillMode.Forwards)
  2213. .width(18)
  2214. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2215. Visibility.None)
  2216. .height(18)
  2217. .iterations(-1) // 播放次数
  2218. }
  2219. .width('18%')
  2220. }
  2221. }
  2222. .backgroundColor(Color.Transparent)
  2223. .width('100%')
  2224. .height(this.twoFingerType==3?ITEM_HEIGHT_BIG:this.twoFingerType==2?ITEM_HEIGHT:ITEM_HEIGHT_SMALL)
  2225. }
  2226. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2227. @Builder
  2228. tabTitle() {
  2229. Column() {
  2230. // 使用 Stack 布局来实现绝对定位效果
  2231. Stack() {
  2232. // 背景动画容器
  2233. Row() {
  2234. ForEach(this.tabs, (i: string, index) => {
  2235. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2236. Flex()
  2237. .backgroundColor(this.isDarkMode?$r('app.color.tab_item_bg'):this.themeColor)
  2238. .borderRadius(20)
  2239. .padding(10)
  2240. .margin(6)
  2241. .width('100%')
  2242. .height('100%')
  2243. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2244. .opacity(this.modeType === index ? 1 : 0)
  2245. .animation({
  2246. duration: 666,
  2247. playMode: PlayMode.Normal,
  2248. curve: 'ease-in-out'
  2249. });
  2250. }
  2251. .layoutWeight(1)
  2252. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?30:5,
  2253. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?30:5, bottom: 1 });
  2254. });
  2255. }
  2256. .width('100%')
  2257. .height(50);
  2258. // 导航栏容器
  2259. Row() {
  2260. ForEach(this.tabs, (item: string, index) => {
  2261. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2262. Text(item)
  2263. .fontSize(16)
  2264. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2265. .padding(15)
  2266. .onClick(() => {
  2267. this.modeType = index;
  2268. this.onModeChange();
  2269. });
  2270. }
  2271. .layoutWeight(1)
  2272. .stateStyles({
  2273. pressed: { opacity: 0.6 } // 按压反馈
  2274. });
  2275. });
  2276. }
  2277. .width('100%')
  2278. .height(this.topBarHeight)
  2279. .opacity(this.barOpacity)
  2280. .backgroundColor(Color.Transparent);
  2281. }
  2282. .width('100%')
  2283. .height(this.topBarHeight)
  2284. .opacity(this.barOpacity)
  2285. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  2286. .opacity(this.barOpacity)
  2287. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  2288. }
  2289. .visibility(this.isShowTitleBar?Visibility.Visible:Visibility.None)
  2290. }
  2291. @Builder
  2292. listViewTitle() {
  2293. Column() {
  2294. Row({ space: 8 }) {
  2295. Row({ space: 8 }) {
  2296. Image($r("app.media.hm_playlist"))
  2297. .width(25)
  2298. .margin({ left: 8 })
  2299. .fillColor(this.themeColor)
  2300. Text(`共找到${this.artistList.length}位艺术家`)
  2301. .fontColor($r('app.color.text_color'))
  2302. .fontSize(14)
  2303. .opacity(this.opacityItem)
  2304. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2305. Text(`共找到${this.albumList.length}张专辑`)
  2306. .fontColor($r('app.color.text_color'))
  2307. .opacity(this.opacityItem)
  2308. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2309. .fontSize(14)
  2310. }
  2311. .layoutWeight(1)
  2312. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2313. Row() {
  2314. TextInput({
  2315. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2316. text: this.searchText
  2317. })
  2318. .height(35)
  2319. .onChange((value: string) => {
  2320. this.onSearchInput(value);
  2321. })
  2322. .layoutWeight(1)
  2323. Text(`取消`)
  2324. .margin({ left: 10, right: 10 })
  2325. .fontColor($r('app.color.text_color'))
  2326. .fontSize(16)
  2327. .onClick(() => {
  2328. this.isSearchMode = false
  2329. this.searchText = ''
  2330. if (this.modeType === 2) {
  2331. this.updateListData(this.artistList)
  2332. } else {
  2333. this.updateListData(this.albumList)
  2334. }
  2335. })
  2336. }
  2337. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2338. .animation({
  2339. duration: 666,
  2340. curve: 'ease-in-out' // 可选动画曲线
  2341. })
  2342. Blank()
  2343. Image($r("app.media.search"))
  2344. .width(25)
  2345. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2346. .animation({
  2347. duration: 666,
  2348. curve: 'ease-in-out' // 可选动画曲线
  2349. })// .opacity(this.opacityItem)
  2350. .fillColor(this.themeColor)
  2351. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2352. .onClick(() => {
  2353. this.isSearchMode = true
  2354. })
  2355. Image($r("app.media.top_rank"))
  2356. .width(25)// .opacity(this.opacityItem)
  2357. .fillColor(this.themeColor)
  2358. .animation({
  2359. duration: 666,
  2360. curve: 'ease-in-out' // 可选动画曲线
  2361. })
  2362. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2363. .onClick(() => {
  2364. this.showRankDialog()
  2365. })
  2366. Image(this.isGridMusic?$r('app.media.list'):$r("app.media.grid"))
  2367. .width(25)
  2368. .animation({
  2369. duration: 666,
  2370. curve: 'ease-in-out' // 可选动画曲线
  2371. })
  2372. .fillColor(this.themeColor)
  2373. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2374. .onClick(() => {
  2375. this.isGridMusic = !this.isGridMusic
  2376. })
  2377. }
  2378. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2379. Visibility.None)
  2380. .width('100%')
  2381. .padding(10)
  2382. .height(50)
  2383. .border({
  2384. width: { bottom: 1 },
  2385. color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
  2386. })
  2387. Row({ space: 8 }) {
  2388. Row({ space: 8 }) {
  2389. Image($r("app.media.hm_play"))
  2390. .width(25)
  2391. .margin({ left: 8 })
  2392. .fillColor(this.themeColor)
  2393. Text(`播放全部`)
  2394. .fontColor($r('app.color.text_color'))
  2395. .fontSize(14)
  2396. .animation({
  2397. duration: 666,
  2398. curve: 'ease-in-out' // 可选动画曲线
  2399. })
  2400. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2401. .fontColor($r('app.color.text_color'))
  2402. .fontSize(14)
  2403. .opacity(this.opacityItem)
  2404. .animation({
  2405. duration: 666,
  2406. curve: 'ease-in-out' // 可选动画曲线
  2407. })
  2408. }
  2409. .clickEffect({level:ClickEffectLevel.LIGHT})
  2410. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2411. .animation({
  2412. duration: 666,
  2413. curve: 'ease-in-out' // 可选动画曲线
  2414. })
  2415. .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2416. .onTouch((event: TouchEvent) => {
  2417. if (event.type === TouchType.Down) {
  2418. this.isClickedPLayAll = true;
  2419. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2420. this.isClickedPLayAll = false;
  2421. }
  2422. })
  2423. .onClick(() => {
  2424. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2425. if (this.modeType === 0) {
  2426. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2427. this.doPlay(this.getCurFileList()[0])
  2428. }
  2429. } else {
  2430. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2431. this.doPlay(this.mediaKuList[0])
  2432. }
  2433. }
  2434. })
  2435. Row() {
  2436. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2437. .height(35)
  2438. .onChange((value: string) => {
  2439. this.onSearchInput(value);
  2440. })
  2441. .layoutWeight(1)
  2442. Text(`取消`)
  2443. .margin({ left: 10, right: 10 })
  2444. .fontColor($r('app.color.text_color'))
  2445. .fontSize(16)
  2446. .onClick(() => {
  2447. this.isSearchMode = false
  2448. this.searchText = ''
  2449. this.updateListData(this.mediaKuList)
  2450. })
  2451. }
  2452. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2453. .animation({
  2454. duration: 666,
  2455. curve: 'ease-in-out' // 可选动画曲线
  2456. })
  2457. Blank()
  2458. Image($r("app.media.search"))
  2459. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2460. .animation({
  2461. duration: 666,
  2462. curve: 'ease-in-out' // 可选动画曲线
  2463. })// .opacity(this.opacityItem)
  2464. .fillColor(this.themeColor)
  2465. .clickEffect({level:ClickEffectLevel.LIGHT})
  2466. .onClick(() => {
  2467. this.isSearchMode = true
  2468. })
  2469. Image($r("app.media.refresh"))
  2470. .fillColor(this.themeColor)
  2471. .width(25)
  2472. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2473. .animation({
  2474. duration: 666,
  2475. curve: 'ease-in-out' // 可选动画曲线
  2476. })
  2477. .clickEffect({level:ClickEffectLevel.LIGHT})
  2478. .onClick(() => {
  2479. if(this.isFavMusic){
  2480. this.getFavList(true)
  2481. }else{
  2482. this.deleteCache(this.currentPath)
  2483. this.getSortedFiles(this.currentPath)
  2484. }
  2485. })
  2486. Image($r("app.media.top_rank"))
  2487. .width(25)
  2488. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2489. Visibility.Visible)// .opacity(this.opacityItem)
  2490. .animation({
  2491. duration: 666,
  2492. curve: 'ease-in-out' // 可选动画曲线
  2493. })
  2494. .fillColor(this.themeColor)
  2495. .clickEffect({level:ClickEffectLevel.HEAVY})
  2496. .onClick(() => {
  2497. this.showRankDialog()
  2498. })
  2499. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2500. .width(24)
  2501. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2502. .animation({
  2503. duration: 666,
  2504. curve: 'ease-in-out' // 可选动画曲线
  2505. })
  2506. .fillColor(this.themeColor)
  2507. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2508. .onClick(() => {
  2509. this.isMultiSelect = !this.isMultiSelect
  2510. })
  2511. SymbolGlyph($r('sys.symbol.trash'))
  2512. .fontColor([this.themeColor])
  2513. .fontSize(25)
  2514. .effectStrategy(1)
  2515. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2516. .animation({
  2517. duration: 666,
  2518. curve: 'ease-in-out' // 可选动画曲线
  2519. })
  2520. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2521. .onClick(() => {
  2522. this.clearVideoHistory() //清空播放记录
  2523. })
  2524. Image(this.isGridMusic?$r('app.media.list'):$r("app.media.grid"))
  2525. .width(24)
  2526. .animation({
  2527. duration: 666,
  2528. curve: 'ease-in-out' // 可选动画曲线
  2529. })
  2530. .fillColor(this.themeColor)
  2531. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2532. .onClick(() => {
  2533. this.isGridMusic = !this.isGridMusic
  2534. })
  2535. }
  2536. .width('100%')
  2537. .padding(10)
  2538. .height(50)
  2539. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2540. .border({
  2541. width: { bottom: 1 },
  2542. color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
  2543. })
  2544. }
  2545. .height(this.topBarHeight)
  2546. .opacity(this.barOpacity)
  2547. .visibility(this.isShowAllBar?Visibility.Visible:Visibility.None)
  2548. }
  2549. //搜索功能的实现
  2550. @State searchText: string = ''; // 用户输入内容
  2551. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2552. @State isSearchMode: boolean = false
  2553. // 实时搜索逻辑(带防抖)
  2554. private onSearchInput(value: string) {
  2555. this.searchText = value.trim();
  2556. let mSearchList: Array<VideoItem> = []
  2557. switch (this.modeType) {
  2558. case 0:
  2559. mSearchList = this.videoLocalList
  2560. break;
  2561. case 1:
  2562. mSearchList = this.mediaKuList
  2563. break;
  2564. case 2:
  2565. mSearchList = this.artistList
  2566. break;
  2567. case 3:
  2568. mSearchList = this.albumList
  2569. break;
  2570. }
  2571. // 新增条件判断:空输入时显示所有数据
  2572. if (this.searchText === '') {
  2573. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2574. } else {
  2575. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2576. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2577. });
  2578. }
  2579. this.updateListData(this.filteredList);
  2580. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2581. }
  2582. @State dragItem: number = -1
  2583. @State scaleItem: number = -1
  2584. @State neighborItem: number = -1
  2585. @State neighborScale: number = -1
  2586. @State offsetY: number = 0
  2587. private dragRefOffset: number = 0
  2588. private ITEM_INTV: number = 78
  2589. scaleSelect(item: number): number {
  2590. if (this.scaleItem === item) {
  2591. return 1.05
  2592. } else if (this.neighborItem === item) {
  2593. return this.neighborScale
  2594. } else {
  2595. return 1
  2596. }
  2597. }
  2598. itemMove(index: number, newIndex: number): void {
  2599. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2600. return;
  2601. }
  2602. let tmp = this.videoLocalList.splice(index, 1);
  2603. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2604. this.dataSource.pushArrayData(this.videoLocalList)
  2605. }
  2606. // Grid布局的开始
  2607. private dragRefOffSetX: number = 0;
  2608. private dragRefOffSetY: number = 0;
  2609. private FIX_VP_X: number = 180;
  2610. private FIX_VP_Y: number = 84;
  2611. isDraggable(index: number): boolean {
  2612. return index >= 0;
  2613. }
  2614. getRowEnd(item: number) {
  2615. if (item.toString() === '0') {
  2616. return 1;
  2617. } else {
  2618. return 0;
  2619. }
  2620. }
  2621. // [Start itemMove_start]
  2622. // itemMoveGrid(index: number, newIndex: number): void {
  2623. // if (!this.isDraggable(newIndex)) {
  2624. // return;
  2625. // }
  2626. // let tmp = this.videoLocalList.splice(index, 1);
  2627. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2628. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2629. // }
  2630. isInLeft(index: number) {
  2631. return index % 2 == 0;
  2632. }
  2633. down(index: number): void {
  2634. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2635. return;
  2636. }
  2637. this.offsetY -= this.FIX_VP_Y;
  2638. this.dragRefOffSetY += this.FIX_VP_Y;
  2639. this.itemMove(index, index + 1);
  2640. }
  2641. up(index: number): void {
  2642. if (!this.isDraggable(index - 2)) {
  2643. return;
  2644. }
  2645. this.offsetY += this.FIX_VP_Y;
  2646. this.dragRefOffSetY -= this.FIX_VP_Y;
  2647. this.itemMove(index, index - 1);
  2648. }
  2649. left(index: number): void {
  2650. if (this.isInLeft(index)) {
  2651. return;
  2652. }
  2653. if (!this.isDraggable(index - 1)) {
  2654. return;
  2655. }
  2656. this.offsetX += this.FIX_VP_X;
  2657. this.dragRefOffSetX -= this.FIX_VP_X;
  2658. this.itemMove(index, index - 1)
  2659. }
  2660. right(index: number): void {
  2661. if (!this.isInLeft(index)) {
  2662. return;
  2663. }
  2664. if (!this.isDraggable(index + 1)) {
  2665. return;
  2666. }
  2667. this.offsetX -= this.FIX_VP_X;
  2668. this.dragRefOffSetX += this.FIX_VP_X;
  2669. this.itemMove(index, index + 1)
  2670. }
  2671. private scroller: Scroller = new Scroller();
  2672. @State startIndex:number = 0
  2673. @State endIndex:number = 0
  2674. @State scaleValue:number = 1
  2675. @State pinchValue:number = 1
  2676. @Builder
  2677. getGridView(){
  2678. Grid(this.scroller) {
  2679. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  2680. GridItem() {
  2681. Stack({ alignContent: Alignment.Center }) {
  2682. this.MusicItemGrid(item,index)
  2683. }
  2684. }
  2685. // .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  2686. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  2687. TransitionEffect.scale({ x: 0, y: 0 }) ))
  2688. .clickEffect({level:ClickEffectLevel.LIGHT})
  2689. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  2690. .zIndex(this.dragItem === index ? 1 : 0)
  2691. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  2692. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  2693. //长按拖动代码
  2694. .gesture(
  2695. GestureGroup(GestureMode.Sequence,
  2696. LongPressGesture({ repeat: true })
  2697. .onAction(() => {
  2698. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2699. this.scaleItem = index;
  2700. })
  2701. })
  2702. .onActionEnd(() => {
  2703. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2704. this.scaleItem = -1;
  2705. })
  2706. }),
  2707. PanGesture({ fingers: 1, direction: null, distance: 0 })
  2708. .onActionStart(() => {
  2709. this.dragItem = index;
  2710. this.dragRefOffSetX = 0;
  2711. this.dragRefOffSetY = 0;
  2712. })
  2713. .onActionUpdate((event: GestureEvent) => {
  2714. this.offsetX = event.offsetX - this.dragRefOffSetX;
  2715. this.offsetY = event.offsetY - this.dragRefOffSetY;
  2716. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2717. let index = this.videoLocalList.indexOf(item);
  2718. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2719. this.down(index);
  2720. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2721. this.up(index);
  2722. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2723. this.right(index);
  2724. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2725. this.left(index);
  2726. }
  2727. })
  2728. // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  2729. // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  2730. // }
  2731. })
  2732. .onActionEnd(() => {
  2733. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2734. this.dragItem = -1;
  2735. })
  2736. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  2737. this.scaleItem = -1;
  2738. })
  2739. })
  2740. )
  2741. .onCancel(() => {
  2742. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2743. this.dragItem = -1;
  2744. })
  2745. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  2746. this.scaleItem = -1;
  2747. })
  2748. })
  2749. )
  2750. // [End gesture_start]
  2751. // [EndExclude GridItem_start]
  2752. }, (item: VideoItem) => item.filePath)
  2753. }
  2754. .width('94%')
  2755. .height('100%')
  2756. .editMode(true)
  2757. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  2758. .animation({ duration: 500, curve: Curve.Ease }))
  2759. .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  2760. .layoutWeight(1)
  2761. .scrollBar(BarState.Off)
  2762. .supportAnimation(true)
  2763. .cachedCount(3)
  2764. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  2765. .columnsTemplate(this.twoFingerType==3?'repeat(auto-fit, 160)':this.twoFingerType==2?'repeat(auto-fit, 110)':'repeat(auto-fit, 80)')
  2766. .rowsGap(this.twoFingerType==3?10:this.twoFingerType==2?5:1)
  2767. .visibility(this.isGridMusic?Visibility.Visible:Visibility.None)
  2768. .scale({x:this.scaleValue,y:this.scaleValue,z:1})
  2769. .gesture(PinchGesture({ fingers: 2 })
  2770. .onActionEnd((event: GestureEvent)=>{
  2771. this.setGridTwoFingers()
  2772. })
  2773. .onActionUpdate(e=>{
  2774. this.scaleValue = this.pinchValue*e.scale
  2775. })
  2776. .onActionStart(e => {
  2777. }))
  2778. .enableScrollInteraction(true)
  2779. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  2780. .onScrollIndex((start: number, end: number) => {
  2781. this.startIndex = start
  2782. this.endIndex = end
  2783. })
  2784. .onScrollFrameBegin((offset: number) => {
  2785. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  2786. if(this.isPhoneLan()){
  2787. this.setBarHeightHide(offset)
  2788. }else if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  2789. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  2790. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  2791. if(this.isScrollHide){
  2792. this.setBarHeightHide2(offset)
  2793. }else{
  2794. this.setBarHeightNormal()
  2795. }
  2796. }else{
  2797. this.setBarHeightHide(offset)
  2798. }
  2799. return { offsetRemain: offset };
  2800. })
  2801. }
  2802. setGridTwoFingers(){
  2803. this.pinchValue = this.scaleValue;
  2804. Logger.info('this.pinchValue = '+this.pinchValue);
  2805. if(this.pinchValue >=1){
  2806. this.twoFingerType ++
  2807. Logger.info('this.twoFingerType1 = '+this.twoFingerType);
  2808. if(this.twoFingerType > 3){
  2809. this.twoFingerType = 3
  2810. }
  2811. }else{
  2812. this.twoFingerType --
  2813. Logger.info('this.twoFingerType2 = '+this.twoFingerType);
  2814. if(this.twoFingerType < 1){
  2815. this.twoFingerType = 3
  2816. this.isGridMusic = false
  2817. }
  2818. }
  2819. this.pinchValue = 1;
  2820. this.scaleValue = 1;
  2821. }
  2822. @State longItemFilePath:string =''
  2823. @State tempLyricContent:string = ''
  2824. @Builder
  2825. private MusicItemGrid(item: VideoItem, index: number) {
  2826. Button({ type: ButtonType.Normal, stateEffect: false }) {
  2827. Stack() {
  2828. Column() {
  2829. Image(StrUtil.isEmpty(item.pixelMapPath) ?Utility.getMusisBg2(index) : item.pixelMapPath)
  2830. .height(this.getGridHeight())
  2831. .width(this.getGridWight())
  2832. .alt($r('app.media.ic_avatar6'))
  2833. .clip(true)
  2834. .borderRadius({
  2835. topLeft: 12,
  2836. topRight : 12,
  2837. bottomLeft: 0,
  2838. bottomRight: 0
  2839. })
  2840. .draggable(false)
  2841. .opacity(this.opacityItem)// 绑定透明度
  2842. .animation({ curve: Curve.Sharp, duration: 300 })
  2843. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20 ,
  2844. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20})
  2845. Column() {
  2846. Text(item.name.startsWith('.')?item.name.replace(/\./g, ''):item.name)
  2847. .fontSize(this.twoFingerType==1?14:this.twoFingerType==2?16:18)
  2848. .maxLines(1)
  2849. .fontWeight(FontWeight.Bold)
  2850. .textOverflow({overflow: TextOverflow.MARQUEE}) //超长滚动
  2851. .animation({
  2852. duration: 555,
  2853. curve: 'Linear',
  2854. })
  2855. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2856. $r('app.color.text_color'))
  2857. Column(){
  2858. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2859. .fontSize(11)
  2860. .fontSize(this.twoFingerType==1?10:this.twoFingerType==2?12:14)
  2861. .visibility(this.modeType===2&&!this.isCanBack?Visibility.Visible:Visibility.None)
  2862. .fontColor($r('app.color.text_color'))
  2863. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2864. .fontSize(11)
  2865. .fontSize(this.twoFingerType==1?10:this.twoFingerType==2?12:14)
  2866. .visibility(this.modeType===3&&!this.isCanBack?Visibility.Visible:Visibility.None)
  2867. .fontColor($r('app.color.text_color'))
  2868. Text(StrUtil.isEmpty(item.artist) ? 'Unknown' : item.artist )
  2869. .fontSize(11)
  2870. .fontSize(this.twoFingerType==1?10:this.twoFingerType==2?12:14)
  2871. .maxLines(1)
  2872. .margin({top:2})
  2873. .visibility(item.type==CommonConstants.TYPE_IS_ARTIST
  2874. ||item.type==CommonConstants.TYPE_IS_ALBUM
  2875. ||item.type==CommonConstants.TYPE_IS_DIR?Visibility.None:Visibility.Visible)
  2876. .fontWeight(FontWeight.Medium)
  2877. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor:
  2878. $r('app.color.text_color'))
  2879. }
  2880. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  2881. }
  2882. .bindPopup(this.longItemFilePath === item.filePath, {
  2883. builder: this.MenuBuilder(item,index,item.filePath),
  2884. placement: Placement.Top,
  2885. // autoCancel: true,
  2886. mask: {color:'#33000000'},
  2887. // popupColor: Color.Yellow,
  2888. enableArrow: false,//是否显示箭头
  2889. showInSubWindow: false,
  2890. onStateChange: (e) => {
  2891. if (!e.isVisible) {
  2892. this.longItemFilePath = ''
  2893. this.tempLyricContent = ''
  2894. }
  2895. }
  2896. })
  2897. .gesture(LongPressGesture()
  2898. .onAction(async () => {
  2899. //如果是专辑和艺术家的首页,不能长按
  2900. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2901. return
  2902. //如果是我的收藏 最近播放等也不能长按
  2903. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2904. item.name === LocalMusic.STR_HISTORY_MUSIC
  2905. )
  2906. return
  2907. this.longItemFilePath = item.filePath
  2908. this.tempLyricContent = await this.getLyricContent(item)
  2909. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2910. })
  2911. .onActionEnd((event: GestureEvent) => {
  2912. })
  2913. )
  2914. .height(this.twoFingerType==3?60:this.twoFingerType==2?55:42)
  2915. .width(this.getGridWight())
  2916. .justifyContent(FlexAlign.Center)
  2917. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20 ,
  2918. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20})
  2919. }
  2920. .width(this.getGridWight())
  2921. .borderRadius(12)
  2922. .backgroundImage(item.pixelMapPath)
  2923. .backgroundImageSize({ height: '100%',width:'100%' })
  2924. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  2925. .animation({ curve: Curve.Sharp, duration: 300 })
  2926. Checkbox({ name: 'checkbox' + index })
  2927. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  2928. .selectedColor(this.themeColor)
  2929. .shape(CheckBoxShape.CIRCLE)
  2930. .opacity(this.isMultiSelect ? 1 : 0)
  2931. .animation({
  2932. duration: 666,
  2933. curve: 'Smooth' // 可选动画曲线
  2934. })
  2935. .visibility(this.isMultiSelect&&item.type!==CommonConstants.TYPE_IS_DIR?Visibility.Visible:Visibility.None)
  2936. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2937. .margin({ left: 20, top: 8, bottom: 8 })
  2938. .width(38)
  2939. .height(38)
  2940. }
  2941. }
  2942. .backgroundColor(Color.Transparent)
  2943. .width('100%')
  2944. .padding({top:15})
  2945. .height(this.getGridAllHeight())
  2946. .onClick(() => {
  2947. if(this.isMultiSelect&&item.type!==CommonConstants.TYPE_IS_DIR){
  2948. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  2949. this.handleFileSelection(item, !isChecked);
  2950. }else{
  2951. this.doPlay(item, index)
  2952. }
  2953. })
  2954. }
  2955. getGridAllHeight(){
  2956. let heightG = 222
  2957. switch (this.twoFingerType){
  2958. case 1:
  2959. heightG = 118
  2960. break;
  2961. case 2:
  2962. heightG = 168
  2963. break;
  2964. case 3:
  2965. heightG = 222
  2966. break;
  2967. }
  2968. return heightG
  2969. }
  2970. getGridHeight(){
  2971. let heightG = 150
  2972. switch (this.twoFingerType){
  2973. case 1:
  2974. heightG = 55
  2975. break;
  2976. case 2:
  2977. heightG = 100
  2978. break;
  2979. case 3:
  2980. heightG = 150
  2981. break;
  2982. }
  2983. return heightG
  2984. }
  2985. getGridWight(){
  2986. let wightG = 158
  2987. switch (this.twoFingerType){
  2988. case 1:
  2989. wightG = 80
  2990. break;
  2991. case 2:
  2992. wightG = 110
  2993. break;
  2994. case 3:
  2995. wightG = 158
  2996. break;
  2997. }
  2998. return wightG
  2999. }
  3000. @Builder
  3001. MenuBuilder(item: VideoItem,index: number,filePath:string) {
  3002. Scroll(){
  3003. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3004. Menu() {
  3005. MenuItem({
  3006. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList,item)?$r('sys.symbol.heart_fill'):$r('sys.symbol.heart')),
  3007. content: Utility.getIsFav(this.favList,item)?'取消收藏':'收藏' })
  3008. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3009. .onClick(() => {
  3010. if(item){
  3011. this.doFav(item)
  3012. }
  3013. this.longItemFilePath = ''
  3014. })
  3015. MenuItem({ symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3016. content: '下一首播放' })
  3017. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3018. .onClick(() => {
  3019. this.addToNextPlay(item);
  3020. this.longItemFilePath = ''
  3021. })
  3022. MenuItem({ symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3023. content: '编辑信息' })
  3024. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3025. height:this.isCoverOpacity()?'95%': '88%',
  3026. dragBar: true,
  3027. showClose: true,
  3028. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  3029. title: { title: '编辑信息' }
  3030. })
  3031. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3032. .onClick(() => {
  3033. this.isShowEdit = !this.isShowEdit;
  3034. })
  3035. MenuItem({
  3036. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3037. content: $r('app.string.rename')
  3038. })
  3039. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3040. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3041. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3042. .onClick(() => {
  3043. this.showReNameDialog(item, index + '', filePath)
  3044. this.longItemFilePath = ''
  3045. })
  3046. MenuItem({
  3047. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3048. content: $r('app.string.delete')
  3049. })
  3050. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3051. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3052. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3053. .onClick(() => {
  3054. this.showWarnIsDeleteFile(item, index + '', filePath)
  3055. this.longItemFilePath = ''
  3056. })
  3057. MenuItem({
  3058. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3059. content: $r('app.string.share')
  3060. })
  3061. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3062. .onClick(() => {
  3063. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3064. this.longItemFilePath = ''
  3065. })
  3066. }
  3067. .font({ size: 15, weight: FontWeight.Normal })
  3068. }
  3069. .width(180)
  3070. }
  3071. .height(item.type === CommonConstants.TYPE_IS_DIR ?'22%':'40%')
  3072. }
  3073. private listMaxScrollOffsetY: number = 0
  3074. @State selectedIndex: number = -1
  3075. setlistTwoFingers() {
  3076. this.pinchValue = this.scaleValue;
  3077. Logger.info('this.pinchValue = ' + this.pinchValue);
  3078. if (this.pinchValue >= 1) {
  3079. this.twoFingerType++
  3080. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3081. if (this.twoFingerType > 3) {
  3082. this.twoFingerType = 1
  3083. this.isGridMusic = true
  3084. }
  3085. } else {
  3086. this.twoFingerType--
  3087. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3088. if (this.twoFingerType < 1) {
  3089. this.twoFingerType = 1
  3090. }
  3091. }
  3092. this.pinchValue = 1;
  3093. this.scaleValue = 1;
  3094. }
  3095. @Builder
  3096. getListView() {
  3097. List({ scroller: this.listScroller }) {
  3098. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3099. ListItem() {
  3100. Column() {
  3101. if (item.type === CommonConstants.TYPE_IS_DIR
  3102. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3103. this.DirItem(item, index)
  3104. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3105. } else {
  3106. this.MusicItem(item, index)
  3107. }
  3108. }
  3109. .shadow(this.scaleItem === index ? {
  3110. radius: 70,
  3111. color: '#15000000',
  3112. offsetX: 0,
  3113. offsetY: 0
  3114. } :
  3115. {
  3116. radius: 0,
  3117. color: '#15000000',
  3118. offsetX: 0,
  3119. offsetY: 0
  3120. })
  3121. .animation({ curve: Curve.Sharp, duration: 300 })
  3122. }
  3123. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3124. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3125. TransitionEffect.scale({ x: 0, y: 0 }) ))
  3126. .clickEffect({level:ClickEffectLevel.LIGHT})
  3127. .swipeAction((
  3128. (this.modeType==0||this.modeType==1 ||((this.modeType==3||this.modeType==2)&&this.isCanBack))
  3129. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3130. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3131. .onClick(() => {
  3132. if(this.isMultiSelect&&item.type!==CommonConstants.TYPE_IS_DIR){
  3133. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3134. this.handleFileSelection(item, !isChecked);
  3135. }else{
  3136. this.doPlay(item, index)
  3137. }
  3138. })
  3139. //拖动List关键代码开始
  3140. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3141. .zIndex(this.dragItem === index ? 1 : 0)
  3142. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3143. .gesture(
  3144. GestureGroup(GestureMode.Sequence,
  3145. LongPressGesture({ repeat: true })
  3146. .onAction((event?: GestureEvent) => {
  3147. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3148. this.scaleItem = index
  3149. })
  3150. })
  3151. .onActionEnd(() => {
  3152. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3153. this.scaleItem = -1
  3154. })
  3155. }),
  3156. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3157. .onActionStart(() => {
  3158. this.dragItem = index // 记录当前拖动项索引
  3159. this.dragRefOffset = 0 // 重置偏移基准
  3160. })
  3161. .onActionUpdate((event: GestureEvent) => {
  3162. this.offsetY = event.offsetY - this.dragRefOffset;
  3163. this.neighborItem = -1;
  3164. let indexA = this.videoLocalList.indexOf(item);
  3165. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3166. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3167. let value: number = 0;
  3168. if (this.offsetY < 0) {
  3169. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3170. this.neighborItem = indexA - 1;
  3171. this.neighborScale = 1 - value / 20;
  3172. } else if (this.offsetY > 0) {
  3173. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3174. this.neighborItem = indexA + 1;
  3175. this.neighborScale = 1 - value / 20;
  3176. }
  3177. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3178. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3179. this.offsetY -= this.ITEM_INTV;
  3180. this.dragRefOffset += this.ITEM_INTV;
  3181. this.itemMove(indexA, indexA + 1);
  3182. });
  3183. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3184. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3185. this.offsetY += this.ITEM_INTV;
  3186. this.dragRefOffset -= this.ITEM_INTV;
  3187. this.itemMove(indexA, indexA - 1);
  3188. });
  3189. }
  3190. let curListOffset = this.listScroller.currentOffset()
  3191. // 获取手指信息
  3192. let fingerInfo = event.fingerList[0]
  3193. let clickPercentY =
  3194. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3195. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3196. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3197. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3198. this.listScroller.scrollTo({xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity})
  3199. }
  3200. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3201. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3202. if (curListOffset.yOffset > scrollVelocity + 5) {
  3203. this.listScroller.scrollTo({xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity})
  3204. }
  3205. }
  3206. })
  3207. .onActionEnd((event: GestureEvent) => {
  3208. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3209. this.dragItem = -1
  3210. this.neighborItem = -1
  3211. })
  3212. animateTo({
  3213. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3214. }, () => {
  3215. this.scaleItem = -1
  3216. })
  3217. })
  3218. )
  3219. .onCancel(() => {
  3220. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3221. this.dragItem = -1
  3222. this.neighborItem = -1
  3223. })
  3224. animateTo({
  3225. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3226. }, () => {
  3227. this.scaleItem = -1
  3228. })
  3229. })
  3230. ) //拖动List关键代码结束
  3231. }, (item: VideoItem) => item.filePath)
  3232. }
  3233. .scale({x:this.scaleValue,y:this.scaleValue,z:1})
  3234. .gesture(PinchGesture({ fingers: 2 })
  3235. .onActionEnd((event: GestureEvent)=>{
  3236. this.setlistTwoFingers()
  3237. })
  3238. .onActionUpdate(e=>{
  3239. this.scaleValue = this.pinchValue*e.scale
  3240. })
  3241. .onActionStart(e => {
  3242. }))
  3243. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3244. .margin({ bottom: this.isCoverOpacity() ? 80 : 166 })
  3245. .cachedCount(6)
  3246. .borderRadius(20)
  3247. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3248. .animation({ duration: 500, curve: Curve.Ease }))
  3249. .layoutWeight(1)
  3250. .onScrollIndex((start) => {
  3251. this.selectedIndex = start
  3252. })
  3253. .visibility(this.isGridMusic?Visibility.None:Visibility.Visible)
  3254. .lanes(
  3255. new BreakpointType<number>({
  3256. sm: 1,
  3257. md: 2,
  3258. lg: 3,
  3259. xl: 4,
  3260. xxl: 4
  3261. }).getValue(this.currentBreakpoint),
  3262. new BreakpointType<number>({
  3263. sm: 0,
  3264. md: 12,
  3265. lg: 16,
  3266. xl: 18,
  3267. xxl: 20
  3268. }).getValue(this.currentBreakpoint)
  3269. )
  3270. .onAreaChange((oldValue: Area, newValue: Area) => {
  3271. this.listArea = newValue
  3272. if(this.twoFingerType==3){
  3273. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3274. }else if(this.twoFingerType==2){
  3275. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3276. }else if(this.twoFingerType==1){
  3277. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3278. }
  3279. })
  3280. .onScrollFrameBegin((offset: number) => {
  3281. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3282. if(this.isPhoneLan()){
  3283. this.setBarHeightHide(offset)
  3284. }else if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3285. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3286. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3287. if(this.isScrollHide){
  3288. this.setBarHeightHide2(offset)
  3289. }else{
  3290. this.setBarHeightNormal()
  3291. }
  3292. }else{
  3293. this.setBarHeightHide(offset)
  3294. }
  3295. return { offsetRemain: offset };
  3296. })
  3297. }
  3298. setBarHeightNormal(){
  3299. this.hideDone = false;
  3300. this.getUIContext().animateTo({
  3301. duration: 300
  3302. }, () => {
  3303. this.bottomBarHeight = 55 + 0;
  3304. this.topBarHeight = 50 + 0;
  3305. this.barOpacity = 1;
  3306. this.barBottomOpacity = 1
  3307. this.currentYOffset = 0;
  3308. this.isHiding = false;
  3309. });
  3310. }
  3311. setBarHeightHide(offset: number){
  3312. if (offset > 0 && !this.hideDone) {
  3313. this.currentYOffset += offset;
  3314. if (this.currentYOffset <= 100) {
  3315. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3316. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3317. this.barOpacity = 1 - this.currentYOffset / 100;
  3318. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3319. } else {
  3320. this.topBarHeight = 0;
  3321. this.bottomBarHeight = 0;
  3322. this.barBottomOpacity = 0
  3323. this.barOpacity = 0;
  3324. this.hideDone = true;
  3325. }
  3326. this.isHiding = true;
  3327. }
  3328. if (offset < 0 && this.isHiding) {
  3329. this.hideDone = false;
  3330. this.getUIContext().animateTo({
  3331. duration: 300
  3332. }, () => {
  3333. this.bottomBarHeight = 55 + 0;
  3334. this.topBarHeight = 50 + 0;
  3335. this.barOpacity = 1;
  3336. this.barBottomOpacity = 1
  3337. this.currentYOffset = 0;
  3338. this.isHiding = false;
  3339. });
  3340. }
  3341. }
  3342. //这个方法没隐藏bottomBar,只隐藏topbar
  3343. setBarHeightHide2(offset: number){
  3344. if (offset > 0 && !this.hideDone) {
  3345. this.currentYOffset += offset;
  3346. if (this.currentYOffset <= 100) {
  3347. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3348. this.barOpacity = 1 - this.currentYOffset / 100;
  3349. } else {
  3350. this.topBarHeight = 0;
  3351. this.barOpacity = 0;
  3352. this.hideDone = true;
  3353. }
  3354. this.isHiding = true;
  3355. }
  3356. if (offset < 0 && this.isHiding) {
  3357. this.hideDone = false;
  3358. this.getUIContext().animateTo({
  3359. duration: 300
  3360. }, () => {
  3361. this.topBarHeight = 50 + 0;
  3362. this.barOpacity = 1;
  3363. this.currentYOffset = 0;
  3364. this.isHiding = false;
  3365. });
  3366. }
  3367. }
  3368. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3369. switch (item.type) {
  3370. case CommonConstants.TYPE_IS_DIR:
  3371. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3372. this.showVerifyDialog()
  3373. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3374. this.titleBarModel.setTitleName('最近播放')
  3375. //加载动画效果
  3376. this.updateListData(this.historyList,true)
  3377. // this.videoLocalList = this.historyList
  3378. if (ArrayUtil.isEmpty(this.historyList)) {
  3379. ToastUtil.showToast('最近播放记录空空如也')
  3380. }
  3381. this.isHistory = true
  3382. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3383. } else if(item.name === LocalMusic.STR_FAC_VIDEO){
  3384. this.titleBarModel.setTitleName('我的收藏')
  3385. //加载动画效果
  3386. this.updateListData(this.favList)
  3387. if(ArrayUtil.isEmpty(this.favList)){
  3388. ToastUtil.showToast('无音乐收藏记录')
  3389. }
  3390. this.isFavMusic = true
  3391. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3392. }else {
  3393. this.currentPath = item.filePath
  3394. this.getSortedFiles(this.currentPath)
  3395. }
  3396. break;
  3397. case CommonConstants.TYPE_IS_ARTIST:
  3398. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3399. let offsetA = 0
  3400. if (this.isGridMusic) {
  3401. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3402. let cur = this.scroller.currentOffset()
  3403. if (cur && typeof cur.yOffset === 'number') {
  3404. offsetA = cur.yOffset
  3405. }
  3406. }
  3407. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3408. } else {
  3409. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3410. let cur = this.listScroller.currentOffset()
  3411. if (cur && typeof cur.yOffset === 'number') {
  3412. offsetA = cur.yOffset
  3413. }
  3414. }
  3415. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3416. }
  3417. let mList = this.artistMap.get(item.name)
  3418. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3419. Utility.doSortListAscending(mList)
  3420. this.isCanBack = true
  3421. this.titleBarModel.setTitleName(item.name)
  3422. this.updateListData(mList)
  3423. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3424. }
  3425. break;
  3426. case CommonConstants.TYPE_IS_ALBUM:
  3427. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3428. let offset = 0
  3429. if (this.isGridMusic) {
  3430. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3431. let cur = this.scroller.currentOffset()
  3432. if (cur && typeof cur.yOffset === 'number') {
  3433. offset = cur.yOffset
  3434. }
  3435. }
  3436. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3437. } else {
  3438. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3439. let cur = this.listScroller.currentOffset()
  3440. if (cur && typeof cur.yOffset === 'number') {
  3441. offset = cur.yOffset
  3442. }
  3443. }
  3444. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  3445. }
  3446. let albumList = this.albumMap.get(item.name)
  3447. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  3448. Utility.doSortListAscending(albumList)
  3449. this.isCanBack = true
  3450. this.titleBarModel.setTitleName(item.name)
  3451. this.updateListData(albumList)
  3452. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3453. this.mScrollMap.set(item.name, this.selectedIndex)
  3454. }
  3455. break;
  3456. case CommonConstants.TYPE_IS_CSJAD:
  3457. return
  3458. break;
  3459. case CommonConstants.TYPE_LOCAL:
  3460. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  3461. this.stop();
  3462. }
  3463. if (isFromSonPlayList) { //点击来自右下角的播放列表
  3464. this.currentSong = item
  3465. if (index !== undefined) {
  3466. this.curIndex = index
  3467. }
  3468. } else {
  3469. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  3470. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  3471. this.songList = globalVideoList
  3472. this.sonDataSource.pushArrayData(this.songList)
  3473. this.currentSong = globalVideoList[this.curIndex]
  3474. }
  3475. this.videoUrl = this.currentSong.filePath
  3476. this.name = this.currentSong.name
  3477. this.cover = this.currentSong.pixelMapPath
  3478. this.artist = this.currentSong.artist
  3479. LogUtil.info('this.currentSong.duration ='+this.currentSong.duration)
  3480. LogUtil.info('this.currentSong.sampleRate ='+this.currentSong.sampleRate)
  3481. LogUtil.info('this.currentSongmimeType ='+this.currentSong.mimeType)
  3482. this.startPlayOrResumePlay()
  3483. break;
  3484. }
  3485. }
  3486. @Builder
  3487. PlayController() {
  3488. Column() {
  3489. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  3490. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  3491. Row() {
  3492. Row() {
  3493. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  3494. Column() {
  3495. Text(this.currentSong?.name)
  3496. .fontSize(13)
  3497. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3498. .maxLines(1)
  3499. .fontColor($r('app.color.text_color'))
  3500. .fontWeight(500)
  3501. Row() {
  3502. Text(this.currentSong?.artist)
  3503. .margin({ top: 2 })
  3504. .fontSize(11)
  3505. .fontColor($r('app.color.text_color'))
  3506. }
  3507. }
  3508. .alignItems(HorizontalAlign.Start)
  3509. .margin({ right: 22 })
  3510. }
  3511. .layoutWeight(1)
  3512. .onClick(() => {
  3513. if (ArrayUtil.isNotEmpty(this.songList)) {
  3514. this.isShowPlay = true;
  3515. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  3516. this.initLyric(lyricPath);
  3517. } else {
  3518. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3519. }
  3520. })
  3521. Row() {
  3522. Image($r('app.media.hm_previous'))
  3523. .height(24)
  3524. .width(24)
  3525. .clickEffect({level:ClickEffectLevel.HEAVY})
  3526. .margin({ left: 8, right: 16 })
  3527. .fillColor(this.themeColor)
  3528. .displayPriority(2)
  3529. .onClick(() => {
  3530. if (ArrayUtil.isNotEmpty(this.songList)) {
  3531. this.playPrevious()
  3532. } else {
  3533. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3534. }
  3535. })
  3536. //播放进度条
  3537. Stack() {
  3538. Progress({
  3539. value: Math.floor(this.progressValue),
  3540. type: ProgressType.Ring,
  3541. })
  3542. .color(this.themeColor)// 进度条前景色为灰色
  3543. .backgroundColor($r('app.color.index_background'))
  3544. .height(36)
  3545. .aspectRatio(CommonConstants.ASPECT_RATIO)
  3546. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  3547. .height(32)
  3548. .width(32)
  3549. .displayPriority(3)
  3550. .clickEffect({level:ClickEffectLevel.HEAVY})
  3551. .fillColor(this.themeColor)
  3552. .onClick(() => {
  3553. if (ArrayUtil.isNotEmpty(this.songList)) {
  3554. this.playOrPause()
  3555. } else {
  3556. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3557. }
  3558. })
  3559. }
  3560. Image($r('app.media.hm_next'))
  3561. .height(24)
  3562. .width(24)
  3563. .margin({
  3564. right: 16,
  3565. left: 16
  3566. })
  3567. .fillColor(this.themeColor)
  3568. .clickEffect({level:ClickEffectLevel.HEAVY})
  3569. .displayPriority(2)
  3570. .onClick(() => {
  3571. if (ArrayUtil.isNotEmpty(this.songList)) {
  3572. this.playNext()
  3573. } else {
  3574. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3575. }
  3576. })
  3577. Image($r('app.media.hm_playlist'))
  3578. .height(24)
  3579. .width(24)
  3580. .displayPriority(1)
  3581. .clickEffect({level:ClickEffectLevel.HEAVY})
  3582. .fillColor(this.themeColor)
  3583. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3584. height: '95%',
  3585. dragBar: true,
  3586. showClose: true,
  3587. blurStyle: BlurStyle.Thin,
  3588. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3589. backgroundColor: Color.Transparent,
  3590. title: {
  3591. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3592. + `(${this.songList.length}首)`
  3593. }
  3594. })
  3595. .onClick(() => {
  3596. if (ArrayUtil.isNotEmpty(this.songList)) {
  3597. this.isShowSheet = !this.isShowSheet;
  3598. this.isFrontWhite = false
  3599. LogUtil.info('onecold scrollToIndex = '+this.curIndex)
  3600. setTimeout(() => {
  3601. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  3602. }, 123)
  3603. } else {
  3604. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3605. }
  3606. })
  3607. }
  3608. }
  3609. .width('100%')
  3610. .height(this.bottomBarHeight)
  3611. .justifyContent(FlexAlign.Center)
  3612. .hitTestBehavior(HitTestMode.Transparent)
  3613. .backgroundColor(this.isCustomizeBg?Color.Transparent:$r('app.color.bottom_control_background'))
  3614. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3615. // modalTransition: ModalTransition.DEFAULT,
  3616. transition: AnimationHelper.transitionInDown(666),
  3617. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  3618. })
  3619. .padding({
  3620. left: 16,
  3621. right: 16
  3622. })
  3623. Line().width('100%').height(25).backgroundColor($r('app.color.bottom_control_background'))
  3624. // .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  3625. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  3626. }
  3627. .clickEffect({level:ClickEffectLevel.HEAVY})
  3628. }
  3629. @State isFrontWhite: boolean = false
  3630. //播放列表布局
  3631. @Builder
  3632. PlayListSheet() {
  3633. Column() {
  3634. this.PlayList()
  3635. }
  3636. .width('100%')
  3637. .height('100%')
  3638. }
  3639. @State titleStr: string = ''
  3640. @State ablumStr: string = ''
  3641. @State artistStr: string = ''
  3642. @State lyricConStr: string = ''
  3643. @State currentEditItem: string = ''
  3644. doUpdateData() {
  3645. setTimeout(() => {
  3646. if (this.modeType === 0) {
  3647. this.deleteCache(this.currentPath)
  3648. this.getSortedFiles(this.currentPath)
  3649. }
  3650. workerInstance.postMessage({ code: 2, data: this.context });
  3651. workerInstance.postMessage({ code: 3, data: this.context });
  3652. workerInstance.postMessage({ code: 4, data: this.context });
  3653. }, 999)
  3654. }
  3655. //编辑信息
  3656. doEdit(item:VideoItem) {
  3657. if (!item) {
  3658. return
  3659. }
  3660. if (StrUtil.isEmpty(this.titleStr)) {
  3661. ToastUtil.showToast('标题不能为空')
  3662. return
  3663. }
  3664. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  3665. (success: boolean, error?: string) => {
  3666. this.isShowEdit = false
  3667. if (success) {
  3668. console.log(" onecold 编辑信息成功,数据库已同步");
  3669. ToastUtil.showToast('保存成功')
  3670. this.isShowMoreView = false
  3671. this.name = this.titleStr
  3672. if (item.filePath==this.currentSong?.filePath) {
  3673. this.currentSong.name = this.titleStr
  3674. this.artist = this.artistStr
  3675. this.currentSong.artist = this.artistStr
  3676. this.currentSong.album = this.ablumStr
  3677. }
  3678. this.doUpdateData()
  3679. } else {
  3680. ToastUtil.showToast('保存失败' + error?.toString())
  3681. console.error(" onecold 编辑信息数据库失败原因: " + error);
  3682. }
  3683. });
  3684. let doChangeLyric = false
  3685. if(item.filePath==this.currentSong?.filePath){
  3686. if(this.lyricConStr !== this.lyricContent){
  3687. doChangeLyric = true
  3688. }
  3689. }else if(this.lyricConStr !== this.tempLyricContent){
  3690. doChangeLyric = true
  3691. }
  3692. if (doChangeLyric) {
  3693. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  3694. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  3695. let isJiaMi = false;
  3696. let realLyricPath = lyricPath
  3697. if (FileUtil.accessSync(jiaMilyricPath)) {
  3698. isJiaMi = true
  3699. realLyricPath = jiaMilyricPath
  3700. console.info("onecold doEdit找到加密本地歌词 ");
  3701. } else {
  3702. isJiaMi = false
  3703. realLyricPath = lyricPath
  3704. console.info("onecold doEdit本地歌词 ");
  3705. }
  3706. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  3707. }
  3708. }
  3709. updateLyricToDB(){
  3710. }
  3711. @Builder
  3712. editSheet(item:VideoItem) {
  3713. Scroll() {
  3714. Column() {
  3715. this.editDetail(item)
  3716. }
  3717. }
  3718. .width('100%')
  3719. .height('100%')
  3720. }
  3721. @Builder
  3722. editDetail(item:VideoItem) {
  3723. Column() {
  3724. if (item) {
  3725. Row() {
  3726. Stack() {
  3727. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  3728. item.pixelMapPath)
  3729. .fillColor(this.themeColor)
  3730. .height(33)
  3731. .width(33)
  3732. .borderRadius('100%')
  3733. .clip(true)
  3734. .opacity(this.opacityItem)// 绑定透明度
  3735. .margin({ left: 20 })
  3736. }
  3737. .width('15%')
  3738. Row() {
  3739. Column() {
  3740. Text(item.name)
  3741. .fontSize(14)
  3742. .maxLines(1)
  3743. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3744. .animation({
  3745. duration: 555,
  3746. curve: 'Linear',
  3747. })
  3748. .fontColor(this.themeColor)
  3749. .margin({ left: 10 })
  3750. Row() {
  3751. Text(item.artist)
  3752. .fontSize(11)
  3753. .maxLines(1)
  3754. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3755. .padding({ top: 8 })
  3756. .fontColor(this.themeColor)
  3757. .margin({ left: 10 })
  3758. }
  3759. }
  3760. .height('100%')
  3761. .width(100)
  3762. .visibility(this.isDarkMode?Visibility.None:Visibility.Visible)
  3763. .justifyContent(FlexAlign.Center)
  3764. .alignItems(HorizontalAlign.Start)
  3765. Button('本地封面')
  3766. .fontColor(Color.White)
  3767. .fontSize(12)
  3768. .height(38)
  3769. .width(88)
  3770. .backgroundColor(this.themeColor)
  3771. .stateEffect(true)
  3772. .margin({ right: 5, left: 12 })
  3773. .onClick(async () => {
  3774. this.goSelectImage(item)
  3775. })
  3776. Button('获取封面')
  3777. .fontColor(Color.White)
  3778. .fontSize(12)
  3779. .height(38)
  3780. .width(88)
  3781. .backgroundColor(this.themeColor)
  3782. .stateEffect(true)
  3783. .margin({ right: 12, left: 5 })
  3784. .onClick(async () => {
  3785. this.doSearchCover(item)
  3786. })
  3787. }
  3788. .height('100%')
  3789. .justifyContent(FlexAlign.Start)
  3790. .layoutWeight(1)
  3791. }
  3792. .width('100%')
  3793. .height(58)
  3794. Row() {
  3795. Text('标题:')
  3796. .fontSize(14)
  3797. .fontColor($r('app.color.text_color'))
  3798. .margin({ left: 22 })
  3799. TextInput({ text: item.name })
  3800. .height(40)
  3801. .maxLines(1)
  3802. .fontSize(14)
  3803. .layoutWeight(1)
  3804. .fontColor($r('app.color.text_color'))
  3805. .margin({ right: 20, left: 10 })
  3806. .onChange((val: string) => {
  3807. this.titleStr = val
  3808. })
  3809. }
  3810. .width('100%')
  3811. .margin({ top: 10, bottom: 10 })
  3812. .justifyContent(FlexAlign.Start)
  3813. Row() {
  3814. Text('艺术家:')
  3815. .fontSize(14)
  3816. .fontColor($r('app.color.text_color'))
  3817. .margin({ left: 22 })
  3818. TextInput({ text: item.artist })
  3819. .height(40)
  3820. .maxLines(1)
  3821. .fontSize(14)
  3822. .layoutWeight(1)
  3823. .fontColor($r('app.color.text_color'))
  3824. .margin({ right: 20, left: 10 })
  3825. .onChange((val: string) => {
  3826. this.artistStr = val
  3827. })
  3828. }
  3829. .width('100%')
  3830. .margin({ top: 10, bottom: 10 })
  3831. .justifyContent(FlexAlign.Start)
  3832. Row() {
  3833. Text('专辑名:')
  3834. .fontSize(14)
  3835. .fontColor($r('app.color.text_color'))
  3836. .margin({ left: 22 })
  3837. TextInput({ text: item.album })
  3838. .height(40)
  3839. .maxLines(1)
  3840. .fontSize(14)
  3841. .layoutWeight(1)
  3842. .fontColor($r('app.color.text_color'))
  3843. .margin({ right: 20, left: 10 })
  3844. .onChange((val: string) => {
  3845. this.ablumStr = val
  3846. })
  3847. }
  3848. .width('100%')
  3849. .margin({ top: 10, bottom: 10 })
  3850. .justifyContent(FlexAlign.Start)
  3851. Row() {
  3852. Text('歌词:')
  3853. .fontSize(14)
  3854. .fontColor($r('app.color.text_color'))
  3855. .margin({ left: 22 })
  3856. TextArea({ text:item.filePath===this.currentSong?.filePath? this.lyricContent : this.tempLyricContent })
  3857. .type(TextAreaType.NORMAL)
  3858. .height(275)
  3859. .fontSize(14)
  3860. .layoutWeight(1)
  3861. .fontColor($r('app.color.text_color'))
  3862. .margin({ right: 20, left: 10 })
  3863. .onChange((val: string) => {
  3864. this.lyricConStr = val
  3865. })
  3866. }
  3867. .width('100%')
  3868. .margin({ top: 10, bottom: 10 })
  3869. .justifyContent(FlexAlign.Start)
  3870. Row() {
  3871. Button('保存')
  3872. .fontColor(Color.White)
  3873. .layoutWeight(1)
  3874. .height(50)
  3875. .width(100)
  3876. .backgroundColor(this.themeColor)
  3877. .stateEffect(true)
  3878. .margin({ right: 20, bottom: 20 })
  3879. .onClick(async () => {
  3880. this.doEdit(item)
  3881. })
  3882. Button('取消')
  3883. .fontColor(Color.White)
  3884. .layoutWeight(1)
  3885. .height(50)
  3886. .width(100)
  3887. .backgroundColor(this.themeColor)
  3888. .stateEffect(true)
  3889. .margin({ left: 20, bottom: 20 })
  3890. .onClick(async () => {
  3891. this.isShowEdit = false
  3892. })
  3893. }
  3894. .margin({
  3895. left: 38,
  3896. right: 38,
  3897. top: 10,
  3898. bottom: 10
  3899. })
  3900. .width(250)
  3901. .height(60)
  3902. }
  3903. }
  3904. .margin({ bottom: 20 })
  3905. }
  3906. @Builder
  3907. detailSheet() {
  3908. Scroll() {
  3909. Column() {
  3910. this.songDetail()
  3911. }
  3912. }
  3913. .width('100%')
  3914. .height('100%')
  3915. }
  3916. @Builder
  3917. songDetail() {
  3918. Column() {
  3919. if (this.currentSong) {
  3920. Row() {
  3921. Stack() {
  3922. Image(StrUtil.isEmpty(this.currentSong.pixelMapPath) ? $r('app.media.music_red') :
  3923. this.currentSong.pixelMapPath)
  3924. .fillColor(this.themeColor)
  3925. .height(33)
  3926. .width(33)
  3927. .borderRadius('100%')
  3928. .clip(true)
  3929. .opacity(this.opacityItem)// 绑定透明度
  3930. .margin({ left: 20 })
  3931. }
  3932. .width('15%')
  3933. Column() {
  3934. Column() {
  3935. Text(this.currentSong.name)
  3936. .fontSize(14)
  3937. .maxLines(1)
  3938. .animation({
  3939. duration: 555,
  3940. curve: 'Linear',
  3941. })
  3942. .fontColor($r('app.color.text_color'))
  3943. .margin({ left: 10 })
  3944. Row() {
  3945. Text(StrUtil.isEmpty(this.currentSong.artist) ? this.currentSong.cTime :
  3946. this.currentSong.artist + ' ' + this.currentSong?.album)
  3947. .fontSize(11)
  3948. .padding({ top: 8 })
  3949. .fontColor($r('app.color.text_color'))
  3950. .margin({ left: 10 })
  3951. }
  3952. }
  3953. .height('100%')
  3954. .width('100%')
  3955. .justifyContent(FlexAlign.Center)
  3956. .alignItems(HorizontalAlign.Start)
  3957. }
  3958. .height('100%')
  3959. }
  3960. .width('100%')
  3961. .height(58)
  3962. .justifyContent(FlexAlign.SpaceBetween)
  3963. Row() {
  3964. Text('歌手名:')
  3965. .fontSize(14)
  3966. .fontColor(Color.White)
  3967. .margin({ left: 22 })
  3968. Text(this.currentSong?.artist ? this.currentSong.artist : '未知歌手')
  3969. .fontSize(14)
  3970. .fontColor(Color.White)
  3971. .margin({ left: 10 })
  3972. .layoutWeight(1)
  3973. }
  3974. .width('100%')
  3975. .margin({ top: 10, bottom: 10 })
  3976. .justifyContent(FlexAlign.Start)
  3977. Row() {
  3978. Text('专辑名:')
  3979. .fontSize(14)
  3980. .fontColor(Color.White)
  3981. .margin({ left: 22 })
  3982. Text(this.currentSong?.album ? this.currentSong.album : '未知专辑')
  3983. .fontSize(14)
  3984. .margin({ left: 10 })
  3985. .fontColor(Color.White)
  3986. .layoutWeight(1)
  3987. }
  3988. .width('100%')
  3989. .margin({ top: 10, bottom: 10 })
  3990. .justifyContent(FlexAlign.Start)
  3991. Row() {
  3992. Text('时长:')
  3993. .fontSize(14)
  3994. .fontColor(Color.White)
  3995. .margin({ left: 22 })
  3996. Text(this.totalTime)
  3997. .fontSize(14)
  3998. .margin({ left: 10 })
  3999. .fontColor(Color.White)
  4000. .layoutWeight(1)
  4001. }
  4002. .width('100%')
  4003. .margin({ top: 10, bottom: 10 })
  4004. .justifyContent(FlexAlign.Start)
  4005. Row() {
  4006. Text('采样率:')
  4007. .fontSize(14)
  4008. .fontColor(Color.White)
  4009. .margin({ left: 22 })
  4010. Text(Utility.convertToKHz(this.currentSong.sampleRate))
  4011. .fontSize(14)
  4012. .margin({ left: 10 })
  4013. .fontColor(Color.White)
  4014. .layoutWeight(1)
  4015. }
  4016. .width('100%')
  4017. .margin({ top: 10, bottom: 10 })
  4018. .justifyContent(FlexAlign.Start)
  4019. Row() {
  4020. Text('音轨数:')
  4021. .fontSize(14)
  4022. .fontColor(Color.White)
  4023. .margin({ left: 22 })
  4024. Text(this.currentSong.trackCount)
  4025. .fontSize(14)
  4026. .margin({ left: 10 })
  4027. .fontColor(Color.White)
  4028. .layoutWeight(1)
  4029. }
  4030. .width('100%')
  4031. .margin({ top: 10, bottom: 10 })
  4032. .justifyContent(FlexAlign.Start)
  4033. Row() {
  4034. Text('格式:')
  4035. .fontSize(14)
  4036. .fontColor(Color.White)
  4037. .margin({ left: 22 })
  4038. Text(Utility.formatMimeType(this.currentSong.mimeType))
  4039. .fontSize(14)
  4040. .margin({ left: 10 })
  4041. .fontColor(Color.White)
  4042. .layoutWeight(1)
  4043. }
  4044. .width('100%')
  4045. .margin({ top: 10, bottom: 10 })
  4046. .justifyContent(FlexAlign.Start)
  4047. Row() {
  4048. Text('文件大小:')
  4049. .fontSize(14)
  4050. .fontColor(Color.White)
  4051. .margin({ left: 22 })
  4052. Text(this.currentSong.size)
  4053. .fontSize(14)
  4054. .margin({ left: 10 })
  4055. .fontColor(Color.White)
  4056. .layoutWeight(1)
  4057. }
  4058. .width('100%')
  4059. .margin({ top: 10, bottom: 10 })
  4060. .justifyContent(FlexAlign.Start)
  4061. Row() {
  4062. Text('文件名:')
  4063. .fontSize(14)
  4064. .fontColor(Color.White)
  4065. .margin({ left: 22 })
  4066. Text(this.currentSong.fileName)
  4067. .fontSize(14)
  4068. .margin({ left: 10 })
  4069. .fontColor(Color.White)
  4070. .layoutWeight(1)
  4071. }
  4072. .width('100%')
  4073. .margin({ top: 10, bottom: 10 })
  4074. .justifyContent(FlexAlign.Start)
  4075. Row() {
  4076. Text('修改时间:')
  4077. .fontSize(14)
  4078. .fontColor(Color.White)
  4079. .margin({ left: 22 })
  4080. Text(this.currentSong.cTime)
  4081. .fontSize(14)
  4082. .margin({ left: 10 })
  4083. .fontColor(Color.White)
  4084. .layoutWeight(1)
  4085. }
  4086. .width('100%')
  4087. .margin({ top: 10, bottom: 10 })
  4088. .justifyContent(FlexAlign.Start)
  4089. Row() {
  4090. Text('存放目录:')
  4091. .fontSize(14)
  4092. .fontColor(Color.White)
  4093. .margin({ left: 22 })
  4094. Text(this.currentSong.filePath)
  4095. .fontSize(12)
  4096. .margin({ left: 10 })
  4097. .fontColor(Color.White)
  4098. .layoutWeight(1)
  4099. }
  4100. .margin({ top: 10, bottom: 10 })
  4101. .width('100%')
  4102. .justifyContent(FlexAlign.Start)
  4103. }
  4104. }
  4105. .margin({ bottom: 20 })
  4106. }
  4107. //定时关闭布局
  4108. @Builder
  4109. TimeCloseSheet() {
  4110. Scroll() {
  4111. Column() {
  4112. this.TimeClose()
  4113. }
  4114. }
  4115. .width('100%')
  4116. .height('100%')
  4117. }
  4118. //倒计时关闭音乐,退出App功能实现。
  4119. @State selectedMinutes: number = 0 // 0表示未开启
  4120. @State remainingSeconds: number = 0
  4121. @State isCustomSuccess: boolean = false //设置自定义成功
  4122. // 预设时间选项
  4123. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  4124. private formatTime(seconds: number): string {
  4125. const mins = Math.floor(seconds / 60)
  4126. const secs = seconds % 60
  4127. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  4128. }
  4129. // 开始倒计时
  4130. private handleTimeSelect(minutes: number) {
  4131. if (minutes === this.selectedMinutes) {
  4132. this.stopCountdown();
  4133. this.selectedMinutes = 0;
  4134. return;
  4135. }
  4136. this.selectedMinutes = minutes;
  4137. this.remainingSeconds = minutes * 60;
  4138. this.startCountdown(); // 新增调用
  4139. }
  4140. @Builder
  4141. TimeClose() {
  4142. Column() {
  4143. // 倒计时显示区域
  4144. Text(this.selectedMinutes > 0 ?
  4145. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  4146. "定时关闭未开启")
  4147. .fontSize(17)
  4148. .fontColor($r('app.color.text_color'))
  4149. .margin({ top: 2 });
  4150. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  4151. ForEach(this.presetTimes, (minutes: number) => {
  4152. // 单行时间选项容器
  4153. Row() {
  4154. // 文字描述区域
  4155. Text(this.getDisplayText(minutes))
  4156. .fontSize(15)
  4157. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  4158. $r('app.color.text_color'))// 选中态颜色变化
  4159. .textAlign(TextAlign.Start)
  4160. .layoutWeight(1); // 占据剩余空间
  4161. // 复选框区域
  4162. Checkbox()
  4163. .select(minutes === this.selectedMinutes ? true : minutes === -1 ? this.isCustomSuccess : false)// 绑定选中状态
  4164. .selectedColor(this.themeColor)// 主题色
  4165. .shape(CheckBoxShape.CIRCLE)
  4166. .size({ width: 24, height: 24 })
  4167. .margin({ left: 20 })
  4168. }
  4169. .width('100%')
  4170. .padding(10)
  4171. .backgroundColor(minutes === this.selectedMinutes ?$r('app.color.timeColor_bg') :$r('app.color.bottom_control_background')) // 选中背景高亮
  4172. .borderRadius(12)
  4173. .margin({ bottom: 6 })
  4174. .onClick(() => this.handleSelect(minutes)); // 确保点击触发选择
  4175. });
  4176. }
  4177. .width('100%')
  4178. .padding(16)
  4179. }
  4180. }
  4181. // 获取显示文本
  4182. private getDisplayText(minutes: number): string {
  4183. if (minutes === -1) {
  4184. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  4185. }
  4186. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  4187. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  4188. }
  4189. // 处理选择事件
  4190. private handleSelect(minutes: number): void {
  4191. if (minutes === -1) { // 自定义
  4192. // 弹出自定义时间对话框
  4193. DialogHelper.showTextInputDialog({
  4194. title: '自定义时间',
  4195. maskColor: Color.Transparent,
  4196. inputType: InputType.Number,
  4197. text: '',
  4198. onChange: (text) => {
  4199. console.error("onChange: " + text);
  4200. },
  4201. onAction: (action, dialogId, content) => {
  4202. if (action == DialogAction.TWO) {
  4203. this.handleTimeSelect(Number(content)); // 改为调用统一方法
  4204. this.isCustomSuccess = true
  4205. ToastUtil.showToast("设置成功," + this.selectedMinutes + "分钟后定时关闭");
  4206. }
  4207. }
  4208. });
  4209. } else {
  4210. this.isCustomSuccess = false
  4211. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  4212. }
  4213. }
  4214. // 添加定时器引用
  4215. private timerId: number = -1;
  4216. // 启动/重置倒计时
  4217. private startCountdown() {
  4218. // 清除旧定时器
  4219. if (this.timerId !== -1) {
  4220. clearInterval(this.timerId);
  4221. }
  4222. // 创建新定时器
  4223. if (this.selectedMinutes > 0) {
  4224. this.timerId = setInterval(() => {
  4225. if (this.remainingSeconds === 15) {
  4226. this.showConfirmationDialog();
  4227. }
  4228. if (this.remainingSeconds > 0) {
  4229. this.remainingSeconds -= 1;
  4230. } else {
  4231. this.stopCountdown();
  4232. this.handleTimeout();
  4233. }
  4234. }, 1000);
  4235. }
  4236. }
  4237. // 15倒计时后再次提示显示确认是否关闭App对话框
  4238. private showConfirmationDialog() {
  4239. DialogHelper.showAlertDialog({
  4240. backgroundColor: $r('app.color.btn_green'),
  4241. title: '确认关闭',
  4242. maskColor: Color.Transparent,
  4243. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  4244. borderStyle: BorderStyle.Dashed,
  4245. primaryButton: '暂不关闭',
  4246. secondaryButton: '确定',
  4247. onAction: (action) => {
  4248. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  4249. this.stopCountdown();
  4250. this.selectedMinutes = 0
  4251. } else if (action == DialogAction.TWO) {
  4252. }
  4253. }
  4254. })
  4255. }
  4256. // 停止倒计时
  4257. private stopCountdown() {
  4258. if (this.timerId !== -1) {
  4259. clearInterval(this.timerId);
  4260. this.timerId = -1;
  4261. }
  4262. }
  4263. // 超时处理
  4264. private handleTimeout() {
  4265. // 执行播放器关闭逻辑
  4266. this.selectedMinutes = 0;
  4267. this.isCustomSuccess = false;
  4268. ToastUtil.showToast(" 定时关闭已完成");
  4269. this.stop(); // 假设存在的播放器实例
  4270. //退出APP
  4271. const mContext = getContext(this) as common.UIAbilityContext
  4272. mContext.terminateSelf();
  4273. AvSessionController.getInstance(true).unregisterSessionListener()
  4274. }
  4275. //倒计时关闭音乐,退出App功能实现结束。
  4276. //播放列表的拖动List 重新排序
  4277. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  4278. //左滑操作 移动文件 重命名 删除等操作
  4279. @Builder
  4280. sonButton(item: VideoItem, index: number, filePath: string) {
  4281. Row() {
  4282. //加入下一首播放
  4283. Button() {
  4284. Image($r('app.media.next_to_play'))
  4285. .fillColor(Color.White)
  4286. .width(20)
  4287. }
  4288. .width(40)
  4289. .height(40)
  4290. .type(ButtonType.Circle)
  4291. .backgroundColor(this.themeColor)
  4292. .margin(5)
  4293. .onClick(() => {
  4294. this.addToNextPlay(item);
  4295. })
  4296. Button() {
  4297. Image($r('app.media.close'))
  4298. .fillColor(Color.White)
  4299. .width(20)
  4300. }
  4301. .width(40)
  4302. .height(40)
  4303. .type(ButtonType.Circle)
  4304. .backgroundColor(this.themeColor)
  4305. .margin(5)
  4306. .onClick(() => {
  4307. this.songList.splice(Number(index), 1)
  4308. this.sonDataSource.pushArrayData(this.songList)
  4309. })
  4310. Button() {
  4311. Image($r('app.media.share2'))
  4312. .fillColor(Color.White)
  4313. .width(20)
  4314. }
  4315. .width(40)
  4316. .height(40)
  4317. .type(ButtonType.Circle)
  4318. .backgroundColor(this.themeColor)
  4319. .margin(5)
  4320. .onClick(() => {
  4321. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4322. })
  4323. }
  4324. }
  4325. itemMoveSon(index: number, newIndex: number): void {
  4326. if (newIndex < 0 || newIndex >= this.songList.length) {
  4327. return;
  4328. }
  4329. let tmp = this.songList.splice(index, 1);
  4330. this.songList.splice(newIndex, 0, tmp[0]);
  4331. this.sonDataSource.pushArrayData(this.songList)
  4332. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  4333. }
  4334. @Builder
  4335. PlayList() {
  4336. List({ scroller: this.playListScroller }) {
  4337. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  4338. ListItem() {
  4339. this.MusicItemSon(item, index)
  4340. }
  4341. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  4342. .animation({
  4343. duration: 666,
  4344. curve: 'ease-in-out' // 可选动画曲线
  4345. })
  4346. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  4347. TransitionEffect.scale({ x: 0, y: 0 }) ))
  4348. .clickEffect({level:ClickEffectLevel.MIDDLE})
  4349. //拖动List关键代码开始
  4350. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4351. .zIndex(this.dragItem === index ? 1 : 0)
  4352. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4353. .gesture(
  4354. GestureGroup(GestureMode.Sequence,
  4355. LongPressGesture({ repeat: true })
  4356. .onAction((event?: GestureEvent) => {
  4357. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4358. this.scaleItem = index
  4359. })
  4360. })
  4361. .onActionEnd(() => {
  4362. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4363. this.scaleItem = -1
  4364. })
  4365. }),
  4366. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4367. .onActionStart(() => {
  4368. this.dragItem = index // 记录当前拖动项索引
  4369. this.dragRefOffset = 0 // 重置偏移基准
  4370. })
  4371. .onActionUpdate((event: GestureEvent) => {
  4372. this.offsetY = event.offsetY - this.dragRefOffset;
  4373. this.neighborItem = -1;
  4374. let indexA = this.songList.indexOf(item);
  4375. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4376. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4377. let value: number = 0;
  4378. if (this.offsetY < 0) {
  4379. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4380. this.neighborItem = indexA - 1;
  4381. this.neighborScale = 1 - value / 20;
  4382. } else if (this.offsetY > 0) {
  4383. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4384. this.neighborItem = indexA + 1;
  4385. this.neighborScale = 1 - value / 20;
  4386. }
  4387. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  4388. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4389. this.offsetY -= this.ITEM_INTV;
  4390. this.dragRefOffset += this.ITEM_INTV;
  4391. this.itemMoveSon(indexA, indexA + 1);
  4392. });
  4393. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4394. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4395. this.offsetY += this.ITEM_INTV;
  4396. this.dragRefOffset -= this.ITEM_INTV;
  4397. this.itemMoveSon(indexA, indexA - 1);
  4398. });
  4399. }
  4400. })
  4401. .onActionEnd((event: GestureEvent) => {
  4402. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4403. this.dragItem = -1
  4404. this.neighborItem = -1
  4405. })
  4406. animateTo({
  4407. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4408. }, () => {
  4409. this.scaleItem = -1
  4410. })
  4411. })
  4412. )
  4413. .onCancel(() => {
  4414. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4415. this.dragItem = -1
  4416. this.neighborItem = -1
  4417. })
  4418. animateTo({
  4419. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4420. }, () => {
  4421. this.scaleItem = -1
  4422. })
  4423. })
  4424. ) //拖动List关键代码结束
  4425. .onClick(() => {
  4426. this.doPlay(item, index, true)
  4427. })
  4428. }, (item: VideoItem) => item.filePath)
  4429. }
  4430. .width('100%')
  4431. .height('100%')
  4432. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4433. // .animation({ duration: 500, curve: Curve.Ease }))
  4434. .cachedCount(10)
  4435. .scale({x:this.scaleValue,y:this.scaleValue,z:1})
  4436. .gesture(PinchGesture({ fingers: 2 })
  4437. .onActionEnd((event: GestureEvent)=>{
  4438. this.setlistTwoFingers()
  4439. })
  4440. .onActionUpdate(e=>{
  4441. this.scaleValue = this.pinchValue*e.scale
  4442. })
  4443. .onActionStart(e => {
  4444. }))
  4445. .padding({
  4446. bottom: 0
  4447. })
  4448. }
  4449. @Builder
  4450. private MusicItemSon(item: VideoItem, index?: number) {
  4451. Button({ type: ButtonType.Normal, stateEffect: true }) {
  4452. Row() {
  4453. Stack() {
  4454. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  4455. .height(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  4456. .width(this.twoFingerType==3?55:this.twoFingerType==2?35:30)
  4457. .alt($r('app.media.music_red'))
  4458. .fillColor(this.themeColor)
  4459. .borderRadius('100%')
  4460. .clip(true)
  4461. .margin({ left: 20 })
  4462. }
  4463. .width('15%')
  4464. Column() {
  4465. Column() {
  4466. Text(item.name)
  4467. .fontSize(this.twoFingerType==1?12:this.twoFingerType==2?15:18)
  4468. .fontColor(this.curIndex === index ? this.themeColor :
  4469. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  4470. .maxLines(1)
  4471. .margin({ left:this.twoFingerType==3?18: 10 })
  4472. Row() {
  4473. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  4474. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  4475. .padding({ top: 8 })
  4476. .fontColor(this.curIndex === index ? this.themeColor :
  4477. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  4478. .margin({ left:this.twoFingerType==3?18: 10 })
  4479. Blank()
  4480. Text(item.size)
  4481. .fontSize(this.twoFingerType==1?11:this.twoFingerType==2?12:14)
  4482. .padding({ top: 8 })
  4483. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  4484. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  4485. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  4486. .margin({ left: 10 })
  4487. }
  4488. }
  4489. .height('100%')
  4490. .width('100%')
  4491. .justifyContent(FlexAlign.Center)
  4492. .alignItems(HorizontalAlign.Start)
  4493. }
  4494. .height('100%')
  4495. .width('65%')
  4496. Column() {
  4497. ImageAnimator()
  4498. .images(this.imagesF)// 动画数组
  4499. .duration(1000)// 持续
  4500. .state(this.animationState)// 动画状态
  4501. .fillMode(FillMode.Forwards)
  4502. .width(18)
  4503. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4504. Visibility.None)
  4505. .height(18)
  4506. .iterations(-1) // 播放次数
  4507. }
  4508. .width('20%')
  4509. }
  4510. }
  4511. .backgroundColor(Color.Transparent)
  4512. .width('100%')
  4513. .height(this.twoFingerType==3?ITEM_HEIGHT_BIG:this.twoFingerType==2?ITEM_HEIGHT:ITEM_HEIGHT_SMALL)
  4514. .shadow(this.scaleItem === index ? {
  4515. radius: 70,
  4516. color: '#15000000',
  4517. offsetX: 0,
  4518. offsetY: 0
  4519. } :
  4520. {
  4521. radius: 0,
  4522. color: '#15000000',
  4523. offsetX: 0,
  4524. offsetY: 0
  4525. })
  4526. .animation({ curve: Curve.Sharp, duration: 300 })
  4527. }
  4528. @Builder
  4529. MusicPlayBuilder() {
  4530. Column() {
  4531. this.IjkMusicPlayerView()
  4532. }
  4533. .height('100%')
  4534. .width('100%')
  4535. .onDisAppear(() => {
  4536. this.translateY = 0;
  4537. })
  4538. .translate({ y: this.translateY })
  4539. .gesture(
  4540. PanGesture(this.panOption)
  4541. .onActionUpdate((event?: GestureEvent) => {
  4542. if (event) {
  4543. this.translateY = event.offsetY;
  4544. if (this.translateY < 0) {
  4545. this.translateY = 0;
  4546. return;
  4547. }
  4548. }
  4549. })
  4550. .onActionEnd(() => {
  4551. if (this.translateY > this.windowHeight / 2) {
  4552. this.isShowPlay = false;
  4553. } else {
  4554. this.getUIContext().animateTo({
  4555. duration: 300,
  4556. curve: Curve.Smooth
  4557. }, () => {
  4558. this.translateY = 0;
  4559. })
  4560. }
  4561. })
  4562. )
  4563. }
  4564. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  4565. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  4566. HeightBreakpoint.HEIGHT_LG;
  4567. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  4568. @State topBarHeight: number = 50
  4569. @State barOpacity: number = 1
  4570. @State barBottomOpacity: number = 1
  4571. private hideDone: boolean = false;
  4572. @State currentYOffset: number = 0;
  4573. @State bottomBarHeight: number = 55;
  4574. private isHiding: boolean = false;
  4575. //是否是Pura X外屏,或者小屏幕
  4576. isPuraWP() {
  4577. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  4578. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  4579. }
  4580. //是否是Pura X外屏,或者小屏幕,手机横屏
  4581. isCoverOpacity() {
  4582. if (this.isPuraWP()) {
  4583. return true
  4584. }
  4585. if (this.isPhoneLan()) {
  4586. return true
  4587. }
  4588. if (deviceInfo.marketName.includes('Pura X')
  4589. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  4590. return true
  4591. }
  4592. return false
  4593. }
  4594. //是不是手机横屏
  4595. isPhoneLan() {
  4596. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  4597. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  4598. if(DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  4599. &&this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  4600. &&this.currentWidthBreakpoint==WidthBreakpoint.WIDTH_MD){//如果是手机横屏,返回false
  4601. return true
  4602. }
  4603. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  4604. && this.currentBreakpoint !== BreakpointTypeEnum.SM) {
  4605. if (DisplayUtil.getFoldStatus() === 0 ) {
  4606. return true
  4607. }
  4608. }
  4609. return false
  4610. }
  4611. //是不是正常的手机竖屏
  4612. isPhonePortrait() {
  4613. LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  4614. LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  4615. if(DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  4616. &&this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  4617. &&this.currentWidthBreakpoint==WidthBreakpoint.WIDTH_SM){//如果是手机横屏,返回false
  4618. return true
  4619. }
  4620. return false
  4621. }
  4622. @Builder
  4623. IjkMusicPlayerView() {
  4624. Column() {
  4625. // Stack({ alignContent: Alignment.Center }) {
  4626. //
  4627. //
  4628. //
  4629. // Image($r('app.media.icon_load'))
  4630. // .objectFit(ImageFit.Auto)
  4631. // .width('120px')
  4632. // .height('120px')
  4633. // .visibility(this.loadingVisible)
  4634. // .border({ width: 0 })
  4635. // .borderStyle(BorderStyle.Dashed)
  4636. //
  4637. //
  4638. // }
  4639. Column() {
  4640. Column() {
  4641. //播放标题
  4642. Column() {
  4643. this.PlayTitle()
  4644. }
  4645. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  4646. .width('100%')
  4647. .margin({ top: 0 })
  4648. .height(PlayConstants.HEIGHT)
  4649. .visibility(DeviceUtil.getDeviceType()==resourceManager.DeviceType.DEVICE_TYPE_2IN1?
  4650. Visibility.Visible:this.isShowPlayPageBack?Visibility.Visible:Visibility.None)
  4651. // .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM
  4652. // ?Visibility.Visible:Visibility.Visible)
  4653. Swiper() {
  4654. this.CoverInfo()
  4655. this.PlayerLyrics()
  4656. }
  4657. .onChange((index:number)=>{
  4658. this.currentSwiperIndex = index
  4659. })
  4660. .indicator(false)
  4661. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  4662. // new DotIndicator()
  4663. // .top(this.isCoverOpacity()?0:10)
  4664. //
  4665. // .selectedColor($r('app.color.select_swiper'))
  4666. // .color($r('app.color.slider_track')):false
  4667. // )
  4668. .displayCount(new BreakpointType({
  4669. sm: 1,
  4670. md: 2,
  4671. lg: 2,
  4672. xl: 2,
  4673. xxl: 2
  4674. }).getValue(this.currentBreakpoint))
  4675. .clip(false)
  4676. .loop(false)
  4677. .autoPlay(false)
  4678. // .interval(8000)
  4679. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  4680. .height('100%')
  4681. .hitTestBehavior(HitTestMode.Transparent)
  4682. Image($r('app.media.icon_replay'))
  4683. .objectFit(ImageFit.Auto)
  4684. .width('120px')
  4685. .height('120px')
  4686. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  4687. .border({ width: 0 })
  4688. .visibility(Visibility.None)
  4689. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  4690. .onClick(() => {
  4691. this.startPlayOrResumePlay();
  4692. })
  4693. }
  4694. .width(CommonConstants.FULL_PERCENT)
  4695. .height(CommonConstants.FULL_PERCENT)
  4696. .justifyContent(FlexAlign.End)
  4697. }
  4698. .justifyContent(FlexAlign.End)
  4699. .margin({ bottom: 8 })
  4700. }
  4701. // .backgroundImage(this.imageLabelBg)
  4702. .backgroundImage(this.isPuraWP()&&this.currentSwiperIndex===0?(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover):this.imageLabelBg)
  4703. .backgroundImageSize(this.isPuraWP()?{ width: '100%' }:{ height: '150%', width: '100%' })
  4704. // .backgroundImagePosition(Alignment.Center)
  4705. .animation({
  4706. duration: 666,
  4707. curve: 'ease-in-out' // 可选动画曲线
  4708. })
  4709. .backgroundBlurStyle(this.isPuraWP()&&this.currentSwiperIndex===0?BlurStyle.NONE:BlurStyle.BACKGROUND_ULTRA_THICK)
  4710. .hitTestBehavior(HitTestMode.Transparent)
  4711. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  4712. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  4713. .backgroundBrightness({rate:this.isPuraWP()?0.1:0,lightUpDegree:-0.1})
  4714. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  4715. .onClick( ()=>{
  4716. this.isAutoHide = false
  4717. this.startAutoHide()
  4718. })
  4719. }
  4720. @State progressValue: number = 0;
  4721. @State currentTime: string = "00:00";
  4722. @State totalTime: string = "00:00";
  4723. @State loadingVisible: Visibility = Visibility.None;
  4724. @State replayVisible: Visibility = Visibility.None;
  4725. @State slideEnable: boolean = false;
  4726. @State aspRatio: number = 0.5;
  4727. @State mContext: object | undefined = undefined;
  4728. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  4729. @State mFirst: boolean = true;
  4730. @State mDestroyPage: boolean = false;
  4731. @State playSpeed: number = 1;
  4732. @State oldSeconds: number = 0;
  4733. @State isSeekTo: boolean = false;
  4734. @State isCurrentTime: boolean = false;
  4735. @State videoWidth: string = '100%';
  4736. @State videoHeight: string = '100%';
  4737. @State initAspectRatio: number = 1;
  4738. @State videoAspectRatio: number = this.initAspectRatio;
  4739. private videoUrl: string = '';
  4740. private last: number = 0;
  4741. @State videoParentAspectRatio: number = this.initAspectRatio;
  4742. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  4743. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  4744. @State PROGRESS_MAX_VALUE: number = 100;
  4745. @State updateProgressTimer: number = 0;
  4746. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  4747. @State name: string = '';
  4748. // @State loop: boolean = false;
  4749. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  4750. @State multiple: string = '1.0X';
  4751. xcomponentController: XComponentController = new XComponentController()
  4752. private panOptionBright: PanGestureOptions =
  4753. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  4754. private panOptionVolume: PanGestureOptions =
  4755. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  4756. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  4757. //手势的音量控制和亮度控制
  4758. private positionX: number = PlayConstants.POSITION_X;
  4759. private positionY: number = PlayConstants.POSITION_Y;
  4760. private windowClass: window.Window = globalThis.windowClass
  4761. @State volume: number = 0.8;
  4762. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  4763. @State bright: number = PlayConstants.BRIGHT;
  4764. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  4765. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  4766. @State screenWidth: number = 0
  4767. @State screenHeight: number = 0
  4768. @State statusBarHeight: number = 0
  4769. @State isYesFull: boolean = false
  4770. private seekValue: number = 0
  4771. @State isVideoLock: boolean = false; // Whether the video playback is locked
  4772. eventHub = getContext().eventHub;
  4773. //投播组件
  4774. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  4775. private castController: avSession.AVCastController | undefined = undefined;
  4776. @State isCastPlaying: boolean = false;
  4777. @State currentTime2: number = 0;
  4778. @State currentStringTime: string = '00:00';
  4779. @State duration: number = 0;
  4780. @State isReady: boolean = false;
  4781. @State durationTime: number = 0;
  4782. @State durationStringTime: string = '00:00';
  4783. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  4784. // @State isPlaying: boolean = false;
  4785. private castSeek: boolean = false;
  4786. private castItem: avSession.AVQueueItem | undefined = undefined;
  4787. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  4788. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  4789. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  4790. @State rotateAngle2: number = 0
  4791. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  4792. @State cover: string | undefined = '';
  4793. @State artist: string | undefined = ''
  4794. // 1.初始化controller
  4795. private lyricController: LyricController = new LyricController()
  4796. private lyricControllerXF: LyricController = new LyricController()//悬浮歌词控制器
  4797. private lyricControllerSingle: LyricController = new LyricController()//播放页单行歌词控制器
  4798. private parser = new LyricParser()
  4799. @State randomColor: string = 'rgb(0,0,0)'
  4800. @State randomShakenX: number = 0
  4801. @State randomShakenY: number = 0
  4802. @State lyricTextSize: number = 24
  4803. @State lyricContent: string = ''
  4804. @State isDebug: boolean = false
  4805. @State isHightLightCenter: boolean = true
  4806. /**
  4807. * 初始化歌词加载与展示逻辑
  4808. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  4809. * @param isToast 是否弹出Toast提示(可选)获取在线歌词为true
  4810. * @param isApi2 是否使用API2获取歌词(可选)
  4811. *
  4812. * 主要流程:
  4813. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  4814. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  4815. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  4816. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  4817. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  4818. * 6. 解析失败或读取失败时,清空歌词显示。
  4819. *
  4820. * 注意事项:
  4821. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  4822. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  4823. * - 歌词内容解析后通过lyricController驱动UI渲染。
  4824. */
  4825. async initLyric(lyricPath: string, isToast?: boolean, isApi2?: boolean) {
  4826. if (StrUtil.isEmpty(lyricPath)) {
  4827. return
  4828. }
  4829. this.initPipLyricSetting()
  4830. this.lyricControllerSingle
  4831. .setTextSize(15)
  4832. .setCacheSize(4)
  4833. .setTextColor("#FFFFFF")
  4834. .setHighlightColor("#FFFFFF")
  4835. .setHighlightScale(1.2)
  4836. .setEmptyHint("")
  4837. .setAlignMode('center')
  4838. .setAnimationDuration(500)
  4839. .setSingleLine(true)
  4840. this.lyricContent = ''
  4841. this.lyricController
  4842. .setTextSize(this.currentLyricSize)
  4843. .setCacheSize(4)
  4844. .setTextColor("#DDDDDD")
  4845. .setHighlightColor("#FFFFFF")
  4846. .setEmptyHint("")
  4847. .setAnimationDuration(1000)
  4848. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  4849. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 0)
  4850. this.setBlurDegree(this.blurDegree,false)
  4851. this.setLyricAlignMode(this.currentLyricAlignMode,false)
  4852. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18),false)
  4853. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23),false)
  4854. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  4855. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'),false)
  4856. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'),false)
  4857. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  4858. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  4859. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight',400)
  4860. this.lyricController.setTextWeight(this.lyricTextWeight)
  4861. this.showSingleLyric = false
  4862. this.timeOffset = 0
  4863. this.lyricController.setLyric(null)
  4864. this.lyricControllerSingle.setLyric(null)
  4865. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4866. LogUtil.debug("onecold lyricPath =" + lyricPath)
  4867. const neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
  4868. if (StrUtil.isNotEmpty(neiqianLrc) && !isToast) {
  4869. LogUtil.debug("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  4870. //赋值给this.lyricContent,播控中心才可以显示歌词
  4871. this.lyricContent = neiqianLrc
  4872. // 将文件内容按行分割成字符串数组
  4873. let lines = neiqianLrc.split('\n').map(line => line.trim());
  4874. // 3.解析歌词
  4875. let lyric = this.parser.parse(lines);
  4876. // 4.设置歌词
  4877. this.lyricController.setLyric(lyric);
  4878. this.lyricControllerXF.setLyric(lyric)
  4879. this.lyricControllerSingle.setLyric(lyric)
  4880. return
  4881. }
  4882. if (isToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  4883. && !Utility.isVideoByExtension(this.videoUrl))) {
  4884. if (this.currentSong !== undefined) {
  4885. // ToastUtil.showShort('正在为你搜索在线歌词!')
  4886. //判断是不是赞助会员,是会员的话才开启歌词功能
  4887. // if (!this.isDebug) {
  4888. // if (!Utility.isNoble()) {
  4889. // LogUtil.debug("onecold 不是赞助会员")
  4890. // return
  4891. // }
  4892. // if(!Utility.isPassInstallTime(33)){
  4893. // LogUtil.debug("onecold not pass time")
  4894. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  4895. // return
  4896. // }
  4897. // }
  4898. let artist = this.currentSong?.artist
  4899. if (artist === undefined) {
  4900. artist = ''
  4901. }
  4902. if (isApi2 === undefined) {
  4903. isApi2 = false
  4904. }
  4905. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  4906. // LogUtil.debug("onecold res =" + res)
  4907. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  4908. if (StrUtil.isNotEmpty(res)) {
  4909. this.lyricContent = res
  4910. let lines = res.split('\n').map(line => line.trim());
  4911. // 3.解析歌词
  4912. let lyric = this.parser.parse(lines);
  4913. // 4.设置歌词
  4914. this.lyricController.setLyric(lyric);
  4915. this.lyricControllerXF.setLyric(lyric)
  4916. this.lyricControllerSingle.setLyric(lyric)
  4917. this.showSingleLyric = true
  4918. // 4.保存歌词文件lyric到本地
  4919. this.saveDataToFile(res, jiaMilyricPath, true)
  4920. } else {
  4921. this.lyricController.setLyric(null)
  4922. this.lyricControllerXF.setLyric(null)
  4923. this.lyricControllerSingle.setLyric(null)
  4924. if (isToast) {
  4925. ToastUtil.showShort('未获取到歌词!')
  4926. }
  4927. }
  4928. } else {
  4929. this.lyricController.setLyric(null)
  4930. this.lyricControllerXF.setLyric(null)
  4931. this.lyricControllerSingle.setLyric(null)
  4932. if (isToast) {
  4933. ToastUtil.showShort('未获取到歌词!')
  4934. }
  4935. }
  4936. })
  4937. } else {
  4938. this.lyricController.setLyric(null)
  4939. this.lyricControllerXF.setLyric(null)
  4940. this.lyricControllerSingle.setLyric(null)
  4941. if (isToast) {
  4942. ToastUtil.showShort('未获取到歌词!')
  4943. }
  4944. }
  4945. return
  4946. }
  4947. try {
  4948. let isJiaMi = false;
  4949. let realLyricPath = lyricPath
  4950. if (FileUtil.accessSync(jiaMilyricPath)) {
  4951. isJiaMi = true
  4952. realLyricPath = jiaMilyricPath
  4953. console.info("onecold 找到加密本地歌词 ");
  4954. } else {
  4955. isJiaMi = false
  4956. realLyricPath = lyricPath
  4957. console.info("onecold 找到本地歌词 ");
  4958. }
  4959. // 3.读取文件内容并指定编码为 UTF-8
  4960. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  4961. let arrayBuffer = new ArrayBuffer(4096);
  4962. fs.read(file.fd, arrayBuffer)
  4963. .then((readLen: number) => {
  4964. console.info("read file data succeed");
  4965. // let buf = buffer.from(arrayBuffer, 0, readLen);
  4966. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  4967. // 检查 buf 是否为空
  4968. if (buf.length === 0) {
  4969. throw new Error("Buffer is empty after reading the file");
  4970. }
  4971. try {
  4972. // 检测文件编码
  4973. let detectedEncoding = chardet.detect(buf);
  4974. console.info("Detected encoding: " + detectedEncoding);
  4975. // 使用检测到的编码解码,解决中文乱码问题
  4976. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  4977. let fileContent = textDecoder.decode(buf);
  4978. console.info(`onecold The content of file1: ${fileContent}`);
  4979. //解密
  4980. if (isJiaMi) {
  4981. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  4982. }
  4983. console.info(`onecold The content of file2: ${fileContent}`);
  4984. this.lyricContent = fileContent
  4985. // 将文件内容按行分割成字符串数组
  4986. let lines = fileContent.split('\n').map(line => line.trim());
  4987. console.info(`onecold The content of file: ${fileContent}`);
  4988. // 3.解析歌词
  4989. let lyric = this.parser.parse(lines);
  4990. // 4.设置歌词
  4991. this.lyricController.setLyric(lyric);
  4992. this.lyricControllerXF.setLyric(lyric)
  4993. this.lyricControllerSingle.setLyric(lyric)
  4994. this.showSingleLyric = true
  4995. console.info(`The content of file: ${fileContent}`);
  4996. } catch (chardetError) {
  4997. console.error("chardet.detect failed with error: " + chardetError.message);
  4998. this.lyricController.setLyric(null);
  4999. this.lyricControllerXF.setLyric(null)
  5000. this.lyricControllerSingle.setLyric(null)
  5001. }
  5002. })
  5003. .catch((err: BusinessError) => {
  5004. this.lyricController.setLyric(null)
  5005. this.lyricControllerXF.setLyric(null)
  5006. this.lyricControllerSingle.setLyric(null)
  5007. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  5008. })
  5009. .catch((err: Error) => {
  5010. this.lyricController.setLyric(null)
  5011. this.lyricControllerXF.setLyric(null)
  5012. this.lyricControllerSingle.setLyric(null)
  5013. console.error("read file 2 data failed with error message: " + err.message);
  5014. })
  5015. .finally(() => {
  5016. fs.closeSync(file);
  5017. });
  5018. } catch (error) {
  5019. this.lyricController.setLyric(null)
  5020. this.lyricControllerSingle.setLyric(null)
  5021. this.lyricControllerXF.setLyric(null)
  5022. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  5023. }
  5024. }
  5025. //初始化悬浮歌词的自定义设置
  5026. initPipLyricSetting(){
  5027. this.lyricControllerXF
  5028. .setTextSize(this.currentLyricSize)
  5029. .setCacheSize(4)
  5030. .setTextColor("#DDDDDD")
  5031. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  5032. .setEmptyHint("")
  5033. .setAnimationDuration(1000)
  5034. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  5035. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 2)
  5036. this.setBlurDegree(this.blurDegreePip,true)
  5037. this.setLyricAlignMode(this.currentLyricAlignModePip,true)
  5038. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18),true)
  5039. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23),true)
  5040. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  5041. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'),true)
  5042. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'),true)
  5043. this.lyricControllerXF.setHightLightCenter(true)
  5044. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip',400)
  5045. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  5046. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  5047. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  5048. if(this.pipBgIndex ===0 ){
  5049. if(this.cover){
  5050. this.pipBg = this.cover
  5051. }else{
  5052. this.pipBg = this.imageColor
  5053. }
  5054. this.nodeController.updateBgColor(this.pipBg,this.lyricControllerXF)
  5055. }
  5056. }
  5057. //根据item返回歌词内容
  5058. async getLyricContent(item: VideoItem): Promise<string> {
  5059. try {
  5060. let filePath = item.filePath;
  5061. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  5062. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  5063. let isJiaMi = false;
  5064. let realLyricPath = lyricPath;
  5065. if (FileUtil.accessSync(jiaMilyricPath)) {
  5066. isJiaMi = true;
  5067. realLyricPath = jiaMilyricPath;
  5068. console.info("onecold 找到加密本地歌词");
  5069. } else {
  5070. console.info("onecold 找到本地歌词");
  5071. }
  5072. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5073. let arrayBuffer = new ArrayBuffer(4096);
  5074. const readLen = await fs.read(file.fd, arrayBuffer);
  5075. console.info("read file data succeed");
  5076. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5077. if (buf.length === 0) {
  5078. throw new Error("Buffer is empty after reading the file");
  5079. }
  5080. let detectedEncoding = chardet.detect(buf);
  5081. console.info("Detected encoding: " + detectedEncoding);
  5082. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5083. let fileContent = textDecoder.decode(buf);
  5084. console.info(`onecold The content of file1: ${fileContent}`);
  5085. if (isJiaMi) {
  5086. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  5087. }
  5088. console.info(`onecold The content of file2: ${fileContent}`);
  5089. fs.closeSync(file);
  5090. return fileContent;
  5091. } catch (error) {
  5092. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  5093. return '';
  5094. }
  5095. }
  5096. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  5097. if (StrUtil.isEmpty(filePath)) {
  5098. return
  5099. }
  5100. try {
  5101. //将content进行加密
  5102. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  5103. let lyricContent = ''
  5104. if (isJiaMi) {
  5105. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  5106. } else {
  5107. lyricContent = content
  5108. }
  5109. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  5110. // 清空文件内容
  5111. await fileIo.truncate(file.fd, 0);
  5112. await fileIo.write(file.fd, lyricContent);
  5113. await fileIo.close(file);
  5114. console.log('onecold lyric file Data saved successfully.');
  5115. } catch (error) {
  5116. console.error('onecold lyric file Failed to save data:', error);
  5117. }
  5118. }
  5119. /**
  5120. * Get largest proportion color of an image.
  5121. */
  5122. getImageColor() {
  5123. if (!this.context) {
  5124. return;
  5125. }
  5126. let bg = Utility.getMusisBg()
  5127. this.imageLabel = bg
  5128. ColorConversion.setSysBarLightBackground(true);
  5129. this.context.resourceManager.getMediaContent(bg)
  5130. .then((value: Uint8Array) => {
  5131. let buffer = value.buffer as ArrayBuffer;
  5132. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  5133. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  5134. if (error) {
  5135. Logger.error('Failed to create color picker.');
  5136. } else {
  5137. let color = colorPicker.getLargestProportionColor();
  5138. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  5139. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  5140. }
  5141. })
  5142. let headFilter = effectKit.createEffect(pixelMap);
  5143. if (headFilter !== null) {
  5144. headFilter.blur(15);
  5145. headFilter.getEffectPixelMap().then((value) => {
  5146. this.imageLabelBg = value;
  5147. })
  5148. }
  5149. })
  5150. .catch((error: BusinessError) => {
  5151. Logger.error(`${error.code} + ${error.message}`)
  5152. })
  5153. })
  5154. .catch((error: BusinessError) => {
  5155. Logger.error(`${error.code} + ${error.message}`)
  5156. })
  5157. }
  5158. setImageColor(cover: string) {
  5159. if (!this.context) {
  5160. return;
  5161. }
  5162. if (cover === undefined) {
  5163. return;
  5164. }
  5165. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  5166. let headFilter = effectKit.createEffect(value);
  5167. if (headFilter !== null) {
  5168. headFilter.blur(15);
  5169. headFilter.getEffectPixelMap().then((value) => {
  5170. this.imageLabelBg = value;
  5171. })
  5172. }
  5173. }).catch((error: BusinessError) => {
  5174. Logger.error(`${error.code} + ${error.message}`)
  5175. })
  5176. }
  5177. setImageColor2(cover: string) {
  5178. if (!this.context) {
  5179. return;
  5180. }
  5181. if (cover === undefined) {
  5182. return;
  5183. }
  5184. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  5185. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  5186. this.imageColor = data.imageColor;
  5187. if (data.blurPixelMap) {
  5188. this.imageLabelBg = data.blurPixelMap;
  5189. }
  5190. })
  5191. }
  5192. // 定义开始旋转的方法
  5193. // 定时器用于一百毫秒执行一次旋转角度
  5194. @State timer: number = 0
  5195. @State rotateAngle: number = 0
  5196. //封面旋转动画
  5197. animationRoFun() {
  5198. if (this.isPlaying && !this.isCoverRectangle) {
  5199. this.timer = setInterval(() => {
  5200. this.rotateAngle += 1
  5201. }, 100)
  5202. this.startRotation()
  5203. } else {
  5204. clearInterval(this.timer)
  5205. this.stopRotation()
  5206. }
  5207. }
  5208. // 定义开始旋转的方法
  5209. startRotation() {
  5210. if (this.isPlaying) {
  5211. animateTo({
  5212. duration: 777,
  5213. iterations: 1,
  5214. curve: Curve.Linear
  5215. }, () => {
  5216. this.rotateAngle2 = 0
  5217. })
  5218. }
  5219. }
  5220. // 回调,暂停和播放按钮回调,下一首和上一首
  5221. playChange() {
  5222. // if(this.isCoverRectangle){
  5223. // return
  5224. // }
  5225. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5226. this.setIsPlaying(true)
  5227. this.animationState = AnimationStatus.Running
  5228. } else {
  5229. this.setIsPlaying(false)
  5230. this.animationState = AnimationStatus.Paused
  5231. }
  5232. }
  5233. // 定义停止旋转的方法
  5234. stopRotation() {
  5235. if (this.isCoverRectangle) {
  5236. this.rotateAngle = 0
  5237. } else {
  5238. //唱针以左上角为点选择逆时针40度
  5239. animateTo({
  5240. duration: 1000,
  5241. curve: Curve.Linear,
  5242. iterations: 1,
  5243. }, () => {
  5244. this.rotateAngle2 = -40;
  5245. });
  5246. }
  5247. }
  5248. @Builder
  5249. private LyricsTopItem() {
  5250. Row() {
  5251. Stack() {
  5252. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  5253. .height(55)
  5254. .width(55)
  5255. .alt(this.imageLabel)
  5256. .borderRadius(8)
  5257. .clickEffect({level:ClickEffectLevel.HEAVY})
  5258. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  5259. }
  5260. .width('18%')
  5261. Column() {
  5262. Column() {
  5263. Text(this.name)
  5264. .fontSize(16)
  5265. .maxLines(1)
  5266. .fontWeight(FontWeight.Bolder)
  5267. .fontColor(this.currentLyricColor)
  5268. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  5269. Row() {
  5270. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  5271. .fontSize(13)
  5272. .fontWeight(FontWeight.Bold)
  5273. .padding({ top: 8 })
  5274. .fontColor(this.currentLyricColor)
  5275. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  5276. Blank()
  5277. }
  5278. }
  5279. .height('100%')
  5280. .width('100%')
  5281. .justifyContent(FlexAlign.Center)
  5282. .alignItems(HorizontalAlign.Start)
  5283. }
  5284. .height('100%')
  5285. .width('65%')
  5286. Column() {
  5287. Image($r('app.media.lyric'))
  5288. .width(28)
  5289. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5290. .margin({ right: 30 })
  5291. .clickEffect({level:ClickEffectLevel.HEAVY})
  5292. .onClick(() => {
  5293. this.isLyricSetting = !this.isLyricSetting;
  5294. })
  5295. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  5296. height: this.isCoverOpacity() ? '95%' : '88%',
  5297. dragBar: true,
  5298. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5299. showClose: true,
  5300. blurStyle: BlurStyle.Thin,
  5301. backgroundColor: Color.Transparent,
  5302. // title: { title: $r('app.string.lyric_setting') }
  5303. })
  5304. }
  5305. .width('18%')
  5306. }
  5307. .width('82%')
  5308. .height(58)
  5309. .justifyContent(FlexAlign.SpaceBetween)
  5310. }
  5311. //歌词显示
  5312. @Builder
  5313. PlayerLyrics() {
  5314. Column() {
  5315. Column() {
  5316. this.LyricsTopItem()
  5317. }
  5318. .height(this.isPuraWP() ? 15 : 58)
  5319. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  5320. Visibility.None: Visibility.Visible)
  5321. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  5322. .width("100%")
  5323. Column() {
  5324. LyricView2({
  5325. controller: this.lyricController,
  5326. enableSeek: true,
  5327. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  5328. seekLineColor: "#80ffffff", // 滑动定位线颜色
  5329. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  5330. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  5331. if(!this.isPlaying){
  5332. this.startPlayOrResumePlay()
  5333. }else{
  5334. this.isSeekTo = true;
  5335. this.mDestroyPage = false;
  5336. this.showLoadIng();
  5337. this.seekTo(position + "");
  5338. this.isSeekTo = false;
  5339. }
  5340. return true
  5341. }
  5342. })
  5343. .width("100%")
  5344. .layoutWeight(1)
  5345. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan() ? 40 :10 })
  5346. if(this.isPhoneLan()){
  5347. Column() {
  5348. this.playCenterView()
  5349. }
  5350. .margin({bottom:20,right:this.currentLyricAlignMode == 0?0:80})
  5351. }
  5352. }
  5353. .position({
  5354. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  5355. (this.isPuraWP() ? 58 : 99)
  5356. })
  5357. .justifyContent(FlexAlign.Center)
  5358. .height(this.isCoverOpacity() ? '95%' : '80%')
  5359. }
  5360. }
  5361. @Builder
  5362. SingleLyricView() {
  5363. Column() {
  5364. Column() {
  5365. LyricView2({ controller: this.lyricControllerSingle,
  5366. enableSeek: false,
  5367. seekUIColor: "#ff0000",// 滑动定位的按钮和文本颜色
  5368. seekLineColor: "#80ffffff",// 滑动定位线颜色
  5369. seekUIStyle: "listItem",// 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  5370. })
  5371. }
  5372. .height(48)
  5373. .margin({bottom:20})
  5374. }
  5375. }
  5376. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  5377. @Builder
  5378. BottomControl() {
  5379. Column() {
  5380. //播放 暂停,下一首,上一首
  5381. this.playCenterView()
  5382. //播放进度条
  5383. this.playProgressView()
  5384. }
  5385. .position({ bottom:this.isCoverOpacity()?55: 100 }) // 将 固定在底部
  5386. }
  5387. //播放控制上一首 下一首 暂停和播放
  5388. @Builder
  5389. playCenterView(){
  5390. Row() {
  5391. Row({ space: 33 }) {
  5392. Button({type:ButtonType.Circle,stateEffect:true}){
  5393. //更多功能
  5394. Image($r('app.media.menu'))
  5395. .width(24)
  5396. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5397. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  5398. height: this.isCoverOpacity() ? '95%' : '93%',
  5399. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5400. dragBar: true,
  5401. showClose: true,
  5402. blurStyle: BlurStyle.Thin,
  5403. backgroundColor: Color.Transparent,
  5404. })
  5405. }
  5406. .backgroundColor(Color.Transparent)
  5407. .onClick(() => {
  5408. this.isShowMoreView = !this.isShowMoreView;
  5409. })
  5410. Button({type:ButtonType.Circle,stateEffect:true}){
  5411. Image($r('app.media.ic_previous'))
  5412. .width(33)
  5413. .clickEffect({level:ClickEffectLevel.HEAVY})
  5414. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5415. .onClick(async () => {
  5416. this.playPrevious()
  5417. })
  5418. }
  5419. .backgroundColor(Color.Transparent)
  5420. }
  5421. // .margin({ left: 20 })
  5422. Button({type:ButtonType.Circle,stateEffect:true}){
  5423. Column() {
  5424. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  5425. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  5426. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  5427. .width(this.isPhoneLan()?48:60)
  5428. .clickEffect({level:ClickEffectLevel.HEAVY})
  5429. .fillColor(Color.White)
  5430. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5431. .onClick(async () => {
  5432. this.playOrPause()
  5433. })
  5434. }
  5435. }
  5436. .backgroundColor(Color.Transparent)
  5437. .layoutWeight(1)
  5438. .margin({ left: 33, right: 33 })
  5439. Row({ space: 33 }) {
  5440. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5441. Image($r('app.media.ic_next'))
  5442. .width(33)
  5443. .clickEffect({level:ClickEffectLevel.HEAVY})
  5444. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5445. .onClick(() => {
  5446. this.playNext();
  5447. })
  5448. }
  5449. .backgroundColor(Color.Transparent)
  5450. .width(33)
  5451. Button({type:ButtonType.Circle,stateEffect:true}){
  5452. //添加或取消收藏
  5453. Image(Utility.getIsFav(this.favList,this.currentSong)?
  5454. $r('app.media.add_fac_light'):$r('app.media.add_fac'))
  5455. .width(24)
  5456. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5457. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5458. .onClick(async () => {
  5459. if(this.currentSong){
  5460. this.doFav(this.currentSong)
  5461. }
  5462. })
  5463. }
  5464. .backgroundColor(Color.Transparent)
  5465. .width(24)
  5466. }
  5467. // .margin({ right: 33 })
  5468. }
  5469. .width('100%')
  5470. .margin({ left:10,right:10,bottom:this.isCoverOpacity()?0:20 })
  5471. .justifyContent(FlexAlign.Center)
  5472. }
  5473. //播放进度条
  5474. @Builder
  5475. playProgressView(){
  5476. Row() {
  5477. Button({type:ButtonType.Circle,stateEffect:true}){
  5478. Column() {
  5479. if (this.playType === 0) {
  5480. Image($r('app.media.loop'))
  5481. .width($r('app.float.control_image_width'))
  5482. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5483. } else if (this.playType === 1) {
  5484. Image($r('app.media.single'))
  5485. .width($r('app.float.control_image_width'))
  5486. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5487. } else if (this.playType === 2) {
  5488. Image($r('app.media.normal_play'))
  5489. .width($r('app.float.control_image_width'))
  5490. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5491. } else if (this.playType === 3) {
  5492. Image($r('app.media.random'))
  5493. .width($r('app.float.control_image_width'))
  5494. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5495. }
  5496. }
  5497. }
  5498. .backgroundColor(Color.Transparent)
  5499. .margin({ left:10,right:10 })
  5500. .onClick(async () => {
  5501. this.setLoopMode()
  5502. })
  5503. Text(this.currentTime)
  5504. .fontSize($r('app.float.slider_font_size'))
  5505. .fontColor(Color.White)
  5506. .margin(3)
  5507. Slider({
  5508. value: this.progressValue,
  5509. min: 0,
  5510. max: this.PROGRESS_MAX_VALUE,
  5511. step: 1,
  5512. style: SliderStyle.OutSet
  5513. })
  5514. .width('600px')
  5515. .blockColor(Color.White)
  5516. .trackColor($r('app.color.track_color'))
  5517. .selectedColor(Color.White)
  5518. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  5519. .layoutWeight(1)
  5520. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  5521. .showSteps(true)
  5522. .showTips(true)
  5523. .enabled(this.slideEnable)
  5524. .onChange((value: number, mode: SliderChangeMode) => {
  5525. // if (mode == 2) {
  5526. this.isSeekTo = true;
  5527. this.mDestroyPage = false;
  5528. this.showLoadIng();
  5529. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  5530. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  5531. this.seekTo(seekValue + "");
  5532. // this.setProgress()
  5533. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  5534. this.isSeekTo = false;
  5535. // }
  5536. })
  5537. Text(this.totalTime)
  5538. .fontSize($r('app.float.slider_font_size'))
  5539. .fontColor(Color.White)
  5540. .margin(3)
  5541. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  5542. //播放列表
  5543. Button({type:ButtonType.Circle,stateEffect:true}){
  5544. Image($r('app.media.playlist'))
  5545. .width($r('app.float.control_image_width'))
  5546. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5547. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  5548. height: '95%',
  5549. dragBar: true,
  5550. showClose: true,
  5551. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5552. blurStyle: BlurStyle.Thin,
  5553. backgroundColor: Color.Transparent,
  5554. title: {
  5555. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5556. + `(${this.songList.length}首)`
  5557. }
  5558. })
  5559. }
  5560. .backgroundColor(Color.Transparent)
  5561. .margin({ right: 10, left: 20 })
  5562. .onClick(() => {
  5563. this.isShowSheetView = !this.isShowSheetView;
  5564. this.isFrontWhite = true
  5565. setTimeout(() => {
  5566. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5567. }, 123)
  5568. })
  5569. }
  5570. .width(PlayConstants.PROGRESS_ROW_WIDTH)
  5571. .height(this.isPhoneLan()?25:33)
  5572. // .visibility(this.isPhoneLan()&&this.isAutoHide?Visibility.None:Visibility.Visible)
  5573. .animation({
  5574. duration: 666,
  5575. curve: 'ease-in-out' // 可选动画曲线
  5576. })
  5577. }
  5578. isBigScreen(){
  5579. if(this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG){
  5580. return true
  5581. }
  5582. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5583. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5584. &&this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  5585. return false
  5586. }else{
  5587. return true
  5588. }
  5589. return false
  5590. }
  5591. @State isAutoHide: boolean = true//手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  5592. @State isCoverRectangle: boolean = false
  5593. @State isCoverTop: boolean = true
  5594. @Builder
  5595. CoverInfo() {
  5596. Column() {
  5597. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  5598. if(this.isCoverRectangle){
  5599. if(!this.isCoverTop){
  5600. this.musicNameInfo(false)
  5601. }
  5602. }else{
  5603. this.musicNameInfo(false)
  5604. }
  5605. Stack() {
  5606. // 唱片旋转效果
  5607. Image($r('app.media.ic_music_disc'))
  5608. .width(250)
  5609. .height(250)
  5610. .margin({ right: 20, left: 20 })
  5611. .aspectRatio(1)
  5612. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  5613. .visibility(this.isCoverOpacity() || this.isCoverRectangle?Visibility.None:Visibility.Visible)
  5614. .borderRadius('100%')
  5615. .align(Alignment.Center)
  5616. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  5617. .rotate({
  5618. angle: this.rotateAngle,
  5619. centerX: "50%",
  5620. centerY: "50%",
  5621. })
  5622. .animation({
  5623. duration: 100,
  5624. curve: Curve.Linear
  5625. })
  5626. .shadow({
  5627. radius: 30,
  5628. color: this.randomColor
  5629. })
  5630. Column(){
  5631. if(this.isCoverTop&&!this.isCoverOpacity()&&this.isCoverRectangle){
  5632. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  5633. // .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  5634. .width(this.isBigScreen()?'72%':this.isCoverTopBig?'100%':'86%')
  5635. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  5636. .alt(this.imageLabel)
  5637. .margin({ right: 8, left: 8,top:8 })
  5638. .aspectRatio(1)
  5639. .visibility(this.isPuraWP()?Visibility.None:Visibility.Visible)
  5640. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  5641. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5642. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5643. TransitionEffect.scale({ x: 0, y: 0 }) ))
  5644. .align(Alignment.Center)//
  5645. .clip(true)
  5646. .rotate({
  5647. x: 0,
  5648. y: 0,
  5649. z: 1,
  5650. angle: this.rotateAngle
  5651. })
  5652. .onClick(() => {
  5653. this.getImageColor()
  5654. })
  5655. this.musicNameInfo(false)
  5656. }else{
  5657. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  5658. .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  5659. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  5660. .alt(this.imageLabel)
  5661. .margin({ right: 20, left: 20 })
  5662. .aspectRatio(1)
  5663. .visibility(this.isPuraWP()?Visibility.None:Visibility.Visible)
  5664. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  5665. .clickEffect({level:ClickEffectLevel.MIDDLE})
  5666. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5667. TransitionEffect.scale({ x: 0, y: 0 }) ))
  5668. .align(Alignment.Center)//
  5669. .clip(true)
  5670. .rotate({
  5671. x: 0,
  5672. y: 0,
  5673. z: 1,
  5674. angle: this.rotateAngle
  5675. })
  5676. .onClick(() => {
  5677. this.getImageColor()
  5678. })
  5679. }
  5680. }
  5681. // 唱针以左上角为点选择逆时针40度
  5682. Image($r('app.media.ic_music_cover_hand'))
  5683. .height(130)
  5684. .margin({ bottom: 220, top: 0 })
  5685. .align(Alignment.Top)
  5686. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  5687. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  5688. .visibility(this.isCoverOpacity() || this.isCoverRectangle?Visibility.None:Visibility.Visible)
  5689. Column({ space: 8 }) {
  5690. Text(this.name)
  5691. .fontSize(this.isPuraWP()?24:(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  5692. .fontWeight(FontWeight.Bold)
  5693. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5694. .maxLines(1)
  5695. .width('48%')
  5696. .textAlign(TextAlign.Center)
  5697. .fontColor(Color.White)
  5698. .visibility(this.isPhoneLan()?Visibility.None:Visibility.Visible)
  5699. Text(this.artist)
  5700. .fontSize(this.isPuraWP()?18:(this.isCoverOpacity() ? 12 : 15))
  5701. .fontColor(Color.White)
  5702. .fontWeight(FontWeight.Bold)
  5703. .visibility(this.isPhoneLan()?Visibility.None:Visibility.Visible)
  5704. }
  5705. .justifyContent(FlexAlign.Start)
  5706. .zIndex(1)
  5707. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  5708. }
  5709. .margin({
  5710. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  5711. (this.isPhonePortrait()&&this.isShowSingleLineLyric?20:55) : 0,
  5712. top: this.isCoverOpacity() ? 0 : 20
  5713. })
  5714. if(this.isPhonePortrait()&&this.isShowSingleLineLyric){
  5715. this.SingleLyricView()
  5716. }
  5717. if(this.isPhoneLan()){
  5718. Column(){
  5719. Text(this.name)
  5720. .fontSize(18)
  5721. .fontWeight(FontWeight.Bold)
  5722. .textOverflow({ overflow: TextOverflow.Ellipsis })
  5723. .maxLines(1)
  5724. .width('99%')
  5725. .textAlign(TextAlign.Center)
  5726. .fontColor(Color.White)
  5727. Text(this.artist + ' ' + this.currentSong?.album)
  5728. .fontSize(15)
  5729. .visibility(Visibility.Hidden)
  5730. .textOverflow({ overflow: TextOverflow.Ellipsis })
  5731. .fontColor(Color.White)
  5732. .textAlign(TextAlign.Center)
  5733. .width('99%')
  5734. .maxLines(1)
  5735. this.playProgressView()
  5736. }
  5737. .position({bottom:45})
  5738. }else{
  5739. this.BottomControl()
  5740. }
  5741. }
  5742. .width(CommonConstants.FULL_PERCENT)
  5743. .clip(true)
  5744. }
  5745. @Builder
  5746. private musicNameInfo(isHidden:boolean) {
  5747. Column({ space: 8 }) {
  5748. Text(this.name)
  5749. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  5750. .fontWeight(FontWeight.Bold)
  5751. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5752. .maxLines(1)
  5753. .width('99%')
  5754. .textAlign(TextAlign.Center)
  5755. .fontColor(Color.White)
  5756. Text(this.artist + ' ' + this.currentSong?.album)
  5757. .fontSize(this.isCoverOpacity() ? 12 : 15)
  5758. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5759. .fontColor(Color.White)
  5760. .textAlign(TextAlign.Center)
  5761. .width('99%')
  5762. .maxLines(1)
  5763. }
  5764. .margin({ top: this.isCoverOpacity() ? 20 : isHidden?40:20 })
  5765. .zIndex(1)
  5766. .visibility(this.isCoverOpacity()||isHidden ? Visibility.None : Visibility.Visible)
  5767. }
  5768. @Builder
  5769. private PlayTitle() {
  5770. Row() {
  5771. Row() {
  5772. Image($r('app.media.ic_back_down'))
  5773. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  5774. .hitTestBehavior(HitTestMode.Transparent)
  5775. Text(this.name + ' ' + this.artist)
  5776. .fontColor(Color.White)
  5777. .fontSize($r('app.float.title_font_size'))
  5778. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5779. .maxLines(1)
  5780. .visibility(Visibility.None)
  5781. .margin({ left: 2, right: 30 })
  5782. }
  5783. .layoutWeight(1)
  5784. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  5785. .onClick(() => {
  5786. this.isShowPlay = false;
  5787. })
  5788. Column() {
  5789. AVCastPicker({
  5790. normalColor: Color.White,
  5791. onStateChange: this.onStateVastChange
  5792. })
  5793. .width(24)
  5794. .height(24)
  5795. }
  5796. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  5797. //更多功能
  5798. // Image( $r('app.media.two_point') )
  5799. // .width(24)
  5800. // .visibility(this.isHide?Visibility.None:Visibility.Visible)
  5801. // .margin({left:13})
  5802. // .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  5803. // height:this.isCoverOpacity()?'95%':'85%',
  5804. // dragBar: true,
  5805. // showClose: true,
  5806. // blurStyle:BlurStyle.Thin,
  5807. // backgroundColor:Color.Transparent,
  5808. // })
  5809. // .onClick(() => {
  5810. // this.isShowMoreView = !this.isShowMoreView;
  5811. // })
  5812. }
  5813. .width(PlayConstants.ROW_WIDTH)
  5814. }
  5815. @Builder
  5816. lyricSettingSheet(isPip:boolean) {
  5817. Scroll() {
  5818. this.lyricSetting(isPip)
  5819. }
  5820. .width('100%')
  5821. .height('100%')
  5822. }
  5823. @Builder
  5824. lyricSetting(isPip:boolean) {
  5825. Column() {
  5826. // 时间调节模块
  5827. if(!isPip){
  5828. this.BuildTimeControls()
  5829. }
  5830. // 字号控制模块
  5831. this.BuildFontControls(isPip)
  5832. }
  5833. }
  5834. // 歌词时间偏移状态
  5835. @State timeOffset: number = 0.0
  5836. @State currentLyricColor: string = '#FFFFFF'
  5837. @State currentLyricColorPip: string = '#FFFFFF'
  5838. @State currentHighLightLyricColor: string = '#FF4081'
  5839. @State currentHighLightLyricColorPip: string = '#FF4081'
  5840. // 歌词字号状态
  5841. @State currentLyricSize: number = 20
  5842. @State currentLyricSizePip: number = 20
  5843. // 高亮歌词放大倍数
  5844. @State currentHightLyricSize: number = 1.2
  5845. @State currentHightLyricSizePip: number = 1.2
  5846. @State currentLyricLineSpace: number = 10
  5847. @State currentLyricLineSpacePip: number = 10
  5848. @State currentLyricAlignMode: number = 1
  5849. @State currentLyricAlignModePip: number = 1
  5850. @State blurDegree: number = 2
  5851. @State blurDegreePip: number = 2
  5852. @State isShowSelectColor: boolean = false
  5853. @State isShowHLSelectColor: boolean = false
  5854. @State isShowPipBgSelectColor: boolean = false
  5855. @State pipLyWidth: number = 330
  5856. @State pipLyHeight: number = 120
  5857. // 构建颜色选择器
  5858. @Builder
  5859. SelectColor(isHighColor:boolean,isPip:boolean,isBGPip?:boolean) {
  5860. Row({space: 10}) {
  5861. HSBColorPicker({
  5862. color: '#FFFFFF',
  5863. radius: 8,
  5864. layout: HSBColorPickerLayout.COLUMN,
  5865. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4', '#fa7105'],
  5866. onChange:(value: string) =>isHighColor?this.changeLyricHightLightColor(value,isPip):this.changeLyricColor(value,isPip,isBGPip)
  5867. })
  5868. .height(250)
  5869. .layoutWeight(1)
  5870. .padding(25)
  5871. }
  5872. .width('66%')
  5873. }
  5874. @State isOpenPip:boolean = false
  5875. @State pipBgIndex:number = 0
  5876. // 构建字号控制器
  5877. @Builder
  5878. BuildFontControls(isPip:boolean) {
  5879. Column() {
  5880. if(isPip){
  5881. Column() {
  5882. Row() {
  5883. Text('悬浮歌词')
  5884. .margin({ left: 18 })
  5885. .fontSize(15)
  5886. .fontColor(Color.White)
  5887. .fontWeight(480)
  5888. .layoutWeight(1)
  5889. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  5890. .selectedColor(this.themeColor)
  5891. .switchPointColor(Color.White)
  5892. .margin({ right: 18 })
  5893. .onChange((checked: boolean) => {
  5894. this.isOpenPip = checked;
  5895. if(this.isOpenPip){
  5896. this.startPip()
  5897. }else{
  5898. this.stopPip()
  5899. }
  5900. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  5901. })
  5902. .width(50)
  5903. .height(30);
  5904. }
  5905. .height(55)
  5906. }
  5907. .backgroundColor(Color.Transparent)
  5908. .borderRadius(15)
  5909. .margin({ left: 30, right: 30, top: 0, bottom: 20 })
  5910. .padding(0)
  5911. .border({
  5912. color: Color.White,
  5913. width: 1.8
  5914. })
  5915. }
  5916. Row() {
  5917. Text(`歌词居中:`)
  5918. .fontSize(14)
  5919. .fontColor(Color.White)
  5920. .margin({left:2})
  5921. Row() {
  5922. ForEach(['居中', '居左'], (size: string, index: number) => {
  5923. Button(size)
  5924. .width(60)
  5925. .height(28)
  5926. .fontSize(12)
  5927. .fontColor('#FFFFFF')
  5928. .backgroundColor((!isPip&&this.currentLyricAlignMode === index)||(isPip&&this.currentLyricAlignModePip === index) ? this.themeColor :Color.Transparent)
  5929. .border({
  5930. color: (!isPip&&this.currentLyricAlignMode === index) || (isPip&&this.currentLyricAlignModePip === index)?
  5931. '#007DFF' : '#DDDDDD',
  5932. width: 1.8
  5933. })
  5934. .onClick(() => {
  5935. this.setLyricAlignMode(index,isPip)
  5936. })
  5937. .margin({ left: 10, right: 8 })
  5938. })
  5939. }
  5940. .width('76%')
  5941. Blank()
  5942. }
  5943. .margin({ top:10,bottom:10,right:20,left:20})
  5944. if(isPip){
  5945. Row() {
  5946. Text(`悬浮背景:`)
  5947. .fontSize(14)
  5948. .fontColor(Color.White)
  5949. Select([
  5950. { value:CommonConstants.PIP_LYRIC_BG[0]},
  5951. { value: CommonConstants.PIP_LYRIC_BG[1]}])
  5952. .font({ size: 13, weight: FontWeight.Medium })
  5953. .fontColor(Color.White)
  5954. .margin({ left: 10 })
  5955. .selected(this.pipBgIndex)
  5956. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  5957. .onSelect(async (_index: number, text?: string | undefined) => {
  5958. this.pipBgIndex = _index
  5959. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  5960. if(this.pipBgIndex ===0 ){
  5961. if(this.cover){
  5962. this.pipBg = this.cover
  5963. }else{
  5964. this.pipBg = this.imageColor
  5965. }
  5966. this.nodeController.updateBgColor(this.pipBg,this.lyricControllerXF)
  5967. }else{
  5968. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  5969. }
  5970. })
  5971. Column(){}
  5972. .backgroundColor(this.pipBg)
  5973. .margin({ left:10,right: 10 })
  5974. .borderRadius(20)
  5975. .height(28)
  5976. .width(28)
  5977. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5978. Row() {
  5979. SymbolGlyph($r('sys.symbol.paintbrush'))
  5980. .fontColor([Color.White])
  5981. .effectStrategy(1)
  5982. Text(`选择颜色`)
  5983. .fontSize(13)
  5984. .margin({ left: 10 })
  5985. .fontColor(Color.White)
  5986. }
  5987. }
  5988. .visibility(this.pipBgIndex===1?Visibility.Visible:Visibility.None)
  5989. .backgroundColor(Color.Transparent)
  5990. .border({
  5991. color: '#FFFFFF',
  5992. radius: 20,
  5993. width: 1.8
  5994. })
  5995. .height(36)
  5996. .width(110)
  5997. .onClick(()=>{
  5998. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  5999. })
  6000. .bindPopup(this.isShowPipBgSelectColor, {
  6001. builder: this.SelectColor(false,isPip,true),
  6002. placement: Placement.Top,
  6003. mask: {color:'#33000000'},
  6004. enableArrow: false,//是否显示箭头
  6005. showInSubWindow: false,
  6006. onStateChange: (e) => {
  6007. if (!e.isVisible) {
  6008. this.isShowPipBgSelectColor = false
  6009. }
  6010. }
  6011. })
  6012. }
  6013. .width('76%')
  6014. .margin({ bottom:5,right:45,left:20})
  6015. }
  6016. if(!isPip){
  6017. Row() {
  6018. Text(`高亮居中:`)
  6019. .fontSize(14)
  6020. .fontColor(Color.White)
  6021. Column(){
  6022. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  6023. .selectedColor(this.themeColor)
  6024. .switchPointColor(Color.White)
  6025. .onChange((checked: boolean) => {
  6026. this.isHightLightCenter = checked;
  6027. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  6028. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6029. })
  6030. .width(50)
  6031. .height(30)
  6032. .alignSelf(ItemAlign.Start)
  6033. .margin({ left: 12 })
  6034. Blank()
  6035. }
  6036. .width('76%')
  6037. }
  6038. .margin({
  6039. left: 20,
  6040. right: 15,
  6041. top: 10,
  6042. bottom: 10
  6043. })
  6044. }
  6045. Row() {
  6046. Text(`歌词颜色:`)
  6047. .fontSize(14)
  6048. .fontColor(Color.White)
  6049. Text(isPip?this.currentLyricColorPip:this.currentLyricColor)
  6050. .fontSize(15)
  6051. .fontColor(Color.White)
  6052. .margin({ left: 12, right: 12 })
  6053. Column(){}
  6054. .backgroundColor(isPip?this.currentLyricColorPip:this.currentLyricColor)
  6055. .margin({ right: 12 })
  6056. .borderRadius(20)
  6057. .height(28)
  6058. .width(28)
  6059. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6060. Row() {
  6061. SymbolGlyph($r('sys.symbol.paintbrush'))
  6062. .fontColor([Color.White])
  6063. .effectStrategy(1)
  6064. Text(`选择颜色`)
  6065. .fontSize(13)
  6066. .margin({ left: 10 })
  6067. .fontColor(Color.White)
  6068. }
  6069. }
  6070. .backgroundColor(Color.Transparent)
  6071. .border({
  6072. color: '#FFFFFF',
  6073. radius: 20,
  6074. width: 1.8
  6075. })
  6076. .height(36)
  6077. .width(110)
  6078. .onClick(()=>{
  6079. this.isShowSelectColor = !this.isShowSelectColor
  6080. })
  6081. .bindPopup(this.isShowSelectColor, {
  6082. builder: this.SelectColor(false,isPip),
  6083. placement: Placement.Top,
  6084. mask: {color:'#33000000'},
  6085. enableArrow: false,//是否显示箭头
  6086. showInSubWindow: false,
  6087. onStateChange: (e) => {
  6088. if (!e.isVisible) {
  6089. this.isShowSelectColor = false
  6090. }
  6091. }
  6092. })
  6093. }
  6094. .width('76%')
  6095. .margin({ top:10,bottom:10,right:45,left:20})
  6096. Row() {
  6097. Text(`高亮颜色:`)
  6098. .fontSize(14)
  6099. .fontColor(Color.White)
  6100. Text(isPip?this.currentHighLightLyricColorPip:this.currentHighLightLyricColor)
  6101. .fontSize(15)
  6102. .fontColor(Color.White)
  6103. .margin({ left: 12, right: 12 })
  6104. Column(){}
  6105. .backgroundColor(isPip?this.currentHighLightLyricColorPip:this.currentHighLightLyricColor)
  6106. .margin({ right: 12 })
  6107. .borderRadius(20)
  6108. .height(28)
  6109. .width(28)
  6110. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6111. Row() {
  6112. SymbolGlyph($r('sys.symbol.paintbrush'))
  6113. .fontColor([Color.White])
  6114. .effectStrategy(1)
  6115. Text(`选择颜色`)
  6116. .fontSize(13)
  6117. .margin({ left: 10 })
  6118. .fontColor(Color.White)
  6119. }
  6120. }
  6121. .backgroundColor(Color.Transparent)
  6122. .border({
  6123. color: '#FFFFFF',
  6124. radius: 20,
  6125. width: 1.8
  6126. })
  6127. .height(36)
  6128. .width(110)
  6129. .onClick(()=>{
  6130. this.isShowHLSelectColor = !this.isShowHLSelectColor
  6131. })
  6132. .bindPopup(this.isShowHLSelectColor, {
  6133. builder: this.SelectColor(true,isPip),
  6134. placement: Placement.Top,
  6135. mask: {color:'#33000000'},
  6136. enableArrow: false,//是否显示箭头
  6137. showInSubWindow: false,
  6138. onStateChange: (e) => {
  6139. if (!e.isVisible) {
  6140. this.isShowHLSelectColor = false
  6141. }
  6142. }
  6143. })
  6144. }
  6145. .width('76%')
  6146. .margin({ top:10,bottom:10,right:45,left:20})
  6147. if(isPip){
  6148. Row() {
  6149. Text(`显示宽度:`)
  6150. .fontSize(14)
  6151. .fontColor(Color.White)
  6152. Slider({
  6153. value: this.pipLyWidth,
  6154. min: 10,
  6155. max: 800,
  6156. step: 1,
  6157. style: SliderStyle.OutSet
  6158. })
  6159. .blockColor(this.themeColor)
  6160. .trackColor($r('app.color.speed_text_color'))
  6161. .selectedColor(Color.White)
  6162. .trackThickness(6)
  6163. .onChange((value: number) => {
  6164. this.pipLyWidth = value
  6165. if(this.pipController){
  6166. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  6167. PreferencesUtil.putSync('pipLyWidth',this.pipLyWidth)
  6168. }
  6169. })
  6170. .width('76%')
  6171. }
  6172. .margin({
  6173. left: 20,
  6174. right: 15,
  6175. top: 5,
  6176. bottom: 5
  6177. })
  6178. Row() {
  6179. Text(`显示高度:`)
  6180. .fontSize(14)
  6181. .fontColor(Color.White)
  6182. Slider({
  6183. value: this.pipLyHeight,
  6184. min: 10,
  6185. max: 1000,
  6186. step: 1,
  6187. style: SliderStyle.OutSet
  6188. })
  6189. .blockColor(this.themeColor)
  6190. .trackColor($r('app.color.speed_text_color'))
  6191. .selectedColor(Color.White)
  6192. .trackThickness(6)
  6193. .onChange((value: number) => {
  6194. this.pipLyHeight = value
  6195. if(this.pipController){
  6196. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  6197. PreferencesUtil.putSync('pipLyHeight',this.pipLyHeight)
  6198. }
  6199. })
  6200. .width('76%')
  6201. }
  6202. .margin({
  6203. left: 20,
  6204. right: 15,
  6205. top: 5,
  6206. bottom: 5
  6207. })
  6208. }
  6209. Row() {
  6210. Text(`歌词字号:`)
  6211. .fontSize(14)
  6212. .fontColor(Color.White)
  6213. Slider({
  6214. value: isPip?this.currentLyricSizePip:this.currentLyricSize,
  6215. min: 12,
  6216. max: 30,
  6217. step: 0.1,
  6218. style: SliderStyle.OutSet
  6219. })
  6220. .blockColor(this.themeColor)
  6221. .trackColor($r('app.color.speed_text_color'))
  6222. .selectedColor(Color.White)
  6223. .trackThickness(6)
  6224. .onChange((value: number) => {
  6225. this.setLyricTextSize(value,isPip)
  6226. })
  6227. .width('76%')
  6228. }
  6229. .margin({
  6230. left: 20,
  6231. right: 15,
  6232. top: 5,
  6233. bottom: 5
  6234. })
  6235. Row() {
  6236. Text(`高亮倍数:`)
  6237. .fontSize(14)
  6238. .fontColor(Color.White)
  6239. Slider({
  6240. value: isPip?this.currentHightLyricSizePip:this.currentHightLyricSize,
  6241. min: 1,
  6242. max: 2,
  6243. step: 0.1,
  6244. style: SliderStyle.OutSet
  6245. })
  6246. .blockColor(this.themeColor)
  6247. .trackColor($r('app.color.speed_text_color'))
  6248. .selectedColor(Color.White)
  6249. .trackThickness(6)
  6250. .onChange((value: number) => {
  6251. this.setHighLyricTextSize(value,isPip)
  6252. })
  6253. .width('76%')
  6254. }
  6255. .margin({
  6256. left: 20,
  6257. right: 15,
  6258. top: 5,
  6259. bottom: 5
  6260. })
  6261. Row() {
  6262. Text(`歌词间隙:`)
  6263. .fontSize(14)
  6264. .fontColor(Color.White)
  6265. Slider({
  6266. value: isPip?this.currentLyricLineSpacePip:this.currentLyricLineSpace,
  6267. min: 2,
  6268. max: 120,
  6269. step: 1,
  6270. style: SliderStyle.OutSet
  6271. })
  6272. .blockColor(this.themeColor)
  6273. .trackColor($r('app.color.speed_text_color'))
  6274. .selectedColor(Color.White)
  6275. .trackThickness(6)
  6276. .onChange((value: number) => {
  6277. this.setLyricLineSpace(value,isPip)
  6278. })
  6279. .width('76%')
  6280. }
  6281. .margin({
  6282. left: 20,
  6283. right: 15,
  6284. top: 5,
  6285. bottom: 5
  6286. })
  6287. //取值间隔为100,默认为400,取值越大,字体越粗
  6288. Row() {
  6289. Text(`歌词字重:`)
  6290. .fontSize(14)
  6291. .fontColor(Color.White)
  6292. Slider({
  6293. value: isPip?this.lyricTextWeightPip:this.lyricTextWeight,
  6294. min: 100,
  6295. max: 900,
  6296. step: 100,
  6297. style: SliderStyle.OutSet
  6298. })
  6299. .blockColor(this.themeColor)
  6300. .trackColor($r('app.color.speed_text_color'))
  6301. .selectedColor(Color.White)
  6302. .trackThickness(6)
  6303. .onChange((value: number) => {
  6304. if(isPip){
  6305. this.lyricTextWeightPip = value
  6306. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  6307. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  6308. }else{
  6309. this.lyricTextWeight = value
  6310. this.lyricController.setTextWeight(this.lyricTextWeight)
  6311. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  6312. }
  6313. })
  6314. .width('76%')
  6315. }
  6316. .margin({
  6317. left: 20,
  6318. right: 15,
  6319. top: 5,
  6320. bottom: 5
  6321. })
  6322. if(!isPip){
  6323. Row() {
  6324. Text(`歌词模糊:`)
  6325. .fontSize(14)
  6326. .fontColor(Color.White)
  6327. Slider({
  6328. value: isPip?this.blurDegreePip:this.blurDegree,
  6329. min: 0,
  6330. max: 10,
  6331. step: 0.1,
  6332. style: SliderStyle.OutSet
  6333. })
  6334. .blockColor(this.themeColor)
  6335. .trackColor($r('app.color.speed_text_color'))
  6336. .selectedColor(Color.White)
  6337. .trackThickness(6)
  6338. .onChange((value: number) => {
  6339. this.setBlurDegree(value,isPip)
  6340. })
  6341. .width('76%')
  6342. }
  6343. .margin({
  6344. left: 20,
  6345. right: 15,
  6346. top: 5,
  6347. bottom: 15
  6348. })
  6349. }
  6350. Row() {
  6351. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  6352. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  6353. }
  6354. .justifyContent(FlexAlign.Center)
  6355. .margin({ top: 3, bottom: 10 })
  6356. }
  6357. }
  6358. private setBlurDegree(index: number,isPip:boolean) {
  6359. if(isPip){
  6360. this.blurDegreePip = index
  6361. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  6362. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  6363. }else{
  6364. this.blurDegree = index
  6365. this.lyricController.setBlurDegree(this.blurDegree)
  6366. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  6367. }
  6368. }
  6369. private setLyricAlignMode(index: number,isPip:boolean) {
  6370. if(isPip){
  6371. this.currentLyricAlignModePip = index
  6372. if (this.currentLyricAlignModePip === 1) {
  6373. this.lyricControllerXF.setAlignMode("left")
  6374. } else {
  6375. this.lyricControllerXF.setAlignMode("center")
  6376. }
  6377. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  6378. }else{
  6379. this.currentLyricAlignMode = index
  6380. if (this.currentLyricAlignMode === 1) {
  6381. this.lyricController.setAlignMode("left")
  6382. } else {
  6383. this.lyricController.setAlignMode("center")
  6384. }
  6385. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  6386. }
  6387. }
  6388. private setLyricTextSize(index: number,isPip:boolean) {
  6389. if(isPip){
  6390. this.currentLyricSizePip = index
  6391. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  6392. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  6393. }else{
  6394. this.currentLyricSize = index
  6395. this.lyricController.setTextSize(this.currentLyricSize)
  6396. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  6397. }
  6398. }
  6399. private setHighLyricTextSize(scale: number,isPip:boolean) {
  6400. if(isPip){
  6401. this.currentHightLyricSizePip = scale
  6402. this.lyricControllerXF
  6403. .setHighlightScale(this.currentHightLyricSizePip)
  6404. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  6405. }else{
  6406. this.currentHightLyricSize = scale
  6407. this.lyricController
  6408. .setHighlightScale(this.currentHightLyricSize)
  6409. PreferencesUtil.putSync('HighLyricTextSize', scale)
  6410. }
  6411. }
  6412. private setLyricLineSpace(index: number,isPip:boolean) {
  6413. if(isPip){
  6414. this.currentLyricLineSpacePip = index
  6415. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  6416. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  6417. }else{
  6418. this.currentLyricLineSpace = index
  6419. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  6420. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  6421. }
  6422. }
  6423. private changeLyricColor(color: string,isPip:boolean,isBG?:boolean) {
  6424. LogUtil.info('onecold isBG = '+isBG)
  6425. if(isBG){//如果是设置悬浮背景
  6426. this.pipBg = color
  6427. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  6428. this.nodeController.updateBgColor(this.pipBg,this.lyricControllerXF)
  6429. return
  6430. }
  6431. if(isPip){
  6432. this.currentLyricColorPip = color
  6433. this.lyricControllerXF
  6434. .setTextColor(this.currentLyricColorPip)
  6435. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  6436. }else{
  6437. this.currentLyricColor = color
  6438. this.lyricController
  6439. .setTextColor(this.currentLyricColor)
  6440. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  6441. }
  6442. }
  6443. private changeLyricHightLightColor(color: string,isPip:boolean) {
  6444. if(isPip){
  6445. this.currentHighLightLyricColorPip = color
  6446. this.lyricControllerXF
  6447. .setHighlightColor(this.currentHighLightLyricColorPip)
  6448. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  6449. }else{
  6450. this.currentHighLightLyricColor = color
  6451. this.lyricController
  6452. .setHighlightColor(this.currentHighLightLyricColor)
  6453. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  6454. }
  6455. }
  6456. // 构建时间控制器
  6457. @Builder
  6458. BuildTimeControls() {
  6459. Column() {
  6460. // 时间显示
  6461. Text(this.getTimeText())
  6462. .fontSize(18)
  6463. .fontColor(Color.White)
  6464. .margin({ bottom: 10 })
  6465. Row() {
  6466. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  6467. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  6468. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  6469. }
  6470. .justifyContent(FlexAlign.Center)
  6471. }
  6472. .margin({ top: 12, bottom: 8 })
  6473. }
  6474. // 精度按钮组件
  6475. @Builder
  6476. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  6477. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6478. Column() {
  6479. Image(icon)
  6480. .width(28)
  6481. .margin({ bottom: 5 })
  6482. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  6483. Text(label)
  6484. .fontSize(12)
  6485. .fontColor('#FFFFFF')
  6486. }
  6487. }
  6488. .backgroundColor(Color.Transparent)
  6489. .enabled(!this.isButtonDisabled(step))
  6490. .onClick(() => this.handlePrecisionAdjust(step))
  6491. .padding(5)
  6492. .width(66)
  6493. .height(66)
  6494. .margin({ left: 18, right: 18 })
  6495. .border({
  6496. color: '#FFFFFF',
  6497. width: 1.8
  6498. })
  6499. }
  6500. private handlePrecisionAdjust(step: number) {
  6501. if (step === 0) {
  6502. this.timeOffset = 0
  6503. return
  6504. }
  6505. // 精度处理:保留1位小数
  6506. const newOffset = Number((this.timeOffset + step).toFixed(5))
  6507. // 边界保护(±15.0秒)
  6508. if (newOffset < -30.0 || newOffset > 30.0) {
  6509. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  6510. return
  6511. }
  6512. // 状态更新
  6513. this.timeOffset = newOffset
  6514. }
  6515. // 按钮禁用逻辑
  6516. private isButtonDisabled(step: number): boolean {
  6517. const futureOffset = this.timeOffset + step
  6518. return (futureOffset < -30.0) || (futureOffset > 30.0)
  6519. }
  6520. // 时间显示文本升级
  6521. private getTimeText(): string {
  6522. const absValue = Math.abs(this.timeOffset)
  6523. return this.timeOffset === 0
  6524. ? '歌词时间已重置'
  6525. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  6526. }
  6527. // 导入 本地歌词 搜索歌词
  6528. @Builder
  6529. pushLyricButton(icon: Resource, step: number, label: string) {
  6530. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6531. Row() {
  6532. Image(icon)
  6533. .width(14)
  6534. .margin({ left: 13 })
  6535. Text(label)
  6536. .fontSize(12)
  6537. .margin({ left: 6 })
  6538. .fontColor('#FFFFFF')}
  6539. }
  6540. .onClick(() => {
  6541. switch (step) {
  6542. case 0:
  6543. this.callFilePickerSelectFileForLyric()
  6544. break;
  6545. case 1:
  6546. //判断是不是赞助会员
  6547. if(PreferencesUtil.getStringSync('LRC_API','')===''){
  6548. this.isLyricSetting = false
  6549. this.showTipsDialog()
  6550. return
  6551. }
  6552. if (StrUtil.isNotEmpty(this.videoUrl)) {
  6553. ToastUtil.showToast('正在获取')
  6554. this.isLyricSetting = false
  6555. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  6556. this.initLyric(lyricPath, true);
  6557. }
  6558. break;
  6559. }
  6560. })
  6561. .padding(5)
  6562. .width(110)
  6563. .backgroundColor(Color.Transparent)
  6564. .height(40)
  6565. .margin({ left: 6, right: 6 })
  6566. .border({
  6567. color: '#FFFFFF',
  6568. radius: 20,
  6569. width: 1.8
  6570. })
  6571. }
  6572. showVipDialog() {
  6573. DialogHelper.showCustomContentDialog({
  6574. dialogId: 'vip',
  6575. title: "友情提示",
  6576. autoCancel: false, //点击遮障层时,不关闭弹窗
  6577. backCancel: true, //点击返回键,不关闭弹窗
  6578. contentBuilder: () => {
  6579. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  6580. },
  6581. buttons: [],
  6582. })
  6583. }
  6584. //去赞助的自定义内容
  6585. @Builder
  6586. customVipBuilder(content: string) {
  6587. Column() {
  6588. Text(content)
  6589. .fontColor(Color.Gray)
  6590. .fontSize(16)
  6591. .alignSelf(ItemAlign.Start)
  6592. .margin({ bottom: 15 })
  6593. .fontSize(16)
  6594. Row() {
  6595. Button('取消')
  6596. .fontColor(Color.White)
  6597. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  6598. .height(50)
  6599. .layoutWeight(1)
  6600. .stateEffect(true)
  6601. .margin({ right: 6 })
  6602. .onClick(() => {
  6603. DialogHelper.closeDialog('vip'); //关闭弹框
  6604. })
  6605. Button('开通')
  6606. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  6607. .layoutWeight(1)
  6608. .height(50)
  6609. .backgroundColor(this.themeColor)
  6610. .stateEffect(true)
  6611. .margin({ left: 6 })
  6612. .onClick(() => {
  6613. DialogHelper.closeDialog('vip'); //关闭弹框
  6614. this.isShowPlay = false
  6615. this.mType = 1//跳转到用户中心
  6616. // router.pushUrl({
  6617. // url: 'pages/VipPage'
  6618. // }, router.RouterMode.Single);
  6619. })
  6620. }
  6621. }
  6622. .width("100%")
  6623. .padding(10)
  6624. }
  6625. showTipsDialog() {
  6626. DialogHelper.showCustomContentDialog({
  6627. dialogId: 'tips',
  6628. title: "友情提示",
  6629. autoCancel: false, //点击遮障层时,不关闭弹窗
  6630. backCancel: true, //点击返回键,不关闭弹窗
  6631. contentBuilder: () => {
  6632. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  6633. },
  6634. buttons: [],
  6635. })
  6636. }
  6637. @Builder
  6638. customTipsBuilder(content: string) {
  6639. Column() {
  6640. Text(content)
  6641. .fontColor(Color.Gray)
  6642. .fontSize(16)
  6643. .alignSelf(ItemAlign.Start)
  6644. .margin({ bottom: 15 })
  6645. .fontSize(16)
  6646. Row() {
  6647. Button('取消')
  6648. .fontColor(Color.White)
  6649. .backgroundColor(this.themeColor)
  6650. .height(50)
  6651. .layoutWeight(1)
  6652. .stateEffect(true)
  6653. .margin({ right: 6 })
  6654. .onClick(() => {
  6655. DialogHelper.closeDialog('tips'); //关闭弹框
  6656. })
  6657. Button('跳转')
  6658. .fontColor(Color.White)//
  6659. .layoutWeight(1)
  6660. .height(50)
  6661. .backgroundColor(this.themeColor)
  6662. .stateEffect(true)
  6663. .margin({ left: 6 })
  6664. .onClick(() => {
  6665. DialogHelper.closeDialog('tips'); //关闭弹框
  6666. this.isShowPlay = false
  6667. router.pushUrl({
  6668. url: 'pages/SettingPage'
  6669. }, router.RouterMode.Single);
  6670. })
  6671. }
  6672. }
  6673. .width("100%")
  6674. .padding(10)
  6675. }
  6676. @Builder
  6677. PlayMoreSheet() {
  6678. Column() {
  6679. this.MoreList()
  6680. }
  6681. .width('100%')
  6682. .height('100%')
  6683. }
  6684. @Builder
  6685. MoreList() {
  6686. Scroll() {
  6687. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6688. ForEach(this.moreItems, (more: MoreItem,index:number) => {
  6689. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6690. Row() {
  6691. if (more.id === 3) {
  6692. Image(more.image)
  6693. .width(24)
  6694. .height(24)
  6695. .margin({ left: 10, right: 10 })
  6696. Text(more.title)
  6697. .fontSize(16)
  6698. .fontColor(Color.White)
  6699. .bindSheet($$this.isShowDetailMore, this.detailSheet(), {
  6700. height: this.isCoverOpacity() ? '95%' : '65%',
  6701. dragBar: true,
  6702. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6703. showClose: true,
  6704. blurStyle: BlurStyle.Thin,
  6705. backgroundColor: Color.Transparent,
  6706. title: { title: '歌曲信息' }
  6707. })
  6708. } else if (more.id === 15&&this.currentSong) { //编辑信息
  6709. Image(more.image)
  6710. .width(24)
  6711. .height(24)
  6712. .margin({ left: 10, right: 10 })
  6713. Text(more.title)
  6714. .fontSize(16)
  6715. .fontColor(Color.White)
  6716. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  6717. height: this.isCoverOpacity() ? '95%' : '93%',
  6718. dragBar: true,
  6719. showClose: true,
  6720. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6721. // blurStyle:BlurStyle.Thin,
  6722. // backgroundColor:Color.Transparent,
  6723. title: { title: '编辑信息' }
  6724. })
  6725. } else if (more.id === 5) { //定时关闭
  6726. Image(more.image)
  6727. .width(24)
  6728. .height(24)
  6729. .margin({ left: 10, right: 10 })
  6730. Text(more.title)
  6731. .fontSize(16)
  6732. .fontColor(Color.White)
  6733. .onClick(() => {
  6734. this.doMore(more.id)
  6735. })
  6736. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  6737. height: this.isCoverOpacity() ? '95%' : '78%',
  6738. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6739. dragBar: true,
  6740. showClose: true,
  6741. title: { title: $r('app.string.time_close') }
  6742. })
  6743. } else if (more.id === 2) { //歌词设置
  6744. Image(more.image)
  6745. .width(24)
  6746. .height(24)
  6747. .margin({ left: 10, right: 10 })
  6748. Text(more.title)
  6749. .fontSize(16)
  6750. .fontColor(Color.White)
  6751. }
  6752. else if (more.id === 16) { //悬浮歌词设置
  6753. Image(more.image)
  6754. .width(24)
  6755. .height(24)
  6756. .margin({ left: 10, right: 10 })
  6757. Text(more.title)
  6758. .fontSize(16)
  6759. .fontColor(Color.White)
  6760. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  6761. height: this.isCoverOpacity() ? '95%' : '95%',
  6762. dragBar: true,
  6763. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6764. showClose: true,
  6765. blurStyle: BlurStyle.Thin,
  6766. backgroundColor: Color.Transparent,
  6767. title: { title: '悬浮歌词' }
  6768. })
  6769. } else if (more.id === 11) {
  6770. Image(more.image)
  6771. .width(24)
  6772. .height(24)
  6773. .margin({ left: 10, right: 10 })
  6774. Text(more.title)
  6775. .fontSize(16)
  6776. .fontColor(Color.White)
  6777. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  6778. height: this.isCoverOpacity() ? '95%' : '60%',
  6779. dragBar: true,
  6780. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6781. showClose: true,
  6782. blurStyle: BlurStyle.Thin,
  6783. backgroundColor: Color.Transparent,
  6784. title: { title: '跳过头尾' }
  6785. })
  6786. }else if (more.id === 12) { //投播
  6787. AVCastPicker({
  6788. customPicker: (): void => this.TPImageBuilder(more),
  6789. onStateChange: (state) => {
  6790. if (state == AVCastPickerState.STATE_APPEARING) {
  6791. console.log(' The picker starts showing.');
  6792. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  6793. console.log(' The picker finishes presenting.');
  6794. }
  6795. },
  6796. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  6797. sessionType: 'video'
  6798. })
  6799. .id('AVCastPicker')
  6800. } else {
  6801. Image(more.image)
  6802. .width(24)
  6803. .height(24)
  6804. .margin({ left: 10, right: 10 })
  6805. .onClick(() => {
  6806. this.doMore(more.id)
  6807. })
  6808. Text(more.id==17?(this.isLandscape?'竖屏模式':'横屏模式'):more.title)
  6809. .fontSize(16)
  6810. .fontColor(Color.White)
  6811. .onClick(() => {
  6812. this.doMore(more.id)
  6813. })
  6814. Select([//倍速
  6815. { value: '0.25x' },
  6816. { value: '0.5x' },
  6817. { value: '0.75x' },
  6818. { value: '1x' },
  6819. { value: '1.25x' },
  6820. { value: '1.5x' },
  6821. { value: '1.75x' },
  6822. { value: '2x' },
  6823. { value: '3x' }])
  6824. .font({ size: 16, weight: FontWeight.Medium })
  6825. .fontColor($r('sys.color.white'))
  6826. .margin({ left: 25 })
  6827. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  6828. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  6829. .value(Utility.optimizedFormat(this.playSpeed))
  6830. .onSelect(async (_index: number, text?: string | undefined) => {
  6831. let speed = parseFloat(text?.replace('x', '') || '1');
  6832. if (!CommonConstants.video_speed_list.includes(speed)) {
  6833. speed = 1;
  6834. }
  6835. this.playSpeed = speed
  6836. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  6837. })
  6838. Slider({
  6839. value: this.volume,
  6840. min: 0,
  6841. max: 1,
  6842. step: 0.1,
  6843. style: SliderStyle.OutSet
  6844. })
  6845. .margin({ left: 18, right: 8 })
  6846. .blockColor(this.themeColor)
  6847. .trackColor($r('app.color.speed_text_color'))
  6848. .selectedColor(Color.White)
  6849. .trackThickness(9)
  6850. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  6851. .onChange((value: number) => {
  6852. this.volume = value;
  6853. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  6854. })
  6855. .layoutWeight(1)
  6856. Blank()
  6857. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  6858. .selectedColor(this.themeColor)
  6859. .switchPointColor(Color.White)
  6860. .margin({ right: 15 })
  6861. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  6862. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6863. if (more.id == 6) {
  6864. this.isMusicMemoryPlay = checked;
  6865. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  6866. if (this.isMusicMemoryPlay) {
  6867. ToastUtil.showToast('记忆播放已开启')
  6868. } else {
  6869. ToastUtil.showToast('记忆播放已关闭')
  6870. }
  6871. }
  6872. })
  6873. .width(48)
  6874. .height(24);
  6875. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  6876. .selectedColor(this.themeColor)
  6877. .switchPointColor(Color.White)
  6878. .margin({ right: 15 })
  6879. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  6880. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6881. if (more.id == 7) {
  6882. this.isMusicBGCover = checked;
  6883. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  6884. if (this.isMusicBGCover) {
  6885. ToastUtil.showToast('播放背景随音乐封面已开启')
  6886. } else {
  6887. ToastUtil.showToast('播放背景随音乐封面已关闭')
  6888. }
  6889. }
  6890. })
  6891. .width(48)
  6892. .height(24);
  6893. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  6894. .selectedColor(this.themeColor)
  6895. .switchPointColor(Color.White)
  6896. .margin({ right: 15 })
  6897. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  6898. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6899. if (more.id == 8) {
  6900. this.isSavePlayMode = checked;
  6901. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  6902. if (this.isSavePlayMode) {
  6903. ToastUtil.showToast('保存播放模式已开启')
  6904. } else {
  6905. ToastUtil.showToast('保存播放模式已关闭')
  6906. }
  6907. }
  6908. })
  6909. .width(48)
  6910. .height(24);
  6911. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  6912. .selectedColor(this.themeColor)
  6913. .switchPointColor(Color.White)
  6914. .margin({ right: 15 })
  6915. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  6916. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  6917. if (more.id == 13) {
  6918. this.isCoverRectangle = checked;
  6919. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  6920. if (this.isCoverRectangle) {
  6921. ToastUtil.showToast('封面方形已开启')
  6922. this.animationRoFun()
  6923. } else {
  6924. ToastUtil.showToast('封面圆形已开启')
  6925. this.animationRoFun()
  6926. }
  6927. }
  6928. })
  6929. .width(48)
  6930. .height(24);
  6931. }
  6932. }
  6933. .width('100%')
  6934. .height(45)
  6935. .padding(15)
  6936. .backgroundColor(Color.Transparent)
  6937. .borderRadius(12)
  6938. .margin({ bottom: 6 })
  6939. }
  6940. .transition(TransitionEffect.move(TransitionEdge.BOTTOM).animation({ duration: 600, curve: Curve.Ease, delay: 60*index }))
  6941. .backgroundColor(Color.Transparent)
  6942. .onClick(() => {
  6943. this.doMore(more.id)
  6944. })
  6945. });
  6946. }
  6947. .width('100%')
  6948. .padding(16)
  6949. }.margin({ bottom: 18 })
  6950. }
  6951. @Builder
  6952. TPImageBuilder(more: MoreItem): void {
  6953. Row() {
  6954. Image($r('app.media.tuoping'))
  6955. .width(22)
  6956. .height(22)
  6957. .margin({ left: 10, right: 10 })
  6958. Text(more.title)
  6959. .fontSize(16)
  6960. .fontColor(Color.White)
  6961. }
  6962. .width('100%')
  6963. .layoutWeight(1)
  6964. .alignItems(VerticalAlign.Center)
  6965. .justifyContent(FlexAlign.Start)
  6966. }
  6967. private moreItems: MoreItem[] = [
  6968. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  6969. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  6970. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  6971. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  6972. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  6973. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  6974. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  6975. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  6976. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  6977. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  6978. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  6979. { id: 4, image: $r('app.media.share2'), title: '分享' },
  6980. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  6981. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  6982. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  6983. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  6984. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  6985. ];
  6986. @State isShowMoreView: boolean = false;
  6987. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  6988. @State isShowTimeCloseMore: boolean = false
  6989. @State isShowDetailMore: boolean = false
  6990. @State isMusicBGCover: boolean = true
  6991. @State isSavePlayMode: boolean = true
  6992. @State isLyricSetting: boolean = false
  6993. @State isJumpSetting: boolean = false
  6994. @State isShowEdit: boolean = false
  6995. @State showPipLyric: boolean = false
  6996. async setRingTone() {
  6997. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  6998. return
  6999. }
  7000. // 确定后的逻辑
  7001. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  7002. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  7003. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  7004. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  7005. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  7006. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  7007. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  7008. , this.videoUrl, this.name).then(res => {
  7009. LogUtil.info('onecold setFlag :' + res);
  7010. });
  7011. }
  7012. doMore(moreId: number) {
  7013. switch (moreId) {
  7014. case 2: //歌词
  7015. this.isLyricSetting = !this.isLyricSetting;
  7016. this.isShowMoreView = false
  7017. break;
  7018. case 3: //详情
  7019. this.isShowDetailMore = !this.isShowDetailMore;
  7020. break;
  7021. case 4: //分享
  7022. if (this.currentSong !== undefined) {
  7023. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  7024. }
  7025. this.isShowMoreView = false
  7026. break;
  7027. case 5: //定时关闭
  7028. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  7029. break;
  7030. case 10: //设为铃声
  7031. this.setRingTone()
  7032. this.isShowMoreView = false
  7033. break;
  7034. case 11: //跳过头尾
  7035. this.isJumpSetting = !this.isJumpSetting;
  7036. break;
  7037. case 13: //倍速
  7038. break;
  7039. case 14: //搜索封面
  7040. if (this.currentSong !== undefined) {
  7041. this.doSearchCover(this.currentSong)
  7042. }
  7043. this.isShowMoreView = false
  7044. break;
  7045. case 15: //编辑信息
  7046. this.isShowEdit = !this.isShowEdit;
  7047. break;
  7048. case 16: //悬浮歌词
  7049. this.showPipLyric = !this.showPipLyric;
  7050. break;
  7051. case 17: //横屏模式
  7052. if (this.isLandscape) {
  7053. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  7054. } else {
  7055. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  7056. }
  7057. this.isShowMoreView = false
  7058. break;
  7059. }
  7060. }
  7061. /**
  7062. * 切换横竖屏
  7063. *
  7064. */
  7065. setOrientation(orientation: number) {
  7066. this.windowClass.setPreferredOrientation(orientation).then(() => {
  7067. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  7068. }).catch((err: BusinessError) => {
  7069. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  7070. });
  7071. }
  7072. /**
  7073. * 画中画功能(悬浮歌词功能)
  7074. *
  7075. */
  7076. private nodeController: TextNodeController = new TextNodeController('#000000',this.lyricControllerXF);
  7077. pipController?: PiPWindow.PiPController;
  7078. navigationId: string = '';
  7079. @State curState: string = '';
  7080. @State curError: ResourceStr = '';
  7081. @State pipBg:string = '#E8E8E8'
  7082. @State buttonAction: string = '';
  7083. //开启画中画功能
  7084. async startPip() {
  7085. this.nodeController = new TextNodeController(this.pipBg,this.lyricControllerXF);
  7086. if (!this.pipController) {
  7087. await this.createPipController();
  7088. }
  7089. if (!this.pipController) {
  7090. Logger.info(`[${TAG}] pipController create error`);
  7091. return;
  7092. }
  7093. await this.pipController.startPiP();
  7094. }
  7095. async stopPip() {
  7096. if (!this.pipController) {
  7097. Logger.info(`[${TAG}] pipController is not exist`);
  7098. return;
  7099. }
  7100. this.isOpenPip = false
  7101. await this.pipController.stopPiP();
  7102. }
  7103. async createPipController() {
  7104. this.pipController = await PiPWindow.create({
  7105. context: getContext(this),
  7106. componentController: this.xcomponentController,
  7107. navigationId: this.navigationId,
  7108. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  7109. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  7110. customUIController: this.nodeController,
  7111. });
  7112. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth',330)
  7113. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight',120)
  7114. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7115. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  7116. this.onStateChange(state, reason);
  7117. });
  7118. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  7119. this.onActionEvent(event, status);
  7120. });
  7121. }
  7122. destroyPipController() {
  7123. if (!this.pipController) {
  7124. return;
  7125. }
  7126. this.pipController.off('stateChange');
  7127. this.pipController.off('controlPanelActionEvent');
  7128. this.pipController = undefined;
  7129. }
  7130. onStateChange(state: PiPWindow.PiPState, reason: string) {
  7131. switch (state) {
  7132. case PiPWindow.PiPState.ABOUT_TO_START:
  7133. this.curState = 'ABOUT_TO_START';
  7134. this.curError = $r('app.string.current_error_hint');
  7135. break;
  7136. case PiPWindow.PiPState.STARTED:
  7137. this.curState = 'STARTED';
  7138. this.curError = $r('app.string.current_error_hint');
  7139. break;
  7140. case PiPWindow.PiPState.ABOUT_TO_STOP:
  7141. this.curState = 'ABOUT_TO_STOP';
  7142. this.curError = $r('app.string.current_error_hint');
  7143. break;
  7144. case PiPWindow.PiPState.STOPPED:
  7145. this.curState = 'STOPPED';
  7146. this.curError = $r('app.string.current_error_hint');
  7147. this.stopPip()
  7148. this.destroyPipController()
  7149. break;
  7150. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  7151. this.curState = 'ABOUT_TO_RESTORE';
  7152. this.curError = $r('app.string.current_error_hint');
  7153. break;
  7154. case PiPWindow.PiPState.ERROR:
  7155. this.curState = 'ERROR';
  7156. this.curError = reason;
  7157. break;
  7158. default:
  7159. break;
  7160. }
  7161. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  7162. }
  7163. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  7164. LogUtil.info('onecold onActionEvent = '+ event + ' status='+status )
  7165. switch (event) {
  7166. case 'playbackStateChanged':
  7167. if (status === 0) {
  7168. this.pause();
  7169. } else {
  7170. this.startPlayOrResumePlay();
  7171. }
  7172. break;
  7173. case 'nextVideo':
  7174. // 切换到下一个视频
  7175. this.playNext()
  7176. break;
  7177. case 'previousVideo':
  7178. // 切换到上一个视频
  7179. this.playPrevious()
  7180. break;
  7181. case 'previousVideo':
  7182. // 切换到上一个视频
  7183. this.playPrevious()
  7184. break;
  7185. default:
  7186. }
  7187. this.buttonAction = event + `-status:${status}`;
  7188. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  7189. }
  7190. /**
  7191. * 画中画功能(悬浮歌词功能)结束
  7192. *
  7193. */
  7194. doSearchCover(item:VideoItem){
  7195. if(PreferencesUtil.getStringSync('COVER_API','')===''){
  7196. this.isShowMoreView = false
  7197. this.showTipsDialog()
  7198. return
  7199. }
  7200. if (item !== undefined) {
  7201. let artist = item?.artist
  7202. if (StrUtil.isEmpty(artist) || artist === undefined) {
  7203. artist = ''
  7204. }
  7205. this.searchCover(item,item.name, artist)
  7206. }
  7207. }
  7208. searchCover(item:VideoItem,title: string, artist: string) {
  7209. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API','')).then(async (res) => {
  7210. LogUtil.debug("onecold res =" + res)
  7211. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7212. if(item.filePath==this.currentSong?.filePath){
  7213. this.cover = res
  7214. if (this.currentSong) {
  7215. this.currentSong.pixelMapPath = res
  7216. }
  7217. }
  7218. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  7219. if (success) {
  7220. this.doUpdateData()
  7221. console.log(" onecold 更新音乐封面成功,数据库已同步");
  7222. } else {
  7223. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  7224. }
  7225. });
  7226. LogUtil.debug("onecold this.cover =" + this.cover)
  7227. }
  7228. })
  7229. }
  7230. @State jumpTopTime: number = 0
  7231. @State jumpEndTime: number = 0
  7232. @State isOpenJump: boolean = false
  7233. @Builder
  7234. JumpTopEndSheet() {
  7235. Scroll() {
  7236. Column() {
  7237. Column() {
  7238. Text('仅对本播放列表有效')
  7239. .fontSize(16)
  7240. .fontColor($r('app.color.text_color'))
  7241. // 跳过头尾
  7242. Column() {
  7243. Row() {
  7244. Text('跳过片头:')
  7245. .fontSize(16)
  7246. .fontColor($r('app.color.text_color'))
  7247. Text(this.jumpTopTime + 's')
  7248. .fontSize(16)
  7249. .fontColor($r('app.color.text_color'))
  7250. }
  7251. .margin({ bottom: 5 })
  7252. Row() {
  7253. Slider({
  7254. value: this.jumpTopTime,
  7255. min: 0,
  7256. max: 120,
  7257. step: 1,
  7258. style: SliderStyle.OutSet
  7259. })
  7260. .blockColor(this.themeColor)
  7261. .trackColor($r('app.color.speed_text_color'))
  7262. .selectedColor(Color.White)
  7263. .trackThickness(8)
  7264. .onChange((value: number) => {
  7265. this.jumpTopTime = value;
  7266. })
  7267. .width('85%')
  7268. }
  7269. .alignItems(VerticalAlign.Top)
  7270. }
  7271. .margin({ top: 10, bottom: 10 })
  7272. // 跳过头尾
  7273. Column() {
  7274. Row() {
  7275. Text('跳过片尾:')
  7276. .fontSize(16)
  7277. .fontColor($r('app.color.text_color'))
  7278. Text(this.jumpEndTime + 's')
  7279. .fontSize(16)
  7280. .fontColor($r('app.color.text_color'))
  7281. }
  7282. .margin({ bottom: 5 })
  7283. Row() {
  7284. Slider({
  7285. value: this.jumpEndTime,
  7286. min: 0,
  7287. max: 120,
  7288. step: 1,
  7289. style: SliderStyle.OutSet
  7290. })
  7291. .blockColor(this.themeColor)
  7292. .trackColor($r('app.color.speed_text_color'))
  7293. .selectedColor(Color.White)
  7294. .trackThickness(8)
  7295. .onChange((value: number) => {
  7296. this.jumpEndTime = value;
  7297. })
  7298. .width('85%')
  7299. }
  7300. .alignItems(VerticalAlign.Top)
  7301. }
  7302. .margin({ top: 10, bottom: 10 })
  7303. Row() {
  7304. Button('保存设置')
  7305. .fontColor(Color.White)
  7306. .layoutWeight(1)
  7307. .height(40)
  7308. .width(80)
  7309. .backgroundColor(this.themeColor)
  7310. .stateEffect(true)
  7311. .margin({ left: 0, bottom: 20 })
  7312. .onClick(async () => {
  7313. if (!Utility.isNoble()) {
  7314. this.isJumpSetting = false
  7315. this.isShowMoreView = false
  7316. this.showVipDialog()
  7317. return
  7318. }
  7319. if (this.currentSong === undefined) {
  7320. return
  7321. }
  7322. if (this.modeType === 0) {
  7323. let parentPath = FileUtil.getParentPath(this.videoUrl)
  7324. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  7325. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  7326. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  7327. } else if (this.modeType === 1) { //媒体库
  7328. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  7329. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  7330. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  7331. } else if (this.modeType === 2) { //艺术家
  7332. if (this.currentSong?.artist) {
  7333. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  7334. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  7335. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  7336. }
  7337. } else if (this.modeType === 3) { //专辑
  7338. if (this.currentSong?.album) {
  7339. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  7340. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  7341. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  7342. }
  7343. }
  7344. ToastUtil.showShort("保存成功")
  7345. this.isJumpSetting = false
  7346. })
  7347. }
  7348. .margin({
  7349. left: 38,
  7350. right: 38,
  7351. top: 10,
  7352. bottom: 10
  7353. })
  7354. .width(120)
  7355. .height(50)
  7356. }
  7357. }
  7358. }
  7359. .width('100%')
  7360. .height('100%')
  7361. }
  7362. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  7363. private onStateVastChange(state: AVCastPickerState) {
  7364. if (state == AVCastPickerState.STATE_APPEARING) {
  7365. console.log('The picker starts showing.');
  7366. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  7367. console.log('The picker finishes presenting.');
  7368. }
  7369. }
  7370. private showSelectLyric() {
  7371. DialogHelper.showActionSheetDialog({
  7372. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  7373. // sheets: ["本地歌词", "搜索歌词"],
  7374. sheets:[
  7375. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  7376. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  7377. ],
  7378. maskColor: Color.Transparent,
  7379. backgroundColor: $r('app.color.bg_card'),
  7380. transition: AnimationHelper.transitionInDown(666),
  7381. onAction: (index) => {
  7382. switch (index) {
  7383. case 0:
  7384. this.callFilePickerSelectFileForLyric()
  7385. break;
  7386. case 1:
  7387. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7388. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7389. this.initLyric(lyricPath);
  7390. }
  7391. break;
  7392. }
  7393. }
  7394. })
  7395. }
  7396. // 拉起picker选择文件管理器
  7397. async callFilePickerSelectFileForLyric(): Promise<void> {
  7398. try {
  7399. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  7400. DocumentSelectOptions.maxSelectNumber = 1
  7401. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  7402. let documentPicker = new picker.DocumentViewPicker();
  7403. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  7404. Logger.info(TAG,
  7405. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  7406. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  7407. this.saveVideoDatasLyric(DocumentSelectResult)
  7408. }
  7409. }).catch((err: BusinessError) => {
  7410. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  7411. });
  7412. } catch (err) {
  7413. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  7414. }
  7415. }
  7416. async saveVideoDatasLyric(uris: string[]) {
  7417. if (ArrayUtil.isEmpty(uris)) {
  7418. return
  7419. }
  7420. let newUris: string[] = [];
  7421. for (let i = 0; i < uris.length; i++) {
  7422. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  7423. Logger.info(TAG, 'filePath uri: ' + filePath);
  7424. newUris.push(filePath)
  7425. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  7426. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  7427. fileIo.copyFileSync(file.fd, file2.fd)
  7428. fileIo.closeSync(file);
  7429. fileIo.closeSync(file2);
  7430. this.initLyric(filePath)
  7431. }
  7432. }
  7433. private initDelayPlay(context: object) {
  7434. this.mContext = context;
  7435. }
  7436. startPipLyric(){
  7437. if(this.pipController)
  7438. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE, PiPWindow.PiPControlStatus.PLAY);
  7439. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip',false)
  7440. if(this.isOpenPip){
  7441. this.startPip()
  7442. }else{
  7443. this.stopPip()
  7444. }
  7445. }
  7446. private startPlayOrResumePlay() {
  7447. this.startPipLyric()
  7448. this.mDestroyPage = false;
  7449. this.animationState = AnimationStatus.Running
  7450. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  7451. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  7452. this.stopProgressTask();
  7453. this.startProgressTask();
  7454. this.play(this.videoUrl.toString());
  7455. }
  7456. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  7457. this.mIjkMediaPlayer.start();
  7458. this.setProgress()
  7459. this.CONTROL_PlayStatus = PlayStatus.PLAY
  7460. }
  7461. this.setIsPlaying(true)
  7462. this.updateSessionPlayState(true)
  7463. this.watchStatus();
  7464. this.updateLastPlayTimeStr(this.videoUrl)
  7465. }
  7466. updateLastPlayTimeStr(filePath:string){
  7467. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  7468. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  7469. if (success) {
  7470. this.getHistoryList(false)
  7471. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  7472. } else {
  7473. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  7474. }
  7475. });
  7476. }
  7477. private completionNum(num: number): string | number {
  7478. if (num < 10) {
  7479. return '0' + num;
  7480. } else {
  7481. return num;
  7482. }
  7483. }
  7484. private stringForTime(timeMs: number): string {
  7485. let totalSeconds: number | string = (timeMs / 1000);
  7486. let newSeconds: number | string = totalSeconds % 60;
  7487. let minutes: number | string = (totalSeconds / 60) % 60;
  7488. let hours: number | string = totalSeconds / 3600;
  7489. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  7490. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  7491. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  7492. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  7493. if (this.isCurrentTime) {
  7494. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  7495. this.oldSeconds = newSeconds
  7496. } else {
  7497. newSeconds = this.oldSeconds
  7498. }
  7499. }
  7500. newSeconds = this.completionNum(newSeconds);
  7501. if (hours > 0) {
  7502. return hours + ":" + minutes + ":" + newSeconds;
  7503. } else {
  7504. return minutes + ":" + newSeconds;
  7505. }
  7506. }
  7507. private setProgress() {
  7508. let position = this.mIjkMediaPlayer.getCurrentPosition();
  7509. let duration = this.mIjkMediaPlayer.getDuration();
  7510. let pos = 0;
  7511. if (duration > 0) {
  7512. this.slideEnable = true;
  7513. let curPercent = position / duration;
  7514. pos = curPercent * 100;
  7515. if (pos > this.PROGRESS_MAX_VALUE) {
  7516. this.progressValue = this.PROGRESS_MAX_VALUE
  7517. } else {
  7518. this.progressValue = pos;
  7519. }
  7520. }
  7521. // LogUtils.getInstance()
  7522. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  7523. this.totalTime = this.stringForTime(duration);
  7524. if (position > duration) {
  7525. position = duration;
  7526. }
  7527. this.isCurrentTime = true;
  7528. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  7529. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  7530. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  7531. this.currentTime = this.stringForTime(position);
  7532. this.isCurrentTime = false
  7533. if (this.mIjkMediaPlayer.isPlaying()) {
  7534. this.randomColor =
  7535. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  7536. // 判断是否播放到结束时间
  7537. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  7538. if (position >= duration - this.jumpEndTime * 1000) {
  7539. this.playNext()
  7540. }
  7541. }
  7542. } else {
  7543. this.randomColor = 'rbg(0,0,0)'
  7544. }
  7545. }
  7546. private startProgressTask() {
  7547. let that = this;
  7548. this.updateProgressTimer = setInterval(() => {
  7549. //LogUtils.getInstance().LOGI("startProgressTask");
  7550. if (!that.mDestroyPage) {
  7551. that.setProgress();
  7552. }
  7553. }, 300);
  7554. }
  7555. private stopProgressTask() {
  7556. LogUtils.getInstance().LOGI("stopProgressTask");
  7557. clearInterval(this.updateProgressTimer);
  7558. }
  7559. private showLoadIng() {
  7560. this.loadingVisible = Visibility.Visible;
  7561. this.replayVisible = Visibility.None;
  7562. }
  7563. private hideLoadIng() {
  7564. this.loadingVisible = Visibility.None;
  7565. this.replayVisible = Visibility.None;
  7566. }
  7567. private showRePlay() {
  7568. this.loadingVisible = Visibility.None;
  7569. this.replayVisible = Visibility.Visible;
  7570. }
  7571. private async play(url: string) {
  7572. let that = this;
  7573. that.showLoadIng();
  7574. //设置XComponent回调的context
  7575. if (!!this.mContext) {
  7576. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  7577. }
  7578. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  7579. this.mIjkMediaPlayer.reset();
  7580. }
  7581. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  7582. //设置debug模式
  7583. this.mIjkMediaPlayer.setDebug(false);
  7584. //初始化配置
  7585. this.mIjkMediaPlayer.native_setup();
  7586. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0
  7587. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  7588. //设置视频源
  7589. this.mIjkMediaPlayer.setDataSource(url);
  7590. //设置视频源http请求头
  7591. let headers = new Map([
  7592. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  7593. ["referer", "https://www.bilibili.com"]
  7594. ]);
  7595. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  7596. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  7597. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  7598. // }
  7599. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  7600. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  7601. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  7602. const fileSize = await this.getFileSize(this.videoUrl);
  7603. let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
  7604. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  7605. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  7606. }
  7607. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  7608. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  7609. //停止预读的最小帧数
  7610. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  7611. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  7612. // 设置其他缓冲相关选项
  7613. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  7614. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  7615. //启动预加载
  7616. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  7617. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  7618. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  7619. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  7620. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  7621. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  7622. // 因此需要播放器丢包,才不会累积延时
  7623. // 这个和第三个参数packet-buffering无关。
  7624. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  7625. // 无限制收流
  7626. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  7627. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  7628. // 屏幕常亮
  7629. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  7630. // 设置超时
  7631. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  7632. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  7633. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  7634. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  7635. // 变速播放
  7636. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  7637. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7638. let Speed = this.mIjkMediaPlayer.getSpeed()
  7639. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  7640. //是否开启循环播放
  7641. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  7642. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  7643. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  7644. if (height === 0) {
  7645. return;
  7646. }
  7647. const va = width / height;
  7648. const vpa = that.videoParentAspectRatio;
  7649. if (vpa > va) {
  7650. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  7651. } else {
  7652. that.videoWidth = '100%';
  7653. }
  7654. if (width && height) {
  7655. that.videoAspectRatio = width / height;
  7656. }
  7657. LogUtils.getInstance()
  7658. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  7659. that.hideLoadIng();
  7660. }
  7661. }
  7662. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  7663. let mOnPreparedListener: OnPreparedListener = {
  7664. onPrepared: async () => {
  7665. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  7666. try {
  7667. // this.cover = this.songList[this.curIndex].pixelMapPath
  7668. // this.artist = this.songList[this.curIndex].artist
  7669. // this.videoUrl = this.songList[this.curIndex].filePath
  7670. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  7671. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  7672. this.setImageColor2(this.cover)
  7673. } else {
  7674. this.getImageColor();
  7675. }
  7676. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7677. await this.initLyric(lyricPath);
  7678. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  7679. this.avSessionController.initAvSession(false);
  7680. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  7681. this.setAvSessionListener();
  7682. this.updateSessionPlayState(true)
  7683. this.setCurrentPlayMode()
  7684. }, 500)
  7685. let timeoutPlay = 0
  7686. if (StrUtil.isNotEmpty(this.videoUrl) &&
  7687. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  7688. timeoutPlay = 1000
  7689. }
  7690. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  7691. if (this.modeType === 0) { //文件夹
  7692. let parentPath = FileUtil.getParentPath(this.videoUrl)
  7693. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  7694. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  7695. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  7696. } else if (this.modeType === 1) { //媒体库
  7697. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  7698. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  7699. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  7700. } else if (this.modeType === 2) { //艺术家
  7701. if (this.currentSong?.artist) {
  7702. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  7703. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  7704. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  7705. }
  7706. } else if (this.modeType === 3) { //专辑
  7707. if (this.currentSong?.album) {
  7708. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  7709. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  7710. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  7711. }
  7712. }
  7713. this.duration = this.mIjkMediaPlayer.getDuration()
  7714. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  7715. if (this.mIjkMediaPlayer != null) {
  7716. if (this.jumpTopTime * 1000 <= this.duration) {
  7717. // 调用 seekTo 方法,跳到指定时间
  7718. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  7719. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  7720. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  7721. }
  7722. }, timeoutPlay)
  7723. } else {
  7724. // 提示用户无法跳过
  7725. ToastUtil.showToast('跳过时间超过视频时长');
  7726. }
  7727. }
  7728. } else {
  7729. this.jumpTopTime = 0
  7730. this.jumpEndTime = 0
  7731. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  7732. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  7733. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' + PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  7734. //记忆播放(每一首都会记忆播放)
  7735. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  7736. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  7737. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  7738. this.restorePlaybackPosition() //读取播放记忆功能
  7739. }else if(this.isMemoryLastPlay&&this.isFirstStartPlay){
  7740. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  7741. this.restorePlaybackPosition() //读取播放记忆功能
  7742. }
  7743. this.isFirstStartPlay = false
  7744. }, timeoutPlay)
  7745. }else{
  7746. this.isFirstStartPlay = false
  7747. }
  7748. }
  7749. this.saveLastPlayList()
  7750. } catch (error) {
  7751. let err: BusinessError = error as BusinessError;
  7752. console.error('onecold failed with err: ' + JSON.stringify(err));
  7753. }
  7754. }
  7755. }
  7756. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  7757. let mOnTimedTextListener: OnTimedTextListener = {
  7758. onTimedText: () => {
  7759. }
  7760. }
  7761. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  7762. let mOnCompletionListener: OnCompletionListener = {
  7763. onCompletion: () => {
  7764. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  7765. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  7766. this.playNext()
  7767. } else if (this.playType == 1) { //1:单片重复播放
  7768. this.CONTROL_PlayStatus = PlayStatus.INIT
  7769. that.startPlayOrResumePlay();
  7770. } else if (this.playType == 2) { //2:正常播放,单曲播完
  7771. that.showRePlay();
  7772. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  7773. that.progressValue = this.PROGRESS_MAX_VALUE;
  7774. that.slideEnable = false;
  7775. that.stop();
  7776. // ToastUtil.showToast('开始重新播放')
  7777. } else if (this.playType == 3) { //3:随机播放
  7778. this.randomPlay()
  7779. }
  7780. }
  7781. }
  7782. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  7783. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  7784. onBufferingUpdate: (percent: number) => {
  7785. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  7786. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  7787. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  7788. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  7789. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  7790. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  7791. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  7792. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  7793. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  7794. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  7795. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  7796. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  7797. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  7798. let Looping = this.mIjkMediaPlayer.isLooping()
  7799. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  7800. }
  7801. }
  7802. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  7803. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  7804. onSeekComplete: () => {
  7805. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  7806. that.startPlayOrResumePlay();
  7807. }
  7808. }
  7809. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  7810. let mOnInfoListener: OnInfoListener = {
  7811. onInfo: (what: number, extra: number) => {
  7812. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  7813. that.hideLoadIng();
  7814. }
  7815. }
  7816. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  7817. let mOnErrorListener: OnErrorListener = {
  7818. onError: (what: number, extra: number) => {
  7819. this.stopProgressTask();
  7820. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  7821. that.hideLoadIng();
  7822. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  7823. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  7824. } else {
  7825. ToastUtil.showToast(getContext()
  7826. .resourceManager
  7827. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  7828. }
  7829. }
  7830. }
  7831. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  7832. this.mIjkMediaPlayer.setMessageListener();
  7833. this.mIjkMediaPlayer.prepareAsync();
  7834. this.mIjkMediaPlayer.start();
  7835. }
  7836. //保存最后播放的那首歌和已经对应的播放列表
  7837. saveLastPlayList() {
  7838. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  7839. PreferencesUtil.putSync('LastMusicList', this.songList)
  7840. }
  7841. // 清空播放记录
  7842. clearVideoHistory() {
  7843. this.table.clearPlayHistory( (success: boolean, error?: string) => {
  7844. if (success) {
  7845. this.historyList = [];
  7846. this.updateListData(this.historyList)
  7847. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  7848. ToastUtil.showToast('清空播放记录成功')
  7849. } else {
  7850. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  7851. }
  7852. });
  7853. }
  7854. public async setAvSessionListener() {
  7855. if (!this.avSessionController) {
  7856. return;
  7857. }
  7858. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  7859. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  7860. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  7861. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  7862. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  7863. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  7864. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  7865. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  7866. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  7867. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  7868. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  7869. }
  7870. setLoopMode() {
  7871. let itype = this.playType + 1
  7872. if (itype >= 4) {
  7873. this.playType = 0
  7874. ToastUtil.showToast('连续播放')
  7875. } else if (itype === 1) {
  7876. this.playType = 1
  7877. ToastUtil.showToast('单曲循环')
  7878. } else if (itype === 2) {
  7879. this.playType = 2
  7880. ToastUtil.showToast('单曲播完')
  7881. } else if (itype === 3) {
  7882. this.playType = 3
  7883. ToastUtil.showToast('随机播放')
  7884. } else if (itype === 0) {
  7885. this.playType = 0
  7886. ToastUtil.showToast('连续播放')
  7887. }
  7888. PreferencesUtil.putSync('musicPlayType', this.playType)
  7889. this.setCurrentPlayMode()
  7890. }
  7891. private sessionSetLoopModeCallback = (mode: number) => {
  7892. if (this.mIjkMediaPlayer != null) {
  7893. ToastUtil.showToast('当前播放模式:' + mode)
  7894. Logger.info('onecold 当前播放模式= ' + mode)
  7895. let hmPlayMode = mode + 1
  7896. if (hmPlayMode >= 4) {
  7897. hmPlayMode = 0
  7898. }
  7899. if (hmPlayMode === 1) {
  7900. this.playType = 1
  7901. ToastUtil.showToast('单曲循环')
  7902. } else if (hmPlayMode === 0) {
  7903. this.playType = 2
  7904. ToastUtil.showToast('单曲播完')
  7905. } else if (hmPlayMode === 3) {
  7906. this.playType = 3
  7907. ToastUtil.showToast('随机播放')
  7908. } else if (hmPlayMode === 2) {
  7909. this.playType = 0
  7910. ToastUtil.showToast('连续播放')
  7911. }
  7912. PreferencesUtil.putSync('musicPlayType', this.playType)
  7913. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  7914. let playBackState: avSession.AVPlaybackState = {
  7915. loopMode: hmPlayMode,
  7916. };
  7917. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  7918. console.info(`set setLoopMode AVPlaybackState successfully`);
  7919. }).catch((err: BusinessError) => {
  7920. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  7921. });
  7922. }
  7923. }
  7924. setCurrentPlayMode() {
  7925. if (!this.avSessionController) {
  7926. return;
  7927. }
  7928. let mLoopMode = 0
  7929. switch (this.playType) {
  7930. case 0:
  7931. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  7932. break;
  7933. case 1:
  7934. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  7935. break;
  7936. case 2:
  7937. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  7938. break;
  7939. case 3:
  7940. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  7941. break;
  7942. }
  7943. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  7944. let playBState: avSession.AVPlaybackState = {
  7945. loopMode: mLoopMode,
  7946. isFavorite:Utility.getIsFav(this.favList,this.currentSong),
  7947. };
  7948. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  7949. console.info(`set setLoopMode AVPlaybackState successfully`);
  7950. }).catch((err: BusinessError) => {
  7951. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  7952. });
  7953. }
  7954. private sessionToggleFavoriteCallback = (assetId: string) => {
  7955. if (this.mIjkMediaPlayer != null && this.currentSong) {
  7956. console.info(`on toggleFavorite `);
  7957. // 应用收到收藏命令,进行收藏处理。
  7958. this.isFac = Utility.getIsFav(this.favList,this.currentSong)
  7959. this.doFav(this.currentSong)
  7960. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  7961. let playbackState: avSession.AVPlaybackState = {
  7962. isFavorite:!this.isFac,
  7963. };
  7964. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  7965. console.info(`SetAVPlaybackState successfully`);
  7966. }).catch((err: BusinessError) => {
  7967. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  7968. });
  7969. }
  7970. }
  7971. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  7972. device: avSession.OutputDeviceInfo) => {
  7973. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  7974. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  7975. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  7976. await this.startCasting();
  7977. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  7978. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  7979. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  7980. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  7981. if (device) {
  7982. this.endCasting();
  7983. }
  7984. }
  7985. };
  7986. private async startCasting() {
  7987. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  7988. this.setPlaybackStateChangeListener();
  7989. this.pause();
  7990. this.initQueueItem();
  7991. this.prepare();
  7992. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  7993. refToIsCasting?.set(true);
  7994. this.castSeek = true;
  7995. this.isCastPlaying = true;
  7996. }
  7997. async changeCasting() {
  7998. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  7999. this.initQueueItem();
  8000. this.prepare();
  8001. this.setPlaybackStateChangeListener();
  8002. this.isCastPlaying = true;
  8003. this.castSeek = true;
  8004. }
  8005. public endCasting() {
  8006. this.avSessionController.getAvSession()?.stopCasting();
  8007. this.stopCast();
  8008. this.isCastPlaying = false;
  8009. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8010. refToIsCasting?.set(false);
  8011. this.pause();
  8012. this.setIsPlaying(false);
  8013. // if (this.curIndex === this.curSource.index) {
  8014. // this.play
  8015. // this.seek(this.currentTime * 1000);
  8016. // this.setIsPlaying(true);
  8017. // } else {
  8018. // this.pauseVideo();
  8019. // this.setIsPlaying(false);
  8020. // }
  8021. }
  8022. public setIsPlaying(isPlayer: boolean) {
  8023. this.isPlaying = isPlayer;
  8024. }
  8025. private setPlaybackStateChangeListener(): void {
  8026. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  8027. this.castController?.on('endOfStream', this.reloadCasting);
  8028. this.castController?.on('playNext', this.playNextCallback);
  8029. this.castController?.on('playPrevious', this.playPreviousCallback);
  8030. }
  8031. private updateSessionPlayState(isPlay: boolean): void {
  8032. // if(!this.isBgPlayOpen)
  8033. // return
  8034. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  8035. this.setAVSessionPlayState({
  8036. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  8037. position: {
  8038. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  8039. updateTime: new Date().getTime()
  8040. }
  8041. });
  8042. }
  8043. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  8044. this.avSessionController.setAvSessionPlayState(playbackState)
  8045. }
  8046. private positionChange(position: number) {
  8047. this.currentTime2 = position / 1000;
  8048. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  8049. }
  8050. private playDurationChange(duration: number) {
  8051. this.duration = duration;
  8052. this.durationTime = Math.floor(this.duration / 1000);
  8053. this.durationStringTime = secondToTime((this.durationTime));
  8054. }
  8055. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  8056. const duration = playbackState?.extras?.duration;
  8057. if (typeof duration === 'number') {
  8058. this.playDurationChange(duration as number);
  8059. }
  8060. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  8061. this.positionChange(playbackState?.position?.elapsedTime);
  8062. }
  8063. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  8064. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  8065. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  8066. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  8067. this.isCastPlaying = false;
  8068. }
  8069. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  8070. this.isCastPlaying = true;
  8071. }
  8072. };
  8073. private reloadCasting = async () => {
  8074. let item = this.songList[this.curIndex];
  8075. let uri = fileUri.getUriFromPath(item.filePath);
  8076. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8077. // description.startPosition = 0;
  8078. this.castItem = {
  8079. itemId: this.curIndex,
  8080. description: {
  8081. assetId: item.filePath,
  8082. title: item.name,
  8083. artist: '',
  8084. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8085. // mediaUri: item.filePath,
  8086. fdSrc: {
  8087. fd: file.fd
  8088. },
  8089. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8090. mediaType: 'VIDEO',
  8091. mediaSize: item.videoSize,
  8092. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8093. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8094. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8095. duration: this.duration,
  8096. // albumCoverUri: 'https://www.example.jpeg',
  8097. // albumTitle: '《ExampleAlbum》',
  8098. appName: this.appName,
  8099. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8100. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8101. }
  8102. };
  8103. this.prepare();
  8104. this.isCastPlaying = true;
  8105. };
  8106. public playNextCallback = (): void => {
  8107. this.playNext()
  8108. };
  8109. public playPreviousCallback = (): void => {
  8110. this.playPrevious()
  8111. };
  8112. async prepare() {
  8113. await this.castController?.prepare(this.castItem);
  8114. await this.castController?.start(this.castItem);
  8115. }
  8116. public initQueueItem() {
  8117. let item = this.songList[this.curIndex];
  8118. let time = this.currentTime;
  8119. let uri = fileUri.getUriFromPath(item.filePath);
  8120. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8121. this.castItem = {
  8122. itemId: this.curIndex,
  8123. description: {
  8124. assetId: item.filePath,
  8125. title: item.name,
  8126. artist: '',
  8127. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8128. fdSrc: {
  8129. fd: file.fd
  8130. },
  8131. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8132. mediaType: 'AUDIO',
  8133. mediaSize: item.videoSize,
  8134. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8135. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8136. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8137. duration: this.duration,
  8138. // albumCoverUri: 'https://www.example.jpeg',
  8139. // albumTitle: '《ExampleAlbum》',
  8140. appName: this.appName,
  8141. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8142. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8143. }
  8144. };
  8145. }
  8146. async stopCast() {
  8147. try {
  8148. this.castController?.off('playbackStateChange');
  8149. this.castController?.off('endOfStream');
  8150. this.castController?.off('playNext');
  8151. this.castController?.off('playPrevious');
  8152. this.castController?.off('error');
  8153. } catch (error) {
  8154. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  8155. }
  8156. }
  8157. private sessionPlayCallback = (): void => {
  8158. this.playOrPause()
  8159. };
  8160. private sessionPauseCallback = (): void => {
  8161. this.playOrPause()
  8162. };
  8163. private playOrPause() {
  8164. if (!this.debounce()) {
  8165. return;
  8166. }
  8167. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8168. this.pause();
  8169. } else {
  8170. this.startPlayOrResumePlay();
  8171. this.playChange()
  8172. }
  8173. }
  8174. private sessionPlayNextCallback = (): void => {
  8175. this.playNext()
  8176. };
  8177. private sessionPlayPreviousCallback = (): void => {
  8178. this.playPrevious()
  8179. };
  8180. private sessionStopCallback = (): void => {
  8181. this.stop()
  8182. };
  8183. private sessionFastForwardCallback = (time?: number) => {
  8184. if (!time) {
  8185. return;
  8186. }
  8187. if (this.mIjkMediaPlayer != null) {
  8188. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  8189. let seeTime = curPosition + time * 1000;
  8190. // 限制 seekValue 在合法范围内
  8191. if (seeTime < 0) {
  8192. seeTime = 0;
  8193. } else if (seeTime > this.duration) {
  8194. seeTime = this.duration;
  8195. }
  8196. Logger.info('onecold seeTime= ' + seeTime)
  8197. this.setSeekToActionProgress(seeTime)
  8198. this.seekTo(seeTime + "")
  8199. }
  8200. };
  8201. /**
  8202. * Gesture method onActionUpdate.
  8203. *
  8204. * @param event Gesture event.手势拖动设置快进和后退
  8205. */
  8206. private setSeekToActionProgress(position: number) {
  8207. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  8208. let duration = this.mIjkMediaPlayer.getDuration();
  8209. let pos = 0;
  8210. if (duration > 0) {
  8211. this.slideEnable = true;
  8212. let curPercent = position / duration;
  8213. pos = curPercent * 100;
  8214. if (pos > this.PROGRESS_MAX_VALUE) {
  8215. this.progressValue = this.PROGRESS_MAX_VALUE
  8216. } else {
  8217. this.progressValue = pos;
  8218. }
  8219. }
  8220. // LogUtils.getInstance()
  8221. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8222. this.totalTime = this.stringForTime(duration);
  8223. if (position > duration) {
  8224. position = duration;
  8225. }
  8226. this.isCurrentTime = true;
  8227. this.currentTime = this.stringForTime(position);
  8228. this.isCurrentTime = false
  8229. }
  8230. private sessionRewindCallback = (time?: number) => {
  8231. if (!time) {
  8232. return;
  8233. }
  8234. if (this.mIjkMediaPlayer != null) {
  8235. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  8236. let seeTime = curPosition - time * 1000;
  8237. // 限制 seekValue 在合法范围内
  8238. if (seeTime < 0) {
  8239. seeTime = 0;
  8240. } else if (seeTime > this.duration) {
  8241. seeTime = this.duration;
  8242. }
  8243. Logger.info('onecold seeTime= ' + seeTime)
  8244. this.setSeekToActionProgress(seeTime)
  8245. this.seekTo(seeTime + "")
  8246. }
  8247. };
  8248. private sessionSeekCallback = (seekTime: number) => {
  8249. if (this.mIjkMediaPlayer != null) {
  8250. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  8251. this.seekTo(seekTime + "")
  8252. }
  8253. };
  8254. private async getFileSize(filePath: string): Promise<number> {
  8255. try {
  8256. const stat = await fs.stat(filePath);
  8257. return stat.size;
  8258. } catch (err) {
  8259. console.error('Failed to get file size: ' + err.message);
  8260. return 0;
  8261. }
  8262. }
  8263. private pause() {
  8264. if (this.mIjkMediaPlayer.isPlaying()) {
  8265. this.savePlaybackPosition();
  8266. this.mIjkMediaPlayer.pause();
  8267. this.setProgress();
  8268. this.mDestroyPage = true;
  8269. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  8270. this.updateSessionPlayState(false)
  8271. this.playChange()
  8272. if(this.pipController)
  8273. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE, PiPWindow.PiPControlStatus.PAUSE);
  8274. }
  8275. }
  8276. private stop() {
  8277. this.savePlaybackPosition();
  8278. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8279. this.mIjkMediaPlayer.stop();
  8280. this.mIjkMediaPlayer.release();
  8281. this.stopProgressTask();
  8282. this.updateSessionPlayState(false)
  8283. this.playChange()
  8284. this.watchStatus();
  8285. }
  8286. //保持记忆播放功能
  8287. private savePlaybackPosition() {
  8288. if (this.mIjkMediaPlayer != null) {
  8289. const position = this.mIjkMediaPlayer.getCurrentPosition();
  8290. // ToastUtil.showToast('保存记忆播放 = ' + position)
  8291. const duration = this.mIjkMediaPlayer.getDuration();
  8292. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  8293. // 如果播放位置接近视频末尾,则保存 position 为 0
  8294. const playbackPosition = (duration - position < threshold) ? 0 : position;
  8295. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  8296. }
  8297. }
  8298. //获取记忆播放功能
  8299. private restorePlaybackPosition() {
  8300. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  8301. // ToastUtil.showToast('position = ' + position)
  8302. if (this.mIjkMediaPlayer != null && position > 0) {
  8303. // ToastUtil.showToast('seekTo = ' + position)
  8304. this.seekTo(position + "");
  8305. }
  8306. }
  8307. private seekTo(value: string) {
  8308. // this.stopProgressTask();
  8309. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  8310. // ToastUtil.showToast('wma格式不支持拖动快进。')
  8311. // return
  8312. // }
  8313. this.mIjkMediaPlayer.seekTo(value);
  8314. // this.startPlayOrResumePlay()
  8315. // 在这里恢复计时器状态
  8316. this.setProgress()
  8317. // this.startProgressTask();
  8318. }
  8319. // 添加到下一首播放
  8320. private addToNextPlay(song: VideoItem) {
  8321. if (!this.debounce()) {
  8322. return;
  8323. }
  8324. if (this.currentSong) {
  8325. if (this.currentSong === song) {
  8326. ToastUtil.showToast('当前已经在播放这首歌了!')
  8327. return
  8328. }
  8329. }
  8330. // 如果未开始播放或队列为空
  8331. if (this.curIndex === -1 || this.songList.length === 0) {
  8332. this.songList = [song];
  8333. this.curIndex = 0;
  8334. this.doPlay(song)
  8335. return;
  8336. }
  8337. // 插入到当前索引+1的位置
  8338. const insertPos = this.curIndex + 1;
  8339. this.songList.splice(insertPos, 0, song);
  8340. this.songList = [...this.songList]; // 触发状态更新
  8341. this.sonDataSource.pushArrayData(this.songList)
  8342. ToastUtil.showToast('已添加至下一首播放')
  8343. }
  8344. //下一个
  8345. private playNext() {
  8346. if (!this.debounce()) {
  8347. return;
  8348. }
  8349. if (this.playType == 3) { //3:随机播放
  8350. this.randomPlay()
  8351. return;
  8352. }
  8353. if (ArrayUtil.isNotEmpty(this.songList)) {
  8354. if (this.curIndex == this.songList.length - 1) {
  8355. this.curIndex = 0;
  8356. } else {
  8357. this.curIndex++;
  8358. }
  8359. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8360. this.stop();
  8361. this.currentSong = this.songList[this.curIndex]
  8362. this.videoUrl = this.songList[this.curIndex].filePath;
  8363. this.cover = this.songList[this.curIndex].pixelMapPath
  8364. this.artist = this.songList[this.curIndex].artist
  8365. this.name = this.songList[this.curIndex].name
  8366. this.startPlayOrResumePlay()
  8367. }
  8368. }
  8369. // 存储已播放的歌曲索引
  8370. private playedIndices: Set<number> = new Set();
  8371. //随机播放
  8372. private randomPlay() {
  8373. // if (!this.debounce()) {
  8374. // return;
  8375. // }
  8376. if (ArrayUtil.isNotEmpty(this.songList)) {
  8377. if (this.songList.length > 3) {
  8378. // 如果所有歌曲都播放过一次,清空已播放索引集合
  8379. if (this.playedIndices.size === this.songList.length) {
  8380. this.playedIndices.clear();
  8381. }
  8382. // 随机选择一个未播放的歌曲索引
  8383. let newIndex: number;
  8384. // 添加超时机制防止无限循环
  8385. let attempt = 0;
  8386. const maxAttempts = 100; // 根据需求调整
  8387. do {
  8388. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  8389. attempt++;
  8390. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  8391. if (attempt >= maxAttempts) {
  8392. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  8393. newIndex = Math.floor(Math.random() * this.songList.length);
  8394. }
  8395. this.curIndex = newIndex;
  8396. this.playedIndices.add(newIndex);
  8397. } else {
  8398. // 当歌曲数量小于或等于3时,直接播放下一首
  8399. if (this.curIndex == this.songList.length - 1) {
  8400. this.curIndex = 0;
  8401. } else {
  8402. this.curIndex++;
  8403. }
  8404. }
  8405. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8406. this.stop();
  8407. this.currentSong = this.songList[this.curIndex];
  8408. this.videoUrl = this.songList[this.curIndex].filePath;
  8409. this.name = this.songList[this.curIndex].name;
  8410. this.cover = this.songList[this.curIndex].pixelMapPath
  8411. this.artist = this.songList[this.curIndex].artist
  8412. this.startPlayOrResumePlay();
  8413. }
  8414. }
  8415. private playIndex(index: number) {
  8416. if (!this.debounce()) {
  8417. return;
  8418. }
  8419. if (ArrayUtil.isNotEmpty(this.songList)) {
  8420. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8421. this.stop();
  8422. this.currentSong = this.songList[this.curIndex]
  8423. this.videoUrl = this.songList[index].filePath;
  8424. this.name = this.songList[index].name
  8425. this.cover = this.songList[this.curIndex].pixelMapPath
  8426. this.artist = this.songList[this.curIndex].artist
  8427. this.curIndex = index;
  8428. this.startPlayOrResumePlay()
  8429. }
  8430. }
  8431. //上一个
  8432. private playPrevious() {
  8433. if (!this.debounce()) {
  8434. return;
  8435. }
  8436. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  8437. this.randomModePlayFromHistory()
  8438. return;
  8439. }
  8440. if (this.curIndex == 0) {
  8441. this.curIndex = this.songList.length - 1;
  8442. } else {
  8443. this.curIndex--;
  8444. }
  8445. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8446. this.stop();
  8447. this.currentSong = this.songList[this.curIndex]
  8448. this.videoUrl = this.songList[this.curIndex].filePath;
  8449. this.name = this.songList[this.curIndex].name
  8450. this.cover = this.songList[this.curIndex].pixelMapPath
  8451. this.artist = this.songList[this.curIndex].artist
  8452. this.startPlayOrResumePlay()
  8453. }
  8454. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  8455. private randomModePlayFromHistory() {
  8456. if (this.historyList.length >= 2) {
  8457. // 播放历史记录的第二首
  8458. const prevSong = this.historyList[1];
  8459. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  8460. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8461. this.stop();
  8462. this.currentSong = prevSong;
  8463. this.videoUrl = prevSong.filePath;
  8464. this.cover = prevSong.pixelMapPath
  8465. this.artist = prevSong.artist
  8466. this.name = prevSong.name;
  8467. this.startPlayOrResumePlay();
  8468. } else {
  8469. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  8470. if (this.curIndex === 0) {
  8471. this.curIndex = this.songList.length - 1;
  8472. } else {
  8473. this.curIndex--;
  8474. }
  8475. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8476. this.stop();
  8477. this.currentSong = this.songList[this.curIndex];
  8478. this.videoUrl = this.songList[this.curIndex].filePath;
  8479. this.cover = this.songList[this.curIndex].pixelMapPath
  8480. this.artist = this.songList[this.curIndex].artist
  8481. this.name = this.songList[this.curIndex].name;
  8482. this.startPlayOrResumePlay();
  8483. }
  8484. }
  8485. debounce() {
  8486. const delay = 600;
  8487. let cur = new Date().getTime();
  8488. if (cur - this.last > delay) {
  8489. this.last = cur;
  8490. return true;
  8491. }
  8492. return false;
  8493. }
  8494. /**
  8495. * Sets whether the screen is a constant based on the playback status.
  8496. */
  8497. watchStatus() {
  8498. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  8499. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8500. this.windowClass.setWindowKeepScreenOn(true);
  8501. } else {
  8502. this.windowClass.setWindowKeepScreenOn(false);
  8503. }
  8504. }
  8505. /**
  8506. * Volume gesture method onActionStart.
  8507. *
  8508. * @param event Gesture event.
  8509. */
  8510. private customDialogComponentIdMM: number = 0
  8511. @Builder
  8512. customDialogComponentMM() {
  8513. Column() {
  8514. Row() {
  8515. Blank()
  8516. Text('验证密码')
  8517. .fontSize(22)
  8518. .fontColor($r('app.color.pri_bg'))
  8519. .margin({ top: 18 })
  8520. Blank()
  8521. Image($r('app.media.close'))
  8522. .fillColor(Color.White)
  8523. .margin({ top: 18, right: 18 })
  8524. .width(20)
  8525. .onClick(() => {
  8526. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  8527. })
  8528. }
  8529. .width('100%') // 使Row占据整个宽度
  8530. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  8531. Verify({
  8532. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  8533. });
  8534. }.height('60%')
  8535. .backgroundColor($r('app.color.index_background'))
  8536. .justifyContent(FlexAlign.SpaceBetween)
  8537. }
  8538. private handleVerifyCompleted(isSuccess: boolean) {
  8539. if (isSuccess) {
  8540. console.log('验证成功');
  8541. // 在这里处理验证成功后的逻辑
  8542. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  8543. this.currentPath = this.lockPath
  8544. this.getSortedFiles(this.currentPath)
  8545. } else {
  8546. // console.log('验证失败');
  8547. ToastUtil.showToast('验证失败')
  8548. }
  8549. }
  8550. private showVerifyDialog() {
  8551. promptAction.openCustomDialog({
  8552. transition: TransitionEffect.asymmetric(
  8553. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  8554. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  8555. ,
  8556. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  8557. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  8558. ),
  8559. builder: () => {
  8560. this.customDialogComponentMM()
  8561. },
  8562. isModal: true,
  8563. autoCancel: true,
  8564. maskColor: Color.Transparent,
  8565. alignment: DialogAlignment.Bottom,
  8566. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  8567. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  8568. console.log("dialog onWillDismiss")
  8569. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  8570. dismissDialogAction.dismiss()
  8571. }
  8572. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  8573. dismissDialogAction.dismiss()
  8574. }
  8575. }
  8576. }).then((dialogId: number) => {
  8577. this.customDialogComponentIdMM = dialogId
  8578. })
  8579. }
  8580. //左滑操作 移动文件 重命名 删除等操作
  8581. @Builder
  8582. DeleteButton(item: VideoItem, index: number, filePath: string) {
  8583. Row() {
  8584. //加入收藏
  8585. Button() {
  8586. Image(Utility.getIsFav(this.favList,item)?$r('app.media.add_fac_light2'):$r('app.media.add_fac'))
  8587. .fillColor(Color.White)
  8588. .width(20)
  8589. }
  8590. .width(40)
  8591. .height(40)
  8592. .type(ButtonType.Circle)
  8593. .backgroundColor(this.themeColor)
  8594. .margin(5)
  8595. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8596. .onClick(() => {
  8597. if(item){
  8598. this.doFav(item)
  8599. }
  8600. })
  8601. //加入下一首播放
  8602. Button() {
  8603. Image($r('app.media.next_to_play'))
  8604. .fillColor(Color.White)
  8605. .width(20)
  8606. }
  8607. .width(40)
  8608. .height(40)
  8609. .type(ButtonType.Circle)
  8610. .backgroundColor(this.themeColor)
  8611. .margin(5)
  8612. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8613. .onClick(() => {
  8614. this.addToNextPlay(item);
  8615. })
  8616. //复制文件
  8617. Button() {
  8618. Image($r('app.media.copy'))
  8619. .fillColor(Color.White)
  8620. .width(20)
  8621. }
  8622. .width(40)
  8623. .height(40)
  8624. .type(ButtonType.Circle)
  8625. .backgroundColor(this.themeColor)
  8626. .margin(5)
  8627. .id(filePath + 'copy')
  8628. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8629. .onClick(() => {
  8630. this.showCopyDialog(false, item, index, filePath + 'copy');
  8631. })
  8632. //移动文件
  8633. Button() {
  8634. Image($r('app.media.cut'))
  8635. .fillColor(Color.White)
  8636. .width(20)
  8637. }
  8638. .width(40)
  8639. .height(40)
  8640. .type(ButtonType.Circle)
  8641. .backgroundColor(this.themeColor)
  8642. .margin(5)
  8643. .id(filePath)
  8644. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8645. .onClick(() => {
  8646. this.showCutDialog(false, item, index, filePath);
  8647. })
  8648. Button() {
  8649. Image($r('app.media.cut_current'))
  8650. .fillColor(Color.White)
  8651. .width(20)
  8652. }
  8653. .width(40)
  8654. .height(40)
  8655. .type(ButtonType.Circle)
  8656. .backgroundColor(this.themeColor)
  8657. .margin(5)
  8658. .id(filePath + 'current')
  8659. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  8660. (this.isHasDir ? Visibility.Visible : Visibility.None))
  8661. .onClick(() => {
  8662. this.showCutDialog(true, item, index, filePath + 'current');
  8663. })
  8664. //重命名
  8665. Button() {
  8666. Image($r('app.media.rename2'))
  8667. .fillColor(Color.White)
  8668. .width(20)
  8669. }
  8670. .width(40)
  8671. .height(40)
  8672. .type(ButtonType.Circle)
  8673. .backgroundColor(this.themeColor)
  8674. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  8675. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  8676. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  8677. .margin(5)
  8678. .onClick(() => {
  8679. this.showReNameDialog(item, index + '', filePath)
  8680. })
  8681. Button() {
  8682. Image($r('app.media.delete2'))
  8683. .fillColor(Color.White)
  8684. .width(20)
  8685. }
  8686. .width(40)
  8687. .height(40)
  8688. .type(ButtonType.Circle)
  8689. .backgroundColor(this.themeColor)
  8690. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  8691. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  8692. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  8693. .margin(5)
  8694. .onClick(() => {
  8695. this.showWarnIsDeleteFile(item, index + '', filePath)
  8696. })
  8697. Button() {
  8698. Image($r('app.media.share2'))
  8699. .fillColor(Color.White)
  8700. .width(20)
  8701. }
  8702. .width(40)
  8703. .height(40)
  8704. .type(ButtonType.Circle)
  8705. .backgroundColor(this.themeColor)
  8706. .margin(5)
  8707. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  8708. .onClick(() => {
  8709. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8710. })
  8711. }
  8712. }
  8713. /**
  8714. * 穿山甲banner广告
  8715. */
  8716. // private declare bannerAd: CSJNativeExpressAd;
  8717. // @State private status: string = "未加载"
  8718. // @State private isShowAd: boolean = false
  8719. // private declare mAdSlot: AdSlot;
  8720. // private mBiddingAdm = '' //服务端bidding才需要设置
  8721. // private expressLoadAdListener: NativeExpressAdListener = {
  8722. // /**
  8723. // * 加载失败的回调
  8724. // *
  8725. // * @param code
  8726. // * @param message
  8727. // */
  8728. // onError: (code: number, message: string) => {
  8729. // console.error("加载广告失败,code=" + code + ",message=" + message);
  8730. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  8731. // },
  8732. //
  8733. // /**
  8734. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  8735. // *
  8736. // * @param ads 返回的广告列表
  8737. // */
  8738. //
  8739. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  8740. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  8741. // if (ads && ads.length > 0) {
  8742. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  8743. // ad.setExpressInteractionListener({
  8744. // /**
  8745. // *广告的点击回调
  8746. // * @param type 广告的交互类型
  8747. // */
  8748. // onAdClicked: (type: number) => {
  8749. // console.log("BannerExpressAdPage==onAdClicked......");
  8750. // },
  8751. //
  8752. // /**
  8753. // * 广告的展示回调 每个广告仅回调一次
  8754. // * @param type 广告的交互类型
  8755. // */
  8756. // onAdShow: (type: number) => {
  8757. // console.log("BannerExpressAdPage==onAdShow......");
  8758. // },
  8759. //
  8760. // /**
  8761. // * 模板渲染失败
  8762. // */
  8763. // onRenderFail: (code: number, msg: string) => {
  8764. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  8765. // },
  8766. //
  8767. // /**
  8768. // * 模板渲染成功
  8769. // * @param width 返回view的宽 单位 vp
  8770. // * @param height 返回view的高 单位 vp
  8771. // */
  8772. // onRenderSuccess: (width: number, height: number) => {
  8773. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  8774. // this.bannerAd = ad;
  8775. // this.status = "广告加载完成待展示";
  8776. //
  8777. // this.showBannerAd()
  8778. // }
  8779. // })
  8780. // //渲染广告
  8781. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  8782. // this.setDislikeCallback(ad); //设置dislike
  8783. // ad.render(this.getUIContext())
  8784. // this.status = "广告加载中...";
  8785. // });
  8786. // }
  8787. // }
  8788. // }
  8789. //
  8790. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  8791. // ad.setDislikeCallback({
  8792. // /**
  8793. // * dislike show
  8794. // */
  8795. // onShow: () => {
  8796. // console.log("BannerExpressAdPage==dislike......show");
  8797. // },
  8798. //
  8799. // /**
  8800. // * @param position 选择的位置
  8801. // * @param value 选择的内容
  8802. // * @param enforceRemove 是否强制关闭广告
  8803. // */
  8804. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  8805. // this.isShowAd = false;
  8806. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  8807. // ",enforce=" + enforceRemove);
  8808. // },
  8809. //
  8810. // /**
  8811. // * 点击取消
  8812. // */
  8813. // onCancel: () => {
  8814. // console.log("BannerExpressAdPage==dislike......onCancel");
  8815. // }
  8816. //
  8817. // })
  8818. // }
  8819. /**
  8820. * 加载Banner广告
  8821. */
  8822. loadBannerAd(rit: string) {
  8823. // if (Utility.isNoble()) {
  8824. // return
  8825. // }
  8826. // if (!Utility.isPassInstallTime(2)) {
  8827. // return
  8828. // }
  8829. // this.isShowAd = false;
  8830. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  8831. // this.mAdSlot = new AdSlotBuilder()
  8832. // .setCodeId(rit)
  8833. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  8834. // .setAdCount(1)
  8835. // .setBidAdm(this.mBiddingAdm)
  8836. // .build()
  8837. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  8838. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  8839. // this.status = "广告加载中..."
  8840. }
  8841. /**
  8842. * 展示Banner广告
  8843. */
  8844. // showBannerAd() {
  8845. // if (!this.bannerAd) {
  8846. // return
  8847. // }
  8848. // this.isShowAd = true
  8849. // this.status = "已展示"
  8850. // }
  8851. /**
  8852. * 穿山甲广告代码结束
  8853. */
  8854. }
  8855. //视频气泡窗口的布局
  8856. @Builder
  8857. function customPopupBuilder(dataBu: BubbleBean) {
  8858. List() {
  8859. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  8860. ListItem() {
  8861. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8862. Row() {
  8863. Column() {
  8864. Image(dataBu.imageRes[index])
  8865. .height(28)
  8866. .fillColor(dataBu.color)
  8867. .alignSelf(ItemAlign.Center)
  8868. }
  8869. .width(32)
  8870. Text(item)
  8871. .padding({
  8872. top: 10,
  8873. bottom: 10,
  8874. right: 10,
  8875. left: 10
  8876. })
  8877. .fontColor(dataBu.modeType ==index?dataBu.color:$r('app.color.index_tab_font_color'))
  8878. .textAlign(TextAlign.Start)
  8879. .width("100%")
  8880. }
  8881. }
  8882. .backgroundColor($r('app.color.settings_background_main'))
  8883. .margin({ top: 6, bottom: 6 })
  8884. }
  8885. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM).animation({ duration: 500,curve: Curve.Ease, delay: 100*index }),
  8886. TransitionEffect.scale({ x: 0, y: 0 }) ))
  8887. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  8888. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  8889. .onClick(() => {
  8890. dataBu.onItemClick?.(index)
  8891. })
  8892. })
  8893. }
  8894. .width(120)
  8895. .divider({
  8896. strokeWidth: 1,
  8897. color: "#22FFFFFF"
  8898. })
  8899. }
  8900. // Function to calculate a hash for the file list
  8901. function simpleHash(fileList: string[]): string {
  8902. let hash = 0;
  8903. const str = fileList.join(',');
  8904. for (let i = 0; i < str.length; i++) {
  8905. const char = str.charCodeAt(i);
  8906. hash = (hash << 5) - hash + char;
  8907. hash |= 0; // Convert to 32bit integer
  8908. }
  8909. return hash.toString();
  8910. }
  8911. interface MoreItem {
  8912. id: number;
  8913. image: Resource;
  8914. title: string;
  8915. }
  8916. //视频气泡窗口的布局
  8917. @Builder
  8918. function cutPopupBuilder(dataBu: BubbleBean) {
  8919. Column() {
  8920. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  8921. .padding({
  8922. top: 10,
  8923. bottom: 10,
  8924. right: 10,
  8925. left: 10
  8926. })
  8927. .textAlign(TextAlign.Start)
  8928. .width(160)
  8929. .fontWeight(666)
  8930. .fontSize(16)
  8931. List() {
  8932. ForEach(dataBu.data, (item: string, index: number) => {
  8933. ListItem() {
  8934. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8935. Row() {
  8936. Column() {
  8937. Image($r('app.media.music_group'))
  8938. .height(28)
  8939. .fillColor(dataBu.color)
  8940. .alignSelf(ItemAlign.Center)
  8941. }
  8942. .width(32)
  8943. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  8944. .padding({
  8945. top: 10,
  8946. bottom: 10,
  8947. right: 10,
  8948. left: 10
  8949. })
  8950. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  8951. .fontSize(15)
  8952. }
  8953. }
  8954. .backgroundColor(Color.Transparent)
  8955. .margin({ top: 7, bottom: 7 })
  8956. }
  8957. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM).animation({ duration: 500 }),
  8958. TransitionEffect.scale({ x: 0, y: 0 }) ))
  8959. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  8960. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  8961. .onClick(() => {
  8962. dataBu.onItemClick?.(index)
  8963. })
  8964. })
  8965. }
  8966. .width(150)
  8967. .divider({
  8968. strokeWidth: 1,
  8969. color: "#22FFFFFF"
  8970. })
  8971. }
  8972. .height(300)
  8973. .padding({
  8974. bottom:30
  8975. })
  8976. }