LocalMusic.ets 352 KB

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