LocalMusic.ets 333 KB

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