LocalMusic.ets 374 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070
  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 { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  21. import { CommonConstants } from '../common/constants/CommonConstants';
  22. import Logger from '../common/util/Logger';
  23. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  24. import { Utility } from '../common/util/Utility';
  25. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  26. import { BubbleBean } from '../viewmodel/BubbleBean';
  27. import { PopupPosition, XPopup } from '@chinalike/popup';
  28. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  29. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  30. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  31. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  32. import { Verify } from './Verify';
  33. import { RotatingCover } from './RotatingCover';
  34. import { PlayConstants } from '../common/constants/PlayConstants';
  35. import { effectKit } from '@kit.ArkGraphics2D';
  36. import { ColorConversion } from '../common/util/ColorConversion';
  37. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  38. import { AvSessionController } from '../controller/AvSessionController';
  39. import {
  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 { UniversalDetector } from '@ohos/juniversalchardet';
  60. import { SettingPage } from '../pages/SettingPage';
  61. import { secondToTime } from '../common/util/CommUtils';
  62. import { CommonConstants2 } from '../common/util/CommonConstants2';
  63. import { hilog } from '@kit.PerformanceAnalysisKit';
  64. import { LazyDataSource } from '../common/util/LazyDataSource';
  65. import MediaTable from '../common/util/MediaTable';
  66. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  67. import ImageUtils from '../common/util/ImageUtils';
  68. import { ringtone } from '@kit.RingtoneKit';
  69. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  70. import { resourceManager } from '@kit.LocalizationKit';
  71. import { deviceInfo } from '@kit.BasicServicesKit';
  72. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  73. import { LrcParser } from '@sgaolei/lrc_parser';
  74. import app from '@system.app';
  75. import { TextNodeController } from './PipLyricTextBuilder';
  76. import { IndexerView } from './IndexerView';
  77. import { KeyCode } from '@kit.InputKit';
  78. // import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  79. const TAG = 'LocalMusic';
  80. const DEFAULT_INDEX =
  81. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  82. 'X', 'Y', 'Z']
  83. //排序类型
  84. function getTypeOrder(type: number) {
  85. switch (type) {
  86. case CommonConstants.TYPE_IS_DIR:
  87. return 1; // First
  88. case CommonConstants.TYPE_IS_CSJAD:
  89. return 2; // Middle
  90. case CommonConstants.TYPE_LOCAL:
  91. return 3; // Last
  92. default:
  93. return 4; // Unknown types, if any, go last
  94. }
  95. }
  96. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  97. // 定义接口
  98. interface HiCarAspectRatio {
  99. ratio: number;
  100. name: string;
  101. }
  102. interface GeneratedObjectLiteralInterface_1 {
  103. assetId: string;
  104. title: string;
  105. artist: string;
  106. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  107. mediaUri: string;
  108. // 该字段大写,音频'AUDIO',视频'VIDEO'
  109. mediaType: string;
  110. mediaSize: number;
  111. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  112. startPosition: number;
  113. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  114. duration: number;
  115. albumCoverUri: string;
  116. albumTitle: string;
  117. appName: string;
  118. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  119. drmScheme: string;
  120. }
  121. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  122. const ITEM_HEIGHT: number = 58; // 列表项中高度
  123. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  124. //功能强大的音乐播放器
  125. @Preview
  126. @Component
  127. export struct LocalMusic {
  128. @Consume mType: number;
  129. @StorageProp('themeColor') themeColor: string =
  130. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  131. themeMode: number = 0;
  132. @State titleName: string = '首页'
  133. @State textStr: string = ''
  134. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  135. // private download_path: string = '';
  136. @Consume rootPath: string //音频根目录
  137. @Consume currentPath: string
  138. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  139. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  140. @State lockPath: string = ''
  141. @State favPath: string = ''
  142. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  143. @State historyPath: string = ''
  144. @State historyList: Array<VideoItem> = []
  145. @Consume isHistory: boolean
  146. static readonly HISTORY_MUSIC: string = 'music_historyList';
  147. private table: MediaTable = new MediaTable(getContext(this))
  148. @State isZero: boolean = false
  149. @State fileList: Array<string> = []
  150. @State dirList: Array<VideoItem> = []
  151. @Consume videoLocalList: Array<VideoItem>
  152. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  153. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  154. @State artistList: Array<VideoItem> = []; //艺术家文件
  155. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  156. @State albumList: Array<VideoItem> = []; //专辑文件
  157. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  158. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  159. @State imageOpacities: number[] = [];
  160. @Consume isCanBack: boolean
  161. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  162. @State showSingleLyric: boolean = false
  163. @State sortType: number = 4 //默认排序方式
  164. @State isShowSimi: boolean = false //是否显示私密音频
  165. @State isShowFAV: boolean = true //是否显示我的收藏
  166. @State isShowTitleBar: boolean = true //是否显示分类导航条
  167. @State isShowAllBar: boolean = true //是否显示播放全部条
  168. @State isShowHistory: boolean = true //是否显示最近播放
  169. @State isCustomizeBg: boolean = false //自定义背景界面
  170. @State isGridMusic: boolean = false //是否网格布局
  171. @State isCircleBtn: boolean = false //是否圆形播放按钮
  172. @State twoFingerType: number = 3 //双支放大缩小的类型
  173. @State isScrollHide: boolean = false //是否滚动隐藏
  174. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  175. @State isStartAutoPlay: boolean = false //启动后自动播放
  176. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  177. @State isShowHeader: boolean = true
  178. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  179. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  180. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  181. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  182. @State isSwipe: boolean = false //listItem的左滑开关
  183. @State customizeBgPath: string | undefined = '';
  184. @State isDarkMode: boolean = false
  185. @State lyricTextWeight: number = 400
  186. @State lyricTextWeightPip: number = 400
  187. @State currentSwiperIndex: number = 0
  188. @State blurValue: number = 0 //背景模糊
  189. @State bgBrightness: number = 0 //背景亮度
  190. private listScroller: ListScroller = new ListScroller()
  191. private playListScroller: Scroller = new Scroller()
  192. @StorageProp('isLandscape') isLandscape: boolean = false;
  193. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  194. @StorageProp('windowWidth') windowWidth: number = 0;
  195. @StorageProp('windowHeight') windowHeight: number = 0;
  196. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  197. private UNKONWN:string = '';
  198. private listArea: Area = {
  199. width: 0,
  200. height: 0,
  201. position: {},
  202. globalPosition: {}
  203. }
  204. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  205. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  206. onColorModeChange() {
  207. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  208. if (this.isCustomizeBg) {
  209. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  210. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  211. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  212. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  213. } else {
  214. if (!this.isDarkMode) {
  215. this.titleBarModel.setTitleBarBackground(this.themeColor)
  216. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  217. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  218. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  219. } else {
  220. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  221. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  222. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  223. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  224. }
  225. }
  226. }
  227. onModeChange() {
  228. this.isFavMusic = false
  229. if (this.modeType === 2 || this.modeType === 3) {
  230. this.titleBarModel.setRightIcon(null)
  231. } else {
  232. this.titleBarModel.setRightIcon(($r('app.media.add')))
  233. }
  234. LogUtil.info('onecold onModeChange = ' + this.modeType)
  235. switch (this.modeType) {
  236. case 0:
  237. this.getSortedFiles(this.currentPath)
  238. break
  239. case 1:
  240. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  241. this.updateListData(this.mediaKuList)
  242. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  243. break
  244. case 2:
  245. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  246. this.updateListData(this.artistList)
  247. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  248. break
  249. case 3:
  250. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  251. this.updateListData(this.albumList)
  252. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  253. break
  254. }
  255. }
  256. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  257. // @StorageLink('isPlay') isPlay: boolean = false;
  258. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  259. @StorageLink('songList') songList: Array<VideoItem> = [];
  260. @State translateY: number = 0;
  261. @State isShowSheet: boolean = false;
  262. @State isShowSheetView: boolean = false;
  263. @State isShowTimeCloseView: boolean = false;
  264. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  265. @StorageLink('currIndex') curIndex: number = 0;
  266. @Consume isShowDrawer: boolean;
  267. @Consume offsetX: number;
  268. @State isFac: boolean = false;
  269. @State favList: Array<VideoItem> = []
  270. @Consume isFavMusic: boolean
  271. @State isClickedPLayAll: boolean = false;
  272. private scrollerForlist: ListScroller = new ListScroller();
  273. imagesF: ImageFrameInfo[] = [
  274. { src: $r("app.media.app_loading0") },
  275. { src: $r("app.media.app_loading1") },
  276. { src: $r("app.media.app_loading2") },
  277. { src: $r("app.media.app_loading3") },
  278. ]
  279. @State animationState: AnimationStatus = AnimationStatus.Initial
  280. // 缓存机制
  281. private cache: Map<string, Array<VideoItem>> = new Map();
  282. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  283. // 持久化缓存
  284. private async saveCacheToStorage() {
  285. const cacheArray = Array.from(this.cache.entries());
  286. const stringCacheArray = Array.from(this.stringCache.entries());
  287. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  288. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  289. }
  290. // 载入缓存
  291. private async loadCacheFromStorage() {
  292. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  293. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  294. if (cacheString) {
  295. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  296. this.cache = new Map(cacheArray);
  297. }
  298. if (stringCacheString) {
  299. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  300. this.stringCache = new Map(stringCacheArray);
  301. }
  302. }
  303. // 查找缓存
  304. private findCache(key: string): Array<VideoItem> | undefined {
  305. return this.cache.get(key);
  306. }
  307. // 查找字符串缓存
  308. private findStringCache(key: string): string | undefined {
  309. return this.stringCache.get(key);
  310. }
  311. // 添加缓存
  312. private addCache(key: string, value: Array<VideoItem>) {
  313. this.cache.set(key, value);
  314. }
  315. // 添加字符串缓存
  316. private addStringCache(key: string, value: string) {
  317. this.stringCache.set(key, value);
  318. }
  319. // 删除缓存
  320. private deleteCache(key: string) {
  321. this.cache.delete(key);
  322. this.saveCacheToStorage()
  323. }
  324. // 删除字符串缓存
  325. private deleteStringCache(key: string) {
  326. this.stringCache.delete(key);
  327. }
  328. // 多选机制
  329. @State selectedFiles: Array<VideoItem> = [];
  330. @State isMultiSelect: boolean = false;
  331. @State isAllSelected: boolean = false;
  332. @State appName: string = ''
  333. @State isHasDir: boolean = false
  334. @State packName: string = ''
  335. context = getContext(this);
  336. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  337. .setTitleTextStyle(FontStyle.Normal)
  338. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  339. .setLeftIcon($r('app.media.menu'))
  340. .setLeftIconWidth(25)
  341. .setLeftIconHeight(25)
  342. .setTitleName('首页')
  343. .setTitleFontSize(18)
  344. .setTitleFontColor(Color.White)
  345. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  346. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  347. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  348. .setRightIcon($r('app.media.add'))
  349. .setOnRightClickListener(() => {
  350. this.showSheelDialog()
  351. })
  352. .setOnTitleClickListener(() => {
  353. this.showPupDialog()
  354. })
  355. .setOnLeftClickListener(() => {
  356. this.doSwipBack()
  357. })
  358. doSwipBack() {
  359. if (this.modeType !== 0 && this.isCanBack) {
  360. this.onModeChange()
  361. this.isCanBack = false
  362. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  363. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  364. setTimeout(() => {
  365. if (this.modeType == 2) {
  366. if (this.isGridMusic) {
  367. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  368. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  369. } else {
  370. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  371. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  372. }
  373. } else if (this.modeType == 3) {
  374. if (this.isGridMusic) {
  375. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  376. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  377. } else {
  378. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  379. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  380. }
  381. }
  382. }, 200)
  383. return
  384. }
  385. if (this.isHistory || this.isFavMusic) {
  386. this.isHistory = false
  387. this.getSortedFiles(this.currentPath)
  388. return
  389. }
  390. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  391. animateTo({ duration: 555 }, () => {
  392. // 动画闭包内控制Image组件的出现和消失
  393. this.isShowDrawer = !this.isShowDrawer
  394. this.offsetX = 0
  395. })
  396. return
  397. }
  398. //返回上一级歌单的滚动位置
  399. setTimeout(() => {
  400. if (this.modeType == 0) {
  401. if (this.isGridMusic) {
  402. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  403. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  404. } else {
  405. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  406. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  407. }
  408. }
  409. }, 300)
  410. this.currentPath = Utility.getParentDirectory(this.currentPath)
  411. Logger.info('this.currentPath2 = ' + this.currentPath)
  412. this.getSortedFiles(this.currentPath)
  413. }
  414. // 组件生命周期
  415. aboutToAppear() {
  416. this.initSetting()
  417. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  418. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  419. Utility.getAppName(getContext(this)).then((appName: string) => {
  420. this.appName = appName
  421. })
  422. this.packName = AppUtil.getBundleName()
  423. this.loadCacheFromStorage(); // 加载缓存
  424. this.mkDownLoadDir()
  425. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  426. // 监听广播事件(打开其他应用处理)
  427. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  428. this.saveVideoDatas([eventData.data?.message], true)
  429. });
  430. //侧滑广播接收时间
  431. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  432. // 监听广播事件(打开其他应用处理)
  433. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  434. animateTo({ duration: 555 }, () => {
  435. this.doSwipBack()
  436. })
  437. });
  438. //ScanFilePage广播接收时间
  439. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  440. // 监听ScanFilePage广播事件(更新数据库)
  441. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  442. this.doUpdateData()
  443. });
  444. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  445. // 监听广播事件(通用设置配置更新)
  446. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  447. this.doChangeSetting()
  448. });
  449. let event: Callback<InterruptEvent> = (event) => {
  450. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  451. this.savePlaybackPosition()
  452. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  453. this.pause();
  454. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  455. this.startPlayOrResumePlay();
  456. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  457. this.stop();
  458. }
  459. }
  460. this.mIjkMediaPlayer.on('audioInterrupt', event);
  461. // 音频设备断连回调处理
  462. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  463. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  464. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  465. // this.pause();
  466. // }
  467. // }
  468. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  469. this.makeWorker()
  470. //折叠屏的屏幕显示模式变化
  471. display.on('foldDisplayModeChange', (data) => {
  472. this.doChangeBarHeight()
  473. });
  474. display.on('foldStatusChange', (data) => {
  475. Logger.info('onecold foldStatusChange ')
  476. });
  477. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  478. // 读取 themeMode 并同步 currentColorMode
  479. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  480. this.applyThemeMode(this.themeMode)
  481. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  482. AppStorage.setOrCreate('themeColor', themeColor);
  483. this.themeColor = themeColor;
  484. this.doChangeSetting()
  485. this.windowClass.on('windowSizeChange', (size) => {
  486. // LogUtil.info('onecold windowSizeChange')
  487. this.doChangeBarHeight()
  488. let viewWidth = px2vp(size.width);
  489. let viewHeight = px2vp(size.height);
  490. if(this.isPhoneLan()){
  491. this.is_auto_hide_progress = false
  492. setTimeout(() => {
  493. this.is_auto_hide_progress = true
  494. }, 6000)
  495. }else{
  496. this.startAutoHide()
  497. }
  498. });
  499. this.eventHub.on('onStateChange', (fg: boolean) => {
  500. if (fg && this.curState === 'STARTED') {
  501. this.stopPip();
  502. }
  503. });
  504. }
  505. startAutoHide() {
  506. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  507. this.is_auto_hide_progress = false
  508. setTimeout(() => {
  509. this.is_auto_hide_progress = true
  510. }, 6000)
  511. }
  512. }
  513. applyThemeMode(mode: number) {
  514. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  515. if (mode === 1) {
  516. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  517. } else if (mode === 2) {
  518. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  519. }
  520. AppStorage.setOrCreate('currentColorMode', colorMode)
  521. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  522. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  523. AppStorage.setOrCreate('themeMode', mode)
  524. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  525. // 只有强制浅色/深色时才主动设置
  526. const context = getContext(this) as common.UIAbilityContext
  527. context.getApplicationContext().setColorMode(colorMode)
  528. }
  529. initSetting() {
  530. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  531. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  532. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  533. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  534. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  535. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  536. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  537. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  538. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  539. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  540. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  541. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  542. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  543. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  544. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  545. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  546. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  547. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  548. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  549. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  550. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  551. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  552. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  553. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  554. //如果是hicar连接状态,这些都是false
  555. if(this.isHiCarStatus){
  556. this.isShowTitleBar = false//不显示导航栏
  557. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//大屏幕不可以Grid
  558. {
  559. this.isShowHeader = false//二级菜单不显示头部
  560. this.isGridMusic= false//用list不用网格
  561. this.isCoverTopBig = false
  562. }
  563. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  564. }
  565. if (this.isSavePlayMode) {
  566. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  567. }
  568. if (this.isCustomizeBg) {
  569. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  570. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  571. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  572. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  573. } else {
  574. if (!this.isDarkMode) {
  575. this.titleBarModel.setTitleBarBackground(this.themeColor)
  576. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  577. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  578. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  579. } else {
  580. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  581. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  582. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  583. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  584. }
  585. }
  586. }
  587. doChangeSetting() {
  588. this.initSetting()
  589. this.deleteCache(this.currentPath)
  590. if (this.modeType === 0) {
  591. this.getSortedFiles(this.currentPath)
  592. }
  593. }
  594. doChangeBarHeight() {
  595. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  596. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  597. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  598. this.setBarHeightNormal()
  599. }
  600. }
  601. onPageShow() {
  602. app.setImageCacheCount(100);
  603. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  604. app.setImageRawDataCacheSize(104857600);
  605. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  606. }
  607. //开启线程查看各个数据库
  608. makeWorker() {
  609. setTimeout(() => {
  610. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  611. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  612. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  613. // workerInstance.postMessage({
  614. // code: 1,
  615. // data1: this.context,
  616. // data2: this.rootPath,
  617. // data3: this.lockPath,
  618. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  619. // });
  620. PreferencesUtil.putSync('isFirstApp', false)
  621. } else {
  622. workerInstance.postMessage({ code: 2, data: this.context });
  623. workerInstance.postMessage({ code: 3, data: this.context });
  624. workerInstance.postMessage({ code: 4, data: this.context });
  625. this.getHistoryList(false)
  626. }
  627. }, 1000)
  628. workerInstance.onmessage = (e: MessageEvents): void => {
  629. switch (e.data.code) {
  630. case 101: //第一次扫描文件夹入库
  631. ToastUtil.showToast('刷新同步数据库成功!')
  632. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  633. this.doUpdateData()
  634. break;
  635. case 102: //查询媒体库列表
  636. this.mediaKuList = e.data.data
  637. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  638. Utility.doSortListAscending(this.mediaKuList)
  639. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  640. if (this.modeType === 1) {
  641. this.updateListData(this.mediaKuList)
  642. }
  643. break;
  644. case 103: //收到查询艺术家列表
  645. this.artistMap = e.data.data1;
  646. this.artistList = e.data.data2;
  647. break;
  648. case 104: //收到查询专辑列表
  649. this.albumMap = e.data.data1;
  650. this.albumList = e.data.data2
  651. //查询完毕在启动是否自动播放
  652. if (this.isStartAutoPlay) {
  653. this.startPlayOrResumePlay()
  654. }
  655. break;
  656. }
  657. };
  658. // 在调用terminate后,执行onexit
  659. workerInstance.onexit = (code) => {
  660. console.log("main thread terminate");
  661. }
  662. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  663. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  664. workerInstance.onerror = (err: ErrorEvent) => {
  665. console.log("onerror" + err.message);
  666. }
  667. }
  668. @State isFirstStartPlay: boolean = false
  669. //获取download_path
  670. async mkDownLoadDir() {
  671. const documentViewPicker = new picker.DocumentViewPicker()
  672. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  673. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  674. // this.rootPath = this.download_path
  675. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  676. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  677. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  678. Logger.info('onecold rootPath = ' + this.rootPath)
  679. Logger.info('onecold lockPath = ' + this.lockPath)
  680. if (!FileUtil.accessSync(this.lockPath)) {
  681. FileUtil.mkdirSync(this.lockPath)
  682. }
  683. if (!FileUtil.accessSync(this.favPath)) {
  684. FileUtil.mkdirSync(this.favPath)
  685. }
  686. if (!FileUtil.accessSync(this.historyPath)) {
  687. FileUtil.mkdirSync(this.historyPath)
  688. }
  689. this.getSortedFiles(this.rootPath).then(() => {
  690. this.isFavMusic = false
  691. //穿山甲
  692. // this.loadBannerAd(CSJUtil.getBannerID())
  693. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  694. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  695. if (ArrayUtil.isEmpty(this.songList)) {
  696. this.songList = this.getCurFileList()
  697. } else {
  698. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  699. }
  700. if (ArrayUtil.isNotEmpty(this.songList)) {
  701. this.isFirstStartPlay = true
  702. this.sonDataSource.pushArrayData(this.songList)
  703. if (this.currentSong === undefined) {
  704. this.isFirstStartPlay = false
  705. this.currentSong = this.songList[0]
  706. }
  707. this.videoUrl = this.currentSong.filePath
  708. this.name = this.currentSong.name
  709. this.cover = this.currentSong.pixelMapPath
  710. } else {
  711. this.name = '空空如也'
  712. }
  713. })
  714. this.getFavList(false)
  715. }
  716. getFavList(isFavRefresh: boolean) {
  717. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  718. this.favList = result
  719. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  720. this.videoLocalList = this.favList
  721. this.updateListData(this.videoLocalList)
  722. }
  723. })
  724. }
  725. getHistoryList(isRefresh: boolean) {
  726. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  727. this.historyList = result
  728. // for (let i = 0; i < this.historyList.length; i++) {
  729. //
  730. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  731. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  732. // }
  733. if (isRefresh) {
  734. this.videoLocalList = this.historyList
  735. this.updateListData(this.videoLocalList, true)
  736. }
  737. })
  738. }
  739. // 组件消失生命周期
  740. aboutToDisappear() {
  741. console.info('LifeCycleComponent aboutToDisappear');
  742. emitter.off(2);
  743. emitter.off(101);
  744. emitter.off(888);
  745. emitter.off(333);
  746. this.mDestroyPage = true;
  747. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  748. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  749. this.stop();
  750. }
  751. this.mIjkMediaPlayer.off('audioInterrupt');
  752. if (workerInstance) {
  753. workerInstance.terminate();
  754. }
  755. this.stopPip();
  756. this.destroyPipController()
  757. }
  758. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  759. this.isFavMusic = false
  760. if (isWorkerPost) {
  761. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  762. }
  763. if (this.modeType !== 0) {
  764. return
  765. }
  766. this.isCanBack = false
  767. this.currentPath = curPath
  768. this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
  769. if (curPath === this.rootPath) {
  770. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  771. } else {
  772. this.currentTitleName = Utility.getFileDirName(this.currentPath, this.rootPath)
  773. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  774. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  775. }
  776. }
  777. // Get the current file list and calculate its hash
  778. this.fileList = FileUtil.listFileSync(curPath);
  779. const currentHash = simpleHash(this.fileList);
  780. // Check cache
  781. const cachedValue = this.findCache(curPath);
  782. Logger.info('onecold cachedValue = ' + cachedValue)
  783. const cachedHash = this.findStringCache(curPath + '_hash');
  784. const cachedDirList = this.findCache(curPath + "_dirList");
  785. if (cachedValue !== undefined) {
  786. // this.videoLocalList = cachedValue;
  787. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  788. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  789. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  790. }
  791. this.updateListData(cachedValue)
  792. }
  793. if (cachedDirList !== undefined) {
  794. this.dirList = cachedDirList
  795. }
  796. //通过当前hash值和缓存hash判断list有没有变化
  797. if (cachedValue && cachedHash === currentHash) {
  798. return;
  799. }
  800. this.fileList = FileUtil.listFileSync(curPath)
  801. let directories: Array<VideoItem> = [];
  802. let files: Array<VideoItem> = [];
  803. for (let i = 0; i < this.fileList.length; i++) {
  804. console.info(`The name of file: ${this.fileList[i]}`);
  805. let path = curPath + '/' + this.fileList[i]
  806. if (FileUtil.isDirectory(path)) {
  807. let item: VideoItem =
  808. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  809. '')
  810. if (this.isShowDir(item.name)) {
  811. directories.push(item);
  812. }
  813. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  814. // Utility.doSortListAscending(directories)
  815. } else {
  816. if (this.currentPath === this.lockPath) {
  817. let item: VideoItem =
  818. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  819. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  820. files.push(item);
  821. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  822. // this.doSortListAscending(files)
  823. }
  824. }
  825. }
  826. }
  827. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  828. if (this.currentPath !== this.lockPath) {
  829. files = result;
  830. }
  831. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  832. Utility.doSortListAscending(files)
  833. if (this.currentPath === this.rootPath) {
  834. this.dirList = directories
  835. this.addCache(curPath + "_dirList", this.dirList);
  836. }
  837. //插入广告先注释掉
  838. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  839. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  840. // directories.push(adItem)
  841. // }
  842. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  843. this.videoLocalList = directories.concat(files);
  844. this.updateListData(this.videoLocalList)
  845. if (ArrayUtil.isNotEmpty(files)) {
  846. if (this.currentPath != this.rootPath) {
  847. if (files) {
  848. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  849. }
  850. }
  851. // 缓存结果
  852. this.addCache(curPath, this.videoLocalList);
  853. await this.saveCacheToStorage(); // 保存缓存至本地存储
  854. this.addStringCache(curPath + '_hash', currentHash);
  855. }
  856. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  857. // for (let i = 0; i < this.videoLocalList.length; i++) {
  858. //
  859. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  860. //
  861. // }
  862. // this.setButtonStatus()
  863. if (isOpen) {
  864. if (destPath === undefined) {
  865. // 处理 destPath 为 undefined 的情况
  866. return
  867. }
  868. if (destPath.endsWith('.lrc')) {
  869. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  870. if (StrUtil.isNotEmpty(this.videoUrl)) {
  871. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  872. this.initLyric(lyricPath);
  873. }
  874. return
  875. }
  876. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  877. this.doPlay(item2)
  878. }
  879. });
  880. }
  881. //扫描文件夹入库
  882. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  883. const files = FileUtil.listFileSync(curPath);
  884. let mediaItems: VideoItem[] = [];
  885. Logger.info('onecold scanDirectory start ')
  886. for (const file of files) {
  887. const fPath = `${curPath}/${file}`;
  888. if (fPath === this.lockPath) {
  889. Logger.info(`Skipping locked path: ${fPath}`);
  890. continue;
  891. }
  892. if (FileUtil.isDirectory(fPath)) {
  893. // Recursively scan subdirectories
  894. const subDirItems = await this.scanDirectory(fPath);
  895. mediaItems = mediaItems.concat(subDirItems);
  896. } else {
  897. Logger.info('onecold scanDirectory filePath = ' + fPath)
  898. // Process media files
  899. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  900. let mediaItem: VideoItem =
  901. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  902. mediaItems.push(mediaItem);
  903. this.table.insert(mediaItem, (id: number) => {
  904. });
  905. }
  906. }
  907. }
  908. return mediaItems;
  909. }
  910. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  911. animateTo({ duration: 888 }, () => {
  912. this.opacityItem = 0;
  913. });
  914. setTimeout(() => {
  915. this.videoLocalList = mList;
  916. if (!noSort) {
  917. if (this.modeType === 0 || this.modeType === 1) {
  918. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  919. this.doSortType(this.sortType)
  920. }
  921. }
  922. this.dataSource.pushArrayData(this.videoLocalList)
  923. animateTo({ duration: 888 }, () => {
  924. this.opacityItem = 1;
  925. });
  926. this.setButtonStatus()
  927. }, 200);
  928. }
  929. //排序模式和多选模式
  930. showPupDialog() {
  931. if (this.modeType === 2 || this.modeType === 3) {
  932. this.titleBarModel.setRightIcon(null)
  933. } else {
  934. this.titleBarModel.setRightIcon(($r('app.media.add')))
  935. }
  936. let dataBean = new BubbleBean()
  937. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  938. dataBean.color = this.themeColor
  939. dataBean.modeType = this.modeType
  940. dataBean.imageRes =
  941. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  942. $r('app.media.refresh')]
  943. let pup: XPopup;
  944. if (this.isDarkMode) {
  945. pup = XPopup.Builder()
  946. .setPopupPosition(PopupPosition.BOTTOM)
  947. .atView('pup_positon_music')
  948. .setBackgroundColor(Color.Black)
  949. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  950. .show()
  951. } else {
  952. pup = XPopup.Builder()
  953. .setPopupPosition(PopupPosition.BOTTOM)
  954. .atView('pup_positon_music')
  955. .setBackgroundColor(Color.White)
  956. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  957. .show()
  958. }
  959. dataBean.onItemClick = (i) => {
  960. XPopup.dismissTop()
  961. switch (i) {
  962. case 0: //首页
  963. this.modeType = 0
  964. this.getSortedFiles(this.currentPath)
  965. break
  966. case 1:
  967. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  968. this.modeType = 1
  969. this.updateListData(this.mediaKuList)
  970. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  971. break
  972. case 2:
  973. this.modeType = 2
  974. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  975. this.updateListData(this.artistList)
  976. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  977. break
  978. case 3:
  979. this.modeType = 3
  980. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  981. this.updateListData(this.albumList)
  982. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  983. break
  984. case 4: //同步数据
  985. this.asyncCurrentPathData()
  986. break
  987. }
  988. }
  989. }
  990. getCurFileList(): Array<VideoItem> {
  991. let files: Array<VideoItem> = [];
  992. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  993. for (let i = 0; i < this.videoLocalList.length; i++) {
  994. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  995. files.push(this.videoLocalList[i]);
  996. }
  997. }
  998. }
  999. return files
  1000. }
  1001. setButtonStatus() {
  1002. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1003. this.isZero = false
  1004. } else {
  1005. this.isZero = true
  1006. }
  1007. if (this.currentPath !== this.rootPath &&
  1008. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1009. this.isHasDir = true //不为空,说明有子文件夹
  1010. } else {
  1011. this.isHasDir = false
  1012. }
  1013. }
  1014. showRankDialog() {
  1015. if (this.modeType === 2 || this.modeType === 3) {
  1016. //动作面板
  1017. DialogHelper.showBottomSheetDialog({
  1018. title: "请选择排序模式",
  1019. maskColor: Color.Transparent,
  1020. // sheets: ["按名称升序", "按名称降序"],
  1021. sheets: [
  1022. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1023. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1024. ],
  1025. backgroundColor: $r('app.color.bg_card'),
  1026. height: '30%',
  1027. transition: AnimationHelper.transitionInDown(555),
  1028. onAction: (index) => {
  1029. switch (index) {
  1030. case 0:
  1031. Utility.doSortListAscending(this.videoLocalList)
  1032. break;
  1033. case 1:
  1034. Utility.doSortListDescending(this.videoLocalList)
  1035. break;
  1036. }
  1037. this.updateListData(this.videoLocalList)
  1038. }
  1039. })
  1040. return
  1041. }
  1042. //动作面板
  1043. DialogHelper.showBottomSheetDialog({
  1044. title: "请选择排序模式",
  1045. maskColor: Color.Transparent,
  1046. height: '75%',
  1047. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1048. sheets: [
  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. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1054. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1055. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1056. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1057. ],
  1058. backgroundColor: $r('app.color.bg_card'),
  1059. transition: AnimationHelper.transitionInDown(555),
  1060. onAction: (index) => {
  1061. this.doSortType(index)
  1062. this.updateListData(this.videoLocalList, true)
  1063. }
  1064. })
  1065. }
  1066. doSortType(index: number) {
  1067. switch (index) {
  1068. case 0:
  1069. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1070. // 类型排序优先级
  1071. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1072. if (typeOrder !== 0) {
  1073. return typeOrder;
  1074. }
  1075. // 处理艺术家可能为undefined的字符串比较
  1076. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1077. const artistB = b.artist?.trim() || '';
  1078. return artistA.localeCompare(artistB);
  1079. });
  1080. break;
  1081. case 1:
  1082. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1083. // 类型排序优先级
  1084. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1085. if (typeOrder !== 0) {
  1086. return typeOrder;
  1087. }
  1088. // 处理艺术家可能为undefined的字符串比较
  1089. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1090. const artistB = b.artist?.trim() || '';
  1091. return artistB.localeCompare(artistA);
  1092. });
  1093. break;
  1094. case 2:
  1095. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1096. // 类型排序优先级
  1097. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1098. if (typeOrder !== 0) {
  1099. return typeOrder;
  1100. }
  1101. // 处理专辑可能为undefined的字符串比较
  1102. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1103. const albumB = b.album?.trim() || '';
  1104. return albumA.localeCompare(albumB);
  1105. });
  1106. break;
  1107. case 3:
  1108. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1109. // 类型排序优先级
  1110. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1111. if (typeOrder !== 0) {
  1112. return typeOrder;
  1113. }
  1114. // 处理专辑可能为undefined的字符串比较
  1115. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1116. const albumB = b.album?.trim() || '';
  1117. return albumB.localeCompare(albumA);
  1118. });
  1119. break;
  1120. case 4:
  1121. Utility.doSortListAscending(this.videoLocalList)
  1122. break;
  1123. case 5:
  1124. Utility.doSortListDescending(this.videoLocalList)
  1125. break;
  1126. case 6:
  1127. this.videoLocalList.sort((a, b) => {
  1128. // First, sort by type
  1129. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1130. if (typeOrder !== 0) {
  1131. return typeOrder;
  1132. }
  1133. // If types are the same, sort by cTime in ascending order
  1134. return a.cTime.localeCompare(b.cTime);
  1135. });
  1136. break;
  1137. case 7:
  1138. this.videoLocalList.sort((a, b) => {
  1139. // First, sort by type
  1140. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1141. if (typeOrder !== 0) {
  1142. return typeOrder;
  1143. }
  1144. // If types are the same, sort by cTime in descending order
  1145. return b.cTime.localeCompare(a.cTime);
  1146. });
  1147. break;
  1148. }
  1149. }
  1150. showSheelDialog() {
  1151. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1152. // this.showTips()
  1153. // return
  1154. // }
  1155. this.showAddDialog()
  1156. }
  1157. showAddDialog() {
  1158. if (this.modeType === 2 || this.modeType === 3) {
  1159. return
  1160. }
  1161. DialogHelper.showActionSheetDialog({
  1162. title: "请选择添加方式(建议歌词文件一起导入)",
  1163. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1164. sheets: [
  1165. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1166. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1167. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1168. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1169. ],
  1170. maskColor: Color.Transparent,
  1171. backgroundColor: $r('app.color.bg_card'),
  1172. transition: AnimationHelper.transitionInDown(555),
  1173. onAction: (index) => {
  1174. switch (index) {
  1175. case 0:
  1176. if (this.modeType === 0) {
  1177. this.showMkDialog()
  1178. } else {
  1179. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1180. }
  1181. break;
  1182. case 1:
  1183. this.callFilePickerSelectFile()
  1184. break;
  1185. case 2:
  1186. this.showTips()
  1187. break;
  1188. case 3:
  1189. this.goSelectMusic()
  1190. break;
  1191. }
  1192. }
  1193. })
  1194. }
  1195. //拉起音频
  1196. goSelectMusic() {
  1197. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1198. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1199. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1200. ) {
  1201. ToastUtil.showToast('暂时不支持该设备')
  1202. return
  1203. }
  1204. try {
  1205. let documentSelectOptions = new picker.DocumentSelectOptions();
  1206. documentSelectOptions.authMode = true
  1207. documentSelectOptions.multiAuthMode = true
  1208. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1209. let documentPicker = new picker.DocumentViewPicker(this.context);
  1210. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1211. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1212. this.saveVideoDatas(documentSelectResult)
  1213. }
  1214. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1215. JSON.stringify(documentSelectResult));
  1216. }).catch((err: BusinessError) => {
  1217. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1218. });
  1219. } catch (error) {
  1220. let err: BusinessError = error as BusinessError;
  1221. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1222. }
  1223. }
  1224. async showTips() {
  1225. DialogHelper.showTipsDialog({
  1226. title: '使用提示:自动导入教程',
  1227. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1228. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1229. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1230. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1231. onAction: (action) => {
  1232. if (action == DialogAction.TWO) {
  1233. PreferencesUtil.putSync('isFirstMusic', false)
  1234. router.pushUrl({
  1235. url: 'pages/ScanFilePage'
  1236. });
  1237. }
  1238. }
  1239. })
  1240. }
  1241. showMkDialog() {
  1242. DialogHelper.showTextInputDialog({
  1243. title: '新建歌单',
  1244. maskColor: Color.Transparent,
  1245. text: '',
  1246. transition: AnimationHelper.transitionInDown(666),
  1247. onChange: (text) => {
  1248. console.error("onChange: " + text);
  1249. },
  1250. onAction: (action, dialogId, content) => {
  1251. // ToastUtil.showToast('content = ' +content)
  1252. if (action == DialogAction.TWO) {
  1253. const newName = content
  1254. const newPath = this.currentPath + '/' + newName
  1255. FileUtil.mkdir(newPath, true).then(() => {
  1256. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1257. this.getSortedFiles(this.currentPath)
  1258. }).catch((error: BusinessError) => {
  1259. console.error(error.message);
  1260. });
  1261. }
  1262. }
  1263. })
  1264. }
  1265. @State progress: number = 0;
  1266. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1267. if (ArrayUtil.isEmpty(uris)) {
  1268. return;
  1269. }
  1270. let newUris: string[] = [];
  1271. this.progress = 0
  1272. DialogHelper.showLoadingProgress({
  1273. progress: this.progress,
  1274. backCancel: false,
  1275. autoCancel: false,
  1276. loadColor: this.themeColor,
  1277. fontColor: this.themeColor
  1278. });
  1279. // 计算所有文件的总大小
  1280. let totalSize = 0;
  1281. for (let uri of uris) {
  1282. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1283. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1284. await fileIo.close(sourceFile.fd);
  1285. }
  1286. let totalRead = 0;
  1287. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1288. Logger.info(TAG, 'destPath uri: ' + destPath);
  1289. for (let i = 0; i < uris.length; i++) {
  1290. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1291. Logger.info(TAG, 'filePath uri: ' + filePath);
  1292. newUris.push(filePath);
  1293. try {
  1294. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1295. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1296. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1297. const buffer = new ArrayBuffer(buffSize);
  1298. let len = await fileIo.read(sourceFile.fd, buffer);
  1299. while (len > 0) {
  1300. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1301. totalRead += len;
  1302. // 计算总进度
  1303. this.progress = Math.floor((totalRead / totalSize) * 100);
  1304. DialogHelper.updateLoading('正在导入', this.progress);
  1305. len = await fileIo.read(sourceFile.fd, buffer);
  1306. }
  1307. await fileIo.close(sourceFile.fd);
  1308. await fileIo.close(destFile.fd);
  1309. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1310. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1311. let mediaItem: VideoItem =
  1312. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1313. this.table.insert(mediaItem, (id: number) => {
  1314. // 删除目标路径缓存
  1315. this.cache.delete(this.currentPath);
  1316. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1317. });
  1318. }
  1319. }
  1320. } catch (error) {
  1321. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1322. }
  1323. }
  1324. DialogHelper.closeLoading()
  1325. this.isZero = false
  1326. // setTimeout(() => {
  1327. // // 删除目标路径缓存
  1328. // this.cache.delete(this.currentPath);
  1329. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1330. // }, 500);
  1331. Logger.info(TAG, 'scan select video result:' + newUris)
  1332. }
  1333. //拉起音频
  1334. // goSelectMusic(){
  1335. //
  1336. // try {
  1337. // let audioSelectOptions = new picker.AudioSelectOptions();
  1338. // let audioPicker = new picker.AudioViewPicker(this.context);
  1339. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1340. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1341. // this.saveVideoDatas(audioSelectResult)
  1342. // }
  1343. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1344. // }).catch((err: BusinessError) => {
  1345. //
  1346. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1347. // });
  1348. // } catch (error) {
  1349. // let err: BusinessError = error as BusinessError;
  1350. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1351. // }
  1352. //
  1353. //
  1354. //
  1355. // }
  1356. goSelectImage(item: VideoItem) {
  1357. if (!item) {
  1358. return
  1359. }
  1360. let selectUris: Array<string> = [];
  1361. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1362. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1363. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1364. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1365. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1366. //用一个全局变量存储返回的uri
  1367. selectUris = photoSelectResult.photoUris;
  1368. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1369. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1370. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1371. console.info('file fd: ' + file.fd);
  1372. let name = await MD5.digestSync(this.videoUrl)
  1373. let imagePath = this.context.filesDir + FileUtil.separator + name
  1374. imagePath = fileUri.getUriFromPath(imagePath)
  1375. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1376. fileIo.copyFileSync(file.fd, file2.fd)
  1377. fileIo.closeSync(file);
  1378. fileIo.closeSync(file2);
  1379. if (item.filePath == this.currentSong?.filePath) {
  1380. this.cover = imagePath
  1381. }
  1382. if (item) {
  1383. item.pixelMapPath = imagePath
  1384. }
  1385. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1386. if (success) {
  1387. this.doUpdateData()
  1388. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1389. } else {
  1390. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1391. }
  1392. });
  1393. LogUtil.debug("onecold this.cover =" + this.cover)
  1394. }).catch((err: BusinessError) => {
  1395. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1396. })
  1397. }
  1398. // 拉起picker选择文件管理器
  1399. async callFilePickerSelectFile(): Promise<void> {
  1400. try {
  1401. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1402. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1403. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1404. } else {
  1405. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1406. }
  1407. let documentPicker = new picker.DocumentViewPicker();
  1408. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1409. Logger.info(TAG,
  1410. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1411. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1412. this.saveVideoDatas(DocumentSelectResult)
  1413. }
  1414. }).catch((err: BusinessError) => {
  1415. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1416. });
  1417. } catch (err) {
  1418. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1419. }
  1420. }
  1421. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1422. //操作确认类弹出框
  1423. DialogHelper.showAlertDialog({
  1424. maskColor: Color.Transparent,
  1425. content: "确定要删除这个文件吗?",
  1426. backgroundColor: Color.Grey,
  1427. transition: AnimationHelper.transitionInUp(555),
  1428. onAction: (action) => {
  1429. if (action == DialogAction.ONE) {
  1430. // ToastUtil.showToast(`您点击了取消按钮`);
  1431. } else if (action == DialogAction.TWO) {
  1432. // ToastUtil.showToast(`您点击了确认按钮`);
  1433. this.doDelete(item, index + '', filePath)
  1434. }
  1435. }
  1436. })
  1437. }
  1438. //删除单个索引index的视频
  1439. doDelete(item: VideoItem, index: string, filePath: string) {
  1440. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1441. Logger.info(TAG, 'delete filePath = ' + filePath);
  1442. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1443. //旧文件删除
  1444. this.table.deleteDataForParentPath(item.filePath, () => {
  1445. FileUtil.rmdir(filePath).then(() => {
  1446. this.videoLocalList.splice(Number(index), 1)
  1447. this.deleteCache(this.currentPath)
  1448. this.getSortedFiles(this.currentPath, true)
  1449. }).catch((error: BusinessError) => {
  1450. console.error(error.message);
  1451. });
  1452. });
  1453. } else {
  1454. this.table.deleteData(item, () => {
  1455. FileUtil.unlink(filePath)
  1456. .catch((error: BusinessError) => {
  1457. console.error(error.message);
  1458. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1459. })
  1460. .finally(() => {
  1461. this.videoLocalList.splice(Number(index), 1)
  1462. this.deleteCache(this.currentPath)
  1463. this.getSortedFiles(this.currentPath, true)
  1464. });
  1465. });
  1466. }
  1467. }
  1468. }
  1469. //重命名的对话框
  1470. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1471. DialogHelper.showTextInputDialog({
  1472. title: '重命名',
  1473. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1474. maskColor: Color.Transparent,
  1475. backgroundColor: Color.Grey,
  1476. transition: AnimationHelper.transitionInDown(666),
  1477. onChange: (text) => {
  1478. console.error("onChange: " + text);
  1479. },
  1480. onAction: (action, dialogId, content) => {
  1481. // ToastUtil.showToast('content = ' +content)
  1482. if (action == DialogAction.TWO) {
  1483. const newName = content
  1484. const newPath = this.currentPath + '/' + newName
  1485. console.log("onecold item = " + item.type);
  1486. this.doReName(index, newName, filePath, newPath, item)
  1487. }
  1488. }
  1489. })
  1490. }
  1491. //剪切 移动到另个文件夹的对话框
  1492. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1493. Logger.info('onecold showCutDialog')
  1494. let mList: Array<string> = []
  1495. let rPath = this.rootPath
  1496. if (isCurrent) {
  1497. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1498. rPath = this.currentPath
  1499. } else {
  1500. mList = Utility.getNameList(this.dirList);
  1501. rPath = this.rootPath
  1502. }
  1503. let dataBean = new BubbleBean()
  1504. dataBean.data = mList
  1505. dataBean.color = this.themeColor
  1506. dataBean.onItemClick = (i) => {
  1507. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1508. Logger.info('newPath = ' + newPath)
  1509. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1510. ToastUtil.showToast('移动成功')
  1511. this.table.deleteData(item, () => {
  1512. });
  1513. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1514. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1515. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1516. CommonConstants.TYPE_LOCAL, true);
  1517. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1518. this.table.insert(newItem, (id: number) => {
  1519. //加入数据库
  1520. });
  1521. }
  1522. this.cache.delete(this.currentPath); // 删除原路径缓存
  1523. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1524. this.getSortedFiles(this.currentPath, true)
  1525. }).catch((error: BusinessError) => {
  1526. console.error(error.message);
  1527. });
  1528. XPopup.dismissTop()
  1529. }
  1530. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1531. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1532. popupPosition = PopupPosition.TOP
  1533. }
  1534. if (index <= 3) {
  1535. popupPosition = PopupPosition.BOTTOM
  1536. }
  1537. let pup: XPopup
  1538. if (this.isDarkMode) {
  1539. pup = XPopup.Builder()
  1540. .setPopupPosition(popupPosition)
  1541. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1542. .setBackgroundColor(Color.Black)
  1543. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1544. .show()
  1545. } else {
  1546. pup = XPopup.Builder()
  1547. .setPopupPosition(popupPosition)
  1548. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1549. .setBackgroundColor(Color.White)
  1550. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1551. .show()
  1552. }
  1553. }
  1554. //复制 到另个文件夹的对话框
  1555. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1556. Logger.info('onecoldv showCopyDialog')
  1557. let mList: Array<string> = []
  1558. let rPath = this.rootPath
  1559. if (isCurrent) {
  1560. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1561. rPath = this.currentPath
  1562. } else {
  1563. mList = Utility.getNameList(this.dirList);
  1564. rPath = this.rootPath
  1565. }
  1566. let dataBean = new BubbleBean()
  1567. dataBean.data = mList
  1568. dataBean.isCopy = true
  1569. dataBean.color = this.themeColor
  1570. dataBean.onItemClick = (i) => {
  1571. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1572. Logger.info('newPath = ' + newPath)
  1573. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1574. ToastUtil.showToast('复制成功')
  1575. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1576. this.getSortedFiles(this.currentPath)
  1577. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1578. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1579. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1580. CommonConstants.TYPE_LOCAL, true);
  1581. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1582. this.table.insert(newItem, (id: number) => {
  1583. //加入数据库
  1584. });
  1585. }
  1586. }).catch((error: BusinessError) => {
  1587. console.error(error.message);
  1588. });
  1589. XPopup.dismissTop()
  1590. }
  1591. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1592. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1593. popupPosition = PopupPosition.TOP
  1594. }
  1595. if (index <= 3) {
  1596. popupPosition = PopupPosition.BOTTOM
  1597. }
  1598. let pup: XPopup
  1599. if (this.isDarkMode) {
  1600. pup = XPopup.Builder()
  1601. .setPopupPosition(popupPosition)
  1602. .atView(id)
  1603. .setMaxHeight('60%')
  1604. .setBackgroundColor(Color.Black)
  1605. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1606. .show();
  1607. } else {
  1608. pup = XPopup.Builder()
  1609. .setPopupPosition(popupPosition)
  1610. .atView(id)
  1611. .setMaxHeight('60%')
  1612. .setBackgroundColor(Color.White)
  1613. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1614. .show();
  1615. }
  1616. }
  1617. //重命名索引index的视频
  1618. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1619. FileUtil.rename(oldPath, newPath).then(async () => {
  1620. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1621. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1622. //如果是文件夹先删除源数据,再添加新数据
  1623. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1624. if (success) {
  1625. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1626. } else {
  1627. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1628. }
  1629. });
  1630. this.scanDirectory(newPath)
  1631. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1632. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1633. if (success) {
  1634. console.log(" onecold 重命名成功,数据库已同步");
  1635. } else {
  1636. console.error(" onecold 重命名数据库失败原因: " + error);
  1637. }
  1638. });
  1639. }
  1640. let mediaItem: VideoItem =
  1641. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1642. this.videoLocalList[index] = mediaItem;
  1643. }
  1644. this.cache.delete(this.currentPath)
  1645. this.getSortedFiles(this.currentPath, true)
  1646. }).catch((error: BusinessError) => {
  1647. console.error(error.message);
  1648. });
  1649. }
  1650. build() {
  1651. Scroll() {
  1652. Column() {
  1653. if (!this.isShowCoverHeader()) {
  1654. Column() {
  1655. Line().width('100%').height('100%')
  1656. }
  1657. .height(this.topRectHeight)
  1658. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1659. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1660. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1661. TitleBar({ model: $titleBarModel })
  1662. .id('pup_positon_music')
  1663. }
  1664. Stack() {
  1665. Column() {
  1666. XComponent({
  1667. id: 'xcomponentId',
  1668. type: 'surface',
  1669. libraryname: 'ijkplayer_napi',
  1670. controller: this.xcomponentController
  1671. })
  1672. .onLoad((event?: object) => {
  1673. if (!!event) {
  1674. this.initDelayPlay(event);
  1675. }
  1676. })
  1677. .onLoad((event?: object) => {
  1678. if (!!event) {
  1679. this.initDelayPlay(event);
  1680. }
  1681. })
  1682. .onKeyEvent((event?: KeyEvent) => {
  1683. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1684. if (!event || event.type !== KeyType.Down) {
  1685. return;
  1686. }
  1687. //空格键 Space key controls pause/play
  1688. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1689. this.playOrPause()
  1690. }
  1691. // Right-click to fast forward
  1692. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1693. this.sessionFastForwardCallback(15);
  1694. }
  1695. // Left-click to rewind
  1696. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1697. this.sessionRewindCallback(15);
  1698. }
  1699. })
  1700. .onDestroy(() => {
  1701. })
  1702. .width('100%')// .width(this.videoWidth)
  1703. .aspectRatio(this.videoAspectRatio)
  1704. }
  1705. .aspectRatio(this.videoAspectRatio)
  1706. .justifyContent(FlexAlign.Center)
  1707. .backgroundColor(Color.Transparent)
  1708. .visibility(Visibility.Hidden)
  1709. .height(CommonConstants.FULL_PERCENT)
  1710. .width(CommonConstants.FULL_PERCENT)
  1711. Stack() {
  1712. Row() {
  1713. Blank()
  1714. .layoutWeight(1)
  1715. IndexerView(
  1716. {
  1717. indexArray: DEFAULT_INDEX,
  1718. selectedIndex: this.selectedIndex,
  1719. textSize: 12,
  1720. selectedColor: "#ff419ee5",
  1721. normalColor: "#ffa0a0a0",
  1722. floatSelectedTextColor: "#ffffff",
  1723. floatSelectedViewColor: "#ff419ee5",
  1724. onIndexChanged: (index) => {
  1725. this.listScroller.scrollToIndex(index)
  1726. }
  1727. })
  1728. .width(24)
  1729. .height("50%")
  1730. }.visibility(Visibility.None)
  1731. Column() {
  1732. if (!this.isShowCoverHeader()) {
  1733. this.tabTitle()
  1734. }
  1735. if (this.isGridMusic) {
  1736. this.getGridView()
  1737. } else {
  1738. this.getListView()
  1739. }
  1740. if (this.modeType == 0) {
  1741. Column() {
  1742. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1743. .width(130)
  1744. .height(50)
  1745. .margin({ top: 100, bottom: 40 })
  1746. .backgroundColor(this.themeColor)
  1747. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  1748. .onClick(() => {
  1749. this.asyncCurrentPathData()
  1750. })
  1751. }
  1752. .height(100)
  1753. .position({ top: 260 })
  1754. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  1755. .animation({ duration: 500 }),
  1756. TransitionEffect.scale({ x: 0, y: 0 })))
  1757. .justifyContent(FlexAlign.Center)
  1758. .opacity(this.isZero ? 1 : 0)
  1759. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  1760. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1761. .animation({
  1762. duration: 500,
  1763. curve: 'ease-in-out' // 可选动画曲线
  1764. })
  1765. .width('100%')
  1766. }
  1767. }
  1768. .layoutWeight(1)
  1769. .height('100%')
  1770. }
  1771. .layoutWeight(1)
  1772. .height('100%')
  1773. Row() {
  1774. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1775. .width('35%')
  1776. .height(60)
  1777. .margin({ top: 10, bottom: 10, right: 6 })
  1778. .backgroundColor(this.themeColor)
  1779. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1780. .onClick(() => {
  1781. if (this.isAllSelected) {
  1782. // 全不选
  1783. this.selectedFiles = [];
  1784. } else {
  1785. // 全选
  1786. this.selectedFiles = [...this.getCurFileList()];
  1787. }
  1788. this.isAllSelected = !this.isAllSelected;
  1789. })
  1790. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1791. .width('35%')
  1792. .height(60)
  1793. .id('music_cut')
  1794. .margin({ top: 10, bottom: 10, right: 6 })
  1795. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1796. .backgroundColor(this.themeColor)
  1797. .onClick(() => {
  1798. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1799. })
  1800. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1801. .width('35%')
  1802. .height(60)
  1803. .id('music_cut_current')
  1804. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1805. .margin({ top: 10, bottom: 10, right: 6 })
  1806. .backgroundColor(this.themeColor)
  1807. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1808. .onClick(() => {
  1809. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1810. })
  1811. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1812. .width('35%')
  1813. .height(60)
  1814. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1815. .margin({ top: 10, bottom: 10, right: 6 })
  1816. .backgroundColor(this.themeColor)
  1817. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1818. .onClick(() => {
  1819. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1820. })
  1821. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1822. .width('35%')
  1823. .height(60)
  1824. .margin({ top: 10, bottom: 10, right: 6 })
  1825. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  1826. .backgroundColor(this.themeColor)
  1827. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1828. .onClick(() => {
  1829. this.showWarnIsDelete()
  1830. })
  1831. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1832. .width('35%')
  1833. .height(60)
  1834. .margin({ top: 10, bottom: 10, right: 6 })
  1835. .backgroundColor(this.themeColor)
  1836. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1837. .onClick(() => {
  1838. this.selectedFiles = [];
  1839. this.isAllSelected = false
  1840. this.isMultiSelect = false
  1841. })
  1842. }
  1843. .width('100%')
  1844. .justifyContent(FlexAlign.Center)
  1845. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1846. .opacity(this.isMultiSelect ? 1 : 0)
  1847. .animation({
  1848. duration: 666,
  1849. curve: 'ease-in-out' // 可选动画曲线
  1850. })
  1851. .position(this.isShowCoverHeader() ? { bottom: 78 }
  1852. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  1853. }
  1854. .width('100%')
  1855. .height('100%')
  1856. .alignContent(Alignment.Top)
  1857. Column() {
  1858. this.PlayController()
  1859. }
  1860. .hitTestBehavior(HitTestMode.Transparent)
  1861. .position({ bottom: 0 }) // 将 Row 固定在底部
  1862. .opacity(this.barBottomOpacity)
  1863. }
  1864. .width('100%')
  1865. .height('100%')
  1866. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  1867. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  1868. .backgroundImagePosition(Alignment.Center)
  1869. .backdropBlur(this.blurValue)
  1870. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  1871. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1872. }
  1873. }
  1874. asyncCurrentPathData() {
  1875. if (this.modeType == 0) {
  1876. workerInstance.postMessage({
  1877. code: 1,
  1878. data1: this.context,
  1879. data2: this.currentPath,
  1880. data3: this.lockPath,
  1881. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1882. });
  1883. }
  1884. }
  1885. // 处理文件选择的函数
  1886. handleFileSelection(item: VideoItem, checked: boolean) {
  1887. if (checked) {
  1888. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1889. this.selectedFiles.push(item);
  1890. }
  1891. } else {
  1892. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1893. if (index > -1) {
  1894. this.selectedFiles.splice(index, 1);
  1895. }
  1896. }
  1897. }
  1898. showWarnIsDelete() {
  1899. //操作确认类弹出框
  1900. DialogHelper.showAlertDialog({
  1901. content: "确定要删除这些文件吗?",
  1902. transition: AnimationHelper.transitionInUp(666),
  1903. maskColor: Color.Transparent,
  1904. backgroundColor: Color.Grey,
  1905. onAction: (action) => {
  1906. if (action == DialogAction.ONE) {
  1907. // ToastUtil.showToast(`您点击了取消按钮`);
  1908. } else if (action == DialogAction.TWO) {
  1909. // ToastUtil.showToast(`您点击了确认按钮`);
  1910. this.deleteMultipleFiles()
  1911. }
  1912. }
  1913. })
  1914. }
  1915. //多选删除文件
  1916. deleteMultipleFiles() {
  1917. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1918. this.selectedFiles.forEach((item) => {
  1919. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1920. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1921. this.table.deleteDataForParentPath(item.filePath, () => {
  1922. FileUtil.rmdir(item.filePath).then(() => {
  1923. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1924. this.selectedFiles = [];
  1925. this.isMultiSelect = false
  1926. this.isAllSelected = false
  1927. this.cache.delete(this.currentPath);
  1928. this.getSortedFiles(this.currentPath, true);
  1929. }).catch((error: Error) => {
  1930. console.error(error.message);
  1931. });
  1932. });
  1933. } else {
  1934. this.table.deleteData(item, () => {
  1935. FileUtil.unlink(item.filePath).catch((error: Error) => {
  1936. console.error(error.message);
  1937. }).finally(() => {
  1938. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1939. this.selectedFiles = [];
  1940. this.isMultiSelect = false
  1941. this.isAllSelected = false
  1942. this.cache.delete(this.currentPath);
  1943. this.getSortedFiles(this.currentPath, true);
  1944. });
  1945. });
  1946. }
  1947. });
  1948. }
  1949. }
  1950. //多选移动文件
  1951. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1952. Logger.info('onecold showCutDialogForMultipleFiles')
  1953. let mList: Array<string> = []
  1954. let rPath = this.rootPath
  1955. if (isCurrent) {
  1956. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1957. rPath = this.currentPath
  1958. } else {
  1959. mList = Utility.getNameList(this.dirList);
  1960. rPath = this.rootPath
  1961. }
  1962. let dataBean = new BubbleBean();
  1963. dataBean.data = mList;
  1964. dataBean.color = this.themeColor
  1965. dataBean.onItemClick = (i) => {
  1966. const newDirPath = rPath + '/' + mList[i];
  1967. // Logger.info('newDirPath = ' + newDirPath)
  1968. this.selectedFiles.forEach((item) => {
  1969. const newPath = newDirPath + '/' + item.fileName;
  1970. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1971. ToastUtil.showToast('移动成功');
  1972. this.table.deleteData(item, () => {
  1973. this.cache.delete(this.currentPath); // 删除原路径缓存
  1974. this.cache.delete(newDirPath); // 删除目标路径缓存
  1975. this.getSortedFiles(this.currentPath, true);
  1976. });
  1977. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1978. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1979. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1980. CommonConstants.TYPE_LOCAL, true);
  1981. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1982. this.table.insert(newItem, (id: number) => {
  1983. //加入数据库
  1984. });
  1985. }
  1986. }).catch((error: Error) => {
  1987. console.error(error.message);
  1988. });
  1989. });
  1990. this.isMultiSelect = false
  1991. this.selectedFiles = [];
  1992. this.isAllSelected = false
  1993. XPopup.dismissTop();
  1994. };
  1995. let pup: XPopup
  1996. if (this.isDarkMode) {
  1997. pup = XPopup.Builder()
  1998. .setPopupPosition(PopupPosition.TOP)
  1999. .atView(viewId)
  2000. .setBackgroundColor(Color.Black)
  2001. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2002. .show();
  2003. } else {
  2004. pup = XPopup.Builder()
  2005. .setPopupPosition(PopupPosition.TOP)
  2006. .atView(viewId)
  2007. .setBackgroundColor(Color.White)
  2008. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2009. .show();
  2010. }
  2011. }
  2012. doFav(item: VideoItem) {
  2013. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2014. let isFav = 0
  2015. if (Utility.getIsFav(this.favList, item)) {
  2016. isFav = 0
  2017. } else {
  2018. isFav = 1
  2019. }
  2020. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2021. if (result) {
  2022. if (isFav === 1) {
  2023. ToastUtil.showToast('收藏成功');
  2024. } else {
  2025. ToastUtil.showToast('取消收藏成功');
  2026. }
  2027. this.deleteCache(this.currentPath)
  2028. this.getFavList(false)
  2029. if (this.modeType === 0 && !this.isFavMusic) {
  2030. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2031. this.getSortedFiles(this.currentPath)
  2032. }
  2033. workerInstance.postMessage({ code: 2, data: this.context });
  2034. workerInstance.postMessage({ code: 3, data: this.context });
  2035. workerInstance.postMessage({ code: 4, data: this.context });
  2036. }
  2037. })
  2038. }
  2039. //多选复制文件
  2040. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2041. console.log('onecold showCopyDialogForMultipleFiles');
  2042. let mList: Array<string> = []
  2043. let rPath = this.rootPath
  2044. if (isCurrent) {
  2045. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2046. rPath = this.currentPath
  2047. } else {
  2048. mList = Utility.getNameList(this.dirList);
  2049. rPath = this.rootPath
  2050. }
  2051. let dataBean = new BubbleBean();
  2052. dataBean.data = mList;
  2053. dataBean.isCopy = true
  2054. dataBean.color = this.themeColor
  2055. dataBean.onItemClick = (i) => {
  2056. const newDirPath = rPath + '/' + mList[i];
  2057. // Logger.info('newDirPath = ' + newDirPath)
  2058. this.selectedFiles.forEach((item) => {
  2059. const newPath = newDirPath + '/' + item.fileName;
  2060. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2061. ToastUtil.showToast('复制成功');
  2062. this.cache.delete(newDirPath); // 删除目标路径缓存
  2063. this.getSortedFiles(this.currentPath);
  2064. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2065. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2066. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2067. CommonConstants.TYPE_LOCAL, true);
  2068. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2069. this.table.insert(newItem, (id: number) => {
  2070. //加入数据库
  2071. });
  2072. }
  2073. }).catch((error: Error) => {
  2074. console.error(error.message);
  2075. });
  2076. });
  2077. this.isMultiSelect = false
  2078. this.selectedFiles = [];
  2079. this.isAllSelected = false
  2080. XPopup.dismissTop();
  2081. };
  2082. let pup: XPopup
  2083. if (this.isDarkMode) {
  2084. pup = XPopup.Builder()
  2085. .setPopupPosition(PopupPosition.TOP)
  2086. .atView(viewId)
  2087. .setBackgroundColor(Color.Black)
  2088. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2089. .show();
  2090. } else {
  2091. pup = XPopup.Builder()
  2092. .setPopupPosition(PopupPosition.TOP)
  2093. .atView(viewId)
  2094. .setBackgroundColor(Color.White)
  2095. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2096. .show();
  2097. }
  2098. }
  2099. @Builder
  2100. private DirItem(item: VideoItem, index?: number) {
  2101. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2102. Row() {
  2103. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2104. $r('app.media.music_group'))
  2105. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2106. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2107. .fillColor(this.themeColor)// .fontSize(33)
  2108. .alt($r('app.media.music_group'))
  2109. .borderRadius('100%')
  2110. .clip(true)
  2111. .margin({ left: 20, top: 8, bottom: 8 })
  2112. Column() {
  2113. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2114. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2115. .maxLines(1)// .width('88%')
  2116. .animation({
  2117. duration: 555,
  2118. curve: 'ease-in-out',
  2119. })
  2120. .transition({
  2121. type: TransitionType.Insert,
  2122. opacity: 0,
  2123. translate: { x: 160 }
  2124. })
  2125. .margin({ left: 10, right: 20 })
  2126. .fontColor($r('app.color.text_color'))
  2127. Row() {
  2128. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2129. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2130. .padding({ top: 8 })
  2131. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2132. .fontColor($r('app.color.text_color'))
  2133. .margin({ left: 10 })
  2134. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2135. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2136. .padding({ top: 8 })
  2137. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2138. .fontColor($r('app.color.text_color'))
  2139. .margin({ left: 10 })
  2140. Blank()
  2141. }
  2142. }
  2143. .height('100%')
  2144. .layoutWeight(1)
  2145. .justifyContent(FlexAlign.Center)
  2146. .alignItems(HorizontalAlign.Start)
  2147. Blank()
  2148. Image($r('app.media.arrow_right'))
  2149. .height(25)
  2150. .margin({ right: 10 })
  2151. .alignSelf(ItemAlign.Center)
  2152. .id(item.filePath)
  2153. }
  2154. }
  2155. .backgroundColor(Color.Transparent)
  2156. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2157. .width('100%')
  2158. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2159. .opacity(this.opacityItem) // 绑定透明度
  2160. }
  2161. isShowDir(dirName: string) {
  2162. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2163. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2164. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2165. if (dirName === undefined) {
  2166. return true
  2167. }
  2168. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2169. return this.isShowSimi
  2170. }
  2171. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2172. return this.isShowFAV
  2173. }
  2174. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2175. return this.isShowHistory
  2176. }
  2177. return true
  2178. }
  2179. @State opacityItem: number = 1; // 控制透明度的状态变量
  2180. @Builder
  2181. private MusicItem(item: VideoItem, index?: number) {
  2182. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2183. Row() {
  2184. Stack() {
  2185. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2186. .fillColor(this.themeColor)
  2187. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2188. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2189. .alt($r('app.media.music_red'))
  2190. .borderRadius('100%')
  2191. .clip(true)
  2192. .opacity(this.opacityItem)// 绑定透明度
  2193. .margin({ left: 20 })
  2194. }
  2195. Column() {
  2196. Column() {
  2197. Text(item.name)
  2198. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2199. .maxLines(1)
  2200. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2201. .animation({
  2202. duration: 555,
  2203. curve: 'Linear',
  2204. })
  2205. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2206. $r('app.color.text_color'))
  2207. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2208. .bindPopup(this.longItemFilePath === item.filePath, {
  2209. builder: this.MenuBuilder(item,index,item.filePath),
  2210. placement: Placement.Top,
  2211. // autoCancel: true,
  2212. mask: {color:'#33000000'},
  2213. // popupColor: Color.Yellow,
  2214. enableArrow: false,//是否显示箭头
  2215. showInSubWindow: false,
  2216. onStateChange: (e) => {
  2217. if (!e.isVisible) {
  2218. this.longItemFilePath = ''
  2219. this.tempLyricContent = ''
  2220. }
  2221. }
  2222. })
  2223. .gesture(LongPressGesture()
  2224. .onAction(async () => {
  2225. //如果是专辑和艺术家的首页,不能长按
  2226. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2227. return
  2228. //如果是我的收藏 最近播放等也不能长按
  2229. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2230. item.name === LocalMusic.STR_HISTORY_MUSIC
  2231. )
  2232. return
  2233. this.longItemFilePath = item.filePath
  2234. this.tempLyricContent = await this.getLyricContent(item)
  2235. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2236. })
  2237. .onActionEnd((event: GestureEvent) => {
  2238. })
  2239. )
  2240. Row() {
  2241. Column(){
  2242. Text(item.md5Str?.includes('Lossless')?
  2243. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2244. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2245. .padding({ top: 3,right:6,left:6,bottom:3 })
  2246. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2247. $r('app.color.text_color'))
  2248. .fontWeight(500)
  2249. .borderRadius(12)
  2250. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2251. .backgroundColor('#FFC107')
  2252. }
  2253. .padding({ top: 8 })
  2254. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2255. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2256. .padding({ top: 8 })
  2257. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2258. $r('app.color.text_color'))
  2259. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2260. Blank()
  2261. Text(item.size)
  2262. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2263. .padding({ top: 8 })
  2264. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2265. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2266. $r('app.color.text_color'))
  2267. .margin({ left: 10 })
  2268. }
  2269. .gesture(LongPressGesture()
  2270. .onAction(async () => {
  2271. //如果是专辑和艺术家的首页,不能长按
  2272. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2273. return
  2274. //如果是我的收藏 最近播放等也不能长按
  2275. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2276. item.name === LocalMusic.STR_HISTORY_MUSIC
  2277. )
  2278. return
  2279. this.longItemFilePath = item.filePath
  2280. this.tempLyricContent = await this.getLyricContent(item)
  2281. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2282. })
  2283. .onActionEnd((event: GestureEvent) => {
  2284. })
  2285. )
  2286. }
  2287. .height('100%')
  2288. .width('100%')
  2289. .justifyContent(FlexAlign.Center)
  2290. .alignItems(HorizontalAlign.Start)
  2291. }
  2292. .height('100%')
  2293. .margin({ left: 5 })
  2294. .layoutWeight(1)
  2295. Column() {
  2296. Checkbox({ name: 'checkbox' + index })
  2297. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2298. .selectedColor(this.themeColor)
  2299. .shape(CheckBoxShape.CIRCLE)
  2300. .opacity(this.isMultiSelect ? 1 : 0)
  2301. .animation({
  2302. duration: 666,
  2303. curve: 'Smooth' // 可选动画曲线
  2304. })
  2305. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2306. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2307. .margin({ left: 20, top: 8, bottom: 8 })
  2308. .width(22)
  2309. .height(22)
  2310. ImageAnimator()
  2311. .images(this.imagesF)// 动画数组
  2312. .duration(1000)// 持续
  2313. .state(this.animationState)// 动画状态
  2314. .fillMode(FillMode.Forwards)
  2315. .width(18)
  2316. .margin({ right: 20, top: 8, bottom: 8 })
  2317. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2318. Visibility.None)
  2319. .height(18)
  2320. .iterations(-1) // 播放次数
  2321. }
  2322. }
  2323. }
  2324. .backgroundColor(Color.Transparent)
  2325. .width('100%')
  2326. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2327. }
  2328. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2329. @Builder
  2330. tabTitle() {
  2331. Column() {
  2332. // 使用 Stack 布局来实现绝对定位效果
  2333. Stack() {
  2334. // 背景动画容器
  2335. Row() {
  2336. ForEach(this.tabs, (i: string, index) => {
  2337. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2338. Flex()
  2339. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2340. .borderRadius(20)
  2341. .padding(10)
  2342. .margin(6)
  2343. .width('100%')
  2344. .height('100%')
  2345. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2346. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2347. .opacity(this.modeType === index ? 1 : 0)
  2348. .animation({
  2349. duration: 666,
  2350. playMode: PlayMode.Normal,
  2351. curve: 'ease-in-out'
  2352. });
  2353. }
  2354. .layoutWeight(1)
  2355. .margin({
  2356. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2357. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2358. });
  2359. });
  2360. }
  2361. .width('100%')
  2362. .height(50);
  2363. // 导航栏容器
  2364. Row() {
  2365. ForEach(this.tabs, (item: string, index) => {
  2366. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2367. Text(item)
  2368. .fontSize(16)
  2369. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2370. .padding(15)
  2371. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2372. .onClick(() => {
  2373. this.modeType = index;
  2374. this.onModeChange();
  2375. });
  2376. }
  2377. .layoutWeight(1)
  2378. .stateStyles({
  2379. pressed: { opacity: 0.6 } // 按压反馈
  2380. });
  2381. });
  2382. }
  2383. .width('100%')
  2384. .height(this.topBarHeight)
  2385. .opacity(this.barOpacity)
  2386. .backgroundColor(Color.Transparent);
  2387. }
  2388. .width('100%')
  2389. .height(this.topBarHeight)
  2390. .opacity(this.barOpacity)
  2391. Line()
  2392. .width('100%')
  2393. .height(1)
  2394. .backgroundColor($r('app.color.index_background'))
  2395. .opacity(this.barOpacity)
  2396. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2397. }
  2398. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2399. }
  2400. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2401. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2402. @State currentYear:string = ''
  2403. isShowCoverHeader() {
  2404. if (!this.isShowHeader) {
  2405. return false
  2406. }
  2407. if (this.modeType == 0) {
  2408. if (this.isHistory || this.isFavMusic) {
  2409. return true
  2410. }
  2411. if (this.currentPath != this.rootPath) {
  2412. return true
  2413. }
  2414. }
  2415. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2416. }
  2417. @Builder
  2418. coverHeader() {
  2419. if (this.isShowCoverHeader()) {
  2420. Column() {
  2421. Stack() {
  2422. // 居中标题
  2423. Text('')
  2424. .fontSize(18)
  2425. .fontColor(Color.White)
  2426. .align(Alignment.Center)
  2427. // 左右按钮
  2428. Row() {
  2429. Image($r('app.media.left_back_white'))
  2430. .width(28)
  2431. .height(28)
  2432. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2433. .margin({ left: 12, right: 8 })
  2434. .onClick(() => {
  2435. animateTo({ duration: 555 }, () => {
  2436. this.doSwipBack()
  2437. })
  2438. })
  2439. Blank().flexGrow(1)
  2440. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2441. Image($r('app.media.add'))
  2442. .width(25)
  2443. .height(25)
  2444. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2445. .margin({ left: 8, right: 15 })
  2446. .onClick(() => {
  2447. this.showAddDialog()
  2448. })
  2449. }
  2450. }
  2451. .height(48)
  2452. .width('100%')
  2453. .alignItems(VerticalAlign.Center)
  2454. }
  2455. .height(48)
  2456. .width('100%')
  2457. Row() {
  2458. Column() {
  2459. Image(this.currentTitleCover)
  2460. .height(100)
  2461. .width(100)
  2462. .alt(this.imageLabel)
  2463. .borderRadius(8)
  2464. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2465. }
  2466. .alignItems(HorizontalAlign.Start)
  2467. .margin({ left: 30, top: 3, bottom: 15 })
  2468. Column() {
  2469. Column() {
  2470. Text(this.currentTitleName)
  2471. .fontSize(16)
  2472. .maxLines(1)
  2473. .fontWeight(FontWeight.Bold)
  2474. .fontColor($r('app.color.text_color'))
  2475. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2476. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2477. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2478. .fontSize(14)
  2479. .padding({ top: 8 })
  2480. .maxLines(1)
  2481. .fontWeight(FontWeight.Bold)
  2482. .fontColor($r('app.color.text_color'))
  2483. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2484. if(this.videoLocalList[0].genre){
  2485. Text(`风格:${this.videoLocalList[0].genre}`)
  2486. .fontSize(14)
  2487. .padding({ top: 8 })
  2488. .maxLines(1)
  2489. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2490. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2491. ?Visibility.None:Visibility.Visible)
  2492. .fontWeight(FontWeight.Bold)
  2493. .fontColor($r('app.color.text_color'))
  2494. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2495. }
  2496. if(this.videoLocalList[0].year){
  2497. Text(`发行时间:${this.videoLocalList[0].year}`)
  2498. .fontSize(14)
  2499. .padding({ top: 8 })
  2500. .maxLines(1)
  2501. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2502. this.videoLocalList[0].year.includes(this.UNKONWN)
  2503. ?Visibility.None:Visibility.Visible)
  2504. .fontWeight(FontWeight.Bold)
  2505. .fontColor($r('app.color.text_color'))
  2506. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2507. }
  2508. }
  2509. if(this.modeType != 3){
  2510. Row() {
  2511. Text(`共${this.videoLocalList.length}首歌`)
  2512. .fontSize(13)
  2513. .fontWeight(FontWeight.Bold)
  2514. .padding({ top: 8 })
  2515. .fontColor($r('app.color.text_color'))
  2516. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2517. Blank()
  2518. }
  2519. }
  2520. }
  2521. .height('100%')
  2522. .width('100%')
  2523. .justifyContent(FlexAlign.Center)
  2524. .alignItems(HorizontalAlign.Start)
  2525. }
  2526. .height('100%')
  2527. .layoutWeight(1)
  2528. .margin({ left: 20 })
  2529. }
  2530. this.listViewTitle()
  2531. }
  2532. .backgroundImage(this.getCoverTitleBg())
  2533. .height(250)
  2534. .width('100%')
  2535. .backgroundImageSize({ height: '100%', width: '100%' })
  2536. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2537. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2538. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2539. .justifyContent(FlexAlign.SpaceBetween)
  2540. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2541. TransitionEffect.scale({ x: 0, y: 0 })))
  2542. } else {
  2543. this.listViewTitle()
  2544. }
  2545. }
  2546. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2547. if (this.isCustomizeBg) {
  2548. return ('rgba(255,255,255,0.2)')
  2549. }
  2550. if (this.isDarkMode) {
  2551. return $r('app.color.user_center_card_background')
  2552. }
  2553. return this.currentTitleCover
  2554. }
  2555. @Builder
  2556. listViewTitle() {
  2557. Column() {
  2558. Row({ space: 8 }) {
  2559. Row({ space: 8 }) {
  2560. Image($r("app.media.hm_playlist"))
  2561. .width(25)
  2562. .margin({ left: 8 })
  2563. .fillColor(this.themeColor)
  2564. Text(`共找到${this.artistList.length}位艺术家`)
  2565. .fontColor($r('app.color.text_color'))
  2566. .fontSize(14)
  2567. .opacity(this.opacityItem)
  2568. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2569. Text(`共找到${this.albumList.length}张专辑`)
  2570. .fontColor($r('app.color.text_color'))
  2571. .opacity(this.opacityItem)
  2572. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2573. .fontSize(14)
  2574. }
  2575. .layoutWeight(1)
  2576. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2577. Row() {
  2578. TextInput({
  2579. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2580. text: this.searchText
  2581. })
  2582. .height(35)
  2583. .onChange((value: string) => {
  2584. this.onSearchInput(value);
  2585. })
  2586. .layoutWeight(1)
  2587. Text(`取消`)
  2588. .margin({ left: 10, right: 10 })
  2589. .fontColor($r('app.color.text_color'))
  2590. .fontSize(16)
  2591. .onClick(() => {
  2592. this.isSearchMode = false
  2593. this.searchText = ''
  2594. if (this.modeType === 2) {
  2595. this.updateListData(this.artistList)
  2596. } else {
  2597. this.updateListData(this.albumList)
  2598. }
  2599. })
  2600. }
  2601. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2602. .animation({
  2603. duration: 666,
  2604. curve: 'ease-in-out' // 可选动画曲线
  2605. })
  2606. Blank()
  2607. Image($r("app.media.search"))
  2608. .width(25)
  2609. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2610. .animation({
  2611. duration: 666,
  2612. curve: 'ease-in-out' // 可选动画曲线
  2613. })// .opacity(this.opacityItem)
  2614. .fillColor(this.themeColor)
  2615. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2616. .onClick(() => {
  2617. this.isSearchMode = true
  2618. })
  2619. Image($r("app.media.top_rank"))
  2620. .width(25)// .opacity(this.opacityItem)
  2621. .fillColor(this.themeColor)
  2622. .animation({
  2623. duration: 666,
  2624. curve: 'ease-in-out' // 可选动画曲线
  2625. })
  2626. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2627. .onClick(() => {
  2628. this.showRankDialog()
  2629. })
  2630. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2631. .width(25)
  2632. .animation({
  2633. duration: 666,
  2634. curve: 'ease-in-out' // 可选动画曲线
  2635. })
  2636. .fillColor(this.themeColor)
  2637. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2638. .onClick(() => {
  2639. this.isGridMusic = !this.isGridMusic
  2640. })
  2641. }
  2642. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2643. Visibility.None)
  2644. .width('100%')
  2645. .padding(10)
  2646. .height(50)
  2647. .border({
  2648. width: { bottom: 1 },
  2649. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2650. })
  2651. Row({ space: 8 }) {
  2652. Row({ space: 8 }) {
  2653. Image($r("app.media.hm_play"))
  2654. .width(25)
  2655. .margin({ left: 8 })
  2656. .fillColor(this.themeColor)
  2657. Text(`播放全部`)
  2658. .fontColor($r('app.color.text_color'))
  2659. .fontSize(14)
  2660. .animation({
  2661. duration: 666,
  2662. curve: 'ease-in-out' // 可选动画曲线
  2663. })
  2664. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2665. .fontColor($r('app.color.text_color'))
  2666. .fontSize(14)
  2667. .opacity(this.opacityItem)
  2668. .animation({
  2669. duration: 666,
  2670. curve: 'ease-in-out' // 可选动画曲线
  2671. })
  2672. }
  2673. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2674. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2675. .animation({
  2676. duration: 666,
  2677. curve: 'ease-in-out' // 可选动画曲线
  2678. })
  2679. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2680. .onTouch((event: TouchEvent) => {
  2681. if (event.type === TouchType.Down) {
  2682. this.isClickedPLayAll = true;
  2683. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2684. this.isClickedPLayAll = false;
  2685. }
  2686. })
  2687. .onClick(() => {
  2688. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2689. if (this.modeType === 0) {
  2690. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2691. this.doPlay(this.getCurFileList()[0])
  2692. }
  2693. } else {
  2694. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2695. this.doPlay(this.mediaKuList[0])
  2696. }
  2697. }
  2698. })
  2699. Row() {
  2700. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2701. .height(35)
  2702. .onChange((value: string) => {
  2703. this.onSearchInput(value);
  2704. })
  2705. .layoutWeight(1)
  2706. Text(`取消`)
  2707. .margin({ left: 10, right: 10 })
  2708. .fontColor($r('app.color.text_color'))
  2709. .fontSize(16)
  2710. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2711. .onClick(() => {
  2712. this.isSearchMode = false
  2713. this.searchText = ''
  2714. this.updateListData(this.mediaKuList)
  2715. })
  2716. }
  2717. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2718. .animation({
  2719. duration: 666,
  2720. curve: 'ease-in-out' // 可选动画曲线
  2721. })
  2722. Blank()
  2723. Image($r("app.media.search"))
  2724. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2725. .animation({
  2726. duration: 666,
  2727. curve: 'ease-in-out' // 可选动画曲线
  2728. })// .opacity(this.opacityItem)
  2729. .fillColor(this.themeColor)
  2730. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2731. .onClick(() => {
  2732. this.isSearchMode = true
  2733. })
  2734. Image($r("app.media.refresh"))
  2735. .fillColor(this.themeColor)
  2736. .width(25)
  2737. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2738. .animation({
  2739. duration: 666,
  2740. curve: 'ease-in-out' // 可选动画曲线
  2741. })
  2742. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2743. .onClick(() => {
  2744. if (this.isFavMusic) {
  2745. this.getFavList(true)
  2746. } else {
  2747. this.deleteCache(this.currentPath)
  2748. this.getSortedFiles(this.currentPath)
  2749. }
  2750. })
  2751. Image($r("app.media.top_rank"))
  2752. .width(25)
  2753. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2754. Visibility.Visible)// .opacity(this.opacityItem)
  2755. .animation({
  2756. duration: 666,
  2757. curve: 'ease-in-out' // 可选动画曲线
  2758. })
  2759. .fillColor(this.themeColor)
  2760. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2761. .onClick(() => {
  2762. this.showRankDialog()
  2763. })
  2764. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2765. .width(24)
  2766. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2767. .animation({
  2768. duration: 666,
  2769. curve: 'ease-in-out' // 可选动画曲线
  2770. })
  2771. .fillColor(this.themeColor)
  2772. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2773. .onClick(() => {
  2774. this.isMultiSelect = !this.isMultiSelect
  2775. })
  2776. SymbolGlyph($r('sys.symbol.trash'))
  2777. .fontColor([this.themeColor])
  2778. .fontSize(25)
  2779. .effectStrategy(1)
  2780. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2781. .animation({
  2782. duration: 666,
  2783. curve: 'ease-in-out' // 可选动画曲线
  2784. })
  2785. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2786. .onClick(() => {
  2787. this.clearVideoHistory() //清空播放记录
  2788. })
  2789. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2790. .width(24)
  2791. .animation({
  2792. duration: 666,
  2793. curve: 'ease-in-out' // 可选动画曲线
  2794. })
  2795. .fillColor(this.themeColor)
  2796. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2797. .onClick(() => {
  2798. this.isGridMusic = !this.isGridMusic
  2799. })
  2800. }
  2801. .width('100%')
  2802. .padding(10)
  2803. .height(50)
  2804. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2805. .border({
  2806. width: { bottom: 1 },
  2807. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2808. })
  2809. }
  2810. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  2811. }
  2812. //搜索功能的实现
  2813. @State searchText: string = ''; // 用户输入内容
  2814. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2815. @State isSearchMode: boolean = false
  2816. // 实时搜索逻辑(带防抖)
  2817. private onSearchInput(value: string) {
  2818. this.searchText = value.trim();
  2819. let mSearchList: Array<VideoItem> = []
  2820. switch (this.modeType) {
  2821. case 0:
  2822. mSearchList = this.videoLocalList
  2823. break;
  2824. case 1:
  2825. mSearchList = this.mediaKuList
  2826. break;
  2827. case 2:
  2828. mSearchList = this.artistList
  2829. break;
  2830. case 3:
  2831. mSearchList = this.albumList
  2832. break;
  2833. }
  2834. // 新增条件判断:空输入时显示所有数据
  2835. if (this.searchText === '') {
  2836. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2837. } else {
  2838. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2839. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2840. });
  2841. }
  2842. this.updateListData(this.filteredList);
  2843. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2844. }
  2845. @State dragItem: number = -1
  2846. @State scaleItem: number = -1
  2847. @State neighborItem: number = -1
  2848. @State neighborScale: number = -1
  2849. @State offsetY: number = 0
  2850. private dragRefOffset: number = 0
  2851. private ITEM_INTV: number = 78
  2852. scaleSelect(item: number): number {
  2853. if (this.scaleItem === item) {
  2854. return 1.05
  2855. } else if (this.neighborItem === item) {
  2856. return this.neighborScale
  2857. } else {
  2858. return 1
  2859. }
  2860. }
  2861. itemMove(index: number, newIndex: number): void {
  2862. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2863. return;
  2864. }
  2865. let tmp = this.videoLocalList.splice(index, 1);
  2866. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2867. this.dataSource.pushArrayData(this.videoLocalList)
  2868. }
  2869. // Grid布局的开始
  2870. private dragRefOffSetX: number = 0;
  2871. private dragRefOffSetY: number = 0;
  2872. private FIX_VP_X: number = 180;
  2873. private FIX_VP_Y: number = 84;
  2874. isDraggable(index: number): boolean {
  2875. return index >= 0;
  2876. }
  2877. getRowEnd(item: number) {
  2878. if (item.toString() === '0') {
  2879. return 1;
  2880. } else {
  2881. return 0;
  2882. }
  2883. }
  2884. // [Start itemMove_start]
  2885. // itemMoveGrid(index: number, newIndex: number): void {
  2886. // if (!this.isDraggable(newIndex)) {
  2887. // return;
  2888. // }
  2889. // let tmp = this.videoLocalList.splice(index, 1);
  2890. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2891. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2892. // }
  2893. isInLeft(index: number) {
  2894. return index % 2 == 0;
  2895. }
  2896. down(index: number): void {
  2897. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2898. return;
  2899. }
  2900. this.offsetY -= this.FIX_VP_Y;
  2901. this.dragRefOffSetY += this.FIX_VP_Y;
  2902. this.itemMove(index, index + 1);
  2903. }
  2904. up(index: number): void {
  2905. if (!this.isDraggable(index - 2)) {
  2906. return;
  2907. }
  2908. this.offsetY += this.FIX_VP_Y;
  2909. this.dragRefOffSetY -= this.FIX_VP_Y;
  2910. this.itemMove(index, index - 1);
  2911. }
  2912. left(index: number): void {
  2913. if (this.isInLeft(index)) {
  2914. return;
  2915. }
  2916. if (!this.isDraggable(index - 1)) {
  2917. return;
  2918. }
  2919. this.offsetX += this.FIX_VP_X;
  2920. this.dragRefOffSetX -= this.FIX_VP_X;
  2921. this.itemMove(index, index - 1)
  2922. }
  2923. right(index: number): void {
  2924. if (!this.isInLeft(index)) {
  2925. return;
  2926. }
  2927. if (!this.isDraggable(index + 1)) {
  2928. return;
  2929. }
  2930. this.offsetX -= this.FIX_VP_X;
  2931. this.dragRefOffSetX += this.FIX_VP_X;
  2932. this.itemMove(index, index + 1)
  2933. }
  2934. private scroller: Scroller = new Scroller();
  2935. @State startIndex: number = 0
  2936. @State endIndex: number = 0
  2937. @State scaleValue: number = 1
  2938. @State pinchValue: number = 1
  2939. layoutOptionsForHeader: GridLayoutOptions = {
  2940. regularSize: [1, 1], // 只支持[1, 1]
  2941. irregularIndexes: [0], // 索引为0的GridItem占用一行
  2942. };
  2943. @Builder
  2944. getGridView() {
  2945. Grid(this.scroller, this.layoutOptionsForHeader) {
  2946. GridItem() {
  2947. if (this.isShowCoverHeader()) {
  2948. this.coverHeader()
  2949. } else {
  2950. this.listViewTitle()
  2951. }
  2952. }
  2953. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  2954. GridItem() {
  2955. Stack({ alignContent: Alignment.Center }) {
  2956. this.MusicItemGrid(item, index)
  2957. }
  2958. }
  2959. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  2960. TransitionEffect.scale({ x: 0, y: 0 })))
  2961. .clickEffect({ level: ClickEffectLevel.LIGHT })
  2962. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  2963. .zIndex(this.dragItem === index ? 1 : 0)
  2964. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  2965. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  2966. //长按拖动代码
  2967. .gesture(
  2968. GestureGroup(GestureMode.Sequence,
  2969. LongPressGesture({ repeat: true })
  2970. .onAction(() => {
  2971. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2972. this.scaleItem = index;
  2973. })
  2974. })
  2975. .onActionEnd(() => {
  2976. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2977. this.scaleItem = -1;
  2978. })
  2979. }),
  2980. PanGesture({ fingers: 1, direction: null, distance: 0 })
  2981. .onActionStart(() => {
  2982. this.dragItem = index;
  2983. this.dragRefOffSetX = 0;
  2984. this.dragRefOffSetY = 0;
  2985. })
  2986. .onActionUpdate((event: GestureEvent) => {
  2987. this.offsetX = event.offsetX - this.dragRefOffSetX;
  2988. this.offsetY = event.offsetY - this.dragRefOffSetY;
  2989. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2990. let index = this.videoLocalList.indexOf(item);
  2991. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2992. this.down(index);
  2993. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2994. this.up(index);
  2995. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2996. this.right(index);
  2997. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2998. this.left(index);
  2999. }
  3000. })
  3001. // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  3002. // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  3003. // }
  3004. })
  3005. .onActionEnd(() => {
  3006. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3007. this.dragItem = -1;
  3008. })
  3009. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3010. this.scaleItem = -1;
  3011. })
  3012. })
  3013. )
  3014. .onCancel(() => {
  3015. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3016. this.dragItem = -1;
  3017. })
  3018. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3019. this.scaleItem = -1;
  3020. })
  3021. })
  3022. )
  3023. // [End gesture_start]
  3024. // [EndExclude GridItem_start]
  3025. }, (item: VideoItem) => item.filePath)
  3026. }
  3027. .width(this.isShowHeader ? '100%' : '94%')
  3028. .height('100%')
  3029. .editMode(true)
  3030. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3031. .animation({ duration: 500, curve: Curve.Ease }))
  3032. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3033. .margin({
  3034. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? 45 : 80)
  3035. : (this.isShowCoverHeader() ? 95 : 178)
  3036. })
  3037. .layoutWeight(1)
  3038. .scrollBar(BarState.Off)
  3039. .supportAnimation(true)
  3040. .cachedCount(3)
  3041. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3042. .columnsTemplate(
  3043. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3044. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3045. )
  3046. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3047. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3048. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3049. .gesture(PinchGesture({ fingers: 2 })
  3050. .onActionEnd((event: GestureEvent) => {
  3051. this.setGridTwoFingers()
  3052. })
  3053. .onActionUpdate(e => {
  3054. this.scaleValue = this.pinchValue * e.scale
  3055. })
  3056. .onActionStart(e => {
  3057. }))
  3058. .enableScrollInteraction(true)
  3059. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3060. .onScrollIndex((start: number, end: number) => {
  3061. this.startIndex = start
  3062. this.endIndex = end
  3063. })
  3064. .onScrollFrameBegin((offset: number) => {
  3065. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3066. // if (this.isPhoneLan()) {
  3067. // this.setBarHeightHide(offset)
  3068. // } else
  3069. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3070. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3071. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3072. if (this.isScrollHide) {
  3073. this.setBarHeightHide2(offset)
  3074. } else {
  3075. this.setBarHeightNormal()
  3076. }
  3077. } else {
  3078. this.setBarHeightHide(offset)
  3079. }
  3080. return { offsetRemain: offset };
  3081. })
  3082. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3083. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3084. .onDrop((event?: DragEvent) => {
  3085. try {
  3086. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3087. if (dragData !== undefined) {
  3088. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3089. if (records.length > 0) {
  3090. for (let i = 0; i < records.length; i++) {
  3091. let types = records[i].getTypes();
  3092. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3093. const fileUriUds =
  3094. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3095. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3096. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3097. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3098. this.targetFile = fileUriUds.oriUri;
  3099. this.saveVideoDatas([this.targetFile])
  3100. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3101. }
  3102. }
  3103. }
  3104. } else {
  3105. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3106. }
  3107. } else {
  3108. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3109. }
  3110. } catch (error) {
  3111. const err = error as BusinessError;
  3112. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3113. }
  3114. })
  3115. }
  3116. @State targetFile: string = '';
  3117. setGridTwoFingers() {
  3118. this.pinchValue = this.scaleValue;
  3119. Logger.info('this.pinchValue = ' + this.pinchValue);
  3120. if (this.pinchValue >= 1) {
  3121. this.twoFingerType++
  3122. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3123. if (this.twoFingerType > 3) {
  3124. this.twoFingerType = 3
  3125. }
  3126. } else {
  3127. this.twoFingerType--
  3128. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3129. if (this.twoFingerType < 1) {
  3130. this.twoFingerType = 3
  3131. this.isGridMusic = false
  3132. }
  3133. }
  3134. this.pinchValue = 1;
  3135. this.scaleValue = 1;
  3136. }
  3137. @State longItemFilePath: string = ''
  3138. @State tempLyricContent: string = ''
  3139. @Builder
  3140. private MusicItemGrid(item: VideoItem, index: number) {
  3141. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3142. Stack() {
  3143. Column() {
  3144. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3145. .height(this.getGridHeight())
  3146. .width(this.getGridWight())
  3147. .alt($r('app.media.ic_avatar6'))
  3148. .clip(true)
  3149. .borderRadius({
  3150. topLeft: 12,
  3151. topRight: 12,
  3152. bottomLeft: 0,
  3153. bottomRight: 0
  3154. })
  3155. .draggable(false)
  3156. .opacity(this.opacityItem)// 绑定透明度
  3157. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3158. // .animation({ duration: 500, curve: Curve.Ease }))
  3159. .animation({
  3160. duration: 666,
  3161. curve: 'ease-in-out' // 可选动画曲线
  3162. })
  3163. .margin({
  3164. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3165. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3166. })
  3167. Column() {
  3168. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3169. .fontSize(this.twoFingerType == 1 ? 14 : this.twoFingerType == 2 ? 16 : 18)
  3170. .maxLines(1)
  3171. .fontWeight(FontWeight.Bold)
  3172. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3173. .animation({
  3174. duration: 555,
  3175. curve: 'Linear',
  3176. })
  3177. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3178. $r('app.color.text_color'))
  3179. Column() {
  3180. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3181. .fontSize(11)
  3182. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3183. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3184. .fontColor($r('app.color.text_color'))
  3185. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3186. .fontSize(11)
  3187. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3188. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3189. .fontColor($r('app.color.text_color'))
  3190. Row(){
  3191. Column(){
  3192. Text(item.md5Str?.includes('Lossless')?
  3193. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3194. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3195. .padding({ top: 3,right:6,left:6,bottom:3 })
  3196. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3197. $r('app.color.text_color'))
  3198. .fontWeight(500)
  3199. .borderRadius(12)
  3200. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3201. .backgroundColor('#FFC107')
  3202. }
  3203. .margin({ top: 2 ,right:6})
  3204. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3205. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3206. Text(StrUtil.isEmpty(item.artist) ? 'Unknown' : item.artist)
  3207. .fontSize(11)
  3208. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3209. .maxLines(1)
  3210. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3211. .margin({ top: 2 ,right:18})
  3212. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3213. || item.type == CommonConstants.TYPE_IS_ALBUM
  3214. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3215. .fontWeight(FontWeight.Medium)
  3216. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3217. $r('app.color.text_color'))
  3218. }
  3219. }
  3220. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3221. }
  3222. .bindPopup(this.longItemFilePath === item.filePath, {
  3223. builder: this.MenuBuilder(item, index, item.filePath),
  3224. placement: Placement.Top,
  3225. // autoCancel: true,
  3226. mask: { color: '#33000000' },
  3227. // popupColor: Color.Yellow,
  3228. enableArrow: false, //是否显示箭头
  3229. showInSubWindow: false,
  3230. onStateChange: (e) => {
  3231. if (!e.isVisible) {
  3232. this.longItemFilePath = ''
  3233. this.tempLyricContent = ''
  3234. }
  3235. }
  3236. })
  3237. .gesture(LongPressGesture()
  3238. .onAction(async () => {
  3239. //如果是专辑和艺术家的首页,不能长按
  3240. if ((this.modeType === 2 || this.modeType == 3) && !this.isCanBack) {
  3241. return
  3242. }
  3243. //如果是我的收藏 最近播放等也不能长按
  3244. if (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3245. item.name === LocalMusic.STR_HISTORY_MUSIC
  3246. ) {
  3247. return
  3248. }
  3249. this.longItemFilePath = item.filePath
  3250. this.tempLyricContent = await this.getLyricContent(item)
  3251. LogUtil.info('长按this.tempLyricContent = ' + this.tempLyricContent)
  3252. })
  3253. .onActionEnd((event: GestureEvent) => {
  3254. })
  3255. )
  3256. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 55 : 42)
  3257. .width(this.getGridWight())
  3258. .justifyContent(FlexAlign.Center)
  3259. .margin({
  3260. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3261. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3262. })
  3263. }
  3264. .width(this.getGridWight())
  3265. .borderRadius(12)
  3266. .backgroundImage(item.pixelMapPath)
  3267. .backgroundImageSize({ height: '100%', width: '100%' })
  3268. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3269. .animation({ curve: Curve.Sharp, duration: 300 })
  3270. Checkbox({ name: 'checkbox' + index })
  3271. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3272. .selectedColor(this.themeColor)
  3273. .shape(CheckBoxShape.CIRCLE)
  3274. .opacity(this.isMultiSelect ? 1 : 0)
  3275. .animation({
  3276. duration: 666,
  3277. curve: 'Smooth' // 可选动画曲线
  3278. })
  3279. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3280. Visibility.None)
  3281. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3282. .margin({ left: 20, top: 8, bottom: 8 })
  3283. .width(38)
  3284. .height(38)
  3285. }
  3286. }
  3287. .backgroundColor(Color.Transparent)
  3288. .width('100%')
  3289. .padding({ top: 15 })
  3290. .height(this.getGridAllHeight())
  3291. .onClick(() => {
  3292. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3293. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3294. this.handleFileSelection(item, !isChecked);
  3295. } else {
  3296. this.doPlay(item, index)
  3297. }
  3298. })
  3299. }
  3300. getGridAllHeight() {
  3301. let heightG = 222
  3302. switch (this.twoFingerType) {
  3303. case 1:
  3304. heightG = 118
  3305. break;
  3306. case 2:
  3307. heightG = 168
  3308. break;
  3309. case 3:
  3310. heightG = 222
  3311. break;
  3312. }
  3313. return heightG
  3314. }
  3315. getGridHeight() {
  3316. let heightG = 150
  3317. switch (this.twoFingerType) {
  3318. case 1:
  3319. heightG = 55
  3320. break;
  3321. case 2:
  3322. heightG = 100
  3323. break;
  3324. case 3:
  3325. heightG = 150
  3326. break;
  3327. }
  3328. return heightG
  3329. }
  3330. getGridWight() {
  3331. let wightG = 158
  3332. switch (this.twoFingerType) {
  3333. case 1:
  3334. wightG = 80
  3335. break;
  3336. case 2:
  3337. wightG = 110
  3338. break;
  3339. case 3:
  3340. wightG = 158
  3341. break;
  3342. }
  3343. return wightG
  3344. }
  3345. @State isShowDetail:boolean = false
  3346. @Builder
  3347. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3348. Scroll() {
  3349. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3350. Menu() {
  3351. MenuItem({
  3352. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3353. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3354. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3355. })
  3356. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3357. .onClick(() => {
  3358. if (item) {
  3359. this.doFav(item)
  3360. }
  3361. this.longItemFilePath = ''
  3362. })
  3363. MenuItem({
  3364. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3365. content: '下一首播放'
  3366. })
  3367. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3368. .onClick(() => {
  3369. this.addToNextPlay(item);
  3370. this.longItemFilePath = ''
  3371. })
  3372. MenuItem({
  3373. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3374. content: '编辑信息'
  3375. })
  3376. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3377. height: this.isCoverOpacity() ? '95%' : '88%',
  3378. dragBar: true,
  3379. showClose: true,
  3380. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3381. title: { title: '编辑信息' }
  3382. })
  3383. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3384. .onClick(() => {
  3385. this.isShowEdit = !this.isShowEdit;
  3386. })
  3387. MenuItem({
  3388. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3389. content: $r('app.string.rename')
  3390. })
  3391. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3392. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3393. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3394. .onClick(() => {
  3395. this.showReNameDialog(item, index + '', filePath)
  3396. this.longItemFilePath = ''
  3397. })
  3398. MenuItem({
  3399. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3400. content: $r('app.string.delete')
  3401. })
  3402. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3403. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3404. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3405. .onClick(() => {
  3406. this.showWarnIsDeleteFile(item, index + '', filePath)
  3407. this.longItemFilePath = ''
  3408. })
  3409. MenuItem({
  3410. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3411. content: $r('app.string.detail')
  3412. })
  3413. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3414. height:this.isCoverOpacity()?'95%': '95%',
  3415. dragBar: true,
  3416. showClose: true,
  3417. blurStyle:BlurStyle.Thin,
  3418. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3419. backgroundColor:Color.Transparent,
  3420. title: { title: '详情信息' }
  3421. })
  3422. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3423. .onClick(() => {
  3424. this.isShowDetail = !this.isShowDetail
  3425. })
  3426. MenuItem({
  3427. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3428. content: $r('app.string.share')
  3429. })
  3430. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3431. .onClick(() => {
  3432. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3433. this.longItemFilePath = ''
  3434. })
  3435. }
  3436. .font({ size: 15, weight: FontWeight.Normal })
  3437. }
  3438. .width(180)
  3439. }
  3440. .height(item.type === CommonConstants.TYPE_IS_DIR ? 150 : 400)
  3441. }
  3442. private listMaxScrollOffsetY: number = 0
  3443. @State selectedIndex: number = -1
  3444. setlistTwoFingers() {
  3445. this.pinchValue = this.scaleValue;
  3446. Logger.info('this.pinchValue = ' + this.pinchValue);
  3447. if (this.pinchValue >= 1) {
  3448. this.twoFingerType++
  3449. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3450. if (this.twoFingerType > 3) {
  3451. this.twoFingerType = 1
  3452. this.isGridMusic = true
  3453. }
  3454. } else {
  3455. this.twoFingerType--
  3456. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3457. if (this.twoFingerType < 1) {
  3458. this.twoFingerType = 1
  3459. }
  3460. }
  3461. this.pinchValue = 1;
  3462. this.scaleValue = 1;
  3463. }
  3464. @Builder
  3465. getListView() {
  3466. List({ scroller: this.listScroller }) {
  3467. ListItemGroup({ header: this.coverHeader() }) {
  3468. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3469. ListItem() {
  3470. Column() {
  3471. if (item.type === CommonConstants.TYPE_IS_DIR
  3472. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3473. this.DirItem(item, index)
  3474. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3475. } else {
  3476. this.MusicItem(item, index)
  3477. }
  3478. }
  3479. .shadow(this.scaleItem === index ? {
  3480. radius: 70,
  3481. color: '#15000000',
  3482. offsetX: 0,
  3483. offsetY: 0
  3484. } :
  3485. {
  3486. radius: 0,
  3487. color: '#15000000',
  3488. offsetX: 0,
  3489. offsetY: 0
  3490. })
  3491. .animation({ curve: Curve.Sharp, duration: 300 })
  3492. }
  3493. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3494. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3495. .animation({ duration: 500 }),
  3496. TransitionEffect.scale({ x: 0, y: 0 })))
  3497. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3498. .swipeAction((
  3499. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3500. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3501. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3502. .onClick(() => {
  3503. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3504. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3505. this.handleFileSelection(item, !isChecked);
  3506. } else {
  3507. this.doPlay(item, index)
  3508. }
  3509. })
  3510. //拖动List关键代码开始
  3511. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3512. .zIndex(this.dragItem === index ? 1 : 0)
  3513. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3514. .gesture(
  3515. GestureGroup(GestureMode.Sequence,
  3516. LongPressGesture({ repeat: true })
  3517. .onAction((event?: GestureEvent) => {
  3518. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3519. this.scaleItem = index
  3520. })
  3521. })
  3522. .onActionEnd(() => {
  3523. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3524. this.scaleItem = -1
  3525. })
  3526. }),
  3527. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3528. .onActionStart(() => {
  3529. this.dragItem = index // 记录当前拖动项索引
  3530. this.dragRefOffset = 0 // 重置偏移基准
  3531. })
  3532. .onActionUpdate((event: GestureEvent) => {
  3533. this.offsetY = event.offsetY - this.dragRefOffset;
  3534. this.neighborItem = -1;
  3535. let indexA = this.videoLocalList.indexOf(item);
  3536. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3537. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3538. let value: number = 0;
  3539. if (this.offsetY < 0) {
  3540. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3541. this.neighborItem = indexA - 1;
  3542. this.neighborScale = 1 - value / 20;
  3543. } else if (this.offsetY > 0) {
  3544. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3545. this.neighborItem = indexA + 1;
  3546. this.neighborScale = 1 - value / 20;
  3547. }
  3548. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3549. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3550. this.offsetY -= this.ITEM_INTV;
  3551. this.dragRefOffset += this.ITEM_INTV;
  3552. this.itemMove(indexA, indexA + 1);
  3553. });
  3554. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3555. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3556. this.offsetY += this.ITEM_INTV;
  3557. this.dragRefOffset -= this.ITEM_INTV;
  3558. this.itemMove(indexA, indexA - 1);
  3559. });
  3560. }
  3561. let curListOffset = this.listScroller.currentOffset()
  3562. // 获取手指信息
  3563. let fingerInfo = event.fingerList[0]
  3564. let clickPercentY =
  3565. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3566. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3567. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3568. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3569. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  3570. }
  3571. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3572. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3573. if (curListOffset.yOffset > scrollVelocity + 5) {
  3574. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  3575. }
  3576. }
  3577. })
  3578. .onActionEnd((event: GestureEvent) => {
  3579. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3580. this.dragItem = -1
  3581. this.neighborItem = -1
  3582. })
  3583. animateTo({
  3584. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3585. }, () => {
  3586. this.scaleItem = -1
  3587. })
  3588. })
  3589. )
  3590. .onCancel(() => {
  3591. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3592. this.dragItem = -1
  3593. this.neighborItem = -1
  3594. })
  3595. animateTo({
  3596. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3597. }, () => {
  3598. this.scaleItem = -1
  3599. })
  3600. })
  3601. ) //拖动List关键代码结束
  3602. }, (item: VideoItem) => item.filePath)
  3603. }
  3604. }
  3605. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3606. .gesture(PinchGesture({ fingers: 2 })
  3607. .onActionEnd((event: GestureEvent) => {
  3608. this.setlistTwoFingers()
  3609. })
  3610. .onActionUpdate(e => {
  3611. this.scaleValue = this.pinchValue * e.scale
  3612. })
  3613. .onActionStart(e => {
  3614. }))
  3615. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3616. .margin({
  3617. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? 25 : 80)
  3618. : (this.isShowCoverHeader() ? 85 : this.isHiCarSmall()?140:175)
  3619. })
  3620. .cachedCount(6)
  3621. .borderRadius(20)
  3622. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3623. TransitionEffect.scale({ x: 0, y: 0 })))
  3624. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3625. // .animation({ duration: 500, curve: Curve.Ease }))
  3626. .layoutWeight(1)
  3627. .onScrollIndex((start) => {
  3628. this.selectedIndex = start
  3629. })
  3630. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  3631. .lanes(
  3632. new BreakpointType<number>({
  3633. sm: 1,
  3634. md: 2,
  3635. lg: 2,
  3636. xl: 3,
  3637. xxl: 4
  3638. }).getValue(this.currentBreakpoint),
  3639. new BreakpointType<number>({
  3640. sm: 0,
  3641. md: 12,
  3642. lg: 12,
  3643. xl: 16,
  3644. xxl: 20
  3645. }).getValue(this.currentBreakpoint)
  3646. )
  3647. .onAreaChange((oldValue: Area, newValue: Area) => {
  3648. this.listArea = newValue
  3649. if (this.twoFingerType == 3) {
  3650. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3651. } else if (this.twoFingerType == 2) {
  3652. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3653. } else if (this.twoFingerType == 1) {
  3654. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3655. }
  3656. })
  3657. .onScrollFrameBegin((offset: number) => {
  3658. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3659. // if (this.isPhoneLan()) {
  3660. // this.setBarHeightHide(offset)
  3661. // } else
  3662. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3663. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3664. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3665. if (this.isScrollHide) {
  3666. this.setBarHeightHide2(offset)
  3667. } else {
  3668. this.setBarHeightNormal()
  3669. }
  3670. } else {
  3671. this.setBarHeightHide(offset)
  3672. }
  3673. return { offsetRemain: offset };
  3674. })
  3675. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3676. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3677. .onDrop((event?: DragEvent) => {
  3678. try {
  3679. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3680. if (dragData !== undefined) {
  3681. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3682. if (records.length > 0) {
  3683. for (let i = 0; i < records.length; i++) {
  3684. let types = records[i].getTypes();
  3685. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3686. const fileUriUds =
  3687. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3688. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3689. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3690. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3691. this.targetFile = fileUriUds.oriUri;
  3692. this.saveVideoDatas([this.targetFile])
  3693. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3694. }
  3695. }
  3696. }
  3697. } else {
  3698. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3699. }
  3700. } else {
  3701. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3702. }
  3703. } catch (error) {
  3704. const err = error as BusinessError;
  3705. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3706. }
  3707. })
  3708. }
  3709. setBarHeightNormal() {
  3710. this.hideDone = false;
  3711. this.getUIContext().animateTo({
  3712. duration: 300
  3713. }, () => {
  3714. this.bottomBarHeight = 55 + 0;
  3715. this.topBarHeight = 50 + 0;
  3716. this.barOpacity = 1;
  3717. this.barBottomOpacity = 1
  3718. this.currentYOffset = 0;
  3719. this.isHiding = false;
  3720. });
  3721. }
  3722. setBarHeightHide(offset: number) {
  3723. if (offset > 0 && !this.hideDone) {
  3724. this.currentYOffset += offset;
  3725. if (this.currentYOffset <= 100) {
  3726. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3727. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3728. this.barOpacity = 1 - this.currentYOffset / 100;
  3729. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3730. } else {
  3731. this.topBarHeight = 0;
  3732. this.bottomBarHeight = 0;
  3733. this.barBottomOpacity = 0
  3734. this.barOpacity = 0;
  3735. this.hideDone = true;
  3736. }
  3737. this.isHiding = true;
  3738. }
  3739. if (offset < 0 && this.isHiding) {
  3740. this.hideDone = false;
  3741. this.getUIContext().animateTo({
  3742. duration: 300
  3743. }, () => {
  3744. this.bottomBarHeight = 55 + 0;
  3745. this.topBarHeight = 50 + 0;
  3746. this.barOpacity = 1;
  3747. this.barBottomOpacity = 1
  3748. this.currentYOffset = 0;
  3749. this.isHiding = false;
  3750. });
  3751. }
  3752. }
  3753. //这个方法没隐藏bottomBar,只隐藏topbar
  3754. setBarHeightHide2(offset: number) {
  3755. if (offset > 0 && !this.hideDone) {
  3756. this.currentYOffset += offset;
  3757. if (this.currentYOffset <= 100) {
  3758. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3759. this.barOpacity = 1 - this.currentYOffset / 100;
  3760. } else {
  3761. this.topBarHeight = 0;
  3762. this.barOpacity = 0;
  3763. this.hideDone = true;
  3764. }
  3765. this.isHiding = true;
  3766. }
  3767. if (offset < 0 && this.isHiding) {
  3768. this.hideDone = false;
  3769. this.getUIContext().animateTo({
  3770. duration: 300
  3771. }, () => {
  3772. this.topBarHeight = 50 + 0;
  3773. this.barOpacity = 1;
  3774. this.currentYOffset = 0;
  3775. this.isHiding = false;
  3776. });
  3777. }
  3778. }
  3779. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3780. switch (item.type) {
  3781. case CommonConstants.TYPE_IS_DIR:
  3782. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  3783. let offsetB = 0
  3784. if (this.isGridMusic) {
  3785. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3786. let cur = this.scroller.currentOffset()
  3787. if (cur && typeof cur.yOffset === 'number') {
  3788. offsetB = cur.yOffset
  3789. }
  3790. }
  3791. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  3792. } else {
  3793. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3794. let cur = this.listScroller.currentOffset()
  3795. if (cur && typeof cur.yOffset === 'number') {
  3796. offsetB = cur.yOffset
  3797. }
  3798. }
  3799. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  3800. }
  3801. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3802. this.showVerifyDialog()
  3803. this.currentTitleName = '私密音频'
  3804. this.currentTitleCover = $r('app.media.ic_avatar5')
  3805. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3806. this.titleBarModel.setTitleName('最近播放')
  3807. this.currentTitleCover = $r('app.media.ic_avatar2')
  3808. this.currentTitleName = '最近播放'
  3809. //加载动画效果
  3810. this.updateListData(this.historyList, true)
  3811. // this.videoLocalList = this.historyList
  3812. if (ArrayUtil.isEmpty(this.historyList)) {
  3813. ToastUtil.showToast('最近播放记录空空如也')
  3814. } else {
  3815. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  3816. }
  3817. this.isHistory = true
  3818. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3819. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  3820. this.titleBarModel.setTitleName('我的收藏')
  3821. this.currentTitleName = '我的收藏'
  3822. this.currentTitleCover = $r('app.media.ic_avatar1')
  3823. //加载动画效果
  3824. this.updateListData(this.favList)
  3825. if (ArrayUtil.isEmpty(this.favList)) {
  3826. ToastUtil.showToast('无音乐收藏记录')
  3827. } else {
  3828. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  3829. }
  3830. this.isFavMusic = true
  3831. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3832. } else {
  3833. this.currentTitleName = item.name
  3834. this.currentPath = item.filePath
  3835. this.currentTitleCover = $r('app.media.ic_avatar5')
  3836. this.getSortedFiles(this.currentPath)
  3837. }
  3838. //进入歌单的时候的滚动位置在顶部
  3839. if (this.isGridMusic) {
  3840. this.scroller.scrollToIndex(0)
  3841. }
  3842. setTimeout(() => {
  3843. if (this.modeType == 0) {
  3844. if (!this.isGridMusic) {
  3845. this.listScroller.scrollToIndex(0)
  3846. }
  3847. }
  3848. }, 200)
  3849. break;
  3850. case CommonConstants.TYPE_IS_ARTIST:
  3851. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3852. let offsetA = 0
  3853. if (this.isGridMusic) {
  3854. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3855. let cur = this.scroller.currentOffset()
  3856. if (cur && typeof cur.yOffset === 'number') {
  3857. offsetA = cur.yOffset
  3858. }
  3859. }
  3860. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3861. } else {
  3862. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3863. let cur = this.listScroller.currentOffset()
  3864. if (cur && typeof cur.yOffset === 'number') {
  3865. offsetA = cur.yOffset
  3866. }
  3867. }
  3868. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3869. }
  3870. let mList = this.artistMap.get(item.name)
  3871. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3872. Utility.doSortListAscending(mList)
  3873. this.isCanBack = true
  3874. this.titleBarModel.setTitleName(item.name)
  3875. this.currentTitleName = '艺术家:' + item.name
  3876. if (item.pixelMapPath) {
  3877. this.currentTitleCover = item.pixelMapPath
  3878. }
  3879. this.updateListData(mList)
  3880. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3881. }
  3882. break;
  3883. case CommonConstants.TYPE_IS_ALBUM:
  3884. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3885. let offset = 0
  3886. if (this.isGridMusic) {
  3887. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3888. let cur = this.scroller.currentOffset()
  3889. if (cur && typeof cur.yOffset === 'number') {
  3890. offset = cur.yOffset
  3891. }
  3892. }
  3893. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3894. } else {
  3895. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3896. let cur = this.listScroller.currentOffset()
  3897. if (cur && typeof cur.yOffset === 'number') {
  3898. offset = cur.yOffset
  3899. }
  3900. }
  3901. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  3902. }
  3903. let albumList = this.albumMap.get(item.name)
  3904. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  3905. Utility.doSortListAscending(albumList)
  3906. this.isCanBack = true
  3907. this.titleBarModel.setTitleName(item.name)
  3908. this.currentTitleName = '专辑:' + item.name
  3909. this.currentYear = '发行时间:' + albumList[0].year
  3910. if (item.pixelMapPath) {
  3911. this.currentTitleCover = item.pixelMapPath
  3912. }
  3913. this.updateListData(albumList)
  3914. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3915. this.mScrollMap.set(item.name, this.selectedIndex)
  3916. }
  3917. break;
  3918. case CommonConstants.TYPE_IS_CSJAD:
  3919. return
  3920. break;
  3921. case CommonConstants.TYPE_LOCAL:
  3922. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  3923. this.stop();
  3924. }
  3925. if (isFromSonPlayList) { //点击来自右下角的播放列表
  3926. this.currentSong = item
  3927. if (index !== undefined) {
  3928. this.curIndex = index
  3929. }
  3930. } else {
  3931. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  3932. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  3933. this.songList = globalVideoList
  3934. this.sonDataSource.pushArrayData(this.songList)
  3935. this.currentSong = globalVideoList[this.curIndex]
  3936. }
  3937. this.videoUrl = this.currentSong.filePath
  3938. this.name = this.currentSong.name
  3939. this.cover = this.currentSong.pixelMapPath
  3940. this.artist = this.currentSong.artist
  3941. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  3942. LogUtil.info('this.currentSong.sampleRate =' + this.currentSong.sampleRate)
  3943. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  3944. this.startPlayOrResumePlay()
  3945. break;
  3946. }
  3947. }
  3948. @Builder
  3949. PlayController() {
  3950. Column() {
  3951. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  3952. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  3953. Row() {
  3954. Row() {
  3955. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  3956. Column() {
  3957. Text(this.currentSong?.name)
  3958. .fontSize(16)
  3959. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3960. .maxLines(1)
  3961. .fontColor($r('app.color.text_color'))
  3962. .fontWeight(500)
  3963. Row() {
  3964. Text(this.currentSong?.artist)
  3965. .margin({ top: 2 })
  3966. .fontSize(13)
  3967. .fontColor($r('app.color.text_color'))
  3968. }
  3969. }
  3970. .alignItems(HorizontalAlign.Start)
  3971. .margin({ right: 22 })
  3972. }
  3973. .padding({ right: 18 })
  3974. .layoutWeight(1)
  3975. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3976. .onClick(() => {
  3977. if (ArrayUtil.isNotEmpty(this.songList)) {
  3978. this.isShowPlay = true;
  3979. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  3980. this.initLyric(lyricPath);
  3981. this.startAutoHide()
  3982. } else {
  3983. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3984. }
  3985. })
  3986. Row() {
  3987. Image($r('app.media.hm_previous'))
  3988. .height(28)
  3989. .width(28)
  3990. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3991. .margin({ left: 8, right: 16 })
  3992. .fillColor(this.themeColor)
  3993. .displayPriority(2)
  3994. .onClick(() => {
  3995. if (ArrayUtil.isNotEmpty(this.songList)) {
  3996. this.playPrevious()
  3997. } else {
  3998. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  3999. }
  4000. })
  4001. //播放进度条
  4002. Stack() {
  4003. Progress({
  4004. value: Math.floor(this.progressValue),
  4005. type: ProgressType.Ring,
  4006. })
  4007. .color(this.themeColor)// 进度条前景色为灰色
  4008. .backgroundColor($r('app.color.index_background'))
  4009. .height(40)
  4010. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4011. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4012. .height(38)
  4013. .width(38)
  4014. .displayPriority(3)
  4015. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4016. .fillColor(this.themeColor)
  4017. .onClick(() => {
  4018. if (ArrayUtil.isNotEmpty(this.songList)) {
  4019. this.playOrPause()
  4020. } else {
  4021. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4022. }
  4023. })
  4024. }
  4025. Image($r('app.media.hm_next'))
  4026. .height(28)
  4027. .width(28)
  4028. .margin({
  4029. right: 16,
  4030. left: 16
  4031. })
  4032. .fillColor(this.themeColor)
  4033. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4034. .displayPriority(2)
  4035. .onClick(() => {
  4036. if (ArrayUtil.isNotEmpty(this.songList)) {
  4037. this.playNext()
  4038. } else {
  4039. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4040. }
  4041. })
  4042. Image($r('app.media.hm_playlist'))
  4043. .height(28)
  4044. .width(28)
  4045. .displayPriority(1)
  4046. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4047. .fillColor(this.themeColor)
  4048. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4049. height: '95%',
  4050. dragBar: true,
  4051. showClose: true,
  4052. blurStyle: BlurStyle.Thin,
  4053. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4054. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4055. title: {
  4056. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4057. + `(${this.songList.length}首)`
  4058. }
  4059. })
  4060. .onClick(() => {
  4061. if (ArrayUtil.isNotEmpty(this.songList)) {
  4062. this.isShowSheet = !this.isShowSheet;
  4063. this.isFrontWhite = false
  4064. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4065. setTimeout(() => {
  4066. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  4067. }, 123)
  4068. } else {
  4069. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4070. }
  4071. })
  4072. }
  4073. }
  4074. .width('100%')
  4075. .height(this.bottomBarHeight)
  4076. .justifyContent(FlexAlign.Center)
  4077. .hitTestBehavior(HitTestMode.Transparent)
  4078. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4079. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4080. // modalTransition: ModalTransition.DEFAULT,
  4081. transition: AnimationHelper.transitionInDown(666),
  4082. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4083. })
  4084. .padding({
  4085. left: 16,
  4086. right: 16
  4087. })
  4088. Line()
  4089. .width('100%')
  4090. .height(25)
  4091. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4092. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4093. }
  4094. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4095. }
  4096. @State isFrontWhite: boolean = false
  4097. //播放列表布局
  4098. @Builder
  4099. PlayListSheet() {
  4100. Column() {
  4101. this.PlayList()
  4102. }
  4103. .width('100%')
  4104. .height('100%')
  4105. }
  4106. @State titleStr: string = ''
  4107. @State ablumStr: string = ''
  4108. @State artistStr: string = ''
  4109. @State lyricConStr: string = ''
  4110. @State currentEditItem: string = ''
  4111. doUpdateData() {
  4112. setTimeout(() => {
  4113. if (this.modeType === 0) {
  4114. this.deleteCache(this.currentPath)
  4115. this.getSortedFiles(this.currentPath)
  4116. }
  4117. workerInstance.postMessage({ code: 2, data: this.context });
  4118. workerInstance.postMessage({ code: 3, data: this.context });
  4119. workerInstance.postMessage({ code: 4, data: this.context });
  4120. }, 999)
  4121. }
  4122. //编辑信息
  4123. doEdit(item: VideoItem) {
  4124. if (!item) {
  4125. return
  4126. }
  4127. if (StrUtil.isEmpty(this.titleStr)) {
  4128. ToastUtil.showToast('标题不能为空')
  4129. return
  4130. }
  4131. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  4132. (success: boolean, error?: string) => {
  4133. this.isShowEdit = false
  4134. if (success) {
  4135. console.log(" onecold 编辑信息成功,数据库已同步");
  4136. ToastUtil.showToast('保存成功')
  4137. this.isShowMoreView = false
  4138. this.name = this.titleStr
  4139. if (item.filePath == this.currentSong?.filePath) {
  4140. this.currentSong.name = this.titleStr
  4141. this.artist = this.artistStr
  4142. this.currentSong.artist = this.artistStr
  4143. this.currentSong.album = this.ablumStr
  4144. }
  4145. this.doUpdateData()
  4146. } else {
  4147. ToastUtil.showToast('保存失败' + error?.toString())
  4148. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4149. }
  4150. });
  4151. let doChangeLyric = false
  4152. if (item.filePath == this.currentSong?.filePath) {
  4153. if (this.lyricConStr !== this.lyricContent) {
  4154. doChangeLyric = true
  4155. }
  4156. } else if (this.lyricConStr !== this.tempLyricContent) {
  4157. doChangeLyric = true
  4158. }
  4159. if (doChangeLyric) {
  4160. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4161. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4162. let isJiaMi = false;
  4163. let realLyricPath = lyricPath
  4164. if (FileUtil.accessSync(jiaMilyricPath)) {
  4165. isJiaMi = true
  4166. realLyricPath = jiaMilyricPath
  4167. console.info("onecold doEdit找到加密本地歌词 ");
  4168. } else {
  4169. isJiaMi = false
  4170. realLyricPath = lyricPath
  4171. console.info("onecold doEdit本地歌词 ");
  4172. }
  4173. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  4174. }
  4175. }
  4176. updateLyricToDB() {
  4177. }
  4178. @Builder
  4179. editSheet(item: VideoItem) {
  4180. Scroll() {
  4181. Column() {
  4182. this.editDetail(item)
  4183. }
  4184. }
  4185. .width('100%')
  4186. .height('100%')
  4187. }
  4188. @Builder
  4189. editDetail(item: VideoItem) {
  4190. Column() {
  4191. if (item) {
  4192. Row() {
  4193. Stack() {
  4194. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4195. item.pixelMapPath)
  4196. .fillColor(this.themeColor)
  4197. .height(33)
  4198. .width(33)
  4199. .borderRadius('100%')
  4200. .clip(true)
  4201. .opacity(this.opacityItem)// 绑定透明度
  4202. .margin({ left: 20 })
  4203. }
  4204. .width('15%')
  4205. Row() {
  4206. Column() {
  4207. Text(item.name)
  4208. .fontSize(14)
  4209. .maxLines(1)
  4210. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4211. .animation({
  4212. duration: 555,
  4213. curve: 'Linear',
  4214. })
  4215. .fontColor(this.themeColor)
  4216. .margin({ left: 10 })
  4217. Row() {
  4218. Text(item.artist)
  4219. .fontSize(11)
  4220. .maxLines(1)
  4221. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4222. .padding({ top: 8 })
  4223. .fontColor(this.themeColor)
  4224. .margin({ left: 10 })
  4225. }
  4226. }
  4227. .height('100%')
  4228. .width(100)
  4229. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4230. .justifyContent(FlexAlign.Center)
  4231. .alignItems(HorizontalAlign.Start)
  4232. Button('本地封面')
  4233. .fontColor(Color.White)
  4234. .fontSize(12)
  4235. .height(38)
  4236. .width(88)
  4237. .backgroundColor(this.themeColor)
  4238. .stateEffect(true)
  4239. .margin({ right: 5, left: 12 })
  4240. .onClick(async () => {
  4241. this.goSelectImage(item)
  4242. })
  4243. Button('获取封面')
  4244. .fontColor(Color.White)
  4245. .fontSize(12)
  4246. .height(38)
  4247. .width(88)
  4248. .backgroundColor(this.themeColor)
  4249. .stateEffect(true)
  4250. .margin({ right: 12, left: 5 })
  4251. .onClick(async () => {
  4252. this.doSearchCover(item)
  4253. })
  4254. }
  4255. .height('100%')
  4256. .justifyContent(FlexAlign.Start)
  4257. .layoutWeight(1)
  4258. }
  4259. .width('100%')
  4260. .height(58)
  4261. Row() {
  4262. Text('标题:')
  4263. .fontSize(14)
  4264. .fontColor($r('app.color.text_color'))
  4265. .margin({ left: 22 })
  4266. TextInput({ text: item.name })
  4267. .height(40)
  4268. .maxLines(1)
  4269. .fontSize(14)
  4270. .layoutWeight(1)
  4271. .fontColor($r('app.color.text_color'))
  4272. .margin({ right: 20, left: 10 })
  4273. .onChange((val: string) => {
  4274. this.titleStr = val
  4275. })
  4276. }
  4277. .width('100%')
  4278. .margin({ top: 10, bottom: 10 })
  4279. .justifyContent(FlexAlign.Start)
  4280. Row() {
  4281. Text('艺术家:')
  4282. .fontSize(14)
  4283. .fontColor($r('app.color.text_color'))
  4284. .margin({ left: 22 })
  4285. TextInput({ text: item.artist })
  4286. .height(40)
  4287. .maxLines(1)
  4288. .fontSize(14)
  4289. .layoutWeight(1)
  4290. .fontColor($r('app.color.text_color'))
  4291. .margin({ right: 20, left: 10 })
  4292. .onChange((val: string) => {
  4293. this.artistStr = val
  4294. })
  4295. }
  4296. .width('100%')
  4297. .margin({ top: 10, bottom: 10 })
  4298. .justifyContent(FlexAlign.Start)
  4299. Row() {
  4300. Text('专辑名:')
  4301. .fontSize(14)
  4302. .fontColor($r('app.color.text_color'))
  4303. .margin({ left: 22 })
  4304. TextInput({ text: item.album })
  4305. .height(40)
  4306. .maxLines(1)
  4307. .fontSize(14)
  4308. .layoutWeight(1)
  4309. .fontColor($r('app.color.text_color'))
  4310. .margin({ right: 20, left: 10 })
  4311. .onChange((val: string) => {
  4312. this.ablumStr = val
  4313. })
  4314. }
  4315. .width('100%')
  4316. .margin({ top: 10, bottom: 10 })
  4317. .justifyContent(FlexAlign.Start)
  4318. Row() {
  4319. Text('歌词:')
  4320. .fontSize(14)
  4321. .fontColor($r('app.color.text_color'))
  4322. .margin({ left: 22 })
  4323. TextArea({ text: item.filePath === this.currentSong?.filePath ? this.lyricContent : this.tempLyricContent })
  4324. .type(TextAreaType.NORMAL)
  4325. .height(275)
  4326. .fontSize(14)
  4327. .layoutWeight(1)
  4328. .fontColor($r('app.color.text_color'))
  4329. .margin({ right: 20, left: 10 })
  4330. .onChange((val: string) => {
  4331. this.lyricConStr = val
  4332. })
  4333. }
  4334. .width('100%')
  4335. .margin({ top: 10, bottom: 10 })
  4336. .justifyContent(FlexAlign.Start)
  4337. Row() {
  4338. Button('保存')
  4339. .fontColor(Color.White)
  4340. .layoutWeight(1)
  4341. .height(50)
  4342. .width(100)
  4343. .backgroundColor(this.themeColor)
  4344. .stateEffect(true)
  4345. .margin({ right: 20, bottom: 20 })
  4346. .onClick(async () => {
  4347. this.doEdit(item)
  4348. })
  4349. Button('取消')
  4350. .fontColor(Color.White)
  4351. .layoutWeight(1)
  4352. .height(50)
  4353. .width(100)
  4354. .backgroundColor(this.themeColor)
  4355. .stateEffect(true)
  4356. .margin({ left: 20, bottom: 20 })
  4357. .onClick(async () => {
  4358. this.isShowEdit = false
  4359. })
  4360. }
  4361. .margin({
  4362. left: 38,
  4363. right: 38,
  4364. top: 10,
  4365. bottom: 10
  4366. })
  4367. .width(250)
  4368. .height(60)
  4369. }
  4370. }
  4371. .margin({ bottom: 20 })
  4372. }
  4373. @Builder
  4374. detailSheet(item:VideoItem) {
  4375. Scroll() {
  4376. Column() {
  4377. this.songDetail(item)
  4378. }
  4379. }
  4380. .width('100%')
  4381. .height('100%')
  4382. }
  4383. @Builder
  4384. songDetail(currentItem:VideoItem) {
  4385. Column() {
  4386. if (currentItem) {
  4387. Row() {
  4388. Stack() {
  4389. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4390. currentItem.pixelMapPath)
  4391. .fillColor(this.themeColor)
  4392. .height(33)
  4393. .width(33)
  4394. .borderRadius('100%')
  4395. .clip(true)
  4396. .opacity(this.opacityItem)// 绑定透明度
  4397. .margin({ left: 20 })
  4398. }
  4399. .width('15%')
  4400. Column() {
  4401. Column() {
  4402. Text(currentItem.name)
  4403. .fontSize(14)
  4404. .maxLines(1)
  4405. .animation({
  4406. duration: 555,
  4407. curve: 'Linear',
  4408. })
  4409. .fontColor($r('app.color.text_color'))
  4410. .margin({ left: 10 })
  4411. Row() {
  4412. Text(StrUtil.isEmpty(currentItem.artist) ? currentItem.cTime :
  4413. currentItem.artist + ' ' + currentItem?.album)
  4414. .fontSize(11)
  4415. .padding({ top: 8 })
  4416. .fontColor($r('app.color.text_color'))
  4417. .margin({ left: 10 })
  4418. }
  4419. }
  4420. .height('100%')
  4421. .width('100%')
  4422. .justifyContent(FlexAlign.Center)
  4423. .alignItems(HorizontalAlign.Start)
  4424. }
  4425. .height('100%')
  4426. }
  4427. .width('100%')
  4428. .height(58)
  4429. .justifyContent(FlexAlign.SpaceBetween)
  4430. Row() {
  4431. Text('歌手名:')
  4432. .fontSize(14)
  4433. .fontColor(Color.White)
  4434. .margin({ left: 22 })
  4435. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4436. .fontSize(14)
  4437. .fontColor(Color.White)
  4438. .margin({ left: 10 })
  4439. .layoutWeight(1)
  4440. }
  4441. .width('100%')
  4442. .margin({ top: 10, bottom: 10 })
  4443. .justifyContent(FlexAlign.Start)
  4444. Row() {
  4445. Text('专辑名:')
  4446. .fontSize(14)
  4447. .fontColor(Color.White)
  4448. .margin({ left: 22 })
  4449. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4450. .fontSize(14)
  4451. .margin({ left: 10 })
  4452. .fontColor(Color.White)
  4453. .layoutWeight(1)
  4454. }
  4455. .width('100%')
  4456. .margin({ top: 10, bottom: 10 })
  4457. .justifyContent(FlexAlign.Start)
  4458. Row() {
  4459. Text('时长:')
  4460. .fontSize(14)
  4461. .fontColor(Color.White)
  4462. .margin({ left: 22 })
  4463. Text(StrUtil.isEmpty(currentItem.duration)?
  4464. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4465. .fontSize(14)
  4466. .margin({ left: 10 })
  4467. .fontColor(Color.White)
  4468. .layoutWeight(1)
  4469. }
  4470. .width('100%')
  4471. .margin({ top: 10, bottom: 10 })
  4472. .justifyContent(FlexAlign.Start)
  4473. Row() {
  4474. Text('采样率:')
  4475. .fontSize(14)
  4476. .fontColor(Color.White)
  4477. .margin({ left: 22 })
  4478. Text(Utility.convertToKHz(currentItem.sampleRate))
  4479. .fontSize(14)
  4480. .margin({ left: 10 })
  4481. .fontColor(Color.White)
  4482. .layoutWeight(1)
  4483. }
  4484. .width('100%')
  4485. .margin({ top: 10, bottom: 10 })
  4486. .justifyContent(FlexAlign.Start)
  4487. Row() {
  4488. Text('比特率:')
  4489. .fontSize(14)
  4490. .fontColor(Color.White)
  4491. .margin({ left: 22 })
  4492. Text(currentItem.bit_rate)
  4493. .fontSize(14)
  4494. .margin({ left: 10 })
  4495. .fontColor(Color.White)
  4496. .layoutWeight(1)
  4497. }
  4498. .width('100%')
  4499. .margin({ top: 10, bottom: 10 })
  4500. .justifyContent(FlexAlign.Start)
  4501. Row() {
  4502. Text('风格:')
  4503. .fontSize(14)
  4504. .fontColor(Color.White)
  4505. .margin({ left: 22 })
  4506. Text(currentItem.genre)
  4507. .fontSize(14)
  4508. .margin({ left: 10 })
  4509. .fontColor(Color.White)
  4510. .layoutWeight(1)
  4511. }
  4512. .width('100%')
  4513. .margin({ top: 10, bottom: 10 })
  4514. .justifyContent(FlexAlign.Start)
  4515. Row() {
  4516. Text('发行时间:')
  4517. .fontSize(14)
  4518. .fontColor(Color.White)
  4519. .margin({ left: 22 })
  4520. Text(currentItem.year)
  4521. .fontSize(14)
  4522. .margin({ left: 10 })
  4523. .fontColor(Color.White)
  4524. .layoutWeight(1)
  4525. }
  4526. .width('100%')
  4527. .margin({ top: 10, bottom: 10 })
  4528. .justifyContent(FlexAlign.Start)
  4529. Row() {
  4530. Text('质量评分:')
  4531. .fontSize(14)
  4532. .fontColor(Color.White)
  4533. .margin({ left: 22 })
  4534. Text(currentItem.probe_score+"")
  4535. .fontSize(14)
  4536. .margin({ left: 10 })
  4537. .fontColor(Color.White)
  4538. .layoutWeight(1)
  4539. }
  4540. .width('100%')
  4541. .margin({ top: 10, bottom: 10 })
  4542. .justifyContent(FlexAlign.Start)
  4543. Row() {
  4544. Text('音轨号:')
  4545. .fontSize(14)
  4546. .fontColor(Color.White)
  4547. .margin({ left: 22 })
  4548. Text(currentItem.track)
  4549. .fontSize(14)
  4550. .margin({ left: 10 })
  4551. .fontColor(Color.White)
  4552. .layoutWeight(1)
  4553. }
  4554. .width('100%')
  4555. .margin({ top: 10, bottom: 10 })
  4556. .justifyContent(FlexAlign.Start)
  4557. Row() {
  4558. Text('音轨数:')
  4559. .fontSize(14)
  4560. .fontColor(Color.White)
  4561. .margin({ left: 22 })
  4562. Text(StrUtil.isEmpty(currentItem.trackCount)?'1':currentItem.trackCount)
  4563. .fontSize(14)
  4564. .margin({ left: 10 })
  4565. .fontColor(Color.White)
  4566. .layoutWeight(1)
  4567. }
  4568. .width('100%')
  4569. .margin({ top: 10, bottom: 10 })
  4570. .justifyContent(FlexAlign.Start)
  4571. Row() {
  4572. Text('格式:')
  4573. .fontSize(14)
  4574. .fontColor(Color.White)
  4575. .margin({ left: 22 })
  4576. Text(Utility.formatMimeType(currentItem.mimeType))
  4577. .fontSize(14)
  4578. .margin({ left: 10 })
  4579. .fontColor(Color.White)
  4580. .layoutWeight(1)
  4581. }
  4582. .width('100%')
  4583. .margin({ top: 10, bottom: 10 })
  4584. .justifyContent(FlexAlign.Start)
  4585. Row() {
  4586. Text('播放次数:')
  4587. .fontSize(14)
  4588. .fontColor(Color.White)
  4589. .margin({ left: 22 })
  4590. Text(currentItem.playCount?.toString())
  4591. .fontSize(14)
  4592. .margin({ left: 10 })
  4593. .fontColor(Color.White)
  4594. .layoutWeight(1)
  4595. }
  4596. .width('100%')
  4597. .margin({ top: 10, bottom: 10 })
  4598. .justifyContent(FlexAlign.Start)
  4599. Row() {
  4600. Text('流数量:')
  4601. .fontSize(14)
  4602. .fontColor(Color.White)
  4603. .margin({ left: 22 })
  4604. Text(currentItem.nb_streams?.toString())
  4605. .fontSize(14)
  4606. .margin({ left: 10 })
  4607. .fontColor(Color.White)
  4608. .layoutWeight(1)
  4609. }
  4610. .width('100%')
  4611. .margin({ top: 10, bottom: 10 })
  4612. .justifyContent(FlexAlign.Start)
  4613. Row() {
  4614. Text('文件大小:')
  4615. .fontSize(14)
  4616. .fontColor(Color.White)
  4617. .margin({ left: 22 })
  4618. Text(currentItem.size)
  4619. .fontSize(14)
  4620. .margin({ left: 10 })
  4621. .fontColor(Color.White)
  4622. .layoutWeight(1)
  4623. }
  4624. .width('100%')
  4625. .margin({ top: 10, bottom: 10 })
  4626. .justifyContent(FlexAlign.Start)
  4627. Row() {
  4628. Text('文件名:')
  4629. .fontSize(14)
  4630. .fontColor(Color.White)
  4631. .margin({ left: 22 })
  4632. Text(currentItem.fileName)
  4633. .fontSize(14)
  4634. .margin({ left: 10 })
  4635. .fontColor(Color.White)
  4636. .layoutWeight(1)
  4637. }
  4638. .width('100%')
  4639. .margin({ top: 10, bottom: 10 })
  4640. .justifyContent(FlexAlign.Start)
  4641. Row() {
  4642. Text('修改时间:')
  4643. .fontSize(14)
  4644. .fontColor(Color.White)
  4645. .margin({ left: 22 })
  4646. Text(currentItem.cTime)
  4647. .fontSize(14)
  4648. .margin({ left: 10 })
  4649. .fontColor(Color.White)
  4650. .layoutWeight(1)
  4651. }
  4652. .width('100%')
  4653. .margin({ top: 10, bottom: 10 })
  4654. .justifyContent(FlexAlign.Start)
  4655. Row() {
  4656. Text('存放目录:')
  4657. .fontSize(14)
  4658. .fontColor(Color.White)
  4659. .margin({ left: 22 })
  4660. Text(currentItem.filePath)
  4661. .fontSize(12)
  4662. .margin({ left: 10 })
  4663. .fontColor(Color.White)
  4664. .layoutWeight(1)
  4665. }
  4666. .margin({ top: 10, bottom: 10 })
  4667. .width('100%')
  4668. .justifyContent(FlexAlign.Start)
  4669. }
  4670. }
  4671. .margin({ bottom: 20 })
  4672. }
  4673. //定时关闭布局
  4674. @Builder
  4675. TimeCloseSheet() {
  4676. Scroll() {
  4677. Column() {
  4678. this.TimeClose()
  4679. }
  4680. }
  4681. .width('100%')
  4682. .height('100%')
  4683. }
  4684. //倒计时关闭音乐,退出App功能实现。
  4685. @State selectedMinutes: number = 0 // 0表示未开启
  4686. @State remainingSeconds: number = 0
  4687. // 预设时间选项
  4688. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  4689. private formatTime(seconds: number): string {
  4690. const mins = Math.floor(seconds / 60)
  4691. const secs = seconds % 60
  4692. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  4693. }
  4694. // 开始倒计时
  4695. private handleTimeSelect(minutes: number) {
  4696. if (minutes === this.selectedMinutes) {
  4697. this.stopCountdown();
  4698. this.selectedMinutes = 0;
  4699. return;
  4700. }
  4701. this.selectedMinutes = minutes;
  4702. this.remainingSeconds = minutes * 60;
  4703. this.startCountdown(); // 新增调用
  4704. }
  4705. @Builder
  4706. TimeClose() {
  4707. Column() {
  4708. // 倒计时显示区域
  4709. Text(this.selectedMinutes > 0 ?
  4710. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  4711. "定时关闭未开启")
  4712. .fontSize(17)
  4713. .fontColor($r('app.color.text_color'))
  4714. .margin({ top: 2, bottom: 8 });
  4715. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  4716. ForEach(this.presetTimes, (minutes: number, index: number) => {
  4717. // 单行时间选项容器
  4718. Row() {
  4719. // 文字描述区域
  4720. Text(this.getDisplayText(minutes))
  4721. .fontSize(15)
  4722. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  4723. $r('app.color.text_color'))// 选中态颜色变化
  4724. .textAlign(TextAlign.Start)
  4725. .layoutWeight(1); // 占据剩余空间
  4726. // 复选框样式的选择器
  4727. Row() {
  4728. if (minutes === this.selectedMinutes) {
  4729. // 选中状态 - 带勾号的圆形复选框
  4730. Row() {
  4731. // 使用系统内置的勾号图标
  4732. Image($r('sys.media.ohos_ic_public_ok'))
  4733. .width(14)
  4734. .height(14)
  4735. .fillColor(Color.White)
  4736. }
  4737. .width(24)
  4738. .height(24)
  4739. .borderRadius(12)
  4740. .backgroundColor(this.themeColor)
  4741. .justifyContent(FlexAlign.Center)
  4742. .alignItems(VerticalAlign.Center)
  4743. } else {
  4744. // 未选中状态的圆形边框
  4745. Row()
  4746. .width(24)
  4747. .height(24)
  4748. .borderRadius(12)
  4749. .border({
  4750. width: 2,
  4751. color: $r('app.color.text_color'),
  4752. style: BorderStyle.Solid
  4753. })
  4754. .backgroundColor(Color.Transparent)
  4755. }
  4756. }
  4757. .width(24)
  4758. .height(24)
  4759. .margin({ left: 20 })
  4760. .justifyContent(FlexAlign.Center)
  4761. .alignItems(VerticalAlign.Center)
  4762. }
  4763. .width('100%')
  4764. .padding({
  4765. top: 18,
  4766. bottom: 18,
  4767. left: 18,
  4768. right: 18
  4769. })
  4770. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  4771. $r('app.color.bottom_control_background')) // 选中背景高亮
  4772. .borderRadius(12)
  4773. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4774. .margin({ bottom: 18 })
  4775. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  4776. });
  4777. }
  4778. .width('100%')
  4779. .padding(16)
  4780. }
  4781. }
  4782. // 获取显示文本
  4783. private getDisplayText(minutes: number): string {
  4784. if (minutes === -1) {
  4785. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  4786. }
  4787. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  4788. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  4789. }
  4790. // 处理选择事件
  4791. private handleSelect(minutes: number): void {
  4792. if (minutes === -1) { // 自定义
  4793. // 弹出自定义时间对话框
  4794. DialogHelper.showTextInputDialog({
  4795. title: '自定义时间',
  4796. maskColor: Color.Transparent,
  4797. inputType: InputType.Number,
  4798. text: '',
  4799. onChange: (text) => {
  4800. console.error("onChange: " + text);
  4801. },
  4802. onAction: (action, dialogId, content) => {
  4803. if (action == DialogAction.TWO) {
  4804. const customMinutes = Number(content);
  4805. if (customMinutes > 0) {
  4806. this.handleTimeSelect(customMinutes); // 设置自定义时间
  4807. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  4808. }
  4809. }
  4810. }
  4811. });
  4812. } else {
  4813. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  4814. }
  4815. }
  4816. // 添加定时器引用
  4817. private timerId: number = -1;
  4818. // 启动/重置倒计时
  4819. private startCountdown() {
  4820. // 清除旧定时器
  4821. if (this.timerId !== -1) {
  4822. clearInterval(this.timerId);
  4823. }
  4824. // 创建新定时器
  4825. if (this.selectedMinutes > 0) {
  4826. this.timerId = setInterval(() => {
  4827. if (this.remainingSeconds === 15) {
  4828. this.showConfirmationDialog();
  4829. }
  4830. if (this.remainingSeconds > 0) {
  4831. this.remainingSeconds -= 1;
  4832. } else {
  4833. this.stopCountdown();
  4834. this.handleTimeout();
  4835. }
  4836. }, 1000);
  4837. }
  4838. }
  4839. // 15倒计时后再次提示显示确认是否关闭App对话框
  4840. private showConfirmationDialog() {
  4841. DialogHelper.showAlertDialog({
  4842. backgroundColor: $r('app.color.btn_green'),
  4843. title: '确认关闭',
  4844. maskColor: Color.Transparent,
  4845. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  4846. borderStyle: BorderStyle.Dashed,
  4847. primaryButton: '暂不关闭',
  4848. secondaryButton: '确定',
  4849. onAction: (action) => {
  4850. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  4851. this.stopCountdown();
  4852. this.selectedMinutes = 0
  4853. } else if (action == DialogAction.TWO) {
  4854. }
  4855. }
  4856. })
  4857. }
  4858. // 停止倒计时
  4859. private stopCountdown() {
  4860. if (this.timerId !== -1) {
  4861. clearInterval(this.timerId);
  4862. this.timerId = -1;
  4863. }
  4864. }
  4865. // 超时处理
  4866. private handleTimeout() {
  4867. // 执行播放器关闭逻辑
  4868. this.selectedMinutes = 0;
  4869. ToastUtil.showToast(" 定时关闭已完成");
  4870. this.stop(); // 假设存在的播放器实例
  4871. //退出APP
  4872. const mContext = getContext(this) as common.UIAbilityContext
  4873. mContext.terminateSelf();
  4874. AvSessionController.getInstance(true).unregisterSessionListener()
  4875. }
  4876. //倒计时关闭音乐,退出App功能实现结束。
  4877. //播放列表的拖动List 重新排序
  4878. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  4879. //左滑操作 移动文件 重命名 删除等操作
  4880. @Builder
  4881. sonButton(item: VideoItem, index: number, filePath: string) {
  4882. Row() {
  4883. //加入下一首播放
  4884. Button() {
  4885. Image($r('app.media.next_to_play'))
  4886. .fillColor(Color.White)
  4887. .width(20)
  4888. }
  4889. .width(40)
  4890. .height(40)
  4891. .type(ButtonType.Circle)
  4892. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4893. .backgroundColor(this.themeColor)
  4894. .margin(5)
  4895. .onClick(() => {
  4896. this.addToNextPlay(item);
  4897. })
  4898. Button() {
  4899. Image($r('app.media.close'))
  4900. .fillColor(Color.White)
  4901. .width(20)
  4902. }
  4903. .width(40)
  4904. .height(40)
  4905. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4906. .type(ButtonType.Circle)
  4907. .backgroundColor(this.themeColor)
  4908. .margin(5)
  4909. .onClick(() => {
  4910. this.songList.splice(Number(index), 1)
  4911. this.sonDataSource.pushArrayData(this.songList)
  4912. })
  4913. Button() {
  4914. Image($r('app.media.share2'))
  4915. .fillColor(Color.White)
  4916. .width(20)
  4917. }
  4918. .width(40)
  4919. .height(40)
  4920. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4921. .type(ButtonType.Circle)
  4922. .backgroundColor(this.themeColor)
  4923. .margin(5)
  4924. .onClick(() => {
  4925. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4926. })
  4927. }
  4928. }
  4929. itemMoveSon(index: number, newIndex: number): void {
  4930. if (newIndex < 0 || newIndex >= this.songList.length) {
  4931. return;
  4932. }
  4933. let tmp = this.songList.splice(index, 1);
  4934. this.songList.splice(newIndex, 0, tmp[0]);
  4935. this.sonDataSource.pushArrayData(this.songList)
  4936. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  4937. }
  4938. @Builder
  4939. PlayList() {
  4940. List({ scroller: this.playListScroller }) {
  4941. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  4942. ListItem() {
  4943. this.MusicItemSon(item, index)
  4944. }
  4945. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  4946. .animation({
  4947. duration: 666,
  4948. curve: 'ease-in-out' // 可选动画曲线
  4949. })
  4950. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  4951. TransitionEffect.scale({ x: 0, y: 0 })))
  4952. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  4953. //拖动List关键代码开始
  4954. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4955. .zIndex(this.dragItem === index ? 1 : 0)
  4956. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4957. .gesture(
  4958. GestureGroup(GestureMode.Sequence,
  4959. LongPressGesture({ repeat: true })
  4960. .onAction((event?: GestureEvent) => {
  4961. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4962. this.scaleItem = index
  4963. })
  4964. })
  4965. .onActionEnd(() => {
  4966. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4967. this.scaleItem = -1
  4968. })
  4969. }),
  4970. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4971. .onActionStart(() => {
  4972. this.dragItem = index // 记录当前拖动项索引
  4973. this.dragRefOffset = 0 // 重置偏移基准
  4974. })
  4975. .onActionUpdate((event: GestureEvent) => {
  4976. this.offsetY = event.offsetY - this.dragRefOffset;
  4977. this.neighborItem = -1;
  4978. let indexA = this.songList.indexOf(item);
  4979. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4980. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4981. let value: number = 0;
  4982. if (this.offsetY < 0) {
  4983. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4984. this.neighborItem = indexA - 1;
  4985. this.neighborScale = 1 - value / 20;
  4986. } else if (this.offsetY > 0) {
  4987. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4988. this.neighborItem = indexA + 1;
  4989. this.neighborScale = 1 - value / 20;
  4990. }
  4991. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  4992. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4993. this.offsetY -= this.ITEM_INTV;
  4994. this.dragRefOffset += this.ITEM_INTV;
  4995. this.itemMoveSon(indexA, indexA + 1);
  4996. });
  4997. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4998. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4999. this.offsetY += this.ITEM_INTV;
  5000. this.dragRefOffset -= this.ITEM_INTV;
  5001. this.itemMoveSon(indexA, indexA - 1);
  5002. });
  5003. }
  5004. })
  5005. .onActionEnd((event: GestureEvent) => {
  5006. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5007. this.dragItem = -1
  5008. this.neighborItem = -1
  5009. })
  5010. animateTo({
  5011. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5012. }, () => {
  5013. this.scaleItem = -1
  5014. })
  5015. })
  5016. )
  5017. .onCancel(() => {
  5018. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5019. this.dragItem = -1
  5020. this.neighborItem = -1
  5021. })
  5022. animateTo({
  5023. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5024. }, () => {
  5025. this.scaleItem = -1
  5026. })
  5027. })
  5028. ) //拖动List关键代码结束
  5029. .onClick(() => {
  5030. this.doPlay(item, index, true)
  5031. })
  5032. }, (item: VideoItem) => item.filePath)
  5033. }
  5034. .width('100%')
  5035. .height('100%')
  5036. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5037. // .animation({ duration: 500, curve: Curve.Ease }))
  5038. .cachedCount(10)
  5039. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5040. .gesture(PinchGesture({ fingers: 2 })
  5041. .onActionEnd((event: GestureEvent) => {
  5042. this.setlistTwoFingers()
  5043. })
  5044. .onActionUpdate(e => {
  5045. this.scaleValue = this.pinchValue * e.scale
  5046. })
  5047. .onActionStart(e => {
  5048. }))
  5049. .padding({
  5050. bottom: 0
  5051. })
  5052. }
  5053. @Builder
  5054. private MusicItemSon(item: VideoItem, index?: number) {
  5055. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5056. Row() {
  5057. Stack() {
  5058. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5059. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5060. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5061. .alt($r('app.media.music_red'))
  5062. .fillColor(this.themeColor)
  5063. .borderRadius('100%')
  5064. .clip(true)
  5065. .margin({ left: 20 })
  5066. }
  5067. .width('15%')
  5068. Column() {
  5069. Column() {
  5070. Text(item.name)
  5071. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5072. .fontColor(this.curIndex === index ? this.themeColor :
  5073. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5074. .maxLines(1)
  5075. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5076. Row() {
  5077. Column(){
  5078. Text(item.md5Str?.includes('Lossless')?
  5079. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5080. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5081. .padding({ top: 3,right:6,left:6,bottom:3 })
  5082. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5083. $r('app.color.text_color'))
  5084. .fontWeight(500)
  5085. .borderRadius(12)
  5086. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5087. .backgroundColor('#FFC107')
  5088. }
  5089. .padding({ top: 8 })
  5090. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5091. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5092. .padding({ top: 8 })
  5093. .fontColor(this.curIndex === index ? this.themeColor :
  5094. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5095. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5096. Blank()
  5097. Text(item.size)
  5098. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5099. .padding({ top: 8 })
  5100. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5101. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5102. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5103. .margin({ left: 10 })
  5104. }
  5105. }
  5106. .height('100%')
  5107. .width('100%')
  5108. .justifyContent(FlexAlign.Center)
  5109. .alignItems(HorizontalAlign.Start)
  5110. }
  5111. .height('100%')
  5112. .width('65%')
  5113. Column() {
  5114. ImageAnimator()
  5115. .images(this.imagesF)// 动画数组
  5116. .duration(1000)// 持续
  5117. .state(this.animationState)// 动画状态
  5118. .fillMode(FillMode.Forwards)
  5119. .width(18)
  5120. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5121. Visibility.None)
  5122. .height(18)
  5123. .iterations(-1) // 播放次数
  5124. }
  5125. .width('20%')
  5126. }
  5127. }
  5128. .backgroundColor(Color.Transparent)
  5129. .width('100%')
  5130. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5131. .shadow(this.scaleItem === index ? {
  5132. radius: 70,
  5133. color: '#15000000',
  5134. offsetX: 0,
  5135. offsetY: 0
  5136. } :
  5137. {
  5138. radius: 0,
  5139. color: '#15000000',
  5140. offsetX: 0,
  5141. offsetY: 0
  5142. })
  5143. .animation({ curve: Curve.Sharp, duration: 300 })
  5144. }
  5145. @Builder
  5146. MusicPlayBuilder() {
  5147. Column() {
  5148. this.IjkMusicPlayerView()
  5149. }
  5150. .height('100%')
  5151. .width('100%')
  5152. .onDisAppear(() => {
  5153. this.translateY = 0;
  5154. })
  5155. .translate({ y: this.translateY })
  5156. .gesture(
  5157. PanGesture(this.panOption)
  5158. .onActionUpdate((event?: GestureEvent) => {
  5159. if (event) {
  5160. // 只允许向下滑动,向上滑动时限制为0
  5161. this.translateY = Math.max(0, event.offsetY);
  5162. }
  5163. })
  5164. .onActionEnd((event?: GestureEvent) => {
  5165. // 使用更低的阈值和滑动速度判断
  5166. const minDistance = 100; // 最小滑动距离 100vp
  5167. const minVelocity = 500; // 最小滑动速度
  5168. // 获取滑动速度(如果可用)
  5169. const velocity = event?.velocityY || 0;
  5170. // 判断是否应该关闭:距离足够 或者 速度足够快
  5171. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5172. if (shouldClose) {
  5173. // 添加关闭动画
  5174. this.getUIContext().animateTo({
  5175. duration: 300,
  5176. curve: Curve.Smooth
  5177. }, () => {
  5178. this.isShowPlay = false;
  5179. this.translateY = 0;
  5180. })
  5181. } else {
  5182. // 回弹动画
  5183. this.getUIContext().animateTo({
  5184. duration: 300,
  5185. curve: Curve.Smooth
  5186. }, () => {
  5187. this.translateY = 0;
  5188. })
  5189. }
  5190. })
  5191. )
  5192. }
  5193. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5194. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5195. HeightBreakpoint.HEIGHT_LG;
  5196. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5197. @State topBarHeight: number = 50
  5198. @State barOpacity: number = 1
  5199. @State barBottomOpacity: number = 1
  5200. private hideDone: boolean = false;
  5201. @State currentYOffset: number = 0;
  5202. @State bottomBarHeight: number = 60;
  5203. private isHiding: boolean = false;
  5204. //是否是Pura X外屏,或者小屏幕
  5205. isPuraWP() {
  5206. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5207. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5208. }
  5209. //是否是Pura X外屏,或者小屏幕,手机横屏
  5210. isCoverOpacity() {
  5211. if (this.isPuraWP()) {
  5212. return true
  5213. }
  5214. if (this.isPhoneLan()) {
  5215. return true
  5216. }
  5217. if (deviceInfo.marketName.includes('Pura X')
  5218. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5219. return true
  5220. }
  5221. return false
  5222. }
  5223. //是不是手机横屏
  5224. isPhoneLan() {
  5225. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5226. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5227. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5228. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5229. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, isHiCar: ${this.isHiCar()}`);
  5230. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5231. if (this.isHiCar()) {
  5232. return false
  5233. }
  5234. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5235. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5236. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD) { //如果是手机横屏,返回true
  5237. return true
  5238. }
  5239. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5240. && this.currentBreakpoint !== BreakpointTypeEnum.SM) {
  5241. if (DisplayUtil.getFoldStatus() === 0) {
  5242. return true
  5243. }
  5244. }
  5245. return false
  5246. }
  5247. //是不是1920x720的hicar的屏幕分辨率
  5248. isHiCarKuanBianPing(){
  5249. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5250. { ratio: 1920 / 720, name: "1920x720" },
  5251. ];
  5252. const currentRatio: number = this.windowWidth / this.windowHeight;
  5253. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5254. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5255. for (const hiCarRatio of hiCarAspectRatios) {
  5256. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5257. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5258. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5259. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5260. return true&&this.isHiCarStatus;
  5261. }
  5262. }
  5263. return false;
  5264. }
  5265. //是不是hicar的屏幕分辨率
  5266. isHiCarSmall() {
  5267. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5268. return false
  5269. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5270. { ratio: 800 / 480, name: "800x480" },
  5271. { ratio: 1280 / 720, name: "1280x720" },
  5272. { ratio: 1920 / 720, name: "1920x720" },
  5273. ];
  5274. const currentRatio: number = this.windowWidth / this.windowHeight;
  5275. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5276. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5277. for (const hiCarRatio of hiCarAspectRatios) {
  5278. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5279. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5280. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5281. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5282. return true&&this.isHiCarStatus;
  5283. }
  5284. }
  5285. return false;
  5286. }
  5287. isHiCar() {
  5288. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5289. { ratio: 800 / 480, name: "800x480" },
  5290. { ratio: 762 / 752, name: "762x752" },
  5291. { ratio: 968 / 1280, name: "968x1280" },
  5292. { ratio: 1200 / 1200, name: "1200x1200" },
  5293. { ratio: 1280 / 720, name: "1280x720" },
  5294. { ratio: 1920 / 720, name: "1920x720" },
  5295. { ratio: 1920 / 1080, name: "1920x1080" }
  5296. ];
  5297. const currentRatio: number = this.windowWidth / this.windowHeight;
  5298. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5299. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5300. for (const hiCarRatio of hiCarAspectRatios) {
  5301. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5302. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5303. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5304. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5305. return true&&this.isHiCarStatus;
  5306. }
  5307. }
  5308. return false;
  5309. }
  5310. //是不是正常的手机竖屏
  5311. isPhonePortrait() {
  5312. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5313. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5314. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5315. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5316. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5317. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5318. return true
  5319. }
  5320. return false
  5321. }
  5322. @State showSpeedDialog: boolean = false
  5323. @State longPressSpeed: number = 3 //长按默认倍数
  5324. @Builder
  5325. SpeedDialog() {
  5326. Stack() {
  5327. Column() {
  5328. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5329. .fontColor(Color.White)
  5330. .visibility(Visibility.Hidden)
  5331. }
  5332. .backgroundColor(Color.Black)
  5333. .borderRadius(20)
  5334. .padding({
  5335. top: 10,
  5336. right: 20,
  5337. left: 15,
  5338. bottom: 20
  5339. })
  5340. .opacity(0.6)
  5341. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5342. .fontColor(Color.White)
  5343. }
  5344. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5345. .zIndex(5)
  5346. .margin({ top: 80 })
  5347. }
  5348. @Builder
  5349. IjkMusicPlayerView() {
  5350. Column() {
  5351. Column() {
  5352. Column() {
  5353. //播放标题
  5354. Column() {
  5355. this.PlayTitle()
  5356. }
  5357. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5358. .width('100%')
  5359. .margin({ top: 0 })
  5360. .height(PlayConstants.HEIGHT)
  5361. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5362. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5363. if (this.showSpeedDialog) {
  5364. this.SpeedDialog()
  5365. }
  5366. Stack() {
  5367. //手势拖动快进
  5368. Column()
  5369. .width(CommonConstants.FULL_PERCENT)
  5370. .height('100%')
  5371. .gesture(
  5372. GestureGroup(GestureMode.Parallel,
  5373. // 长按屏幕倍数播放
  5374. LongPressGesture({ repeat: true })
  5375. .onAction(() => {
  5376. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5377. this.showSpeedDialog = true;
  5378. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  5379. }
  5380. })
  5381. .onActionEnd(() => {
  5382. this.showSpeedDialog = false;
  5383. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5384. }),
  5385. //双击屏幕暂停或者播放
  5386. TapGesture({ count: 2 })
  5387. .onAction((event: GestureEvent) => {
  5388. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5389. ToastUtil.showToast('已暂停')
  5390. }
  5391. this.playOrPause()
  5392. })
  5393. )
  5394. )
  5395. }
  5396. .height('65%')
  5397. Swiper() {
  5398. this.CoverInfo()
  5399. this.PlayerLyrics()
  5400. }
  5401. .onChange((index: number) => {
  5402. this.currentSwiperIndex = index
  5403. })
  5404. .indicator(false)
  5405. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5406. // new DotIndicator()
  5407. // .top(this.isCoverOpacity()?0:10)
  5408. //
  5409. // .selectedColor($r('app.color.select_swiper'))
  5410. // .color($r('app.color.slider_track')):false
  5411. // )
  5412. .displayCount(new BreakpointType({
  5413. sm: 1,
  5414. md: 2,
  5415. lg: 2,
  5416. xl: 2,
  5417. xxl: 2
  5418. }).getValue(this.currentBreakpoint))
  5419. .clip(false)
  5420. .loop(false)
  5421. .autoPlay(false)
  5422. // .interval(8000)
  5423. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5424. .height('100%')
  5425. .hitTestBehavior(HitTestMode.Transparent)
  5426. Image($r('app.media.icon_replay'))
  5427. .objectFit(ImageFit.Auto)
  5428. .width('120px')
  5429. .height('120px')
  5430. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5431. .border({ width: 0 })
  5432. .visibility(Visibility.None)
  5433. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5434. .onClick(() => {
  5435. this.startPlayOrResumePlay();
  5436. })
  5437. }
  5438. .width(CommonConstants.FULL_PERCENT)
  5439. .height(CommonConstants.FULL_PERCENT)
  5440. .justifyContent(FlexAlign.End)
  5441. }
  5442. .justifyContent(FlexAlign.End)
  5443. .margin({ bottom: 8 })
  5444. }
  5445. // .backgroundImage(this.imageLabelBg)
  5446. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5447. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5448. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5449. // .backgroundImagePosition(Alignment.Center)
  5450. .animation({
  5451. duration: 666,
  5452. curve: 'ease-in-out' // 可选动画曲线
  5453. })
  5454. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5455. BlurStyle.BACKGROUND_ULTRA_THICK)
  5456. .hitTestBehavior(HitTestMode.Transparent)
  5457. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5458. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5459. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5460. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5461. .onClick(() => {
  5462. // this.startAutoHide()
  5463. this.is_auto_hide_progress = false
  5464. setTimeout(() => {
  5465. this.is_auto_hide_progress = true
  5466. }, 6000)
  5467. })
  5468. }
  5469. @State progressValue: number = 0;
  5470. @State currentTime: string = "00:00";
  5471. @State totalTime: string = "00:00";
  5472. @State loadingVisible: Visibility = Visibility.None;
  5473. @State replayVisible: Visibility = Visibility.None;
  5474. @State slideEnable: boolean = false;
  5475. @State aspRatio: number = 0.5;
  5476. @State mContext: object | undefined = undefined;
  5477. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  5478. @State mFirst: boolean = true;
  5479. @State mDestroyPage: boolean = false;
  5480. @State playSpeed: number = 1;
  5481. @State oldSeconds: number = 0;
  5482. @State isSeekTo: boolean = false;
  5483. @State isCurrentTime: boolean = false;
  5484. @State videoWidth: string = '100%';
  5485. @State videoHeight: string = '100%';
  5486. @State initAspectRatio: number = 1;
  5487. @State videoAspectRatio: number = this.initAspectRatio;
  5488. private videoUrl: string = '';
  5489. private last: number = 0;
  5490. @State videoParentAspectRatio: number = this.initAspectRatio;
  5491. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  5492. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  5493. @State PROGRESS_MAX_VALUE: number = 100;
  5494. @State updateProgressTimer: number = 0;
  5495. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  5496. @State name: string = '';
  5497. // @State loop: boolean = false;
  5498. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  5499. @State multiple: string = '1.0X';
  5500. xcomponentController: XComponentController = new XComponentController()
  5501. private panOptionBright: PanGestureOptions =
  5502. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  5503. private panOptionVolume: PanGestureOptions =
  5504. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  5505. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  5506. //手势的音量控制和亮度控制
  5507. private positionX: number = PlayConstants.POSITION_X;
  5508. private positionY: number = PlayConstants.POSITION_Y;
  5509. private windowClass: window.Window = globalThis.windowClass
  5510. @State volume: number = 0.3;
  5511. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  5512. @State bright: number = PlayConstants.BRIGHT;
  5513. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  5514. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  5515. @State screenWidth: number = 0
  5516. @State screenHeight: number = 0
  5517. @State statusBarHeight: number = 0
  5518. @State isYesFull: boolean = false
  5519. private seekValue: number = 0
  5520. @State isVideoLock: boolean = false; // Whether the video playback is locked
  5521. eventHub = getContext().eventHub;
  5522. //投播组件
  5523. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  5524. private castController: avSession.AVCastController | undefined = undefined;
  5525. @State isCastPlaying: boolean = false;
  5526. @State currentTime2: number = 0;
  5527. @State currentStringTime: string = '00:00';
  5528. @State duration: number = 0;
  5529. @State isReady: boolean = false;
  5530. @State durationTime: number = 0;
  5531. @State durationStringTime: string = '00:00';
  5532. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  5533. // @State isPlaying: boolean = false;
  5534. private castSeek: boolean = false;
  5535. private castItem: avSession.AVQueueItem | undefined = undefined;
  5536. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  5537. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  5538. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  5539. @State rotateAngle2: number = 0
  5540. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  5541. @State cover: string | undefined = '';
  5542. @State artist: string | undefined = ''
  5543. // 1.初始化controller
  5544. private lyricController: LyricController = new LyricController()
  5545. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  5546. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  5547. private parser = new LyricParser()
  5548. @State randomColor: string = 'rgb(0,0,0)'
  5549. @State randomShakenX: number = 0
  5550. @State randomShakenY: number = 0
  5551. @State lyricTextSize: number = 24
  5552. @State lyricContent: string = ''
  5553. @State isDebug: boolean = false
  5554. @State isHightLightCenter: boolean = true
  5555. /**
  5556. * 初始化歌词加载与展示逻辑
  5557. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  5558. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  5559. * @param isApi2 是否使用API2获取歌词(可选)
  5560. *
  5561. * 主要流程:
  5562. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  5563. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  5564. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  5565. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  5566. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  5567. * 6. 解析失败或读取失败时,清空歌词显示。
  5568. *
  5569. * 注意事项:
  5570. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  5571. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  5572. * - 歌词内容解析后通过lyricController驱动UI渲染。
  5573. */
  5574. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  5575. if (StrUtil.isEmpty(lyricPath)) {
  5576. return
  5577. }
  5578. this.initPipLyricSetting()
  5579. this.lyricControllerSingle
  5580. .setTextSize(15)
  5581. .setCacheSize(4)
  5582. .setTextColor("#FFFFFF")
  5583. .setHighlightColor("#FFFFFF")
  5584. .setHighlightScale(1.2)
  5585. .setEmptyHint("")
  5586. .setAlignMode('center')
  5587. .setAnimationDuration(500)
  5588. .setSingleLine(true)
  5589. this.lyricContent = ''
  5590. this.lyricController
  5591. .setTextSize(this.currentLyricSize)
  5592. .setCacheSize(4)
  5593. .setTextColor("#DDDDDD")
  5594. .setHighlightColor("#FFFFFF")
  5595. .setEmptyHint("")
  5596. .setAnimationDuration(1000)
  5597. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  5598. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 0)
  5599. this.setBlurDegree(this.blurDegree, false)
  5600. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  5601. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  5602. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  5603. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  5604. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  5605. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  5606. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  5607. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  5608. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  5609. this.lyricController.setTextWeight(this.lyricTextWeight)
  5610. this.showSingleLyric = false
  5611. this.timeOffset = 0
  5612. this.lyricController.setLyric(null)
  5613. this.lyricControllerSingle.setLyric(null)
  5614. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  5615. console.log("onecold lyricPath =" + lyricPath)
  5616. let neiqianLrc = ''
  5617. let lyContent = this.currentSong?.lyricContent
  5618. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  5619. neiqianLrc = lyContent
  5620. }else{
  5621. neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
  5622. }
  5623. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  5624. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  5625. //赋值给this.lyricContent,播控中心才可以显示歌词
  5626. this.lyricContent = neiqianLrc
  5627. // 将文件内容按行分割成字符串数组
  5628. let lines = neiqianLrc.split('\n').map(line => line.trim());
  5629. // 3.解析歌词
  5630. let lyric = this.parser.parse(lines);
  5631. // 4.设置歌词
  5632. this.lyricController.setLyric(lyric);
  5633. this.lyricControllerXF.setLyric(lyric)
  5634. this.lyricControllerSingle.setLyric(lyric)
  5635. return
  5636. }
  5637. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  5638. && !Utility.isVideoByExtension(this.videoUrl))) {
  5639. if (this.currentSong !== undefined) {
  5640. // ToastUtil.showShort('正在为你搜索在线歌词!')
  5641. //判断是不是赞助会员,是会员的话才开启歌词功能
  5642. // if (!this.isDebug) {
  5643. // if (!Utility.isNoble()) {
  5644. // LogUtil.debug("onecold 不是赞助会员")
  5645. // return
  5646. // }
  5647. // if(!Utility.isPassInstallTime(33)){
  5648. // LogUtil.debug("onecold not pass time")
  5649. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  5650. // return
  5651. // }
  5652. // }
  5653. let artist = this.currentSong?.artist
  5654. if (artist === undefined) {
  5655. artist = ''
  5656. }
  5657. if (isApi2 === undefined) {
  5658. isApi2 = false
  5659. }
  5660. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  5661. // LogUtil.debug("onecold res =" + res)
  5662. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5663. if (StrUtil.isNotEmpty(res)) {
  5664. this.lyricContent = res
  5665. let lines = res.split('\n').map(line => line.trim());
  5666. // 3.解析歌词
  5667. let lyric = this.parser.parse(lines);
  5668. // 4.设置歌词
  5669. this.lyricController.setLyric(lyric);
  5670. this.lyricControllerXF.setLyric(lyric)
  5671. this.lyricControllerSingle.setLyric(lyric)
  5672. this.showSingleLyric = true
  5673. // 4.保存歌词文件lyric到本地
  5674. this.saveDataToFile(res, jiaMilyricPath, true)
  5675. } else {
  5676. this.lyricController.setLyric(null)
  5677. this.lyricControllerXF.setLyric(null)
  5678. this.lyricControllerSingle.setLyric(null)
  5679. if (isOnLineAndToast) {
  5680. ToastUtil.showShort('未获取到歌词!')
  5681. }
  5682. }
  5683. } else {
  5684. this.lyricController.setLyric(null)
  5685. this.lyricControllerXF.setLyric(null)
  5686. this.lyricControllerSingle.setLyric(null)
  5687. if (isOnLineAndToast) {
  5688. ToastUtil.showShort('未获取到歌词!')
  5689. }
  5690. }
  5691. })
  5692. } else {
  5693. this.lyricController.setLyric(null)
  5694. this.lyricControllerXF.setLyric(null)
  5695. this.lyricControllerSingle.setLyric(null)
  5696. if (isOnLineAndToast) {
  5697. ToastUtil.showShort('未获取到歌词!')
  5698. }
  5699. }
  5700. return
  5701. }
  5702. try {
  5703. let isJiaMi = false;
  5704. let realLyricPath = lyricPath
  5705. if (FileUtil.accessSync(jiaMilyricPath)) {
  5706. isJiaMi = true
  5707. realLyricPath = jiaMilyricPath
  5708. console.info("onecold 找到加密本地歌词 ");
  5709. } else {
  5710. isJiaMi = false
  5711. realLyricPath = lyricPath
  5712. console.info("onecold 找到本地歌词 ");
  5713. }
  5714. // 3.读取文件内容并指定编码为 UTF-8
  5715. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5716. let arrayBuffer = new ArrayBuffer(4096);
  5717. fs.read(file.fd, arrayBuffer)
  5718. .then((readLen: number) => {
  5719. console.info("read file data succeed");
  5720. // let buf = buffer.from(arrayBuffer, 0, readLen);
  5721. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5722. // 检查 buf 是否为空
  5723. if (buf.length === 0) {
  5724. throw new Error("Buffer is empty after reading the file");
  5725. }
  5726. try {
  5727. // 检测文件编码
  5728. // let detectedEncoding = chardet.detect(buf);
  5729. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  5730. let detectedEncoding = this.detect(arrayBuffer)
  5731. console.info("onecoldT Detected encoding: " + detectedEncoding);
  5732. // 使用检测到的编码解码,解决中文乱码问题
  5733. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5734. console.info("onecoldT Detected textDecoder: " + textDecoder);
  5735. let fileContent = textDecoder.decode(buf);
  5736. console.info(`onecoldT The content of file1: ${fileContent}`);
  5737. //解密
  5738. if (isJiaMi) {
  5739. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  5740. }
  5741. console.info(`onecold The content of file2: ${fileContent}`);
  5742. this.lyricContent = fileContent
  5743. // 将文件内容按行分割成字符串数组
  5744. let lines = fileContent.split('\n').map(line => line.trim());
  5745. console.info(`onecold The content of file: ${fileContent}`);
  5746. // 3.解析歌词
  5747. let lyric = this.parser.parse(lines);
  5748. // 4.设置歌词
  5749. this.lyricController.setLyric(lyric);
  5750. this.lyricControllerXF.setLyric(lyric)
  5751. this.lyricControllerSingle.setLyric(lyric)
  5752. this.showSingleLyric = true
  5753. console.info(`The content of file: ${fileContent}`);
  5754. } catch (chardetError) {
  5755. console.error("chardet.detect failed with error: " + chardetError.message);
  5756. this.lyricController.setLyric(null);
  5757. this.lyricControllerXF.setLyric(null)
  5758. this.lyricControllerSingle.setLyric(null)
  5759. }
  5760. })
  5761. .catch((err: BusinessError) => {
  5762. this.lyricController.setLyric(null)
  5763. this.lyricControllerXF.setLyric(null)
  5764. this.lyricControllerSingle.setLyric(null)
  5765. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  5766. })
  5767. .catch((err: Error) => {
  5768. this.lyricController.setLyric(null)
  5769. this.lyricControllerXF.setLyric(null)
  5770. this.lyricControllerSingle.setLyric(null)
  5771. console.error("read file 2 data failed with error message: " + err.message);
  5772. })
  5773. .finally(() => {
  5774. fs.closeSync(file);
  5775. });
  5776. } catch (error) {
  5777. this.lyricController.setLyric(null)
  5778. this.lyricControllerSingle.setLyric(null)
  5779. this.lyricControllerXF.setLyric(null)
  5780. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  5781. }
  5782. }
  5783. detect(data: ArrayBuffer): string {
  5784. //创建检测对象
  5785. let detector: UniversalDetector = new UniversalDetector();
  5786. // 传入检测数据并实时判断编码格式
  5787. detector.handleData(data, 0, data.byteLength);
  5788. // 标记检测数据 读取结束
  5789. detector.dataEnd();
  5790. // 获取检测结果
  5791. let detected: string = detector.getDetectedCharset();
  5792. // 释放资源
  5793. detector.reset();
  5794. return detected;
  5795. }
  5796. //初始化悬浮歌词的自定义设置
  5797. initPipLyricSetting() {
  5798. this.lyricControllerXF
  5799. .setTextSize(this.currentLyricSize)
  5800. .setCacheSize(4)
  5801. .setTextColor("#DDDDDD")
  5802. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  5803. .setEmptyHint("")
  5804. .setAnimationDuration(1000)
  5805. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  5806. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 2)
  5807. this.setBlurDegree(this.blurDegreePip, true)
  5808. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  5809. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  5810. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  5811. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  5812. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  5813. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  5814. this.lyricControllerXF.setHightLightCenter(true)
  5815. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  5816. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  5817. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  5818. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  5819. if (this.pipBgIndex === 0) {
  5820. if (this.cover) {
  5821. this.pipBg = this.cover
  5822. } else {
  5823. this.pipBg = this.imageColor
  5824. }
  5825. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  5826. }
  5827. }
  5828. //根据item返回歌词内容
  5829. async getLyricContent(item: VideoItem): Promise<string> {
  5830. try {
  5831. let filePath = item.filePath;
  5832. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  5833. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  5834. let isJiaMi = false;
  5835. let realLyricPath = lyricPath;
  5836. if (FileUtil.accessSync(jiaMilyricPath)) {
  5837. isJiaMi = true;
  5838. realLyricPath = jiaMilyricPath;
  5839. console.info("onecold 找到加密本地歌词");
  5840. } else {
  5841. console.info("onecold 找到本地歌词");
  5842. }
  5843. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5844. let arrayBuffer = new ArrayBuffer(4096);
  5845. const readLen = await fs.read(file.fd, arrayBuffer);
  5846. console.info("read file data succeed");
  5847. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5848. if (buf.length === 0) {
  5849. throw new Error("Buffer is empty after reading the file");
  5850. }
  5851. // let detectedEncoding = chardet.detect(buf);
  5852. let detectedEncoding = this.detect(arrayBuffer)
  5853. console.info("Detected encoding: " + detectedEncoding);
  5854. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5855. let fileContent = textDecoder.decode(buf);
  5856. console.info(`onecold The content of file1: ${fileContent}`);
  5857. if (isJiaMi) {
  5858. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  5859. }
  5860. console.info(`onecold The content of file2: ${fileContent}`);
  5861. fs.closeSync(file);
  5862. return fileContent;
  5863. } catch (error) {
  5864. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  5865. return '';
  5866. }
  5867. }
  5868. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  5869. if (StrUtil.isEmpty(filePath)) {
  5870. return
  5871. }
  5872. try {
  5873. //将content进行加密
  5874. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  5875. let lyricContent = ''
  5876. if (isJiaMi) {
  5877. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  5878. } else {
  5879. lyricContent = content
  5880. }
  5881. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  5882. // 清空文件内容
  5883. await fileIo.truncate(file.fd, 0);
  5884. await fileIo.write(file.fd, lyricContent);
  5885. await fileIo.close(file);
  5886. console.log('onecold lyric file Data saved successfully.');
  5887. } catch (error) {
  5888. console.error('onecold lyric file Failed to save data:', error);
  5889. }
  5890. }
  5891. /**
  5892. * Get largest proportion color of an image.
  5893. */
  5894. getImageColor() {
  5895. if (!this.context) {
  5896. return;
  5897. }
  5898. let bg = Utility.getMusisBg()
  5899. this.imageLabel = bg
  5900. ColorConversion.setSysBarLightBackground(true);
  5901. this.context.resourceManager.getMediaContent(bg)
  5902. .then((value: Uint8Array) => {
  5903. let buffer = value.buffer as ArrayBuffer;
  5904. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  5905. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  5906. if (error) {
  5907. Logger.error('Failed to create color picker.');
  5908. } else {
  5909. let color = colorPicker.getLargestProportionColor();
  5910. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  5911. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  5912. }
  5913. })
  5914. let headFilter = effectKit.createEffect(pixelMap);
  5915. if (headFilter !== null) {
  5916. headFilter.blur(15);
  5917. headFilter.getEffectPixelMap().then((value) => {
  5918. this.imageLabelBg = value;
  5919. })
  5920. }
  5921. })
  5922. .catch((error: BusinessError) => {
  5923. Logger.error(`${error.code} + ${error.message}`)
  5924. })
  5925. })
  5926. .catch((error: BusinessError) => {
  5927. Logger.error(`${error.code} + ${error.message}`)
  5928. })
  5929. }
  5930. setImageColor(cover: string) {
  5931. if (!this.context) {
  5932. return;
  5933. }
  5934. if (cover === undefined) {
  5935. return;
  5936. }
  5937. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  5938. let headFilter = effectKit.createEffect(value);
  5939. if (headFilter !== null) {
  5940. headFilter.blur(15);
  5941. headFilter.getEffectPixelMap().then((value) => {
  5942. this.imageLabelBg = value;
  5943. })
  5944. }
  5945. }).catch((error: BusinessError) => {
  5946. Logger.error(`${error.code} + ${error.message}`)
  5947. })
  5948. }
  5949. setImageColor2(cover: string) {
  5950. if (!this.context) {
  5951. return;
  5952. }
  5953. if (cover === undefined) {
  5954. return;
  5955. }
  5956. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  5957. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  5958. this.imageColor = data.imageColor;
  5959. if (data.blurPixelMap) {
  5960. this.imageLabelBg = data.blurPixelMap;
  5961. }
  5962. })
  5963. }
  5964. // 定义开始旋转的方法
  5965. // 定时器用于一百毫秒执行一次旋转角度
  5966. @State timer: number = 0
  5967. @State rotateAngle: number = 0
  5968. //封面旋转动画
  5969. animationRoFun() {
  5970. if (this.isPlaying && !this.isCoverRectangle) {
  5971. this.timer = setInterval(() => {
  5972. this.rotateAngle += 1
  5973. }, 100)
  5974. this.startRotation()
  5975. } else {
  5976. clearInterval(this.timer)
  5977. this.stopRotation()
  5978. }
  5979. }
  5980. // 定义开始旋转的方法
  5981. startRotation() {
  5982. if (this.isPlaying) {
  5983. animateTo({
  5984. duration: 777,
  5985. iterations: 1,
  5986. curve: Curve.Linear
  5987. }, () => {
  5988. this.rotateAngle2 = 0
  5989. })
  5990. }
  5991. }
  5992. // 回调,暂停和播放按钮回调,下一首和上一首
  5993. playChange() {
  5994. // if(this.isCoverRectangle){
  5995. // return
  5996. // }
  5997. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5998. this.setIsPlaying(true)
  5999. this.animationState = AnimationStatus.Running
  6000. } else {
  6001. this.setIsPlaying(false)
  6002. this.animationState = AnimationStatus.Paused
  6003. }
  6004. }
  6005. // 定义停止旋转的方法
  6006. stopRotation() {
  6007. if (this.isCoverRectangle) {
  6008. this.rotateAngle = 0
  6009. } else {
  6010. //唱针以左上角为点选择逆时针40度
  6011. animateTo({
  6012. duration: 1000,
  6013. curve: Curve.Linear,
  6014. iterations: 1,
  6015. }, () => {
  6016. this.rotateAngle2 = -40;
  6017. });
  6018. }
  6019. }
  6020. @Builder
  6021. private LyricsTopItem() {
  6022. Row() {
  6023. Stack() {
  6024. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6025. .height(55)
  6026. .width(55)
  6027. .alt(this.imageLabel)
  6028. .borderRadius(8)
  6029. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6030. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6031. }
  6032. .width('18%')
  6033. Column() {
  6034. Column() {
  6035. Text(this.name)
  6036. .fontSize(16)
  6037. .maxLines(1)
  6038. .fontWeight(FontWeight.Bolder)
  6039. .fontColor(this.currentLyricColor)
  6040. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6041. Row() {
  6042. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6043. .fontSize(13)
  6044. .fontWeight(FontWeight.Bold)
  6045. .padding({ top: 8 })
  6046. .fontColor(this.currentLyricColor)
  6047. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6048. Blank()
  6049. }
  6050. }
  6051. .height('100%')
  6052. .width('100%')
  6053. .justifyContent(FlexAlign.Center)
  6054. .alignItems(HorizontalAlign.Start)
  6055. }
  6056. .height('100%')
  6057. .width('65%')
  6058. Column() {
  6059. Image($r('app.media.lyric'))
  6060. .width(28)
  6061. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6062. .margin({ right: 30 })
  6063. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6064. .onClick(() => {
  6065. this.isLyricSetting = !this.isLyricSetting;
  6066. })
  6067. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6068. height: this.isCoverOpacity() ? '95%' : '88%',
  6069. dragBar: true,
  6070. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6071. showClose: true,
  6072. blurStyle: BlurStyle.Thin,
  6073. backgroundColor: Color.Transparent,
  6074. // title: { title: $r('app.string.lyric_setting') }
  6075. })
  6076. }
  6077. .width('18%')
  6078. }
  6079. .width('82%')
  6080. .height(58)
  6081. .justifyContent(FlexAlign.SpaceBetween)
  6082. }
  6083. //歌词显示
  6084. @Builder
  6085. PlayerLyrics() {
  6086. Column() {
  6087. Column() {
  6088. this.LyricsTopItem()
  6089. }
  6090. .height(this.isPuraWP() ? 15 : 58)
  6091. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6092. Visibility.None : Visibility.Visible)
  6093. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6094. .width("100%")
  6095. Column() {
  6096. LyricView2({
  6097. controller: this.lyricController,
  6098. enableSeek: true,
  6099. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6100. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6101. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6102. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6103. if (!this.isPlaying) {
  6104. this.startPlayOrResumePlay()
  6105. } else {
  6106. this.isSeekTo = true;
  6107. this.mDestroyPage = false;
  6108. this.showLoadIng();
  6109. this.seekTo(position + "");
  6110. this.isSeekTo = false;
  6111. }
  6112. return true
  6113. }
  6114. })
  6115. .width("100%")
  6116. .layoutWeight(1)
  6117. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6118. if (this.isPhoneLan()) {
  6119. Column() {
  6120. this.playCenterView()
  6121. }
  6122. .margin({ bottom: 20, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6123. }
  6124. }
  6125. .position({
  6126. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6127. (this.isPuraWP() ? 58 : 99)
  6128. })
  6129. .justifyContent(FlexAlign.Center)
  6130. .height(this.isCoverOpacity() ? '95%' : '80%')
  6131. }
  6132. }
  6133. @Builder
  6134. SingleLyricView() {
  6135. Column() {
  6136. Column() {
  6137. LyricView2({
  6138. controller: this.lyricControllerSingle,
  6139. enableSeek: false,
  6140. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6141. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6142. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6143. })
  6144. }
  6145. .height(66)
  6146. .margin({ bottom: 20 })
  6147. }
  6148. }
  6149. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6150. @Builder
  6151. BottomControl() {
  6152. Column() {
  6153. //播放 暂停,下一首,上一首
  6154. this.playCenterView()
  6155. //播放进度条
  6156. this.playProgressView()
  6157. }
  6158. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 100) }) // 将 固定在底部
  6159. }
  6160. //播放控制上一首 下一首 暂停和播放
  6161. @Builder
  6162. playCenterView() {
  6163. Row() {
  6164. Row({ space: 20 }) {
  6165. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6166. //更多功能
  6167. Image($r('app.media.menu'))
  6168. .width(24)
  6169. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6170. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6171. height: this.isCoverOpacity() ? '95%' : '93%',
  6172. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6173. dragBar: true,
  6174. showClose: true,
  6175. blurStyle: BlurStyle.Thin,
  6176. backgroundColor: Color.Transparent,
  6177. })
  6178. }
  6179. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6180. .backgroundColor(Color.Transparent)
  6181. .onClick(() => {
  6182. this.isShowMoreView = !this.isShowMoreView;
  6183. })
  6184. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6185. Image($r('app.media.ic_previous'))
  6186. .width(33)
  6187. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6188. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6189. }
  6190. .onClick(async () => {
  6191. this.playPrevious()
  6192. })
  6193. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6194. .backgroundColor(Color.Transparent)
  6195. .margin({ left: 5 })
  6196. }
  6197. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6198. Column() {
  6199. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6200. (this.isCircleBtn ? $r('app.media.hm_pause') : $r('app.media.ic_public_play'))
  6201. : (this.isCircleBtn ? $r('app.media.hm_play2') : $r('app.media.ic_public_pause')))
  6202. .width(this.isPhoneLan() ? 48 : 60)
  6203. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6204. .fillColor(Color.White)
  6205. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6206. .onClick(async () => {
  6207. this.playOrPause()
  6208. })
  6209. }
  6210. }
  6211. .backgroundColor(Color.Transparent)
  6212. .layoutWeight(1)
  6213. .margin({ left: 38, right: 38 })
  6214. Row({ space: 20 }) {
  6215. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6216. Image($r('app.media.ic_next'))
  6217. .width(33)
  6218. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6219. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6220. .onClick(() => {
  6221. this.playNext();
  6222. })
  6223. }
  6224. .backgroundColor(Color.Transparent)
  6225. .margin({ right: 5 })
  6226. .width(33)
  6227. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6228. //添加或取消收藏
  6229. Image(Utility.getIsFav(this.favList, this.currentSong) ?
  6230. $r('app.media.add_fac_light') : $r('app.media.add_fac'))
  6231. .width(24)
  6232. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6233. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6234. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6235. .onClick(async () => {
  6236. if (this.currentSong) {
  6237. this.doFav(this.currentSong)
  6238. }
  6239. })
  6240. }
  6241. .backgroundColor(Color.Transparent)
  6242. .width(24)
  6243. }
  6244. // .margin({ left: 5 })
  6245. }
  6246. .width('100%')
  6247. .margin({ left: 10, right: 10, bottom: this.isCoverOpacity() ? 0 : 20 })
  6248. .justifyContent(FlexAlign.Center)
  6249. }
  6250. //播放进度条
  6251. @Builder
  6252. playProgressView() {
  6253. Row() {
  6254. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6255. Column() {
  6256. if (this.playType === 0) {
  6257. Image($r('app.media.loop'))
  6258. .width($r('app.float.control_image_width'))
  6259. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6260. } else if (this.playType === 1) {
  6261. Image($r('app.media.single'))
  6262. .width($r('app.float.control_image_width'))
  6263. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6264. } else if (this.playType === 2) {
  6265. Image($r('app.media.normal_play'))
  6266. .width($r('app.float.control_image_width'))
  6267. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6268. } else if (this.playType === 3) {
  6269. Image($r('app.media.random'))
  6270. .width($r('app.float.control_image_width'))
  6271. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6272. }
  6273. }
  6274. }
  6275. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6276. .animation({
  6277. duration: 666,
  6278. curve: 'ease-in-out' // 可选动画曲线
  6279. })
  6280. .backgroundColor(Color.Transparent)
  6281. .margin({ left: 20, right: 10 })
  6282. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6283. .onClick(async () => {
  6284. this.setLoopMode()
  6285. })
  6286. Text(this.currentTime)
  6287. .fontSize($r('app.float.slider_font_size'))
  6288. .fontColor(Color.White)
  6289. .margin(3)
  6290. Slider({
  6291. value: this.progressValue,
  6292. min: 0,
  6293. max: this.PROGRESS_MAX_VALUE,
  6294. step: 1,
  6295. style: SliderStyle.OutSet
  6296. })
  6297. .width('600px')
  6298. .blockColor('rgba(255,255,255,1)')
  6299. .trackColor('rgba(255,255,255,0.3)')
  6300. .selectedColor(Color.White)
  6301. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  6302. .layoutWeight(1)
  6303. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6304. .showSteps(false)
  6305. .showTips(true)
  6306. .enabled(this.slideEnable)
  6307. .onChange((value: number, mode: SliderChangeMode) => {
  6308. // if (mode == 2) {
  6309. this.isSeekTo = true;
  6310. this.mDestroyPage = false;
  6311. this.showLoadIng();
  6312. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6313. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6314. this.seekTo(seekValue + "");
  6315. // this.setProgress()
  6316. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6317. this.isSeekTo = false;
  6318. // }
  6319. })
  6320. Text(this.totalTime)
  6321. .fontSize($r('app.float.slider_font_size'))
  6322. .fontColor(Color.White)
  6323. .margin(3)
  6324. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6325. //播放列表
  6326. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6327. Image($r('app.media.hm_playlist'))
  6328. .width($r('app.float.control_image_width'))
  6329. .fillColor(Color.White)
  6330. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6331. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6332. height: '95%',
  6333. dragBar: true,
  6334. showClose: true,
  6335. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6336. blurStyle: BlurStyle.Thin,
  6337. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6338. title: {
  6339. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6340. + `(${this.songList.length}首)`
  6341. }
  6342. })
  6343. }
  6344. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6345. .animation({
  6346. duration: 666,
  6347. curve: 'ease-in-out' // 可选动画曲线
  6348. })
  6349. .backgroundColor(Color.Transparent)
  6350. .margin({ right: 20, left: 10 })
  6351. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6352. .onClick(() => {
  6353. this.isShowSheetView = !this.isShowSheetView;
  6354. if (this.isPlayListBgGrass) {
  6355. this.isFrontWhite = true
  6356. } else {
  6357. this.isFrontWhite = false
  6358. }
  6359. setTimeout(() => {
  6360. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  6361. }, 123)
  6362. })
  6363. }
  6364. //x5的竖屏模式需要99%
  6365. .width(this.isPhonePortrait() ? '93.4%'
  6366. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  6367. .height(this.isPhoneLan() ? 25 : 33)
  6368. .animation({
  6369. duration: 666,
  6370. curve: 'ease-in-out' // 可选动画曲线
  6371. })
  6372. }
  6373. isBigScreen() {
  6374. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  6375. return true
  6376. }
  6377. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6378. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6379. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  6380. return false
  6381. } else {
  6382. return true
  6383. }
  6384. return false
  6385. }
  6386. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  6387. @State isCoverRectangle: boolean = false
  6388. @State isCoverTop: boolean = true
  6389. @Builder
  6390. CoverInfo() {
  6391. Column() {
  6392. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  6393. if (this.isCoverRectangle) {
  6394. if (!this.isCoverTop) {
  6395. this.musicNameInfo(false)
  6396. }
  6397. } else {
  6398. this.musicNameInfo(false)
  6399. }
  6400. Stack() {
  6401. // 唱片旋转效果
  6402. Image($r('app.media.ic_music_disc'))
  6403. .width(250)
  6404. .height(250)
  6405. .margin({ right: 20, left: 20 })
  6406. .aspectRatio(1)
  6407. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6408. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6409. .borderRadius('100%')
  6410. .align(Alignment.Center)
  6411. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  6412. .rotate({
  6413. angle: this.rotateAngle,
  6414. centerX: "50%",
  6415. centerY: "50%",
  6416. })
  6417. .animation({
  6418. duration: 100,
  6419. curve: Curve.Linear
  6420. })
  6421. .shadow({
  6422. radius: 30,
  6423. color: this.randomColor
  6424. })
  6425. Column() {
  6426. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  6427. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel :
  6428. this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  6429. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  6430. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6431. .alt(this.imageLabel)
  6432. .margin({ right: 8, left: 8, top: 8 })
  6433. .aspectRatio(1)
  6434. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6435. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6436. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6437. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  6438. .animation({ duration: 500 }),
  6439. TransitionEffect.scale({ x: 0, y: 0 })))
  6440. .align(Alignment.Center)//
  6441. .clip(true)
  6442. .rotate({
  6443. x: 0,
  6444. y: 0,
  6445. z: 1,
  6446. angle: this.rotateAngle
  6447. })
  6448. .onClick(() => {
  6449. this.getImageColor()
  6450. })
  6451. this.musicNameInfo(false)
  6452. } else {
  6453. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6454. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:220):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  6455. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6456. .alt(this.imageLabel)
  6457. .margin({ right: 20, left: 20 })
  6458. .aspectRatio(1)
  6459. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6460. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6461. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6462. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  6463. .animation({ duration: 500 }),
  6464. TransitionEffect.scale({ x: 0, y: 0 })))
  6465. .align(Alignment.Center)//
  6466. .clip(true)
  6467. .rotate({
  6468. x: 0,
  6469. y: 0,
  6470. z: 1,
  6471. angle: this.rotateAngle
  6472. })
  6473. .onClick(() => {
  6474. this.getImageColor()
  6475. })
  6476. if (this.isPhoneLan()) {
  6477. Text(this.name)
  6478. .fontSize(18)
  6479. .fontWeight(FontWeight.Bold)
  6480. .margin({ top: 13 })
  6481. .textOverflow({ overflow: TextOverflow.Ellipsis })
  6482. .maxLines(1)
  6483. .width('99%')
  6484. .textAlign(TextAlign.Center)
  6485. .fontColor(Color.White)
  6486. }
  6487. }
  6488. }
  6489. // 唱针以左上角为点选择逆时针40度
  6490. Image($r('app.media.ic_music_cover_hand'))
  6491. .height(130)
  6492. .margin({ bottom: 220, top: 0 })
  6493. .align(Alignment.Top)
  6494. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  6495. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6496. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6497. Column({ space: 8 }) {
  6498. Text(this.name)
  6499. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  6500. .fontWeight(FontWeight.Bold)
  6501. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6502. .maxLines(1)
  6503. .width('48%')
  6504. .textAlign(TextAlign.Center)
  6505. .fontColor(Color.White)
  6506. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6507. Text(this.artist)
  6508. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  6509. .fontColor(Color.White)
  6510. .fontWeight(FontWeight.Bold)
  6511. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6512. }
  6513. .justifyContent(FlexAlign.Start)
  6514. .zIndex(1)
  6515. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  6516. }
  6517. .margin({
  6518. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  6519. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  6520. top: this.isCoverOpacity() ? 0 : 20
  6521. })
  6522. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  6523. this.SingleLyricView()
  6524. }
  6525. if (this.isPhoneLan()) {
  6526. Column() {
  6527. this.playProgressView()
  6528. }
  6529. .position({ left: 40, bottom: 48 })
  6530. } else {
  6531. this.BottomControl()
  6532. }
  6533. }
  6534. .width(CommonConstants.FULL_PERCENT)
  6535. .clip(true)
  6536. }
  6537. @Builder
  6538. private musicNameInfo(isHidden: boolean) {
  6539. Column({ space: 8 }) {
  6540. Text(this.name)
  6541. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  6542. .fontWeight(FontWeight.Bold)
  6543. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6544. .maxLines(1)
  6545. .width('99%')
  6546. .textAlign(TextAlign.Center)
  6547. .fontColor(Color.White)
  6548. Text(this.artist + ' ' + this.currentSong?.album)
  6549. .fontSize(this.isCoverOpacity() ? 12 : 15)
  6550. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6551. .fontColor(Color.White)
  6552. .textAlign(TextAlign.Center)
  6553. .width('99%')
  6554. .maxLines(1)
  6555. }
  6556. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  6557. .zIndex(1)
  6558. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  6559. }
  6560. @Builder
  6561. private PlayTitle() {
  6562. Row() {
  6563. Row() {
  6564. Image($r('app.media.ic_back_down'))
  6565. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  6566. .hitTestBehavior(HitTestMode.Transparent)
  6567. Text(this.name + ' ' + this.artist)
  6568. .fontColor(Color.White)
  6569. .fontSize($r('app.float.title_font_size'))
  6570. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6571. .maxLines(1)
  6572. .visibility(Visibility.None)
  6573. .margin({ left: 2, right: 30 })
  6574. }
  6575. .layoutWeight(1)
  6576. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6577. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  6578. .onClick(() => {
  6579. this.isShowPlay = false;
  6580. })
  6581. Column() {
  6582. AVCastPicker({
  6583. normalColor: Color.White,
  6584. onStateChange: this.onStateVastChange
  6585. })
  6586. .width(24)
  6587. .height(24)
  6588. }
  6589. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  6590. }
  6591. .width(PlayConstants.ROW_WIDTH)
  6592. }
  6593. @Builder
  6594. lyricSettingSheet(isPip: boolean) {
  6595. Scroll() {
  6596. this.lyricSetting(isPip)
  6597. }
  6598. .width('100%')
  6599. .height('100%')
  6600. }
  6601. @Builder
  6602. lyricSetting(isPip: boolean) {
  6603. Column() {
  6604. // 时间调节模块
  6605. if (!isPip) {
  6606. this.BuildTimeControls()
  6607. }
  6608. // 字号控制模块
  6609. this.BuildFontControls(isPip)
  6610. }
  6611. }
  6612. // 歌词时间偏移状态
  6613. @State timeOffset: number = 0.0
  6614. @State currentLyricColor: string = '#FFFFFF'
  6615. @State currentLyricColorPip: string = '#FFFFFF'
  6616. @State currentHighLightLyricColor: string = '#FF4081'
  6617. @State currentHighLightLyricColorPip: string = '#FF4081'
  6618. // 歌词字号状态
  6619. @State currentLyricSize: number = 20
  6620. @State currentLyricSizePip: number = 20
  6621. // 高亮歌词放大倍数
  6622. @State currentHightLyricSize: number = 1.2
  6623. @State currentHightLyricSizePip: number = 1.2
  6624. @State currentLyricLineSpace: number = 10
  6625. @State currentLyricLineSpacePip: number = 10
  6626. @State currentLyricAlignMode: number = 1
  6627. @State currentLyricAlignModePip: number = 1
  6628. @State blurDegree: number = 2
  6629. @State blurDegreePip: number = 2
  6630. @State isShowSelectColor: boolean = false
  6631. @State isShowHLSelectColor: boolean = false
  6632. @State isShowPipBgSelectColor: boolean = false
  6633. @State pipLyWidth: number = 330
  6634. @State pipLyHeight: number = 120
  6635. // 构建颜色选择器
  6636. @Builder
  6637. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  6638. Row({ space: 10 }) {
  6639. HSBColorPicker({
  6640. color: '#FFFFFF',
  6641. radius: 8,
  6642. layout: HSBColorPickerLayout.COLUMN,
  6643. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  6644. '#fa7105'],
  6645. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  6646. this.changeLyricColor(value, isPip, isBGPip)
  6647. })
  6648. .height(250)
  6649. .layoutWeight(1)
  6650. .padding(25)
  6651. }
  6652. .width('66%')
  6653. }
  6654. @State isOpenPip: boolean = false
  6655. @State pipBgIndex: number = 0
  6656. // 构建字号控制器
  6657. @Builder
  6658. BuildFontControls(isPip: boolean) {
  6659. Column() {
  6660. if (isPip) {
  6661. Column() {
  6662. Row() {
  6663. Text('悬浮歌词')
  6664. .margin({ left: 18 })
  6665. .fontSize(15)
  6666. .fontColor(Color.White)
  6667. .fontWeight(480)
  6668. .layoutWeight(1)
  6669. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  6670. .selectedColor(this.themeColor)
  6671. .switchPointColor(Color.White)
  6672. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6673. .margin({ right: 18 })
  6674. .onChange((checked: boolean) => {
  6675. this.isOpenPip = checked;
  6676. if (this.isOpenPip) {
  6677. this.startPip()
  6678. } else {
  6679. this.stopPip()
  6680. }
  6681. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  6682. })
  6683. .width(50)
  6684. .height(30);
  6685. }
  6686. .height(55)
  6687. }
  6688. .backgroundColor(Color.Transparent)
  6689. .borderRadius(15)
  6690. .margin({
  6691. left: 30,
  6692. right: 30,
  6693. top: 0,
  6694. bottom: 20
  6695. })
  6696. .padding(0)
  6697. .border({
  6698. color: Color.White,
  6699. width: 1.8
  6700. })
  6701. }
  6702. Row() {
  6703. Text(`歌词居中:`)
  6704. .fontSize(14)
  6705. .fontColor(Color.White)
  6706. .margin({ left: 2 })
  6707. Row() {
  6708. ForEach(['居中', '居左'], (size: string, index: number) => {
  6709. Button(size)
  6710. .width(60)
  6711. .height(28)
  6712. .fontSize(12)
  6713. .fontColor('#FFFFFF')
  6714. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  6715. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  6716. .border({
  6717. color: (!isPip && this.currentLyricAlignMode === index) ||
  6718. (isPip && this.currentLyricAlignModePip === index) ?
  6719. '#007DFF' : '#DDDDDD',
  6720. width: 1.8
  6721. })
  6722. .onClick(() => {
  6723. this.setLyricAlignMode(index, isPip)
  6724. })
  6725. .margin({ left: 10, right: 8 })
  6726. })
  6727. }
  6728. .width('76%')
  6729. Blank()
  6730. }
  6731. .margin({
  6732. top: 10,
  6733. bottom: 10,
  6734. right: 20,
  6735. left: 20
  6736. })
  6737. if (isPip) {
  6738. Row() {
  6739. Text(`悬浮背景:`)
  6740. .fontSize(14)
  6741. .fontColor(Color.White)
  6742. Select([
  6743. { value: CommonConstants.PIP_LYRIC_BG[0] },
  6744. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  6745. .font({ size: 13, weight: FontWeight.Medium })
  6746. .fontColor(Color.White)
  6747. .margin({ left: 10 })
  6748. .selected(this.pipBgIndex)
  6749. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  6750. .onSelect(async (_index: number, text?: string | undefined) => {
  6751. this.pipBgIndex = _index
  6752. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  6753. if (this.pipBgIndex === 0) {
  6754. if (this.cover) {
  6755. this.pipBg = this.cover
  6756. } else {
  6757. this.pipBg = this.imageColor
  6758. }
  6759. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6760. } else {
  6761. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6762. }
  6763. })
  6764. Column() {
  6765. }
  6766. .backgroundColor(this.pipBg)
  6767. .margin({ left: 10, right: 10 })
  6768. .borderRadius(20)
  6769. .height(28)
  6770. .width(28)
  6771. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6772. Row() {
  6773. SymbolGlyph($r('sys.symbol.paintbrush'))
  6774. .fontColor([Color.White])
  6775. .effectStrategy(1)
  6776. Text(`选择颜色`)
  6777. .fontSize(13)
  6778. .margin({ left: 10 })
  6779. .fontColor(Color.White)
  6780. }
  6781. }
  6782. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  6783. .backgroundColor(Color.Transparent)
  6784. .border({
  6785. color: '#FFFFFF',
  6786. radius: 20,
  6787. width: 1.8
  6788. })
  6789. .height(36)
  6790. .width(110)
  6791. .onClick(() => {
  6792. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  6793. })
  6794. .bindPopup(this.isShowPipBgSelectColor, {
  6795. builder: this.SelectColor(false, isPip, true),
  6796. placement: Placement.Top,
  6797. mask: { color: '#33000000' },
  6798. enableArrow: false, //是否显示箭头
  6799. showInSubWindow: false,
  6800. onStateChange: (e) => {
  6801. if (!e.isVisible) {
  6802. this.isShowPipBgSelectColor = false
  6803. }
  6804. }
  6805. })
  6806. }
  6807. .width('76%')
  6808. .margin({ bottom: 5, right: 45, left: 20 })
  6809. }
  6810. if (!isPip) {
  6811. Row() {
  6812. Text(`高亮居中:`)
  6813. .fontSize(14)
  6814. .fontColor(Color.White)
  6815. Column() {
  6816. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  6817. .selectedColor(this.themeColor)
  6818. .switchPointColor(Color.White)
  6819. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6820. .onChange((checked: boolean) => {
  6821. this.isHightLightCenter = checked;
  6822. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  6823. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6824. })
  6825. .width(50)
  6826. .height(30)
  6827. .alignSelf(ItemAlign.Start)
  6828. .margin({ left: 12 })
  6829. Blank()
  6830. }
  6831. .width('76%')
  6832. }
  6833. .margin({
  6834. left: 20,
  6835. right: 15,
  6836. top: 10,
  6837. bottom: 10
  6838. })
  6839. }
  6840. Row() {
  6841. Text(`歌词颜色:`)
  6842. .fontSize(14)
  6843. .fontColor(Color.White)
  6844. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6845. .fontSize(15)
  6846. .fontColor(Color.White)
  6847. .margin({ left: 12, right: 12 })
  6848. Column() {
  6849. }
  6850. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6851. .margin({ right: 12 })
  6852. .borderRadius(20)
  6853. .height(28)
  6854. .width(28)
  6855. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6856. Row() {
  6857. SymbolGlyph($r('sys.symbol.paintbrush'))
  6858. .fontColor([Color.White])
  6859. .effectStrategy(1)
  6860. Text(`选择颜色`)
  6861. .fontSize(13)
  6862. .margin({ left: 10 })
  6863. .fontColor(Color.White)
  6864. }
  6865. }
  6866. .backgroundColor(Color.Transparent)
  6867. .border({
  6868. color: '#FFFFFF',
  6869. radius: 20,
  6870. width: 1.8
  6871. })
  6872. .height(36)
  6873. .width(110)
  6874. .onClick(() => {
  6875. this.isShowSelectColor = !this.isShowSelectColor
  6876. })
  6877. .bindPopup(this.isShowSelectColor, {
  6878. builder: this.SelectColor(false, isPip),
  6879. placement: Placement.Top,
  6880. mask: { color: '#33000000' },
  6881. enableArrow: false, //是否显示箭头
  6882. showInSubWindow: false,
  6883. onStateChange: (e) => {
  6884. if (!e.isVisible) {
  6885. this.isShowSelectColor = false
  6886. }
  6887. }
  6888. })
  6889. }
  6890. .width('76%')
  6891. .margin({
  6892. top: 10,
  6893. bottom: 10,
  6894. right: 45,
  6895. left: 20
  6896. })
  6897. Row() {
  6898. Text(`高亮颜色:`)
  6899. .fontSize(14)
  6900. .fontColor(Color.White)
  6901. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6902. .fontSize(15)
  6903. .fontColor(Color.White)
  6904. .margin({ left: 12, right: 12 })
  6905. Column() {
  6906. }
  6907. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6908. .margin({ right: 12 })
  6909. .borderRadius(20)
  6910. .height(28)
  6911. .width(28)
  6912. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6913. Row() {
  6914. SymbolGlyph($r('sys.symbol.paintbrush'))
  6915. .fontColor([Color.White])
  6916. .effectStrategy(1)
  6917. Text(`选择颜色`)
  6918. .fontSize(13)
  6919. .margin({ left: 10 })
  6920. .fontColor(Color.White)
  6921. }
  6922. }
  6923. .backgroundColor(Color.Transparent)
  6924. .border({
  6925. color: '#FFFFFF',
  6926. radius: 20,
  6927. width: 1.8
  6928. })
  6929. .height(36)
  6930. .width(110)
  6931. .onClick(() => {
  6932. this.isShowHLSelectColor = !this.isShowHLSelectColor
  6933. })
  6934. .bindPopup(this.isShowHLSelectColor, {
  6935. builder: this.SelectColor(true, isPip),
  6936. placement: Placement.Top,
  6937. mask: { color: '#33000000' },
  6938. enableArrow: false, //是否显示箭头
  6939. showInSubWindow: false,
  6940. onStateChange: (e) => {
  6941. if (!e.isVisible) {
  6942. this.isShowHLSelectColor = false
  6943. }
  6944. }
  6945. })
  6946. }
  6947. .width('76%')
  6948. .margin({
  6949. top: 10,
  6950. bottom: 10,
  6951. right: 45,
  6952. left: 20
  6953. })
  6954. if (isPip) {
  6955. Row() {
  6956. Text(`显示宽度:`)
  6957. .fontSize(14)
  6958. .fontColor(Color.White)
  6959. Slider({
  6960. value: this.pipLyWidth,
  6961. min: 10,
  6962. max: 800,
  6963. step: 1,
  6964. style: SliderStyle.OutSet
  6965. })
  6966. .blockColor(this.themeColor)
  6967. .trackColor($r('app.color.speed_text_color'))
  6968. .selectedColor(Color.White)
  6969. .trackThickness(6)
  6970. .onChange((value: number) => {
  6971. this.pipLyWidth = value
  6972. if (this.pipController) {
  6973. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  6974. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  6975. }
  6976. })
  6977. .width('76%')
  6978. }
  6979. .margin({
  6980. left: 20,
  6981. right: 15,
  6982. top: 5,
  6983. bottom: 5
  6984. })
  6985. Row() {
  6986. Text(`显示高度:`)
  6987. .fontSize(14)
  6988. .fontColor(Color.White)
  6989. Slider({
  6990. value: this.pipLyHeight,
  6991. min: 10,
  6992. max: 1000,
  6993. step: 1,
  6994. style: SliderStyle.OutSet
  6995. })
  6996. .blockColor(this.themeColor)
  6997. .trackColor($r('app.color.speed_text_color'))
  6998. .selectedColor(Color.White)
  6999. .trackThickness(6)
  7000. .onChange((value: number) => {
  7001. this.pipLyHeight = value
  7002. if (this.pipController) {
  7003. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7004. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7005. }
  7006. })
  7007. .width('76%')
  7008. }
  7009. .margin({
  7010. left: 20,
  7011. right: 15,
  7012. top: 5,
  7013. bottom: 5
  7014. })
  7015. }
  7016. Row() {
  7017. Text(`歌词字号:`)
  7018. .fontSize(14)
  7019. .fontColor(Color.White)
  7020. Slider({
  7021. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7022. min: 12,
  7023. max: 30,
  7024. step: 0.1,
  7025. style: SliderStyle.OutSet
  7026. })
  7027. .blockColor(this.themeColor)
  7028. .trackColor($r('app.color.speed_text_color'))
  7029. .selectedColor(Color.White)
  7030. .trackThickness(6)
  7031. .onChange((value: number) => {
  7032. this.setLyricTextSize(value, isPip)
  7033. })
  7034. .width('76%')
  7035. }
  7036. .margin({
  7037. left: 20,
  7038. right: 15,
  7039. top: 5,
  7040. bottom: 5
  7041. })
  7042. Row() {
  7043. Text(`高亮倍数:`)
  7044. .fontSize(14)
  7045. .fontColor(Color.White)
  7046. Slider({
  7047. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7048. min: 1,
  7049. max: 2,
  7050. step: 0.1,
  7051. style: SliderStyle.OutSet
  7052. })
  7053. .blockColor(this.themeColor)
  7054. .trackColor($r('app.color.speed_text_color'))
  7055. .selectedColor(Color.White)
  7056. .trackThickness(6)
  7057. .onChange((value: number) => {
  7058. this.setHighLyricTextSize(value, isPip)
  7059. })
  7060. .width('76%')
  7061. }
  7062. .margin({
  7063. left: 20,
  7064. right: 15,
  7065. top: 5,
  7066. bottom: 5
  7067. })
  7068. Row() {
  7069. Text(`歌词间隙:`)
  7070. .fontSize(14)
  7071. .fontColor(Color.White)
  7072. Slider({
  7073. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7074. min: 2,
  7075. max: 120,
  7076. step: 1,
  7077. style: SliderStyle.OutSet
  7078. })
  7079. .blockColor(this.themeColor)
  7080. .trackColor($r('app.color.speed_text_color'))
  7081. .selectedColor(Color.White)
  7082. .trackThickness(6)
  7083. .onChange((value: number) => {
  7084. this.setLyricLineSpace(value, isPip)
  7085. })
  7086. .width('76%')
  7087. }
  7088. .margin({
  7089. left: 20,
  7090. right: 15,
  7091. top: 5,
  7092. bottom: 5
  7093. })
  7094. //取值间隔为100,默认为400,取值越大,字体越粗
  7095. Row() {
  7096. Text(`歌词字重:`)
  7097. .fontSize(14)
  7098. .fontColor(Color.White)
  7099. Slider({
  7100. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7101. min: 100,
  7102. max: 900,
  7103. step: 100,
  7104. style: SliderStyle.OutSet
  7105. })
  7106. .blockColor(this.themeColor)
  7107. .trackColor($r('app.color.speed_text_color'))
  7108. .selectedColor(Color.White)
  7109. .trackThickness(6)
  7110. .onChange((value: number) => {
  7111. if (isPip) {
  7112. this.lyricTextWeightPip = value
  7113. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7114. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7115. } else {
  7116. this.lyricTextWeight = value
  7117. this.lyricController.setTextWeight(this.lyricTextWeight)
  7118. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7119. }
  7120. })
  7121. .width('76%')
  7122. }
  7123. .margin({
  7124. left: 20,
  7125. right: 15,
  7126. top: 5,
  7127. bottom: 5
  7128. })
  7129. if (!isPip) {
  7130. Row() {
  7131. Text(`歌词模糊:`)
  7132. .fontSize(14)
  7133. .fontColor(Color.White)
  7134. Slider({
  7135. value: isPip ? this.blurDegreePip : this.blurDegree,
  7136. min: 0,
  7137. max: 10,
  7138. step: 0.1,
  7139. style: SliderStyle.OutSet
  7140. })
  7141. .blockColor(this.themeColor)
  7142. .trackColor($r('app.color.speed_text_color'))
  7143. .selectedColor(Color.White)
  7144. .trackThickness(6)
  7145. .onChange((value: number) => {
  7146. this.setBlurDegree(value, isPip)
  7147. })
  7148. .width('76%')
  7149. }
  7150. .margin({
  7151. left: 20,
  7152. right: 15,
  7153. top: 5,
  7154. bottom: 15
  7155. })
  7156. }
  7157. Row() {
  7158. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7159. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7160. }
  7161. .justifyContent(FlexAlign.Center)
  7162. .margin({ top: 3, bottom: 10 })
  7163. }
  7164. }
  7165. private setBlurDegree(index: number, isPip: boolean) {
  7166. if (isPip) {
  7167. this.blurDegreePip = index
  7168. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7169. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7170. } else {
  7171. this.blurDegree = index
  7172. this.lyricController.setBlurDegree(this.blurDegree)
  7173. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7174. }
  7175. }
  7176. private setLyricAlignMode(index: number, isPip: boolean) {
  7177. if (isPip) {
  7178. this.currentLyricAlignModePip = index
  7179. if (this.currentLyricAlignModePip === 1) {
  7180. this.lyricControllerXF.setAlignMode("left")
  7181. } else {
  7182. this.lyricControllerXF.setAlignMode("center")
  7183. }
  7184. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7185. } else {
  7186. this.currentLyricAlignMode = index
  7187. if (this.currentLyricAlignMode === 1) {
  7188. this.lyricController.setAlignMode("left")
  7189. } else {
  7190. this.lyricController.setAlignMode("center")
  7191. }
  7192. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7193. }
  7194. }
  7195. private setLyricTextSize(index: number, isPip: boolean) {
  7196. if (isPip) {
  7197. this.currentLyricSizePip = index
  7198. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7199. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7200. } else {
  7201. this.currentLyricSize = index
  7202. this.lyricController.setTextSize(this.currentLyricSize)
  7203. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7204. }
  7205. }
  7206. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7207. if (isPip) {
  7208. this.currentHightLyricSizePip = scale
  7209. this.lyricControllerXF
  7210. .setHighlightScale(this.currentHightLyricSizePip)
  7211. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7212. } else {
  7213. this.currentHightLyricSize = scale
  7214. this.lyricController
  7215. .setHighlightScale(this.currentHightLyricSize)
  7216. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7217. }
  7218. }
  7219. private setLyricLineSpace(index: number, isPip: boolean) {
  7220. if (isPip) {
  7221. this.currentLyricLineSpacePip = index
  7222. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7223. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7224. } else {
  7225. this.currentLyricLineSpace = index
  7226. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7227. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7228. }
  7229. }
  7230. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7231. LogUtil.info('onecold isBG = ' + isBG)
  7232. if (isBG) { //如果是设置悬浮背景
  7233. this.pipBg = color
  7234. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7235. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7236. return
  7237. }
  7238. if (isPip) {
  7239. this.currentLyricColorPip = color
  7240. this.lyricControllerXF
  7241. .setTextColor(this.currentLyricColorPip)
  7242. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7243. } else {
  7244. this.currentLyricColor = color
  7245. this.lyricController
  7246. .setTextColor(this.currentLyricColor)
  7247. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7248. }
  7249. }
  7250. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7251. if (isPip) {
  7252. this.currentHighLightLyricColorPip = color
  7253. this.lyricControllerXF
  7254. .setHighlightColor(this.currentHighLightLyricColorPip)
  7255. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7256. } else {
  7257. this.currentHighLightLyricColor = color
  7258. this.lyricController
  7259. .setHighlightColor(this.currentHighLightLyricColor)
  7260. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7261. }
  7262. }
  7263. // 构建时间控制器
  7264. @Builder
  7265. BuildTimeControls() {
  7266. Column() {
  7267. // 时间显示
  7268. Text(this.getTimeText())
  7269. .fontSize(18)
  7270. .fontColor(Color.White)
  7271. .margin({ bottom: 10 })
  7272. Row() {
  7273. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  7274. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  7275. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  7276. }
  7277. .justifyContent(FlexAlign.Center)
  7278. }
  7279. .margin({ top: 12, bottom: 8 })
  7280. }
  7281. // 精度按钮组件
  7282. @Builder
  7283. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  7284. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7285. Column() {
  7286. Image(icon)
  7287. .width(28)
  7288. .margin({ bottom: 5 })
  7289. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  7290. Text(label)
  7291. .fontSize(12)
  7292. .fontColor('#FFFFFF')
  7293. }
  7294. }
  7295. .backgroundColor(Color.Transparent)
  7296. .enabled(!this.isButtonDisabled(step))
  7297. .onClick(() => this.handlePrecisionAdjust(step))
  7298. .padding(5)
  7299. .width(66)
  7300. .height(66)
  7301. .margin({ left: 18, right: 18 })
  7302. .border({
  7303. color: '#FFFFFF',
  7304. width: 1.8
  7305. })
  7306. }
  7307. private handlePrecisionAdjust(step: number) {
  7308. if (step === 0) {
  7309. this.timeOffset = 0
  7310. return
  7311. }
  7312. // 精度处理:保留1位小数
  7313. const newOffset = Number((this.timeOffset + step).toFixed(5))
  7314. // 边界保护(±15.0秒)
  7315. if (newOffset < -30.0 || newOffset > 30.0) {
  7316. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  7317. return
  7318. }
  7319. // 状态更新
  7320. this.timeOffset = newOffset
  7321. }
  7322. // 按钮禁用逻辑
  7323. private isButtonDisabled(step: number): boolean {
  7324. const futureOffset = this.timeOffset + step
  7325. return (futureOffset < -30.0) || (futureOffset > 30.0)
  7326. }
  7327. // 时间显示文本升级
  7328. private getTimeText(): string {
  7329. const absValue = Math.abs(this.timeOffset)
  7330. return this.timeOffset === 0
  7331. ? '歌词时间已重置'
  7332. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  7333. }
  7334. // 导入 本地歌词 搜索歌词
  7335. @Builder
  7336. pushLyricButton(icon: Resource, step: number, label: string) {
  7337. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7338. Row() {
  7339. Image(icon)
  7340. .width(14)
  7341. .margin({ left: 13 })
  7342. Text(label)
  7343. .fontSize(12)
  7344. .margin({ left: 6 })
  7345. .fontColor('#FFFFFF')
  7346. }
  7347. }
  7348. .onClick(() => {
  7349. switch (step) {
  7350. case 0:
  7351. this.callFilePickerSelectFileForLyric()
  7352. break;
  7353. case 1:
  7354. //判断是不是赞助会员
  7355. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  7356. this.isLyricSetting = false
  7357. this.showTipsDialog()
  7358. return
  7359. }
  7360. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7361. ToastUtil.showToast('正在获取')
  7362. this.isLyricSetting = false
  7363. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7364. this.initLyric(lyricPath, true);
  7365. }
  7366. break;
  7367. }
  7368. })
  7369. .padding(5)
  7370. .width(110)
  7371. .backgroundColor(Color.Transparent)
  7372. .height(40)
  7373. .margin({ left: 6, right: 6 })
  7374. .border({
  7375. color: '#FFFFFF',
  7376. radius: 20,
  7377. width: 1.8
  7378. })
  7379. }
  7380. showVipDialog() {
  7381. DialogHelper.showCustomContentDialog({
  7382. dialogId: 'vip',
  7383. title: "友情提示",
  7384. autoCancel: false, //点击遮障层时,不关闭弹窗
  7385. backCancel: true, //点击返回键,不关闭弹窗
  7386. contentBuilder: () => {
  7387. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  7388. },
  7389. buttons: [],
  7390. })
  7391. }
  7392. //去赞助的自定义内容
  7393. @Builder
  7394. customVipBuilder(content: string) {
  7395. Column() {
  7396. Text(content)
  7397. .fontColor(Color.Gray)
  7398. .fontSize(16)
  7399. .alignSelf(ItemAlign.Start)
  7400. .margin({ bottom: 15 })
  7401. .fontSize(16)
  7402. Row() {
  7403. Button('取消')
  7404. .fontColor(Color.White)
  7405. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7406. .height(50)
  7407. .layoutWeight(1)
  7408. .stateEffect(true)
  7409. .margin({ right: 6 })
  7410. .onClick(() => {
  7411. DialogHelper.closeDialog('vip'); //关闭弹框
  7412. })
  7413. Button('开通')
  7414. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7415. .layoutWeight(1)
  7416. .height(50)
  7417. .backgroundColor(this.themeColor)
  7418. .stateEffect(true)
  7419. .margin({ left: 6 })
  7420. .onClick(() => {
  7421. DialogHelper.closeDialog('vip'); //关闭弹框
  7422. this.isShowPlay = false
  7423. this.mType = 1 //跳转到用户中心
  7424. // router.pushUrl({
  7425. // url: 'pages/VipPage'
  7426. // }, router.RouterMode.Single);
  7427. })
  7428. }
  7429. }
  7430. .width("100%")
  7431. .padding(10)
  7432. }
  7433. showTipsDialog() {
  7434. DialogHelper.showCustomContentDialog({
  7435. dialogId: 'tips',
  7436. title: "友情提示",
  7437. autoCancel: false, //点击遮障层时,不关闭弹窗
  7438. backCancel: true, //点击返回键,不关闭弹窗
  7439. contentBuilder: () => {
  7440. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  7441. },
  7442. buttons: [],
  7443. })
  7444. }
  7445. @Builder
  7446. customTipsBuilder(content: string) {
  7447. Column() {
  7448. Text(content)
  7449. .fontColor(Color.Gray)
  7450. .fontSize(16)
  7451. .alignSelf(ItemAlign.Start)
  7452. .margin({ bottom: 15 })
  7453. .fontSize(16)
  7454. Row() {
  7455. Button('取消')
  7456. .fontColor(Color.White)
  7457. .backgroundColor(this.themeColor)
  7458. .height(50)
  7459. .layoutWeight(1)
  7460. .stateEffect(true)
  7461. .margin({ right: 6 })
  7462. .onClick(() => {
  7463. DialogHelper.closeDialog('tips'); //关闭弹框
  7464. })
  7465. Button('跳转')
  7466. .fontColor(Color.White)//
  7467. .layoutWeight(1)
  7468. .height(50)
  7469. .backgroundColor(this.themeColor)
  7470. .stateEffect(true)
  7471. .margin({ left: 6 })
  7472. .onClick(() => {
  7473. DialogHelper.closeDialog('tips'); //关闭弹框
  7474. this.isShowPlay = false
  7475. this.mType = 3
  7476. // router.pushUrl({
  7477. // url: 'pages/SettingPage'
  7478. // }, router.RouterMode.Single);
  7479. })
  7480. }
  7481. }
  7482. .width("100%")
  7483. .padding(10)
  7484. }
  7485. @Builder
  7486. PlayMoreSheet() {
  7487. Column() {
  7488. this.MoreList()
  7489. }
  7490. .width('100%')
  7491. .height('100%')
  7492. }
  7493. @Builder
  7494. MoreList() {
  7495. Scroll() {
  7496. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7497. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  7498. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7499. Row() {
  7500. if (more.id === 3&&this.currentSong) {
  7501. Image(more.image)
  7502. .width(24)
  7503. .height(24)
  7504. .margin({ left: 10, right: 10 })
  7505. Text(more.title)
  7506. .fontSize(16)
  7507. .fontColor(Color.White)
  7508. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  7509. height: this.isCoverOpacity() ? '95%' : '95%',
  7510. dragBar: true,
  7511. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7512. showClose: true,
  7513. blurStyle: BlurStyle.Thin,
  7514. backgroundColor: Color.Transparent,
  7515. title: { title: '歌曲信息' }
  7516. })
  7517. } else if (more.id === 15 && this.currentSong) { //编辑信息
  7518. Image(more.image)
  7519. .width(24)
  7520. .height(24)
  7521. .margin({ left: 10, right: 10 })
  7522. Text(more.title)
  7523. .fontSize(16)
  7524. .fontColor(Color.White)
  7525. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  7526. height: this.isCoverOpacity() ? '95%' : '93%',
  7527. dragBar: true,
  7528. showClose: true,
  7529. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7530. // blurStyle:BlurStyle.Thin,
  7531. // backgroundColor:Color.Transparent,
  7532. title: { title: '编辑信息' }
  7533. })
  7534. } else if (more.id === 5) { //定时关闭
  7535. Image(more.image)
  7536. .width(24)
  7537. .height(24)
  7538. .margin({ left: 10, right: 10 })
  7539. Text(more.title)
  7540. .fontSize(16)
  7541. .fontColor(Color.White)
  7542. .onClick(() => {
  7543. this.doMore(more.id)
  7544. })
  7545. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  7546. height: this.isCoverOpacity() ? '95%' : '95%',
  7547. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7548. dragBar: true,
  7549. showClose: true,
  7550. title: { title: $r('app.string.time_close') }
  7551. })
  7552. } else if (more.id === 2) { //歌词设置
  7553. Image(more.image)
  7554. .width(24)
  7555. .height(24)
  7556. .margin({ left: 10, right: 10 })
  7557. Text(more.title)
  7558. .fontSize(16)
  7559. .fontColor(Color.White)
  7560. } else if (more.id === 16) { //悬浮歌词设置
  7561. Image(more.image)
  7562. .width(24)
  7563. .height(24)
  7564. .margin({ left: 10, right: 10 })
  7565. Text(more.title)
  7566. .fontSize(16)
  7567. .fontColor(Color.White)
  7568. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  7569. height: this.isCoverOpacity() ? '95%' : '95%',
  7570. dragBar: true,
  7571. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7572. showClose: true,
  7573. blurStyle: BlurStyle.Thin,
  7574. backgroundColor: Color.Transparent,
  7575. title: { title: '悬浮歌词' }
  7576. })
  7577. } else if (more.id === 11) {
  7578. Image(more.image)
  7579. .width(24)
  7580. .height(24)
  7581. .margin({ left: 10, right: 10 })
  7582. Text(more.title)
  7583. .fontSize(16)
  7584. .fontColor(Color.White)
  7585. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  7586. height: this.isCoverOpacity() ? '95%' : '60%',
  7587. dragBar: true,
  7588. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7589. showClose: true,
  7590. blurStyle: BlurStyle.Thin,
  7591. backgroundColor: Color.Transparent,
  7592. title: { title: '跳过头尾' }
  7593. })
  7594. } else if (more.id === 12) { //投播
  7595. AVCastPicker({
  7596. customPicker: (): void => this.TPImageBuilder(more),
  7597. onStateChange: (state) => {
  7598. if (state == AVCastPickerState.STATE_APPEARING) {
  7599. console.log(' The picker starts showing.');
  7600. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  7601. console.log(' The picker finishes presenting.');
  7602. }
  7603. },
  7604. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  7605. sessionType: 'video'
  7606. })
  7607. .id('AVCastPicker')
  7608. } else {
  7609. Image(more.image)
  7610. .width(24)
  7611. .height(24)
  7612. .margin({ left: 10, right: 10 })
  7613. .onClick(() => {
  7614. this.doMore(more.id)
  7615. })
  7616. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  7617. .fontSize(16)
  7618. .fontColor(Color.White)
  7619. .onClick(() => {
  7620. this.doMore(more.id)
  7621. })
  7622. Select([//倍速
  7623. { value: '0.25x' },
  7624. { value: '0.5x' },
  7625. { value: '0.75x' },
  7626. { value: '1x' },
  7627. { value: '1.25x' },
  7628. { value: '1.5x' },
  7629. { value: '1.75x' },
  7630. { value: '2x' },
  7631. { value: '3x' }])
  7632. .font({ size: 16, weight: FontWeight.Medium })
  7633. .fontColor($r('sys.color.white'))
  7634. .margin({ left: 25 })
  7635. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  7636. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  7637. .value(Utility.optimizedFormat(this.playSpeed))
  7638. .onSelect(async (_index: number, text?: string | undefined) => {
  7639. let speed = parseFloat(text?.replace('x', '') || '1');
  7640. if (!CommonConstants.video_speed_list.includes(speed)) {
  7641. speed = 1;
  7642. }
  7643. this.playSpeed = speed
  7644. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7645. })
  7646. Slider({
  7647. value: this.volume,
  7648. min: 0,
  7649. max: 1,
  7650. step: 0.1,
  7651. style: SliderStyle.OutSet
  7652. })
  7653. .margin({ left: 18, right: 8 })
  7654. .blockColor(this.themeColor)
  7655. .trackColor($r('app.color.speed_text_color'))
  7656. .selectedColor(Color.White)
  7657. .trackThickness(9)
  7658. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  7659. .onChange((value: number) => {
  7660. this.volume = value;
  7661. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  7662. PreferencesUtil.putSync('DefalutVolume',this.volume)
  7663. })
  7664. .layoutWeight(1)
  7665. Blank()
  7666. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  7667. .selectedColor(this.themeColor)
  7668. .switchPointColor(Color.White)
  7669. .margin({ right: 15 })
  7670. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7671. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  7672. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7673. if (more.id == 6) {
  7674. this.isMusicMemoryPlay = checked;
  7675. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  7676. if (this.isMusicMemoryPlay) {
  7677. ToastUtil.showToast('记忆播放已开启')
  7678. } else {
  7679. ToastUtil.showToast('记忆播放已关闭')
  7680. }
  7681. }
  7682. })
  7683. .width(48)
  7684. .height(24);
  7685. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  7686. .selectedColor(this.themeColor)
  7687. .switchPointColor(Color.White)
  7688. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7689. .margin({ right: 15 })
  7690. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  7691. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7692. if (more.id == 7) {
  7693. this.isMusicBGCover = checked;
  7694. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  7695. if (this.isMusicBGCover) {
  7696. ToastUtil.showToast('播放背景随音乐封面已开启')
  7697. } else {
  7698. ToastUtil.showToast('播放背景随音乐封面已关闭')
  7699. }
  7700. }
  7701. })
  7702. .width(48)
  7703. .height(24);
  7704. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  7705. .selectedColor(this.themeColor)
  7706. .switchPointColor(Color.White)
  7707. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7708. .margin({ right: 15 })
  7709. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  7710. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7711. if (more.id == 8) {
  7712. this.isSavePlayMode = checked;
  7713. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  7714. if (this.isSavePlayMode) {
  7715. ToastUtil.showToast('保存播放模式已开启')
  7716. } else {
  7717. ToastUtil.showToast('保存播放模式已关闭')
  7718. }
  7719. }
  7720. })
  7721. .width(48)
  7722. .height(24);
  7723. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  7724. .selectedColor(this.themeColor)
  7725. .switchPointColor(Color.White)
  7726. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7727. .margin({ right: 15 })
  7728. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  7729. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7730. if (more.id == 13) {
  7731. this.isCoverRectangle = checked;
  7732. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  7733. if (this.isCoverRectangle) {
  7734. ToastUtil.showToast('封面方形已开启')
  7735. this.animationRoFun()
  7736. } else {
  7737. ToastUtil.showToast('封面圆形已开启')
  7738. this.animationRoFun()
  7739. }
  7740. }
  7741. })
  7742. .width(48)
  7743. .height(24);
  7744. }
  7745. }
  7746. .width('100%')
  7747. .height(45)
  7748. .padding(15)
  7749. .backgroundColor(Color.Transparent)
  7750. .borderRadius(12)
  7751. .margin({ bottom: 6 })
  7752. }
  7753. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  7754. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7755. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  7756. .backgroundColor(Color.Transparent)
  7757. .onClick(() => {
  7758. this.doMore(more.id)
  7759. })
  7760. });
  7761. }
  7762. .width('100%')
  7763. .padding(16)
  7764. }.margin({ bottom: 18 })
  7765. }
  7766. @Builder
  7767. TPImageBuilder(more: MoreItem): void {
  7768. Row() {
  7769. Image($r('app.media.tuoping'))
  7770. .width(22)
  7771. .height(22)
  7772. .margin({ left: 10, right: 10 })
  7773. Text(more.title)
  7774. .fontSize(16)
  7775. .fontColor(Color.White)
  7776. }
  7777. .width('100%')
  7778. .layoutWeight(1)
  7779. .alignItems(VerticalAlign.Center)
  7780. .justifyContent(FlexAlign.Start)
  7781. }
  7782. private moreItems: MoreItem[] = [
  7783. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  7784. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  7785. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  7786. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  7787. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  7788. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  7789. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  7790. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  7791. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  7792. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  7793. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  7794. { id: 4, image: $r('app.media.share2'), title: '分享' },
  7795. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  7796. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  7797. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  7798. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  7799. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  7800. ];
  7801. @State isShowMoreView: boolean = false;
  7802. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  7803. @State isShowTimeCloseMore: boolean = false
  7804. @State isShowDetailMore: boolean = false
  7805. @State isMusicBGCover: boolean = true
  7806. @State isSavePlayMode: boolean = true
  7807. @State isLyricSetting: boolean = false
  7808. @State isJumpSetting: boolean = false
  7809. @State isShowEdit: boolean = false
  7810. @State showPipLyric: boolean = false
  7811. async setRingTone() {
  7812. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  7813. return
  7814. }
  7815. // 确定后的逻辑
  7816. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  7817. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  7818. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  7819. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  7820. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  7821. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  7822. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  7823. , this.videoUrl, this.name).then(res => {
  7824. LogUtil.info('onecold setFlag :' + res);
  7825. });
  7826. }
  7827. doMore(moreId: number) {
  7828. switch (moreId) {
  7829. case 2: //歌词
  7830. this.isLyricSetting = !this.isLyricSetting;
  7831. this.isShowMoreView = false
  7832. break;
  7833. case 3: //详情
  7834. this.isShowDetailMore = !this.isShowDetailMore;
  7835. break;
  7836. case 4: //分享
  7837. if (this.currentSong !== undefined) {
  7838. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  7839. }
  7840. this.isShowMoreView = false
  7841. break;
  7842. case 5: //定时关闭
  7843. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  7844. break;
  7845. case 10: //设为铃声
  7846. this.setRingTone()
  7847. this.isShowMoreView = false
  7848. break;
  7849. case 11: //跳过头尾
  7850. this.isJumpSetting = !this.isJumpSetting;
  7851. break;
  7852. case 13: //倍速
  7853. break;
  7854. case 14: //搜索封面
  7855. if (this.currentSong !== undefined) {
  7856. this.doSearchCover(this.currentSong)
  7857. }
  7858. this.isShowMoreView = false
  7859. break;
  7860. case 15: //编辑信息
  7861. this.isShowEdit = !this.isShowEdit;
  7862. break;
  7863. case 16: //悬浮歌词
  7864. this.showPipLyric = !this.showPipLyric;
  7865. break;
  7866. case 17: //横屏模式
  7867. if (this.isLandscape) {
  7868. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  7869. } else {
  7870. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  7871. }
  7872. this.isShowMoreView = false
  7873. break;
  7874. }
  7875. }
  7876. /**
  7877. * 切换横竖屏
  7878. *
  7879. */
  7880. setOrientation(orientation: number) {
  7881. this.windowClass.setPreferredOrientation(orientation).then(() => {
  7882. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  7883. }).catch((err: BusinessError) => {
  7884. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  7885. });
  7886. }
  7887. /**
  7888. * 画中画功能(悬浮歌词功能)
  7889. *
  7890. */
  7891. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  7892. pipController?: PiPWindow.PiPController;
  7893. navigationId: string = '';
  7894. @State curState: string = '';
  7895. @State curError: ResourceStr = '';
  7896. @State pipBg: string = '#E8E8E8'
  7897. @State buttonAction: string = '';
  7898. //开启画中画功能
  7899. async startPip() {
  7900. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  7901. if (!this.pipController) {
  7902. await this.createPipController();
  7903. }
  7904. if (!this.pipController) {
  7905. Logger.info(`[${TAG}] pipController create error`);
  7906. return;
  7907. }
  7908. await this.pipController.startPiP();
  7909. }
  7910. async stopPip() {
  7911. if (!this.pipController) {
  7912. Logger.info(`[${TAG}] pipController is not exist`);
  7913. return;
  7914. }
  7915. this.isOpenPip = false
  7916. await this.pipController.stopPiP();
  7917. }
  7918. async createPipController() {
  7919. this.pipController = await PiPWindow.create({
  7920. context: getContext(this),
  7921. componentController: this.xcomponentController,
  7922. navigationId: this.navigationId,
  7923. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  7924. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  7925. customUIController: this.nodeController,
  7926. });
  7927. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  7928. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  7929. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7930. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  7931. this.onStateChange(state, reason);
  7932. });
  7933. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  7934. this.onActionEvent(event, status);
  7935. });
  7936. }
  7937. destroyPipController() {
  7938. if (!this.pipController) {
  7939. return;
  7940. }
  7941. this.pipController.off('stateChange');
  7942. this.pipController.off('controlPanelActionEvent');
  7943. this.pipController = undefined;
  7944. }
  7945. onStateChange(state: PiPWindow.PiPState, reason: string) {
  7946. switch (state) {
  7947. case PiPWindow.PiPState.ABOUT_TO_START:
  7948. this.curState = 'ABOUT_TO_START';
  7949. this.curError = $r('app.string.current_error_hint');
  7950. break;
  7951. case PiPWindow.PiPState.STARTED:
  7952. this.curState = 'STARTED';
  7953. this.curError = $r('app.string.current_error_hint');
  7954. break;
  7955. case PiPWindow.PiPState.ABOUT_TO_STOP:
  7956. this.curState = 'ABOUT_TO_STOP';
  7957. this.curError = $r('app.string.current_error_hint');
  7958. break;
  7959. case PiPWindow.PiPState.STOPPED:
  7960. this.curState = 'STOPPED';
  7961. this.curError = $r('app.string.current_error_hint');
  7962. this.stopPip()
  7963. this.destroyPipController()
  7964. break;
  7965. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  7966. this.curState = 'ABOUT_TO_RESTORE';
  7967. this.curError = $r('app.string.current_error_hint');
  7968. break;
  7969. case PiPWindow.PiPState.ERROR:
  7970. this.curState = 'ERROR';
  7971. this.curError = reason;
  7972. break;
  7973. default:
  7974. break;
  7975. }
  7976. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  7977. }
  7978. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  7979. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  7980. switch (event) {
  7981. case 'playbackStateChanged':
  7982. if (status === 0) {
  7983. this.pause();
  7984. } else {
  7985. this.startPlayOrResumePlay();
  7986. }
  7987. break;
  7988. case 'nextVideo':
  7989. // 切换到下一个视频
  7990. this.playNext()
  7991. break;
  7992. case 'previousVideo':
  7993. // 切换到上一个视频
  7994. this.playPrevious()
  7995. break;
  7996. case 'previousVideo':
  7997. // 切换到上一个视频
  7998. this.playPrevious()
  7999. break;
  8000. default:
  8001. }
  8002. this.buttonAction = event + `-status:${status}`;
  8003. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8004. }
  8005. /**
  8006. * 画中画功能(悬浮歌词功能)结束
  8007. *
  8008. */
  8009. doSearchCover(item: VideoItem) {
  8010. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8011. this.isShowMoreView = false
  8012. this.showTipsDialog()
  8013. return
  8014. }
  8015. if (item !== undefined) {
  8016. let artist = item?.artist
  8017. if (StrUtil.isEmpty(artist) || artist === undefined) {
  8018. artist = ''
  8019. }
  8020. this.searchCover(item, item.name, artist)
  8021. }
  8022. }
  8023. searchCover(item: VideoItem, title: string, artist: string) {
  8024. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8025. LogUtil.debug("onecold res =" + res)
  8026. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8027. if (item.filePath == this.currentSong?.filePath) {
  8028. this.cover = res
  8029. if (this.currentSong) {
  8030. this.currentSong.pixelMapPath = res
  8031. }
  8032. }
  8033. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8034. if (success) {
  8035. this.doUpdateData()
  8036. console.log(" onecold 更新音乐封面成功,数据库已同步");
  8037. } else {
  8038. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  8039. }
  8040. });
  8041. LogUtil.debug("onecold this.cover =" + this.cover)
  8042. }
  8043. })
  8044. }
  8045. @State jumpTopTime: number = 0
  8046. @State jumpEndTime: number = 0
  8047. @State isOpenJump: boolean = false
  8048. @Builder
  8049. JumpTopEndSheet() {
  8050. Scroll() {
  8051. Column() {
  8052. Column() {
  8053. Text('仅对本播放列表有效')
  8054. .fontSize(16)
  8055. .fontColor($r('app.color.text_color'))
  8056. // 跳过头尾
  8057. Column() {
  8058. Row() {
  8059. Text('跳过片头:')
  8060. .fontSize(16)
  8061. .fontColor($r('app.color.text_color'))
  8062. Text(this.jumpTopTime + 's')
  8063. .fontSize(16)
  8064. .fontColor($r('app.color.text_color'))
  8065. }
  8066. .margin({ bottom: 5 })
  8067. Row() {
  8068. Slider({
  8069. value: this.jumpTopTime,
  8070. min: 0,
  8071. max: 120,
  8072. step: 1,
  8073. style: SliderStyle.OutSet
  8074. })
  8075. .blockColor(this.themeColor)
  8076. .trackColor($r('app.color.speed_text_color'))
  8077. .selectedColor(Color.White)
  8078. .trackThickness(8)
  8079. .onChange((value: number) => {
  8080. this.jumpTopTime = value;
  8081. })
  8082. .width('85%')
  8083. }
  8084. .alignItems(VerticalAlign.Top)
  8085. }
  8086. .margin({ top: 10, bottom: 10 })
  8087. // 跳过头尾
  8088. Column() {
  8089. Row() {
  8090. Text('跳过片尾:')
  8091. .fontSize(16)
  8092. .fontColor($r('app.color.text_color'))
  8093. Text(this.jumpEndTime + 's')
  8094. .fontSize(16)
  8095. .fontColor($r('app.color.text_color'))
  8096. }
  8097. .margin({ bottom: 5 })
  8098. Row() {
  8099. Slider({
  8100. value: this.jumpEndTime,
  8101. min: 0,
  8102. max: 120,
  8103. step: 1,
  8104. style: SliderStyle.OutSet
  8105. })
  8106. .blockColor(this.themeColor)
  8107. .trackColor($r('app.color.speed_text_color'))
  8108. .selectedColor(Color.White)
  8109. .trackThickness(8)
  8110. .onChange((value: number) => {
  8111. this.jumpEndTime = value;
  8112. })
  8113. .width('85%')
  8114. }
  8115. .alignItems(VerticalAlign.Top)
  8116. }
  8117. .margin({ top: 10, bottom: 10 })
  8118. Row() {
  8119. Button('保存设置')
  8120. .fontColor(Color.White)
  8121. .layoutWeight(1)
  8122. .height(40)
  8123. .width(80)
  8124. .backgroundColor(this.themeColor)
  8125. .stateEffect(true)
  8126. .margin({ left: 0, bottom: 20 })
  8127. .onClick(async () => {
  8128. if (!Utility.isNoble()) {
  8129. this.isJumpSetting = false
  8130. this.isShowMoreView = false
  8131. this.showVipDialog()
  8132. return
  8133. }
  8134. if (this.currentSong === undefined) {
  8135. return
  8136. }
  8137. if (this.modeType === 0) {
  8138. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8139. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8140. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8141. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8142. } else if (this.modeType === 1) { //媒体库
  8143. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8144. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8145. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8146. } else if (this.modeType === 2) { //艺术家
  8147. if (this.currentSong?.artist) {
  8148. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8149. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8150. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8151. }
  8152. } else if (this.modeType === 3) { //专辑
  8153. if (this.currentSong?.album) {
  8154. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8155. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8156. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8157. }
  8158. }
  8159. ToastUtil.showShort("保存成功")
  8160. this.isJumpSetting = false
  8161. })
  8162. }
  8163. .margin({
  8164. left: 38,
  8165. right: 38,
  8166. top: 10,
  8167. bottom: 10
  8168. })
  8169. .width(120)
  8170. .height(50)
  8171. }
  8172. }
  8173. }
  8174. .width('100%')
  8175. .height('100%')
  8176. }
  8177. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8178. private onStateVastChange(state: AVCastPickerState) {
  8179. if (state == AVCastPickerState.STATE_APPEARING) {
  8180. console.log('The picker starts showing.');
  8181. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8182. console.log('The picker finishes presenting.');
  8183. }
  8184. }
  8185. private showSelectLyric() {
  8186. DialogHelper.showActionSheetDialog({
  8187. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  8188. // sheets: ["本地歌词", "搜索歌词"],
  8189. sheets: [
  8190. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  8191. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  8192. ],
  8193. maskColor: Color.Transparent,
  8194. backgroundColor: $r('app.color.bg_card'),
  8195. transition: AnimationHelper.transitionInDown(666),
  8196. onAction: (index) => {
  8197. switch (index) {
  8198. case 0:
  8199. this.callFilePickerSelectFileForLyric()
  8200. break;
  8201. case 1:
  8202. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8203. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8204. this.initLyric(lyricPath);
  8205. }
  8206. break;
  8207. }
  8208. }
  8209. })
  8210. }
  8211. // 拉起picker选择文件管理器
  8212. async callFilePickerSelectFileForLyric(): Promise<void> {
  8213. try {
  8214. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  8215. DocumentSelectOptions.maxSelectNumber = 1
  8216. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  8217. let documentPicker = new picker.DocumentViewPicker();
  8218. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  8219. Logger.info(TAG,
  8220. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  8221. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  8222. this.saveVideoDatasLyric(DocumentSelectResult)
  8223. }
  8224. }).catch((err: BusinessError) => {
  8225. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  8226. });
  8227. } catch (err) {
  8228. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  8229. }
  8230. }
  8231. async saveVideoDatasLyric(uris: string[]) {
  8232. if (ArrayUtil.isEmpty(uris)) {
  8233. return
  8234. }
  8235. let newUris: string[] = [];
  8236. for (let i = 0; i < uris.length; i++) {
  8237. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  8238. Logger.info(TAG, 'filePath uri: ' + filePath);
  8239. newUris.push(filePath)
  8240. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  8241. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  8242. fileIo.copyFileSync(file.fd, file2.fd)
  8243. fileIo.closeSync(file);
  8244. fileIo.closeSync(file2);
  8245. this.initLyric(filePath)
  8246. }
  8247. }
  8248. private initDelayPlay(context: object) {
  8249. this.mContext = context;
  8250. }
  8251. startPipLyric() {
  8252. if (this.pipController) {
  8253. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  8254. PiPWindow.PiPControlStatus.PLAY);
  8255. }
  8256. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  8257. if (this.isOpenPip) {
  8258. this.startPip()
  8259. } else {
  8260. this.stopPip()
  8261. }
  8262. }
  8263. private startPlayOrResumePlay() {
  8264. this.startPipLyric()
  8265. this.mDestroyPage = false;
  8266. this.animationState = AnimationStatus.Running
  8267. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  8268. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8269. this.stopProgressTask();
  8270. this.startProgressTask();
  8271. this.play(this.videoUrl.toString());
  8272. }
  8273. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  8274. this.mIjkMediaPlayer.start();
  8275. this.setProgress()
  8276. this.CONTROL_PlayStatus = PlayStatus.PLAY
  8277. }
  8278. this.setIsPlaying(true)
  8279. this.updateSessionPlayState(true)
  8280. this.watchStatus();
  8281. this.updateLastPlayTimeStr(this.videoUrl)
  8282. }
  8283. updateLastPlayTimeStr(filePath: string) {
  8284. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  8285. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  8286. if (success) {
  8287. this.getHistoryList(false)
  8288. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  8289. } else {
  8290. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  8291. }
  8292. });
  8293. }
  8294. private completionNum(num: number): string | number {
  8295. if (num < 10) {
  8296. return '0' + num;
  8297. } else {
  8298. return num;
  8299. }
  8300. }
  8301. private stringForTime(timeMs: number): string {
  8302. let totalSeconds: number | string = (timeMs / 1000);
  8303. let newSeconds: number | string = totalSeconds % 60;
  8304. let minutes: number | string = (totalSeconds / 60) % 60;
  8305. let hours: number | string = totalSeconds / 3600;
  8306. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  8307. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  8308. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  8309. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  8310. if (this.isCurrentTime) {
  8311. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  8312. this.oldSeconds = newSeconds
  8313. } else {
  8314. newSeconds = this.oldSeconds
  8315. }
  8316. }
  8317. newSeconds = this.completionNum(newSeconds);
  8318. if (hours > 0) {
  8319. return hours + ":" + minutes + ":" + newSeconds;
  8320. } else {
  8321. return minutes + ":" + newSeconds;
  8322. }
  8323. }
  8324. private setProgress() {
  8325. let position = this.mIjkMediaPlayer.getCurrentPosition();
  8326. let duration = this.mIjkMediaPlayer.getDuration();
  8327. let pos = 0;
  8328. if (duration > 0) {
  8329. this.slideEnable = true;
  8330. let curPercent = position / duration;
  8331. pos = curPercent * 100;
  8332. if (pos > this.PROGRESS_MAX_VALUE) {
  8333. this.progressValue = this.PROGRESS_MAX_VALUE
  8334. } else {
  8335. this.progressValue = pos;
  8336. }
  8337. }
  8338. // LogUtils.getInstance()
  8339. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8340. this.totalTime = this.stringForTime(duration);
  8341. if (position > duration) {
  8342. position = duration;
  8343. }
  8344. this.isCurrentTime = true;
  8345. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  8346. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  8347. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  8348. this.currentTime = this.stringForTime(position);
  8349. this.isCurrentTime = false
  8350. if (this.mIjkMediaPlayer.isPlaying()) {
  8351. this.randomColor =
  8352. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  8353. // 判断是否播放到结束时间
  8354. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  8355. if (position >= duration - this.jumpEndTime * 1000) {
  8356. this.playNext()
  8357. }
  8358. }
  8359. } else {
  8360. this.randomColor = 'rbg(0,0,0)'
  8361. }
  8362. }
  8363. private startProgressTask() {
  8364. let that = this;
  8365. this.updateProgressTimer = setInterval(() => {
  8366. //LogUtils.getInstance().LOGI("startProgressTask");
  8367. if (!that.mDestroyPage) {
  8368. that.setProgress();
  8369. }
  8370. }, 300);
  8371. }
  8372. private stopProgressTask() {
  8373. LogUtils.getInstance().LOGI("stopProgressTask");
  8374. clearInterval(this.updateProgressTimer);
  8375. }
  8376. private showLoadIng() {
  8377. this.loadingVisible = Visibility.Visible;
  8378. this.replayVisible = Visibility.None;
  8379. }
  8380. private hideLoadIng() {
  8381. this.loadingVisible = Visibility.None;
  8382. this.replayVisible = Visibility.None;
  8383. }
  8384. private showRePlay() {
  8385. this.loadingVisible = Visibility.None;
  8386. this.replayVisible = Visibility.Visible;
  8387. }
  8388. private async play(url: string) {
  8389. let that = this;
  8390. that.showLoadIng();
  8391. //设置XComponent回调的context
  8392. if (!!this.mContext) {
  8393. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  8394. }
  8395. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8396. this.mIjkMediaPlayer.reset();
  8397. }
  8398. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  8399. //设置debug模式
  8400. this.mIjkMediaPlayer.setDebug(false);
  8401. //初始化配置
  8402. this.mIjkMediaPlayer.native_setup();
  8403. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  8404. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  8405. this.mIjkMediaPlayer.setVolume('1', '1');
  8406. }else{
  8407. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  8408. }
  8409. //设置视频源
  8410. this.mIjkMediaPlayer.setDataSource(url);
  8411. //设置视频源http请求头
  8412. let headers = new Map([
  8413. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  8414. ["referer", "https://www.bilibili.com"]
  8415. ]);
  8416. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  8417. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  8418. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  8419. // }
  8420. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8421. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  8422. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  8423. const fileSize = await this.getFileSize(this.videoUrl);
  8424. let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
  8425. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  8426. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  8427. }
  8428. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  8429. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  8430. //停止预读的最小帧数
  8431. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  8432. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  8433. // 设置其他缓冲相关选项
  8434. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  8435. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  8436. //启动预加载
  8437. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  8438. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  8439. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  8440. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  8441. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  8442. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  8443. // 因此需要播放器丢包,才不会累积延时
  8444. // 这个和第三个参数packet-buffering无关。
  8445. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  8446. // 无限制收流
  8447. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  8448. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  8449. // 屏幕常亮
  8450. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  8451. // 设置超时
  8452. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  8453. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  8454. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  8455. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  8456. // 变速播放
  8457. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  8458. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8459. let Speed = this.mIjkMediaPlayer.getSpeed()
  8460. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  8461. //是否开启循环播放
  8462. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  8463. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  8464. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  8465. if (height === 0) {
  8466. return;
  8467. }
  8468. const va = width / height;
  8469. const vpa = that.videoParentAspectRatio;
  8470. if (vpa > va) {
  8471. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  8472. } else {
  8473. that.videoWidth = '100%';
  8474. }
  8475. if (width && height) {
  8476. that.videoAspectRatio = width / height;
  8477. }
  8478. LogUtils.getInstance()
  8479. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  8480. that.hideLoadIng();
  8481. }
  8482. }
  8483. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  8484. let mOnPreparedListener: OnPreparedListener = {
  8485. onPrepared: async () => {
  8486. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  8487. try {
  8488. // this.cover = this.songList[this.curIndex].pixelMapPath
  8489. // this.artist = this.songList[this.curIndex].artist
  8490. // this.videoUrl = this.songList[this.curIndex].filePath
  8491. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8492. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  8493. this.setImageColor2(this.cover)
  8494. } else {
  8495. this.getImageColor();
  8496. }
  8497. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8498. await this.initLyric(lyricPath);
  8499. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8500. this.avSessionController.initAvSession(false);
  8501. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  8502. this.setAvSessionListener();
  8503. this.updateSessionPlayState(true)
  8504. this.setCurrentPlayMode()
  8505. }, 500)
  8506. let timeoutPlay = 0
  8507. if (StrUtil.isNotEmpty(this.videoUrl) &&
  8508. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  8509. timeoutPlay = 1000
  8510. }
  8511. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  8512. if (this.modeType === 0) { //文件夹
  8513. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8514. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  8515. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  8516. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  8517. } else if (this.modeType === 1) { //媒体库
  8518. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  8519. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  8520. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  8521. } else if (this.modeType === 2) { //艺术家
  8522. if (this.currentSong?.artist) {
  8523. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  8524. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  8525. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  8526. }
  8527. } else if (this.modeType === 3) { //专辑
  8528. if (this.currentSong?.album) {
  8529. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  8530. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  8531. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  8532. }
  8533. }
  8534. this.duration = this.mIjkMediaPlayer.getDuration()
  8535. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  8536. if (this.mIjkMediaPlayer != null) {
  8537. if (this.jumpTopTime * 1000 <= this.duration) {
  8538. // 调用 seekTo 方法,跳到指定时间
  8539. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8540. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8541. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  8542. }
  8543. }, timeoutPlay)
  8544. } else {
  8545. // 提示用户无法跳过
  8546. ToastUtil.showToast('跳过时间超过视频时长');
  8547. }
  8548. }
  8549. } else {
  8550. this.jumpTopTime = 0
  8551. this.jumpEndTime = 0
  8552. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  8553. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  8554. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  8555. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  8556. //记忆播放(每一首都会记忆播放)
  8557. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8558. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8559. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  8560. this.restorePlaybackPosition() //读取播放记忆功能
  8561. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  8562. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  8563. this.restorePlaybackPosition() //读取播放记忆功能
  8564. }
  8565. this.isFirstStartPlay = false
  8566. }, timeoutPlay)
  8567. } else {
  8568. this.isFirstStartPlay = false
  8569. }
  8570. }
  8571. this.saveLastPlayList()
  8572. } catch (error) {
  8573. let err: BusinessError = error as BusinessError;
  8574. console.error('onecold failed with err: ' + JSON.stringify(err));
  8575. }
  8576. }
  8577. }
  8578. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  8579. let mOnTimedTextListener: OnTimedTextListener = {
  8580. onTimedText: () => {
  8581. }
  8582. }
  8583. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  8584. let mOnCompletionListener: OnCompletionListener = {
  8585. onCompletion: () => {
  8586. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  8587. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  8588. this.playNext()
  8589. } else if (this.playType == 1) { //1:单片重复播放
  8590. this.CONTROL_PlayStatus = PlayStatus.INIT
  8591. that.startPlayOrResumePlay();
  8592. } else if (this.playType == 2) { //2:正常播放,单曲播完
  8593. that.showRePlay();
  8594. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  8595. that.progressValue = this.PROGRESS_MAX_VALUE;
  8596. that.slideEnable = false;
  8597. that.stop();
  8598. // ToastUtil.showToast('开始重新播放')
  8599. } else if (this.playType == 3) { //3:随机播放
  8600. this.randomPlay()
  8601. }
  8602. }
  8603. }
  8604. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  8605. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  8606. onBufferingUpdate: (percent: number) => {
  8607. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  8608. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  8609. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  8610. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  8611. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  8612. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  8613. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  8614. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  8615. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  8616. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  8617. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  8618. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  8619. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  8620. let Looping = this.mIjkMediaPlayer.isLooping()
  8621. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  8622. }
  8623. }
  8624. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  8625. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  8626. onSeekComplete: () => {
  8627. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  8628. that.startPlayOrResumePlay();
  8629. }
  8630. }
  8631. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  8632. let mOnInfoListener: OnInfoListener = {
  8633. onInfo: (what: number, extra: number) => {
  8634. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  8635. that.hideLoadIng();
  8636. }
  8637. }
  8638. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  8639. let mOnErrorListener: OnErrorListener = {
  8640. onError: (what: number, extra: number) => {
  8641. this.stopProgressTask();
  8642. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  8643. that.hideLoadIng();
  8644. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  8645. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  8646. } else {
  8647. ToastUtil.showToast(getContext()
  8648. .resourceManager
  8649. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  8650. }
  8651. }
  8652. }
  8653. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  8654. this.mIjkMediaPlayer.setMessageListener();
  8655. this.mIjkMediaPlayer.prepareAsync();
  8656. this.mIjkMediaPlayer.start();
  8657. }
  8658. //保存最后播放的那首歌和已经对应的播放列表
  8659. saveLastPlayList() {
  8660. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  8661. PreferencesUtil.putSync('LastMusicList', this.songList)
  8662. }
  8663. // 清空播放记录
  8664. clearVideoHistory() {
  8665. this.table.clearPlayHistory((success: boolean, error?: string) => {
  8666. if (success) {
  8667. this.historyList = [];
  8668. this.updateListData(this.historyList)
  8669. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  8670. ToastUtil.showToast('清空播放记录成功')
  8671. } else {
  8672. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  8673. }
  8674. });
  8675. }
  8676. public async setAvSessionListener() {
  8677. if (!this.avSessionController) {
  8678. return;
  8679. }
  8680. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  8681. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  8682. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  8683. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  8684. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  8685. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  8686. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  8687. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  8688. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  8689. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  8690. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  8691. }
  8692. setLoopMode() {
  8693. let itype = this.playType + 1
  8694. if (itype >= 4) {
  8695. this.playType = 0
  8696. ToastUtil.showToast('连续播放')
  8697. } else if (itype === 1) {
  8698. this.playType = 1
  8699. ToastUtil.showToast('单曲循环')
  8700. } else if (itype === 2) {
  8701. this.playType = 2
  8702. ToastUtil.showToast('单曲播完')
  8703. } else if (itype === 3) {
  8704. this.playType = 3
  8705. ToastUtil.showToast('随机播放')
  8706. } else if (itype === 0) {
  8707. this.playType = 0
  8708. ToastUtil.showToast('连续播放')
  8709. }
  8710. PreferencesUtil.putSync('musicPlayType', this.playType)
  8711. this.setCurrentPlayMode()
  8712. }
  8713. private sessionSetLoopModeCallback = (mode: number) => {
  8714. if (this.mIjkMediaPlayer != null) {
  8715. ToastUtil.showToast('当前播放模式:' + mode)
  8716. Logger.info('onecold 当前播放模式= ' + mode)
  8717. let hmPlayMode = mode + 1
  8718. if (hmPlayMode >= 4) {
  8719. hmPlayMode = 0
  8720. }
  8721. if (hmPlayMode === 1) {
  8722. this.playType = 1
  8723. ToastUtil.showToast('单曲循环')
  8724. } else if (hmPlayMode === 0) {
  8725. this.playType = 2
  8726. ToastUtil.showToast('单曲播完')
  8727. } else if (hmPlayMode === 3) {
  8728. this.playType = 3
  8729. ToastUtil.showToast('随机播放')
  8730. } else if (hmPlayMode === 2) {
  8731. this.playType = 0
  8732. ToastUtil.showToast('连续播放')
  8733. }
  8734. PreferencesUtil.putSync('musicPlayType', this.playType)
  8735. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  8736. let playBackState: avSession.AVPlaybackState = {
  8737. loopMode: hmPlayMode,
  8738. };
  8739. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  8740. console.info(`set setLoopMode AVPlaybackState successfully`);
  8741. }).catch((err: BusinessError) => {
  8742. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8743. });
  8744. }
  8745. }
  8746. setCurrentPlayMode() {
  8747. if (!this.avSessionController) {
  8748. return;
  8749. }
  8750. let mLoopMode = 0
  8751. switch (this.playType) {
  8752. case 0:
  8753. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  8754. break;
  8755. case 1:
  8756. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  8757. break;
  8758. case 2:
  8759. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  8760. break;
  8761. case 3:
  8762. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  8763. break;
  8764. }
  8765. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  8766. let playBState: avSession.AVPlaybackState = {
  8767. loopMode: mLoopMode,
  8768. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  8769. };
  8770. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  8771. console.info(`set setLoopMode AVPlaybackState successfully`);
  8772. }).catch((err: BusinessError) => {
  8773. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8774. });
  8775. }
  8776. private sessionToggleFavoriteCallback = (assetId: string) => {
  8777. if (this.mIjkMediaPlayer != null && this.currentSong) {
  8778. console.info(`on toggleFavorite `);
  8779. // 应用收到收藏命令,进行收藏处理。
  8780. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  8781. this.doFav(this.currentSong)
  8782. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  8783. let playbackState: avSession.AVPlaybackState = {
  8784. isFavorite: !this.isFac,
  8785. };
  8786. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  8787. console.info(`SetAVPlaybackState successfully`);
  8788. }).catch((err: BusinessError) => {
  8789. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  8790. });
  8791. }
  8792. }
  8793. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  8794. device: avSession.OutputDeviceInfo) => {
  8795. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  8796. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8797. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  8798. await this.startCasting();
  8799. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8800. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  8801. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  8802. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  8803. if (device) {
  8804. this.endCasting();
  8805. }
  8806. }
  8807. };
  8808. private async startCasting() {
  8809. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8810. this.setPlaybackStateChangeListener();
  8811. this.pause();
  8812. this.initQueueItem();
  8813. this.prepare();
  8814. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8815. refToIsCasting?.set(true);
  8816. this.castSeek = true;
  8817. this.isCastPlaying = true;
  8818. }
  8819. async changeCasting() {
  8820. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8821. this.initQueueItem();
  8822. this.prepare();
  8823. this.setPlaybackStateChangeListener();
  8824. this.isCastPlaying = true;
  8825. this.castSeek = true;
  8826. }
  8827. public endCasting() {
  8828. this.avSessionController.getAvSession()?.stopCasting();
  8829. this.stopCast();
  8830. this.isCastPlaying = false;
  8831. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8832. refToIsCasting?.set(false);
  8833. this.pause();
  8834. this.setIsPlaying(false);
  8835. // if (this.curIndex === this.curSource.index) {
  8836. // this.play
  8837. // this.seek(this.currentTime * 1000);
  8838. // this.setIsPlaying(true);
  8839. // } else {
  8840. // this.pauseVideo();
  8841. // this.setIsPlaying(false);
  8842. // }
  8843. }
  8844. public setIsPlaying(isPlayer: boolean) {
  8845. this.isPlaying = isPlayer;
  8846. }
  8847. private setPlaybackStateChangeListener(): void {
  8848. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  8849. this.castController?.on('endOfStream', this.reloadCasting);
  8850. this.castController?.on('playNext', this.playNextCallback);
  8851. this.castController?.on('playPrevious', this.playPreviousCallback);
  8852. }
  8853. private updateSessionPlayState(isPlay: boolean): void {
  8854. // if(!this.isBgPlayOpen)
  8855. // return
  8856. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  8857. this.setAVSessionPlayState({
  8858. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  8859. position: {
  8860. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  8861. updateTime: new Date().getTime()
  8862. }
  8863. });
  8864. }
  8865. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  8866. this.avSessionController.setAvSessionPlayState(playbackState)
  8867. }
  8868. private positionChange(position: number) {
  8869. this.currentTime2 = position / 1000;
  8870. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  8871. }
  8872. private playDurationChange(duration: number) {
  8873. this.duration = duration;
  8874. this.durationTime = Math.floor(this.duration / 1000);
  8875. this.durationStringTime = secondToTime((this.durationTime));
  8876. }
  8877. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  8878. const duration = playbackState?.extras?.duration;
  8879. if (typeof duration === 'number') {
  8880. this.playDurationChange(duration as number);
  8881. }
  8882. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  8883. this.positionChange(playbackState?.position?.elapsedTime);
  8884. }
  8885. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  8886. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  8887. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  8888. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  8889. this.isCastPlaying = false;
  8890. }
  8891. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  8892. this.isCastPlaying = true;
  8893. }
  8894. };
  8895. private reloadCasting = async () => {
  8896. let item = this.songList[this.curIndex];
  8897. let uri = fileUri.getUriFromPath(item.filePath);
  8898. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8899. // description.startPosition = 0;
  8900. this.castItem = {
  8901. itemId: this.curIndex,
  8902. description: {
  8903. assetId: item.filePath,
  8904. title: item.name,
  8905. artist: '',
  8906. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8907. // mediaUri: item.filePath,
  8908. fdSrc: {
  8909. fd: file.fd
  8910. },
  8911. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8912. mediaType: 'VIDEO',
  8913. mediaSize: item.videoSize,
  8914. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8915. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8916. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8917. duration: this.duration,
  8918. // albumCoverUri: 'https://www.example.jpeg',
  8919. // albumTitle: '《ExampleAlbum》',
  8920. appName: this.appName,
  8921. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8922. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8923. }
  8924. };
  8925. this.prepare();
  8926. this.isCastPlaying = true;
  8927. };
  8928. public playNextCallback = (): void => {
  8929. this.playNext()
  8930. };
  8931. public playPreviousCallback = (): void => {
  8932. this.playPrevious()
  8933. };
  8934. async prepare() {
  8935. await this.castController?.prepare(this.castItem);
  8936. await this.castController?.start(this.castItem);
  8937. }
  8938. public initQueueItem() {
  8939. let item = this.songList[this.curIndex];
  8940. let time = this.currentTime;
  8941. let uri = fileUri.getUriFromPath(item.filePath);
  8942. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8943. this.castItem = {
  8944. itemId: this.curIndex,
  8945. description: {
  8946. assetId: item.filePath,
  8947. title: item.name,
  8948. artist: '',
  8949. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  8950. fdSrc: {
  8951. fd: file.fd
  8952. },
  8953. // 该字段大写,音频'AUDIO',视频'VIDEO'
  8954. mediaType: 'AUDIO',
  8955. mediaSize: item.videoSize,
  8956. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  8957. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  8958. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  8959. duration: this.duration,
  8960. // albumCoverUri: 'https://www.example.jpeg',
  8961. // albumTitle: '《ExampleAlbum》',
  8962. appName: this.appName,
  8963. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  8964. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  8965. }
  8966. };
  8967. }
  8968. async stopCast() {
  8969. try {
  8970. this.castController?.off('playbackStateChange');
  8971. this.castController?.off('endOfStream');
  8972. this.castController?.off('playNext');
  8973. this.castController?.off('playPrevious');
  8974. this.castController?.off('error');
  8975. } catch (error) {
  8976. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  8977. }
  8978. }
  8979. private sessionPlayCallback = (): void => {
  8980. this.playOrPause()
  8981. };
  8982. private sessionPauseCallback = (): void => {
  8983. this.playOrPause()
  8984. };
  8985. private playOrPause() {
  8986. if (!this.debounce()) {
  8987. return;
  8988. }
  8989. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8990. this.pause();
  8991. } else {
  8992. this.startPlayOrResumePlay();
  8993. this.playChange()
  8994. }
  8995. }
  8996. private sessionPlayNextCallback = (): void => {
  8997. this.playNext()
  8998. };
  8999. private sessionPlayPreviousCallback = (): void => {
  9000. this.playPrevious()
  9001. };
  9002. private sessionStopCallback = (): void => {
  9003. this.stop()
  9004. };
  9005. private sessionFastForwardCallback = (time?: number) => {
  9006. if (!time) {
  9007. return;
  9008. }
  9009. if (this.mIjkMediaPlayer != null) {
  9010. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9011. let seeTime = curPosition + time * 1000;
  9012. // 限制 seekValue 在合法范围内
  9013. if (seeTime < 0) {
  9014. seeTime = 0;
  9015. } else if (seeTime > this.duration) {
  9016. seeTime = this.duration;
  9017. }
  9018. Logger.info('onecold seeTime= ' + seeTime)
  9019. this.setSeekToActionProgress(seeTime)
  9020. this.seekTo(seeTime + "")
  9021. }
  9022. };
  9023. /**
  9024. * Gesture method onActionUpdate.
  9025. *
  9026. * @param event Gesture event.手势拖动设置快进和后退
  9027. */
  9028. private setSeekToActionProgress(position: number) {
  9029. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  9030. let duration = this.mIjkMediaPlayer.getDuration();
  9031. let pos = 0;
  9032. if (duration > 0) {
  9033. this.slideEnable = true;
  9034. let curPercent = position / duration;
  9035. pos = curPercent * 100;
  9036. if (pos > this.PROGRESS_MAX_VALUE) {
  9037. this.progressValue = this.PROGRESS_MAX_VALUE
  9038. } else {
  9039. this.progressValue = pos;
  9040. }
  9041. }
  9042. // LogUtils.getInstance()
  9043. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9044. this.totalTime = this.stringForTime(duration);
  9045. if (position > duration) {
  9046. position = duration;
  9047. }
  9048. this.isCurrentTime = true;
  9049. this.currentTime = this.stringForTime(position);
  9050. this.isCurrentTime = false
  9051. }
  9052. private sessionRewindCallback = (time?: number) => {
  9053. if (!time) {
  9054. return;
  9055. }
  9056. if (this.mIjkMediaPlayer != null) {
  9057. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9058. let seeTime = curPosition - time * 1000;
  9059. // 限制 seekValue 在合法范围内
  9060. if (seeTime < 0) {
  9061. seeTime = 0;
  9062. } else if (seeTime > this.duration) {
  9063. seeTime = this.duration;
  9064. }
  9065. Logger.info('onecold seeTime= ' + seeTime)
  9066. this.setSeekToActionProgress(seeTime)
  9067. this.seekTo(seeTime + "")
  9068. }
  9069. };
  9070. private sessionSeekCallback = (seekTime: number) => {
  9071. if (this.mIjkMediaPlayer != null) {
  9072. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9073. this.seekTo(seekTime + "")
  9074. }
  9075. };
  9076. private async getFileSize(filePath: string): Promise<number> {
  9077. try {
  9078. const stat = await fs.stat(filePath);
  9079. return stat.size;
  9080. } catch (err) {
  9081. console.error('Failed to get file size: ' + err.message);
  9082. return 0;
  9083. }
  9084. }
  9085. private pause() {
  9086. if (this.mIjkMediaPlayer.isPlaying()) {
  9087. this.savePlaybackPosition();
  9088. this.mIjkMediaPlayer.pause();
  9089. this.setProgress();
  9090. this.mDestroyPage = true;
  9091. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9092. this.updateSessionPlayState(false)
  9093. this.playChange()
  9094. if (this.pipController) {
  9095. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9096. PiPWindow.PiPControlStatus.PAUSE);
  9097. }
  9098. }
  9099. }
  9100. private stop() {
  9101. this.savePlaybackPosition();
  9102. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9103. this.mIjkMediaPlayer.stop();
  9104. this.mIjkMediaPlayer.release();
  9105. this.stopProgressTask();
  9106. this.updateSessionPlayState(false)
  9107. this.playChange()
  9108. this.watchStatus();
  9109. }
  9110. //保持记忆播放功能
  9111. private savePlaybackPosition() {
  9112. if (this.mIjkMediaPlayer != null) {
  9113. const position = this.mIjkMediaPlayer.getCurrentPosition();
  9114. // ToastUtil.showToast('保存记忆播放 = ' + position)
  9115. const duration = this.mIjkMediaPlayer.getDuration();
  9116. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  9117. // 如果播放位置接近视频末尾,则保存 position 为 0
  9118. const playbackPosition = (duration - position < threshold) ? 0 : position;
  9119. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  9120. }
  9121. }
  9122. //获取记忆播放功能
  9123. private restorePlaybackPosition() {
  9124. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  9125. // ToastUtil.showToast('position = ' + position)
  9126. if (this.mIjkMediaPlayer != null && position > 0) {
  9127. // ToastUtil.showToast('seekTo = ' + position)
  9128. this.seekTo(position + "");
  9129. }
  9130. }
  9131. private seekTo(value: string) {
  9132. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  9133. ToastUtil.showToast('wma格式不支持拖动快进。')
  9134. return
  9135. }
  9136. this.mIjkMediaPlayer.seekTo(value);
  9137. // this.startPlayOrResumePlay()
  9138. // 在这里恢复计时器状态
  9139. this.setProgress()
  9140. // this.startProgressTask();
  9141. }
  9142. // 添加到下一首播放
  9143. private addToNextPlay(song: VideoItem) {
  9144. if (!this.debounce()) {
  9145. return;
  9146. }
  9147. if (this.currentSong) {
  9148. if (this.currentSong === song) {
  9149. ToastUtil.showToast('当前已经在播放这首歌了!')
  9150. return
  9151. }
  9152. }
  9153. // 如果未开始播放或队列为空
  9154. if (this.curIndex === -1 || this.songList.length === 0) {
  9155. this.songList = [song];
  9156. this.curIndex = 0;
  9157. this.doPlay(song)
  9158. return;
  9159. }
  9160. // 插入到当前索引+1的位置
  9161. const insertPos = this.curIndex + 1;
  9162. this.songList.splice(insertPos, 0, song);
  9163. this.songList = [...this.songList]; // 触发状态更新
  9164. this.sonDataSource.pushArrayData(this.songList)
  9165. ToastUtil.showToast('已添加至下一首播放')
  9166. }
  9167. //下一个
  9168. private playNext() {
  9169. if (!this.debounce()) {
  9170. return;
  9171. }
  9172. if (this.playType == 3) { //3:随机播放
  9173. this.randomPlay()
  9174. return;
  9175. }
  9176. if (ArrayUtil.isNotEmpty(this.songList)) {
  9177. if (this.curIndex == this.songList.length - 1) {
  9178. this.curIndex = 0;
  9179. } else {
  9180. this.curIndex++;
  9181. }
  9182. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9183. this.stop();
  9184. this.currentSong = this.songList[this.curIndex]
  9185. this.videoUrl = this.songList[this.curIndex].filePath;
  9186. this.cover = this.songList[this.curIndex].pixelMapPath
  9187. this.artist = this.songList[this.curIndex].artist
  9188. this.name = this.songList[this.curIndex].name
  9189. this.startPlayOrResumePlay()
  9190. }
  9191. }
  9192. // 存储已播放的歌曲索引
  9193. private playedIndices: Set<number> = new Set();
  9194. //随机播放
  9195. private randomPlay() {
  9196. // if (!this.debounce()) {
  9197. // return;
  9198. // }
  9199. if (ArrayUtil.isNotEmpty(this.songList)) {
  9200. if (this.songList.length > 3) {
  9201. // 如果所有歌曲都播放过一次,清空已播放索引集合
  9202. if (this.playedIndices.size === this.songList.length) {
  9203. this.playedIndices.clear();
  9204. }
  9205. // 随机选择一个未播放的歌曲索引
  9206. let newIndex: number;
  9207. // 添加超时机制防止无限循环
  9208. let attempt = 0;
  9209. const maxAttempts = 100; // 根据需求调整
  9210. do {
  9211. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  9212. attempt++;
  9213. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  9214. if (attempt >= maxAttempts) {
  9215. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  9216. newIndex = Math.floor(Math.random() * this.songList.length);
  9217. }
  9218. this.curIndex = newIndex;
  9219. this.playedIndices.add(newIndex);
  9220. } else {
  9221. // 当歌曲数量小于或等于3时,直接播放下一首
  9222. if (this.curIndex == this.songList.length - 1) {
  9223. this.curIndex = 0;
  9224. } else {
  9225. this.curIndex++;
  9226. }
  9227. }
  9228. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9229. this.stop();
  9230. this.currentSong = this.songList[this.curIndex];
  9231. this.videoUrl = this.songList[this.curIndex].filePath;
  9232. this.name = this.songList[this.curIndex].name;
  9233. this.cover = this.songList[this.curIndex].pixelMapPath
  9234. this.artist = this.songList[this.curIndex].artist
  9235. this.startPlayOrResumePlay();
  9236. }
  9237. }
  9238. private playIndex(index: number) {
  9239. if (!this.debounce()) {
  9240. return;
  9241. }
  9242. if (ArrayUtil.isNotEmpty(this.songList)) {
  9243. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9244. this.stop();
  9245. this.currentSong = this.songList[this.curIndex]
  9246. this.videoUrl = this.songList[index].filePath;
  9247. this.name = this.songList[index].name
  9248. this.cover = this.songList[this.curIndex].pixelMapPath
  9249. this.artist = this.songList[this.curIndex].artist
  9250. this.curIndex = index;
  9251. this.startPlayOrResumePlay()
  9252. }
  9253. }
  9254. //上一个
  9255. private playPrevious() {
  9256. if (!this.debounce()) {
  9257. return;
  9258. }
  9259. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  9260. this.randomModePlayFromHistory()
  9261. return;
  9262. }
  9263. if (this.curIndex == 0) {
  9264. this.curIndex = this.songList.length - 1;
  9265. } else {
  9266. this.curIndex--;
  9267. }
  9268. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9269. this.stop();
  9270. this.currentSong = this.songList[this.curIndex]
  9271. this.videoUrl = this.songList[this.curIndex].filePath;
  9272. this.name = this.songList[this.curIndex].name
  9273. this.cover = this.songList[this.curIndex].pixelMapPath
  9274. this.artist = this.songList[this.curIndex].artist
  9275. this.startPlayOrResumePlay()
  9276. }
  9277. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  9278. private randomModePlayFromHistory() {
  9279. if (this.historyList.length >= 2) {
  9280. // 播放历史记录的第二首
  9281. const prevSong = this.historyList[1];
  9282. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  9283. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9284. this.stop();
  9285. this.currentSong = prevSong;
  9286. this.videoUrl = prevSong.filePath;
  9287. this.cover = prevSong.pixelMapPath
  9288. this.artist = prevSong.artist
  9289. this.name = prevSong.name;
  9290. this.startPlayOrResumePlay();
  9291. } else {
  9292. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  9293. if (this.curIndex === 0) {
  9294. this.curIndex = this.songList.length - 1;
  9295. } else {
  9296. this.curIndex--;
  9297. }
  9298. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9299. this.stop();
  9300. this.currentSong = this.songList[this.curIndex];
  9301. this.videoUrl = this.songList[this.curIndex].filePath;
  9302. this.cover = this.songList[this.curIndex].pixelMapPath
  9303. this.artist = this.songList[this.curIndex].artist
  9304. this.name = this.songList[this.curIndex].name;
  9305. this.startPlayOrResumePlay();
  9306. }
  9307. }
  9308. debounce() {
  9309. const delay = 600;
  9310. let cur = new Date().getTime();
  9311. if (cur - this.last > delay) {
  9312. this.last = cur;
  9313. return true;
  9314. }
  9315. return false;
  9316. }
  9317. /**
  9318. * Sets whether the screen is a constant based on the playback status.
  9319. */
  9320. watchStatus() {
  9321. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  9322. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9323. this.windowClass.setWindowKeepScreenOn(true);
  9324. } else {
  9325. this.windowClass.setWindowKeepScreenOn(false);
  9326. }
  9327. }
  9328. /**
  9329. * Volume gesture method onActionStart.
  9330. *
  9331. * @param event Gesture event.
  9332. */
  9333. private customDialogComponentIdMM: number = 0
  9334. @Builder
  9335. customDialogComponentMM() {
  9336. Column() {
  9337. Row() {
  9338. Blank()
  9339. Text('验证密码')
  9340. .fontSize(22)
  9341. .fontColor($r('app.color.pri_bg'))
  9342. .margin({ top: 18 })
  9343. Blank()
  9344. Image($r('app.media.close'))
  9345. .fillColor(Color.White)
  9346. .margin({ top: 18, right: 18 })
  9347. .width(20)
  9348. .onClick(() => {
  9349. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9350. })
  9351. }
  9352. .width('100%') // 使Row占据整个宽度
  9353. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  9354. Verify({
  9355. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  9356. });
  9357. }.height('60%')
  9358. .backgroundColor($r('app.color.index_background'))
  9359. .justifyContent(FlexAlign.SpaceBetween)
  9360. }
  9361. private handleVerifyCompleted(isSuccess: boolean) {
  9362. if (isSuccess) {
  9363. console.log('验证成功');
  9364. // 在这里处理验证成功后的逻辑
  9365. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9366. this.currentPath = this.lockPath
  9367. this.getSortedFiles(this.currentPath)
  9368. } else {
  9369. // console.log('验证失败');
  9370. ToastUtil.showToast('验证失败')
  9371. }
  9372. }
  9373. private showVerifyDialog() {
  9374. promptAction.openCustomDialog({
  9375. transition: TransitionEffect.asymmetric(
  9376. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  9377. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9378. ,
  9379. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  9380. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9381. ),
  9382. builder: () => {
  9383. this.customDialogComponentMM()
  9384. },
  9385. isModal: true,
  9386. autoCancel: true,
  9387. maskColor: Color.Transparent,
  9388. alignment: DialogAlignment.Bottom,
  9389. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  9390. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  9391. console.log("dialog onWillDismiss")
  9392. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  9393. dismissDialogAction.dismiss()
  9394. }
  9395. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  9396. dismissDialogAction.dismiss()
  9397. }
  9398. }
  9399. }).then((dialogId: number) => {
  9400. this.customDialogComponentIdMM = dialogId
  9401. })
  9402. }
  9403. //左滑操作 移动文件 重命名 删除等操作
  9404. @Builder
  9405. DeleteButton(item: VideoItem, index: number, filePath: string) {
  9406. Row() {
  9407. //加入收藏
  9408. Button() {
  9409. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  9410. .fillColor(Color.White)
  9411. .width(20)
  9412. }
  9413. .width(40)
  9414. .height(40)
  9415. .type(ButtonType.Circle)
  9416. .backgroundColor(this.themeColor)
  9417. .margin(5)
  9418. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9419. .onClick(() => {
  9420. if (item) {
  9421. this.doFav(item)
  9422. }
  9423. })
  9424. //加入下一首播放
  9425. Button() {
  9426. Image($r('app.media.next_to_play'))
  9427. .fillColor(Color.White)
  9428. .width(20)
  9429. }
  9430. .width(40)
  9431. .height(40)
  9432. .type(ButtonType.Circle)
  9433. .backgroundColor(this.themeColor)
  9434. .margin(5)
  9435. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9436. .onClick(() => {
  9437. this.addToNextPlay(item);
  9438. })
  9439. //复制文件
  9440. Button() {
  9441. Image($r('app.media.copy'))
  9442. .fillColor(Color.White)
  9443. .width(20)
  9444. }
  9445. .width(40)
  9446. .height(40)
  9447. .type(ButtonType.Circle)
  9448. .backgroundColor(this.themeColor)
  9449. .margin(5)
  9450. .id(filePath + 'copy')
  9451. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9452. .onClick(() => {
  9453. this.showCopyDialog(false, item, index, filePath + 'copy');
  9454. })
  9455. //移动文件
  9456. Button() {
  9457. Image($r('app.media.cut'))
  9458. .fillColor(Color.White)
  9459. .width(20)
  9460. }
  9461. .width(40)
  9462. .height(40)
  9463. .type(ButtonType.Circle)
  9464. .backgroundColor(this.themeColor)
  9465. .margin(5)
  9466. .id(filePath)
  9467. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9468. .onClick(() => {
  9469. this.showCutDialog(false, item, index, filePath);
  9470. })
  9471. Button() {
  9472. Image($r('app.media.cut_current'))
  9473. .fillColor(Color.White)
  9474. .width(20)
  9475. }
  9476. .width(40)
  9477. .height(40)
  9478. .type(ButtonType.Circle)
  9479. .backgroundColor(this.themeColor)
  9480. .margin(5)
  9481. .id(filePath + 'current')
  9482. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  9483. (this.isHasDir ? Visibility.Visible : Visibility.None))
  9484. .onClick(() => {
  9485. this.showCutDialog(true, item, index, filePath + 'current');
  9486. })
  9487. //重命名
  9488. Button() {
  9489. Image($r('app.media.rename2'))
  9490. .fillColor(Color.White)
  9491. .width(20)
  9492. }
  9493. .width(40)
  9494. .height(40)
  9495. .type(ButtonType.Circle)
  9496. .backgroundColor(this.themeColor)
  9497. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9498. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9499. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9500. .margin(5)
  9501. .onClick(() => {
  9502. this.showReNameDialog(item, index + '', filePath)
  9503. })
  9504. Button() {
  9505. Image($r('app.media.delete2'))
  9506. .fillColor(Color.White)
  9507. .width(20)
  9508. }
  9509. .width(40)
  9510. .height(40)
  9511. .type(ButtonType.Circle)
  9512. .backgroundColor(this.themeColor)
  9513. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9514. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9515. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9516. .margin(5)
  9517. .onClick(() => {
  9518. this.showWarnIsDeleteFile(item, index + '', filePath)
  9519. })
  9520. Button() {
  9521. Image($r('app.media.share2'))
  9522. .fillColor(Color.White)
  9523. .width(20)
  9524. }
  9525. .width(40)
  9526. .height(40)
  9527. .type(ButtonType.Circle)
  9528. .backgroundColor(this.themeColor)
  9529. .margin(5)
  9530. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9531. .onClick(() => {
  9532. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  9533. })
  9534. }
  9535. }
  9536. /**
  9537. * 穿山甲banner广告
  9538. */
  9539. // private declare bannerAd: CSJNativeExpressAd;
  9540. // @State private status: string = "未加载"
  9541. // @State private isShowAd: boolean = false
  9542. // private declare mAdSlot: AdSlot;
  9543. // private mBiddingAdm = '' //服务端bidding才需要设置
  9544. // private expressLoadAdListener: NativeExpressAdListener = {
  9545. // /**
  9546. // * 加载失败的回调
  9547. // *
  9548. // * @param code
  9549. // * @param message
  9550. // */
  9551. // onError: (code: number, message: string) => {
  9552. // console.error("加载广告失败,code=" + code + ",message=" + message);
  9553. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  9554. // },
  9555. //
  9556. // /**
  9557. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  9558. // *
  9559. // * @param ads 返回的广告列表
  9560. // */
  9561. //
  9562. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  9563. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  9564. // if (ads && ads.length > 0) {
  9565. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  9566. // ad.setExpressInteractionListener({
  9567. // /**
  9568. // *广告的点击回调
  9569. // * @param type 广告的交互类型
  9570. // */
  9571. // onAdClicked: (type: number) => {
  9572. // console.log("BannerExpressAdPage==onAdClicked......");
  9573. // },
  9574. //
  9575. // /**
  9576. // * 广告的展示回调 每个广告仅回调一次
  9577. // * @param type 广告的交互类型
  9578. // */
  9579. // onAdShow: (type: number) => {
  9580. // console.log("BannerExpressAdPage==onAdShow......");
  9581. // },
  9582. //
  9583. // /**
  9584. // * 模板渲染失败
  9585. // */
  9586. // onRenderFail: (code: number, msg: string) => {
  9587. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  9588. // },
  9589. //
  9590. // /**
  9591. // * 模板渲染成功
  9592. // * @param width 返回view的宽 单位 vp
  9593. // * @param height 返回view的高 单位 vp
  9594. // */
  9595. // onRenderSuccess: (width: number, height: number) => {
  9596. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  9597. // this.bannerAd = ad;
  9598. // this.status = "广告加载完成待展示";
  9599. //
  9600. // this.showBannerAd()
  9601. // }
  9602. // })
  9603. // //渲染广告
  9604. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  9605. // this.setDislikeCallback(ad); //设置dislike
  9606. // ad.render(this.getUIContext())
  9607. // this.status = "广告加载中...";
  9608. // });
  9609. // }
  9610. // }
  9611. // }
  9612. //
  9613. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  9614. // ad.setDislikeCallback({
  9615. // /**
  9616. // * dislike show
  9617. // */
  9618. // onShow: () => {
  9619. // console.log("BannerExpressAdPage==dislike......show");
  9620. // },
  9621. //
  9622. // /**
  9623. // * @param position 选择的位置
  9624. // * @param value 选择的内容
  9625. // * @param enforceRemove 是否强制关闭广告
  9626. // */
  9627. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  9628. // this.isShowAd = false;
  9629. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  9630. // ",enforce=" + enforceRemove);
  9631. // },
  9632. //
  9633. // /**
  9634. // * 点击取消
  9635. // */
  9636. // onCancel: () => {
  9637. // console.log("BannerExpressAdPage==dislike......onCancel");
  9638. // }
  9639. //
  9640. // })
  9641. // }
  9642. /**
  9643. * 加载Banner广告
  9644. */
  9645. loadBannerAd(rit: string) {
  9646. // if (Utility.isNoble()) {
  9647. // return
  9648. // }
  9649. // if (!Utility.isPassInstallTime(2)) {
  9650. // return
  9651. // }
  9652. // this.isShowAd = false;
  9653. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  9654. // this.mAdSlot = new AdSlotBuilder()
  9655. // .setCodeId(rit)
  9656. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  9657. // .setAdCount(1)
  9658. // .setBidAdm(this.mBiddingAdm)
  9659. // .build()
  9660. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  9661. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  9662. // this.status = "广告加载中..."
  9663. }
  9664. /**
  9665. * 展示Banner广告
  9666. */
  9667. // showBannerAd() {
  9668. // if (!this.bannerAd) {
  9669. // return
  9670. // }
  9671. // this.isShowAd = true
  9672. // this.status = "已展示"
  9673. // }
  9674. /**
  9675. * 穿山甲广告代码结束
  9676. */
  9677. }
  9678. //视频气泡窗口的布局
  9679. @Builder
  9680. function customPopupBuilder(dataBu: BubbleBean) {
  9681. List() {
  9682. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  9683. ListItem() {
  9684. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9685. Row() {
  9686. Column() {
  9687. Image(dataBu.imageRes[index])
  9688. .height(28)
  9689. .fillColor(dataBu.color)
  9690. .alignSelf(ItemAlign.Center)
  9691. }
  9692. .width(32)
  9693. Text(item)
  9694. .padding({
  9695. top: 10,
  9696. bottom: 10,
  9697. right: 10,
  9698. left: 10
  9699. })
  9700. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  9701. .textAlign(TextAlign.Start)
  9702. .width("100%")
  9703. }
  9704. }
  9705. .backgroundColor($r('app.color.settings_background_main'))
  9706. .margin({ top: 6, bottom: 6 })
  9707. }
  9708. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  9709. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  9710. TransitionEffect.scale({ x: 0, y: 0 })))
  9711. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  9712. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  9713. .onClick(() => {
  9714. dataBu.onItemClick?.(index)
  9715. })
  9716. })
  9717. }
  9718. .width(120)
  9719. .divider({
  9720. strokeWidth: 1,
  9721. color: "#22FFFFFF"
  9722. })
  9723. }
  9724. // Function to calculate a hash for the file list
  9725. function simpleHash(fileList: string[]): string {
  9726. let hash = 0;
  9727. const str = fileList.join(',');
  9728. for (let i = 0; i < str.length; i++) {
  9729. const char = str.charCodeAt(i);
  9730. hash = (hash << 5) - hash + char;
  9731. hash |= 0; // Convert to 32bit integer
  9732. }
  9733. return hash.toString();
  9734. }
  9735. interface MoreItem {
  9736. id: number;
  9737. image: Resource;
  9738. title: string;
  9739. }
  9740. //视频气泡窗口的布局
  9741. @Builder
  9742. function cutPopupBuilder(dataBu: BubbleBean) {
  9743. Column() {
  9744. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  9745. .padding({
  9746. top: 10,
  9747. bottom: 10,
  9748. right: 10,
  9749. left: 10
  9750. })
  9751. .textAlign(TextAlign.Start)
  9752. .width(160)
  9753. .fontWeight(666)
  9754. .fontSize(16)
  9755. List() {
  9756. ForEach(dataBu.data, (item: string, index: number) => {
  9757. ListItem() {
  9758. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9759. Row() {
  9760. Column() {
  9761. Image($r('app.media.music_group'))
  9762. .height(28)
  9763. .fillColor(dataBu.color)
  9764. .alignSelf(ItemAlign.Center)
  9765. }
  9766. .width(32)
  9767. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  9768. .padding({
  9769. top: 10,
  9770. bottom: 10,
  9771. right: 10,
  9772. left: 10
  9773. })
  9774. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  9775. .fontSize(15)
  9776. }
  9777. }
  9778. .backgroundColor(Color.Transparent)
  9779. .margin({ top: 7, bottom: 7 })
  9780. }
  9781. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  9782. .animation({ duration: 500 }),
  9783. TransitionEffect.scale({ x: 0, y: 0 })))
  9784. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  9785. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  9786. .onClick(() => {
  9787. dataBu.onItemClick?.(index)
  9788. })
  9789. })
  9790. }
  9791. .width(150)
  9792. .divider({
  9793. strokeWidth: 1,
  9794. color: "#22FFFFFF"
  9795. })
  9796. }
  9797. .height(300)
  9798. .padding({
  9799. bottom: 30
  9800. })
  9801. }