LocalMusic.ets 438 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825
  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 { imagePathToPixelMap } from '../common/util/CommUtils';
  21. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  22. import { CommonConstants } from '../common/constants/CommonConstants';
  23. import Logger from '../common/util/Logger';
  24. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  25. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  26. import { BubbleBean } from '../viewmodel/BubbleBean';
  27. import { PopupPosition, XPopup } from '@chinalike/popup';
  28. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  29. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  30. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  31. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  32. import { Verify } from './Verify';
  33. import { RotatingCover } from './RotatingCover';
  34. import { PlayConstants } from '../common/constants/PlayConstants';
  35. import { effectKit } from '@kit.ArkGraphics2D';
  36. import { ColorConversion } from '../common/util/ColorConversion';
  37. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  38. import { AvSessionController } from '../controller/AvSessionController';
  39. import { repairAudioMetadata, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  40. import { FFMpegTags,Utility } from '../common/util/Utility';
  41. import { TagsContentCover } from '../view/TagsContentCover';
  42. import { ImageFancyModifier } from '../common/util/AttributeModifierUtil'
  43. import {
  44. // DeviceChangeReason,
  45. IjkMediaPlayer,
  46. InterruptEvent,
  47. InterruptHintType,
  48. LogUtils,
  49. OnBufferingUpdateListener,
  50. OnCompletionListener,
  51. OnErrorListener,
  52. OnInfoListener,
  53. OnPreparedListener,
  54. OnSeekCompleteListener,
  55. OnTimedTextListener,
  56. OnVideoSizeChangedListener
  57. } from '@ohos/ijkplayer';
  58. import { PlayStatus } from '../common/PlayStatus';
  59. import fs from '@ohos.file.fs';
  60. import { image } from '@kit.ImageKit';
  61. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  62. import { UniversalDetector } from '@ohos/juniversalchardet';
  63. import { SettingPage } from '../pages/SettingPage';
  64. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  65. import { CommonConstants2 } from '../common/util/CommonConstants2';
  66. import { hilog } from '@kit.PerformanceAnalysisKit';
  67. import { LazyDataSource } from '../common/util/LazyDataSource';
  68. import MediaTable from '../common/util/MediaTable';
  69. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  70. import ImageUtils from '../common/util/ImageUtils';
  71. import { ringtone } from '@kit.RingtoneKit';
  72. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  73. import { resourceManager } from '@kit.LocalizationKit';
  74. import { deviceInfo } from '@kit.BasicServicesKit';
  75. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  76. import app from '@system.app';
  77. import { TextNodeController } from './PipLyricTextBuilder';
  78. import { IndexerView } from './IndexerView';
  79. import { KeyCode } from '@kit.InputKit';
  80. import { KnockController } from '../controller/KnockController';
  81. import { DeleteComptent } from '../view/DeleteComptent'
  82. import { ABLoopComptent } from '../view/ABLoopComptent';
  83. import { FixMessyView } from '../view/FixMessyView';
  84. const TAG = 'LocalMusic';
  85. const DEFAULT_INDEX =
  86. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  87. 'X', 'Y', 'Z']
  88. //排序类型
  89. function getTypeOrder(type: number) {
  90. switch (type) {
  91. case CommonConstants.TYPE_IS_DIR:
  92. return 1; // First
  93. case CommonConstants.TYPE_IS_CSJAD:
  94. return 2; // Middle
  95. case CommonConstants.TYPE_LOCAL:
  96. return 3; // Last
  97. default:
  98. return 4; // Unknown types, if any, go last
  99. }
  100. }
  101. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  102. // 定义接口
  103. interface HiCarAspectRatio {
  104. ratio: number;
  105. name: string;
  106. }
  107. interface GeneratedObjectLiteralInterface_1 {
  108. assetId: string;
  109. title: string;
  110. artist: string;
  111. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  112. mediaUri: string;
  113. // 该字段大写,音频'AUDIO',视频'VIDEO'
  114. mediaType: string;
  115. mediaSize: number;
  116. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  117. startPosition: number;
  118. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  119. duration: number;
  120. albumCoverUri: string;
  121. albumTitle: string;
  122. appName: string;
  123. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  124. drmScheme: string;
  125. }
  126. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  127. const ITEM_HEIGHT: number = 58; // 列表项中高度
  128. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  129. //功能强大的音乐播放器
  130. @Preview
  131. @Component
  132. export struct LocalMusic {
  133. @State fastForwardSeconds: string = '10'
  134. @State isShowBackFast: boolean = true//快进快退按钮
  135. @State isCanAuto:boolean = true
  136. @State opacityValueImage: number = 1;
  137. @State tipPopup:boolean = false
  138. @Consume mType: number;
  139. @StorageProp('themeColor') themeColor: string =
  140. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  141. themeMode: number = 0;
  142. @State titleName: string = '首页'
  143. @State textStr: string = ''
  144. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  145. // private download_path: string = '';
  146. @Consume rootPath: string //音频根目录
  147. @Consume currentPath: string
  148. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  149. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  150. @State lockPath: string = ''
  151. @State favPath: string = ''
  152. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  153. @State historyPath: string = ''
  154. @State historyList: Array<VideoItem> = []
  155. @Consume isHistory: boolean
  156. static readonly HISTORY_MUSIC: string = 'music_historyList';
  157. private table: MediaTable = new MediaTable(getContext(this))
  158. @State isZero: boolean = false
  159. @State fileList: Array<string> = []
  160. @State dirList: Array<VideoItem> = []
  161. @Consume videoLocalList: Array<VideoItem>
  162. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  163. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  164. @State artistList: Array<VideoItem> = []; //艺术家文件
  165. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  166. @State albumList: Array<VideoItem> = []; //专辑文件
  167. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  168. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  169. @State imageOpacities: number[] = [];
  170. @Consume isCanBack: boolean
  171. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  172. @State showSingleLyric: boolean = false
  173. @State sortType: number = 4 //默认排序方式
  174. @State isShowSimi: boolean = false //是否显示私密音频
  175. @State isShowFAV: boolean = true //是否显示我的收藏
  176. @State isShowTitleBar: boolean = true //是否显示分类导航条
  177. @State isShowAllBar: boolean = true //是否显示播放全部条
  178. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  179. @State isShowHistory: boolean = true //是否显示最近播放
  180. @State isCustomizeBg: boolean = false //自定义背景界面
  181. @State isGridMusic: boolean = false //是否网格布局
  182. @State isCircleBtn: boolean = false //是否圆形播放按钮
  183. @State twoFingerType: number = 3 //双支放大缩小的类型
  184. @State isScrollHide: boolean = false //是否滚动隐藏
  185. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  186. @State isStartAutoPlay: boolean = false //启动后自动播放
  187. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  188. @State isShowHeader: boolean = true
  189. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  190. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  191. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  192. @State isSwipe: boolean = false //listItem的左滑开关
  193. @State openSkipSongAnimate: boolean = true//切歌动画效果
  194. @State customizeBgPath: string | undefined = '';
  195. @State isDarkMode: boolean = false
  196. @State lyricTextWeight: number = 400
  197. @State lyricTextWeightPip: number = 400
  198. @State currentSwiperIndex: number = 0
  199. @State blurValue: number = 0 //背景模糊
  200. @State bgBrightness: number = 0 //背景亮度
  201. private listScroller: ListScroller = new ListScroller()
  202. private playListScroller: Scroller = new Scroller()
  203. @State isOneKeyTags:boolean = false
  204. @State isFixMessy:boolean = false
  205. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  206. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  207. @StorageProp('windowWidth') windowWidth: number = 0;
  208. @StorageProp('windowHeight') windowHeight: number = 0;
  209. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  210. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  211. private UNKONWN:string = '';
  212. private listArea: Area = {
  213. width: 0,
  214. height: 0,
  215. position: {},
  216. globalPosition: {}
  217. }
  218. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  219. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  220. //瀑布流的列数横竖屏动态切换
  221. onIsLandscapeChange() {
  222. if(this.isLandscape){
  223. this.columns = 4
  224. }else{
  225. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  226. }
  227. }
  228. onColorModeChange() {
  229. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  230. if (this.isCustomizeBg) {
  231. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  232. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  233. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  234. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  235. } else {
  236. if (!this.isDarkMode) {
  237. this.titleBarModel.setTitleBarBackground(this.themeColor)
  238. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  239. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  240. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  241. } else {
  242. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  243. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  244. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  245. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  246. }
  247. }
  248. }
  249. onModeChange() {
  250. this.isFavMusic = false
  251. if (this.modeType === 2 || this.modeType === 3) {
  252. this.titleBarModel.setRightIcon(null)
  253. } else {
  254. this.titleBarModel.setRightIcon(($r('app.media.add')))
  255. }
  256. LogUtil.info('onecold onModeChange = ' + this.modeType)
  257. switch (this.modeType) {
  258. case 0:
  259. this.getSortedFiles(this.currentPath)
  260. break
  261. case 1:
  262. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  263. this.updateListData(this.mediaKuList)
  264. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  265. break
  266. case 2:
  267. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  268. this.updateListData(this.artistList)
  269. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  270. break
  271. case 3:
  272. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  273. this.updateListData(this.albumList)
  274. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  275. break
  276. }
  277. }
  278. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  279. // @StorageLink('isPlay') isPlay: boolean = false;
  280. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  281. @StorageLink('songList') songList: Array<VideoItem> = [];
  282. @State translateY: number = 0;
  283. @State isShowSheet: boolean = false;
  284. @State isShowSheetView: boolean = false;
  285. @State isShowTimeCloseView: boolean = false;
  286. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  287. @StorageLink('currIndex') curIndex: number = 0;
  288. @Consume isShowDrawer: boolean;
  289. @Consume offsetX: number;
  290. @State isFac: boolean = false;
  291. @State favList: Array<VideoItem> = []
  292. @Consume isFavMusic: boolean
  293. @State isClickedPLayAll: boolean = false;
  294. private scrollerForlist: ListScroller = new ListScroller();
  295. private knockController: KnockController | undefined = undefined;
  296. imagesF: ImageFrameInfo[] = [
  297. { src: $r("app.media.app_loading0") },
  298. { src: $r("app.media.app_loading1") },
  299. { src: $r("app.media.app_loading2") },
  300. { src: $r("app.media.app_loading3") },
  301. ]
  302. @State animationState: AnimationStatus = AnimationStatus.Initial
  303. // 缓存机制
  304. private cache: Map<string, Array<VideoItem>> = new Map();
  305. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  306. // 持久化缓存
  307. private async saveCacheToStorage() {
  308. const cacheArray = Array.from(this.cache.entries());
  309. const stringCacheArray = Array.from(this.stringCache.entries());
  310. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  311. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  312. }
  313. // 载入缓存
  314. private async loadCacheFromStorage() {
  315. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  316. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  317. if (cacheString) {
  318. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  319. this.cache = new Map(cacheArray);
  320. }
  321. if (stringCacheString) {
  322. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  323. this.stringCache = new Map(stringCacheArray);
  324. }
  325. }
  326. // 查找缓存
  327. private findCache(key: string): Array<VideoItem> | undefined {
  328. return this.cache.get(key);
  329. }
  330. // 查找字符串缓存
  331. private findStringCache(key: string): string | undefined {
  332. return this.stringCache.get(key);
  333. }
  334. // 添加缓存
  335. private addCache(key: string, value: Array<VideoItem>) {
  336. this.cache.set(key, value);
  337. }
  338. // 添加字符串缓存
  339. private addStringCache(key: string, value: string) {
  340. this.stringCache.set(key, value);
  341. }
  342. // 删除缓存
  343. private deleteCache(key: string) {
  344. this.cache.delete(key);
  345. this.saveCacheToStorage()
  346. }
  347. // 删除字符串缓存
  348. private deleteStringCache(key: string) {
  349. this.stringCache.delete(key);
  350. }
  351. // 多选机制
  352. @State selectedFiles: Array<VideoItem> = [];
  353. @State isMultiSelect: boolean = false;
  354. @State isAllSelected: boolean = false;
  355. @State appName: string = ''
  356. @State isHasDir: boolean = false
  357. @State packName: string = ''
  358. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  359. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  360. .setTitleTextStyle(FontStyle.Normal)
  361. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  362. .setLeftIcon($r('app.media.menu'))
  363. .setLeftIconWidth(26)
  364. .setLeftIconHeight(26)
  365. .setTitleName('首页')
  366. .setTitleFontSize(18)
  367. .setTitleFontColor(Color.White)
  368. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  369. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  370. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  371. .setRightIcon($r('app.media.add'))
  372. .setOnRightClickListener(() => {
  373. this.showSheelDialog()
  374. })
  375. // .setOnTitleClickListener(() => {
  376. // this.showPupDialog()
  377. // })
  378. .setOnLeftClickListener(() => {
  379. this.doSwipBack()
  380. })
  381. doSwipBack() {
  382. this.isZero = false
  383. if (this.modeType !== 0 && this.isCanBack) {
  384. this.onModeChange()
  385. this.isCanBack = false
  386. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  387. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  388. setTimeout(() => {
  389. if (this.modeType == 2) {
  390. if (this.isGridMusic||this.twoFingerType==4) {
  391. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  392. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  393. if(this.twoFingerType==4){
  394. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  395. }else{
  396. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  397. }
  398. } else {
  399. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  400. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  401. }
  402. } else if (this.modeType == 3) {
  403. if (this.isGridMusic||this.twoFingerType==4) {
  404. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  405. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  406. if(this.twoFingerType==4){
  407. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  408. }else{
  409. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  410. }
  411. } else {
  412. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  413. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  414. }
  415. }
  416. }, 200)
  417. return
  418. }
  419. if (this.isHistory || this.isFavMusic) {
  420. this.isHistory = false
  421. this.getSortedFiles(this.currentPath)
  422. return
  423. }
  424. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  425. animateTo({ duration: 555 }, () => {
  426. // 动画闭包内控制Image组件的出现和消失
  427. this.isShowDrawer = !this.isShowDrawer
  428. this.offsetX = 0
  429. })
  430. return
  431. }
  432. //返回上一级歌单的滚动位置
  433. setTimeout(() => {
  434. if (this.modeType == 0) {
  435. if (this.isGridMusic||this.twoFingerType==4) {
  436. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  437. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  438. if(this.twoFingerType==4){
  439. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  440. }else{
  441. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  442. }
  443. } else {
  444. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  445. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  446. }
  447. }
  448. }, 300)
  449. this.currentPath = Utility.getParentDirectory(this.currentPath)
  450. Logger.info('this.currentPath2 = ' + this.currentPath)
  451. this.getSortedFiles(this.currentPath)
  452. }
  453. // 组件生命周期
  454. aboutToAppear() {
  455. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  456. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  457. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  458. this.tipPopup = !this.tipPopup
  459. PreferencesUtil.putSync('isFirstTiped',false)
  460. }
  461. this.initSetting()
  462. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  463. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  464. Utility.getAppName(getContext(this)).then((appName: string) => {
  465. this.appName = appName
  466. })
  467. this.packName = AppUtil.getBundleName()
  468. this.loadCacheFromStorage(); // 加载缓存
  469. // 在首页初始化时读取媒体库缓存数据
  470. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  471. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  472. if(ArrayUtil.isNotEmpty(cachedList)){
  473. this.mediaKuList = cachedList
  474. if(this.modeType==1){
  475. this.updateListData(this.mediaKuList)
  476. }
  477. }
  478. this.mkDownLoadDir()
  479. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  480. // 监听广播事件(打开其他应用处理)
  481. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  482. this.saveVideoDatas([eventData.data?.message], true)
  483. });
  484. //侧滑广播接收时间
  485. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  486. // 监听广播事件(打开其他应用处理)
  487. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  488. animateTo({ duration: 555 }, () => {
  489. this.doSwipBack()
  490. })
  491. });
  492. //ScanFilePage广播接收时间
  493. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  494. // 监听ScanFilePage广播事件(更新数据库)
  495. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  496. this.doUpdateData()
  497. });
  498. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  499. // 监听广播事件(通用设置配置更新)
  500. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  501. this.doChangeSetting()
  502. });
  503. let event: Callback<InterruptEvent> = (event) => {
  504. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  505. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  506. this.savePlaybackPosition()
  507. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  508. this.pause();
  509. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  510. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  511. console.info('onecold startPlayOrResumePlay 514')
  512. this.startPlayOrResumePlay();
  513. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  514. this.stop();
  515. }
  516. }
  517. this.mIjkMediaPlayer.on('audioInterrupt', event);
  518. // 音频设备断连回调处理
  519. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  520. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  521. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  522. // this.pause();
  523. // }
  524. // }
  525. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  526. this.makeWorker()
  527. //折叠屏的屏幕显示模式变化
  528. display.on('foldDisplayModeChange', (data) => {
  529. this.doChangeBarHeight()
  530. });
  531. display.on('foldStatusChange', (data) => {
  532. Logger.info('onecold foldStatusChange ')
  533. });
  534. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  535. // 读取 themeMode 并同步 currentColorMode
  536. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  537. this.applyThemeMode(this.themeMode)
  538. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  539. AppStorage.setOrCreate('themeColor', themeColor);
  540. this.themeColor = themeColor;
  541. this.doChangeSetting()
  542. this.windowClass.on('windowSizeChange', (size) => {
  543. LogUtil.info('onecold windowSizeChange')
  544. this.doChangeBarHeight()
  545. let viewWidth = px2vp(size.width);
  546. let viewHeight = px2vp(size.height);
  547. if(this.isPhoneLan()){
  548. this.is_auto_hide_progress = false
  549. if(this.isHiCar()){
  550. return
  551. }
  552. setTimeout(() => {
  553. this.is_auto_hide_progress = true
  554. }, 6000)
  555. }else{
  556. this.startAutoHide()
  557. }
  558. });
  559. this.eventHub.on('onStateChange', (fg: boolean) => {
  560. if (fg && this.curState === 'STARTED') {
  561. this.stopPip();
  562. }
  563. });
  564. }
  565. startAutoHide() {
  566. if(this.isHiCar()){
  567. return
  568. }
  569. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  570. console.info('onecold startAutoHide')
  571. this.is_auto_hide_progress = false
  572. setTimeout(() => {
  573. this.is_auto_hide_progress = true
  574. }, 6000)
  575. }
  576. }
  577. applyThemeMode(mode: number) {
  578. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  579. if (mode === 1) {
  580. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  581. } else if (mode === 2) {
  582. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  583. }
  584. AppStorage.setOrCreate('currentColorMode', colorMode)
  585. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  586. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  587. AppStorage.setOrCreate('themeMode', mode)
  588. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  589. // 只有强制浅色/深色时才主动设置
  590. const context = getContext(this) as common.UIAbilityContext
  591. context.getApplicationContext().setColorMode(colorMode)
  592. }
  593. initSetting() {
  594. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  595. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  596. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  597. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  598. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  599. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  600. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  601. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  602. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  603. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  604. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  605. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  606. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  607. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  608. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  609. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  610. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  611. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  612. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  613. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  614. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  615. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  616. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  617. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, false)
  618. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  619. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  620. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  621. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  622. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  623. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  624. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  625. if(this.volumeSmall){
  626. this.volume = 0.5
  627. }else{
  628. this.volume = 1
  629. }
  630. //如果是hicar连接状态,这些都是false
  631. if(this.isHiCar()){
  632. this.isShowTitleBar = false//不显示导航栏
  633. this.columns=4
  634. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  635. {
  636. this.isShowHeader = false//二级菜单不显示头部
  637. this.isGridMusic= false//用list不用网格
  638. this.isCoverTopBig = false
  639. }
  640. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  641. }
  642. if (this.isSavePlayMode) {
  643. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  644. }
  645. if (this.isCustomizeBg) {
  646. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  647. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  648. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  649. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  650. } else {
  651. if (!this.isDarkMode) {
  652. this.titleBarModel.setTitleBarBackground(this.themeColor)
  653. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  654. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  655. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  656. } else {
  657. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  658. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  659. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  660. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  661. }
  662. }
  663. }
  664. doChangeSetting() {
  665. this.initSetting()
  666. this.deleteCache(this.currentPath)
  667. if (this.modeType === 0) {
  668. this.getSortedFiles(this.currentPath)
  669. }
  670. }
  671. doChangeBarHeight() {
  672. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  673. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  674. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  675. this.setBarHeightNormal()
  676. }
  677. }
  678. onPageShow() {
  679. this.knockController?.immersiveListening();
  680. app.setImageCacheCount(100);
  681. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  682. app.setImageRawDataCacheSize(104857600);
  683. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  684. }
  685. //开启线程查看各个数据库
  686. makeWorker() {
  687. setTimeout(() => {
  688. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  689. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  690. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  691. // workerInstance.postMessage({
  692. // code: 1,
  693. // data1: this.context,
  694. // data2: this.rootPath,
  695. // data3: this.lockPath,
  696. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  697. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  698. // });
  699. PreferencesUtil.putSync('isFirstApp', false)
  700. } else {
  701. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  702. workerInstance.postMessage({ code: 3, data: this.context });
  703. workerInstance.postMessage({ code: 4, data: this.context });
  704. this.getHistoryList(false)
  705. }
  706. }, 1000)
  707. workerInstance.onmessage = (e: MessageEvents): void => {
  708. switch (e.data.code) {
  709. case 101: //第一次扫描文件夹入库
  710. ToastUtil.showToast('刷新同步数据库成功!')
  711. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  712. this.doUpdateData()
  713. break;
  714. case 102: //查询媒体库列表
  715. this.mediaKuList = e.data.data
  716. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  717. Utility.doSortListAscending(this.mediaKuList)
  718. // AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  719. if (this.modeType === 1) {
  720. this.updateListData(this.mediaKuList)
  721. }
  722. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  723. // 处理媒体库前50条记录,列表长度并存储到PreferencesUtil
  724. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 50) {
  725. // 只保存前50条记录到缓存中
  726. let truncatedList = this.mediaKuList.slice(0, 50);
  727. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  728. } else {
  729. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  730. }
  731. break;
  732. case 103: //收到查询艺术家列表
  733. this.artistMap = e.data.data1;
  734. this.artistList = e.data.data2;
  735. PreferencesUtil.putSync('artistCount', this.artistList.length)
  736. break;
  737. case 104: //收到查询专辑列表
  738. this.albumMap = e.data.data1;
  739. this.albumList = e.data.data2
  740. //查询完毕在启动是否自动播放
  741. if (this.isStartAutoPlay&&this.isCanAuto) {
  742. this.isCanAuto = false
  743. console.info('onecold startPlayOrResumePlay 757')
  744. this.startPlayOrResumePlay()
  745. }
  746. PreferencesUtil.putSync('albumCount', this.albumList.length)
  747. break;
  748. }
  749. };
  750. // 在调用terminate后,执行onexit
  751. workerInstance.onexit = (code) => {
  752. console.log("main thread terminate");
  753. }
  754. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  755. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  756. workerInstance.onerror = (err: ErrorEvent) => {
  757. console.log("onerror" + err.message);
  758. }
  759. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  760. //碰一碰分享的监听
  761. this.knockController = KnockController.getInstance(this.context);
  762. this.knockController?.immersiveListening();
  763. }
  764. onPageHide(): void {
  765. this.knockController?.immersiveDisableListening();
  766. }
  767. @State isFirstStartPlay: boolean = false
  768. //获取download_path
  769. async mkDownLoadDir() {
  770. const documentViewPicker = new picker.DocumentViewPicker()
  771. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  772. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  773. this.currentPath = this.rootPath
  774. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  775. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  776. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  777. Logger.info('onecold rootPath = ' + this.rootPath)
  778. Logger.info('onecold lockPath = ' + this.lockPath)
  779. if (!FileUtil.accessSync(this.lockPath)) {
  780. FileUtil.mkdirSync(this.lockPath)
  781. }
  782. if (!FileUtil.accessSync(this.favPath)) {
  783. FileUtil.mkdirSync(this.favPath)
  784. }
  785. if (!FileUtil.accessSync(this.historyPath)) {
  786. FileUtil.mkdirSync(this.historyPath)
  787. }
  788. this.getSortedFiles(this.rootPath).then(() => {
  789. this.isFavMusic = false
  790. //穿山甲
  791. // this.loadBannerAd(CSJUtil.getBannerID())
  792. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  793. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  794. if (ArrayUtil.isEmpty(this.songList)) {
  795. this.songList = this.getCurFileList()
  796. } else {
  797. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  798. }
  799. if (ArrayUtil.isNotEmpty(this.songList)) {
  800. this.isFirstStartPlay = true
  801. this.sonDataSource.pushArrayData(this.songList)
  802. if (this.currentSong === undefined) {
  803. this.isFirstStartPlay = false
  804. this.currentSong = this.songList[0]
  805. }
  806. this.videoUrl = this.currentSong.filePath
  807. this.name = this.currentSong.name
  808. this.cover = this.currentSong.pixelMapPath
  809. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  810. } else {
  811. this.name = '空空如也'
  812. }
  813. })
  814. this.getFavList(false)
  815. }
  816. getFavList(isFavRefresh: boolean) {
  817. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  818. this.favList = result
  819. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  820. this.videoLocalList = this.favList
  821. this.updateListData(this.videoLocalList)
  822. }
  823. })
  824. }
  825. getHistoryList(isRefresh: boolean) {
  826. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  827. this.historyList = result
  828. // for (let i = 0; i < this.historyList.length; i++) {
  829. //
  830. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  831. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  832. // }
  833. if (isRefresh) {
  834. this.videoLocalList = this.historyList
  835. this.updateListData(this.videoLocalList, true)
  836. }
  837. })
  838. }
  839. // 组件消失生命周期
  840. aboutToDisappear() {
  841. console.info('LifeCycleComponent aboutToDisappear');
  842. this.knockController?.immersiveDisableListening();
  843. this.curIndex = 0
  844. emitter.off(2);
  845. emitter.off(101);
  846. emitter.off(888);
  847. emitter.off(333);
  848. this.mDestroyPage = true;
  849. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  850. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  851. this.stop();
  852. }
  853. this.mIjkMediaPlayer.off('audioInterrupt');
  854. if (workerInstance) {
  855. workerInstance.terminate();
  856. }
  857. this.stopPip();
  858. this.destroyPipController()
  859. }
  860. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  861. this.isFavMusic = false
  862. console.info('onecold getSortedFiles 1 curPath '+curPath)
  863. if (isWorkerPost) {
  864. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  865. }
  866. if (this.modeType !== 0) {
  867. this.openMusic(isOpen, destPath)
  868. return
  869. }
  870. console.info('onecold getSortedFiles 2')
  871. this.isCanBack = false
  872. this.currentPath = curPath
  873. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  874. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  875. if (curPath === this.rootPath) {
  876. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  877. } else {
  878. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  879. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  880. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  881. }
  882. }
  883. // Get the current file list and calculate its hash
  884. this.fileList = FileUtil.listFileSync(curPath);
  885. const currentHash = simpleHash(this.fileList);
  886. // Check cache
  887. const cachedValue = this.findCache(curPath);
  888. Logger.info('onecold cachedValue = ' + cachedValue)
  889. const cachedHash = this.findStringCache(curPath + '_hash');
  890. const cachedDirList = this.findCache(curPath + "_dirList");
  891. if (cachedValue !== undefined) {
  892. // this.videoLocalList = cachedValue;
  893. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  894. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  895. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  896. }
  897. this.updateListData(cachedValue)
  898. }
  899. if (cachedDirList !== undefined) {
  900. this.dirList = cachedDirList
  901. }
  902. //通过当前hash值和缓存hash判断list有没有变化
  903. if (cachedValue && cachedHash === currentHash) {
  904. return;
  905. }
  906. this.fileList = FileUtil.listFileSync(curPath)
  907. let directories: Array<VideoItem> = [];
  908. let files: Array<VideoItem> = [];
  909. for (let i = 0; i < this.fileList.length; i++) {
  910. console.info(`The name of file: ${this.fileList[i]}`);
  911. let path = curPath + '/' + this.fileList[i]
  912. if (FileUtil.isDirectory(path)) {
  913. let item: VideoItem =
  914. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  915. '')
  916. if (this.isShowDir(item.name)) {
  917. directories.push(item);
  918. }
  919. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  920. // Utility.doSortListAscending(directories)
  921. } else {
  922. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  923. let item: VideoItem =
  924. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  925. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  926. files.push(item);
  927. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  928. // this.doSortListAscending(files)
  929. }
  930. }
  931. }
  932. }
  933. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  934. if (this.currentPath !== this.lockPath) {
  935. files = result;
  936. }
  937. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  938. Utility.doSortListAscending(files)
  939. if (this.currentPath === this.rootPath) {
  940. this.dirList = directories
  941. this.addCache(curPath + "_dirList", this.dirList);
  942. }
  943. //插入广告先注释掉
  944. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  945. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  946. // directories.push(adItem)
  947. // }
  948. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  949. this.videoLocalList = directories.concat(files);
  950. this.updateListData(this.videoLocalList)
  951. if (ArrayUtil.isNotEmpty(files)) {
  952. if (this.currentPath != this.rootPath) {
  953. if (files) {
  954. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  955. }
  956. }
  957. // 缓存结果
  958. this.addCache(curPath, this.videoLocalList);
  959. await this.saveCacheToStorage(); // 保存缓存至本地存储
  960. this.addStringCache(curPath + '_hash', currentHash);
  961. }
  962. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  963. // for (let i = 0; i < this.videoLocalList.length; i++) {
  964. //
  965. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  966. //
  967. // }
  968. // this.setButtonStatus()
  969. this.openMusic(isOpen, destPath)
  970. });
  971. }
  972. //第三方app打开天天静听导入音乐后播放
  973. openMusic(isOpen?: boolean, destPath?: string){
  974. if (isOpen&&destPath) {
  975. if (destPath === undefined) {
  976. // 处理 destPath 为 undefined 的情况
  977. return
  978. }
  979. if (destPath.endsWith('.lrc')) {
  980. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  981. if (StrUtil.isNotEmpty(this.videoUrl)) {
  982. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  983. this.initLyric(lyricPath);
  984. }
  985. return
  986. }
  987. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  988. this.doPlay(item2,0,false,true)
  989. this.isShowPlay = true
  990. }
  991. }
  992. //扫描文件夹入库
  993. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  994. const files = FileUtil.listFileSync(curPath);
  995. let mediaItems: VideoItem[] = [];
  996. Logger.info('onecold scanDirectory start ')
  997. for (const file of files) {
  998. const fPath = `${curPath}/${file}`;
  999. if (fPath === this.lockPath) {
  1000. Logger.info(`Skipping locked path: ${fPath}`);
  1001. continue;
  1002. }
  1003. if (FileUtil.isDirectory(fPath)) {
  1004. // Recursively scan subdirectories
  1005. const subDirItems = await this.scanDirectory(fPath);
  1006. mediaItems = mediaItems.concat(subDirItems);
  1007. } else {
  1008. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1009. // Process media files
  1010. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1011. let mediaItem: VideoItem =
  1012. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1013. mediaItems.push(mediaItem);
  1014. this.table.insert(mediaItem, (id: number) => {
  1015. });
  1016. }
  1017. }
  1018. }
  1019. return mediaItems;
  1020. }
  1021. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1022. animateTo({ duration: 888 }, () => {
  1023. this.opacityItem = 0;
  1024. });
  1025. setTimeout(() => {
  1026. this.videoLocalList = mList;
  1027. if (!noSort) {
  1028. if (this.modeType === 0 || this.modeType === 1) {
  1029. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1030. this.doSortType(this.sortType)
  1031. }
  1032. }
  1033. this.dataSource.pushArrayData(this.videoLocalList)
  1034. animateTo({ duration: 888 }, () => {
  1035. this.opacityItem = 1;
  1036. });
  1037. this.setButtonStatus()
  1038. }, 200);
  1039. }
  1040. //排序模式和多选模式
  1041. showPupDialog() {
  1042. if (this.modeType === 2 || this.modeType === 3) {
  1043. this.titleBarModel.setRightIcon(null)
  1044. } else {
  1045. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1046. }
  1047. let dataBean = new BubbleBean()
  1048. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1049. dataBean.color = this.themeColor
  1050. dataBean.modeType = this.modeType
  1051. dataBean.imageRes =
  1052. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1053. $r('app.media.refresh')]
  1054. let pup: XPopup;
  1055. if (this.isDarkMode) {
  1056. pup = XPopup.Builder()
  1057. .setPopupPosition(PopupPosition.BOTTOM)
  1058. .atView('pup_positon_music')
  1059. .setBackgroundColor(Color.Black)
  1060. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1061. .show()
  1062. } else {
  1063. pup = XPopup.Builder()
  1064. .setPopupPosition(PopupPosition.BOTTOM)
  1065. .atView('pup_positon_music')
  1066. .setBackgroundColor(Color.White)
  1067. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1068. .show()
  1069. }
  1070. dataBean.onItemClick = (i) => {
  1071. XPopup.dismissTop()
  1072. switch (i) {
  1073. case 0: //首页
  1074. this.modeType = 0
  1075. this.getSortedFiles(this.currentPath)
  1076. break
  1077. case 1:
  1078. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1079. this.modeType = 1
  1080. this.updateListData(this.mediaKuList)
  1081. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1082. break
  1083. case 2:
  1084. this.modeType = 2
  1085. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1086. this.updateListData(this.artistList)
  1087. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1088. break
  1089. case 3:
  1090. this.modeType = 3
  1091. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1092. this.updateListData(this.albumList)
  1093. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1094. break
  1095. case 4: //同步数据
  1096. this.asyncCurrentPathData()
  1097. break
  1098. }
  1099. }
  1100. }
  1101. getCurFileList(): Array<VideoItem> {
  1102. if(this.isSearchMode){
  1103. return this.filteredList
  1104. }
  1105. let files: Array<VideoItem> = [];
  1106. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1107. for (let i = 0; i < this.videoLocalList.length; i++) {
  1108. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1109. files.push(this.videoLocalList[i]);
  1110. }
  1111. }
  1112. }
  1113. return files
  1114. }
  1115. setButtonStatus() {
  1116. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1117. this.isZero = false
  1118. } else {
  1119. this.isZero = true
  1120. }
  1121. if (this.currentPath !== this.rootPath &&
  1122. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1123. this.isHasDir = true //不为空,说明有子文件夹
  1124. } else {
  1125. this.isHasDir = false
  1126. }
  1127. }
  1128. showRankDialog() {
  1129. if (this.modeType === 2 || this.modeType === 3) {
  1130. //动作面板
  1131. DialogHelper.showBottomSheetDialog({
  1132. title: "请选择排序模式",
  1133. maskColor: Color.Transparent,
  1134. // sheets: ["按名称升序", "按名称降序"],
  1135. sheets: [
  1136. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1137. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1138. ],
  1139. backgroundColor: $r('app.color.bg_card'),
  1140. height: '30%',
  1141. transition: AnimationHelper.transitionInDown(555),
  1142. onAction: (index) => {
  1143. switch (index) {
  1144. case 0:
  1145. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1146. break;
  1147. case 1:
  1148. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1149. break;
  1150. }
  1151. this.updateListData(this.videoLocalList)
  1152. }
  1153. })
  1154. return
  1155. }
  1156. //动作面板
  1157. DialogHelper.showBottomSheetDialog({
  1158. title: "请选择排序模式",
  1159. maskColor: Color.Transparent,
  1160. height: '75%',
  1161. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1162. sheets: [
  1163. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1164. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1165. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1166. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1167. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1168. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1169. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1170. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1171. ],
  1172. backgroundColor: $r('app.color.bg_card'),
  1173. transition: AnimationHelper.transitionInDown(555),
  1174. onAction: (index) => {
  1175. this.doSortType(index)
  1176. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1177. this.updateListData(this.videoLocalList, true)
  1178. }
  1179. })
  1180. }
  1181. doSortType(index: number) {
  1182. switch (index) {
  1183. case 0:
  1184. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1185. // 类型排序优先级
  1186. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1187. if (typeOrder !== 0) {
  1188. return typeOrder;
  1189. }
  1190. // 处理艺术家可能为undefined的字符串比较
  1191. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1192. const artistB = b.artist?.trim() || '';
  1193. return artistA.localeCompare(artistB);
  1194. });
  1195. break;
  1196. case 1:
  1197. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1198. // 类型排序优先级
  1199. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1200. if (typeOrder !== 0) {
  1201. return typeOrder;
  1202. }
  1203. // 处理艺术家可能为undefined的字符串比较
  1204. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1205. const artistB = b.artist?.trim() || '';
  1206. return artistB.localeCompare(artistA);
  1207. });
  1208. break;
  1209. case 2:
  1210. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1211. // 类型排序优先级
  1212. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1213. if (typeOrder !== 0) {
  1214. return typeOrder;
  1215. }
  1216. // 处理专辑可能为undefined的字符串比较
  1217. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1218. const albumB = b.album?.trim() || '';
  1219. return albumA.localeCompare(albumB);
  1220. });
  1221. break;
  1222. case 3:
  1223. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1224. // 类型排序优先级
  1225. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1226. if (typeOrder !== 0) {
  1227. return typeOrder;
  1228. }
  1229. // 处理专辑可能为undefined的字符串比较
  1230. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1231. const albumB = b.album?.trim() || '';
  1232. return albumB.localeCompare(albumA);
  1233. });
  1234. break;
  1235. case 4:
  1236. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1237. break;
  1238. case 5:
  1239. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1240. break;
  1241. case 6:
  1242. this.videoLocalList.sort((a, b) => {
  1243. // First, sort by type
  1244. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1245. if (typeOrder !== 0) {
  1246. return typeOrder;
  1247. }
  1248. // If types are the same, sort by cTime in ascending order
  1249. return a.cTime.localeCompare(b.cTime);
  1250. });
  1251. break;
  1252. case 7:
  1253. this.videoLocalList.sort((a, b) => {
  1254. // First, sort by type
  1255. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1256. if (typeOrder !== 0) {
  1257. return typeOrder;
  1258. }
  1259. // If types are the same, sort by cTime in descending order
  1260. return b.cTime.localeCompare(a.cTime);
  1261. });
  1262. break;
  1263. }
  1264. }
  1265. showSheelDialog() {
  1266. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1267. // this.showTips()
  1268. // return
  1269. // }
  1270. this.showAddDialog()
  1271. }
  1272. showAddDialog() {
  1273. if (this.modeType === 2 || this.modeType === 3) {
  1274. return
  1275. }
  1276. DialogHelper.showActionSheetDialog({
  1277. title: "请选择添加方式(建议歌词文件一起导入)",
  1278. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1279. sheets: [
  1280. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1281. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1282. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1283. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1284. ],
  1285. maskColor: Color.Transparent,
  1286. backgroundColor: $r('app.color.bg_card'),
  1287. transition: AnimationHelper.transitionInDown(555),
  1288. onAction: (index) => {
  1289. switch (index) {
  1290. case 0:
  1291. if (this.modeType === 0) {
  1292. this.showMkDialog()
  1293. } else {
  1294. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1295. }
  1296. break;
  1297. case 1:
  1298. this.callFilePickerSelectFile()
  1299. break;
  1300. case 2:
  1301. this.showTips()
  1302. break;
  1303. case 3:
  1304. this.goSelectMusic()
  1305. break;
  1306. }
  1307. }
  1308. })
  1309. }
  1310. //拉起音频
  1311. goSelectMusic() {
  1312. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1313. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1314. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1315. ) {
  1316. ToastUtil.showToast('暂时不支持该设备')
  1317. return
  1318. }
  1319. try {
  1320. let documentSelectOptions = new picker.DocumentSelectOptions();
  1321. documentSelectOptions.authMode = true
  1322. documentSelectOptions.multiAuthMode = true
  1323. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1324. let documentPicker = new picker.DocumentViewPicker(this.context);
  1325. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1326. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1327. this.saveVideoDatas(documentSelectResult)
  1328. }
  1329. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1330. JSON.stringify(documentSelectResult));
  1331. }).catch((err: BusinessError) => {
  1332. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1333. });
  1334. } catch (error) {
  1335. let err: BusinessError = error as BusinessError;
  1336. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1337. }
  1338. }
  1339. async showTips() {
  1340. DialogHelper.showTipsDialog({
  1341. title: '使用提示:自动导入教程',
  1342. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1343. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1344. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1345. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1346. onAction: (action) => {
  1347. if (action == DialogAction.TWO) {
  1348. PreferencesUtil.putSync('isFirstMusic', false)
  1349. router.pushUrl({
  1350. url: 'pages/ScanFilePage'
  1351. });
  1352. }
  1353. }
  1354. })
  1355. }
  1356. showMkDialog() {
  1357. DialogHelper.showTextInputDialog({
  1358. title: '新建歌单',
  1359. maskColor: Color.Transparent,
  1360. text: '',
  1361. transition: AnimationHelper.transitionInDown(666),
  1362. onChange: (text) => {
  1363. console.error("onChange: " + text);
  1364. },
  1365. onAction: (action, dialogId, content) => {
  1366. // ToastUtil.showToast('content = ' +content)
  1367. if (action == DialogAction.TWO) {
  1368. const newName = content
  1369. const newPath = this.currentPath + '/' + newName
  1370. FileUtil.mkdir(newPath, true).then(() => {
  1371. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1372. this.getSortedFiles(this.currentPath)
  1373. }).catch((error: BusinessError) => {
  1374. console.error(error.message);
  1375. });
  1376. }
  1377. }
  1378. })
  1379. }
  1380. @State progress: number = 0;
  1381. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1382. if (ArrayUtil.isEmpty(uris)) {
  1383. return;
  1384. }
  1385. let newUris: string[] = [];
  1386. this.progress = 0
  1387. DialogHelper.showLoadingProgress({
  1388. progress: this.progress,
  1389. backCancel: false,
  1390. autoCancel: false,
  1391. loadColor: this.themeColor,
  1392. fontColor: this.themeColor
  1393. });
  1394. // 计算所有文件的总大小
  1395. let totalSize = 0;
  1396. for (let uri of uris) {
  1397. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1398. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1399. await fileIo.close(sourceFile.fd);
  1400. }
  1401. let totalRead = 0;
  1402. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1403. Logger.info(TAG, 'destPath uri: ' + destPath);
  1404. for (let i = 0; i < uris.length; i++) {
  1405. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1406. Logger.info(TAG, 'filePath uri: ' + filePath);
  1407. newUris.push(filePath);
  1408. try {
  1409. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1410. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1411. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1412. const buffer = new ArrayBuffer(buffSize);
  1413. let len = await fileIo.read(sourceFile.fd, buffer);
  1414. while (len > 0) {
  1415. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1416. totalRead += len;
  1417. // 计算总进度
  1418. this.progress = Math.floor((totalRead / totalSize) * 100);
  1419. DialogHelper.updateLoading('正在导入', this.progress);
  1420. len = await fileIo.read(sourceFile.fd, buffer);
  1421. }
  1422. await fileIo.close(sourceFile.fd);
  1423. await fileIo.close(destFile.fd);
  1424. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1425. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1426. let mediaItem: VideoItem =
  1427. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1428. this.table.insert(mediaItem, (id: number) => {
  1429. // 删除目标路径缓存
  1430. this.cache.delete(this.currentPath);
  1431. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1432. });
  1433. }
  1434. }
  1435. } catch (error) {
  1436. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1437. }
  1438. }
  1439. DialogHelper.closeLoading()
  1440. this.isZero = false
  1441. // setTimeout(() => {
  1442. // // 删除目标路径缓存
  1443. // this.cache.delete(this.currentPath);
  1444. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1445. // }, 500);
  1446. Logger.info(TAG, 'scan select video result:' + newUris)
  1447. }
  1448. //拉起音频
  1449. // goSelectMusic(){
  1450. //
  1451. // try {
  1452. // let audioSelectOptions = new picker.AudioSelectOptions();
  1453. // let audioPicker = new picker.AudioViewPicker(this.context);
  1454. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1455. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1456. // this.saveVideoDatas(audioSelectResult)
  1457. // }
  1458. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1459. // }).catch((err: BusinessError) => {
  1460. //
  1461. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1462. // });
  1463. // } catch (error) {
  1464. // let err: BusinessError = error as BusinessError;
  1465. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1466. // }
  1467. //
  1468. //
  1469. //
  1470. // }
  1471. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1472. if (!item) {
  1473. return undefined;
  1474. }
  1475. try {
  1476. let selectUris: Array<string> = [];
  1477. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1478. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1479. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1480. photoSelectOptions.maxSelectNumber = 1;
  1481. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1482. selectUris = photoSelectResult.photoUris;
  1483. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1484. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1485. console.info('file fd: ' + file.fd);
  1486. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1487. let imagePath = this.context.filesDir + FileUtil.separator + name
  1488. imagePath = fileUri.getUriFromPath(imagePath)
  1489. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1490. fileIo.copyFileSync(file.fd, file2.fd)
  1491. fileIo.closeSync(file);
  1492. fileIo.closeSync(file2);
  1493. if (item.filePath == this.currentSong?.filePath) {
  1494. this.cover = imagePath
  1495. }
  1496. if (item) {
  1497. item.pixelMapPath = imagePath
  1498. }
  1499. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1500. if (success) {
  1501. this.doUpdateData()
  1502. console.log("onecold 更新音乐封面成功,数据库已同步");
  1503. } else {
  1504. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1505. }
  1506. });
  1507. LogUtil.debug("onecold this.cover =" + this.cover)
  1508. return FileUtil.getFilePath(imagePath); // Return the image path here
  1509. } catch (err) {
  1510. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1511. return undefined;
  1512. }
  1513. }
  1514. // 拉起picker选择文件管理器
  1515. async callFilePickerSelectFile(): Promise<void> {
  1516. try {
  1517. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1518. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1519. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1520. } else {
  1521. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1522. }
  1523. let documentPicker = new picker.DocumentViewPicker();
  1524. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1525. Logger.info(TAG,
  1526. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1527. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1528. this.saveVideoDatas(DocumentSelectResult)
  1529. }
  1530. }).catch((err: BusinessError) => {
  1531. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1532. });
  1533. } catch (err) {
  1534. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1535. }
  1536. }
  1537. //重命名的对话框
  1538. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1539. DialogHelper.showTextInputDialog({
  1540. title: '重命名',
  1541. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1542. maskColor: Color.Transparent,
  1543. backgroundColor: Color.Grey,
  1544. transition: AnimationHelper.transitionInDown(666),
  1545. onChange: (text) => {
  1546. console.error("onChange: " + text);
  1547. },
  1548. onAction: (action, dialogId, content) => {
  1549. // ToastUtil.showToast('content = ' +content)
  1550. if (action == DialogAction.TWO) {
  1551. const newName = content
  1552. const newPath = this.currentPath + '/' + newName
  1553. console.log("onecold item = " + item.type);
  1554. this.doReName(index, newName, filePath, newPath, item)
  1555. }
  1556. }
  1557. })
  1558. }
  1559. //剪切 移动到另个文件夹的对话框
  1560. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1561. Logger.info('onecold showCutDialog')
  1562. let mList: Array<string> = []
  1563. let rPath = this.rootPath
  1564. if (isCurrent) {
  1565. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1566. rPath = this.currentPath
  1567. } else {
  1568. mList = Utility.getNameList(this.dirList);
  1569. rPath = this.rootPath
  1570. }
  1571. let dataBean = new BubbleBean()
  1572. dataBean.data = mList
  1573. dataBean.color = this.themeColor
  1574. dataBean.onItemClick = (i) => {
  1575. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1576. Logger.info('newPath = ' + newPath)
  1577. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1578. ToastUtil.showToast('移动成功')
  1579. this.table.deleteData(item, () => {
  1580. });
  1581. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1582. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1583. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1584. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1585. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1586. this.table.insert(newItem, (id: number) => {
  1587. //加入数据库
  1588. });
  1589. }
  1590. this.cache.delete(this.currentPath); // 删除原路径缓存
  1591. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1592. this.getSortedFiles(this.currentPath, true)
  1593. }).catch((error: BusinessError) => {
  1594. console.error(error.message);
  1595. });
  1596. XPopup.dismissTop()
  1597. }
  1598. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1599. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1600. popupPosition = PopupPosition.TOP
  1601. }
  1602. if (index <= 3) {
  1603. popupPosition = PopupPosition.BOTTOM
  1604. }
  1605. let pup: XPopup
  1606. if (this.isDarkMode) {
  1607. pup = XPopup.Builder()
  1608. .setPopupPosition(popupPosition)
  1609. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1610. .setBackgroundColor(Color.Black)
  1611. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1612. .show()
  1613. } else {
  1614. pup = XPopup.Builder()
  1615. .setPopupPosition(popupPosition)
  1616. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1617. .setBackgroundColor(Color.White)
  1618. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1619. .show()
  1620. }
  1621. }
  1622. //复制 到另个文件夹的对话框
  1623. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1624. Logger.info('onecoldv showCopyDialog')
  1625. let mList: Array<string> = []
  1626. let rPath = this.rootPath
  1627. if (isCurrent) {
  1628. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1629. rPath = this.currentPath
  1630. } else {
  1631. mList = Utility.getNameList(this.dirList);
  1632. rPath = this.rootPath
  1633. }
  1634. let dataBean = new BubbleBean()
  1635. dataBean.data = mList
  1636. dataBean.isCopy = true
  1637. dataBean.color = this.themeColor
  1638. dataBean.onItemClick = (i) => {
  1639. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1640. Logger.info('newPath = ' + newPath)
  1641. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1642. ToastUtil.showToast('复制成功')
  1643. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1644. this.getSortedFiles(this.currentPath)
  1645. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1646. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1647. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1648. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1649. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1650. this.table.insert(newItem, (id: number) => {
  1651. //加入数据库
  1652. });
  1653. }
  1654. }).catch((error: BusinessError) => {
  1655. console.error(error.message);
  1656. });
  1657. XPopup.dismissTop()
  1658. }
  1659. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1660. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1661. popupPosition = PopupPosition.TOP
  1662. }
  1663. if (index <= 3) {
  1664. popupPosition = PopupPosition.BOTTOM
  1665. }
  1666. let pup: XPopup
  1667. if (this.isDarkMode) {
  1668. pup = XPopup.Builder()
  1669. .setPopupPosition(popupPosition)
  1670. .atView(id)
  1671. .setMaxHeight('60%')
  1672. .setBackgroundColor(Color.Black)
  1673. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1674. .show();
  1675. } else {
  1676. pup = XPopup.Builder()
  1677. .setPopupPosition(popupPosition)
  1678. .atView(id)
  1679. .setMaxHeight('60%')
  1680. .setBackgroundColor(Color.White)
  1681. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1682. .show();
  1683. }
  1684. }
  1685. //重命名索引index的视频
  1686. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1687. FileUtil.rename(oldPath, newPath).then(async () => {
  1688. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1689. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1690. //如果是文件夹先删除源数据,再添加新数据
  1691. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1692. if (success) {
  1693. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1694. } else {
  1695. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1696. }
  1697. });
  1698. this.scanDirectory(newPath)
  1699. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1700. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1701. if (success) {
  1702. console.log(" onecold 重命名成功,数据库已同步");
  1703. } else {
  1704. console.error(" onecold 重命名数据库失败原因: " + error);
  1705. }
  1706. });
  1707. }
  1708. let mediaItem: VideoItem =
  1709. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1710. this.videoLocalList[index] = mediaItem;
  1711. }
  1712. this.cache.delete(this.currentPath)
  1713. this.getSortedFiles(this.currentPath, true)
  1714. }).catch((error: BusinessError) => {
  1715. console.error(error.message);
  1716. });
  1717. }
  1718. build() {
  1719. Scroll() {
  1720. Column() {
  1721. if (!this.isShowCoverHeader()) {
  1722. Column() {
  1723. Line().width('100%').height('100%')
  1724. }
  1725. .height(this.topRectHeight)
  1726. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1727. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1728. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1729. TitleBar({ model: $titleBarModel })
  1730. .id('pup_positon_music')
  1731. }
  1732. Stack() {
  1733. Column() {
  1734. XComponent({
  1735. id: 'xcomponentId',
  1736. type: 'surface',
  1737. libraryname: 'ijkplayer_napi',
  1738. controller: this.xcomponentController
  1739. })
  1740. .onLoad((event?: object) => {
  1741. if (!!event) {
  1742. this.initDelayPlay(event);
  1743. }
  1744. })
  1745. .onKeyEvent((event?: KeyEvent) => {
  1746. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1747. if (!event || event.type !== KeyType.Down) {
  1748. return;
  1749. }
  1750. //空格键 Space key controls pause/play
  1751. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1752. console.info('onecold playOrPause 1999')
  1753. this.playOrPause()
  1754. }
  1755. // Right-click to fast forward
  1756. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1757. this.sessionFastForwardCallback(15);
  1758. }
  1759. // Left-click to rewind
  1760. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1761. this.sessionRewindCallback(15);
  1762. }
  1763. })
  1764. .onDestroy(() => {
  1765. })
  1766. .width('100%')// .width(this.videoWidth)
  1767. .aspectRatio(this.videoAspectRatio)
  1768. }
  1769. .aspectRatio(this.videoAspectRatio)
  1770. .justifyContent(FlexAlign.Center)
  1771. .backgroundColor(Color.Transparent)
  1772. .visibility(Visibility.Hidden)
  1773. .height(CommonConstants.FULL_PERCENT)
  1774. .width(CommonConstants.FULL_PERCENT)
  1775. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  1776. height:this.isLandscape?'80%': '43%',
  1777. dragBar: true,
  1778. showClose: true,
  1779. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  1780. blurStyle:BlurStyle.Thin,
  1781. backgroundColor:Color.Transparent,
  1782. title: { title: 'AB循环' }
  1783. })
  1784. Stack() {
  1785. Row() {
  1786. Blank()
  1787. .layoutWeight(1)
  1788. IndexerView(
  1789. {
  1790. indexArray: DEFAULT_INDEX,
  1791. selectedIndex: this.selectedIndex,
  1792. textSize: 12,
  1793. selectedColor: "#ff419ee5",
  1794. normalColor: "#ffa0a0a0",
  1795. floatSelectedTextColor: "#ffffff",
  1796. floatSelectedViewColor: "#ff419ee5",
  1797. onIndexChanged: (index) => {
  1798. this.listScroller.scrollToIndex(index)
  1799. }
  1800. })
  1801. .width(24)
  1802. .height("50%")
  1803. }.visibility(Visibility.None)
  1804. Column() {
  1805. if (!this.isShowCoverHeader()) {
  1806. this.tabTitle()
  1807. }
  1808. if(this.twoFingerType==4){
  1809. this.getWaterView()
  1810. }else{
  1811. if(this.isGridMusic){
  1812. this.getGridView()
  1813. }else {
  1814. this.getListView()
  1815. }
  1816. }
  1817. if (this.modeType == 0) {
  1818. Column() {
  1819. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1820. .width(130)
  1821. .height(50)
  1822. .margin({ top: 100, bottom: 40 })
  1823. .backgroundColor(this.themeColor)
  1824. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  1825. .onClick(() => {
  1826. this.asyncCurrentPathData()
  1827. })
  1828. }
  1829. .height(100)
  1830. .position({ top: 260 })
  1831. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  1832. .animation({ duration: 500 }),
  1833. TransitionEffect.scale({ x: 0, y: 0 })))
  1834. .justifyContent(FlexAlign.Center)
  1835. .opacity(this.isZero ? 1 : 0)
  1836. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  1837. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1838. .animation({
  1839. duration: 500,
  1840. curve: 'ease-in-out' // 可选动画曲线
  1841. })
  1842. .width('100%')
  1843. }
  1844. }
  1845. .layoutWeight(1)
  1846. .height('100%')
  1847. }
  1848. .layoutWeight(1)
  1849. .height('100%')
  1850. Row() {
  1851. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1852. .width(50)
  1853. .height(50)
  1854. .fontSize(13)
  1855. .margin({ top: 10, bottom: 10, right: 6 })
  1856. .backgroundColor(this.themeColor)
  1857. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1858. .onClick(() => {
  1859. if (this.isAllSelected) {
  1860. // 全不选
  1861. this.selectedFiles = [];
  1862. } else {
  1863. // 全选
  1864. this.selectedFiles = [...this.getCurFileList()];
  1865. }
  1866. this.isAllSelected = !this.isAllSelected;
  1867. })
  1868. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  1869. .width(90)
  1870. .height(50)
  1871. .fontSize(13)
  1872. .margin({ top: 10, bottom: 10, right: 6 })
  1873. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1874. .backgroundColor(this.themeColor)
  1875. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  1876. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  1877. })
  1878. .onClick(() => {
  1879. this.isOneKeyTags = !this.isOneKeyTags
  1880. })
  1881. Button('乱码修复', { type: ButtonType.Capsule, stateEffect: true })
  1882. .width(90)
  1883. .height(50)
  1884. .fontSize(13)
  1885. .margin({ top: 10, bottom: 10, right: 6 })
  1886. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1887. .backgroundColor(this.themeColor)
  1888. .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  1889. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  1890. })
  1891. .onClick(() => {
  1892. this.isFixMessy = !this.isFixMessy
  1893. })
  1894. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1895. // .width('35%')
  1896. // .height(60)
  1897. // .id('music_cut')
  1898. // .margin({ top: 10, bottom: 10, right: 6 })
  1899. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1900. // .backgroundColor(this.themeColor)
  1901. // .onClick(() => {
  1902. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  1903. // })
  1904. //
  1905. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1906. // .width('35%')
  1907. // .height(60)
  1908. // .id('music_cut_current')
  1909. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1910. // .margin({ top: 10, bottom: 10, right: 6 })
  1911. // .backgroundColor(this.themeColor)
  1912. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1913. // .onClick(() => {
  1914. //
  1915. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1916. // })
  1917. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1918. // .width('35%')
  1919. // .height(60)
  1920. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1921. // .margin({ top: 10, bottom: 10, right: 6 })
  1922. // .backgroundColor(this.themeColor)
  1923. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1924. // .onClick(() => {
  1925. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1926. // })
  1927. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1928. .width(50)
  1929. .height(50)
  1930. .fontSize(13)
  1931. .margin({ top: 10, bottom: 10, right: 6 })
  1932. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  1933. .backgroundColor(this.themeColor)
  1934. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1935. .onClick(() => {
  1936. this.showWarnIsDelete()
  1937. })
  1938. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1939. .width(50)
  1940. .height(50)
  1941. .fontSize(13)
  1942. .margin({ top: 10, bottom: 10, right: 6 })
  1943. .backgroundColor(this.themeColor)
  1944. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1945. .onClick(() => {
  1946. this.selectedFiles = [];
  1947. this.isAllSelected = false
  1948. this.isMultiSelect = false
  1949. })
  1950. }
  1951. .width('100%')
  1952. .justifyContent(FlexAlign.Center)
  1953. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1954. .opacity(this.isMultiSelect ? 1 : 0)
  1955. .animation({
  1956. duration: 666,
  1957. curve: 'ease-in-out' // 可选动画曲线
  1958. })
  1959. .position(this.isShowCoverHeader() ? { bottom: 78 }
  1960. : { bottom: this.isPhoneLan() ? 130 : 170 }) // 将 Row 固定在底部
  1961. }
  1962. .width('100%')
  1963. .height('100%')
  1964. .alignContent(Alignment.Top)
  1965. Column() {
  1966. this.PlayController()
  1967. }
  1968. .hitTestBehavior(HitTestMode.Transparent)
  1969. .position({ bottom: 0 }) // 将 Row 固定在底部
  1970. .opacity(this.barBottomOpacity)
  1971. }
  1972. .width('100%')
  1973. .height('100%')
  1974. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  1975. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  1976. .backgroundImagePosition(Alignment.Center)
  1977. .backdropBlur(this.blurValue)
  1978. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  1979. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1980. }
  1981. }
  1982. @Builder
  1983. TagsContentCoverBuilder() {
  1984. Scroll() {
  1985. Column() {
  1986. TagsContentCover(
  1987. {
  1988. selectedFiles:this.selectedFiles,
  1989. isShowDrawer:this.isOneKeyTags,
  1990. onTagsResult:(result: boolean)=>{
  1991. this.isMultiSelect = false
  1992. if(result){//如果嵌入成功,更新数据
  1993. this.doUpdateData()
  1994. }
  1995. }
  1996. }
  1997. )
  1998. }
  1999. }
  2000. .width('100%')
  2001. .height('100%')
  2002. }
  2003. @Builder
  2004. FixMessyViewBuilder() {
  2005. Scroll() {
  2006. Column() {
  2007. FixMessyView(
  2008. {
  2009. selectedFiles:this.selectedFiles,
  2010. isShowDrawer:this.isFixMessy,
  2011. onFixResult:(result: boolean)=>{
  2012. this.isMultiSelect = false
  2013. if(result){//如果嵌入成功,更新数据
  2014. this.doUpdateData()
  2015. }
  2016. }
  2017. }
  2018. )
  2019. }
  2020. }
  2021. .width('100%')
  2022. .height('100%')
  2023. }
  2024. asyncCurrentPathData() {
  2025. if (this.modeType == 0) {
  2026. workerInstance.postMessage({
  2027. code: 1,
  2028. data1: this.context,
  2029. data2: this.currentPath,
  2030. data3: this.lockPath,
  2031. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2032. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  2033. });
  2034. }
  2035. }
  2036. // 处理文件选择的函数
  2037. handleFileSelection(item: VideoItem, checked: boolean) {
  2038. if (checked) {
  2039. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2040. this.selectedFiles.push(item);
  2041. }
  2042. } else {
  2043. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2044. if (index > -1) {
  2045. this.selectedFiles.splice(index, 1);
  2046. }
  2047. }
  2048. }
  2049. private deleteComponentId: number = 0
  2050. //多选删除文件
  2051. showWarnIsDelete(){
  2052. this.getUIContext().getPromptAction().openCustomDialog({
  2053. builder: () => {
  2054. this.deleteComptentBuilder()
  2055. },
  2056. isModal:true,
  2057. showInSubWindow:false,
  2058. maskColor: Color.Transparent,
  2059. dialogTransition: // 设置弹窗内容显示的过渡效果
  2060. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  2061. .animation({ duration: 600, curve: Curve.Smooth }),
  2062. maskTransition: // 设置蒙层显示的过渡效果
  2063. TransitionEffect.opacity(0)
  2064. .animation({ duration: 600, curve: Curve.Smooth })
  2065. }).then((dialogId: number) => {
  2066. this.deleteComponentId = dialogId
  2067. })
  2068. .catch((error: BusinessError) => {
  2069. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  2070. })
  2071. }
  2072. @Builder
  2073. deleteComptentBuilder(){
  2074. DeleteComptent({
  2075. selectedFiles:this.selectedFiles,
  2076. onCancel:()=>{
  2077. this.isMultiSelect = false
  2078. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2079. },
  2080. onDeleteResult:(result: boolean)=>{
  2081. this.isMultiSelect = false
  2082. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2083. if(result){//如果删除成功,更新数据
  2084. this.selectedFiles = [];
  2085. this.isAllSelected = false
  2086. this.cache.delete(this.currentPath);
  2087. this.getSortedFiles(this.currentPath, true);
  2088. }
  2089. }
  2090. })
  2091. }
  2092. //多选移动文件
  2093. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2094. Logger.info('onecold showCutDialogForMultipleFiles')
  2095. let mList: Array<string> = []
  2096. let rPath = this.rootPath
  2097. if (isCurrent) {
  2098. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2099. rPath = this.currentPath
  2100. } else {
  2101. mList = Utility.getNameList(this.dirList);
  2102. rPath = this.rootPath
  2103. }
  2104. let dataBean = new BubbleBean();
  2105. dataBean.data = mList;
  2106. dataBean.color = this.themeColor
  2107. dataBean.onItemClick = (i) => {
  2108. const newDirPath = rPath + '/' + mList[i];
  2109. // Logger.info('newDirPath = ' + newDirPath)
  2110. this.selectedFiles.forEach((item) => {
  2111. const newPath = newDirPath + '/' + item.fileName;
  2112. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2113. ToastUtil.showToast('移动成功');
  2114. this.table.deleteData(item, () => {
  2115. this.cache.delete(this.currentPath); // 删除原路径缓存
  2116. this.cache.delete(newDirPath); // 删除目标路径缓存
  2117. this.getSortedFiles(this.currentPath, true);
  2118. });
  2119. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2120. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2121. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2122. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2123. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2124. this.table.insert(newItem, (id: number) => {
  2125. //加入数据库
  2126. });
  2127. }
  2128. }).catch((error: Error) => {
  2129. console.error(error.message);
  2130. });
  2131. });
  2132. this.isMultiSelect = false
  2133. this.selectedFiles = [];
  2134. this.isAllSelected = false
  2135. XPopup.dismissTop();
  2136. };
  2137. let pup: XPopup
  2138. if (this.isDarkMode) {
  2139. pup = XPopup.Builder()
  2140. .setPopupPosition(PopupPosition.TOP)
  2141. .atView(viewId)
  2142. .setBackgroundColor(Color.Black)
  2143. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2144. .show();
  2145. } else {
  2146. pup = XPopup.Builder()
  2147. .setPopupPosition(PopupPosition.TOP)
  2148. .atView(viewId)
  2149. .setBackgroundColor(Color.White)
  2150. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2151. .show();
  2152. }
  2153. }
  2154. doFav(item: VideoItem) {
  2155. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2156. let isFav = 0
  2157. if (Utility.getIsFav(this.favList, item)) {
  2158. isFav = 0
  2159. } else {
  2160. isFav = 1
  2161. }
  2162. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2163. if (result) {
  2164. if (isFav === 1) {
  2165. ToastUtil.showToast('收藏成功');
  2166. } else {
  2167. ToastUtil.showToast('取消收藏成功');
  2168. }
  2169. this.deleteCache(this.currentPath)
  2170. this.getFavList(false)
  2171. if (this.modeType === 0 && !this.isFavMusic) {
  2172. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2173. this.getSortedFiles(this.currentPath)
  2174. }
  2175. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2176. workerInstance.postMessage({ code: 3, data: this.context });
  2177. workerInstance.postMessage({ code: 4, data: this.context });
  2178. }
  2179. })
  2180. }
  2181. //多选复制文件
  2182. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2183. console.log('onecold showCopyDialogForMultipleFiles');
  2184. let mList: Array<string> = []
  2185. let rPath = this.rootPath
  2186. if (isCurrent) {
  2187. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2188. rPath = this.currentPath
  2189. } else {
  2190. mList = Utility.getNameList(this.dirList);
  2191. rPath = this.rootPath
  2192. }
  2193. let dataBean = new BubbleBean();
  2194. dataBean.data = mList;
  2195. dataBean.isCopy = true
  2196. dataBean.color = this.themeColor
  2197. dataBean.onItemClick = (i) => {
  2198. const newDirPath = rPath + '/' + mList[i];
  2199. // Logger.info('newDirPath = ' + newDirPath)
  2200. this.selectedFiles.forEach((item) => {
  2201. const newPath = newDirPath + '/' + item.fileName;
  2202. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2203. ToastUtil.showToast('复制成功');
  2204. this.cache.delete(newDirPath); // 删除目标路径缓存
  2205. this.getSortedFiles(this.currentPath);
  2206. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2207. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2208. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2209. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2210. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2211. this.table.insert(newItem, (id: number) => {
  2212. //加入数据库
  2213. });
  2214. }
  2215. }).catch((error: Error) => {
  2216. console.error(error.message);
  2217. });
  2218. });
  2219. this.isMultiSelect = false
  2220. this.selectedFiles = [];
  2221. this.isAllSelected = false
  2222. XPopup.dismissTop();
  2223. };
  2224. let pup: XPopup
  2225. if (this.isDarkMode) {
  2226. pup = XPopup.Builder()
  2227. .setPopupPosition(PopupPosition.TOP)
  2228. .atView(viewId)
  2229. .setBackgroundColor(Color.Black)
  2230. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2231. .show();
  2232. } else {
  2233. pup = XPopup.Builder()
  2234. .setPopupPosition(PopupPosition.TOP)
  2235. .atView(viewId)
  2236. .setBackgroundColor(Color.White)
  2237. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2238. .show();
  2239. }
  2240. }
  2241. @Builder
  2242. private DirItem(item: VideoItem, index?: number) {
  2243. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2244. Row() {
  2245. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2246. $r('app.media.music_group'))
  2247. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2248. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2249. .fillColor(this.themeColor)// .fontSize(33)
  2250. .alt($r('app.media.music_group'))
  2251. .borderRadius('100%')
  2252. .clip(true)
  2253. .margin({ left: 20, top: 8, bottom: 8 })
  2254. Column() {
  2255. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2256. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2257. .maxLines(1)// .width('88%')
  2258. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2259. .animation({
  2260. duration: 555,
  2261. curve: 'ease-in-out',
  2262. })
  2263. .transition({
  2264. type: TransitionType.Insert,
  2265. opacity: 0,
  2266. translate: { x: 160 }
  2267. })
  2268. .margin({ left: 10, right: 20 })
  2269. .fontColor($r('app.color.text_color'))
  2270. Row() {
  2271. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2272. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2273. .padding({ top: 8 })
  2274. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2275. .fontColor($r('app.color.text_color'))
  2276. .margin({ left: 10 })
  2277. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2278. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2279. .padding({ top: 8 })
  2280. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2281. .fontColor($r('app.color.text_color'))
  2282. .margin({ left: 10 })
  2283. Blank()
  2284. }
  2285. }
  2286. .height('100%')
  2287. .layoutWeight(1)
  2288. .justifyContent(FlexAlign.Center)
  2289. .alignItems(HorizontalAlign.Start)
  2290. Blank()
  2291. Image($r('app.media.arrow_right'))
  2292. .height(25)
  2293. .margin({ right: 10 })
  2294. .alignSelf(ItemAlign.Center)
  2295. .id(item.filePath)
  2296. }
  2297. }
  2298. .backgroundColor(Color.Transparent)
  2299. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2300. .width('100%')
  2301. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2302. .opacity(this.opacityItem) // 绑定透明度
  2303. }
  2304. isShowDir(dirName: string) {
  2305. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2306. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2307. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2308. if (dirName === undefined) {
  2309. return true
  2310. }
  2311. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2312. return this.isShowSimi
  2313. }
  2314. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2315. return this.isShowFAV
  2316. }
  2317. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2318. return this.isShowHistory
  2319. }
  2320. return true
  2321. }
  2322. @State opacityItem: number = 1; // 控制透明度的状态变量
  2323. @Builder
  2324. private MusicItem(item: VideoItem, index?: number) {
  2325. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2326. Row() {
  2327. Stack() {
  2328. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2329. .fillColor(this.themeColor)
  2330. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2331. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2332. .alt($r('app.media.music_red'))
  2333. .borderRadius('100%')
  2334. .clip(true)
  2335. .draggable(false)
  2336. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2337. .autoResize(true) // 重采样,可减少内存占用
  2338. .opacity(this.opacityItem)// 绑定透明度
  2339. .margin({ left: 20 })
  2340. .gesture(LongPressGesture()
  2341. .onAction(async () => {
  2342. //如果是专辑和艺术家的首页,不能长按
  2343. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2344. return
  2345. //如果是我的收藏 最近播放等也不能长按
  2346. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2347. item.name === LocalMusic.STR_HISTORY_MUSIC
  2348. )
  2349. return
  2350. this.longItemFilePath = item.filePath
  2351. this.tempLyricContent = await this.getLyricContent(item)
  2352. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2353. })
  2354. .onActionEnd((event: GestureEvent) => {
  2355. }))
  2356. }
  2357. Column() {
  2358. Column() {
  2359. Text(this.isShowFileName?item.fileName :item.name)
  2360. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2361. .maxLines(1)
  2362. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2363. .animation({
  2364. duration: 555,
  2365. curve: 'Linear',
  2366. })
  2367. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2368. $r('app.color.text_color'))
  2369. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2370. .padding({right:25})
  2371. .bindPopup(this.longItemFilePath === item.filePath, {
  2372. builder: this.MenuBuilder(item,index,item.filePath),
  2373. placement: Placement.Top,
  2374. // autoCancel: true,
  2375. mask: {color:'#33000000'},
  2376. // popupColor: Color.Yellow,
  2377. enableArrow: false,//是否显示箭头
  2378. showInSubWindow: false,
  2379. onStateChange: (e) => {
  2380. if (!e.isVisible) {
  2381. this.longItemFilePath = ''
  2382. this.tempLyricContent = ''
  2383. }
  2384. }
  2385. })
  2386. .gesture(LongPressGesture()
  2387. .onAction(async () => {
  2388. //如果是专辑和艺术家的首页,不能长按
  2389. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2390. return
  2391. //如果是我的收藏 最近播放等也不能长按
  2392. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2393. item.name === LocalMusic.STR_HISTORY_MUSIC
  2394. )
  2395. return
  2396. this.longItemFilePath = item.filePath
  2397. this.tempLyricContent = await this.getLyricContent(item)
  2398. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2399. })
  2400. .onActionEnd((event: GestureEvent) => {
  2401. })
  2402. )
  2403. Row() {
  2404. Column(){
  2405. Text(item.md5Str?.includes('Lossless')?
  2406. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2407. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2408. .padding({ top: 3,right:6,left:6,bottom:3 })
  2409. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2410. $r('app.color.text_color'))
  2411. .fontWeight(500)
  2412. .borderRadius(12)
  2413. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2414. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2415. .backgroundColor('#FFC107')
  2416. }
  2417. .padding({ top: 8 })
  2418. Text(StrUtil.isEmpty(item.artist) ? item.duration : item.artist + ' ' + item?.album)
  2419. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2420. .padding({ top: 8 ,right:25})
  2421. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  2422. .maxLines(1)
  2423. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2424. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2425. $r('app.color.text_color'))
  2426. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2427. Blank()
  2428. Text(this.isShowFileName?item.duration:item.size)
  2429. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2430. .padding({ top: 8 })
  2431. .maxLines(1)
  2432. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  2433. ? Visibility.Visible : Visibility.None)
  2434. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2435. $r('app.color.text_color'))
  2436. .margin({ left: 10 })
  2437. }
  2438. .visibility(this.twoFingerType==1?Visibility.None:Visibility.Visible)
  2439. .gesture(LongPressGesture()
  2440. .onAction(async () => {
  2441. //如果是专辑和艺术家的首页,不能长按
  2442. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2443. return
  2444. //如果是我的收藏 最近播放等也不能长按
  2445. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2446. item.name === LocalMusic.STR_HISTORY_MUSIC
  2447. )
  2448. return
  2449. this.longItemFilePath = item.filePath
  2450. this.tempLyricContent = await this.getLyricContent(item)
  2451. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2452. })
  2453. .onActionEnd((event: GestureEvent) => {
  2454. })
  2455. )
  2456. }
  2457. .height('100%')
  2458. .width('100%')
  2459. .justifyContent(FlexAlign.Center)
  2460. .alignItems(HorizontalAlign.Start)
  2461. }
  2462. .height('100%')
  2463. .margin({ left: 5 })
  2464. .layoutWeight(1)
  2465. Column() {
  2466. Checkbox({ name: 'checkbox' + index })
  2467. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2468. .selectedColor(this.themeColor)
  2469. .shape(CheckBoxShape.CIRCLE)
  2470. .opacity(this.isMultiSelect ? 1 : 0)
  2471. .animation({
  2472. duration: 666,
  2473. curve: 'Smooth' // 可选动画曲线
  2474. })
  2475. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2476. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2477. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  2478. .width(22)
  2479. .height(22)
  2480. ImageAnimator()
  2481. .images(this.imagesF)// 动画数组
  2482. .duration(1000)// 持续
  2483. .state(this.animationState)// 动画状态
  2484. .fillMode(FillMode.Forwards)
  2485. .width(18)
  2486. .margin({ right: 20, top: 8, bottom: 8 })
  2487. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2488. Visibility.None)
  2489. .height(18)
  2490. .iterations(-1) // 播放次数
  2491. }
  2492. }
  2493. }
  2494. .backgroundColor(Color.Transparent)
  2495. .width('100%')
  2496. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2497. }
  2498. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2499. @Builder
  2500. tabTitle() {
  2501. Column() {
  2502. // 使用 Stack 布局来实现绝对定位效果
  2503. Stack() {
  2504. // 背景动画容器
  2505. Row() {
  2506. ForEach(this.tabs, (i: string, index) => {
  2507. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2508. Flex()
  2509. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2510. .borderRadius(20)
  2511. .padding(10)
  2512. .margin(6)
  2513. .width('100%')
  2514. .height('100%')
  2515. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2516. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2517. .opacity(this.modeType === index ? 1 : 0)
  2518. .animation({
  2519. duration: 666,
  2520. playMode: PlayMode.Normal,
  2521. curve: 'ease-in-out'
  2522. });
  2523. }
  2524. .layoutWeight(1)
  2525. .margin({
  2526. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2527. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2528. });
  2529. });
  2530. }
  2531. .width('100%')
  2532. .height(50);
  2533. // 导航栏容器
  2534. Row() {
  2535. ForEach(this.tabs, (item: string, index) => {
  2536. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2537. Text(item)
  2538. .fontSize(16)
  2539. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2540. .padding(15)
  2541. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2542. .onClick(() => {
  2543. this.modeType = index;
  2544. // this.onModeChange();
  2545. });
  2546. }
  2547. .layoutWeight(1)
  2548. .stateStyles({
  2549. pressed: { opacity: 0.6 } // 按压反馈
  2550. });
  2551. });
  2552. }
  2553. .width('100%')
  2554. .height(this.topBarHeight)
  2555. .opacity(this.barOpacity)
  2556. .backgroundColor(Color.Transparent);
  2557. }
  2558. .width('100%')
  2559. .height(this.topBarHeight)
  2560. .opacity(this.barOpacity)
  2561. Line()
  2562. .width('100%')
  2563. .height(1)
  2564. .backgroundColor($r('app.color.index_background'))
  2565. .opacity(this.barOpacity)
  2566. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2567. }
  2568. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2569. }
  2570. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2571. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2572. isShowCoverHeader() {
  2573. if (!this.isShowHeader) {
  2574. return false
  2575. }
  2576. if (this.modeType == 0) {
  2577. if (this.isHistory || this.isFavMusic) {
  2578. return true
  2579. }
  2580. if (this.currentPath != this.rootPath) {
  2581. return true
  2582. }
  2583. }
  2584. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2585. }
  2586. @Builder
  2587. coverHeader() {
  2588. if (this.isShowCoverHeader()) {
  2589. Column() {
  2590. Stack() {
  2591. // 居中标题
  2592. Text('')
  2593. .fontSize(18)
  2594. .fontColor(Color.White)
  2595. .align(Alignment.Center)
  2596. // 左右按钮
  2597. Row() {
  2598. Image($r('app.media.left_back_white'))
  2599. .width(28)
  2600. .height(28)
  2601. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2602. .margin({ left: 12, right: 8 })
  2603. .onClick(() => {
  2604. animateTo({ duration: 555 }, () => {
  2605. this.doSwipBack()
  2606. })
  2607. })
  2608. Blank().flexGrow(1)
  2609. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2610. Image($r('app.media.add'))
  2611. .width(25)
  2612. .height(25)
  2613. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2614. .margin({ left: 8, right: 15 })
  2615. .onClick(() => {
  2616. this.showAddDialog()
  2617. })
  2618. }
  2619. }
  2620. .height(48)
  2621. .width('100%')
  2622. .alignItems(VerticalAlign.Center)
  2623. }
  2624. .height(48)
  2625. .width('100%')
  2626. Row() {
  2627. Column() {
  2628. Image(this.currentTitleCover)
  2629. .height(100)
  2630. .width(100)
  2631. .alt(this.imageLabel)
  2632. .borderRadius(8)
  2633. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2634. }
  2635. .alignItems(HorizontalAlign.Start)
  2636. .margin({ left: 30, top: 3, bottom: 15 })
  2637. Column() {
  2638. Column() {
  2639. Text(this.currentTitleName)
  2640. .fontSize(16)
  2641. .maxLines(1)
  2642. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2643. .fontWeight(FontWeight.Bold)
  2644. .fontColor($r('app.color.text_color'))
  2645. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2646. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2647. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2648. .fontSize(14)
  2649. .padding({ top: 8 })
  2650. .maxLines(1)
  2651. .fontWeight(FontWeight.Bold)
  2652. .fontColor($r('app.color.text_color'))
  2653. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2654. if(this.videoLocalList[0].genre){
  2655. Text(`风格:${this.videoLocalList[0].genre}`)
  2656. .fontSize(14)
  2657. .padding({ top: 8 })
  2658. .maxLines(1)
  2659. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2660. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2661. ?Visibility.None:Visibility.Visible)
  2662. .fontWeight(FontWeight.Bold)
  2663. .fontColor($r('app.color.text_color'))
  2664. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2665. }
  2666. if(this.videoLocalList[0].year){
  2667. Text(`发行时间:${this.videoLocalList[0].year}`)
  2668. .fontSize(14)
  2669. .padding({ top: 8 })
  2670. .maxLines(1)
  2671. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2672. this.videoLocalList[0].year.includes(this.UNKONWN)
  2673. ?Visibility.None:Visibility.Visible)
  2674. .fontWeight(FontWeight.Bold)
  2675. .fontColor($r('app.color.text_color'))
  2676. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2677. }
  2678. }
  2679. if(this.modeType != 3){
  2680. Row() {
  2681. Text(`共${this.videoLocalList.length}首歌`)
  2682. .fontSize(13)
  2683. .fontWeight(FontWeight.Bold)
  2684. .padding({ top: 8 })
  2685. .fontColor($r('app.color.text_color'))
  2686. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2687. Blank()
  2688. }
  2689. }
  2690. }
  2691. .height('100%')
  2692. .width('100%')
  2693. .justifyContent(FlexAlign.Center)
  2694. .alignItems(HorizontalAlign.Start)
  2695. }
  2696. .height('100%')
  2697. .layoutWeight(1)
  2698. .margin({ left: 20 })
  2699. }
  2700. this.listViewTitle()
  2701. }
  2702. .backgroundImage(this.getCoverTitleBg())
  2703. .height(250)
  2704. .width('100%')
  2705. .backgroundImageSize({ height: '100%', width: '100%' })
  2706. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2707. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2708. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2709. .justifyContent(FlexAlign.SpaceBetween)
  2710. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2711. TransitionEffect.scale({ x: 0, y: 0 })))
  2712. } else {
  2713. this.listViewTitle()
  2714. }
  2715. }
  2716. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2717. if (this.isCustomizeBg) {
  2718. return ('rgba(255,255,255,0.2)')
  2719. }
  2720. if (this.isDarkMode) {
  2721. return $r('app.color.user_center_card_background')
  2722. }
  2723. return this.currentTitleCover
  2724. }
  2725. @Builder
  2726. listViewTitle() {
  2727. Column() {
  2728. Row({ space: 8 }) {
  2729. Row({ space: 8 }) {
  2730. Image($r("app.media.hm_playlist"))
  2731. .width(25)
  2732. .margin({ left: 8 })
  2733. .fillColor(this.themeColor)
  2734. Text(`共找到${this.artistList.length}位艺术家`)
  2735. .fontColor($r('app.color.text_color'))
  2736. .fontSize(14)
  2737. .opacity(this.opacityItem)
  2738. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2739. Text(`共找到${this.albumList.length}张专辑`)
  2740. .fontColor($r('app.color.text_color'))
  2741. .opacity(this.opacityItem)
  2742. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2743. .fontSize(14)
  2744. }
  2745. .layoutWeight(1)
  2746. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2747. Row() {
  2748. TextInput({
  2749. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2750. text: this.searchText
  2751. })
  2752. .height(35)
  2753. .onChange((value: string) => {
  2754. this.onSearchInput(value);
  2755. })
  2756. .layoutWeight(1)
  2757. Text(`取消`)
  2758. .margin({ left: 10, right: 10 })
  2759. .fontColor($r('app.color.text_color'))
  2760. .fontSize(16)
  2761. .onClick(() => {
  2762. this.isSearchMode = false
  2763. this.searchText = ''
  2764. if (this.modeType === 2) {
  2765. this.updateListData(this.artistList)
  2766. } else {
  2767. this.updateListData(this.albumList)
  2768. }
  2769. })
  2770. }
  2771. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2772. .animation({
  2773. duration: 666,
  2774. curve: 'ease-in-out' // 可选动画曲线
  2775. })
  2776. Blank()
  2777. Image($r("app.media.search"))
  2778. .width(25)
  2779. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2780. .animation({
  2781. duration: 666,
  2782. curve: 'ease-in-out' // 可选动画曲线
  2783. })// .opacity(this.opacityItem)
  2784. .fillColor(this.themeColor)
  2785. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2786. .onClick(() => {
  2787. this.isSearchMode = true
  2788. })
  2789. Image($r("app.media.top_rank"))
  2790. .width(25)// .opacity(this.opacityItem)
  2791. .fillColor(this.themeColor)
  2792. .animation({
  2793. duration: 666,
  2794. curve: 'ease-in-out' // 可选动画曲线
  2795. })
  2796. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2797. .onClick(() => {
  2798. this.showRankDialog()
  2799. })
  2800. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2801. .width(25)
  2802. .animation({
  2803. duration: 666,
  2804. curve: 'ease-in-out' // 可选动画曲线
  2805. })
  2806. .fillColor(this.themeColor)
  2807. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2808. .onClick(() => {
  2809. this.isGridMusic = !this.isGridMusic
  2810. })
  2811. }
  2812. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2813. Visibility.None)
  2814. .width('100%')
  2815. .padding(10)
  2816. .height(50)
  2817. .border({
  2818. width: { bottom: 1 },
  2819. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2820. })
  2821. Row({ space: 8 }) {
  2822. Row({ space: 8 }) {
  2823. Image($r("app.media.hm_play"))
  2824. .width(25)
  2825. .margin({ left: 8 })
  2826. .fillColor(this.themeColor)
  2827. Text(`播放全部`)
  2828. .fontColor($r('app.color.text_color'))
  2829. .fontSize(14)
  2830. .animation({
  2831. duration: 666,
  2832. curve: 'ease-in-out' // 可选动画曲线
  2833. })
  2834. if(Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length>0){
  2835. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2836. .fontColor($r('app.color.text_color'))
  2837. .fontSize(14)
  2838. .opacity(this.opacityItem)
  2839. .animation({
  2840. duration: 666,
  2841. curve: 'ease-in-out' // 可选动画曲线
  2842. })
  2843. }
  2844. }
  2845. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2846. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2847. .animation({
  2848. duration: 666,
  2849. curve: 'ease-in-out' // 可选动画曲线
  2850. })
  2851. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2852. .onTouch((event: TouchEvent) => {
  2853. if (event.type === TouchType.Down) {
  2854. this.isClickedPLayAll = true;
  2855. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2856. this.isClickedPLayAll = false;
  2857. }
  2858. })
  2859. .onClick(() => {
  2860. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2861. if (this.modeType === 0) {
  2862. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2863. this.doPlay(this.getCurFileList()[0])
  2864. }
  2865. } else {
  2866. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2867. this.doPlay(this.mediaKuList[0])
  2868. }
  2869. }
  2870. })
  2871. Row() {
  2872. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2873. .height(35)
  2874. .onChange((value: string) => {
  2875. this.onSearchInput(value);
  2876. })
  2877. .layoutWeight(1)
  2878. Text(`取消`)
  2879. .margin({ left: 10, right: 10 })
  2880. .fontColor($r('app.color.text_color'))
  2881. .fontSize(16)
  2882. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2883. .onClick(() => {
  2884. this.isSearchMode = false
  2885. this.searchText = ''
  2886. if(this.modeType==0){
  2887. this.updateListData(this.videoLocalList)
  2888. } else if(this.modeType==1){
  2889. this.updateListData(this.mediaKuList)
  2890. } else if(this.modeType==2&&!this.isCanBack){
  2891. this.updateListData(this.artistList)
  2892. } else if(this.modeType==3&&!this.isCanBack){
  2893. this.updateListData(this.albumList)
  2894. }
  2895. })
  2896. }
  2897. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2898. .animation({
  2899. duration: 666,
  2900. curve: 'ease-in-out' // 可选动画曲线
  2901. })
  2902. Blank()
  2903. Image($r("app.media.search"))
  2904. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2905. .animation({
  2906. duration: 666,
  2907. curve: 'ease-in-out' // 可选动画曲线
  2908. })// .opacity(this.opacityItem)
  2909. .fillColor(this.themeColor)
  2910. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2911. .onClick(() => {
  2912. this.isSearchMode = true
  2913. })
  2914. Image($r("app.media.refresh"))
  2915. .fillColor(this.themeColor)
  2916. .width(25)
  2917. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2918. .animation({
  2919. duration: 666,
  2920. curve: 'ease-in-out' // 可选动画曲线
  2921. })
  2922. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2923. .onClick(() => {
  2924. if (this.isFavMusic) {
  2925. this.getFavList(true)
  2926. } else {
  2927. if(this.modeType == 0){
  2928. this.asyncCurrentPathData()
  2929. }else if(this.modeType ==1){
  2930. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2931. }
  2932. }
  2933. })
  2934. Image($r("app.media.top_rank"))
  2935. .width(25)
  2936. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2937. Visibility.Visible)// .opacity(this.opacityItem)
  2938. .animation({
  2939. duration: 666,
  2940. curve: 'ease-in-out' // 可选动画曲线
  2941. })
  2942. .fillColor(this.themeColor)
  2943. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2944. .onClick(() => {
  2945. this.showRankDialog()
  2946. })
  2947. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2948. .width(24)
  2949. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2950. .animation({
  2951. duration: 666,
  2952. curve: 'ease-in-out' // 可选动画曲线
  2953. })
  2954. .fillColor(this.themeColor)
  2955. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2956. .onClick(() => {
  2957. this.isMultiSelect = !this.isMultiSelect
  2958. })
  2959. SymbolGlyph($r('sys.symbol.trash'))
  2960. .fontColor([this.themeColor])
  2961. .fontSize(25)
  2962. .effectStrategy(1)
  2963. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2964. .animation({
  2965. duration: 666,
  2966. curve: 'ease-in-out' // 可选动画曲线
  2967. })
  2968. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2969. .onClick(() => {
  2970. this.clearVideoHistory() //清空播放记录
  2971. })
  2972. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2973. .width(24)
  2974. .animation({
  2975. duration: 666,
  2976. curve: 'ease-in-out' // 可选动画曲线
  2977. })
  2978. .fillColor(this.themeColor)
  2979. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2980. .bindPopup($$this.tipPopup, {
  2981. builder: this.popupBuilder,
  2982. placement: Placement.Bottom,
  2983. maskColor: 0x33000000,
  2984. enableArrow: true,
  2985. onStateChange: (e) => {
  2986. if (!e.isVisible) {
  2987. this.tipPopup = false;
  2988. }
  2989. }
  2990. })
  2991. .onClick(() => {
  2992. if(this.twoFingerType==4){
  2993. this.isGridMusic = false
  2994. this.twoFingerType=3
  2995. }else{
  2996. this.isGridMusic = !this.isGridMusic
  2997. }
  2998. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  2999. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3000. })
  3001. }
  3002. .width('100%')
  3003. .padding(10)
  3004. .height(50)
  3005. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  3006. .border({
  3007. width: { bottom: 1 },
  3008. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3009. })
  3010. }
  3011. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3012. }
  3013. // 第二步:popup构造器定义弹框内容
  3014. @Builder popupBuilder() {
  3015. Column({ space: 2 }) {
  3016. Text('友情提示:双指缩放可以放大缩小列表')
  3017. .fontSize(12)
  3018. .fontWeight(FontWeight.Regular)
  3019. .fontColor($r('app.color.text_color'))
  3020. }
  3021. .justifyContent(FlexAlign.SpaceAround)
  3022. .width(220)
  3023. .height(55)
  3024. .padding(15)
  3025. }
  3026. //搜索功能的实现
  3027. @State searchText: string = ''; // 用户输入内容
  3028. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3029. @State isSearchMode: boolean = false
  3030. // 实时搜索逻辑(带防抖)
  3031. private onSearchInput(value: string) {
  3032. this.searchText = value.trim();
  3033. let mSearchList: Array<VideoItem> = []
  3034. switch (this.modeType) {
  3035. case 0:
  3036. mSearchList = this.videoLocalList
  3037. break;
  3038. case 1:
  3039. mSearchList = this.mediaKuList
  3040. break;
  3041. case 2:
  3042. mSearchList = this.artistList
  3043. break;
  3044. case 3:
  3045. mSearchList = this.albumList
  3046. break;
  3047. }
  3048. // 新增条件判断:空输入时显示所有数据
  3049. if (this.searchText === '') {
  3050. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3051. } else {
  3052. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3053. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  3054. });
  3055. }
  3056. this.updateListData(this.filteredList);
  3057. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3058. }
  3059. @State dragItem: number = -1
  3060. @State scaleItem: number = -1
  3061. @State neighborItem: number = -1
  3062. @State neighborScale: number = -1
  3063. @State offsetY: number = 0
  3064. private dragRefOffset: number = 0
  3065. private ITEM_INTV: number = 78
  3066. scaleSelect(item: number): number {
  3067. if (this.scaleItem === item) {
  3068. return 1.05
  3069. } else if (this.neighborItem === item) {
  3070. return this.neighborScale
  3071. } else {
  3072. return 1
  3073. }
  3074. }
  3075. itemMove(index: number, newIndex: number): void {
  3076. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3077. return;
  3078. }
  3079. let tmp = this.videoLocalList.splice(index, 1);
  3080. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3081. this.dataSource.pushArrayData(this.videoLocalList)
  3082. }
  3083. //瀑布流布局 支持双指缩放
  3084. @State columns: number = 2;
  3085. @State waterFlowScale: number = 1;
  3086. @State imageScale: number = 1;
  3087. @State waterFlowOpacity: number = 1;
  3088. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  3089. private columnChanged: boolean = false;
  3090. private oldColumn: number = this.columns;
  3091. private pinchTime: number = 0;
  3092. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  3093. changeColumns(scale: number) {
  3094. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3095. this.columns--;
  3096. this.columnChanged = true;
  3097. } else if (scale < 1 && this.columns < 4) {
  3098. this.columns++;
  3099. this.columnChanged = true;
  3100. }
  3101. }
  3102. @Builder
  3103. getWaterView(){
  3104. Scroll(this.scroller) {
  3105. Column() {
  3106. if(this.isShowCoverHeader()){
  3107. this.coverHeader()
  3108. }else {
  3109. this.listViewTitle()
  3110. }
  3111. WaterFlow({
  3112. scroller:this.waterScroller,
  3113. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  3114. }) {
  3115. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3116. FlowItem() {
  3117. this.MusicWaterCardItem(item,index)
  3118. }
  3119. .width('100%')
  3120. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3121. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3122. {
  3123. preview: MenuPreviewMode.IMAGE,
  3124. previewAnimationOptions: { scale: [0.8, 1.0] },
  3125. })
  3126. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3127. {
  3128. preview: MenuPreviewMode.IMAGE,
  3129. previewAnimationOptions: { scale: [0.8, 1.0] },
  3130. })
  3131. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  3132. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3133. TransitionEffect.scale({ x: 0, y: 0 }) ))
  3134. .gesture(
  3135. GestureGroup(GestureMode.Exclusive,
  3136. SwipeGesture({ direction: SwipeDirection.Horizontal })
  3137. .onAction((event: GestureEvent) => {
  3138. if (event) {
  3139. // this.sideBarController.openSideBar()
  3140. }
  3141. }),
  3142. TapGesture({ count: 1, fingers: 1 })
  3143. .onAction(async () => {
  3144. })
  3145. )
  3146. )
  3147. }, (item: VideoItem) => item.filePath)
  3148. }
  3149. // .columnsTemplate('repeat(auto-fit, 160)')
  3150. .id('waterflow') // 设置id用于截图
  3151. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  3152. .columnsGap(12) // 列间距
  3153. .rowsGap(16) // 行间距
  3154. .cachedCount(6)
  3155. .margin(
  3156. this.isHiCar()?{bottom:this.bottomBarHeight+90}:
  3157. {bottom:this.isShowCoverHeader()? this.topBarHeight+35:
  3158. this.isCoverOpacity()?this.topBarHeight+this.bottomBarHeight+78
  3159. :this.topBarHeight+this.bottomBarHeight+108})
  3160. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3161. .animation({ duration: 500, curve: Curve.Ease }))
  3162. .scrollBar(BarState.Off)
  3163. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  3164. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  3165. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  3166. .width('100%')
  3167. .height('100%')
  3168. .padding(10)
  3169. .opacity(this.waterFlowOpacity)
  3170. .scale({
  3171. x: this.waterFlowScale,
  3172. y: this.waterFlowScale,
  3173. centerX: 0,
  3174. centerY: 0
  3175. })
  3176. .onAppear(() => {
  3177. this.scroller.scrollEdge(Edge.Top)
  3178. })
  3179. .nestedScroll({
  3180. scrollForward: NestedScrollMode.PARENT_FIRST,
  3181. scrollBackward: NestedScrollMode.SELF_FIRST
  3182. })
  3183. .priorityGesture(
  3184. PinchGesture()
  3185. .onActionStart((event: GestureEvent) => {
  3186. // 双指捏合手势识别成功时截图
  3187. this.pinchTime = event.timestamp;
  3188. this.columnChanged = false;
  3189. this.oldColumn = this.columns;
  3190. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  3191. if (error) {
  3192. console.info('error:' + JSON.stringify(error));
  3193. return;
  3194. }
  3195. this.waterFlowSnapshot = pixmap;
  3196. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  3197. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  3198. if (this.oldColumn ===4) {
  3199. this.twoFingerType =3
  3200. this.isGridMusic = true
  3201. }else if (this.oldColumn ===1) {
  3202. this.twoFingerType =1
  3203. this.isGridMusic = false
  3204. }
  3205. return;
  3206. }
  3207. })
  3208. })
  3209. .onActionUpdate((event: GestureEvent) => {
  3210. // 手势更新:处理缩放逻辑和视觉效果
  3211. // 边界限制:防止超出列数范围时继续缩放
  3212. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  3213. return;
  3214. }
  3215. // 节流处理:避免过于频繁的更新,提升性能
  3216. if (event.timestamp - this.pinchTime < 10000000) {
  3217. return;
  3218. }
  3219. this.pinchTime = event.timestamp;
  3220. this.waterFlowScale = event.scale;
  3221. this.imageScale = event.scale;
  3222. // 根据缩放比例设置WaterFlow透明度
  3223. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  3224. this.waterFlowOpacity *= 3;
  3225. if (!this.columnChanged) {
  3226. this.changeColumns(event.scale);
  3227. }
  3228. // 列数改变后的缩放比例调整:避免出现空白区域
  3229. if (this.columnChanged) {
  3230. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  3231. // 限制缩放范围,确保视觉效果自然
  3232. if (event.scale < 1) {
  3233. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  3234. } else {
  3235. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  3236. }
  3237. }
  3238. })
  3239. .onActionEnd((event: GestureEvent) => {
  3240. // 手势结束:执行归位动画并保存状态
  3241. // 执行归位动画:平滑过渡到正常状态
  3242. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  3243. this.waterFlowScale = 1;
  3244. this.waterFlowOpacity = 1;
  3245. })
  3246. // 持久化保存当前列数:下次启动时恢复
  3247. PreferencesUtil.putSync('lastColumns', this.columns);
  3248. })
  3249. )
  3250. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3251. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3252. .onDrop((event?: DragEvent) => {
  3253. try {
  3254. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3255. if (dragData !== undefined) {
  3256. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3257. if (records.length > 0) {
  3258. for (let i = 0; i < records.length; i++) {
  3259. let types = records[i].getTypes();
  3260. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3261. const fileUriUds =
  3262. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3263. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3264. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3265. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3266. this.targetFile = fileUriUds.oriUri;
  3267. this.saveVideoDatas([this.targetFile])
  3268. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3269. }
  3270. }
  3271. }
  3272. } else {
  3273. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3274. }
  3275. } else {
  3276. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3277. }
  3278. } catch (error) {
  3279. const err = error as BusinessError;
  3280. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3281. }
  3282. })
  3283. }
  3284. }
  3285. .scrollBar(BarState.Off)
  3286. }
  3287. //瀑布流卡片布局
  3288. @Builder
  3289. private MusicWaterCardItem(item: VideoItem, index: number) {
  3290. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3291. Stack() {
  3292. Column() {
  3293. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3294. .backgroundImageSize(ImageSize.Auto)
  3295. .borderRadius({
  3296. topLeft: 12,
  3297. topRight : 12,
  3298. bottomLeft: 0,
  3299. bottomRight: 0
  3300. })
  3301. .draggable(false)// 禁止长按手势拖动
  3302. // .autoResize(true) // 重采样,可减少内存占用
  3303. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3304. .width('100%')
  3305. .height('auto')
  3306. .objectFit(ImageFit.Auto)
  3307. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3308. height: '99%' ,
  3309. dragBar: true,
  3310. onDisappear: () => {
  3311. this.longItemFilePath = '';
  3312. this.tempLyricContent = ''
  3313. },
  3314. showClose: true,
  3315. preferType: SheetType.CENTER ,
  3316. title: { title: '编辑标签' }
  3317. })
  3318. .draggable(false)
  3319. .opacity(this.opacityItem)// 绑定透明度
  3320. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3321. // .animation({ duration: 500, curve: Curve.Ease }))
  3322. .animation({
  3323. duration: 666,
  3324. curve: 'ease-in-out' // 可选动画曲线
  3325. })
  3326. .margin({
  3327. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3328. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3329. })
  3330. Column() {
  3331. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3332. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  3333. .maxLines(1)
  3334. .fontWeight(FontWeight.Bold)
  3335. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3336. .animation({
  3337. duration: 555,
  3338. curve: 'Linear',
  3339. })
  3340. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3341. height: '95%',
  3342. dragBar: true,
  3343. showClose: true,
  3344. onDisappear: () => {
  3345. this.longItemFilePathDetail = '';
  3346. },
  3347. blurStyle:BlurStyle.Thin,
  3348. backgroundColor:Color.Transparent,
  3349. preferType: SheetType.CENTER ,
  3350. title: { title: '详情' }
  3351. })
  3352. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3353. $r('app.color.text_color'))
  3354. Column() {
  3355. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3356. .fontSize(11)
  3357. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3358. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3359. .fontColor($r('app.color.text_color'))
  3360. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3361. .fontSize(11)
  3362. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3363. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3364. .fontColor($r('app.color.text_color'))
  3365. Row(){
  3366. Column(){
  3367. Text(item.md5Str?.includes('Lossless')?
  3368. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3369. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  3370. .padding({ top: 3,right:6,left:6,bottom:3 })
  3371. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3372. $r('app.color.text_color'))
  3373. .fontWeight(500)
  3374. .borderRadius(12)
  3375. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3376. .backgroundColor('#FFC107')
  3377. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  3378. }
  3379. .margin({ top: 2 ,right:6})
  3380. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3381. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3382. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3383. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  3384. .maxLines(1)
  3385. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3386. .margin({ top: 2})
  3387. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3388. || item.type == CommonConstants.TYPE_IS_ALBUM
  3389. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3390. .fontWeight(FontWeight.Medium)
  3391. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3392. $r('app.color.text_color'))
  3393. }
  3394. }
  3395. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3396. }
  3397. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  3398. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  3399. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  3400. .width('100%')
  3401. .justifyContent(FlexAlign.Center)
  3402. .margin({
  3403. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3404. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3405. })
  3406. }
  3407. .width('100%')
  3408. .borderRadius(12)
  3409. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3410. .backgroundImageSize({ height: '100%', width: '100%' })
  3411. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3412. .animation({ curve: Curve.Sharp, duration: 300 })
  3413. Checkbox({ name: 'checkbox' + index })
  3414. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3415. .selectedColor(this.themeColor)
  3416. .shape(CheckBoxShape.CIRCLE)
  3417. .opacity(this.isMultiSelect ? 1 : 0)
  3418. .animation({
  3419. duration: 666,
  3420. curve: 'Smooth' // 可选动画曲线
  3421. })
  3422. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3423. Visibility.None)
  3424. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3425. .margin({ left: 20, top: 8, bottom: 8 })
  3426. .width(38)
  3427. .height(38)
  3428. }
  3429. }
  3430. .backgroundColor(Color.Transparent)
  3431. .width('100%')
  3432. .height('auto')
  3433. .padding({top:2})
  3434. .reuseId('card_item')
  3435. .onClick(() => {
  3436. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3437. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3438. this.handleFileSelection(item, !isChecked);
  3439. } else {
  3440. this.doPlay(item, index)
  3441. }
  3442. })
  3443. }
  3444. // Grid布局的开始
  3445. private dragRefOffSetX: number = 0;
  3446. private dragRefOffSetY: number = 0;
  3447. private FIX_VP_X: number = 180;
  3448. private FIX_VP_Y: number = 84;
  3449. isDraggable(index: number): boolean {
  3450. return index >= 0;
  3451. }
  3452. getRowEnd(item: number) {
  3453. if (item.toString() === '0') {
  3454. return 1;
  3455. } else {
  3456. return 0;
  3457. }
  3458. }
  3459. // [Start itemMove_start]
  3460. // itemMoveGrid(index: number, newIndex: number): void {
  3461. // if (!this.isDraggable(newIndex)) {
  3462. // return;
  3463. // }
  3464. // let tmp = this.videoLocalList.splice(index, 1);
  3465. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3466. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  3467. // }
  3468. isInLeft(index: number) {
  3469. return index % 2 == 0;
  3470. }
  3471. down(index: number): void {
  3472. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  3473. return;
  3474. }
  3475. this.offsetY -= this.FIX_VP_Y;
  3476. this.dragRefOffSetY += this.FIX_VP_Y;
  3477. this.itemMove(index, index + 1);
  3478. }
  3479. up(index: number): void {
  3480. if (!this.isDraggable(index - 2)) {
  3481. return;
  3482. }
  3483. this.offsetY += this.FIX_VP_Y;
  3484. this.dragRefOffSetY -= this.FIX_VP_Y;
  3485. this.itemMove(index, index - 1);
  3486. }
  3487. left(index: number): void {
  3488. if (this.isInLeft(index)) {
  3489. return;
  3490. }
  3491. if (!this.isDraggable(index - 1)) {
  3492. return;
  3493. }
  3494. this.offsetX += this.FIX_VP_X;
  3495. this.dragRefOffSetX -= this.FIX_VP_X;
  3496. this.itemMove(index, index - 1)
  3497. }
  3498. right(index: number): void {
  3499. if (!this.isInLeft(index)) {
  3500. return;
  3501. }
  3502. if (!this.isDraggable(index + 1)) {
  3503. return;
  3504. }
  3505. this.offsetX -= this.FIX_VP_X;
  3506. this.dragRefOffSetX += this.FIX_VP_X;
  3507. this.itemMove(index, index + 1)
  3508. }
  3509. private scroller: Scroller = new Scroller();
  3510. private waterScroller: Scroller = new Scroller();
  3511. @State startIndex: number = 0
  3512. @State endIndex: number = 0
  3513. @State scaleValue: number = 1
  3514. @State pinchValue: number = 1
  3515. layoutOptionsForHeader: GridLayoutOptions = {
  3516. regularSize: [1, 1], // 只支持[1, 1]
  3517. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3518. };
  3519. @Builder
  3520. getGridView() {
  3521. Grid(this.scroller, this.layoutOptionsForHeader) {
  3522. GridItem() {
  3523. if (this.isShowCoverHeader()) {
  3524. this.coverHeader()
  3525. } else {
  3526. this.listViewTitle()
  3527. }
  3528. }
  3529. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3530. GridItem() {
  3531. Stack({ alignContent: Alignment.Center }) {
  3532. this.MusicItemGrid(item, index)
  3533. }
  3534. }
  3535. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3536. {
  3537. preview: MenuPreviewMode.IMAGE,
  3538. previewAnimationOptions: { scale: [0.8, 1.0] },
  3539. })
  3540. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3541. {
  3542. preview: MenuPreviewMode.IMAGE,
  3543. previewAnimationOptions: { scale: [0.8, 1.0] },
  3544. })
  3545. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3546. TransitionEffect.scale({ x: 0, y: 0 })))
  3547. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3548. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3549. .zIndex(this.dragItem === index ? 1 : 0)
  3550. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3551. // .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  3552. }, (item: VideoItem) => item.filePath)
  3553. }
  3554. .width(this.isShowHeader ? '100%' : '94%')
  3555. .height('100%')
  3556. .editMode(true)
  3557. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3558. .animation({ duration: 500, curve: Curve.Ease }))
  3559. .margin(
  3560. this.isHiCar()?{bottom:this.bottomBarHeight+98}:
  3561. {
  3562. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3563. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3564. })
  3565. .reuseId('grid_item')
  3566. .layoutWeight(1)
  3567. .scrollBar(BarState.Off)
  3568. .supportAnimation(true)
  3569. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3570. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3571. .columnsTemplate(
  3572. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3573. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3574. )
  3575. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3576. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3577. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3578. .gesture(PinchGesture({ fingers: 2 })
  3579. .onActionEnd((event: GestureEvent) => {
  3580. this.setGridTwoFingers()
  3581. })
  3582. .onActionUpdate(e => {
  3583. this.scaleValue = this.pinchValue * e.scale
  3584. })
  3585. .onActionStart(e => {
  3586. }))
  3587. .enableScrollInteraction(true)
  3588. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3589. .onScrollIndex((start: number, end: number) => {
  3590. this.startIndex = start
  3591. this.endIndex = end
  3592. })
  3593. .onScrollFrameBegin((offset: number) => {
  3594. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3595. // if (this.isPhoneLan()) {
  3596. // this.setBarHeightHide(offset)
  3597. // } else
  3598. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3599. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3600. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3601. if (this.isScrollHide) {
  3602. this.setBarHeightHide2(offset)
  3603. } else {
  3604. this.setBarHeightNormal()
  3605. }
  3606. } else {
  3607. this.setBarHeightHide(offset)
  3608. }
  3609. return { offsetRemain: offset };
  3610. })
  3611. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3612. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3613. .onDrop((event?: DragEvent) => {
  3614. try {
  3615. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3616. if (dragData !== undefined) {
  3617. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3618. if (records.length > 0) {
  3619. for (let i = 0; i < records.length; i++) {
  3620. let types = records[i].getTypes();
  3621. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3622. const fileUriUds =
  3623. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3624. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3625. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3626. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3627. this.targetFile = fileUriUds.oriUri;
  3628. this.saveVideoDatas([this.targetFile])
  3629. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3630. }
  3631. }
  3632. }
  3633. } else {
  3634. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3635. }
  3636. } else {
  3637. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3638. }
  3639. } catch (error) {
  3640. const err = error as BusinessError;
  3641. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3642. }
  3643. })
  3644. }
  3645. @State targetFile: string = '';
  3646. setGridTwoFingers() {
  3647. this.pinchValue = this.scaleValue;
  3648. Logger.info('this.pinchValue = ' + this.pinchValue);
  3649. if (this.pinchValue >= 1) {
  3650. this.twoFingerType++
  3651. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3652. if(this.twoFingerType >= 4){
  3653. this.twoFingerType = 4//切换成瀑布流
  3654. this.columns = 4
  3655. }
  3656. } else {
  3657. this.twoFingerType--
  3658. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3659. if (this.twoFingerType < 1) {
  3660. this.twoFingerType = 3
  3661. this.isGridMusic = false
  3662. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3663. }
  3664. }
  3665. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3666. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3667. this.pinchValue = 1;
  3668. this.scaleValue = 1;
  3669. }
  3670. @State longItemFilePath: string = ''
  3671. @State tempLyricContent: string = ''
  3672. @Builder
  3673. private MusicItemGrid(item: VideoItem, index: number) {
  3674. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3675. Stack() {
  3676. Column() {
  3677. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3678. .height(this.getGridHeight())
  3679. .width(this.getGridWight())
  3680. .draggable(false)
  3681. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3682. .autoResize(true) // 重采样,可减少内存占用
  3683. .alt($r('app.media.ic_avatar2'))
  3684. .clip(true)
  3685. .borderRadius({
  3686. topLeft: 12,
  3687. topRight: 12,
  3688. bottomLeft: 0,
  3689. bottomRight: 0
  3690. })
  3691. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3692. height: '99%' ,
  3693. dragBar: true,
  3694. onDisappear: () => {
  3695. this.longItemFilePath = '';
  3696. this.tempLyricContent = ''
  3697. },
  3698. showClose: true,
  3699. preferType: SheetType.CENTER ,
  3700. title: { title: '编辑标签' }
  3701. })
  3702. .draggable(false)
  3703. .opacity(this.opacityItem)// 绑定透明度
  3704. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3705. // .animation({ duration: 500, curve: Curve.Ease }))
  3706. .animation({
  3707. duration: 666,
  3708. curve: 'ease-in-out' // 可选动画曲线
  3709. })
  3710. .margin({
  3711. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3712. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3713. })
  3714. Column() {
  3715. Text(this.isShowFileName?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3716. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3717. .maxLines(1)
  3718. .fontWeight(FontWeight.Bold)
  3719. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3720. .animation({
  3721. duration: 555,
  3722. curve: 'Linear',
  3723. })
  3724. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3725. height: '95%',
  3726. dragBar: true,
  3727. showClose: true,
  3728. onDisappear: () => {
  3729. this.longItemFilePathDetail = '';
  3730. },
  3731. blurStyle:BlurStyle.Thin,
  3732. backgroundColor:Color.Transparent,
  3733. preferType: SheetType.CENTER ,
  3734. title: { title: '详情' }
  3735. })
  3736. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3737. $r('app.color.text_color'))
  3738. Column() {
  3739. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3740. .fontSize(11)
  3741. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3742. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3743. .fontColor($r('app.color.text_color'))
  3744. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3745. .fontSize(11)
  3746. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3747. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3748. .fontColor($r('app.color.text_color'))
  3749. Row(){
  3750. Column(){
  3751. Text(item.md5Str?.includes('Lossless')?
  3752. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3753. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3754. .padding({ top: 3,right:6,left:6,bottom:3 })
  3755. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3756. $r('app.color.text_color'))
  3757. .fontWeight(500)
  3758. .borderRadius(12)
  3759. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3760. .backgroundColor('#FFC107')
  3761. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  3762. }
  3763. .margin({ top: 2 ,right:6})
  3764. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3765. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3766. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3767. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3768. .maxLines(1)
  3769. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3770. .margin({ top: 2})
  3771. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3772. || item.type == CommonConstants.TYPE_IS_ALBUM
  3773. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3774. .fontWeight(FontWeight.Medium)
  3775. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3776. $r('app.color.text_color'))
  3777. }
  3778. }
  3779. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3780. }
  3781. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  3782. .width(this.getGridWight())
  3783. .justifyContent(FlexAlign.Center)
  3784. .margin({
  3785. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3786. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3787. })
  3788. }
  3789. .width(this.getGridWight())
  3790. .borderRadius(12)
  3791. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3792. .backgroundImageSize({ height: '100%', width: '100%' })
  3793. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3794. .animation({ curve: Curve.Sharp, duration: 300 })
  3795. Checkbox({ name: 'checkbox' + index })
  3796. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3797. .selectedColor(this.themeColor)
  3798. .shape(CheckBoxShape.CIRCLE)
  3799. .opacity(this.isMultiSelect ? 1 : 0)
  3800. .animation({
  3801. duration: 666,
  3802. curve: 'Smooth' // 可选动画曲线
  3803. })
  3804. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3805. Visibility.None)
  3806. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3807. .margin({ left: 20, top: 8, bottom: 8 })
  3808. .width(38)
  3809. .height(38)
  3810. }
  3811. }
  3812. .backgroundColor(Color.Transparent)
  3813. .width('100%')
  3814. .padding({ top: 15 })
  3815. .height(this.getGridAllHeight())
  3816. .onClick(() => {
  3817. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3818. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3819. this.handleFileSelection(item, !isChecked);
  3820. } else {
  3821. this.doPlay(item, index)
  3822. }
  3823. })
  3824. }
  3825. getGridAllHeight() {
  3826. let heightG = 222
  3827. switch (this.twoFingerType) {
  3828. case 1:
  3829. heightG = 118
  3830. break;
  3831. case 2:
  3832. heightG = 168
  3833. break;
  3834. case 3:
  3835. heightG = 222
  3836. break;
  3837. }
  3838. return heightG
  3839. }
  3840. getGridHeight() {
  3841. let heightG = 150
  3842. switch (this.twoFingerType) {
  3843. case 1:
  3844. heightG = 55
  3845. break;
  3846. case 2:
  3847. heightG = 100
  3848. break;
  3849. case 3:
  3850. heightG = 150
  3851. break;
  3852. }
  3853. return heightG
  3854. }
  3855. getGridWight() {
  3856. let wightG = 158
  3857. switch (this.twoFingerType) {
  3858. case 1:
  3859. wightG = 80
  3860. break;
  3861. case 2:
  3862. wightG = 110
  3863. break;
  3864. case 3:
  3865. wightG = 158
  3866. break;
  3867. }
  3868. return wightG
  3869. }
  3870. @State isShowDetail:boolean = false
  3871. // @State isShowDetailGrid:boolean = false
  3872. // @State isShowEditGrid:boolean = false
  3873. @State longItemFilePathDetail:string =''
  3874. @Builder
  3875. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3876. if(
  3877. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3878. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3879. item.name === LocalMusic.STR_HISTORY_MUSIC)
  3880. ){
  3881. //如果是专辑和艺术家的首页,不能长按
  3882. //如果是我的收藏 最近播放等也不能长按
  3883. }else{
  3884. Scroll() {
  3885. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3886. Menu() {
  3887. MenuItem({
  3888. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3889. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3890. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3891. })
  3892. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3893. .onClick(() => {
  3894. if (item) {
  3895. this.doFav(item)
  3896. }
  3897. this.longItemFilePath = ''
  3898. })
  3899. MenuItem({
  3900. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3901. content: '下一首播放'
  3902. })
  3903. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3904. .onClick(() => {
  3905. this.addToNextPlay(item);
  3906. this.longItemFilePath = ''
  3907. })
  3908. MenuItem({
  3909. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3910. content: '编辑标签'
  3911. })
  3912. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3913. height: '99%',
  3914. dragBar: true,
  3915. showClose: true,
  3916. preferType: SheetType.CENTER ,
  3917. title: { title: '编辑标签' }
  3918. })
  3919. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3920. .onClick(async() => {
  3921. this.setEditStrEmpty()
  3922. this.tempLyricContent = await this.getLyricContent(item);
  3923. // console.info('onecold 长按this.tempLyricContent' +this.tempLyricContent)
  3924. if(this.isGridMusic||this.twoFingerType==4){
  3925. this.longItemFilePath = item.filePath
  3926. }else{
  3927. this.isShowEdit = !this.isShowEdit;
  3928. }
  3929. })
  3930. MenuItem({
  3931. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  3932. content: $r('app.string.select_all')
  3933. })
  3934. .onClick(() => {
  3935. this.isMultiSelect = !this.isMultiSelect
  3936. this.longItemFilePath = ''
  3937. this.selectedFiles.push(item)
  3938. })
  3939. MenuItem({
  3940. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3941. content: $r('app.string.rename')
  3942. })
  3943. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3944. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3945. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3946. .onClick(() => {
  3947. this.showReNameDialog(item, index + '', filePath)
  3948. this.longItemFilePath = ''
  3949. })
  3950. MenuItem({
  3951. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3952. content: $r('app.string.delete')
  3953. })
  3954. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3955. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3956. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3957. .onClick(() => {
  3958. this.selectedFiles.push(item)
  3959. this.showWarnIsDelete()
  3960. this.longItemFilePath = ''
  3961. })
  3962. MenuItem({
  3963. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3964. content: $r('app.string.detail')
  3965. })
  3966. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3967. height:'95%',
  3968. dragBar: true,
  3969. showClose: true,
  3970. blurStyle:BlurStyle.Thin,
  3971. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3972. backgroundColor:Color.Transparent,
  3973. title: { title: '详情信息' }
  3974. })
  3975. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3976. .onClick(() => {
  3977. if(this.isGridMusic||this.twoFingerType==4){
  3978. this.longItemFilePathDetail = item.filePath
  3979. }else{
  3980. this.isShowDetail = !this.isShowDetail
  3981. }
  3982. })
  3983. MenuItem({
  3984. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3985. content: $r('app.string.share')
  3986. })
  3987. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3988. .onClick(() => {
  3989. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3990. this.longItemFilePath = ''
  3991. })
  3992. }
  3993. .font({ size: 15, weight: FontWeight.Normal })
  3994. }
  3995. .width(180)
  3996. }
  3997. .height('auto')
  3998. }
  3999. }
  4000. private listMaxScrollOffsetY: number = 0
  4001. @State selectedIndex: number = -1
  4002. setlistTwoFingers() {
  4003. this.pinchValue = this.scaleValue;
  4004. Logger.info('this.pinchValue = ' + this.pinchValue);
  4005. if (this.pinchValue >= 1) {
  4006. this.twoFingerType++
  4007. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4008. if (this.twoFingerType > 3) {
  4009. this.twoFingerType = 1
  4010. this.isGridMusic = true
  4011. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4012. }
  4013. } else {
  4014. this.twoFingerType--
  4015. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4016. if (this.twoFingerType < 1) {
  4017. this.twoFingerType = 4
  4018. this.columns = 1
  4019. }
  4020. }
  4021. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4022. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4023. this.pinchValue = 1;
  4024. this.scaleValue = 1;
  4025. }
  4026. @Builder
  4027. getListView() {
  4028. List({ scroller: this.listScroller }) {
  4029. ListItemGroup({ header: this.coverHeader() }) {
  4030. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4031. ListItem() {
  4032. Column() {
  4033. if (item.type === CommonConstants.TYPE_IS_DIR
  4034. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  4035. this.DirItem(item, index)
  4036. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  4037. } else {
  4038. this.MusicItem(item, index)
  4039. }
  4040. }
  4041. .shadow(this.scaleItem === index ? {
  4042. radius: 70,
  4043. color: '#15000000',
  4044. offsetX: 0,
  4045. offsetY: 0
  4046. } :
  4047. {
  4048. radius: 0,
  4049. color: '#15000000',
  4050. offsetX: 0,
  4051. offsetY: 0
  4052. })
  4053. .animation({ curve: Curve.Sharp, duration: 300 })
  4054. }
  4055. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  4056. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  4057. .animation({ duration: 500 }),
  4058. TransitionEffect.scale({ x: 0, y: 0 })))
  4059. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4060. .swipeAction((
  4061. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  4062. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  4063. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  4064. .onClick(() => {
  4065. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4066. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4067. this.handleFileSelection(item, !isChecked);
  4068. } else {
  4069. this.doPlay(item, index)
  4070. }
  4071. })
  4072. //拖动List关键代码开始
  4073. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4074. .zIndex(this.dragItem === index ? 1 : 0)
  4075. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4076. .gesture(
  4077. GestureGroup(GestureMode.Sequence,
  4078. LongPressGesture({ repeat: true })
  4079. .onAction((event?: GestureEvent) => {
  4080. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4081. this.scaleItem = index
  4082. })
  4083. })
  4084. .onActionEnd(() => {
  4085. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4086. this.scaleItem = -1
  4087. })
  4088. }),
  4089. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4090. .onActionStart(() => {
  4091. this.dragItem = index // 记录当前拖动项索引
  4092. this.dragRefOffset = 0 // 重置偏移基准
  4093. })
  4094. .onActionUpdate((event: GestureEvent) => {
  4095. this.offsetY = event.offsetY - this.dragRefOffset;
  4096. this.neighborItem = -1;
  4097. let indexA = this.videoLocalList.indexOf(item);
  4098. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4099. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4100. let value: number = 0;
  4101. if (this.offsetY < 0) {
  4102. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4103. this.neighborItem = indexA - 1;
  4104. this.neighborScale = 1 - value / 20;
  4105. } else if (this.offsetY > 0) {
  4106. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4107. this.neighborItem = indexA + 1;
  4108. this.neighborScale = 1 - value / 20;
  4109. }
  4110. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  4111. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4112. this.offsetY -= this.ITEM_INTV;
  4113. this.dragRefOffset += this.ITEM_INTV;
  4114. this.itemMove(indexA, indexA + 1);
  4115. });
  4116. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4117. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4118. this.offsetY += this.ITEM_INTV;
  4119. this.dragRefOffset -= this.ITEM_INTV;
  4120. this.itemMove(indexA, indexA - 1);
  4121. });
  4122. }
  4123. let curListOffset = this.listScroller.currentOffset()
  4124. // 获取手指信息
  4125. let fingerInfo = event.fingerList[0]
  4126. let clickPercentY =
  4127. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  4128. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  4129. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  4130. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  4131. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  4132. }
  4133. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  4134. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  4135. if (curListOffset.yOffset > scrollVelocity + 5) {
  4136. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  4137. }
  4138. }
  4139. })
  4140. .onActionEnd((event: GestureEvent) => {
  4141. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4142. this.dragItem = -1
  4143. this.neighborItem = -1
  4144. })
  4145. animateTo({
  4146. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4147. }, () => {
  4148. this.scaleItem = -1
  4149. })
  4150. })
  4151. )
  4152. .onCancel(() => {
  4153. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4154. this.dragItem = -1
  4155. this.neighborItem = -1
  4156. })
  4157. animateTo({
  4158. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4159. }, () => {
  4160. this.scaleItem = -1
  4161. })
  4162. })
  4163. ) //拖动List关键代码结束
  4164. }, (item: VideoItem) => item.filePath)
  4165. }
  4166. }
  4167. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4168. .gesture(PinchGesture({ fingers: 2 })
  4169. .onActionEnd((event: GestureEvent) => {
  4170. this.setlistTwoFingers()
  4171. })
  4172. .onActionUpdate(e => {
  4173. this.scaleValue = this.pinchValue * e.scale
  4174. })
  4175. .onActionStart(e => {
  4176. }))
  4177. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  4178. .margin(
  4179. this.isHiCar()&&(this.windowWidth>1800&&this.windowHeight>=1200)?{bottom:this.bottomBarHeight+98}:
  4180. {
  4181. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  4182. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+125)
  4183. })
  4184. .cachedCount(6)
  4185. .reuseId('list_item')
  4186. .borderRadius(20)
  4187. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  4188. TransitionEffect.scale({ x: 0, y: 0 })))
  4189. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4190. // .animation({ duration: 500, curve: Curve.Ease }))
  4191. .layoutWeight(1)
  4192. .onScrollIndex((start) => {
  4193. this.selectedIndex = start
  4194. })
  4195. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  4196. .lanes(
  4197. new BreakpointType<number>({
  4198. sm: 1,
  4199. md: 2,
  4200. lg: 2,
  4201. xl: 3,
  4202. xxl: 4
  4203. }).getValue(this.currentBreakpoint),
  4204. new BreakpointType<number>({
  4205. sm: 0,
  4206. md: 12,
  4207. lg: 12,
  4208. xl: 16,
  4209. xxl: 20
  4210. }).getValue(this.currentBreakpoint)
  4211. )
  4212. .onAreaChange((oldValue: Area, newValue: Area) => {
  4213. this.listArea = newValue
  4214. if (this.twoFingerType == 3) {
  4215. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  4216. } else if (this.twoFingerType == 2) {
  4217. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  4218. } else if (this.twoFingerType == 1) {
  4219. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  4220. }
  4221. })
  4222. .onScrollFrameBegin((offset: number) => {
  4223. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  4224. // if (this.isPhoneLan()) {
  4225. // this.setBarHeightHide(offset)
  4226. // } else
  4227. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4228. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4229. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4230. if (this.isScrollHide) {
  4231. this.setBarHeightHide2(offset)
  4232. } else {
  4233. this.setBarHeightNormal()
  4234. }
  4235. } else {
  4236. this.setBarHeightHide(offset)
  4237. }
  4238. return { offsetRemain: offset };
  4239. })
  4240. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  4241. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4242. .onDrop((event?: DragEvent) => {
  4243. try {
  4244. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4245. if (dragData !== undefined) {
  4246. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4247. if (records.length > 0) {
  4248. for (let i = 0; i < records.length; i++) {
  4249. let types = records[i].getTypes();
  4250. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4251. const fileUriUds =
  4252. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4253. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4254. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4255. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4256. this.targetFile = fileUriUds.oriUri;
  4257. this.saveVideoDatas([this.targetFile])
  4258. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4259. }
  4260. }
  4261. }
  4262. } else {
  4263. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4264. }
  4265. } else {
  4266. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4267. }
  4268. } catch (error) {
  4269. const err = error as BusinessError;
  4270. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4271. }
  4272. })
  4273. }
  4274. setBarHeightNormal() {
  4275. this.hideDone = false;
  4276. this.getUIContext().animateTo({
  4277. duration: 300
  4278. }, () => {
  4279. this.bottomBarHeight = 55 + 0;
  4280. this.topBarHeight = 50 + 0;
  4281. this.barOpacity = 1;
  4282. this.barBottomOpacity = 1
  4283. this.currentYOffset = 0;
  4284. this.isHiding = false;
  4285. });
  4286. }
  4287. setBarHeightHide(offset: number) {
  4288. if (offset > 0 && !this.hideDone) {
  4289. this.currentYOffset += offset;
  4290. if (this.currentYOffset <= 100) {
  4291. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  4292. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4293. this.barOpacity = 1 - this.currentYOffset / 100;
  4294. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  4295. } else {
  4296. this.topBarHeight = 0;
  4297. this.bottomBarHeight = 0;
  4298. this.barBottomOpacity = 0
  4299. this.barOpacity = 0;
  4300. this.hideDone = true;
  4301. }
  4302. this.isHiding = true;
  4303. }
  4304. if (offset < 0 && this.isHiding) {
  4305. this.hideDone = false;
  4306. this.getUIContext().animateTo({
  4307. duration: 300
  4308. }, () => {
  4309. this.bottomBarHeight = 55 + 0;
  4310. this.topBarHeight = 50 + 0;
  4311. this.barOpacity = 1;
  4312. this.barBottomOpacity = 1
  4313. this.currentYOffset = 0;
  4314. this.isHiding = false;
  4315. });
  4316. }
  4317. }
  4318. //这个方法没隐藏bottomBar,只隐藏topbar
  4319. setBarHeightHide2(offset: number) {
  4320. if (offset > 0 && !this.hideDone) {
  4321. this.currentYOffset += offset;
  4322. if (this.currentYOffset <= 100) {
  4323. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4324. this.barOpacity = 1 - this.currentYOffset / 100;
  4325. } else {
  4326. this.topBarHeight = 0;
  4327. this.barOpacity = 0;
  4328. this.hideDone = true;
  4329. }
  4330. this.isHiding = true;
  4331. }
  4332. if (offset < 0 && this.isHiding) {
  4333. this.hideDone = false;
  4334. this.getUIContext().animateTo({
  4335. duration: 300
  4336. }, () => {
  4337. this.topBarHeight = 50 + 0;
  4338. this.barOpacity = 1;
  4339. this.currentYOffset = 0;
  4340. this.isHiding = false;
  4341. });
  4342. }
  4343. }
  4344. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  4345. switch (item.type) {
  4346. case CommonConstants.TYPE_IS_DIR:
  4347. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  4348. let offsetB = 0
  4349. if(this.twoFingerType==4){
  4350. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4351. let cur = this.waterScroller.currentOffset()
  4352. if (cur && typeof cur.yOffset === 'number') {
  4353. offsetB = cur.yOffset
  4354. }
  4355. }
  4356. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  4357. }else
  4358. if (this.isGridMusic) {
  4359. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4360. let cur = this.scroller.currentOffset()
  4361. if (cur && typeof cur.yOffset === 'number') {
  4362. offsetB = cur.yOffset
  4363. }
  4364. }
  4365. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  4366. } else {
  4367. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4368. let cur = this.listScroller.currentOffset()
  4369. if (cur && typeof cur.yOffset === 'number') {
  4370. offsetB = cur.yOffset
  4371. }
  4372. }
  4373. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  4374. }
  4375. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  4376. this.showVerifyDialog()
  4377. this.currentTitleName = '私密音频'
  4378. this.currentTitleCover = $r('app.media.ic_avatar5')
  4379. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  4380. this.titleBarModel.setTitleName('最近播放')
  4381. this.currentTitleCover = $r('app.media.ic_avatar2')
  4382. this.currentTitleName = '最近播放'
  4383. //加载动画效果
  4384. this.updateListData(this.historyList, true)
  4385. // this.videoLocalList = this.historyList
  4386. if (ArrayUtil.isEmpty(this.historyList)) {
  4387. ToastUtil.showToast('最近播放记录空空如也')
  4388. } else {
  4389. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  4390. }
  4391. this.isHistory = true
  4392. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4393. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  4394. this.titleBarModel.setTitleName('我的收藏')
  4395. this.currentTitleName = '我的收藏'
  4396. this.currentTitleCover = $r('app.media.ic_avatar1')
  4397. //加载动画效果
  4398. this.updateListData(this.favList)
  4399. if (ArrayUtil.isEmpty(this.favList)) {
  4400. ToastUtil.showToast('无音乐收藏记录')
  4401. } else {
  4402. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  4403. }
  4404. this.isFavMusic = true
  4405. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4406. } else {
  4407. this.currentTitleName = item.name
  4408. this.currentPath = item.filePath
  4409. this.currentTitleCover = $r('app.media.ic_avatar5')
  4410. this.getSortedFiles(this.currentPath)
  4411. }
  4412. //进入歌单的时候的滚动位置在顶部
  4413. if(this.twoFingerType==4){
  4414. setTimeout(() => {
  4415. this.waterScroller.scrollEdge(Edge.Top)
  4416. this.scroller.scrollEdge(Edge.Top)
  4417. }, 380)
  4418. }else{
  4419. if (this.isGridMusic) {
  4420. this.scroller.scrollEdge(Edge.Top)
  4421. }
  4422. }
  4423. break;
  4424. case CommonConstants.TYPE_IS_ARTIST:
  4425. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  4426. let offsetA = 0
  4427. if(this.twoFingerType==4){
  4428. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4429. let cur = this.waterScroller.currentOffset()
  4430. if (cur && typeof cur.yOffset === 'number') {
  4431. offsetA = cur.yOffset
  4432. }
  4433. }
  4434. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  4435. }else
  4436. if (this.isGridMusic) {
  4437. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4438. let cur = this.scroller.currentOffset()
  4439. if (cur && typeof cur.yOffset === 'number') {
  4440. offsetA = cur.yOffset
  4441. }
  4442. }
  4443. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  4444. } else {
  4445. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4446. let cur = this.listScroller.currentOffset()
  4447. if (cur && typeof cur.yOffset === 'number') {
  4448. offsetA = cur.yOffset
  4449. }
  4450. }
  4451. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  4452. }
  4453. let mList = this.artistMap.get(item.name)
  4454. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  4455. Utility.doSortListAscending(mList)
  4456. this.isCanBack = true
  4457. this.titleBarModel.setTitleName(item.name)
  4458. this.currentTitleName = '艺术家:' + item.name
  4459. if (item.pixelMapPath) {
  4460. this.currentTitleCover = item.pixelMapPath
  4461. }
  4462. this.updateListData(mList)
  4463. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4464. }
  4465. //进入歌单的时候的滚动位置在顶部
  4466. if(this.twoFingerType==4){
  4467. setTimeout(() => {
  4468. this.waterScroller.scrollEdge(Edge.Top)
  4469. this.scroller.scrollEdge(Edge.Top)
  4470. }, 380)
  4471. }else{
  4472. if (this.isGridMusic) {
  4473. this.scroller.scrollEdge(Edge.Top)
  4474. }
  4475. }
  4476. break;
  4477. case CommonConstants.TYPE_IS_ALBUM:
  4478. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  4479. let offset = 0
  4480. if(this.twoFingerType==4){
  4481. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4482. let cur = this.waterScroller.currentOffset()
  4483. if (cur && typeof cur.yOffset === 'number') {
  4484. offset = cur.yOffset
  4485. }
  4486. }
  4487. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  4488. }else
  4489. if (this.isGridMusic) {
  4490. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4491. let cur = this.scroller.currentOffset()
  4492. if (cur && typeof cur.yOffset === 'number') {
  4493. offset = cur.yOffset
  4494. }
  4495. }
  4496. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  4497. } else {
  4498. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4499. let cur = this.listScroller.currentOffset()
  4500. if (cur && typeof cur.yOffset === 'number') {
  4501. offset = cur.yOffset
  4502. }
  4503. }
  4504. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4505. }
  4506. let albumList = this.albumMap.get(item.name)
  4507. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4508. Utility.doSortListAscending(albumList)
  4509. this.isCanBack = true
  4510. this.titleBarModel.setTitleName(item.name)
  4511. this.currentTitleName = '专辑:' + item.name
  4512. if (item.pixelMapPath) {
  4513. this.currentTitleCover = item.pixelMapPath
  4514. }
  4515. this.updateListData(albumList)
  4516. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4517. this.mScrollMap.set(item.name, this.selectedIndex)
  4518. }
  4519. //进入歌单的时候的滚动位置在顶部
  4520. if(this.twoFingerType==4){
  4521. setTimeout(() => {
  4522. this.waterScroller.scrollEdge(Edge.Top)
  4523. this.scroller.scrollEdge(Edge.Top)
  4524. }, 380)
  4525. }else{
  4526. if (this.isGridMusic) {
  4527. this.scroller.scrollEdge(Edge.Top)
  4528. }
  4529. }
  4530. break;
  4531. case CommonConstants.TYPE_IS_CSJAD:
  4532. return
  4533. break;
  4534. case CommonConstants.TYPE_LOCAL:
  4535. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4536. this.stop();
  4537. }
  4538. if (isFromSonPlayList||isOpen) { //点击来自右下角的播放列表
  4539. this.currentSong = item
  4540. if (index !== undefined) {
  4541. this.curIndex = index
  4542. }
  4543. this.songList = []
  4544. this.songList.push(item)
  4545. this.sonDataSource.pushArrayData(this.songList)
  4546. } else {
  4547. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4548. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4549. this.songList = globalVideoList
  4550. this.sonDataSource.pushArrayData(this.songList)
  4551. this.currentSong = globalVideoList[this.curIndex]
  4552. }
  4553. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  4554. this.videoUrl = this.currentSong.filePath
  4555. this.name = this.currentSong.name
  4556. this.cover = this.currentSong.pixelMapPath
  4557. this.artist = this.currentSong.artist
  4558. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  4559. LogUtil.info('this.currentSong.sampleRate =' + this.currentSong.sampleRate)
  4560. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  4561. console.info('onecold startPlayOrResumePlay 4547')
  4562. this.startPlayOrResumePlay()
  4563. break;
  4564. }
  4565. }
  4566. @Builder
  4567. PlayController() {
  4568. Column() {
  4569. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4570. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4571. Row() {
  4572. if(this.isHiCar()){
  4573. this.playConRigth()
  4574. Column(){
  4575. this.centerName()
  4576. }.layoutWeight(1)
  4577. .onClick(()=>{
  4578. this.showPlayerView()
  4579. })
  4580. this.playConLeft(false)
  4581. }else{
  4582. this.playConLeft()
  4583. this.playConRigth()
  4584. }
  4585. }
  4586. .width('100%')
  4587. .height(this.bottomBarHeight)
  4588. .justifyContent(FlexAlign.Center)
  4589. .hitTestBehavior(HitTestMode.Transparent)
  4590. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4591. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4592. // modalTransition: ModalTransition.DEFAULT,
  4593. transition: AnimationHelper.transitionInDown(666),
  4594. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4595. })
  4596. .padding({
  4597. left: 16,
  4598. right: 16
  4599. })
  4600. Line()
  4601. .width('100%')
  4602. .height(25)
  4603. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4604. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4605. }
  4606. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4607. }
  4608. @State isFrontWhite: boolean = false
  4609. @Builder
  4610. centerName() {
  4611. Column() {
  4612. Text(this.currentSong?.name)
  4613. .fontSize(16)
  4614. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  4615. .maxLines(1)
  4616. .fontColor($r('app.color.text_color'))
  4617. .fontWeight(500);
  4618. Row() {
  4619. Text(this.currentSong?.artist)
  4620. .margin({ top: 2 })
  4621. .fontSize(13)
  4622. .textAlign(TextAlign.Start)
  4623. .maxLines(1)
  4624. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  4625. .fontColor($r('app.color.text_color'));
  4626. }
  4627. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  4628. }
  4629. .alignItems(HorizontalAlign.Center)
  4630. }
  4631. @Builder
  4632. playConLeft(isLeft: boolean = true) {
  4633. Row() {
  4634. RotatingCover({ songLabel: this.currentSong?.pixelMapPath });
  4635. Column() {
  4636. Text(this.currentSong?.name)
  4637. .fontSize(16)
  4638. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  4639. .maxLines(1)
  4640. .fontColor($r('app.color.text_color'))
  4641. .fontWeight(500);
  4642. Row() {
  4643. Text(this.currentSong?.artist)
  4644. .margin({ top: 2 })
  4645. .fontSize(13)
  4646. .textAlign(TextAlign.Start)
  4647. .maxLines(1)
  4648. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  4649. .fontColor($r('app.color.text_color'));
  4650. }
  4651. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  4652. }
  4653. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  4654. .margin({ right: isLeft?22:10 })
  4655. .visibility(isLeft? Visibility.Visible:Visibility.None)
  4656. }
  4657. .padding({ right: 18 })
  4658. .layoutWeight(isLeft?1:0)
  4659. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4660. .onClick(() => {
  4661. this.showPlayerView()
  4662. })
  4663. }
  4664. //打开播放页
  4665. showPlayerView() {
  4666. if (ArrayUtil.isNotEmpty(this.songList)) {
  4667. this.isShowPlay = true;
  4668. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  4669. this.initLyric(lyricPath);
  4670. this.startAutoHide();
  4671. } else {
  4672. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  4673. }
  4674. }
  4675. @Builder
  4676. playConRigth() {
  4677. Row() {
  4678. Image($r('app.media.hm_previous'))
  4679. .height(28)
  4680. .width(28)
  4681. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4682. .margin({ left: 8, right: 16 })
  4683. .fillColor(this.themeColor)
  4684. .displayPriority(2)
  4685. .onClick(() => {
  4686. if (ArrayUtil.isNotEmpty(this.songList)) {
  4687. this.playPrevious()
  4688. } else {
  4689. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4690. }
  4691. })
  4692. //播放进度条
  4693. Stack() {
  4694. Progress({
  4695. value: Math.floor(this.progressValue),
  4696. type: ProgressType.Ring,
  4697. })
  4698. .color(this.themeColor)// 进度条前景色为灰色
  4699. .backgroundColor($r('app.color.index_background'))
  4700. .height(40)
  4701. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4702. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4703. .height(38)
  4704. .width(38)
  4705. .displayPriority(3)
  4706. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4707. .fillColor(this.themeColor)
  4708. .onClick(() => {
  4709. if (ArrayUtil.isNotEmpty(this.songList)) {
  4710. console.info('onecold playOrPause 4642')
  4711. this.playOrPause()
  4712. } else {
  4713. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4714. }
  4715. })
  4716. }
  4717. Image($r('app.media.hm_next'))
  4718. .height(28)
  4719. .width(28)
  4720. .margin({
  4721. right: 16,
  4722. left: 16
  4723. })
  4724. .fillColor(this.themeColor)
  4725. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4726. .displayPriority(2)
  4727. .onClick(() => {
  4728. if (ArrayUtil.isNotEmpty(this.songList)) {
  4729. this.playNext()
  4730. } else {
  4731. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4732. }
  4733. })
  4734. Image($r('app.media.hm_playlist'))
  4735. .height(28)
  4736. .width(28)
  4737. .displayPriority(1)
  4738. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4739. .fillColor(this.themeColor)
  4740. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4741. height: '95%',
  4742. dragBar: true,
  4743. showClose: true,
  4744. blurStyle: BlurStyle.Thin,
  4745. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4746. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4747. title: {
  4748. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4749. + `(${this.songList.length}首)`
  4750. }
  4751. })
  4752. .onClick(() => {
  4753. if (ArrayUtil.isNotEmpty(this.songList)) {
  4754. this.isShowSheet = !this.isShowSheet;
  4755. this.isFrontWhite = false
  4756. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4757. this.scrollIndex()
  4758. } else {
  4759. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4760. }
  4761. })
  4762. }
  4763. }
  4764. scrollIndex(){
  4765. if(this.curIndex>500)//条数太大的时候 滚动非常卡 导致闪退,先改为不滚
  4766. return
  4767. try {
  4768. setTimeout(() => {
  4769. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  4770. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  4771. })
  4772. }, 123)
  4773. }catch (error) {
  4774. console.error(`onecold scrollIndex出错: ${error}`);
  4775. }
  4776. }
  4777. //播放列表布局
  4778. @Builder
  4779. PlayListSheet() {
  4780. Column() {
  4781. this.PlayList()
  4782. }
  4783. .width('100%')
  4784. .height('100%')
  4785. }
  4786. @State titleStr: string = ''
  4787. @State ablumStr: string = ''
  4788. @State artistStr: string = ''
  4789. @State lyricConStr: string = ''
  4790. @State currentEditItem: string = ''
  4791. @State yearStr: string = ''
  4792. @State trackStr: string = ''
  4793. @State genreStr: string = ''
  4794. @State imagePathStr: string = ''
  4795. @State albumArtistStr: string = ''
  4796. @State composerStr: string = ''
  4797. @State lyricistStr: string = ''
  4798. @State commentStr: string = ''
  4799. @State discStr: string = ''
  4800. doUpdateData() {
  4801. setTimeout(() => {
  4802. if (this.modeType === 0) {
  4803. this.deleteCache(this.currentPath)
  4804. this.getSortedFiles(this.currentPath)
  4805. }
  4806. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4807. workerInstance.postMessage({ code: 3, data: this.context });
  4808. workerInstance.postMessage({ code: 4, data: this.context });
  4809. }, 999)
  4810. }
  4811. //编辑信息
  4812. async doEdit(item: VideoItem) {
  4813. if (!item) {
  4814. return
  4815. }
  4816. if (StrUtil.isEmpty(this.titleStr)) {
  4817. ToastUtil.showToast('标题不能为空')
  4818. return
  4819. }
  4820. // let doChangeLyric = false
  4821. // if(item.filePath==this.currentSong?.filePath){
  4822. // if(this.lyricConStr !== this.lyricContent){
  4823. // doChangeLyric = true
  4824. // }
  4825. // }else if(this.lyricConStr !== this.tempLyricContent){
  4826. // doChangeLyric = true
  4827. // }
  4828. //用户更改了封面,那就内嵌下封面
  4829. if(StrUtil.isNotEmpty(this.imagePathStr)){
  4830. const resultCover:boolean = await changeMusicCover(this.context,
  4831. item.filePath,this.imagePathStr,true);
  4832. this.imagePathStr = ''
  4833. if(resultCover){
  4834. ToastUtil.showToast('内嵌封面成功')
  4835. }
  4836. }
  4837. const metadata:FFMpegTags = {
  4838. title: this.titleStr,
  4839. artist: this.artistStr,
  4840. album: this.ablumStr,
  4841. // LYRICS:this.lyricConStr,
  4842. // USLT:this.lyricConStr,
  4843. TYER:this.yearStr,
  4844. genre:this.genreStr,
  4845. track:this.trackStr,
  4846. album_artist:this.albumArtistStr,
  4847. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  4848. COMPOSER:this.composerStr,
  4849. lyricist:this.lyricistStr,
  4850. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  4851. comment:this.commentStr,
  4852. // comm:this.commentStr,//ID3v2:使用 COMM(Comment)字段。
  4853. disc:this.discStr,
  4854. };
  4855. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  4856. const result:boolean = await repairAudioMetadata(
  4857. item.filePath,
  4858. this.lyricConStr,
  4859. metadata,
  4860. true
  4861. );
  4862. if (result) {
  4863. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  4864. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  4865. (success: boolean, error?: string) => {
  4866. // this.isShowEdit = false
  4867. if (success) {
  4868. console.log(" onecold 编辑信息成功,数据库已同步");
  4869. ToastUtil.showToast('内嵌音乐标签成功')
  4870. this.isShowMoreView = false
  4871. this.name = this.titleStr
  4872. if (item.filePath == this.currentSong?.filePath) {
  4873. this.currentSong.name = this.titleStr
  4874. this.artist = this.artistStr
  4875. this.currentSong.artist = this.artistStr
  4876. this.currentSong.album = this.ablumStr
  4877. this.currentSong.year = this.yearStr
  4878. this.currentSong.genre = this.genreStr
  4879. this.currentSong.track = this.trackStr
  4880. this.currentSong.lyricContent = this.lyricConStr
  4881. this.initLyric(item.filePath)
  4882. this.currentSong.ALBUMARTIST = this.albumArtistStr
  4883. this.currentSong.COMPOSER = this.composerStr
  4884. this.currentSong.LYRICIST = this.lyricistStr
  4885. this.currentSong.COMMENT = this.commentStr
  4886. }
  4887. this.doUpdateData()
  4888. } else {
  4889. // ToastUtil.showToast('保存失败' + error?.toString())
  4890. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4891. }
  4892. });
  4893. console.log(' onecold 元数据标签更新成功,');
  4894. } else {
  4895. ToastUtil.showToast('内嵌音乐标签失败')
  4896. console.log('onecold 内嵌音乐标签失败');
  4897. }
  4898. this.longItemFilePath = ''
  4899. this.tempLyricContent = ''
  4900. this.isShowEdit = false
  4901. }
  4902. updateLyricToDB() {
  4903. }
  4904. @Builder
  4905. editSheet(item: VideoItem) {
  4906. Scroll() {
  4907. Column() {
  4908. this.editDetail(item)
  4909. }
  4910. }
  4911. .width('100%')
  4912. .height('100%')
  4913. }
  4914. @Builder
  4915. editDetail(item: VideoItem) {
  4916. Column() {
  4917. if (item) {
  4918. Row() {
  4919. Stack() {
  4920. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  4921. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  4922. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  4923. item.pixelMapPath)
  4924. .fillColor(this.themeColor)
  4925. .height(88)
  4926. .width(88)
  4927. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  4928. .borderRadius(12)
  4929. .clip(true)
  4930. .opacity(this.opacityItem)// 绑定透明度
  4931. .margin({ left: 25 })
  4932. }
  4933. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  4934. .onClick(async () => {
  4935. const imagePath:string | undefined = await this.goSelectImage(item);
  4936. if (imagePath) {
  4937. //用户更改过图片
  4938. this.imagePathStr = imagePath
  4939. }
  4940. })
  4941. .width('28%')
  4942. Row() {
  4943. Column() {
  4944. Text(item.name)
  4945. .fontSize(17)
  4946. .maxLines(1)
  4947. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4948. .animation({
  4949. duration: 555,
  4950. curve: 'Linear',
  4951. })
  4952. .fontColor(this.themeColor)
  4953. .margin({ left: 8 })
  4954. Row() {
  4955. Text(item.artist)
  4956. .fontSize(14)
  4957. .maxLines(1)
  4958. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4959. .padding({ top: 8 })
  4960. .fontColor(this.themeColor)
  4961. .margin({ left: 8 })
  4962. }
  4963. }
  4964. .height('100%')
  4965. .width(100)
  4966. .layoutWeight(1)
  4967. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4968. .justifyContent(FlexAlign.Center)
  4969. .alignItems(HorizontalAlign.Start)
  4970. Column() {
  4971. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4972. Row(){
  4973. SymbolGlyph($r('sys.symbol.picture'))
  4974. .fontSize(18)
  4975. .fontColor([Color.White])
  4976. Text('获取封面')
  4977. .margin({ left: 4 })
  4978. .fontSize(11)
  4979. .fontColor(Color.White)
  4980. .fontWeight(480)
  4981. .textAlign(TextAlign.Center)
  4982. }
  4983. .justifyContent(FlexAlign.Center)
  4984. }
  4985. .height(38)
  4986. .width(100)
  4987. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4988. .backgroundColor(this.themeColor)
  4989. .stateEffect(true)
  4990. .margin({ right: 35 })
  4991. .onClick(async () => {
  4992. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  4993. this.showTipsDialog();
  4994. return; // Return empty string when no API is configured
  4995. }
  4996. const imagePath:string | undefined = await this.doSearchCover(item);
  4997. console.info('onecold imagePath = '+imagePath)
  4998. if (StrUtil.isNotEmpty(imagePath)) {
  4999. //用户更改过图片
  5000. this.imagePathStr = imagePath
  5001. ToastUtil.showToast('获取封面成功')
  5002. }else{
  5003. ToastUtil.showToast('获取封面失败,请重试')
  5004. }
  5005. })
  5006. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5007. Row(){
  5008. SymbolGlyph($r('sys.symbol.input_mode'))
  5009. .fontSize(18)
  5010. .fontColor([Color.White])
  5011. Text('获取歌词')
  5012. .margin({ left: 4 })
  5013. .fontSize(11)
  5014. .fontColor(Color.White)
  5015. .fontWeight(480)
  5016. .textAlign(TextAlign.Center)
  5017. }
  5018. .justifyContent(FlexAlign.Center)
  5019. }
  5020. .height(38)
  5021. .width(100)
  5022. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5023. .backgroundColor(this.themeColor)
  5024. .stateEffect(true)
  5025. .margin({ top: 9, right: 35 })
  5026. .onClick(async () => {
  5027. //判断有没有设置api
  5028. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  5029. if (StrUtil.isEmpty(apiUrl)) {
  5030. this.isLyricSetting = false
  5031. this.showTipsDialog()
  5032. return
  5033. }
  5034. let artist = item.artist
  5035. let title = item.name
  5036. if(!artist)
  5037. artist = ''
  5038. if(!title)
  5039. title = ''
  5040. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  5041. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5042. this.lyricConStr = res;
  5043. ToastUtil.showToast('获取歌词成功')
  5044. }else{
  5045. ToastUtil.showToast('获取歌词失败,请重试')
  5046. }
  5047. })
  5048. }
  5049. .justifyContent(FlexAlign.Start)
  5050. }
  5051. .height('100%')
  5052. .justifyContent(FlexAlign.Start)
  5053. .layoutWeight(1)
  5054. }
  5055. .width('100%')
  5056. .height(98)
  5057. Row() {
  5058. Text('标题:')
  5059. .fontSize(14)
  5060. .fontColor($r('app.color.text_color'))
  5061. .margin({ left: 22 })
  5062. TextInput({ text: item.name })
  5063. .height(40)
  5064. .maxLines(1)
  5065. .fontSize(14)
  5066. .layoutWeight(1)
  5067. .fontColor($r('app.color.text_color'))
  5068. .margin({ right: 20, left: 10 })
  5069. .onChange((val: string) => {
  5070. this.titleStr = val
  5071. })
  5072. }
  5073. .width('100%')
  5074. .margin({ top: 10, bottom: 10 })
  5075. .justifyContent(FlexAlign.Start)
  5076. Row() {
  5077. Text('艺术家:')
  5078. .fontSize(14)
  5079. .fontColor($r('app.color.text_color'))
  5080. .margin({ left: 22 })
  5081. TextInput({ text: item.artist })
  5082. .height(40)
  5083. .maxLines(1)
  5084. .fontSize(14)
  5085. .layoutWeight(1)
  5086. .fontColor($r('app.color.text_color'))
  5087. .margin({ right: 20, left: 10 })
  5088. .onChange((val: string) => {
  5089. this.artistStr = val
  5090. })
  5091. }
  5092. .width('100%')
  5093. .margin({ top: 10, bottom: 10 })
  5094. .justifyContent(FlexAlign.Start)
  5095. Row() {
  5096. Text('专辑名:')
  5097. .fontSize(14)
  5098. .fontColor($r('app.color.text_color'))
  5099. .margin({ left: 22 })
  5100. TextInput({ text: item.album })
  5101. .height(40)
  5102. .maxLines(1)
  5103. .fontSize(14)
  5104. .layoutWeight(1)
  5105. .fontColor($r('app.color.text_color'))
  5106. .margin({ right: 20, left: 10 })
  5107. .onChange((val: string) => {
  5108. this.ablumStr = val
  5109. })
  5110. }
  5111. .width('100%')
  5112. .margin({ top: 10, bottom: 10 })
  5113. .justifyContent(FlexAlign.Start)
  5114. Row() {
  5115. Column(){
  5116. Column(){
  5117. Text('歌词:')
  5118. .fontSize(14)
  5119. .fontColor($r('app.color.text_color'))
  5120. .margin({ top:9,left: 22 })
  5121. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5122. SymbolGlyph($r('sys.symbol.trash_fill'))
  5123. .fontSize(25)
  5124. .alignSelf(ItemAlign.Center)
  5125. .margin({ left: 22,top:25})
  5126. }
  5127. .backgroundColor(Color.Transparent)
  5128. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5129. Visibility.None:Visibility.Visible)
  5130. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5131. .onClick(()=>{
  5132. this.lyricConStr = ''
  5133. this.lyricContent = ''
  5134. this.tempLyricContent = ''
  5135. })
  5136. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5137. SymbolGlyph($r('sys.symbol.plus'))
  5138. .fontSize(25)
  5139. .alignSelf(ItemAlign.Center)
  5140. .margin({ left: 22,top:25})
  5141. }
  5142. .backgroundColor(Color.Transparent)
  5143. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5144. .onClick( ()=>{
  5145. this.callFilePickerSelectFileForLyric()
  5146. })
  5147. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5148. SymbolGlyph($r('sys.symbol.traditional_square'))
  5149. .fontSize(25)
  5150. .alignSelf(ItemAlign.Center)
  5151. .margin({ left: 22,top:25})
  5152. }
  5153. .backgroundColor(Color.Transparent)
  5154. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5155. Visibility.None:Visibility.Visible)
  5156. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5157. .onClick( ()=>{
  5158. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5159. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  5160. })
  5161. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5162. Image($r('app.media.jianti'))
  5163. .height(25)
  5164. .fillColor($r('app.color.text_color'))
  5165. .alignSelf(ItemAlign.Center)
  5166. .margin({ left: 22,top:25})
  5167. }
  5168. .backgroundColor(Color.Transparent)
  5169. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5170. Visibility.None:Visibility.Visible)
  5171. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5172. .onClick( ()=>{
  5173. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5174. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  5175. })
  5176. }
  5177. .layoutWeight(1)
  5178. }
  5179. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  5180. this.tempLyricContent })
  5181. .type(TextAreaType.NORMAL)
  5182. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  5183. .fontSize(14)
  5184. .layoutWeight(1)
  5185. .fontColor($r('app.color.text_color'))
  5186. .margin({ right: 20, left: 10 })
  5187. .onChange((val: string) => {
  5188. this.lyricConStr = val
  5189. })
  5190. }
  5191. .width('100%')
  5192. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  5193. .margin({ top: 10, bottom: 10 })
  5194. .justifyContent(FlexAlign.Start)
  5195. Row() {
  5196. Text('年份:')
  5197. .fontSize(14)
  5198. .fontColor($r('app.color.text_color'))
  5199. .margin({ left: 22 })
  5200. TextInput({ text: item.year })
  5201. .height(40)
  5202. .maxLines(1)
  5203. .fontSize(14)
  5204. .type(InputType.Number)
  5205. .layoutWeight(1)
  5206. .fontColor($r('app.color.text_color'))
  5207. .margin({ right: 20, left: 10 })
  5208. .onChange((val: string) => {
  5209. this.yearStr = val
  5210. })
  5211. }
  5212. .width('100%')
  5213. .margin({ top: 10, bottom: 10 })
  5214. .justifyContent(FlexAlign.Start)
  5215. Row() {
  5216. Text('音轨号:')
  5217. .fontSize(14)
  5218. .fontColor($r('app.color.text_color'))
  5219. .margin({ left: 22 })
  5220. TextInput({ text:item.track=='未知'?'': item.track })
  5221. .height(40)
  5222. .maxLines(1)
  5223. .fontSize(14)
  5224. .type(InputType.Number)
  5225. .layoutWeight(1)
  5226. .fontColor($r('app.color.text_color'))
  5227. .margin({ right: 20, left: 10 })
  5228. .onChange((val: string) => {
  5229. this.trackStr = val
  5230. })
  5231. }
  5232. .width('100%')
  5233. .margin({ top: 10, bottom: 10 })
  5234. .justifyContent(FlexAlign.Start)
  5235. Row() {
  5236. Text('碟号:')
  5237. .fontSize(14)
  5238. .fontColor($r('app.color.text_color'))
  5239. .margin({ left: 22 })
  5240. TextInput({ text:item.disc })
  5241. .height(40)
  5242. .maxLines(1)
  5243. .fontSize(14)
  5244. .type(InputType.Number)
  5245. .layoutWeight(1)
  5246. .fontColor($r('app.color.text_color'))
  5247. .margin({ right: 20, left: 10 })
  5248. .onChange((val: string) => {
  5249. this.discStr = val
  5250. })
  5251. }
  5252. .width('100%')
  5253. .margin({ top: 10, bottom: 10 })
  5254. .justifyContent(FlexAlign.Start)
  5255. Row() {
  5256. Text('风格:')
  5257. .fontSize(14)
  5258. .fontColor($r('app.color.text_color'))
  5259. .margin({ left: 22 })
  5260. TextInput({ text: item.genre })
  5261. .height(40)
  5262. .maxLines(1)
  5263. .fontSize(14)
  5264. .layoutWeight(1)
  5265. .fontColor($r('app.color.text_color'))
  5266. .margin({ right: 20, left: 10 })
  5267. .onChange((val: string) => {
  5268. this.genreStr = val
  5269. })
  5270. }
  5271. .width('100%')
  5272. .margin({ top: 10, bottom: 10 })
  5273. .justifyContent(FlexAlign.Start)
  5274. Row() {
  5275. Text('专辑艺术家:')
  5276. .fontSize(14)
  5277. .fontColor($r('app.color.text_color'))
  5278. .margin({ left: 22 })
  5279. TextInput({ text: item.ALBUMARTIST })
  5280. .height(40)
  5281. .maxLines(1)
  5282. .fontSize(14)
  5283. .layoutWeight(1)
  5284. .fontColor($r('app.color.text_color'))
  5285. .margin({ right: 20, left: 10 })
  5286. .onChange((val: string) => {
  5287. this.albumArtistStr = val
  5288. })
  5289. }
  5290. .width('100%')
  5291. .margin({ top: 10, bottom: 10 })
  5292. .justifyContent(FlexAlign.Start)
  5293. Row() {
  5294. Text('作曲:')
  5295. .fontSize(14)
  5296. .fontColor($r('app.color.text_color'))
  5297. .margin({ left: 22 })
  5298. TextInput({ text: item.COMPOSER })
  5299. .height(40)
  5300. .maxLines(1)
  5301. .fontSize(14)
  5302. .layoutWeight(1)
  5303. .fontColor($r('app.color.text_color'))
  5304. .margin({ right: 20, left: 10 })
  5305. .onChange((val: string) => {
  5306. this.composerStr = val
  5307. })
  5308. }
  5309. .width('100%')
  5310. .margin({ top: 10, bottom: 10 })
  5311. .justifyContent(FlexAlign.Start)
  5312. Row() {
  5313. Text('作词:')
  5314. .fontSize(14)
  5315. .fontColor($r('app.color.text_color'))
  5316. .margin({ left: 22 })
  5317. TextInput({ text: item.LYRICIST })
  5318. .height(40)
  5319. .maxLines(1)
  5320. .fontSize(14)
  5321. .layoutWeight(1)
  5322. .fontColor($r('app.color.text_color'))
  5323. .margin({ right: 20, left: 10 })
  5324. .onChange((val: string) => {
  5325. this.lyricistStr = val
  5326. })
  5327. }
  5328. .width('100%')
  5329. .margin({ top: 10, bottom: 10 })
  5330. .justifyContent(FlexAlign.Start)
  5331. Row() {
  5332. Text('注释:')
  5333. .fontSize(14)
  5334. .fontColor($r('app.color.text_color'))
  5335. .margin({ left: 22 })
  5336. TextInput({ text: item.COMMENT })
  5337. .height(40)
  5338. .maxLines(1)
  5339. .fontSize(14)
  5340. .layoutWeight(1)
  5341. .fontColor($r('app.color.text_color'))
  5342. .margin({ right: 20, left: 10 })
  5343. .onChange((val: string) => {
  5344. this.commentStr = val
  5345. })
  5346. }
  5347. .width('100%')
  5348. .margin({ top: 10, bottom: 10 })
  5349. .justifyContent(FlexAlign.Start)
  5350. Row() {
  5351. Button('保存')
  5352. .fontColor(Color.White)
  5353. .layoutWeight(1)
  5354. .height(50)
  5355. .width(100)
  5356. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5357. .backgroundColor(this.themeColor)
  5358. .stateEffect(true)
  5359. .margin({ right: 20, bottom: 20 })
  5360. .onClick(async () => {
  5361. this.doEdit(item)
  5362. })
  5363. Button('取消')
  5364. .fontColor(Color.White)
  5365. .layoutWeight(1)
  5366. .height(50)
  5367. .width(100)
  5368. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5369. .backgroundColor(this.themeColor)
  5370. .stateEffect(true)
  5371. .margin({ left: 20, bottom: 20 })
  5372. .onClick(async () => {
  5373. if(this.isGridMusic){
  5374. this.longItemFilePath =''
  5375. }else{
  5376. this.isShowEdit = false
  5377. }
  5378. this.setEditStrEmpty()
  5379. if(this.isShowPlay){
  5380. this.isShowEdit = false
  5381. }
  5382. })
  5383. }
  5384. .margin({
  5385. left: 38,
  5386. right: 38,
  5387. top: 10,
  5388. bottom: 10
  5389. })
  5390. .width(250)
  5391. .height(60)
  5392. }
  5393. }
  5394. .margin({ bottom: 20 })
  5395. }
  5396. setEditStrEmpty(){
  5397. this.imagePathStr = ''
  5398. this.lyricConStr = ''
  5399. this.artistStr = ''
  5400. this.titleStr = ''
  5401. this.ablumStr = ''
  5402. this.genreStr = ''
  5403. this.yearStr = ''
  5404. this.trackStr = ''
  5405. this.albumArtistStr = ''
  5406. this.composerStr = ''
  5407. this.lyricistStr = ''
  5408. this.commentStr = ''
  5409. this.discStr = ''
  5410. }
  5411. @Builder
  5412. detailSheet(item:VideoItem) {
  5413. Scroll() {
  5414. Column() {
  5415. this.songDetail(item)
  5416. }
  5417. }
  5418. .width('100%')
  5419. .height('100%')
  5420. }
  5421. @Builder
  5422. songDetail(currentItem:VideoItem) {
  5423. Column() {
  5424. if (currentItem) {
  5425. Row() {
  5426. Stack() {
  5427. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  5428. currentItem.pixelMapPath)
  5429. .fillColor(this.themeColor)
  5430. .height(80)
  5431. .width(80)
  5432. .borderRadius(10)
  5433. .opacity(this.opacityItem)// 绑定透明度
  5434. .margin({ left: 22 })
  5435. }
  5436. Column() {
  5437. Column() {
  5438. Text(currentItem.name)
  5439. .fontSize(16)
  5440. .maxLines(1)
  5441. .animation({
  5442. duration: 555,
  5443. curve: 'Linear',
  5444. })
  5445. .fontColor($r('app.color.text_color'))
  5446. .margin({ left: 15 })
  5447. }
  5448. .height('100%')
  5449. .width('100%')
  5450. .justifyContent(FlexAlign.Center)
  5451. .alignItems(HorizontalAlign.Start)
  5452. }
  5453. .height('100%')
  5454. }
  5455. .width('100%')
  5456. .height(90)
  5457. .justifyContent(FlexAlign.SpaceBetween)
  5458. Row() {
  5459. Text('艺术家:')
  5460. .fontSize(14)
  5461. .fontColor($r('app.color.text_color'))
  5462. .margin({ left: 22 })
  5463. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  5464. .fontSize(14)
  5465. .fontColor($r('app.color.text_color'))
  5466. .margin({ left: 10 })
  5467. .layoutWeight(1)
  5468. }
  5469. .width('100%')
  5470. .margin({ top: 10, bottom: 10 })
  5471. .justifyContent(FlexAlign.Start)
  5472. Row() {
  5473. Text('专辑名:')
  5474. .fontSize(14)
  5475. .fontColor($r('app.color.text_color'))
  5476. .margin({ left: 22 })
  5477. Text(currentItem?.album ?currentItem.album : '未知专辑')
  5478. .fontSize(14)
  5479. .margin({ left: 10 })
  5480. .fontColor($r('app.color.text_color'))
  5481. .layoutWeight(1)
  5482. }
  5483. .width('100%')
  5484. .margin({ top: 10, bottom: 10 })
  5485. .justifyContent(FlexAlign.Start)
  5486. Row() {
  5487. Text('时长:')
  5488. .fontSize(14)
  5489. .fontColor($r('app.color.text_color'))
  5490. .margin({ left: 22 })
  5491. Text(StrUtil.isEmpty(currentItem.duration)?
  5492. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  5493. .fontSize(14)
  5494. .margin({ left: 10 })
  5495. .fontColor($r('app.color.text_color'))
  5496. .layoutWeight(1)
  5497. }
  5498. .width('100%')
  5499. .margin({ top: 10, bottom: 10 })
  5500. .justifyContent(FlexAlign.Start)
  5501. Row() {
  5502. Text('采样率:')
  5503. .fontSize(14)
  5504. .fontColor($r('app.color.text_color'))
  5505. .margin({ left: 22 })
  5506. Text(Utility.convertToKHz(currentItem.sampleRate))
  5507. .fontSize(14)
  5508. .margin({ left: 10 })
  5509. .fontColor($r('app.color.text_color'))
  5510. .layoutWeight(1)
  5511. }
  5512. .width('100%')
  5513. .margin({ top: 10, bottom: 10 })
  5514. .justifyContent(FlexAlign.Start)
  5515. Row() {
  5516. Text('比特率:')
  5517. .fontSize(14)
  5518. .fontColor($r('app.color.text_color'))
  5519. .margin({ left: 22 })
  5520. Text(currentItem.bit_rate)
  5521. .fontSize(14)
  5522. .margin({ left: 10 })
  5523. .fontColor($r('app.color.text_color'))
  5524. .layoutWeight(1)
  5525. }
  5526. .width('100%')
  5527. .margin({ top: 10, bottom: 10 })
  5528. .justifyContent(FlexAlign.Start)
  5529. Row() {
  5530. Text('位深:')
  5531. .fontSize(14)
  5532. .fontColor($r('app.color.text_color'))
  5533. .margin({ left: 22 })
  5534. Text(`${currentItem.bits_per_raw_sample} bits`)
  5535. .fontSize(14)
  5536. .margin({ left: 10 })
  5537. .fontColor($r('app.color.text_color'))
  5538. .layoutWeight(1)
  5539. }
  5540. .width('100%')
  5541. .margin({ top: 10, bottom: 10 })
  5542. .justifyContent(FlexAlign.Start)
  5543. Row() {
  5544. Text('声道:')
  5545. .fontSize(14)
  5546. .fontColor($r('app.color.text_color'))
  5547. .margin({ left: 22 })
  5548. Text(`${currentItem.channels}`)
  5549. .fontSize(14)
  5550. .margin({ left: 10 })
  5551. .fontColor($r('app.color.text_color'))
  5552. .layoutWeight(1)
  5553. }
  5554. .width('100%')
  5555. .margin({ top: 10, bottom: 10 })
  5556. .justifyContent(FlexAlign.Start)
  5557. Row() {
  5558. Text('声道布局:')
  5559. .fontSize(14)
  5560. .fontColor($r('app.color.text_color'))
  5561. .margin({ left: 22 })
  5562. Text(`${currentItem.channel_layout}`)
  5563. .fontSize(14)
  5564. .margin({ left: 10 })
  5565. .fontColor($r('app.color.text_color'))
  5566. .layoutWeight(1)
  5567. }
  5568. .width('100%')
  5569. .margin({ top: 10, bottom: 10 })
  5570. .justifyContent(FlexAlign.Start)
  5571. Row() {
  5572. Text('起始播放点:')
  5573. .fontSize(14)
  5574. .fontColor($r('app.color.text_color'))
  5575. .margin({ left: 22 })
  5576. Text(`${currentItem.start_time}`)
  5577. .fontSize(14)
  5578. .margin({ left: 10 })
  5579. .fontColor($r('app.color.text_color'))
  5580. .layoutWeight(1)
  5581. }
  5582. .width('100%')
  5583. .margin({ top: 10, bottom: 10 })
  5584. .justifyContent(FlexAlign.Start)
  5585. Row() {
  5586. Text('风格:')
  5587. .fontSize(14)
  5588. .fontColor($r('app.color.text_color'))
  5589. .margin({ left: 22 })
  5590. Text(currentItem.genre)
  5591. .fontSize(14)
  5592. .margin({ left: 10 })
  5593. .fontColor($r('app.color.text_color'))
  5594. .layoutWeight(1)
  5595. }
  5596. .width('100%')
  5597. .margin({ top: 10, bottom: 10 })
  5598. .justifyContent(FlexAlign.Start)
  5599. Row() {
  5600. Text('发行时间:')
  5601. .fontSize(14)
  5602. .fontColor($r('app.color.text_color'))
  5603. .margin({ left: 22 })
  5604. Text(currentItem.year)
  5605. .fontSize(14)
  5606. .margin({ left: 10 })
  5607. .fontColor($r('app.color.text_color'))
  5608. .layoutWeight(1)
  5609. }
  5610. .width('100%')
  5611. .margin({ top: 10, bottom: 10 })
  5612. .justifyContent(FlexAlign.Start)
  5613. Row() {
  5614. Text('质量评分:')
  5615. .fontSize(14)
  5616. .fontColor($r('app.color.text_color'))
  5617. .margin({ left: 22 })
  5618. Text(currentItem.probe_score+"")
  5619. .fontSize(14)
  5620. .margin({ left: 10 })
  5621. .fontColor($r('app.color.text_color'))
  5622. .layoutWeight(1)
  5623. }
  5624. .width('100%')
  5625. .margin({ top: 10, bottom: 10 })
  5626. .justifyContent(FlexAlign.Start)
  5627. Row() {
  5628. Text('音轨号:')
  5629. .fontSize(14)
  5630. .fontColor($r('app.color.text_color'))
  5631. .margin({ left: 22 })
  5632. Text(currentItem.track)
  5633. .fontSize(14)
  5634. .margin({ left: 10 })
  5635. .fontColor($r('app.color.text_color'))
  5636. .layoutWeight(1)
  5637. }
  5638. .width('100%')
  5639. .margin({ top: 10, bottom: 10 })
  5640. .justifyContent(FlexAlign.Start)
  5641. Row() {
  5642. Text('碟号:')
  5643. .fontSize(14)
  5644. .fontColor($r('app.color.text_color'))
  5645. .margin({ left: 22 })
  5646. Text(currentItem.disc)
  5647. .fontSize(14)
  5648. .margin({ left: 10 })
  5649. .fontColor($r('app.color.text_color'))
  5650. .layoutWeight(1)
  5651. }
  5652. .width('100%')
  5653. .margin({ top: 10, bottom: 10 })
  5654. .justifyContent(FlexAlign.Start)
  5655. Row() {
  5656. Text('专辑艺术家:')
  5657. .fontSize(14)
  5658. .fontColor($r('app.color.text_color'))
  5659. .margin({ left: 22 })
  5660. Text(currentItem.ALBUMARTIST)
  5661. .fontSize(14)
  5662. .margin({ left: 10 })
  5663. .fontColor($r('app.color.text_color'))
  5664. .layoutWeight(1)
  5665. }
  5666. .width('100%')
  5667. .margin({ top: 10, bottom: 10 })
  5668. .justifyContent(FlexAlign.Start)
  5669. Row() {
  5670. Text('作曲家:')
  5671. .fontSize(14)
  5672. .fontColor($r('app.color.text_color'))
  5673. .margin({ left: 22 })
  5674. Text(currentItem.COMPOSER)
  5675. .fontSize(14)
  5676. .margin({ left: 10 })
  5677. .fontColor($r('app.color.text_color'))
  5678. .layoutWeight(1)
  5679. }
  5680. .width('100%')
  5681. .margin({ top: 10, bottom: 10 })
  5682. .justifyContent(FlexAlign.Start)
  5683. Row() {
  5684. Text('作词家:')
  5685. .fontSize(14)
  5686. .fontColor($r('app.color.text_color'))
  5687. .margin({ left: 22 })
  5688. Text(currentItem.LYRICIST)
  5689. .fontSize(14)
  5690. .margin({ left: 10 })
  5691. .fontColor($r('app.color.text_color'))
  5692. .layoutWeight(1)
  5693. }
  5694. .width('100%')
  5695. .margin({ top: 10, bottom: 10 })
  5696. .justifyContent(FlexAlign.Start)
  5697. Row() {
  5698. Text('注释:')
  5699. .fontSize(14)
  5700. .fontColor($r('app.color.text_color'))
  5701. .margin({ left: 22 })
  5702. Text(currentItem.COMMENT)
  5703. .fontSize(14)
  5704. .margin({ left: 10 })
  5705. .fontColor($r('app.color.text_color'))
  5706. .layoutWeight(1)
  5707. }
  5708. .width('100%')
  5709. .margin({ top: 10, bottom: 10 })
  5710. .justifyContent(FlexAlign.Start)
  5711. Row() {
  5712. Text('格式:')
  5713. .fontSize(14)
  5714. .fontColor($r('app.color.text_color'))
  5715. .margin({ left: 22 })
  5716. Text(Utility.formatMimeType(currentItem.mimeType))
  5717. .fontSize(14)
  5718. .margin({ left: 10 })
  5719. .fontColor($r('app.color.text_color'))
  5720. .layoutWeight(1)
  5721. }
  5722. .width('100%')
  5723. .margin({ top: 10, bottom: 10 })
  5724. .justifyContent(FlexAlign.Start)
  5725. Row() {
  5726. Text('播放次数:')
  5727. .fontSize(14)
  5728. .fontColor($r('app.color.text_color'))
  5729. .margin({ left: 22 })
  5730. Text(currentItem.playCount?.toString())
  5731. .fontSize(14)
  5732. .margin({ left: 10 })
  5733. .fontColor($r('app.color.text_color'))
  5734. .layoutWeight(1)
  5735. }
  5736. .width('100%')
  5737. .margin({ top: 10, bottom: 10 })
  5738. .justifyContent(FlexAlign.Start)
  5739. Row() {
  5740. Text('流数量:')
  5741. .fontSize(14)
  5742. .fontColor($r('app.color.text_color'))
  5743. .margin({ left: 22 })
  5744. Text(currentItem.nb_streams?.toString())
  5745. .fontSize(14)
  5746. .margin({ left: 10 })
  5747. .fontColor($r('app.color.text_color'))
  5748. .layoutWeight(1)
  5749. }
  5750. .width('100%')
  5751. .margin({ top: 10, bottom: 10 })
  5752. .justifyContent(FlexAlign.Start)
  5753. Row() {
  5754. Text('文件大小:')
  5755. .fontSize(14)
  5756. .fontColor($r('app.color.text_color'))
  5757. .margin({ left: 22 })
  5758. Text(currentItem.size)
  5759. .fontSize(14)
  5760. .margin({ left: 10 })
  5761. .fontColor($r('app.color.text_color'))
  5762. .layoutWeight(1)
  5763. }
  5764. .width('100%')
  5765. .margin({ top: 10, bottom: 10 })
  5766. .justifyContent(FlexAlign.Start)
  5767. Row() {
  5768. Text('文件名:')
  5769. .fontSize(14)
  5770. .fontColor($r('app.color.text_color'))
  5771. .margin({ left: 22 })
  5772. Text(currentItem.fileName)
  5773. .fontSize(14)
  5774. .margin({ left: 10 })
  5775. .fontColor($r('app.color.text_color'))
  5776. .layoutWeight(1)
  5777. }
  5778. .width('100%')
  5779. .margin({ top: 10, bottom: 10 })
  5780. .justifyContent(FlexAlign.Start)
  5781. Row() {
  5782. Text('修改时间:')
  5783. .fontSize(14)
  5784. .fontColor($r('app.color.text_color'))
  5785. .margin({ left: 22 })
  5786. Text(currentItem.cTime)
  5787. .fontSize(14)
  5788. .margin({ left: 10 })
  5789. .fontColor($r('app.color.text_color'))
  5790. .layoutWeight(1)
  5791. }
  5792. .width('100%')
  5793. .margin({ top: 10, bottom: 10 })
  5794. .justifyContent(FlexAlign.Start)
  5795. Row() {
  5796. Text('存放目录:')
  5797. .fontSize(14)
  5798. .fontColor($r('app.color.text_color'))
  5799. .margin({ left: 22 })
  5800. Text(currentItem.filePath)
  5801. .fontSize(12)
  5802. .margin({ left: 10 })
  5803. .fontColor($r('app.color.text_color'))
  5804. .layoutWeight(1)
  5805. }
  5806. .margin({ top: 10, bottom: 10 })
  5807. .width('100%')
  5808. .justifyContent(FlexAlign.Start)
  5809. Row() {
  5810. Text('内嵌歌词:')
  5811. .fontSize(14)
  5812. .fontColor($r('app.color.text_color'))
  5813. .margin({ left: 22 })
  5814. Text(currentItem.lyricContent)
  5815. .fontSize(12)
  5816. .copyOption(CopyOptions.InApp)
  5817. .margin({ left: 10 })
  5818. .fontColor($r('app.color.text_color'))
  5819. .layoutWeight(1)
  5820. }
  5821. .margin({ top: 10, bottom: 10 })
  5822. .width('100%')
  5823. .justifyContent(FlexAlign.Start)
  5824. }
  5825. }
  5826. .margin({ bottom: 20 })
  5827. }
  5828. //定时关闭布局
  5829. @Builder
  5830. TimeCloseSheet() {
  5831. Scroll() {
  5832. Column() {
  5833. this.TimeClose()
  5834. }
  5835. }
  5836. .width('100%')
  5837. .height('100%')
  5838. }
  5839. //倒计时关闭音乐,退出App功能实现。
  5840. @State selectedMinutes: number = 0 // 0表示未开启
  5841. @State remainingSeconds: number = 0
  5842. // 预设时间选项
  5843. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  5844. private formatTime(seconds: number): string {
  5845. const mins = Math.floor(seconds / 60)
  5846. const secs = seconds % 60
  5847. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  5848. }
  5849. // 开始倒计时
  5850. private handleTimeSelect(minutes: number) {
  5851. if (minutes === this.selectedMinutes) {
  5852. this.stopCountdown();
  5853. this.selectedMinutes = 0;
  5854. return;
  5855. }
  5856. this.selectedMinutes = minutes;
  5857. this.remainingSeconds = minutes * 60;
  5858. this.startCountdown(); // 新增调用
  5859. }
  5860. @Builder
  5861. TimeClose() {
  5862. Column() {
  5863. // 倒计时显示区域
  5864. Text(this.selectedMinutes > 0 ?
  5865. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  5866. "定时关闭未开启")
  5867. .fontSize(17)
  5868. .fontColor($r('app.color.text_color'))
  5869. .margin({ top: 2, bottom: 8 });
  5870. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  5871. ForEach(this.presetTimes, (minutes: number, index: number) => {
  5872. // 单行时间选项容器
  5873. Row() {
  5874. // 文字描述区域
  5875. Text(this.getDisplayText(minutes))
  5876. .fontSize(15)
  5877. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  5878. $r('app.color.text_color'))// 选中态颜色变化
  5879. .textAlign(TextAlign.Start)
  5880. .layoutWeight(1); // 占据剩余空间
  5881. // 复选框样式的选择器
  5882. Row() {
  5883. if (minutes === this.selectedMinutes) {
  5884. // 选中状态 - 带勾号的圆形复选框
  5885. Row() {
  5886. // 使用系统内置的勾号图标
  5887. Image($r('sys.media.ohos_ic_public_ok'))
  5888. .width(14)
  5889. .height(14)
  5890. .fillColor(Color.White)
  5891. }
  5892. .width(24)
  5893. .height(24)
  5894. .borderRadius(12)
  5895. .backgroundColor(this.themeColor)
  5896. .justifyContent(FlexAlign.Center)
  5897. .alignItems(VerticalAlign.Center)
  5898. } else {
  5899. // 未选中状态的圆形边框
  5900. Row()
  5901. .width(24)
  5902. .height(24)
  5903. .borderRadius(12)
  5904. .border({
  5905. width: 2,
  5906. color: $r('app.color.text_color'),
  5907. style: BorderStyle.Solid
  5908. })
  5909. .backgroundColor(Color.Transparent)
  5910. }
  5911. }
  5912. .width(24)
  5913. .height(24)
  5914. .margin({ left: 20 })
  5915. .justifyContent(FlexAlign.Center)
  5916. .alignItems(VerticalAlign.Center)
  5917. }
  5918. .width('100%')
  5919. .padding({
  5920. top: 18,
  5921. bottom: 18,
  5922. left: 18,
  5923. right: 18
  5924. })
  5925. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  5926. $r('app.color.bottom_control_background')) // 选中背景高亮
  5927. .borderRadius(12)
  5928. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  5929. .margin({ bottom: 18 })
  5930. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  5931. });
  5932. }
  5933. .width('100%')
  5934. .padding(16)
  5935. }
  5936. }
  5937. // 获取显示文本
  5938. private getDisplayText(minutes: number): string {
  5939. if (minutes === -1) {
  5940. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  5941. }
  5942. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  5943. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  5944. }
  5945. // 处理选择事件
  5946. private handleSelect(minutes: number): void {
  5947. if (minutes === -1) { // 自定义
  5948. // 弹出自定义时间对话框
  5949. DialogHelper.showTextInputDialog({
  5950. title: '自定义时间',
  5951. maskColor: Color.Transparent,
  5952. inputType: InputType.Number,
  5953. text: '',
  5954. onChange: (text) => {
  5955. console.error("onChange: " + text);
  5956. },
  5957. onAction: (action, dialogId, content) => {
  5958. if (action == DialogAction.TWO) {
  5959. const customMinutes = Number(content);
  5960. if (customMinutes > 0) {
  5961. this.handleTimeSelect(customMinutes); // 设置自定义时间
  5962. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  5963. }
  5964. }
  5965. }
  5966. });
  5967. } else {
  5968. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  5969. }
  5970. }
  5971. // 添加定时器引用
  5972. private timerId: number = -1;
  5973. // 启动/重置倒计时
  5974. private startCountdown() {
  5975. // 清除旧定时器
  5976. if (this.timerId !== -1) {
  5977. clearInterval(this.timerId);
  5978. }
  5979. // 创建新定时器
  5980. if (this.selectedMinutes > 0) {
  5981. this.timerId = setInterval(() => {
  5982. if (this.remainingSeconds === 15) {
  5983. this.showConfirmationDialog();
  5984. }
  5985. if (this.remainingSeconds > 0) {
  5986. this.remainingSeconds -= 1;
  5987. } else {
  5988. this.stopCountdown();
  5989. this.handleTimeout();
  5990. }
  5991. }, 1000);
  5992. }
  5993. }
  5994. // 15倒计时后再次提示显示确认是否关闭App对话框
  5995. private showConfirmationDialog() {
  5996. DialogHelper.showAlertDialog({
  5997. backgroundColor: $r('app.color.btn_green'),
  5998. title: '确认关闭',
  5999. maskColor: Color.Transparent,
  6000. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  6001. borderStyle: BorderStyle.Dashed,
  6002. primaryButton: '暂不关闭',
  6003. secondaryButton: '确定',
  6004. onAction: (action) => {
  6005. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  6006. this.stopCountdown();
  6007. this.selectedMinutes = 0
  6008. } else if (action == DialogAction.TWO) {
  6009. }
  6010. }
  6011. })
  6012. }
  6013. // 停止倒计时
  6014. private stopCountdown() {
  6015. if (this.timerId !== -1) {
  6016. clearInterval(this.timerId);
  6017. this.timerId = -1;
  6018. }
  6019. }
  6020. // 超时处理
  6021. private handleTimeout() {
  6022. // 执行播放器关闭逻辑
  6023. this.selectedMinutes = 0;
  6024. ToastUtil.showToast(" 定时关闭已完成");
  6025. this.stop(); // 假设存在的播放器实例
  6026. //退出APP
  6027. const mContext = getContext(this) as common.UIAbilityContext
  6028. mContext.terminateSelf();
  6029. AvSessionController.getInstance(true).unregisterSessionListener()
  6030. }
  6031. //倒计时关闭音乐,退出App功能实现结束。
  6032. //播放列表的拖动List 重新排序
  6033. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  6034. //左滑操作 移动文件 重命名 删除等操作
  6035. @Builder
  6036. sonButton(item: VideoItem, index: number, filePath: string) {
  6037. Row() {
  6038. //加入下一首播放
  6039. Button() {
  6040. Image($r('app.media.next_to_play'))
  6041. .fillColor(Color.White)
  6042. .width(20)
  6043. }
  6044. .width(40)
  6045. .height(40)
  6046. .type(ButtonType.Circle)
  6047. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6048. .backgroundColor(this.themeColor)
  6049. .margin(5)
  6050. .onClick(() => {
  6051. this.addToNextPlay(item);
  6052. })
  6053. Button() {
  6054. Image($r('app.media.close'))
  6055. .fillColor(Color.White)
  6056. .width(20)
  6057. }
  6058. .width(40)
  6059. .height(40)
  6060. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6061. .type(ButtonType.Circle)
  6062. .backgroundColor(this.themeColor)
  6063. .margin(5)
  6064. .onClick(() => {
  6065. this.songList.splice(Number(index), 1)
  6066. this.sonDataSource.pushArrayData(this.songList)
  6067. })
  6068. Button() {
  6069. Image($r('app.media.share2'))
  6070. .fillColor(Color.White)
  6071. .width(20)
  6072. }
  6073. .width(40)
  6074. .height(40)
  6075. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6076. .type(ButtonType.Circle)
  6077. .backgroundColor(this.themeColor)
  6078. .margin(5)
  6079. .onClick(() => {
  6080. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6081. })
  6082. }
  6083. }
  6084. itemMoveSon(index: number, newIndex: number): void {
  6085. if (newIndex < 0 || newIndex >= this.songList.length) {
  6086. return;
  6087. }
  6088. let tmp = this.songList.splice(index, 1);
  6089. this.songList.splice(newIndex, 0, tmp[0]);
  6090. this.sonDataSource.pushArrayData(this.songList)
  6091. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  6092. }
  6093. @Builder
  6094. PlayList() {
  6095. List({ scroller: this.playListScroller }) {
  6096. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  6097. ListItem() {
  6098. this.MusicItemSon(item, index)
  6099. }
  6100. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  6101. .animation({
  6102. duration: 666,
  6103. curve: 'ease-in-out' // 可选动画曲线
  6104. })
  6105. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  6106. TransitionEffect.scale({ x: 0, y: 0 })))
  6107. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6108. //拖动List关键代码开始
  6109. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  6110. .zIndex(this.dragItem === index ? 1 : 0)
  6111. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  6112. .gesture(
  6113. GestureGroup(GestureMode.Sequence,
  6114. LongPressGesture({ repeat: true })
  6115. .onAction((event?: GestureEvent) => {
  6116. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6117. this.scaleItem = index
  6118. })
  6119. })
  6120. .onActionEnd(() => {
  6121. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6122. this.scaleItem = -1
  6123. })
  6124. }),
  6125. PanGesture({ fingers: 1, direction: null, distance: 0 })
  6126. .onActionStart(() => {
  6127. this.dragItem = index // 记录当前拖动项索引
  6128. this.dragRefOffset = 0 // 重置偏移基准
  6129. })
  6130. .onActionUpdate((event: GestureEvent) => {
  6131. this.offsetY = event.offsetY - this.dragRefOffset;
  6132. this.neighborItem = -1;
  6133. let indexA = this.songList.indexOf(item);
  6134. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6135. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6136. let value: number = 0;
  6137. if (this.offsetY < 0) {
  6138. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6139. this.neighborItem = indexA - 1;
  6140. this.neighborScale = 1 - value / 20;
  6141. } else if (this.offsetY > 0) {
  6142. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6143. this.neighborItem = indexA + 1;
  6144. this.neighborScale = 1 - value / 20;
  6145. }
  6146. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  6147. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6148. this.offsetY -= this.ITEM_INTV;
  6149. this.dragRefOffset += this.ITEM_INTV;
  6150. this.itemMoveSon(indexA, indexA + 1);
  6151. });
  6152. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6153. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6154. this.offsetY += this.ITEM_INTV;
  6155. this.dragRefOffset -= this.ITEM_INTV;
  6156. this.itemMoveSon(indexA, indexA - 1);
  6157. });
  6158. }
  6159. })
  6160. .onActionEnd((event: GestureEvent) => {
  6161. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6162. this.dragItem = -1
  6163. this.neighborItem = -1
  6164. })
  6165. animateTo({
  6166. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6167. }, () => {
  6168. this.scaleItem = -1
  6169. })
  6170. })
  6171. )
  6172. .onCancel(() => {
  6173. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6174. this.dragItem = -1
  6175. this.neighborItem = -1
  6176. })
  6177. animateTo({
  6178. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6179. }, () => {
  6180. this.scaleItem = -1
  6181. })
  6182. })
  6183. ) //拖动List关键代码结束
  6184. .onClick(() => {
  6185. this.doPlay(item, index, true)
  6186. })
  6187. }, (item: VideoItem) => item.filePath)
  6188. }
  6189. .width('100%')
  6190. .height('100%')
  6191. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  6192. // .animation({ duration: 500, curve: Curve.Ease }))
  6193. .cachedCount(10)
  6194. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6195. .gesture(PinchGesture({ fingers: 2 })
  6196. .onActionEnd((event: GestureEvent) => {
  6197. this.setSonListTwoFingers()
  6198. })
  6199. .onActionUpdate(e => {
  6200. this.scaleValue = this.pinchValue * e.scale
  6201. })
  6202. .onActionStart(e => {
  6203. }))
  6204. .padding({
  6205. bottom: 0
  6206. })
  6207. }
  6208. setSonListTwoFingers() {
  6209. this.pinchValue = this.scaleValue;
  6210. Logger.info('this.pinchValue = ' + this.pinchValue);
  6211. if (this.pinchValue >= 1) {
  6212. this.sonTwoFingerType++
  6213. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  6214. if (this.sonTwoFingerType > 3) {
  6215. this.sonTwoFingerType = 1
  6216. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6217. }
  6218. } else {
  6219. this.sonTwoFingerType--
  6220. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  6221. if (this.sonTwoFingerType < 1) {
  6222. this.sonTwoFingerType = 1
  6223. }
  6224. }
  6225. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  6226. this.pinchValue = 1;
  6227. this.scaleValue = 1;
  6228. }
  6229. @State sonTwoFingerType:number = 3
  6230. @Builder
  6231. private MusicItemSon(item: VideoItem, index?: number) {
  6232. Button({ type: ButtonType.Normal, stateEffect: true }) {
  6233. Row() {
  6234. Stack() {
  6235. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  6236. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6237. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6238. .alt($r('app.media.music_red'))
  6239. .fillColor(this.themeColor)
  6240. .borderRadius('100%')
  6241. .clip(true)
  6242. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  6243. .draggable(false)// 禁止长按手势拖动
  6244. .autoResize(true) // 重采样,可减少内存占用
  6245. .margin({ left: 20 })
  6246. }
  6247. .width('15%')
  6248. Column() {
  6249. Column() {
  6250. Text(item.name)
  6251. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  6252. .fontColor(this.curIndex === index ? this.themeColor :
  6253. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  6254. .maxLines(1)
  6255. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  6256. Row() {
  6257. Column(){
  6258. Text(item.md5Str?.includes('Lossless')?
  6259. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6260. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  6261. .padding({ top: 3,right:6,left:6,bottom:3 })
  6262. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6263. $r('app.color.text_color'))
  6264. .fontWeight(500)
  6265. .borderRadius(12)
  6266. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  6267. .backgroundColor('#FFC107')
  6268. }
  6269. .padding({ top: 8 })
  6270. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  6271. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6272. .padding({ top: 8 })
  6273. .fontColor(this.curIndex === index ? this.themeColor :
  6274. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6275. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  6276. Blank()
  6277. Text(item.size)
  6278. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6279. .padding({ top: 8 })
  6280. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  6281. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  6282. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6283. .margin({ left: 10 })
  6284. }
  6285. }
  6286. .height('100%')
  6287. .width('100%')
  6288. .justifyContent(FlexAlign.Center)
  6289. .alignItems(HorizontalAlign.Start)
  6290. }
  6291. .height('100%')
  6292. .width('65%')
  6293. Column() {
  6294. ImageAnimator()
  6295. .images(this.imagesF)// 动画数组
  6296. .duration(1000)// 持续
  6297. .state(this.animationState)// 动画状态
  6298. .fillMode(FillMode.Forwards)
  6299. .width(18)
  6300. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  6301. Visibility.None)
  6302. .height(18)
  6303. .iterations(-1) // 播放次数
  6304. }
  6305. .width('20%')
  6306. }
  6307. }
  6308. .backgroundColor(Color.Transparent)
  6309. .width('100%')
  6310. .reuseId('son_item')
  6311. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  6312. .shadow(this.scaleItem === index ? {
  6313. radius: 70,
  6314. color: '#15000000',
  6315. offsetX: 0,
  6316. offsetY: 0
  6317. } :
  6318. {
  6319. radius: 0,
  6320. color: '#15000000',
  6321. offsetX: 0,
  6322. offsetY: 0
  6323. })
  6324. .animation({ curve: Curve.Sharp, duration: 300 })
  6325. }
  6326. @Builder
  6327. MusicPlayBuilder() {
  6328. Column() {
  6329. this.IjkMusicPlayerView()
  6330. }
  6331. .height('100%')
  6332. .width('100%')
  6333. .onDisAppear(() => {
  6334. this.translateY = 0;
  6335. })
  6336. .translate({ y: this.translateY })
  6337. .gesture(
  6338. PanGesture(this.panOption)
  6339. .onActionUpdate((event?: GestureEvent) => {
  6340. if (event) {
  6341. // 只允许向下滑动,向上滑动时限制为0
  6342. this.translateY = Math.max(0, event.offsetY);
  6343. }
  6344. })
  6345. .onActionEnd((event?: GestureEvent) => {
  6346. // 使用更低的阈值和滑动速度判断
  6347. const minDistance = 100; // 最小滑动距离 100vp
  6348. const minVelocity = 500; // 最小滑动速度
  6349. // 获取滑动速度(如果可用)
  6350. const velocity = event?.velocityY || 0;
  6351. // 判断是否应该关闭:距离足够 或者 速度足够快
  6352. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  6353. if (shouldClose) {
  6354. // 添加关闭动画
  6355. this.getUIContext().animateTo({
  6356. duration: 300,
  6357. curve: Curve.Smooth
  6358. }, () => {
  6359. this.isShowPlay = false;
  6360. this.translateY = 0;
  6361. })
  6362. } else {
  6363. // 回弹动画
  6364. this.getUIContext().animateTo({
  6365. duration: 300,
  6366. curve: Curve.Smooth
  6367. }, () => {
  6368. this.translateY = 0;
  6369. })
  6370. }
  6371. })
  6372. )
  6373. }
  6374. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  6375. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  6376. HeightBreakpoint.HEIGHT_LG;
  6377. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  6378. @State topBarHeight: number = 50
  6379. @State barOpacity: number = 1
  6380. @State barBottomOpacity: number = 1
  6381. private hideDone: boolean = false;
  6382. @State currentYOffset: number = 0;
  6383. @State bottomBarHeight: number = 60;
  6384. private isHiding: boolean = false;
  6385. //是否是Pura X外屏,或者小屏幕
  6386. isPuraWP() {
  6387. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6388. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  6389. }
  6390. //是否是Pura X外屏,或者小屏幕,手机横屏
  6391. /**
  6392. * 是否是Pura X外屏,或者小屏幕,手机横屏
  6393. * @returns
  6394. */
  6395. isCoverOpacity() {
  6396. if (this.isPuraWP()) {
  6397. return true
  6398. }
  6399. if (this.isPhoneLan()) {
  6400. return true
  6401. }
  6402. if (deviceInfo.marketName.includes('Pura X')
  6403. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  6404. return true
  6405. }
  6406. return false
  6407. }
  6408. //是不是手机横屏
  6409. isPhoneLan() {
  6410. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  6411. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  6412. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  6413. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  6414. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  6415. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  6416. if (this.isHiCarKuanBianPing()) {
  6417. return true
  6418. }
  6419. if (this.isHiCar()) {
  6420. return false
  6421. }
  6422. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6423. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  6424. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  6425. return true
  6426. }
  6427. return false
  6428. }
  6429. //是不是1920x720的hicar的屏幕分辨率
  6430. isHiCarKuanBianPing(){
  6431. if(!this.isHiCar()){
  6432. return false
  6433. }
  6434. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6435. { ratio: 1920 / 720, name: "1920x720" },
  6436. ];
  6437. const currentRatio: number = this.windowWidth / this.windowHeight;
  6438. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6439. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  6440. for (const hiCarRatio of hiCarAspectRatios) {
  6441. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  6442. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6443. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6444. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6445. //宽扁平的尺寸设置列表展示
  6446. this.twoFingerType ==3
  6447. this.isGridMusic = false
  6448. return true;
  6449. }
  6450. }
  6451. return false;
  6452. }
  6453. //是不是hicar的屏幕分辨率
  6454. isHiCarSmall() {
  6455. if(!this.isHiCar()){
  6456. return false
  6457. }
  6458. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  6459. {
  6460. this.columns = 6
  6461. return false
  6462. }
  6463. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6464. { ratio: 800 / 480, name: "800x480" },
  6465. { ratio: 1280 / 720, name: "1280x720" },
  6466. { ratio: 1920 / 1080, name: "1920x1080" },
  6467. ];
  6468. const currentRatio: number = this.windowWidth / this.windowHeight;
  6469. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6470. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  6471. for (const hiCarRatio of hiCarAspectRatios) {
  6472. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  6473. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6474. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  6475. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6476. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6477. //宽扁平的尺寸设置列表展示
  6478. return true;
  6479. }
  6480. }
  6481. return false;
  6482. }
  6483. isHiCar() {
  6484. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  6485. }
  6486. //是不是正常的手机竖屏
  6487. isPhonePortrait() {
  6488. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  6489. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  6490. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  6491. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6492. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  6493. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  6494. return true
  6495. }
  6496. return false
  6497. }
  6498. @State showSpeedDialog: boolean = false
  6499. @State longPressSpeed: number = 3 //长按默认倍数
  6500. @Builder
  6501. SpeedDialog() {
  6502. Stack() {
  6503. Column() {
  6504. Text('已切换至' + this.longPressSpeed + '倍速播放')
  6505. .fontColor(Color.White)
  6506. .visibility(Visibility.Hidden)
  6507. }
  6508. .backgroundColor(Color.Black)
  6509. .borderRadius(20)
  6510. .padding({
  6511. top: 10,
  6512. right: 20,
  6513. left: 15,
  6514. bottom: 20
  6515. })
  6516. .opacity(0.6)
  6517. Text('已切换至' + this.longPressSpeed + '倍速播放')
  6518. .fontColor(Color.White)
  6519. }
  6520. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  6521. .zIndex(5)
  6522. .margin({ top: 80 })
  6523. }
  6524. @Builder
  6525. IjkMusicPlayerView() {
  6526. Column() {
  6527. Column() {
  6528. Column() {
  6529. //播放标题
  6530. Column() {
  6531. this.PlayTitle()
  6532. }
  6533. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  6534. .width('100%')
  6535. .margin({ top: 0 })
  6536. .height(PlayConstants.HEIGHT)
  6537. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  6538. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  6539. if (this.showSpeedDialog) {
  6540. this.SpeedDialog()
  6541. }
  6542. Stack() {
  6543. //手势拖动快进
  6544. Column()
  6545. .width(CommonConstants.FULL_PERCENT)
  6546. .height('100%')
  6547. .gesture(
  6548. GestureGroup(GestureMode.Parallel,
  6549. // 长按屏幕倍数播放
  6550. LongPressGesture({ repeat: true })
  6551. .onAction(() => {
  6552. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6553. this.showSpeedDialog = true;
  6554. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  6555. }
  6556. })
  6557. .onActionEnd(() => {
  6558. this.showSpeedDialog = false;
  6559. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  6560. }),
  6561. //双击屏幕暂停或者播放
  6562. TapGesture({ count: 2 })
  6563. .onAction((event: GestureEvent) => {
  6564. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6565. ToastUtil.showToast('已暂停')
  6566. }
  6567. console.info('onecold playOrPause 6693')
  6568. this.playOrPause()
  6569. })
  6570. )
  6571. )
  6572. }
  6573. .height('65%')
  6574. Swiper() {
  6575. this.CoverInfo()
  6576. this.PlayerLyrics()
  6577. }
  6578. .onChange((index: number) => {
  6579. this.currentSwiperIndex = index
  6580. })
  6581. .indicator(false)
  6582. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  6583. // new DotIndicator()
  6584. // .top(this.isCoverOpacity()?0:10)
  6585. //
  6586. // .selectedColor($r('app.color.select_swiper'))
  6587. // .color($r('app.color.slider_track')):false
  6588. // )
  6589. .displayCount(new BreakpointType({
  6590. sm: 1,
  6591. md: 2,
  6592. lg: 2,
  6593. xl: 2,
  6594. xxl: 2
  6595. }).getValue(this.currentBreakpoint))
  6596. .clip(false)
  6597. .loop(false)
  6598. .autoPlay(false)
  6599. // .interval(8000)
  6600. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  6601. .height('100%')
  6602. .hitTestBehavior(HitTestMode.Transparent)
  6603. Image($r('app.media.icon_replay'))
  6604. .objectFit(ImageFit.Auto)
  6605. .width('120px')
  6606. .height('120px')
  6607. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  6608. .border({ width: 0 })
  6609. .visibility(Visibility.None)
  6610. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  6611. .onClick(() => {
  6612. console.info('onecold startPlayOrResumePlay 6744')
  6613. this.startPlayOrResumePlay();
  6614. })
  6615. }
  6616. .width(CommonConstants.FULL_PERCENT)
  6617. .height(CommonConstants.FULL_PERCENT)
  6618. .justifyContent(FlexAlign.End)
  6619. }
  6620. .justifyContent(FlexAlign.End)
  6621. .margin({ bottom: 8 })
  6622. }
  6623. .backgroundImage(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6624. // .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  6625. // (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  6626. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  6627. // .backgroundImagePosition(Alignment.Center)
  6628. .animation({
  6629. duration: 666,
  6630. curve: 'ease-in-out' // 可选动画曲线
  6631. })
  6632. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  6633. BlurStyle.BACKGROUND_ULTRA_THICK)
  6634. .hitTestBehavior(HitTestMode.Transparent)
  6635. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  6636. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  6637. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  6638. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  6639. .onClick(() => {
  6640. // this.startAutoHide()
  6641. if(this.isHiCar())
  6642. return
  6643. if(this.is_auto_hide_progress){
  6644. this.is_auto_hide_progress = false
  6645. }
  6646. this.startAutoHide()
  6647. })
  6648. }
  6649. @State progressValue: number = 0;
  6650. @State currentTime: string = "00:00";
  6651. @State totalTime: string = "00:00";
  6652. @State loadingVisible: Visibility = Visibility.None;
  6653. @State replayVisible: Visibility = Visibility.None;
  6654. @State slideEnable: boolean = false;
  6655. @State aspRatio: number = 0.5;
  6656. @State mContext: object | undefined = undefined;
  6657. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  6658. @State mFirst: boolean = true;
  6659. @State mDestroyPage: boolean = false;
  6660. @State playSpeed: number = 1;
  6661. @State oldSeconds: number = 0;
  6662. @State isSeekTo: boolean = false;
  6663. @State isCurrentTime: boolean = false;
  6664. @State videoWidth: string = '100%';
  6665. @State videoHeight: string = '100%';
  6666. @State initAspectRatio: number = 1;
  6667. @State videoAspectRatio: number = this.initAspectRatio;
  6668. private videoUrl: string = '';
  6669. private last: number = 0;
  6670. @State videoParentAspectRatio: number = this.initAspectRatio;
  6671. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  6672. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  6673. @State PROGRESS_MAX_VALUE: number = 100;
  6674. @State updateProgressTimer: number = 0;
  6675. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  6676. @State name: string = '';
  6677. // @State loop: boolean = false;
  6678. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  6679. @State multiple: string = '1.0X';
  6680. xcomponentController: XComponentController = new XComponentController()
  6681. private panOptionBright: PanGestureOptions =
  6682. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  6683. private panOptionVolume: PanGestureOptions =
  6684. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  6685. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  6686. //手势的音量控制和亮度控制
  6687. private positionX: number = PlayConstants.POSITION_X;
  6688. private positionY: number = PlayConstants.POSITION_Y;
  6689. private windowClass: window.Window = globalThis.windowClass
  6690. @State volume: number = 0.5;
  6691. @State volumeSmall: boolean = false
  6692. @State autoParseMusicName: boolean = true
  6693. @State isShowFileName: boolean = false
  6694. @State isLongNameRoLL: boolean = true//长歌名滚动
  6695. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  6696. @State bright: number = PlayConstants.BRIGHT;
  6697. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  6698. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  6699. @State screenWidth: number = 0
  6700. @State screenHeight: number = 0
  6701. @State statusBarHeight: number = 0
  6702. @State isYesFull: boolean = false
  6703. private seekValue: number = 0
  6704. @State isVideoLock: boolean = false; // Whether the video playback is locked
  6705. eventHub = getContext().eventHub;
  6706. //投播组件
  6707. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  6708. private castController: avSession.AVCastController | undefined = undefined;
  6709. @State isCastPlaying: boolean = false;
  6710. @State currentTime2: number = 0;
  6711. @State currentStringTime: string = '00:00';
  6712. @State duration: number = 0;
  6713. @State isReady: boolean = false;
  6714. @State durationTime: number = 0;
  6715. @State durationStringTime: string = '00:00';
  6716. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  6717. // @State isPlaying: boolean = false;
  6718. private castSeek: boolean = false;
  6719. private castItem: avSession.AVQueueItem | undefined = undefined;
  6720. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  6721. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  6722. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  6723. @State rotateAngle2: number = -9
  6724. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  6725. @State cover: string | undefined = '';
  6726. @State artist: string | undefined = ''
  6727. // 1.初始化controller
  6728. private lyricController: LyricController = new LyricController()
  6729. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  6730. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  6731. private parser = new LyricParser()
  6732. @State randomColor: string = 'rgb(0,0,0)'
  6733. @State randomShakenX: number = 0
  6734. @State randomShakenY: number = 0
  6735. @State lyricTextSize: number = 24
  6736. @State lyricContent: string = ''
  6737. @State isDebug: boolean = false
  6738. @State isHightLightCenter: boolean = true
  6739. /**
  6740. * 初始化歌词加载与展示逻辑
  6741. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  6742. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  6743. * @param isApi2 是否使用API2获取歌词(可选)
  6744. *
  6745. * 主要流程:
  6746. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  6747. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  6748. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  6749. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  6750. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  6751. * 6. 解析失败或读取失败时,清空歌词显示。
  6752. *
  6753. * 注意事项:
  6754. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  6755. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  6756. * - 歌词内容解析后通过lyricController驱动UI渲染。
  6757. */
  6758. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  6759. if (StrUtil.isEmpty(lyricPath)) {
  6760. return
  6761. }
  6762. this.initPipLyricSetting()
  6763. this.lyricControllerSingle
  6764. .setTextSize(15)
  6765. .setCacheSize(4)
  6766. .setTextColor("#FFFFFF")
  6767. .setHighlightColor("#FFFFFF")
  6768. .setHighlightScale(1.2)
  6769. .setEmptyHint("")
  6770. .setAlignMode('center')
  6771. .setAnimationDuration(500)
  6772. .setSingleLine(true)
  6773. this.lyricContent = ''
  6774. this.lyricController
  6775. .setTextSize(this.currentLyricSize)
  6776. .setCacheSize(4)
  6777. .setTextColor("#DDDDDD")
  6778. .setHighlightColor("#FFFFFF")
  6779. .setEmptyHint("")
  6780. .setAnimationDuration(1000)
  6781. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  6782. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  6783. this.setBlurDegree(this.blurDegree, false)
  6784. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  6785. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  6786. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  6787. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  6788. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  6789. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  6790. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  6791. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6792. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  6793. this.lyricController.setTextWeight(this.lyricTextWeight)
  6794. this.showSingleLyric = false
  6795. this.timeOffset = 0
  6796. this.lyricController.setLyric(null)
  6797. this.lyricControllerSingle.setLyric(null)
  6798. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  6799. console.log("onecold lyricPath =" + lyricPath)
  6800. let neiqianLrc = ''
  6801. let lyContent = this.currentSong?.lyricContent
  6802. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  6803. neiqianLrc = lyContent
  6804. }
  6805. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  6806. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  6807. //赋值给this.lyricContent,播控中心才可以显示歌词
  6808. this.lyricContent = neiqianLrc
  6809. // 将文件内容按行分割成字符串数组
  6810. let lines = neiqianLrc.split('\n').map(line => line.trim());
  6811. // 3.解析歌词
  6812. let lyric = this.parser.parse(lines);
  6813. // 4.设置歌词
  6814. this.lyricController.setLyric(lyric);
  6815. this.lyricControllerXF.setLyric(lyric)
  6816. this.lyricControllerSingle.setLyric(lyric)
  6817. return
  6818. }
  6819. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  6820. && !Utility.isVideoByExtension(this.videoUrl))) {
  6821. if (this.currentSong !== undefined) {
  6822. // ToastUtil.showShort('正在为你搜索在线歌词!')
  6823. //判断是不是赞助会员,是会员的话才开启歌词功能
  6824. // if (!this.isDebug) {
  6825. // if (!Utility.isNoble()) {
  6826. // LogUtil.debug("onecold 不是赞助会员")
  6827. // return
  6828. // }
  6829. // if(!Utility.isPassInstallTime(33)){
  6830. // LogUtil.debug("onecold not pass time")
  6831. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  6832. // return
  6833. // }
  6834. // }
  6835. let artist = this.currentSong?.artist
  6836. if (artist === undefined) {
  6837. artist = ''
  6838. }
  6839. if (isApi2 === undefined) {
  6840. isApi2 = false
  6841. }
  6842. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  6843. // LogUtil.debug("onecold res =" + res)
  6844. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6845. if (StrUtil.isNotEmpty(res)) {
  6846. this.lyricContent = res
  6847. let lines = res.split('\n').map(line => line.trim());
  6848. // 3.解析歌词
  6849. let lyric = this.parser.parse(lines);
  6850. // 4.设置歌词
  6851. this.lyricController.setLyric(lyric);
  6852. this.lyricControllerXF.setLyric(lyric)
  6853. this.lyricControllerSingle.setLyric(lyric)
  6854. this.showSingleLyric = true
  6855. // 4.保存歌词文件lyric到本地
  6856. //2025年8月28日歌词不再加密下载
  6857. this.saveDataToFile(res, lyricPath, false)
  6858. } else {
  6859. this.lyricController.setLyric(null)
  6860. this.lyricControllerXF.setLyric(null)
  6861. this.lyricControllerSingle.setLyric(null)
  6862. if (isOnLineAndToast) {
  6863. ToastUtil.showShort('未获取到歌词!')
  6864. }
  6865. }
  6866. } else {
  6867. this.lyricController.setLyric(null)
  6868. this.lyricControllerXF.setLyric(null)
  6869. this.lyricControllerSingle.setLyric(null)
  6870. if (isOnLineAndToast) {
  6871. ToastUtil.showShort('未获取到歌词!')
  6872. }
  6873. }
  6874. })
  6875. } else {
  6876. this.lyricController.setLyric(null)
  6877. this.lyricControllerXF.setLyric(null)
  6878. this.lyricControllerSingle.setLyric(null)
  6879. if (isOnLineAndToast) {
  6880. ToastUtil.showShort('未获取到歌词!')
  6881. }
  6882. }
  6883. return
  6884. }
  6885. try {
  6886. let isJiaMi = false;
  6887. let realLyricPath = lyricPath
  6888. if (FileUtil.accessSync(jiaMilyricPath)) {
  6889. isJiaMi = true
  6890. realLyricPath = jiaMilyricPath
  6891. console.info("onecold 找到加密本地歌词 ");
  6892. } else {
  6893. isJiaMi = false
  6894. realLyricPath = lyricPath
  6895. console.info("onecold 找到本地歌词 ");
  6896. }
  6897. // 3.读取文件内容并指定编码为 UTF-8
  6898. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6899. const stat = await fileIo.stat(file.fd);
  6900. const arrayBuffer = new ArrayBuffer(stat.size);
  6901. fs.read(file.fd, arrayBuffer)
  6902. .then((readLen: number) => {
  6903. console.info("read file data succeed");
  6904. // let buf = buffer.from(arrayBuffer, 0, readLen);
  6905. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6906. // 检查 buf 是否为空
  6907. if (buf.length === 0) {
  6908. throw new Error("Buffer is empty after reading the file");
  6909. }
  6910. try {
  6911. // 检测文件编码
  6912. // let detectedEncoding = chardet.detect(buf);
  6913. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  6914. let detectedEncoding = this.detect(arrayBuffer)
  6915. console.info("onecoldT Detected encoding: " + detectedEncoding);
  6916. // 使用检测到的编码解码,解决中文乱码问题
  6917. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6918. console.info("onecoldT Detected textDecoder: " + textDecoder);
  6919. let fileContent = textDecoder.decode(buf);
  6920. console.info(`onecoldT The content of file1: ${fileContent}`);
  6921. //解密
  6922. if (isJiaMi) {
  6923. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  6924. }
  6925. console.info(`onecold The content of file2: ${fileContent}`);
  6926. this.lyricContent = fileContent
  6927. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  6928. this.lyricConStr = fileContent
  6929. }
  6930. // 将文件内容按行分割成字符串数组
  6931. let lines = fileContent.split('\n').map(line => line.trim());
  6932. console.info(`onecold The content of file: ${fileContent}`);
  6933. // 3.解析歌词
  6934. let lyric = this.parser.parse(lines);
  6935. // 4.设置歌词
  6936. this.lyricController.setLyric(lyric);
  6937. this.lyricControllerXF.setLyric(lyric)
  6938. this.lyricControllerSingle.setLyric(lyric)
  6939. this.showSingleLyric = true
  6940. console.info(`The content of file: ${fileContent}`);
  6941. } catch (chardetError) {
  6942. console.error("chardet.detect failed with error: " + chardetError.message);
  6943. this.lyricController.setLyric(null);
  6944. this.lyricControllerXF.setLyric(null)
  6945. this.lyricControllerSingle.setLyric(null)
  6946. }
  6947. })
  6948. .catch((err: BusinessError) => {
  6949. this.lyricController.setLyric(null)
  6950. this.lyricControllerXF.setLyric(null)
  6951. this.lyricControllerSingle.setLyric(null)
  6952. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  6953. })
  6954. .catch((err: Error) => {
  6955. this.lyricController.setLyric(null)
  6956. this.lyricControllerXF.setLyric(null)
  6957. this.lyricControllerSingle.setLyric(null)
  6958. console.error("read file 2 data failed with error message: " + err.message);
  6959. })
  6960. .finally(() => {
  6961. fs.closeSync(file);
  6962. });
  6963. } catch (error) {
  6964. this.lyricController.setLyric(null)
  6965. this.lyricControllerSingle.setLyric(null)
  6966. this.lyricControllerXF.setLyric(null)
  6967. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  6968. }
  6969. }
  6970. detect(data: ArrayBuffer): string {
  6971. //创建检测对象
  6972. let detector: UniversalDetector = new UniversalDetector();
  6973. // 传入检测数据并实时判断编码格式
  6974. detector.handleData(data, 0, data.byteLength);
  6975. // 标记检测数据 读取结束
  6976. detector.dataEnd();
  6977. // 获取检测结果
  6978. let detected: string = detector.getDetectedCharset();
  6979. // 释放资源
  6980. detector.reset();
  6981. return detected;
  6982. }
  6983. //初始化悬浮歌词的自定义设置
  6984. initPipLyricSetting() {
  6985. this.lyricControllerXF
  6986. .setTextSize(this.currentLyricSize)
  6987. .setCacheSize(4)
  6988. .setTextColor("#DDDDDD")
  6989. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  6990. .setEmptyHint("")
  6991. .setAnimationDuration(1000)
  6992. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  6993. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  6994. this.setBlurDegree(this.blurDegreePip, true)
  6995. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  6996. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  6997. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  6998. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  6999. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  7000. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  7001. this.lyricControllerXF.setHightLightCenter(true)
  7002. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  7003. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7004. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7005. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  7006. if (this.pipBgIndex === 0) {
  7007. if (this.cover) {
  7008. this.pipBg = this.cover
  7009. } else {
  7010. this.pipBg = this.imageColor
  7011. }
  7012. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7013. }
  7014. }
  7015. //根据item返回歌词内容
  7016. async getLyricContent(item: VideoItem): Promise<string> {
  7017. let neiqianLrc = ''
  7018. let lyContent = item?.lyricContent
  7019. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  7020. neiqianLrc = lyContent
  7021. return neiqianLrc
  7022. }
  7023. try {
  7024. //取数据库里面的歌词lyContent
  7025. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  7026. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  7027. console.log("onecold Lyrics:", lyricContent);
  7028. neiqianLrc = lyricContent
  7029. return neiqianLrc
  7030. }
  7031. } catch (error) {
  7032. console.error("Error fetching lyrics:", error);
  7033. }
  7034. try {
  7035. let filePath = item.filePath;
  7036. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  7037. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  7038. let isJiaMi = false;
  7039. let realLyricPath = lyricPath;
  7040. if (FileUtil.accessSync(jiaMilyricPath)) {
  7041. isJiaMi = true;
  7042. realLyricPath = jiaMilyricPath;
  7043. console.info("onecold 找到加密本地歌词");
  7044. } else {
  7045. console.info("onecold 找到本地歌词");
  7046. }
  7047. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7048. const stat = await fileIo.stat(file.fd);
  7049. const arrayBuffer = new ArrayBuffer(stat.size);
  7050. const readLen = await fs.read(file.fd, arrayBuffer);
  7051. console.info("read file data succeed");
  7052. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7053. if (buf.length === 0) {
  7054. throw new Error("Buffer is empty after reading the file");
  7055. }
  7056. // let detectedEncoding = chardet.detect(buf);
  7057. let detectedEncoding = this.detect(arrayBuffer)
  7058. console.info("Detected encoding: " + detectedEncoding);
  7059. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7060. let fileContent = textDecoder.decode(buf);
  7061. console.info(`onecold The content of file1: ${fileContent}`);
  7062. if (isJiaMi) {
  7063. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  7064. }
  7065. console.info(`onecold The content of file2: ${fileContent}`);
  7066. fs.closeSync(file);
  7067. return fileContent;
  7068. } catch (error) {
  7069. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  7070. return '';
  7071. }
  7072. }
  7073. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  7074. if (StrUtil.isEmpty(filePath)) {
  7075. return
  7076. }
  7077. try {
  7078. //将content进行加密
  7079. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  7080. let lyricContent = ''
  7081. if (isJiaMi) {
  7082. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  7083. } else {
  7084. lyricContent = content
  7085. }
  7086. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  7087. // 清空文件内容
  7088. await fileIo.truncate(file.fd, 0);
  7089. await fileIo.write(file.fd, lyricContent);
  7090. await fileIo.close(file);
  7091. console.log('onecold lyric file Data saved successfully.');
  7092. } catch (error) {
  7093. console.error('onecold lyric file Failed to save data:', error);
  7094. }
  7095. }
  7096. /**
  7097. * Get largest proportion color of an image.
  7098. */
  7099. getImageColor() {
  7100. if (!this.context) {
  7101. return;
  7102. }
  7103. let bg = Utility.getMusisBg()
  7104. this.imageLabel = bg
  7105. ColorConversion.setSysBarLightBackground(true);
  7106. this.context.resourceManager.getMediaContent(bg)
  7107. .then((value: Uint8Array) => {
  7108. let buffer = value.buffer as ArrayBuffer;
  7109. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  7110. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  7111. if (error) {
  7112. Logger.error('Failed to create color picker.');
  7113. } else {
  7114. let color = colorPicker.getLargestProportionColor();
  7115. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  7116. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  7117. }
  7118. })
  7119. let headFilter = effectKit.createEffect(pixelMap);
  7120. if (headFilter !== null) {
  7121. headFilter.blur(15);
  7122. headFilter.getEffectPixelMap().then((value) => {
  7123. this.imageLabelBg = value;
  7124. })
  7125. }
  7126. })
  7127. .catch((error: BusinessError) => {
  7128. Logger.error(`${error.code} + ${error.message}`)
  7129. })
  7130. })
  7131. .catch((error: BusinessError) => {
  7132. Logger.error(`${error.code} + ${error.message}`)
  7133. })
  7134. }
  7135. setImageColor(cover: string) {
  7136. if (!this.context) {
  7137. return;
  7138. }
  7139. if (cover === undefined) {
  7140. return;
  7141. }
  7142. imagePathToPixelMap(cover).then((value) => {
  7143. let headFilter = effectKit.createEffect(value);
  7144. if (headFilter !== null) {
  7145. headFilter.blur(15);
  7146. headFilter.getEffectPixelMap().then((value) => {
  7147. this.imageLabelBg = value;
  7148. })
  7149. }
  7150. }).catch((error: BusinessError) => {
  7151. Logger.error(`${error.code} + ${error.message}`)
  7152. })
  7153. }
  7154. setImageColor2(cover: string) {
  7155. if (!this.context) {
  7156. return;
  7157. }
  7158. if (cover === undefined) {
  7159. return;
  7160. }
  7161. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  7162. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  7163. this.imageColor = data.imageColor;
  7164. if (data.blurPixelMap) {
  7165. this.imageLabelBg = data.blurPixelMap;
  7166. }
  7167. })
  7168. }
  7169. // 定义开始旋转的方法
  7170. // 定时器用于一百毫秒执行一次旋转角度
  7171. @State timer: number = 0
  7172. @State rotateAngle: number = 0
  7173. //封面旋转动画
  7174. animationRoFun() {
  7175. if (this.isPlaying && !this.isCoverRectangle) {
  7176. this.timer = setInterval(() => {
  7177. this.rotateAngle += 1
  7178. }, 100)
  7179. this.startRotation()
  7180. } else {
  7181. clearInterval(this.timer)
  7182. this.stopRotation()
  7183. }
  7184. }
  7185. // 定义开始旋转的方法
  7186. startRotation() {
  7187. if (this.isPlaying) {
  7188. animateTo({
  7189. duration: 777,
  7190. iterations: 1,
  7191. curve: Curve.Linear
  7192. }, () => {
  7193. this.rotateAngle2 = -9
  7194. })
  7195. }
  7196. }
  7197. // 回调,暂停和播放按钮回调,下一首和上一首
  7198. playChange() {
  7199. // if(this.isCoverRectangle){
  7200. // return
  7201. // }
  7202. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7203. this.setIsPlaying(true)
  7204. this.animationState = AnimationStatus.Running
  7205. } else {
  7206. this.setIsPlaying(false)
  7207. this.animationState = AnimationStatus.Paused
  7208. }
  7209. }
  7210. // 定义停止旋转的方法
  7211. stopRotation() {
  7212. if (this.isCoverRectangle) {
  7213. this.rotateAngle = 0
  7214. } else {
  7215. //唱针以左上角为点选择逆时针40度
  7216. animateTo({
  7217. duration: 1000,
  7218. curve: Curve.Linear,
  7219. iterations: 1,
  7220. }, () => {
  7221. this.rotateAngle2 = -45;
  7222. });
  7223. }
  7224. }
  7225. @Builder
  7226. private LyricsTopItem() {
  7227. Row() {
  7228. Stack() {
  7229. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7230. .height(55)
  7231. .width(55)
  7232. .alt(this.imageLabel)
  7233. .borderRadius(8)
  7234. .clickEffect({ level: ClickEffectLevel.HEAVY })
  7235. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  7236. }
  7237. .width('18%')
  7238. Column() {
  7239. Column() {
  7240. Text(this.name)
  7241. .fontSize(16)
  7242. .maxLines(1)
  7243. .fontWeight(FontWeight.Bolder)
  7244. .fontColor(this.currentLyricColor)
  7245. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7246. Row() {
  7247. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  7248. .fontSize(13)
  7249. .fontWeight(FontWeight.Bold)
  7250. .padding({ top: 8 })
  7251. .fontColor(this.currentLyricColor)
  7252. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7253. Blank()
  7254. }
  7255. }
  7256. .height('100%')
  7257. .width('100%')
  7258. .justifyContent(FlexAlign.Center)
  7259. .alignItems(HorizontalAlign.Start)
  7260. }
  7261. .height('100%')
  7262. .width('65%')
  7263. Column() {
  7264. Image($r('app.media.lyric'))
  7265. .width(28)
  7266. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7267. .margin({ right: 30 })
  7268. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7269. .onClick(() => {
  7270. this.isLyricSetting = !this.isLyricSetting;
  7271. })
  7272. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  7273. height: '95%',
  7274. dragBar: true,
  7275. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7276. showClose: true,
  7277. blurStyle: BlurStyle.Thin,
  7278. backgroundColor: Color.Transparent,
  7279. // title: { title: $r('app.string.lyric_setting') }
  7280. })
  7281. }
  7282. .width('18%')
  7283. }
  7284. .width('82%')
  7285. .height(58)
  7286. .justifyContent(FlexAlign.SpaceBetween)
  7287. }
  7288. //歌词显示
  7289. @Builder
  7290. PlayerLyrics() {
  7291. Column() {
  7292. Column() {
  7293. this.LyricsTopItem()
  7294. }
  7295. .height(this.isPuraWP() ? 15 : 58)
  7296. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  7297. Visibility.None : Visibility.Visible)
  7298. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  7299. .width("100%")
  7300. Column() {
  7301. LyricView2({
  7302. controller: this.lyricController,
  7303. enableSeek: true,
  7304. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7305. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7306. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7307. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  7308. if (!this.isPlaying) {
  7309. console.info('onecold startPlayOrResumePlay 7527')
  7310. this.startPlayOrResumePlay()
  7311. }
  7312. else {
  7313. this.isSeekTo = true;
  7314. this.mDestroyPage = false;
  7315. this.showLoadIng();
  7316. this.seekTo(position + "");
  7317. this.isSeekTo = false;
  7318. }
  7319. return true
  7320. }
  7321. })
  7322. .width("100%")
  7323. .layoutWeight(1)
  7324. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  7325. if (this.isPhoneLan()) {
  7326. Column() {
  7327. this.playProgressView()
  7328. // this.playCenterView()
  7329. }
  7330. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  7331. }
  7332. }
  7333. .position({
  7334. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  7335. (this.isPuraWP() ? 58 : 99)
  7336. })
  7337. .justifyContent(FlexAlign.Center)
  7338. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  7339. }
  7340. }
  7341. @Builder
  7342. SingleLyricView() {
  7343. Column() {
  7344. Column() {
  7345. LyricView2({
  7346. controller: this.lyricControllerSingle,
  7347. enableSeek: false,
  7348. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7349. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7350. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7351. })
  7352. }
  7353. .height(66)
  7354. .margin({ bottom: 20 })
  7355. }
  7356. }
  7357. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  7358. @Builder
  7359. BottomControl() {
  7360. Column() {
  7361. this.TopPlayProgressView()
  7362. //播放 暂停,下一首,上一首
  7363. this.playCenterView()
  7364. //播放进度条
  7365. this.BottomView()
  7366. }
  7367. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  7368. }
  7369. //播放控制上一首 下一首 暂停和播放
  7370. @Builder
  7371. playCenterView(){
  7372. Row() {
  7373. Row({ space: 20 }) {
  7374. Button({type:ButtonType.Circle,stateEffect:true}){
  7375. //更多功能
  7376. Image($r('app.media.menu'))
  7377. .width(24)
  7378. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7379. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  7380. height: this.isCoverOpacity() ? '95%' : '93%',
  7381. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  7382. dragBar: true,
  7383. showClose: true,
  7384. blurStyle: BlurStyle.Thin,
  7385. backgroundColor: Color.Transparent,
  7386. })
  7387. }
  7388. .margin({ left: 5 })
  7389. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7390. .backgroundColor(Color.Transparent)
  7391. .onClick(() => {
  7392. this.isShowMoreView = !this.isShowMoreView;
  7393. })
  7394. Button({type:ButtonType.Circle,stateEffect:true}){
  7395. Image($r('app.media.ic_previous'))
  7396. .width(33)
  7397. .clickEffect({level:ClickEffectLevel.HEAVY})
  7398. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7399. }
  7400. .onClick(async () => {
  7401. this.playPrevious()
  7402. })
  7403. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7404. .backgroundColor(Color.Transparent)
  7405. .margin({ left: 5 })
  7406. }
  7407. Button({type:ButtonType.Circle,stateEffect:true}){
  7408. Column() {
  7409. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  7410. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  7411. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  7412. .width(this.isPhoneLan()?45:55)
  7413. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7414. .fillColor(Color.White)
  7415. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7416. .onClick(async () => {
  7417. console.info('onecold playOrPause 7651')
  7418. this.playOrPause()
  7419. })
  7420. }
  7421. }
  7422. .backgroundColor(Color.Transparent)
  7423. .layoutWeight(1)
  7424. // .margin({ left: 38, right: 38 })
  7425. Row({ space: 20 }) {
  7426. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7427. Image($r('app.media.ic_next'))
  7428. .width(33)
  7429. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7430. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7431. .onClick(() => {
  7432. this.playNext();
  7433. })
  7434. }
  7435. .backgroundColor(Color.Transparent)
  7436. .margin({ right: 5 })
  7437. .width(33)
  7438. if(this.isPhoneLan()){
  7439. this.fullButton()
  7440. }else{
  7441. Button({type:ButtonType.Circle,stateEffect:true}){
  7442. //添加或取消收藏
  7443. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  7444. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  7445. .fontSize(23)
  7446. .fontColor([Color.White])
  7447. .alignSelf(ItemAlign.Center)
  7448. // .width(24)
  7449. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7450. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7451. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7452. .onClick(async () => {
  7453. if(this.currentSong){
  7454. this.doFav(this.currentSong)
  7455. }
  7456. })
  7457. }
  7458. .backgroundColor(Color.Transparent)
  7459. .width(24)
  7460. }
  7461. }
  7462. // .margin({ left: 5 })
  7463. }
  7464. .width('95%')
  7465. .margin({ bottom:this.isCoverOpacity()?0:20 })
  7466. .justifyContent(FlexAlign.SpaceEvenly)
  7467. }
  7468. @Builder
  7469. TopPlayProgressView(){
  7470. Row() {
  7471. Column(){
  7472. Row(){
  7473. Stack(){
  7474. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  7475. .fontColor([Color.White])
  7476. .fontSize(21)
  7477. .effectStrategy(1)
  7478. Text(this.fastForwardSeconds)
  7479. .fontColor(Color.White)
  7480. .fontSize(10)
  7481. .fontWeight(FontWeight.Bold)
  7482. }
  7483. .margin({left:12,bottom:6})
  7484. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  7485. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7486. .onClick(()=>{
  7487. this.backForward()
  7488. })
  7489. Slider({
  7490. value: this.progressValue,
  7491. min: 0,
  7492. max: this.PROGRESS_MAX_VALUE,
  7493. step: 1,
  7494. style: SliderStyle.InSet
  7495. })
  7496. .height(20)
  7497. .blockColor('rgba(255,255,255,1)')
  7498. .trackColor('rgba(255,255,255,0.3)')
  7499. .selectedColor(Color.White)
  7500. .trackThickness(4)
  7501. .layoutWeight(1)
  7502. .showSteps(false)
  7503. .showTips(true)
  7504. .alignSelf(ItemAlign.Center)
  7505. .enabled(this.slideEnable)
  7506. .onChange((value: number, mode: SliderChangeMode) => {
  7507. // if (mode == 2) {
  7508. this.isSeekTo = true;
  7509. this.mDestroyPage = false;
  7510. this.showLoadIng();
  7511. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  7512. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  7513. this.seekTo(seekValue + "");
  7514. // this.setProgress()
  7515. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  7516. this.isSeekTo = false;
  7517. // }
  7518. })
  7519. Stack(){
  7520. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  7521. .fontColor([Color.White])
  7522. .fontSize(21)
  7523. .effectStrategy(1)
  7524. Text(this.fastForwardSeconds)
  7525. .fontColor(Color.White)
  7526. .fontSize(10)
  7527. .fontWeight(FontWeight.Bold)
  7528. }
  7529. .margin({right:10,bottom:6})
  7530. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  7531. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7532. .onClick(()=>{
  7533. this.fastForward()
  7534. })
  7535. }
  7536. .padding({ right: 7,left:22 })
  7537. Row(){
  7538. Text(this.currentTime)
  7539. .fontSize(10)
  7540. .fontColor(Color.White)
  7541. Blank()
  7542. .layoutWeight(1)
  7543. Text(this.totalTime)
  7544. .fontSize(10)
  7545. .fontColor(Color.White)
  7546. }
  7547. .justifyContent(FlexAlign.Start)
  7548. .padding({ right: 18,left:36 })
  7549. }
  7550. }
  7551. //x5的竖屏模式需要99%
  7552. .width(this.isLandscape?'80%':'93%')
  7553. .justifyContent(FlexAlign.Center)
  7554. .margin({bottom:6})
  7555. .animation({
  7556. duration: 666,
  7557. curve: 'ease-in-out' // 可选动画曲线
  7558. })
  7559. }
  7560. //播放进度条
  7561. @Builder
  7562. BottomView(){
  7563. Row() {
  7564. Button({type:ButtonType.Circle,stateEffect:true}){
  7565. Column() {
  7566. if (this.playType === 0) {
  7567. Image($r('app.media.loop'))
  7568. .width(27)
  7569. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7570. } else if (this.playType === 1) {
  7571. Image($r('app.media.single'))
  7572. .width(27)
  7573. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7574. } else if (this.playType === 2) {
  7575. Image($r('app.media.normal_play'))
  7576. .width(27)
  7577. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7578. } else if (this.playType === 3) {
  7579. Image($r('app.media.random'))
  7580. .width(27)
  7581. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7582. }
  7583. }
  7584. }
  7585. .layoutWeight(1)
  7586. .margin({ left: 5 })
  7587. .backgroundColor(Color.Transparent)
  7588. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7589. .onClick(async () => {
  7590. this.setLoopMode()
  7591. })
  7592. this.fullButton()
  7593. Button({type:ButtonType.Circle,stateEffect:true}){
  7594. Column() {
  7595. Image($r('app.media.lyric'))
  7596. .width(26)
  7597. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7598. }
  7599. }
  7600. .layoutWeight(1)
  7601. .backgroundColor(Color.Transparent)
  7602. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7603. .onClick(async () => {
  7604. this.isLyricSetting = !this.isLyricSetting;
  7605. })
  7606. //播放列表
  7607. Button({type:ButtonType.Circle,stateEffect:true}){
  7608. Image($r('app.media.hm_playlist'))
  7609. .width(24)
  7610. .fillColor(Color.White)
  7611. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7612. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  7613. height: '95%',
  7614. dragBar: true,
  7615. showClose: true,
  7616. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7617. blurStyle: BlurStyle.Thin,
  7618. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  7619. title: {
  7620. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  7621. + `(${this.songList.length}首)`
  7622. }
  7623. })
  7624. }
  7625. .layoutWeight(1)
  7626. .backgroundColor(Color.Transparent)
  7627. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7628. .onClick(() => {
  7629. this.isShowSheetView = !this.isShowSheetView;
  7630. if(this.isPlayListBgGrass){
  7631. this.isFrontWhite = true
  7632. }else{
  7633. this.isFrontWhite = false
  7634. }
  7635. this.scrollIndex()
  7636. })
  7637. }
  7638. .width(this.isLandscape?'88%':'95%')
  7639. .justifyContent(FlexAlign.SpaceAround)
  7640. .height(30)
  7641. .margin({top:3})
  7642. .animation({
  7643. duration: 666,
  7644. curve: 'ease-in-out' // 可选动画曲线
  7645. })
  7646. }
  7647. @Builder
  7648. fullButton(){
  7649. Button({type:ButtonType.Circle,stateEffect:true}){
  7650. Column() {
  7651. Image($r('app.media.full_4'))
  7652. .width(25)
  7653. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7654. }
  7655. }
  7656. .layoutWeight(1)
  7657. .backgroundColor(Color.Transparent)
  7658. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7659. .onClick(async () => {
  7660. if (this.isLandscape) {
  7661. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  7662. } else {
  7663. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  7664. }
  7665. })
  7666. }
  7667. //旧版本播放进度条
  7668. @Builder
  7669. playProgressView() {
  7670. Row() {
  7671. Button({ type: ButtonType.Circle, stateEffect: true }) {
  7672. Column() {
  7673. if (this.playType === 0) {
  7674. Image($r('app.media.loop'))
  7675. .width($r('app.float.control_image_width'))
  7676. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7677. } else if (this.playType === 1) {
  7678. Image($r('app.media.single'))
  7679. .width($r('app.float.control_image_width'))
  7680. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7681. } else if (this.playType === 2) {
  7682. Image($r('app.media.normal_play'))
  7683. .width($r('app.float.control_image_width'))
  7684. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7685. } else if (this.playType === 3) {
  7686. Image($r('app.media.random'))
  7687. .width($r('app.float.control_image_width'))
  7688. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7689. }
  7690. }
  7691. }
  7692. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  7693. .animation({
  7694. duration: 666,
  7695. curve: 'ease-in-out' // 可选动画曲线
  7696. })
  7697. .backgroundColor(Color.Transparent)
  7698. .margin({ right: 10 })
  7699. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7700. .onClick(async () => {
  7701. this.setLoopMode()
  7702. })
  7703. Text(this.currentTime)
  7704. .fontSize($r('app.float.slider_font_size'))
  7705. .fontColor(Color.White)
  7706. .margin(3)
  7707. Slider({
  7708. value: this.progressValue,
  7709. min: 0,
  7710. max: this.PROGRESS_MAX_VALUE,
  7711. step: 1,
  7712. style: SliderStyle.OutSet
  7713. })
  7714. .width('600px')
  7715. .blockColor('rgba(255,255,255,1)')
  7716. .trackColor('rgba(255,255,255,0.3)')
  7717. .selectedColor(Color.White)
  7718. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  7719. .layoutWeight(1)
  7720. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  7721. .showSteps(false)
  7722. .showTips(true)
  7723. .enabled(this.slideEnable)
  7724. .onChange((value: number, mode: SliderChangeMode) => {
  7725. // if (mode == 2) {
  7726. this.isSeekTo = true;
  7727. this.mDestroyPage = false;
  7728. this.showLoadIng();
  7729. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  7730. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  7731. this.seekTo(seekValue + "");
  7732. // this.setProgress()
  7733. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  7734. this.isSeekTo = false;
  7735. // }
  7736. })
  7737. Text(this.totalTime)
  7738. .fontSize($r('app.float.slider_font_size'))
  7739. .fontColor(Color.White)
  7740. .margin(3)
  7741. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  7742. //播放列表
  7743. Button({ type: ButtonType.Circle, stateEffect: true }) {
  7744. Image($r('app.media.hm_playlist'))
  7745. .width($r('app.float.control_image_width'))
  7746. .fillColor(Color.White)
  7747. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7748. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  7749. height: '95%',
  7750. dragBar: true,
  7751. showClose: true,
  7752. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7753. blurStyle: BlurStyle.Thin,
  7754. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  7755. title: {
  7756. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  7757. + `(${this.songList.length}首)`
  7758. }
  7759. })
  7760. }
  7761. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  7762. .animation({
  7763. duration: 666,
  7764. curve: 'ease-in-out' // 可选动画曲线
  7765. })
  7766. .backgroundColor(Color.Transparent)
  7767. .margin({ right: 20, left: 10 })
  7768. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7769. .onClick(() => {
  7770. this.isShowSheetView = !this.isShowSheetView;
  7771. if (this.isPlayListBgGrass) {
  7772. this.isFrontWhite = true
  7773. } else {
  7774. this.isFrontWhite = false
  7775. }
  7776. this.scrollIndex()
  7777. })
  7778. }
  7779. //x5的竖屏模式需要99%
  7780. .width(this.isPhonePortrait() ? '93.4%'
  7781. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  7782. .height(this.isPhoneLan() ? 25 : 33)
  7783. .animation({
  7784. duration: 666,
  7785. curve: 'ease-in-out' // 可选动画曲线
  7786. })
  7787. }
  7788. isBigScreen() {
  7789. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  7790. return true
  7791. }
  7792. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7793. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  7794. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  7795. return false
  7796. } else {
  7797. return true
  7798. }
  7799. return false
  7800. }
  7801. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  7802. @State isCoverRectangle: boolean = false
  7803. @State isCoverTop: boolean = true
  7804. // 添加控制缩放的状态变量
  7805. @State scaleValueImage: number = 1
  7806. @Builder
  7807. CoverInfo() {
  7808. Column() {
  7809. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  7810. if (this.isCoverRectangle) {
  7811. if (!this.isCoverTop) {
  7812. this.musicNameInfo(false)
  7813. }
  7814. } else {
  7815. this.musicNameInfo(false)
  7816. }
  7817. Stack() {
  7818. // 唱片旋转效果
  7819. Image($r('app.media.ic_music_disc'))
  7820. .width(245)
  7821. .height(245)
  7822. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  7823. .aspectRatio(1)
  7824. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7825. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7826. .borderRadius('100%')
  7827. .align(Alignment.Center)
  7828. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  7829. .rotate({
  7830. angle: this.rotateAngle,
  7831. centerX: "50%",
  7832. centerY: "50%",
  7833. })
  7834. .animation({
  7835. duration: 100,
  7836. curve: Curve.Linear
  7837. })
  7838. .shadow({
  7839. radius: 30,
  7840. color: this.randomColor
  7841. })
  7842. Column() {
  7843. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  7844. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7845. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  7846. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  7847. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7848. .alt(this.imageLabel)
  7849. .margin({ right: 8, left: 8, top: 8 })
  7850. .aspectRatio(1)
  7851. .opacity(this.opacityValueImage)
  7852. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7853. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7854. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7855. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7856. .align(Alignment.Center)//
  7857. .clip(true)
  7858. .rotate({
  7859. x: 0,
  7860. y: 0,
  7861. z: 1,
  7862. angle: this.rotateAngle
  7863. })
  7864. .onClick(() => {
  7865. this.getImageColor()
  7866. })
  7867. this.musicNameInfo(false)
  7868. } else {
  7869. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7870. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  7871. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  7872. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7873. .alt(this.imageLabel)
  7874. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  7875. .aspectRatio(1)
  7876. .opacity(this.opacityValueImage)
  7877. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7878. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7879. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7880. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7881. .align(Alignment.Center)//
  7882. .clip(true)
  7883. .rotate({
  7884. x: 0,
  7885. y: 0,
  7886. z: 1,
  7887. angle: this.rotateAngle
  7888. })
  7889. .onClick(() => {
  7890. this.getImageColor()
  7891. })
  7892. if (this.isPhoneLan()) {
  7893. Text(this.name)
  7894. .fontSize(18)
  7895. .fontWeight(FontWeight.Bold)
  7896. .margin({ top: 13 })
  7897. .textOverflow({ overflow: TextOverflow.Ellipsis })
  7898. .maxLines(1)
  7899. .width('99%')
  7900. .textAlign(TextAlign.Center)
  7901. .fontColor(Color.White)
  7902. }
  7903. }
  7904. }
  7905. // 唱针以左上角为点选择逆时针40度
  7906. Image($r('app.media.ic_music_cover_hand'))
  7907. .height(130)
  7908. .margin({ bottom: 220, top: 0 })
  7909. .align(Alignment.Top)
  7910. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  7911. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7912. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7913. Column({ space: 8 }) {
  7914. Text(this.name)
  7915. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  7916. .fontWeight(FontWeight.Bold)
  7917. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7918. .maxLines(1)
  7919. .width('48%')
  7920. .textAlign(TextAlign.Center)
  7921. .fontColor(Color.White)
  7922. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7923. Text(this.artist)
  7924. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  7925. .fontColor(Color.White)
  7926. .fontWeight(FontWeight.Bold)
  7927. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7928. }
  7929. .justifyContent(FlexAlign.Start)
  7930. .zIndex(1)
  7931. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  7932. }
  7933. .margin({
  7934. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  7935. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  7936. top: this.isCoverOpacity() ? 0 : 20
  7937. })
  7938. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  7939. this.SingleLyricView()
  7940. }
  7941. if (this.isPhoneLan()) {
  7942. Column() {
  7943. this.playCenterView()
  7944. // this.playProgressView()
  7945. }
  7946. .position({ left: 28, bottom: 38 })
  7947. } else {
  7948. this.BottomControl()
  7949. }
  7950. }
  7951. .width(CommonConstants.FULL_PERCENT)
  7952. .clip(true)
  7953. }
  7954. @Builder
  7955. private musicNameInfo(isHidden: boolean) {
  7956. Column({ space: 8 }) {
  7957. Text(this.name)
  7958. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  7959. .fontWeight(FontWeight.Bold)
  7960. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7961. .maxLines(1)
  7962. .width('99%')
  7963. .textAlign(TextAlign.Center)
  7964. .fontColor(Color.White)
  7965. Text(this.artist + ' ' + this.currentSong?.album)
  7966. .fontSize(this.isCoverOpacity() ? 12 : 15)
  7967. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7968. .fontColor(Color.White)
  7969. .textAlign(TextAlign.Center)
  7970. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  7971. .width('99%')
  7972. .maxLines(1)
  7973. }
  7974. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  7975. .zIndex(1)
  7976. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7977. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  7978. }
  7979. @Builder
  7980. private PlayTitle() {
  7981. Row() {
  7982. Row() {
  7983. Image($r('app.media.ic_back_down'))
  7984. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  7985. .hitTestBehavior(HitTestMode.Transparent)
  7986. Text(this.name + ' ' + this.artist)
  7987. .fontColor(Color.White)
  7988. .fontSize($r('app.float.title_font_size'))
  7989. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7990. .maxLines(1)
  7991. .visibility(Visibility.None)
  7992. .margin({ left: 2, right: 30 })
  7993. }
  7994. .layoutWeight(1)
  7995. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7996. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  7997. .onClick(() => {
  7998. this.isShowPlay = false;
  7999. })
  8000. Column() {
  8001. AVCastPicker({
  8002. normalColor: Color.White,
  8003. onStateChange: this.onStateVastChange
  8004. })
  8005. .width(24)
  8006. .height(24)
  8007. }
  8008. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  8009. }
  8010. .width(PlayConstants.ROW_WIDTH)
  8011. }
  8012. @Builder
  8013. lyricSettingSheet(isPip: boolean) {
  8014. Scroll() {
  8015. this.lyricSetting(isPip)
  8016. }
  8017. .width('100%')
  8018. .height('100%')
  8019. }
  8020. @Builder
  8021. lyricSetting(isPip: boolean) {
  8022. Column() {
  8023. // 时间调节模块
  8024. if (!isPip) {
  8025. this.BuildTimeControls()
  8026. }
  8027. // 字号控制模块
  8028. this.BuildFontControls(isPip)
  8029. }
  8030. }
  8031. // 歌词时间偏移状态
  8032. @State timeOffset: number = 0.0
  8033. @State currentLyricColor: string = '#FFFFFF'
  8034. @State currentLyricColorPip: string = '#FFFFFF'
  8035. @State currentHighLightLyricColor: string = '#FF4081'
  8036. @State currentHighLightLyricColorPip: string = '#FF4081'
  8037. // 歌词字号状态
  8038. @State currentLyricSize: number = 20
  8039. @State currentLyricSizePip: number = 20
  8040. // 高亮歌词放大倍数
  8041. @State currentHightLyricSize: number = 1.2
  8042. @State currentHightLyricSizePip: number = 1.2
  8043. @State currentLyricLineSpace: number = 10
  8044. @State currentLyricLineSpacePip: number = 10
  8045. @State currentLyricAlignMode: number = 1
  8046. @State currentLyricAlignModePip: number = 1
  8047. @State blurDegree: number = 2
  8048. @State blurDegreePip: number = 2
  8049. @State isShowSelectColor: boolean = false
  8050. @State isShowHLSelectColor: boolean = false
  8051. @State isShowPipBgSelectColor: boolean = false
  8052. @State pipLyWidth: number = 330
  8053. @State pipLyHeight: number = 120
  8054. // 构建颜色选择器
  8055. @Builder
  8056. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  8057. Row({ space: 10 }) {
  8058. HSBColorPicker({
  8059. color: '#FFFFFF',
  8060. radius: 8,
  8061. layout: HSBColorPickerLayout.COLUMN,
  8062. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  8063. '#fa7105'],
  8064. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  8065. this.changeLyricColor(value, isPip, isBGPip)
  8066. })
  8067. .height(250)
  8068. .layoutWeight(1)
  8069. .padding(25)
  8070. }
  8071. .width('66%')
  8072. }
  8073. @State isOpenPip: boolean = false
  8074. @State pipBgIndex: number = 0
  8075. // 构建字号控制器
  8076. @Builder
  8077. BuildFontControls(isPip: boolean) {
  8078. Column() {
  8079. if (isPip) {
  8080. Column() {
  8081. Row() {
  8082. Text('悬浮歌词')
  8083. .margin({ left: 18 })
  8084. .fontSize(15)
  8085. .fontColor(Color.White)
  8086. .fontWeight(480)
  8087. .layoutWeight(1)
  8088. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  8089. .selectedColor(this.themeColor)
  8090. .switchPointColor(Color.White)
  8091. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8092. .margin({ right: 18 })
  8093. .onChange((checked: boolean) => {
  8094. this.isOpenPip = checked;
  8095. if (this.isOpenPip) {
  8096. this.startPip()
  8097. } else {
  8098. this.stopPip()
  8099. }
  8100. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  8101. })
  8102. .width(50)
  8103. .height(30);
  8104. }
  8105. .height(55)
  8106. }
  8107. .backgroundColor(Color.Transparent)
  8108. .borderRadius(15)
  8109. .margin({
  8110. left: 30,
  8111. right: 30,
  8112. top: 0,
  8113. bottom: 20
  8114. })
  8115. .padding(0)
  8116. .border({
  8117. color: Color.White,
  8118. width: 1.8
  8119. })
  8120. }else{
  8121. Column() {
  8122. Row() {
  8123. Text('单行歌词')
  8124. .margin({ left: 18 })
  8125. .fontSize(15)
  8126. .fontColor(Color.White)
  8127. .fontWeight(480)
  8128. .layoutWeight(1)
  8129. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  8130. .selectedColor(this.themeColor)
  8131. .switchPointColor(Color.White)
  8132. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8133. .margin({ right: 18 })
  8134. .onChange((checked: boolean) => {
  8135. this.isShowSingleLineLyric = checked;
  8136. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  8137. })
  8138. .width(50)
  8139. .height(30);
  8140. }
  8141. .height(55)
  8142. }
  8143. .backgroundColor(Color.Transparent)
  8144. .borderRadius(15)
  8145. .margin({
  8146. left: 30,
  8147. right: 30,
  8148. top: 10,
  8149. bottom: 10
  8150. })
  8151. .padding(0)
  8152. .border({
  8153. color: Color.White,
  8154. width: 1.8
  8155. })
  8156. }
  8157. Row() {
  8158. Text(`歌词居中:`)
  8159. .fontSize(14)
  8160. .fontColor(Color.White)
  8161. .margin({ left: 2 })
  8162. Row() {
  8163. ForEach(['居中', '居左'], (size: string, index: number) => {
  8164. Button(size)
  8165. .width(60)
  8166. .height(28)
  8167. .fontSize(12)
  8168. .fontColor('#FFFFFF')
  8169. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  8170. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  8171. .border({
  8172. color: (!isPip && this.currentLyricAlignMode === index) ||
  8173. (isPip && this.currentLyricAlignModePip === index) ?
  8174. '#007DFF' : '#DDDDDD',
  8175. width: 1.8
  8176. })
  8177. .onClick(() => {
  8178. this.setLyricAlignMode(index, isPip)
  8179. })
  8180. .margin({ left: 10, right: 8 })
  8181. })
  8182. }
  8183. .width('76%')
  8184. Blank()
  8185. }
  8186. .margin({
  8187. top: 10,
  8188. bottom: 10,
  8189. right: 20,
  8190. left: 20
  8191. })
  8192. if (isPip) {
  8193. Row() {
  8194. Text(`悬浮背景:`)
  8195. .fontSize(14)
  8196. .fontColor(Color.White)
  8197. Select([
  8198. { value: CommonConstants.PIP_LYRIC_BG[0] },
  8199. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  8200. .font({ size: 13, weight: FontWeight.Medium })
  8201. .fontColor(Color.White)
  8202. .margin({ left: 10 })
  8203. .selected(this.pipBgIndex)
  8204. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  8205. .onSelect(async (_index: number, text?: string | undefined) => {
  8206. this.pipBgIndex = _index
  8207. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  8208. if (this.pipBgIndex === 0) {
  8209. if (this.cover) {
  8210. this.pipBg = this.cover
  8211. } else {
  8212. this.pipBg = this.imageColor
  8213. }
  8214. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8215. } else {
  8216. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8217. }
  8218. })
  8219. Column() {
  8220. }
  8221. .backgroundColor(this.pipBg)
  8222. .margin({ left: 10, right: 10 })
  8223. .borderRadius(20)
  8224. .height(28)
  8225. .width(28)
  8226. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8227. Row() {
  8228. SymbolGlyph($r('sys.symbol.paintbrush'))
  8229. .fontColor([Color.White])
  8230. .effectStrategy(1)
  8231. Text(`选择颜色`)
  8232. .fontSize(13)
  8233. .margin({ left: 10 })
  8234. .fontColor(Color.White)
  8235. }
  8236. }
  8237. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  8238. .backgroundColor(Color.Transparent)
  8239. .border({
  8240. color: '#FFFFFF',
  8241. radius: 20,
  8242. width: 1.8
  8243. })
  8244. .height(36)
  8245. .width(110)
  8246. .onClick(() => {
  8247. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  8248. })
  8249. .bindPopup(this.isShowPipBgSelectColor, {
  8250. builder: this.SelectColor(false, isPip, true),
  8251. placement: Placement.Top,
  8252. mask: { color: '#33000000' },
  8253. enableArrow: false, //是否显示箭头
  8254. showInSubWindow: false,
  8255. onStateChange: (e) => {
  8256. if (!e.isVisible) {
  8257. this.isShowPipBgSelectColor = false
  8258. }
  8259. }
  8260. })
  8261. }
  8262. .width('76%')
  8263. .margin({ bottom: 5, right: 45, left: 20 })
  8264. }
  8265. if (!isPip) {
  8266. Row() {
  8267. Text(`高亮居中:`)
  8268. .fontSize(14)
  8269. .fontColor(Color.White)
  8270. Column() {
  8271. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  8272. .selectedColor(this.themeColor)
  8273. .switchPointColor(Color.White)
  8274. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8275. .onChange((checked: boolean) => {
  8276. this.isHightLightCenter = checked;
  8277. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  8278. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8279. })
  8280. .width(50)
  8281. .height(30)
  8282. .alignSelf(ItemAlign.Start)
  8283. .margin({ left: 12 })
  8284. Blank()
  8285. }
  8286. .width('76%')
  8287. }
  8288. .margin({
  8289. left: 20,
  8290. right: 15,
  8291. top: 10,
  8292. bottom: 10
  8293. })
  8294. }
  8295. Row() {
  8296. Text(`歌词颜色:`)
  8297. .fontSize(14)
  8298. .fontColor(Color.White)
  8299. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8300. .fontSize(15)
  8301. .fontColor(Color.White)
  8302. .margin({ left: 12, right: 12 })
  8303. Column() {
  8304. }
  8305. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8306. .margin({ right: 12 })
  8307. .borderRadius(20)
  8308. .height(28)
  8309. .width(28)
  8310. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8311. Row() {
  8312. SymbolGlyph($r('sys.symbol.paintbrush'))
  8313. .fontColor([Color.White])
  8314. .effectStrategy(1)
  8315. Text(`选择颜色`)
  8316. .fontSize(13)
  8317. .margin({ left: 10 })
  8318. .fontColor(Color.White)
  8319. }
  8320. }
  8321. .backgroundColor(Color.Transparent)
  8322. .border({
  8323. color: '#FFFFFF',
  8324. radius: 20,
  8325. width: 1.8
  8326. })
  8327. .height(36)
  8328. .width(110)
  8329. .onClick(() => {
  8330. this.isShowSelectColor = !this.isShowSelectColor
  8331. })
  8332. .bindPopup(this.isShowSelectColor, {
  8333. builder: this.SelectColor(false, isPip),
  8334. placement: Placement.Top,
  8335. mask: { color: '#33000000' },
  8336. enableArrow: false, //是否显示箭头
  8337. showInSubWindow: false,
  8338. onStateChange: (e) => {
  8339. if (!e.isVisible) {
  8340. this.isShowSelectColor = false
  8341. }
  8342. }
  8343. })
  8344. }
  8345. .width('76%')
  8346. .margin({
  8347. top: 10,
  8348. bottom: 10,
  8349. right: 45,
  8350. left: 20
  8351. })
  8352. Row() {
  8353. Text(`高亮颜色:`)
  8354. .fontSize(14)
  8355. .fontColor(Color.White)
  8356. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8357. .fontSize(15)
  8358. .fontColor(Color.White)
  8359. .margin({ left: 12, right: 12 })
  8360. Column() {
  8361. }
  8362. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8363. .margin({ right: 12 })
  8364. .borderRadius(20)
  8365. .height(28)
  8366. .width(28)
  8367. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8368. Row() {
  8369. SymbolGlyph($r('sys.symbol.paintbrush'))
  8370. .fontColor([Color.White])
  8371. .effectStrategy(1)
  8372. Text(`选择颜色`)
  8373. .fontSize(13)
  8374. .margin({ left: 10 })
  8375. .fontColor(Color.White)
  8376. }
  8377. }
  8378. .backgroundColor(Color.Transparent)
  8379. .border({
  8380. color: '#FFFFFF',
  8381. radius: 20,
  8382. width: 1.8
  8383. })
  8384. .height(36)
  8385. .width(110)
  8386. .onClick(() => {
  8387. this.isShowHLSelectColor = !this.isShowHLSelectColor
  8388. })
  8389. .bindPopup(this.isShowHLSelectColor, {
  8390. builder: this.SelectColor(true, isPip),
  8391. placement: Placement.Top,
  8392. mask: { color: '#33000000' },
  8393. enableArrow: false, //是否显示箭头
  8394. showInSubWindow: false,
  8395. onStateChange: (e) => {
  8396. if (!e.isVisible) {
  8397. this.isShowHLSelectColor = false
  8398. }
  8399. }
  8400. })
  8401. }
  8402. .width('76%')
  8403. .margin({
  8404. top: 10,
  8405. bottom: 10,
  8406. right: 45,
  8407. left: 20
  8408. })
  8409. if (isPip) {
  8410. Row() {
  8411. Text(`显示宽度:`)
  8412. .fontSize(14)
  8413. .fontColor(Color.White)
  8414. Slider({
  8415. value: this.pipLyWidth,
  8416. min: 10,
  8417. max: 800,
  8418. step: 1,
  8419. style: SliderStyle.OutSet
  8420. })
  8421. .blockColor(this.themeColor)
  8422. .trackColor($r('app.color.speed_text_color'))
  8423. .selectedColor(Color.White)
  8424. .trackThickness(6)
  8425. .onChange((value: number) => {
  8426. this.pipLyWidth = value
  8427. if (this.pipController) {
  8428. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8429. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  8430. }
  8431. })
  8432. .width('76%')
  8433. }
  8434. .margin({
  8435. left: 20,
  8436. right: 15,
  8437. top: 5,
  8438. bottom: 5
  8439. })
  8440. Row() {
  8441. Text(`显示高度:`)
  8442. .fontSize(14)
  8443. .fontColor(Color.White)
  8444. Slider({
  8445. value: this.pipLyHeight,
  8446. min: 10,
  8447. max: 1000,
  8448. step: 1,
  8449. style: SliderStyle.OutSet
  8450. })
  8451. .blockColor(this.themeColor)
  8452. .trackColor($r('app.color.speed_text_color'))
  8453. .selectedColor(Color.White)
  8454. .trackThickness(6)
  8455. .onChange((value: number) => {
  8456. this.pipLyHeight = value
  8457. if (this.pipController) {
  8458. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8459. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  8460. }
  8461. })
  8462. .width('76%')
  8463. }
  8464. .margin({
  8465. left: 20,
  8466. right: 15,
  8467. top: 5,
  8468. bottom: 5
  8469. })
  8470. }
  8471. Row() {
  8472. Text(`歌词字号:`)
  8473. .fontSize(14)
  8474. .fontColor(Color.White)
  8475. Slider({
  8476. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  8477. min: 12,
  8478. max: 30,
  8479. step: 0.1,
  8480. style: SliderStyle.OutSet
  8481. })
  8482. .blockColor(this.themeColor)
  8483. .trackColor($r('app.color.speed_text_color'))
  8484. .selectedColor(Color.White)
  8485. .trackThickness(6)
  8486. .onChange((value: number) => {
  8487. this.setLyricTextSize(value, isPip)
  8488. })
  8489. .width('76%')
  8490. }
  8491. .margin({
  8492. left: 20,
  8493. right: 15,
  8494. top: 5,
  8495. bottom: 5
  8496. })
  8497. Row() {
  8498. Text(`高亮倍数:`)
  8499. .fontSize(14)
  8500. .fontColor(Color.White)
  8501. Slider({
  8502. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  8503. min: 1,
  8504. max: 2,
  8505. step: 0.1,
  8506. style: SliderStyle.OutSet
  8507. })
  8508. .blockColor(this.themeColor)
  8509. .trackColor($r('app.color.speed_text_color'))
  8510. .selectedColor(Color.White)
  8511. .trackThickness(6)
  8512. .onChange((value: number) => {
  8513. this.setHighLyricTextSize(value, isPip)
  8514. })
  8515. .width('76%')
  8516. }
  8517. .margin({
  8518. left: 20,
  8519. right: 15,
  8520. top: 5,
  8521. bottom: 5
  8522. })
  8523. Row() {
  8524. Text(`歌词间隙:`)
  8525. .fontSize(14)
  8526. .fontColor(Color.White)
  8527. Slider({
  8528. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  8529. min: 0,
  8530. max: 100,
  8531. step: 1,
  8532. style: SliderStyle.OutSet
  8533. })
  8534. .blockColor(this.themeColor)
  8535. .trackColor($r('app.color.speed_text_color'))
  8536. .selectedColor(Color.White)
  8537. .trackThickness(6)
  8538. .onChange((value: number) => {
  8539. this.setLyricLineSpace(value, isPip)
  8540. })
  8541. .width('76%')
  8542. }
  8543. .margin({
  8544. left: 20,
  8545. right: 15,
  8546. top: 5,
  8547. bottom: 5
  8548. })
  8549. //取值间隔为100,默认为400,取值越大,字体越粗
  8550. Row() {
  8551. Text(`歌词字重:`)
  8552. .fontSize(14)
  8553. .fontColor(Color.White)
  8554. Slider({
  8555. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  8556. min: 100,
  8557. max: 900,
  8558. step: 100,
  8559. style: SliderStyle.OutSet
  8560. })
  8561. .blockColor(this.themeColor)
  8562. .trackColor($r('app.color.speed_text_color'))
  8563. .selectedColor(Color.White)
  8564. .trackThickness(6)
  8565. .onChange((value: number) => {
  8566. if (isPip) {
  8567. this.lyricTextWeightPip = value
  8568. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8569. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  8570. } else {
  8571. this.lyricTextWeight = value
  8572. this.lyricController.setTextWeight(this.lyricTextWeight)
  8573. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  8574. }
  8575. })
  8576. .width('76%')
  8577. }
  8578. .margin({
  8579. left: 20,
  8580. right: 15,
  8581. top: 5,
  8582. bottom: 5
  8583. })
  8584. if (!isPip) {
  8585. Row() {
  8586. Text(`歌词模糊:`)
  8587. .fontSize(14)
  8588. .fontColor(Color.White)
  8589. Slider({
  8590. value: isPip ? this.blurDegreePip : this.blurDegree,
  8591. min: 0,
  8592. max: 5,
  8593. step: 0.1,
  8594. style: SliderStyle.OutSet
  8595. })
  8596. .blockColor(this.themeColor)
  8597. .trackColor($r('app.color.speed_text_color'))
  8598. .selectedColor(Color.White)
  8599. .trackThickness(6)
  8600. .onChange((value: number) => {
  8601. this.setBlurDegree(value, isPip)
  8602. })
  8603. .width('76%')
  8604. }
  8605. .margin({
  8606. left: 20,
  8607. right: 15,
  8608. top: 5,
  8609. bottom: 15
  8610. })
  8611. }
  8612. Row() {
  8613. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  8614. // this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  8615. this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  8616. }
  8617. .justifyContent(FlexAlign.Center)
  8618. .margin({ top: 3, bottom: 10 })
  8619. }
  8620. }
  8621. private setBlurDegree(index: number, isPip: boolean) {
  8622. if (isPip) {
  8623. this.blurDegreePip = index
  8624. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  8625. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  8626. } else {
  8627. this.blurDegree = index
  8628. this.lyricController.setBlurDegree(this.blurDegree)
  8629. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  8630. }
  8631. }
  8632. private setLyricAlignMode(index: number, isPip: boolean) {
  8633. if (isPip) {
  8634. this.currentLyricAlignModePip = index
  8635. if (this.currentLyricAlignModePip === 1) {
  8636. this.lyricControllerXF.setAlignMode("left")
  8637. } else {
  8638. this.lyricControllerXF.setAlignMode("center")
  8639. }
  8640. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  8641. } else {
  8642. this.currentLyricAlignMode = index
  8643. if (this.currentLyricAlignMode === 1) {
  8644. this.lyricController.setAlignMode("left")
  8645. } else {
  8646. this.lyricController.setAlignMode("center")
  8647. }
  8648. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  8649. }
  8650. }
  8651. private setLyricTextSize(index: number, isPip: boolean) {
  8652. if (isPip) {
  8653. this.currentLyricSizePip = index
  8654. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  8655. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  8656. } else {
  8657. this.currentLyricSize = index
  8658. this.lyricController.setTextSize(this.currentLyricSize)
  8659. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  8660. }
  8661. }
  8662. private setHighLyricTextSize(scale: number, isPip: boolean) {
  8663. if (isPip) {
  8664. this.currentHightLyricSizePip = scale
  8665. this.lyricControllerXF
  8666. .setHighlightScale(this.currentHightLyricSizePip)
  8667. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  8668. } else {
  8669. this.currentHightLyricSize = scale
  8670. this.lyricController
  8671. .setHighlightScale(this.currentHightLyricSize)
  8672. PreferencesUtil.putSync('HighLyricTextSize', scale)
  8673. }
  8674. }
  8675. private setLyricLineSpace(index: number, isPip: boolean) {
  8676. if (isPip) {
  8677. this.currentLyricLineSpacePip = index
  8678. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  8679. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  8680. } else {
  8681. this.currentLyricLineSpace = index
  8682. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  8683. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  8684. }
  8685. }
  8686. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  8687. LogUtil.info('onecold isBG = ' + isBG)
  8688. if (isBG) { //如果是设置悬浮背景
  8689. this.pipBg = color
  8690. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  8691. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8692. return
  8693. }
  8694. if (isPip) {
  8695. this.currentLyricColorPip = color
  8696. this.lyricControllerXF
  8697. .setTextColor(this.currentLyricColorPip)
  8698. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  8699. } else {
  8700. this.currentLyricColor = color
  8701. this.lyricController
  8702. .setTextColor(this.currentLyricColor)
  8703. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  8704. }
  8705. }
  8706. private changeLyricHightLightColor(color: string, isPip: boolean) {
  8707. if (isPip) {
  8708. this.currentHighLightLyricColorPip = color
  8709. this.lyricControllerXF
  8710. .setHighlightColor(this.currentHighLightLyricColorPip)
  8711. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  8712. } else {
  8713. this.currentHighLightLyricColor = color
  8714. this.lyricController
  8715. .setHighlightColor(this.currentHighLightLyricColor)
  8716. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  8717. }
  8718. }
  8719. // 构建时间控制器
  8720. @Builder
  8721. BuildTimeControls() {
  8722. Column() {
  8723. // 时间显示
  8724. Text(this.getTimeText())
  8725. .fontSize(18)
  8726. .fontColor(Color.White)
  8727. .margin({ bottom: 10 })
  8728. Row() {
  8729. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  8730. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  8731. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  8732. }
  8733. .justifyContent(FlexAlign.Center)
  8734. }
  8735. .margin({ top: 12, bottom: 8 })
  8736. }
  8737. // 精度按钮组件
  8738. @Builder
  8739. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  8740. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8741. Column() {
  8742. Image(icon)
  8743. .width(28)
  8744. .margin({ bottom: 5 })
  8745. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  8746. Text(label)
  8747. .fontSize(12)
  8748. .fontColor('#FFFFFF')
  8749. }
  8750. }
  8751. .backgroundColor(Color.Transparent)
  8752. .enabled(!this.isButtonDisabled(step))
  8753. .onClick(() => this.handlePrecisionAdjust(step))
  8754. .padding(5)
  8755. .width(66)
  8756. .height(66)
  8757. .margin({ left: 18, right: 18 })
  8758. .border({
  8759. color: '#FFFFFF',
  8760. width: 1.8
  8761. })
  8762. }
  8763. private handlePrecisionAdjust(step: number) {
  8764. if (step === 0) {
  8765. this.timeOffset = 0
  8766. return
  8767. }
  8768. // 精度处理:保留1位小数
  8769. const newOffset = Number((this.timeOffset + step).toFixed(5))
  8770. // 边界保护(±15.0秒)
  8771. if (newOffset < -30.0 || newOffset > 30.0) {
  8772. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  8773. return
  8774. }
  8775. // 状态更新
  8776. this.timeOffset = newOffset
  8777. }
  8778. // 按钮禁用逻辑
  8779. private isButtonDisabled(step: number): boolean {
  8780. const futureOffset = this.timeOffset + step
  8781. return (futureOffset < -30.0) || (futureOffset > 30.0)
  8782. }
  8783. // 时间显示文本升级
  8784. private getTimeText(): string {
  8785. const absValue = Math.abs(this.timeOffset)
  8786. return this.timeOffset === 0
  8787. ? '歌词时间已重置'
  8788. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  8789. }
  8790. // 导入 本地歌词 搜索歌词
  8791. @Builder
  8792. pushLyricButton(icon: Resource, step: number, label: string) {
  8793. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8794. Row() {
  8795. Image(icon)
  8796. .width(14)
  8797. .margin({ left: 13 })
  8798. Text(label)
  8799. .fontSize(12)
  8800. .margin({ left: 6 })
  8801. .fontColor('#FFFFFF')
  8802. }
  8803. }
  8804. .onClick(() => {
  8805. switch (step) {
  8806. case 0:
  8807. this.callFilePickerSelectFileForLyric()
  8808. break;
  8809. case 1:
  8810. //判断有没有设置api
  8811. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  8812. this.isLyricSetting = false
  8813. this.showTipsDialog()
  8814. return
  8815. }
  8816. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8817. ToastUtil.showToast('正在获取')
  8818. this.isLyricSetting = false
  8819. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8820. this.initLyric(lyricPath, true);
  8821. }
  8822. break;
  8823. }
  8824. })
  8825. .padding(5)
  8826. .width(110)
  8827. .backgroundColor(Color.Transparent)
  8828. .height(40)
  8829. .margin({ left: 6, right: 6 })
  8830. .border({
  8831. color: '#FFFFFF',
  8832. radius: 20,
  8833. width: 1.8
  8834. })
  8835. }
  8836. showVipDialog() {
  8837. DialogHelper.showCustomContentDialog({
  8838. dialogId: 'vip',
  8839. title: "友情提示",
  8840. autoCancel: false, //点击遮障层时,不关闭弹窗
  8841. backCancel: true, //点击返回键,不关闭弹窗
  8842. contentBuilder: () => {
  8843. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  8844. },
  8845. buttons: [],
  8846. })
  8847. }
  8848. //去赞助的自定义内容
  8849. @Builder
  8850. customVipBuilder(content: string) {
  8851. Column() {
  8852. Text(content)
  8853. .fontColor(Color.Gray)
  8854. .fontSize(16)
  8855. .alignSelf(ItemAlign.Start)
  8856. .margin({ bottom: 15 })
  8857. .fontSize(16)
  8858. Row() {
  8859. Button('取消')
  8860. .fontColor(Color.White)
  8861. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8862. .height(50)
  8863. .layoutWeight(1)
  8864. .stateEffect(true)
  8865. .margin({ right: 6 })
  8866. .onClick(() => {
  8867. DialogHelper.closeDialog('vip'); //关闭弹框
  8868. })
  8869. Button('开通')
  8870. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8871. .layoutWeight(1)
  8872. .height(50)
  8873. .backgroundColor(this.themeColor)
  8874. .stateEffect(true)
  8875. .margin({ left: 6 })
  8876. .onClick(() => {
  8877. DialogHelper.closeDialog('vip'); //关闭弹框
  8878. this.isShowPlay = false
  8879. this.mType = 1 //跳转到用户中心
  8880. // router.pushUrl({
  8881. // url: 'pages/VipPage'
  8882. // }, router.RouterMode.Single);
  8883. })
  8884. }
  8885. }
  8886. .width("100%")
  8887. .padding(10)
  8888. }
  8889. showTipsDialog() {
  8890. DialogHelper.showCustomContentDialog({
  8891. dialogId: 'tips',
  8892. title: "友情提示",
  8893. autoCancel: false, //点击遮障层时,不关闭弹窗
  8894. backCancel: true, //点击返回键,不关闭弹窗
  8895. contentBuilder: () => {
  8896. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  8897. },
  8898. buttons: [],
  8899. })
  8900. }
  8901. @Builder
  8902. customTipsBuilder(content: string) {
  8903. Column() {
  8904. Text(content)
  8905. .fontColor(Color.Gray)
  8906. .fontSize(16)
  8907. .alignSelf(ItemAlign.Start)
  8908. .margin({ bottom: 15 })
  8909. .fontSize(16)
  8910. Row() {
  8911. Button('取消')
  8912. .fontColor(Color.White)
  8913. .backgroundColor(this.themeColor)
  8914. .height(50)
  8915. .layoutWeight(1)
  8916. .stateEffect(true)
  8917. .margin({ right: 6 })
  8918. .onClick(() => {
  8919. DialogHelper.closeDialog('tips'); //关闭弹框
  8920. })
  8921. Button('跳转')
  8922. .fontColor(Color.White)//
  8923. .layoutWeight(1)
  8924. .height(50)
  8925. .backgroundColor(this.themeColor)
  8926. .stateEffect(true)
  8927. .margin({ left: 6 })
  8928. .onClick(() => {
  8929. DialogHelper.closeDialog('tips'); //关闭弹框
  8930. this.isShowEdit = false
  8931. this.longItemFilePath = ''
  8932. // if(this.isGridMusic&&!this.isShowPlay){
  8933. // this.longItemFilePath== ''
  8934. // }else{
  8935. // this.isShowEdit = false
  8936. // }
  8937. this.isShowMoreView = false;
  8938. this.isShowPlay = false
  8939. this.mType = 4
  8940. // router.pushUrl({
  8941. // url: 'pages/SettingPage'
  8942. // }, router.RouterMode.Single);
  8943. })
  8944. }
  8945. }
  8946. .width("100%")
  8947. .padding(10)
  8948. }
  8949. @Builder
  8950. PlayMoreSheet() {
  8951. Column() {
  8952. this.MoreList()
  8953. }
  8954. .width('100%')
  8955. .height('100%')
  8956. }
  8957. @Builder
  8958. MoreList() {
  8959. Scroll() {
  8960. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  8961. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  8962. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8963. Row() {
  8964. if (more.id === 3&&this.currentSong) {
  8965. Image(more.image)
  8966. .width(24)
  8967. .height(24)
  8968. .margin({ left: 10, right: 10 })
  8969. Text(more.title)
  8970. .fontSize(16)
  8971. .fontColor(Color.White)
  8972. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  8973. height: this.isCoverOpacity() ? '95%' : '95%',
  8974. dragBar: true,
  8975. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8976. showClose: true,
  8977. blurStyle: BlurStyle.Thin,
  8978. backgroundColor: Color.Transparent,
  8979. title: { title: '歌曲信息' }
  8980. })
  8981. } else if (more.id === 15 && this.currentSong) { //编辑标签
  8982. Image(more.image)
  8983. .width(24)
  8984. .height(24)
  8985. .margin({ left: 10, right: 10 })
  8986. Text(more.title)
  8987. .fontSize(16)
  8988. .fontColor(Color.White)
  8989. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  8990. height: '99%',
  8991. dragBar: true,
  8992. showClose: true,
  8993. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8994. // blurStyle:BlurStyle.Thin,
  8995. // backgroundColor:Color.Transparent,
  8996. title: { title: '编辑标签' }
  8997. })
  8998. } else if (more.id === 5) { //定时关闭
  8999. Image(more.image)
  9000. .width(24)
  9001. .height(24)
  9002. .margin({ left: 10, right: 10 })
  9003. Text(more.title)
  9004. .fontSize(16)
  9005. .fontColor(Color.White)
  9006. .onClick(() => {
  9007. this.doMore(more.id)
  9008. })
  9009. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  9010. height: this.isCoverOpacity() ? '95%' : '95%',
  9011. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9012. dragBar: true,
  9013. showClose: true,
  9014. title: { title: $r('app.string.time_close') }
  9015. })
  9016. } else if (more.id === 2) { //歌词设置
  9017. Image(more.image)
  9018. .width(24)
  9019. .height(24)
  9020. .margin({ left: 10, right: 10 })
  9021. Text(more.title)
  9022. .fontSize(16)
  9023. .fontColor(Color.White)
  9024. } else if (more.id === 16) { //悬浮歌词设置
  9025. Image(more.image)
  9026. .width(24)
  9027. .height(24)
  9028. .margin({ left: 10, right: 10 })
  9029. Text(more.title)
  9030. .fontSize(16)
  9031. .fontColor(Color.White)
  9032. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  9033. height: this.isCoverOpacity() ? '95%' : '95%',
  9034. dragBar: true,
  9035. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9036. showClose: true,
  9037. blurStyle: BlurStyle.Thin,
  9038. backgroundColor: Color.Transparent,
  9039. title: { title: '悬浮歌词' }
  9040. })
  9041. } else if (more.id === 11) {
  9042. Image(more.image)
  9043. .width(24)
  9044. .height(24)
  9045. .margin({ left: 10, right: 10 })
  9046. Text(more.title)
  9047. .fontSize(16)
  9048. .fontColor(Color.White)
  9049. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  9050. height: this.isCoverOpacity() ? '95%' : '60%',
  9051. dragBar: true,
  9052. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9053. showClose: true,
  9054. blurStyle: BlurStyle.Thin,
  9055. backgroundColor: Color.Transparent,
  9056. title: { title: '跳过头尾' }
  9057. })
  9058. } else if (more.id === 12) { //投播
  9059. AVCastPicker({
  9060. customPicker: (): void => this.TPImageBuilder(more),
  9061. onStateChange: (state) => {
  9062. if (state == AVCastPickerState.STATE_APPEARING) {
  9063. console.log(' The picker starts showing.');
  9064. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  9065. console.log(' The picker finishes presenting.');
  9066. }
  9067. },
  9068. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  9069. sessionType: 'video'
  9070. })
  9071. .id('AVCastPicker')
  9072. } else {
  9073. Image(more.image)
  9074. .width(24)
  9075. .height(24)
  9076. .margin({ left: 10, right: 10 })
  9077. .onClick(() => {
  9078. this.doMore(more.id)
  9079. })
  9080. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  9081. .fontSize(16)
  9082. .fontColor(Color.White)
  9083. .onClick(() => {
  9084. this.doMore(more.id)
  9085. })
  9086. Select([//倍速
  9087. { value: '0.25x' },
  9088. { value: '0.5x' },
  9089. { value: '0.75x' },
  9090. { value: '1x' },
  9091. { value: '1.25x' },
  9092. { value: '1.5x' },
  9093. { value: '1.75x' },
  9094. { value: '2x' },
  9095. { value: '3x' }])
  9096. .font({ size: 16, weight: FontWeight.Medium })
  9097. .fontColor($r('sys.color.white'))
  9098. .margin({ left: 25 })
  9099. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  9100. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  9101. .value(Utility.optimizedFormat(this.playSpeed))
  9102. .onSelect(async (_index: number, text?: string | undefined) => {
  9103. let speed = parseFloat(text?.replace('x', '') || '1');
  9104. if (!CommonConstants.video_speed_list.includes(speed)) {
  9105. speed = 1;
  9106. }
  9107. this.playSpeed = speed
  9108. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9109. })
  9110. Slider({
  9111. value: this.volume,
  9112. min: 0,
  9113. max: 1,
  9114. step: 0.1,
  9115. style: SliderStyle.OutSet
  9116. })
  9117. .margin({ left: 18, right: 8 })
  9118. .blockColor(this.themeColor)
  9119. .trackColor($r('app.color.speed_text_color'))
  9120. .selectedColor(Color.White)
  9121. .trackThickness(9)
  9122. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  9123. .onChange((value: number) => {
  9124. this.volume = value;
  9125. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9126. PreferencesUtil.putSync('DefalutVolume',this.volume)
  9127. })
  9128. .layoutWeight(1)
  9129. Blank()
  9130. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  9131. .selectedColor(this.themeColor)
  9132. .switchPointColor(Color.White)
  9133. .margin({ right: 15 })
  9134. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9135. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  9136. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9137. if (more.id == 6) {
  9138. this.isMusicMemoryPlay = checked;
  9139. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  9140. if (this.isMusicMemoryPlay) {
  9141. ToastUtil.showToast('记忆播放已开启')
  9142. } else {
  9143. ToastUtil.showToast('记忆播放已关闭')
  9144. }
  9145. }
  9146. })
  9147. .width(48)
  9148. .height(24);
  9149. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  9150. .selectedColor(this.themeColor)
  9151. .switchPointColor(Color.White)
  9152. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9153. .margin({ right: 15 })
  9154. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  9155. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9156. if (more.id == 7) {
  9157. this.isMusicBGCover = checked;
  9158. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  9159. if (this.isMusicBGCover) {
  9160. ToastUtil.showToast('播放背景随音乐封面已开启')
  9161. } else {
  9162. ToastUtil.showToast('播放背景随音乐封面已关闭')
  9163. }
  9164. }
  9165. })
  9166. .width(48)
  9167. .height(24);
  9168. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  9169. .selectedColor(this.themeColor)
  9170. .switchPointColor(Color.White)
  9171. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9172. .margin({ right: 15 })
  9173. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  9174. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9175. if (more.id == 8) {
  9176. this.isSavePlayMode = checked;
  9177. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  9178. if (this.isSavePlayMode) {
  9179. ToastUtil.showToast('保存播放模式已开启')
  9180. } else {
  9181. ToastUtil.showToast('保存播放模式已关闭')
  9182. }
  9183. }
  9184. })
  9185. .width(48)
  9186. .height(24);
  9187. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  9188. .selectedColor(this.themeColor)
  9189. .switchPointColor(Color.White)
  9190. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9191. .margin({ right: 15 })
  9192. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  9193. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9194. if (more.id == 13) {
  9195. this.isCoverRectangle = checked;
  9196. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  9197. if (this.isCoverRectangle) {
  9198. ToastUtil.showToast('封面方形已开启')
  9199. this.animationRoFun()
  9200. } else {
  9201. ToastUtil.showToast('封面圆形已开启')
  9202. this.animationRoFun()
  9203. }
  9204. }
  9205. })
  9206. .width(48)
  9207. .height(24);
  9208. }
  9209. }
  9210. .width('100%')
  9211. .height(45)
  9212. .padding(15)
  9213. .backgroundColor(Color.Transparent)
  9214. .borderRadius(12)
  9215. .margin({ bottom: 6 })
  9216. }
  9217. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  9218. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  9219. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  9220. .backgroundColor(Color.Transparent)
  9221. .onClick(() => {
  9222. this.doMore(more.id)
  9223. })
  9224. });
  9225. }
  9226. .width('100%')
  9227. .padding(16)
  9228. }.margin({ bottom: 18 })
  9229. }
  9230. @Builder
  9231. TPImageBuilder(more: MoreItem): void {
  9232. Row() {
  9233. Image($r('app.media.tuoping'))
  9234. .width(22)
  9235. .height(22)
  9236. .margin({ left: 10, right: 10 })
  9237. Text(more.title)
  9238. .fontSize(16)
  9239. .fontColor(Color.White)
  9240. }
  9241. .width('100%')
  9242. .layoutWeight(1)
  9243. .alignItems(VerticalAlign.Center)
  9244. .justifyContent(FlexAlign.Start)
  9245. }
  9246. private moreItems: MoreItem[] = [
  9247. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  9248. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  9249. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  9250. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  9251. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  9252. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  9253. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  9254. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  9255. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  9256. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  9257. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  9258. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  9259. { id: 4, image: $r('app.media.share2'), title: '分享' },
  9260. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  9261. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  9262. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  9263. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  9264. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  9265. ];
  9266. @State isShowMoreView: boolean = false;
  9267. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  9268. @State isShowTimeCloseMore: boolean = false
  9269. @State isShowDetailMore: boolean = false
  9270. @State isMusicBGCover: boolean = true
  9271. @State isSavePlayMode: boolean = true
  9272. @State isLyricSetting: boolean = false
  9273. @State isJumpSetting: boolean = false
  9274. @State isShowEdit: boolean = false
  9275. @State showPipLyric: boolean = false
  9276. async setRingTone() {
  9277. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  9278. return
  9279. }
  9280. // 确定后的逻辑
  9281. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  9282. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  9283. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  9284. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  9285. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  9286. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  9287. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  9288. , this.videoUrl, this.name).then(res => {
  9289. LogUtil.info('onecold setFlag :' + res);
  9290. });
  9291. }
  9292. doMore(moreId: number) {
  9293. switch (moreId) {
  9294. case 2: //歌词
  9295. this.isLyricSetting = !this.isLyricSetting;
  9296. this.isShowMoreView = false
  9297. break;
  9298. case 3: //详情
  9299. this.isShowDetailMore = !this.isShowDetailMore;
  9300. break;
  9301. case 4: //分享
  9302. if (this.currentSong !== undefined) {
  9303. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  9304. }
  9305. this.isShowMoreView = false
  9306. break;
  9307. case 5: //定时关闭
  9308. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  9309. break;
  9310. case 10: //设为铃声
  9311. this.setRingTone()
  9312. this.isShowMoreView = false
  9313. break;
  9314. case 11: //跳过头尾
  9315. this.isJumpSetting = !this.isJumpSetting;
  9316. break;
  9317. case 13: //倍速
  9318. break;
  9319. case 14: //搜索封面
  9320. if (this.currentSong !== undefined) {
  9321. this.doSearchCover(this.currentSong)
  9322. }
  9323. this.isShowMoreView = false
  9324. break;
  9325. case 15: //编辑标签
  9326. this.setEditStrEmpty()
  9327. this.tempLyricContent = this.lyricContent
  9328. this.isShowEdit = !this.isShowEdit;
  9329. break;
  9330. case 16: //悬浮歌词
  9331. this.showPipLyric = !this.showPipLyric;
  9332. break;
  9333. case 17: //横屏模式
  9334. if (this.isLandscape) {
  9335. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9336. } else {
  9337. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9338. }
  9339. this.isShowMoreView = false
  9340. break;
  9341. case 20://AB循环
  9342. this.isABSheet = !this.isABSheet;
  9343. this.isShowMoreView = false
  9344. break;
  9345. }
  9346. }
  9347. //AB循环
  9348. @State isOpenAB:boolean = false
  9349. @State jumpATime:number = 0
  9350. @State jumpBTime:number = 0
  9351. @State isABSheet:boolean = false
  9352. @Builder
  9353. ABLoopSheet() {
  9354. ABLoopComptent({
  9355. jumpATime:this.jumpATime,
  9356. jumpBTime:this.jumpBTime,
  9357. onClickAItem: async ()=>{
  9358. if(this.mIjkMediaPlayer){
  9359. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  9360. }
  9361. },
  9362. onClickBItem: async ()=>{
  9363. if(this.mIjkMediaPlayer){
  9364. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  9365. if(this.jumpBTime<=this.jumpATime){
  9366. ToastUtil.showToast('设置B点时间不能小于A点时间')
  9367. this.jumpBTime = 0
  9368. }
  9369. }
  9370. },
  9371. onCancleButtonClick: async ()=>{
  9372. this.isOpenAB = false
  9373. this.isABSheet = false
  9374. },
  9375. onStartButtonClick: async ()=>{
  9376. this.isABSheet = false
  9377. this.startABLoop()
  9378. },
  9379. })
  9380. }
  9381. //开始AB循环
  9382. startABLoop(){
  9383. if(this.mIjkMediaPlayer){
  9384. this.seekTo(this.jumpATime+'')
  9385. this.isOpenAB = true
  9386. }
  9387. }
  9388. /**
  9389. * 切换横竖屏
  9390. *
  9391. */
  9392. setOrientation(orientation: number) {
  9393. this.windowClass.setPreferredOrientation(orientation).then(() => {
  9394. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  9395. }).catch((err: BusinessError) => {
  9396. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  9397. });
  9398. }
  9399. /**
  9400. * 画中画功能(悬浮歌词功能)
  9401. *
  9402. */
  9403. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  9404. pipController?: PiPWindow.PiPController;
  9405. navigationId: string = '';
  9406. @State curState: string = '';
  9407. @State curError: ResourceStr = '';
  9408. @State pipBg: string = '#E8E8E8'
  9409. @State buttonAction: string = '';
  9410. //开启画中画功能
  9411. async startPip() {
  9412. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  9413. if (!this.pipController) {
  9414. await this.createPipController();
  9415. }
  9416. if (!this.pipController) {
  9417. Logger.info(`[${TAG}] pipController create error`);
  9418. return;
  9419. }
  9420. await this.pipController.startPiP();
  9421. }
  9422. async stopPip() {
  9423. if (!this.pipController) {
  9424. Logger.info(`[${TAG}] pipController is not exist`);
  9425. return;
  9426. }
  9427. this.isOpenPip = false
  9428. await this.pipController.stopPiP();
  9429. }
  9430. async createPipController() {
  9431. this.pipController = await PiPWindow.create({
  9432. context: getContext(this),
  9433. componentController: this.xcomponentController,
  9434. navigationId: this.navigationId,
  9435. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  9436. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  9437. customUIController: this.nodeController,
  9438. });
  9439. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  9440. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  9441. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9442. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  9443. this.onStateChange(state, reason);
  9444. });
  9445. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  9446. this.onActionEvent(event, status);
  9447. });
  9448. }
  9449. destroyPipController() {
  9450. if (!this.pipController) {
  9451. return;
  9452. }
  9453. this.pipController.off('stateChange');
  9454. this.pipController.off('controlPanelActionEvent');
  9455. this.pipController = undefined;
  9456. }
  9457. onStateChange(state: PiPWindow.PiPState, reason: string) {
  9458. switch (state) {
  9459. case PiPWindow.PiPState.ABOUT_TO_START:
  9460. this.curState = 'ABOUT_TO_START';
  9461. this.curError = $r('app.string.current_error_hint');
  9462. break;
  9463. case PiPWindow.PiPState.STARTED:
  9464. this.curState = 'STARTED';
  9465. this.curError = $r('app.string.current_error_hint');
  9466. break;
  9467. case PiPWindow.PiPState.ABOUT_TO_STOP:
  9468. this.curState = 'ABOUT_TO_STOP';
  9469. this.curError = $r('app.string.current_error_hint');
  9470. break;
  9471. case PiPWindow.PiPState.STOPPED:
  9472. this.curState = 'STOPPED';
  9473. this.curError = $r('app.string.current_error_hint');
  9474. this.stopPip()
  9475. this.destroyPipController()
  9476. break;
  9477. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  9478. this.curState = 'ABOUT_TO_RESTORE';
  9479. this.curError = $r('app.string.current_error_hint');
  9480. break;
  9481. case PiPWindow.PiPState.ERROR:
  9482. this.curState = 'ERROR';
  9483. this.curError = reason;
  9484. break;
  9485. default:
  9486. break;
  9487. }
  9488. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  9489. }
  9490. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  9491. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  9492. switch (event) {
  9493. case 'playbackStateChanged':
  9494. if (status === 0) {
  9495. this.pause();
  9496. } else {
  9497. console.info('onecold startPlayOrResumePlay 9869')
  9498. this.startPlayOrResumePlay();
  9499. }
  9500. break;
  9501. case 'nextVideo':
  9502. // 切换到下一个视频
  9503. this.playNext()
  9504. break;
  9505. case 'previousVideo':
  9506. // 切换到上一个视频
  9507. this.playPrevious()
  9508. break;
  9509. case 'previousVideo':
  9510. // 切换到上一个视频
  9511. this.playPrevious()
  9512. break;
  9513. default:
  9514. }
  9515. this.buttonAction = event + `-status:${status}`;
  9516. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  9517. }
  9518. /**
  9519. * 画中画功能(悬浮歌词功能)结束
  9520. *
  9521. */
  9522. async doSearchCover(item: VideoItem): Promise<string> {
  9523. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9524. this.isShowMoreView = false;
  9525. this.showTipsDialog();
  9526. return ''; // Return empty string when no API is configured
  9527. }
  9528. if (!item) {
  9529. return ''; // Return empty string if item is undefined
  9530. }
  9531. const artist = item?.artist || ''; // Use empty string if artist is missing
  9532. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  9533. }
  9534. /**
  9535. *api搜索封面
  9536. *item,根据title和artist
  9537. */
  9538. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  9539. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  9540. LogUtil.debug("onecold res =" + res);
  9541. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9542. if (item.filePath == this.currentSong?.filePath) {
  9543. this.cover = res;
  9544. if (this.currentSong) {
  9545. this.currentSong.pixelMapPath = res;
  9546. }
  9547. }
  9548. // Update pixel map path but always return res regardless of success
  9549. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  9550. if (success) {
  9551. this.doUpdateData();
  9552. console.log("onecold 更新音乐封面成功,数据库已同步");
  9553. } else {
  9554. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  9555. }
  9556. // Note: We don't resolve/reject here because we already returned res
  9557. });
  9558. LogUtil.debug("onecold this.cover =" + this.cover);
  9559. }
  9560. return res; // Always return res regardless of updatePixelMapPath result
  9561. });
  9562. }
  9563. @State jumpTopTime: number = 0
  9564. @State jumpEndTime: number = 0
  9565. @State isOpenJump: boolean = false
  9566. @Builder
  9567. JumpTopEndSheet() {
  9568. Scroll() {
  9569. Column() {
  9570. Column() {
  9571. Text('仅对本播放列表有效')
  9572. .fontSize(16)
  9573. .fontColor($r('app.color.text_color'))
  9574. // 跳过头尾
  9575. Column() {
  9576. Row() {
  9577. Text('跳过片头:')
  9578. .fontSize(16)
  9579. .fontColor($r('app.color.text_color'))
  9580. Text(this.jumpTopTime + 's')
  9581. .fontSize(16)
  9582. .fontColor($r('app.color.text_color'))
  9583. }
  9584. .margin({ bottom: 5 })
  9585. Row() {
  9586. Slider({
  9587. value: this.jumpTopTime,
  9588. min: 0,
  9589. max: 120,
  9590. step: 1,
  9591. style: SliderStyle.OutSet
  9592. })
  9593. .blockColor(this.themeColor)
  9594. .trackColor($r('app.color.speed_text_color'))
  9595. .selectedColor(Color.White)
  9596. .trackThickness(8)
  9597. .onChange((value: number) => {
  9598. this.jumpTopTime = value;
  9599. })
  9600. .width('85%')
  9601. }
  9602. .alignItems(VerticalAlign.Top)
  9603. }
  9604. .margin({ top: 10, bottom: 10 })
  9605. // 跳过头尾
  9606. Column() {
  9607. Row() {
  9608. Text('跳过片尾:')
  9609. .fontSize(16)
  9610. .fontColor($r('app.color.text_color'))
  9611. Text(this.jumpEndTime + 's')
  9612. .fontSize(16)
  9613. .fontColor($r('app.color.text_color'))
  9614. }
  9615. .margin({ bottom: 5 })
  9616. Row() {
  9617. Slider({
  9618. value: this.jumpEndTime,
  9619. min: 0,
  9620. max: 120,
  9621. step: 1,
  9622. style: SliderStyle.OutSet
  9623. })
  9624. .blockColor(this.themeColor)
  9625. .trackColor($r('app.color.speed_text_color'))
  9626. .selectedColor(Color.White)
  9627. .trackThickness(8)
  9628. .onChange((value: number) => {
  9629. this.jumpEndTime = value;
  9630. })
  9631. .width('85%')
  9632. }
  9633. .alignItems(VerticalAlign.Top)
  9634. }
  9635. .margin({ top: 10, bottom: 10 })
  9636. Row() {
  9637. Button('保存设置')
  9638. .fontColor(Color.White)
  9639. .layoutWeight(1)
  9640. .height(40)
  9641. .width(80)
  9642. .backgroundColor(this.themeColor)
  9643. .stateEffect(true)
  9644. .margin({ left: 0, bottom: 20 })
  9645. .onClick(async () => {
  9646. if (!Utility.isNoble()) {
  9647. this.isJumpSetting = false
  9648. this.isShowMoreView = false
  9649. this.showVipDialog()
  9650. return
  9651. }
  9652. if (this.currentSong === undefined) {
  9653. return
  9654. }
  9655. if (this.modeType === 0) {
  9656. let parentPath = FileUtil.getParentPath(this.videoUrl)
  9657. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  9658. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  9659. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  9660. } else if (this.modeType === 1) { //媒体库
  9661. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  9662. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  9663. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  9664. } else if (this.modeType === 2) { //艺术家
  9665. if (this.currentSong?.artist) {
  9666. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  9667. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  9668. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  9669. }
  9670. } else if (this.modeType === 3) { //专辑
  9671. if (this.currentSong?.album) {
  9672. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  9673. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  9674. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  9675. }
  9676. }
  9677. ToastUtil.showShort("保存成功")
  9678. this.isJumpSetting = false
  9679. })
  9680. }
  9681. .margin({
  9682. left: 38,
  9683. right: 38,
  9684. top: 10,
  9685. bottom: 10
  9686. })
  9687. .width(120)
  9688. .height(50)
  9689. }
  9690. }
  9691. }
  9692. .width('100%')
  9693. .height('100%')
  9694. }
  9695. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  9696. private onStateVastChange(state: AVCastPickerState) {
  9697. if (state == AVCastPickerState.STATE_APPEARING) {
  9698. console.log('The picker starts showing.');
  9699. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  9700. console.log('The picker finishes presenting.');
  9701. }
  9702. }
  9703. private showSelectLyric() {
  9704. DialogHelper.showActionSheetDialog({
  9705. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  9706. // sheets: ["本地歌词", "搜索歌词"],
  9707. sheets: [
  9708. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  9709. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  9710. ],
  9711. maskColor: Color.Transparent,
  9712. backgroundColor: $r('app.color.bg_card'),
  9713. transition: AnimationHelper.transitionInDown(666),
  9714. onAction: (index) => {
  9715. switch (index) {
  9716. case 0:
  9717. this.callFilePickerSelectFileForLyric()
  9718. break;
  9719. case 1:
  9720. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9721. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9722. this.initLyric(lyricPath);
  9723. }
  9724. break;
  9725. }
  9726. }
  9727. })
  9728. }
  9729. // 拉起picker选择文件管理器
  9730. async callFilePickerSelectFileForLyric(): Promise<void> {
  9731. try {
  9732. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  9733. DocumentSelectOptions.maxSelectNumber = 1
  9734. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  9735. let documentPicker = new picker.DocumentViewPicker();
  9736. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  9737. Logger.info(TAG,
  9738. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  9739. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  9740. this.saveVideoDatasLyric(DocumentSelectResult)
  9741. }
  9742. }).catch((err: BusinessError) => {
  9743. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  9744. });
  9745. } catch (err) {
  9746. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  9747. }
  9748. }
  9749. async saveVideoDatasLyric(uris: string[]) {
  9750. if (ArrayUtil.isEmpty(uris)) {
  9751. return
  9752. }
  9753. let newUris: string[] = [];
  9754. for (let i = 0; i < uris.length; i++) {
  9755. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  9756. Logger.info(TAG, 'filePath uri: ' + filePath);
  9757. newUris.push(filePath)
  9758. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  9759. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  9760. fileIo.copyFileSync(file.fd, file2.fd)
  9761. fileIo.closeSync(file);
  9762. fileIo.closeSync(file2);
  9763. this.initLyric(filePath,false,false,true)
  9764. }
  9765. }
  9766. private initDelayPlay(context: object) {
  9767. this.mContext = context;
  9768. }
  9769. startPipLyric() {
  9770. if (this.pipController) {
  9771. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9772. PiPWindow.PiPControlStatus.PLAY);
  9773. }
  9774. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  9775. if (this.isOpenPip) {
  9776. this.startPip()
  9777. } else {
  9778. this.stopPip()
  9779. }
  9780. }
  9781. private startPlayOrResumePlay() {
  9782. this.startPipLyric()
  9783. this.mDestroyPage = false;
  9784. this.animationState = AnimationStatus.Running
  9785. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  9786. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  9787. this.stopProgressTask();
  9788. this.startProgressTask();
  9789. this.play(this.videoUrl.toString());
  9790. }
  9791. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  9792. this.mIjkMediaPlayer.start();
  9793. this.setProgress()
  9794. this.CONTROL_PlayStatus = PlayStatus.PLAY
  9795. }
  9796. this.setIsPlaying(true)
  9797. this.updateSessionPlayState(true)
  9798. this.watchStatus();
  9799. this.updateLastPlayTimeStr(this.videoUrl)
  9800. }
  9801. updateLastPlayTimeStr(filePath: string) {
  9802. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  9803. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  9804. if (success) {
  9805. this.getHistoryList(false)
  9806. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  9807. } else {
  9808. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  9809. }
  9810. });
  9811. }
  9812. private completionNum(num: number): string | number {
  9813. if (num < 10) {
  9814. return '0' + num;
  9815. } else {
  9816. return num;
  9817. }
  9818. }
  9819. private stringForTime(timeMs: number): string {
  9820. let totalSeconds: number | string = (timeMs / 1000);
  9821. let newSeconds: number | string = totalSeconds % 60;
  9822. let minutes: number | string = (totalSeconds / 60) % 60;
  9823. let hours: number | string = totalSeconds / 3600;
  9824. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  9825. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  9826. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  9827. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  9828. if (this.isCurrentTime) {
  9829. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  9830. this.oldSeconds = newSeconds
  9831. } else {
  9832. newSeconds = this.oldSeconds
  9833. }
  9834. }
  9835. newSeconds = this.completionNum(newSeconds);
  9836. if (hours > 0) {
  9837. return hours + ":" + minutes + ":" + newSeconds;
  9838. } else {
  9839. return minutes + ":" + newSeconds;
  9840. }
  9841. }
  9842. private setProgress() {
  9843. let position = this.mIjkMediaPlayer.getCurrentPosition();
  9844. let duration = this.mIjkMediaPlayer.getDuration();
  9845. let pos = 0;
  9846. if (duration > 0) {
  9847. this.slideEnable = true;
  9848. let curPercent = position / duration;
  9849. pos = curPercent * 100;
  9850. if (pos > this.PROGRESS_MAX_VALUE) {
  9851. this.progressValue = this.PROGRESS_MAX_VALUE
  9852. } else {
  9853. this.progressValue = pos;
  9854. }
  9855. }
  9856. // LogUtils.getInstance()
  9857. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9858. this.totalTime = this.stringForTime(duration);
  9859. if (position > duration) {
  9860. position = duration;
  9861. }
  9862. this.isCurrentTime = true;
  9863. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  9864. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  9865. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  9866. this.currentTime = this.stringForTime(position);
  9867. this.isCurrentTime = false
  9868. if (this.mIjkMediaPlayer.isPlaying()) {
  9869. this.randomColor =
  9870. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  9871. //如果是开启AB循环
  9872. if(this.isOpenAB){
  9873. if(position >=this.jumpBTime){
  9874. this.seekTo(this.jumpATime+'')
  9875. return
  9876. }
  9877. }
  9878. // 判断是否播放到结束时间
  9879. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  9880. if (position >= duration - this.jumpEndTime * 1000) {
  9881. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  9882. this.CONTROL_PlayStatus = PlayStatus.INIT
  9883. this.startPlayOrResumePlay();
  9884. }else if (this.playType == 2) { //2:正常播放,单曲播完
  9885. this.showRePlay();
  9886. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  9887. this.progressValue = this.PROGRESS_MAX_VALUE;
  9888. this.slideEnable = false;
  9889. this.stop();
  9890. // ToastUtil.showToast('开始重新播放')
  9891. }else{
  9892. this.playNext()
  9893. }
  9894. }
  9895. }
  9896. } else {
  9897. this.randomColor = 'rbg(0,0,0)'
  9898. }
  9899. }
  9900. private startProgressTask() {
  9901. let that = this;
  9902. this.updateProgressTimer = setInterval(() => {
  9903. //LogUtils.getInstance().LOGI("startProgressTask");
  9904. if (!that.mDestroyPage) {
  9905. that.setProgress();
  9906. }
  9907. }, 300);
  9908. }
  9909. private stopProgressTask() {
  9910. LogUtils.getInstance().LOGI("stopProgressTask");
  9911. clearInterval(this.updateProgressTimer);
  9912. }
  9913. private showLoadIng() {
  9914. this.loadingVisible = Visibility.Visible;
  9915. this.replayVisible = Visibility.None;
  9916. }
  9917. private hideLoadIng() {
  9918. this.loadingVisible = Visibility.None;
  9919. this.replayVisible = Visibility.None;
  9920. }
  9921. private showRePlay() {
  9922. this.loadingVisible = Visibility.None;
  9923. this.replayVisible = Visibility.Visible;
  9924. }
  9925. private async play(url: string) {
  9926. let that = this;
  9927. that.showLoadIng();
  9928. this.isOpenAB = false
  9929. //设置XComponent回调的context
  9930. if (!!this.mContext) {
  9931. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  9932. }
  9933. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  9934. this.mIjkMediaPlayer.reset();
  9935. }
  9936. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  9937. //设置debug模式
  9938. this.mIjkMediaPlayer.setDebug(false);
  9939. //初始化配置
  9940. this.mIjkMediaPlayer.native_setup();
  9941. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  9942. if(this.volumeSmall){
  9943. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  9944. this.mIjkMediaPlayer.setVolume('1', '1');
  9945. }else{
  9946. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9947. }
  9948. }else{
  9949. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9950. }
  9951. //设置视频源
  9952. this.mIjkMediaPlayer.setDataSource(url);
  9953. //设置视频源http请求头
  9954. let headers = new Map([
  9955. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  9956. ["referer", "https://www.bilibili.com"]
  9957. ]);
  9958. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  9959. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  9960. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  9961. // }
  9962. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  9963. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  9964. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  9965. const fileSize = await this.getFileSize(this.videoUrl);
  9966. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  9967. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  9968. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  9969. }
  9970. // 使用软件解码(通常比硬件解码更节省内存)
  9971. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  9972. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  9973. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  9974. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  9975. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  9976. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  9977. //停止预读的最小帧数
  9978. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  9979. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  9980. // 设置其他缓冲相关选项
  9981. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  9982. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  9983. //启动预加载
  9984. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  9985. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  9986. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  9987. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  9988. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  9989. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  9990. // 因此需要播放器丢包,才不会累积延时
  9991. // 这个和第三个参数packet-buffering无关。
  9992. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  9993. // 无限制收流
  9994. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  9995. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  9996. // 屏幕常亮
  9997. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  9998. // 设置超时
  9999. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  10000. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  10001. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  10002. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  10003. // 变速播放
  10004. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  10005. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10006. let Speed = this.mIjkMediaPlayer.getSpeed()
  10007. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  10008. //是否开启循环播放
  10009. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  10010. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  10011. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  10012. if (height === 0) {
  10013. return;
  10014. }
  10015. const va = width / height;
  10016. const vpa = that.videoParentAspectRatio;
  10017. if (vpa > va) {
  10018. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  10019. } else {
  10020. that.videoWidth = '100%';
  10021. }
  10022. if (width && height) {
  10023. that.videoAspectRatio = width / height;
  10024. }
  10025. LogUtils.getInstance()
  10026. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  10027. that.hideLoadIng();
  10028. }
  10029. }
  10030. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  10031. let mOnPreparedListener: OnPreparedListener = {
  10032. onPrepared: async () => {
  10033. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  10034. try {
  10035. // this.cover = this.songList[this.curIndex].pixelMapPath
  10036. // this.artist = this.songList[this.curIndex].artist
  10037. // this.videoUrl = this.songList[this.curIndex].filePath
  10038. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10039. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  10040. this.setImageColor2(this.cover)
  10041. } else {
  10042. this.getImageColor();
  10043. }
  10044. //保存碰一碰分享的当前的歌曲
  10045. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  10046. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10047. await this.initLyric(lyricPath);
  10048. setTimeout(() => {
  10049. this.avSessionController.initAvSession(false);
  10050. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  10051. this.setAvSessionListener();
  10052. this.updateSessionPlayState(true)
  10053. this.setCurrentPlayMode()
  10054. }, 500)
  10055. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10056. let timeoutPlay = 0
  10057. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10058. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  10059. timeoutPlay = 1000
  10060. }
  10061. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  10062. if (this.modeType === 0) { //文件夹
  10063. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10064. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  10065. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  10066. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  10067. } else if (this.modeType === 1) { //媒体库
  10068. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  10069. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  10070. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  10071. } else if (this.modeType === 2) { //艺术家
  10072. if (this.currentSong?.artist) {
  10073. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  10074. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  10075. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  10076. }
  10077. } else if (this.modeType === 3) { //专辑
  10078. if (this.currentSong?.album) {
  10079. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  10080. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  10081. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  10082. }
  10083. }
  10084. this.duration = this.mIjkMediaPlayer.getDuration()
  10085. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  10086. if (this.mIjkMediaPlayer != null) {
  10087. let jumpTopTimeMs = this.jumpTopTime*1000;
  10088. if (jumpTopTimeMs <= this.duration) {
  10089. // 调用 seekTo 方法,跳到指定时间
  10090. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  10091. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  10092. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10093. console.log('onecold position = '+position);
  10094. if (position > jumpTopTimeMs) {
  10095. jumpTopTimeMs = position
  10096. }
  10097. }
  10098. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10099. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10100. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  10101. }
  10102. }, timeoutPlay)
  10103. } else {
  10104. // 提示用户无法跳过
  10105. ToastUtil.showToast('跳过时间超过视频时长');
  10106. }
  10107. }
  10108. } else {
  10109. this.jumpTopTime = 0
  10110. this.jumpEndTime = 0
  10111. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  10112. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  10113. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  10114. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  10115. //记忆播放(每一首都会记忆播放)
  10116. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10117. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10118. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  10119. this.restorePlaybackPosition() //读取播放记忆功能
  10120. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  10121. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  10122. this.restorePlaybackPosition() //读取播放记忆功能
  10123. }
  10124. this.isFirstStartPlay = false
  10125. }, timeoutPlay)
  10126. } else {
  10127. this.isFirstStartPlay = false
  10128. }
  10129. }
  10130. this.saveLastPlayList()
  10131. } catch (error) {
  10132. let err: BusinessError = error as BusinessError;
  10133. console.error('onecold failed with err: ' + JSON.stringify(err));
  10134. }
  10135. }
  10136. }
  10137. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  10138. let mOnTimedTextListener: OnTimedTextListener = {
  10139. onTimedText: () => {
  10140. }
  10141. }
  10142. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  10143. let mOnCompletionListener: OnCompletionListener = {
  10144. onCompletion: () => {
  10145. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  10146. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  10147. this.playNext()
  10148. } else if (this.playType == 1) { //1:单片重复播放
  10149. this.CONTROL_PlayStatus = PlayStatus.INIT
  10150. console.info('onecold startPlayOrResumePlay 10592')
  10151. that.startPlayOrResumePlay();
  10152. } else if (this.playType == 2) { //2:正常播放,单曲播完
  10153. that.showRePlay();
  10154. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  10155. that.progressValue = this.PROGRESS_MAX_VALUE;
  10156. that.slideEnable = false;
  10157. that.stop();
  10158. // ToastUtil.showToast('开始重新播放')
  10159. } else if (this.playType == 3) { //3:随机播放
  10160. this.randomPlay()
  10161. }
  10162. }
  10163. }
  10164. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  10165. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  10166. onBufferingUpdate: (percent: number) => {
  10167. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  10168. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  10169. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  10170. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  10171. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  10172. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  10173. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  10174. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  10175. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  10176. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  10177. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  10178. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  10179. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  10180. let Looping = this.mIjkMediaPlayer.isLooping()
  10181. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  10182. }
  10183. }
  10184. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  10185. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  10186. onSeekComplete: () => {
  10187. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  10188. console.info('onecold startPlayOrResumePlay 10643')
  10189. that.startPlayOrResumePlay();
  10190. }
  10191. }
  10192. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  10193. let mOnInfoListener: OnInfoListener = {
  10194. onInfo: (what: number, extra: number) => {
  10195. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  10196. that.hideLoadIng();
  10197. }
  10198. }
  10199. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  10200. let mOnErrorListener: OnErrorListener = {
  10201. onError: (what: number, extra: number) => {
  10202. this.stopProgressTask();
  10203. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  10204. that.hideLoadIng();
  10205. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  10206. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  10207. } else {
  10208. ToastUtil.showToast(getContext()
  10209. .resourceManager
  10210. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  10211. }
  10212. }
  10213. }
  10214. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  10215. this.mIjkMediaPlayer.setMessageListener();
  10216. this.mIjkMediaPlayer.prepareAsync();
  10217. this.mIjkMediaPlayer.start();
  10218. }
  10219. //保存最后播放的那首歌和已经对应的播放列表
  10220. saveLastPlayList() {
  10221. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  10222. PreferencesUtil.putSync('LastMusicList', this.songList)
  10223. }
  10224. // 清空播放记录
  10225. clearVideoHistory() {
  10226. this.table.clearPlayHistory((success: boolean, error?: string) => {
  10227. if (success) {
  10228. this.historyList = [];
  10229. this.updateListData(this.historyList)
  10230. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  10231. ToastUtil.showToast('清空播放记录成功')
  10232. } else {
  10233. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  10234. }
  10235. });
  10236. }
  10237. public async setAvSessionListener() {
  10238. if (!this.avSessionController) {
  10239. return;
  10240. }
  10241. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  10242. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  10243. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  10244. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  10245. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  10246. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  10247. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  10248. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  10249. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  10250. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  10251. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  10252. }
  10253. setLoopMode() {
  10254. let itype = this.playType + 1
  10255. if (itype >= 4) {
  10256. this.playType = 0
  10257. ToastUtil.showToast('连续播放')
  10258. } else if (itype === 1) {
  10259. this.playType = 1
  10260. ToastUtil.showToast('单曲循环')
  10261. } else if (itype === 2) {
  10262. this.playType = 2
  10263. ToastUtil.showToast('单曲播完')
  10264. } else if (itype === 3) {
  10265. this.playType = 3
  10266. ToastUtil.showToast('随机播放')
  10267. } else if (itype === 0) {
  10268. this.playType = 0
  10269. ToastUtil.showToast('连续播放')
  10270. }
  10271. PreferencesUtil.putSync('musicPlayType', this.playType)
  10272. this.setCurrentPlayMode()
  10273. }
  10274. private sessionSetLoopModeCallback = (mode: number) => {
  10275. if (this.mIjkMediaPlayer != null) {
  10276. ToastUtil.showToast('当前播放模式:' + mode)
  10277. Logger.info('onecold 当前播放模式= ' + mode)
  10278. let hmPlayMode = mode + 1
  10279. if (hmPlayMode >= 4) {
  10280. hmPlayMode = 0
  10281. }
  10282. if (hmPlayMode === 1) {
  10283. this.playType = 1
  10284. ToastUtil.showToast('单曲循环')
  10285. } else if (hmPlayMode === 0) {
  10286. this.playType = 2
  10287. ToastUtil.showToast('单曲播完')
  10288. } else if (hmPlayMode === 3) {
  10289. this.playType = 3
  10290. ToastUtil.showToast('随机播放')
  10291. } else if (hmPlayMode === 2) {
  10292. this.playType = 0
  10293. ToastUtil.showToast('连续播放')
  10294. }
  10295. PreferencesUtil.putSync('musicPlayType', this.playType)
  10296. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  10297. let playBackState: avSession.AVPlaybackState = {
  10298. loopMode: hmPlayMode,
  10299. };
  10300. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  10301. console.info(`set setLoopMode AVPlaybackState successfully`);
  10302. }).catch((err: BusinessError) => {
  10303. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  10304. });
  10305. }
  10306. }
  10307. setCurrentPlayMode() {
  10308. if (!this.avSessionController) {
  10309. return;
  10310. }
  10311. let mLoopMode = 0
  10312. switch (this.playType) {
  10313. case 0:
  10314. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  10315. break;
  10316. case 1:
  10317. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  10318. break;
  10319. case 2:
  10320. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  10321. break;
  10322. case 3:
  10323. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  10324. break;
  10325. }
  10326. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  10327. let playBState: avSession.AVPlaybackState = {
  10328. loopMode: mLoopMode,
  10329. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  10330. };
  10331. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  10332. console.info(`set setLoopMode AVPlaybackState successfully`);
  10333. }).catch((err: BusinessError) => {
  10334. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  10335. });
  10336. }
  10337. private sessionToggleFavoriteCallback = (assetId: string) => {
  10338. if (this.mIjkMediaPlayer != null && this.currentSong) {
  10339. console.info(`on toggleFavorite `);
  10340. // 应用收到收藏命令,进行收藏处理。
  10341. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  10342. this.doFav(this.currentSong)
  10343. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  10344. let playbackState: avSession.AVPlaybackState = {
  10345. isFavorite: !this.isFac,
  10346. };
  10347. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  10348. console.info(`SetAVPlaybackState successfully`);
  10349. }).catch((err: BusinessError) => {
  10350. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  10351. });
  10352. }
  10353. }
  10354. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  10355. device: avSession.OutputDeviceInfo) => {
  10356. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  10357. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  10358. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  10359. await this.startCasting();
  10360. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  10361. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  10362. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  10363. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  10364. if (device) {
  10365. this.endCasting();
  10366. }
  10367. }
  10368. };
  10369. private async startCasting() {
  10370. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  10371. this.setPlaybackStateChangeListener();
  10372. this.pause();
  10373. this.initQueueItem();
  10374. this.prepare();
  10375. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  10376. refToIsCasting?.set(true);
  10377. this.castSeek = true;
  10378. this.isCastPlaying = true;
  10379. }
  10380. async changeCasting() {
  10381. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  10382. this.initQueueItem();
  10383. this.prepare();
  10384. this.setPlaybackStateChangeListener();
  10385. this.isCastPlaying = true;
  10386. this.castSeek = true;
  10387. }
  10388. public endCasting() {
  10389. this.avSessionController.getAvSession()?.stopCasting();
  10390. this.stopCast();
  10391. this.isCastPlaying = false;
  10392. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  10393. refToIsCasting?.set(false);
  10394. this.pause();
  10395. this.setIsPlaying(false);
  10396. // if (this.curIndex === this.curSource.index) {
  10397. // this.play
  10398. // this.seek(this.currentTime * 1000);
  10399. // this.setIsPlaying(true);
  10400. // } else {
  10401. // this.pauseVideo();
  10402. // this.setIsPlaying(false);
  10403. // }
  10404. }
  10405. public setIsPlaying(isPlayer: boolean) {
  10406. this.isPlaying = isPlayer;
  10407. }
  10408. private setPlaybackStateChangeListener(): void {
  10409. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  10410. this.castController?.on('endOfStream', this.reloadCasting);
  10411. this.castController?.on('playNext', this.playNextCallback);
  10412. this.castController?.on('playPrevious', this.playPreviousCallback);
  10413. }
  10414. private updateSessionPlayState(isPlay: boolean): void {
  10415. // if(!this.isBgPlayOpen)
  10416. // return
  10417. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  10418. this.setAVSessionPlayState({
  10419. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  10420. position: {
  10421. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  10422. updateTime: new Date().getTime()
  10423. }
  10424. });
  10425. }
  10426. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  10427. this.avSessionController.setAvSessionPlayState(playbackState)
  10428. }
  10429. private positionChange(position: number) {
  10430. this.currentTime2 = position / 1000;
  10431. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  10432. }
  10433. private playDurationChange(duration: number) {
  10434. this.duration = duration;
  10435. this.durationTime = Math.floor(this.duration / 1000);
  10436. this.durationStringTime = secondToTime((this.durationTime));
  10437. }
  10438. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  10439. const duration = playbackState?.extras?.duration;
  10440. if (typeof duration === 'number') {
  10441. this.playDurationChange(duration as number);
  10442. }
  10443. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  10444. this.positionChange(playbackState?.position?.elapsedTime);
  10445. }
  10446. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  10447. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  10448. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  10449. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  10450. this.isCastPlaying = false;
  10451. }
  10452. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  10453. this.isCastPlaying = true;
  10454. }
  10455. };
  10456. private reloadCasting = async () => {
  10457. let item = this.songList[this.curIndex];
  10458. let uri = fileUri.getUriFromPath(item.filePath);
  10459. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  10460. // description.startPosition = 0;
  10461. this.castItem = {
  10462. itemId: this.curIndex,
  10463. description: {
  10464. assetId: item.filePath,
  10465. title: item.name,
  10466. artist: '',
  10467. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  10468. // mediaUri: item.filePath,
  10469. fdSrc: {
  10470. fd: file.fd
  10471. },
  10472. // 该字段大写,音频'AUDIO',视频'VIDEO'
  10473. mediaType: 'VIDEO',
  10474. mediaSize: item.videoSize,
  10475. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  10476. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  10477. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  10478. duration: this.duration,
  10479. // albumCoverUri: 'https://www.example.jpeg',
  10480. // albumTitle: '《ExampleAlbum》',
  10481. appName: this.appName,
  10482. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  10483. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  10484. }
  10485. };
  10486. this.prepare();
  10487. this.isCastPlaying = true;
  10488. };
  10489. public playNextCallback = (): void => {
  10490. this.playNext()
  10491. };
  10492. public playPreviousCallback = (): void => {
  10493. this.playPrevious()
  10494. };
  10495. async prepare() {
  10496. await this.castController?.prepare(this.castItem);
  10497. await this.castController?.start(this.castItem);
  10498. }
  10499. public initQueueItem() {
  10500. let item = this.songList[this.curIndex];
  10501. let time = this.currentTime;
  10502. let uri = fileUri.getUriFromPath(item.filePath);
  10503. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  10504. this.castItem = {
  10505. itemId: this.curIndex,
  10506. description: {
  10507. assetId: item.filePath,
  10508. title: item.name,
  10509. artist: '',
  10510. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  10511. fdSrc: {
  10512. fd: file.fd
  10513. },
  10514. // 该字段大写,音频'AUDIO',视频'VIDEO'
  10515. mediaType: 'AUDIO',
  10516. mediaSize: item.videoSize,
  10517. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  10518. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  10519. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  10520. duration: this.duration,
  10521. // albumCoverUri: 'https://www.example.jpeg',
  10522. // albumTitle: '《ExampleAlbum》',
  10523. appName: this.appName,
  10524. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  10525. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  10526. }
  10527. };
  10528. }
  10529. async stopCast() {
  10530. try {
  10531. this.castController?.off('playbackStateChange');
  10532. this.castController?.off('endOfStream');
  10533. this.castController?.off('playNext');
  10534. this.castController?.off('playPrevious');
  10535. this.castController?.off('error');
  10536. } catch (error) {
  10537. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  10538. }
  10539. }
  10540. private sessionPlayCallback = (): void => {
  10541. console.info('onecold playOrPause 11050')
  10542. this.playOrPause()
  10543. };
  10544. private sessionPauseCallback = (): void => {
  10545. console.info('onecold playOrPause 11054')
  10546. this.pause()
  10547. };
  10548. private playOrPause() {
  10549. if (!this.debounce()) {
  10550. return;
  10551. }
  10552. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10553. this.pause();
  10554. } else {
  10555. console.info('onecold startPlayOrResumePlay 11064')
  10556. this.startPlayOrResumePlay();
  10557. this.playChange()
  10558. }
  10559. }
  10560. private sessionPlayNextCallback = (): void => {
  10561. this.playNext()
  10562. };
  10563. private sessionPlayPreviousCallback = (): void => {
  10564. this.playPrevious()
  10565. };
  10566. private sessionStopCallback = (): void => {
  10567. this.stop()
  10568. };
  10569. private sessionFastForwardCallback = (time?: number) => {
  10570. if (!time) {
  10571. return;
  10572. }
  10573. if (this.mIjkMediaPlayer != null) {
  10574. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  10575. let seeTime = curPosition + time * 1000;
  10576. // 限制 seekValue 在合法范围内
  10577. if (seeTime < 0) {
  10578. seeTime = 0;
  10579. } else if (seeTime > this.duration) {
  10580. seeTime = this.duration;
  10581. }
  10582. Logger.info('onecold seeTime= ' + seeTime)
  10583. this.setSeekToActionProgress(seeTime)
  10584. this.seekTo(seeTime + "")
  10585. }
  10586. };
  10587. /**
  10588. * Gesture method onActionUpdate.
  10589. *
  10590. * @param event Gesture event.手势拖动设置快进和后退
  10591. */
  10592. private setSeekToActionProgress(position: number) {
  10593. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  10594. let duration = this.mIjkMediaPlayer.getDuration();
  10595. let pos = 0;
  10596. if (duration > 0) {
  10597. this.slideEnable = true;
  10598. let curPercent = position / duration;
  10599. pos = curPercent * 100;
  10600. if (pos > this.PROGRESS_MAX_VALUE) {
  10601. this.progressValue = this.PROGRESS_MAX_VALUE
  10602. } else {
  10603. this.progressValue = pos;
  10604. }
  10605. }
  10606. // LogUtils.getInstance()
  10607. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10608. this.totalTime = this.stringForTime(duration);
  10609. if (position > duration) {
  10610. position = duration;
  10611. }
  10612. this.isCurrentTime = true;
  10613. this.currentTime = this.stringForTime(position);
  10614. this.isCurrentTime = false
  10615. }
  10616. private sessionRewindCallback = (time?: number) => {
  10617. if (!time) {
  10618. return;
  10619. }
  10620. if (this.mIjkMediaPlayer != null) {
  10621. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  10622. let seeTime = curPosition - time * 1000;
  10623. // 限制 seekValue 在合法范围内
  10624. if (seeTime < 0) {
  10625. seeTime = 0;
  10626. } else if (seeTime > this.duration) {
  10627. seeTime = this.duration;
  10628. }
  10629. Logger.info('onecold seeTime= ' + seeTime)
  10630. this.setSeekToActionProgress(seeTime)
  10631. this.seekTo(seeTime + "")
  10632. }
  10633. };
  10634. private sessionSeekCallback = (seekTime: number) => {
  10635. if (this.mIjkMediaPlayer != null) {
  10636. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  10637. this.seekTo(seekTime + "")
  10638. }
  10639. };
  10640. private async getFileSize(filePath: string): Promise<number> {
  10641. try {
  10642. const stat = await fs.stat(filePath);
  10643. return stat.size;
  10644. } catch (err) {
  10645. console.error('Failed to get file size: ' + err.message);
  10646. return 0;
  10647. }
  10648. }
  10649. private pause() {
  10650. if (this.mIjkMediaPlayer.isPlaying()) {
  10651. this.savePlaybackPosition();
  10652. this.mIjkMediaPlayer.pause();
  10653. this.setProgress();
  10654. this.mDestroyPage = true;
  10655. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  10656. this.updateSessionPlayState(false)
  10657. this.playChange()
  10658. if (this.pipController) {
  10659. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10660. PiPWindow.PiPControlStatus.PAUSE);
  10661. }
  10662. }
  10663. }
  10664. private stop() {
  10665. this.savePlaybackPosition();
  10666. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10667. this.mIjkMediaPlayer.stop();
  10668. this.mIjkMediaPlayer.release();
  10669. this.stopProgressTask();
  10670. this.updateSessionPlayState(false)
  10671. this.playChange()
  10672. this.watchStatus();
  10673. }
  10674. //保持记忆播放功能
  10675. private savePlaybackPosition() {
  10676. if (this.mIjkMediaPlayer != null) {
  10677. const position = this.mIjkMediaPlayer.getCurrentPosition();
  10678. // ToastUtil.showToast('保存记忆播放 = ' + position)
  10679. const duration = this.mIjkMediaPlayer.getDuration();
  10680. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  10681. // 如果播放位置接近视频末尾,则保存 position 为 0
  10682. const playbackPosition = (duration - position < threshold) ? 0 : position;
  10683. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  10684. }
  10685. }
  10686. //获取记忆播放功能
  10687. private restorePlaybackPosition() {
  10688. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10689. // ToastUtil.showToast('position = ' + position)
  10690. if (this.mIjkMediaPlayer != null && position > 0) {
  10691. // ToastUtil.showToast('seekTo = ' + position)
  10692. this.seekTo(position + "");
  10693. }
  10694. }
  10695. private seekTo(value: string) {
  10696. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  10697. ToastUtil.showToast('wma格式不支持拖动快进。')
  10698. return
  10699. }
  10700. this.isSeekTo = true
  10701. this.mIjkMediaPlayer.seekTo(value);
  10702. console.info('onecold startPlayOrResumePlay 11227')
  10703. // this.startPlayOrResumePlay()
  10704. // 在这里恢复计时器状态
  10705. this.setProgress()
  10706. this.isSeekTo = false
  10707. }
  10708. // 添加到下一首播放
  10709. private addToNextPlay(song: VideoItem) {
  10710. if (!this.debounce()) {
  10711. return;
  10712. }
  10713. if (this.currentSong) {
  10714. if (this.currentSong === song) {
  10715. ToastUtil.showToast('当前已经在播放这首歌了!')
  10716. return
  10717. }
  10718. }
  10719. // 如果未开始播放或队列为空
  10720. if (this.curIndex === -1 || this.songList.length === 0) {
  10721. this.songList = [song];
  10722. this.curIndex = 0;
  10723. this.doPlay(song)
  10724. return;
  10725. }
  10726. // 插入到当前索引+1的位置
  10727. const insertPos = this.curIndex + 1;
  10728. this.songList.splice(insertPos, 0, song);
  10729. this.songList = [...this.songList]; // 触发状态更新
  10730. this.sonDataSource.pushArrayData(this.songList)
  10731. ToastUtil.showToast('已添加至下一首播放')
  10732. }
  10733. //后退10s,可再设置设置默认几秒
  10734. backForward() {
  10735. if(this.mIjkMediaPlayer){
  10736. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  10737. let value = pos - Number(this.fastForwardSeconds) * 1000;
  10738. this.seekTo(value+"");
  10739. }
  10740. }
  10741. //快进10s,可再设置设置默认几秒
  10742. fastForward() {
  10743. if(this.mIjkMediaPlayer){
  10744. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  10745. let value = pos + Number(this.fastForwardSeconds) * 1000;
  10746. this.seekTo(value+"");
  10747. }
  10748. }
  10749. //下一个
  10750. private playNext() {
  10751. if (!this.debounce()) {
  10752. return;
  10753. }
  10754. if (this.playType == 3) { //3:随机播放
  10755. this.randomPlay()
  10756. return;
  10757. }
  10758. if (ArrayUtil.isNotEmpty(this.songList)) {
  10759. if (this.curIndex == this.songList.length - 1) {
  10760. this.curIndex = 0;
  10761. } else {
  10762. this.curIndex++;
  10763. }
  10764. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10765. this.stop();
  10766. this.currentSong = this.songList[this.curIndex]
  10767. this.videoUrl = this.songList[this.curIndex].filePath;
  10768. this.artist = this.songList[this.curIndex].artist
  10769. this.name = this.songList[this.curIndex].name
  10770. //this.cover = this.songList[this.curIndex].pixelMapPath
  10771. this.changeImageAnimation()
  10772. }
  10773. }
  10774. changeImageAnimation() {
  10775. if(this.openSkipSongAnimate){
  10776. // 第一步:淡出动画
  10777. this.getUIContext()?.animateTo({
  10778. duration: 500,
  10779. curve: Curve.EaseOut,
  10780. }, () => {
  10781. this.opacityValueImage = 0.1;
  10782. if(this.isCoverRectangle){
  10783. this.scaleValueImage = 0.88
  10784. }
  10785. });
  10786. // 第二步:切换图片后淡入
  10787. setTimeout(() => {
  10788. this.cover = this.songList[this.curIndex].pixelMapPath
  10789. this.getUIContext()?.animateTo({
  10790. duration: 500,
  10791. curve: Curve.EaseIn,
  10792. }, () => {
  10793. this.opacityValueImage = 1;
  10794. this.scaleValueImage = 1 // 图标恢复到原始大小
  10795. console.info('onecold startPlayOrResumePlay 11313')
  10796. this.startPlayOrResumePlay()
  10797. });
  10798. }, 500);
  10799. }else{
  10800. this.cover = this.songList[this.curIndex].pixelMapPath
  10801. console.info('onecold startPlayOrResumePlay 11319')
  10802. this.startPlayOrResumePlay()
  10803. }
  10804. }
  10805. // 存储已播放的歌曲索引
  10806. private playedIndices: Set<number> = new Set();
  10807. //随机播放
  10808. private randomPlay() {
  10809. // if (!this.debounce()) {
  10810. // return;
  10811. // }
  10812. if (ArrayUtil.isNotEmpty(this.songList)) {
  10813. if (this.songList.length > 3) {
  10814. // 如果所有歌曲都播放过一次,清空已播放索引集合
  10815. if (this.playedIndices.size === this.songList.length) {
  10816. this.playedIndices.clear();
  10817. }
  10818. // 随机选择一个未播放的歌曲索引
  10819. let newIndex: number;
  10820. // 添加超时机制防止无限循环
  10821. let attempt = 0;
  10822. const maxAttempts = 100; // 根据需求调整
  10823. do {
  10824. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  10825. attempt++;
  10826. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  10827. if (attempt >= maxAttempts) {
  10828. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  10829. newIndex = Math.floor(Math.random() * this.songList.length);
  10830. }
  10831. this.curIndex = newIndex;
  10832. this.playedIndices.add(newIndex);
  10833. } else {
  10834. // 当歌曲数量小于或等于3时,直接播放下一首
  10835. if (this.curIndex == this.songList.length - 1) {
  10836. this.curIndex = 0;
  10837. } else {
  10838. this.curIndex++;
  10839. }
  10840. }
  10841. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10842. this.stop();
  10843. this.currentSong = this.songList[this.curIndex];
  10844. this.videoUrl = this.songList[this.curIndex].filePath;
  10845. this.name = this.songList[this.curIndex].name;
  10846. this.artist = this.songList[this.curIndex].artist
  10847. // this.cover = this.songList[this.curIndex].pixelMapPath
  10848. this.changeImageAnimation()
  10849. }
  10850. }
  10851. private playIndex(index: number) {
  10852. if (!this.debounce()) {
  10853. return;
  10854. }
  10855. if (ArrayUtil.isNotEmpty(this.songList)) {
  10856. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10857. this.stop();
  10858. this.currentSong = this.songList[this.curIndex]
  10859. this.videoUrl = this.songList[index].filePath;
  10860. this.name = this.songList[index].name
  10861. this.artist = this.songList[this.curIndex].artist
  10862. this.curIndex = index;
  10863. this.changeImageAnimation()
  10864. }
  10865. }
  10866. //上一个
  10867. private playPrevious() {
  10868. if (!this.debounce()) {
  10869. return;
  10870. }
  10871. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  10872. this.randomModePlayFromHistory()
  10873. return;
  10874. }
  10875. if (this.curIndex == 0) {
  10876. this.curIndex = this.songList.length - 1;
  10877. } else {
  10878. this.curIndex--;
  10879. }
  10880. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10881. this.stop();
  10882. this.currentSong = this.songList[this.curIndex]
  10883. this.videoUrl = this.songList[this.curIndex].filePath;
  10884. this.name = this.songList[this.curIndex].name
  10885. this.artist = this.songList[this.curIndex].artist
  10886. this.changeImageAnimation()
  10887. }
  10888. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  10889. private randomModePlayFromHistory() {
  10890. if (this.historyList.length >= 2) {
  10891. // 播放历史记录的第二首
  10892. const prevSong = this.historyList[1];
  10893. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  10894. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10895. this.stop();
  10896. this.currentSong = prevSong;
  10897. this.videoUrl = prevSong.filePath;
  10898. this.cover = prevSong.pixelMapPath
  10899. this.artist = prevSong.artist
  10900. this.name = prevSong.name;
  10901. console.info('onecold startPlayOrResumePlay 11434')
  10902. this.startPlayOrResumePlay();
  10903. } else {
  10904. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  10905. if (this.curIndex === 0) {
  10906. this.curIndex = this.songList.length - 1;
  10907. } else {
  10908. this.curIndex--;
  10909. }
  10910. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10911. this.stop();
  10912. this.currentSong = this.songList[this.curIndex];
  10913. this.videoUrl = this.songList[this.curIndex].filePath;
  10914. this.artist = this.songList[this.curIndex].artist
  10915. this.name = this.songList[this.curIndex].name;
  10916. this.changeImageAnimation()
  10917. }
  10918. }
  10919. debounce() {
  10920. const delay = 600;
  10921. let cur = new Date().getTime();
  10922. if (cur - this.last > delay) {
  10923. this.last = cur;
  10924. return true;
  10925. }
  10926. return false;
  10927. }
  10928. /**
  10929. * Sets whether the screen is a constant based on the playback status.
  10930. */
  10931. watchStatus() {
  10932. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  10933. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10934. this.windowClass.setWindowKeepScreenOn(true);
  10935. } else {
  10936. this.windowClass.setWindowKeepScreenOn(false);
  10937. }
  10938. }
  10939. /**
  10940. * Volume gesture method onActionStart.
  10941. *
  10942. * @param event Gesture event.
  10943. */
  10944. private customDialogComponentIdMM: number = 0
  10945. @Builder
  10946. customDialogComponentMM() {
  10947. Column() {
  10948. Row() {
  10949. Blank()
  10950. Text('验证密码')
  10951. .fontSize(22)
  10952. .fontColor($r('app.color.pri_bg'))
  10953. .margin({ top: 18 })
  10954. Blank()
  10955. Image($r('app.media.close'))
  10956. .fillColor(Color.White)
  10957. .margin({ top: 18, right: 18 })
  10958. .width(20)
  10959. .onClick(() => {
  10960. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10961. })
  10962. }
  10963. .width('100%') // 使Row占据整个宽度
  10964. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  10965. Verify({
  10966. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  10967. });
  10968. }.height('60%')
  10969. .backgroundColor($r('app.color.index_background'))
  10970. .justifyContent(FlexAlign.SpaceBetween)
  10971. }
  10972. private handleVerifyCompleted(isSuccess: boolean) {
  10973. if (isSuccess) {
  10974. console.log('验证成功');
  10975. // 在这里处理验证成功后的逻辑
  10976. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10977. this.currentPath = this.lockPath
  10978. this.getSortedFiles(this.currentPath)
  10979. } else {
  10980. // console.log('验证失败');
  10981. ToastUtil.showToast('验证失败')
  10982. }
  10983. }
  10984. private showVerifyDialog() {
  10985. promptAction.openCustomDialog({
  10986. transition: TransitionEffect.asymmetric(
  10987. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  10988. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10989. ,
  10990. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  10991. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10992. ),
  10993. builder: () => {
  10994. this.customDialogComponentMM()
  10995. },
  10996. isModal: true,
  10997. autoCancel: true,
  10998. maskColor: Color.Transparent,
  10999. alignment: DialogAlignment.Bottom,
  11000. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  11001. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  11002. console.log("dialog onWillDismiss")
  11003. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  11004. dismissDialogAction.dismiss()
  11005. }
  11006. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  11007. dismissDialogAction.dismiss()
  11008. }
  11009. }
  11010. }).then((dialogId: number) => {
  11011. this.customDialogComponentIdMM = dialogId
  11012. })
  11013. }
  11014. //左滑操作 移动文件 重命名 删除等操作
  11015. @Builder
  11016. DeleteButton(item: VideoItem, index: number, filePath: string) {
  11017. Row() {
  11018. //加入收藏
  11019. Button() {
  11020. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  11021. .fillColor(Color.White)
  11022. .width(20)
  11023. }
  11024. .width(40)
  11025. .height(40)
  11026. .type(ButtonType.Circle)
  11027. .backgroundColor(this.themeColor)
  11028. .margin(5)
  11029. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11030. .onClick(() => {
  11031. if (item) {
  11032. this.doFav(item)
  11033. }
  11034. })
  11035. //加入下一首播放
  11036. Button() {
  11037. Image($r('app.media.next_to_play'))
  11038. .fillColor(Color.White)
  11039. .width(20)
  11040. }
  11041. .width(40)
  11042. .height(40)
  11043. .type(ButtonType.Circle)
  11044. .backgroundColor(this.themeColor)
  11045. .margin(5)
  11046. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11047. .onClick(() => {
  11048. this.addToNextPlay(item);
  11049. })
  11050. //复制文件
  11051. Button() {
  11052. Image($r('app.media.copy'))
  11053. .fillColor(Color.White)
  11054. .width(20)
  11055. }
  11056. .width(40)
  11057. .height(40)
  11058. .type(ButtonType.Circle)
  11059. .backgroundColor(this.themeColor)
  11060. .margin(5)
  11061. .id(filePath + 'copy')
  11062. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11063. .onClick(() => {
  11064. this.showCopyDialog(false, item, index, filePath + 'copy');
  11065. })
  11066. //移动文件
  11067. Button() {
  11068. Image($r('app.media.cut'))
  11069. .fillColor(Color.White)
  11070. .width(20)
  11071. }
  11072. .width(40)
  11073. .height(40)
  11074. .type(ButtonType.Circle)
  11075. .backgroundColor(this.themeColor)
  11076. .margin(5)
  11077. .id(filePath)
  11078. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11079. .onClick(() => {
  11080. this.showCutDialog(false, item, index, filePath);
  11081. })
  11082. Button() {
  11083. Image($r('app.media.cut_current'))
  11084. .fillColor(Color.White)
  11085. .width(20)
  11086. }
  11087. .width(40)
  11088. .height(40)
  11089. .type(ButtonType.Circle)
  11090. .backgroundColor(this.themeColor)
  11091. .margin(5)
  11092. .id(filePath + 'current')
  11093. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  11094. (this.isHasDir ? Visibility.Visible : Visibility.None))
  11095. .onClick(() => {
  11096. this.showCutDialog(true, item, index, filePath + 'current');
  11097. })
  11098. //重命名
  11099. Button() {
  11100. Image($r('app.media.rename2'))
  11101. .fillColor(Color.White)
  11102. .width(20)
  11103. }
  11104. .width(40)
  11105. .height(40)
  11106. .type(ButtonType.Circle)
  11107. .backgroundColor(this.themeColor)
  11108. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11109. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11110. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11111. .margin(5)
  11112. .onClick(() => {
  11113. this.showReNameDialog(item, index + '', filePath)
  11114. })
  11115. Button() {
  11116. Image($r('app.media.delete2'))
  11117. .fillColor(Color.White)
  11118. .width(20)
  11119. }
  11120. .width(40)
  11121. .height(40)
  11122. .type(ButtonType.Circle)
  11123. .backgroundColor(this.themeColor)
  11124. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11125. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11126. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11127. .margin(5)
  11128. .onClick(() => {
  11129. this.selectedFiles.push(item)
  11130. this.showWarnIsDelete()
  11131. // this.showWarnIsDeleteFile(item, index + '', filePath)
  11132. })
  11133. Button() {
  11134. Image($r('app.media.share2'))
  11135. .fillColor(Color.White)
  11136. .width(20)
  11137. }
  11138. .width(40)
  11139. .height(40)
  11140. .type(ButtonType.Circle)
  11141. .backgroundColor(this.themeColor)
  11142. .margin(5)
  11143. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11144. .onClick(() => {
  11145. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11146. })
  11147. }
  11148. }
  11149. /**
  11150. * 穿山甲banner广告
  11151. */
  11152. // private declare bannerAd: CSJNativeExpressAd;
  11153. // @State private status: string = "未加载"
  11154. // @State private isShowAd: boolean = false
  11155. // private declare mAdSlot: AdSlot;
  11156. // private mBiddingAdm = '' //服务端bidding才需要设置
  11157. // private expressLoadAdListener: NativeExpressAdListener = {
  11158. // /**
  11159. // * 加载失败的回调
  11160. // *
  11161. // * @param code
  11162. // * @param message
  11163. // */
  11164. // onError: (code: number, message: string) => {
  11165. // console.error("加载广告失败,code=" + code + ",message=" + message);
  11166. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  11167. // },
  11168. //
  11169. // /**
  11170. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  11171. // *
  11172. // * @param ads 返回的广告列表
  11173. // */
  11174. //
  11175. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  11176. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  11177. // if (ads && ads.length > 0) {
  11178. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  11179. // ad.setExpressInteractionListener({
  11180. // /**
  11181. // *广告的点击回调
  11182. // * @param type 广告的交互类型
  11183. // */
  11184. // onAdClicked: (type: number) => {
  11185. // console.log("BannerExpressAdPage==onAdClicked......");
  11186. // },
  11187. //
  11188. // /**
  11189. // * 广告的展示回调 每个广告仅回调一次
  11190. // * @param type 广告的交互类型
  11191. // */
  11192. // onAdShow: (type: number) => {
  11193. // console.log("BannerExpressAdPage==onAdShow......");
  11194. // },
  11195. //
  11196. // /**
  11197. // * 模板渲染失败
  11198. // */
  11199. // onRenderFail: (code: number, msg: string) => {
  11200. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  11201. // },
  11202. //
  11203. // /**
  11204. // * 模板渲染成功
  11205. // * @param width 返回view的宽 单位 vp
  11206. // * @param height 返回view的高 单位 vp
  11207. // */
  11208. // onRenderSuccess: (width: number, height: number) => {
  11209. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  11210. // this.bannerAd = ad;
  11211. // this.status = "广告加载完成待展示";
  11212. //
  11213. // this.showBannerAd()
  11214. // }
  11215. // })
  11216. // //渲染广告
  11217. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  11218. // this.setDislikeCallback(ad); //设置dislike
  11219. // ad.render(this.getUIContext())
  11220. // this.status = "广告加载中...";
  11221. // });
  11222. // }
  11223. // }
  11224. // }
  11225. //
  11226. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  11227. // ad.setDislikeCallback({
  11228. // /**
  11229. // * dislike show
  11230. // */
  11231. // onShow: () => {
  11232. // console.log("BannerExpressAdPage==dislike......show");
  11233. // },
  11234. //
  11235. // /**
  11236. // * @param position 选择的位置
  11237. // * @param value 选择的内容
  11238. // * @param enforceRemove 是否强制关闭广告
  11239. // */
  11240. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  11241. // this.isShowAd = false;
  11242. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  11243. // ",enforce=" + enforceRemove);
  11244. // },
  11245. //
  11246. // /**
  11247. // * 点击取消
  11248. // */
  11249. // onCancel: () => {
  11250. // console.log("BannerExpressAdPage==dislike......onCancel");
  11251. // }
  11252. //
  11253. // })
  11254. // }
  11255. /**
  11256. * 加载Banner广告
  11257. */
  11258. loadBannerAd(rit: string) {
  11259. // if (Utility.isNoble()) {
  11260. // return
  11261. // }
  11262. // if (!Utility.isPassInstallTime(2)) {
  11263. // return
  11264. // }
  11265. // this.isShowAd = false;
  11266. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  11267. // this.mAdSlot = new AdSlotBuilder()
  11268. // .setCodeId(rit)
  11269. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  11270. // .setAdCount(1)
  11271. // .setBidAdm(this.mBiddingAdm)
  11272. // .build()
  11273. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  11274. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  11275. // this.status = "广告加载中..."
  11276. }
  11277. /**
  11278. * 展示Banner广告
  11279. */
  11280. // showBannerAd() {
  11281. // if (!this.bannerAd) {
  11282. // return
  11283. // }
  11284. // this.isShowAd = true
  11285. // this.status = "已展示"
  11286. // }
  11287. /**
  11288. * 穿山甲广告代码结束
  11289. */
  11290. }
  11291. //视频气泡窗口的布局
  11292. @Builder
  11293. function customPopupBuilder(dataBu: BubbleBean) {
  11294. List() {
  11295. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  11296. ListItem() {
  11297. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11298. Row() {
  11299. Column() {
  11300. Image(dataBu.imageRes[index])
  11301. .height(28)
  11302. .fillColor(dataBu.color)
  11303. .alignSelf(ItemAlign.Center)
  11304. }
  11305. .width(32)
  11306. Text(item)
  11307. .padding({
  11308. top: 10,
  11309. bottom: 10,
  11310. right: 10,
  11311. left: 10
  11312. })
  11313. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  11314. .textAlign(TextAlign.Start)
  11315. .width("100%")
  11316. }
  11317. }
  11318. .backgroundColor($r('app.color.settings_background_main'))
  11319. .margin({ top: 6, bottom: 6 })
  11320. }
  11321. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  11322. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  11323. TransitionEffect.scale({ x: 0, y: 0 })))
  11324. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  11325. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  11326. .onClick(() => {
  11327. dataBu.onItemClick?.(index)
  11328. })
  11329. })
  11330. }
  11331. .width(120)
  11332. .divider({
  11333. strokeWidth: 1,
  11334. color: "#22FFFFFF"
  11335. })
  11336. }
  11337. // Function to calculate a hash for the file list
  11338. function simpleHash(fileList: string[]): string {
  11339. let hash = 0;
  11340. const str = fileList.join(',');
  11341. for (let i = 0; i < str.length; i++) {
  11342. const char = str.charCodeAt(i);
  11343. hash = (hash << 5) - hash + char;
  11344. hash |= 0; // Convert to 32bit integer
  11345. }
  11346. return hash.toString();
  11347. }
  11348. interface MoreItem {
  11349. id: number;
  11350. image: Resource;
  11351. title: string;
  11352. }
  11353. //视频气泡窗口的布局
  11354. @Builder
  11355. function cutPopupBuilder(dataBu: BubbleBean) {
  11356. Column() {
  11357. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  11358. .padding({
  11359. top: 10,
  11360. bottom: 10,
  11361. right: 10,
  11362. left: 10
  11363. })
  11364. .textAlign(TextAlign.Start)
  11365. .width(160)
  11366. .fontWeight(666)
  11367. .fontSize(16)
  11368. List() {
  11369. ForEach(dataBu.data, (item: string, index: number) => {
  11370. ListItem() {
  11371. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11372. Row() {
  11373. Column() {
  11374. Image($r('app.media.music_group'))
  11375. .height(28)
  11376. .fillColor(dataBu.color)
  11377. .alignSelf(ItemAlign.Center)
  11378. }
  11379. .width(32)
  11380. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  11381. .padding({
  11382. top: 10,
  11383. bottom: 10,
  11384. right: 10,
  11385. left: 10
  11386. })
  11387. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  11388. .fontSize(15)
  11389. }
  11390. }
  11391. .backgroundColor(Color.Transparent)
  11392. .margin({ top: 7, bottom: 7 })
  11393. }
  11394. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  11395. .animation({ duration: 500 }),
  11396. TransitionEffect.scale({ x: 0, y: 0 })))
  11397. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  11398. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  11399. .onClick(() => {
  11400. dataBu.onItemClick?.(index)
  11401. })
  11402. })
  11403. }
  11404. .width(150)
  11405. .divider({
  11406. strokeWidth: 1,
  11407. color: "#22FFFFFF"
  11408. })
  11409. }
  11410. .height(300)
  11411. .padding({
  11412. bottom: 30
  11413. })
  11414. }
  11415. function getFileDirName(filePath: string,rootPath:string): string{
  11416. if(filePath===rootPath){
  11417. return '首页'
  11418. }
  11419. let result = FileUtil.getFileName(filePath)
  11420. if(StrUtil.isEmpty(result))
  11421. return ''
  11422. if(result.startsWith('.'))
  11423. result = result.replace(/\./g, '')
  11424. return result
  11425. }