LocalMusic.ets 399 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835
  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 { BusinessError, emitter } from '@kit.BasicServicesKit';
  25. import { BubbleBean } from '../viewmodel/BubbleBean';
  26. import { PopupPosition, XPopup } from '@chinalike/popup';
  27. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  28. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  29. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  30. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  31. import { Verify } from './Verify';
  32. import { RotatingCover } from './RotatingCover';
  33. import { PlayConstants } from '../common/constants/PlayConstants';
  34. import { effectKit } from '@kit.ArkGraphics2D';
  35. import { ColorConversion } from '../common/util/ColorConversion';
  36. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  37. import { AvSessionController } from '../controller/AvSessionController';
  38. import { repairAudioMetadata, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  39. import { FFMpegTags,Utility } from '../common/util/Utility';
  40. import {
  41. // DeviceChangeReason,
  42. IjkMediaPlayer,
  43. InterruptEvent,
  44. InterruptHintType,
  45. LogUtils,
  46. OnBufferingUpdateListener,
  47. OnCompletionListener,
  48. OnErrorListener,
  49. OnInfoListener,
  50. OnPreparedListener,
  51. OnSeekCompleteListener,
  52. OnTimedTextListener,
  53. OnVideoSizeChangedListener
  54. } from '@ohos/ijkplayer';
  55. import { PlayStatus } from '../common/PlayStatus';
  56. import fs from '@ohos.file.fs';
  57. import { image } from '@kit.ImageKit';
  58. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  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 app from '@system.app';
  74. import { TextNodeController } from './PipLyricTextBuilder';
  75. import { IndexerView } from './IndexerView';
  76. import { KeyCode } from '@kit.InputKit';
  77. import { KnockController } from '../controller/KnockController';
  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. @State opacityValueImage: number = 1;
  129. @State tipPopup:boolean = false
  130. @Consume mType: number;
  131. @StorageProp('themeColor') themeColor: string =
  132. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  133. themeMode: number = 0;
  134. @State titleName: string = '首页'
  135. @State textStr: string = ''
  136. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  137. // private download_path: string = '';
  138. @Consume rootPath: string //音频根目录
  139. @Consume currentPath: string
  140. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  141. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  142. @State lockPath: string = ''
  143. @State favPath: string = ''
  144. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  145. @State historyPath: string = ''
  146. @State historyList: Array<VideoItem> = []
  147. @Consume isHistory: boolean
  148. static readonly HISTORY_MUSIC: string = 'music_historyList';
  149. private table: MediaTable = new MediaTable(getContext(this))
  150. @State isZero: boolean = false
  151. @State fileList: Array<string> = []
  152. @State dirList: Array<VideoItem> = []
  153. @Consume videoLocalList: Array<VideoItem>
  154. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  155. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  156. @State artistList: Array<VideoItem> = []; //艺术家文件
  157. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  158. @State albumList: Array<VideoItem> = []; //专辑文件
  159. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  160. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  161. @State imageOpacities: number[] = [];
  162. @Consume isCanBack: boolean
  163. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  164. @State showSingleLyric: boolean = false
  165. @State sortType: number = 4 //默认排序方式
  166. @State isShowSimi: boolean = false //是否显示私密音频
  167. @State isShowFAV: boolean = true //是否显示我的收藏
  168. @State isShowTitleBar: boolean = true //是否显示分类导航条
  169. @State isShowAllBar: boolean = true //是否显示播放全部条
  170. @State isShowHistory: boolean = true //是否显示最近播放
  171. @State isCustomizeBg: boolean = false //自定义背景界面
  172. @State isGridMusic: boolean = false //是否网格布局
  173. @State isCircleBtn: boolean = false //是否圆形播放按钮
  174. @State twoFingerType: number = 3 //双支放大缩小的类型
  175. @State isScrollHide: boolean = false //是否滚动隐藏
  176. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  177. @State isStartAutoPlay: boolean = false //启动后自动播放
  178. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  179. @State isShowHeader: boolean = true
  180. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  181. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  182. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  183. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  184. @State isSwipe: boolean = false //listItem的左滑开关
  185. @State openSkipSongAnimate: boolean = true//切歌动画效果
  186. @State customizeBgPath: string | undefined = '';
  187. @State isDarkMode: boolean = false
  188. @State lyricTextWeight: number = 400
  189. @State lyricTextWeightPip: number = 400
  190. @State currentSwiperIndex: number = 0
  191. @State blurValue: number = 0 //背景模糊
  192. @State bgBrightness: number = 0 //背景亮度
  193. private listScroller: ListScroller = new ListScroller()
  194. private playListScroller: Scroller = new Scroller()
  195. @StorageProp('isLandscape') isLandscape: boolean = false;
  196. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  197. @StorageProp('windowWidth') windowWidth: number = 0;
  198. @StorageProp('windowHeight') windowHeight: number = 0;
  199. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  200. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  201. private UNKONWN:string = '';
  202. private listArea: Area = {
  203. width: 0,
  204. height: 0,
  205. position: {},
  206. globalPosition: {}
  207. }
  208. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  209. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  210. onColorModeChange() {
  211. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  212. if (this.isCustomizeBg) {
  213. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  214. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  215. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  216. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  217. } else {
  218. if (!this.isDarkMode) {
  219. this.titleBarModel.setTitleBarBackground(this.themeColor)
  220. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  221. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  222. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  223. } else {
  224. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  225. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  226. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  227. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  228. }
  229. }
  230. }
  231. onModeChange() {
  232. this.isFavMusic = false
  233. if (this.modeType === 2 || this.modeType === 3) {
  234. this.titleBarModel.setRightIcon(null)
  235. } else {
  236. this.titleBarModel.setRightIcon(($r('app.media.add')))
  237. }
  238. LogUtil.info('onecold onModeChange = ' + this.modeType)
  239. switch (this.modeType) {
  240. case 0:
  241. this.getSortedFiles(this.currentPath)
  242. break
  243. case 1:
  244. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  245. this.updateListData(this.mediaKuList)
  246. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  247. break
  248. case 2:
  249. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  250. this.updateListData(this.artistList)
  251. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  252. break
  253. case 3:
  254. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  255. this.updateListData(this.albumList)
  256. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  257. break
  258. }
  259. }
  260. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  261. // @StorageLink('isPlay') isPlay: boolean = false;
  262. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  263. @StorageLink('songList') songList: Array<VideoItem> = [];
  264. @State translateY: number = 0;
  265. @State isShowSheet: boolean = false;
  266. @State isShowSheetView: boolean = false;
  267. @State isShowTimeCloseView: boolean = false;
  268. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  269. @StorageLink('currIndex') curIndex: number = 0;
  270. @Consume isShowDrawer: boolean;
  271. @Consume offsetX: number;
  272. @State isFac: boolean = false;
  273. @State favList: Array<VideoItem> = []
  274. @Consume isFavMusic: boolean
  275. @State isClickedPLayAll: boolean = false;
  276. private scrollerForlist: ListScroller = new ListScroller();
  277. private knockController: KnockController | undefined = undefined;
  278. imagesF: ImageFrameInfo[] = [
  279. { src: $r("app.media.app_loading0") },
  280. { src: $r("app.media.app_loading1") },
  281. { src: $r("app.media.app_loading2") },
  282. { src: $r("app.media.app_loading3") },
  283. ]
  284. @State animationState: AnimationStatus = AnimationStatus.Initial
  285. // 缓存机制
  286. private cache: Map<string, Array<VideoItem>> = new Map();
  287. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  288. // 持久化缓存
  289. private async saveCacheToStorage() {
  290. const cacheArray = Array.from(this.cache.entries());
  291. const stringCacheArray = Array.from(this.stringCache.entries());
  292. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  293. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  294. }
  295. // 载入缓存
  296. private async loadCacheFromStorage() {
  297. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  298. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  299. if (cacheString) {
  300. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  301. this.cache = new Map(cacheArray);
  302. }
  303. if (stringCacheString) {
  304. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  305. this.stringCache = new Map(stringCacheArray);
  306. }
  307. }
  308. // 查找缓存
  309. private findCache(key: string): Array<VideoItem> | undefined {
  310. return this.cache.get(key);
  311. }
  312. // 查找字符串缓存
  313. private findStringCache(key: string): string | undefined {
  314. return this.stringCache.get(key);
  315. }
  316. // 添加缓存
  317. private addCache(key: string, value: Array<VideoItem>) {
  318. this.cache.set(key, value);
  319. }
  320. // 添加字符串缓存
  321. private addStringCache(key: string, value: string) {
  322. this.stringCache.set(key, value);
  323. }
  324. // 删除缓存
  325. private deleteCache(key: string) {
  326. this.cache.delete(key);
  327. this.saveCacheToStorage()
  328. }
  329. // 删除字符串缓存
  330. private deleteStringCache(key: string) {
  331. this.stringCache.delete(key);
  332. }
  333. // 多选机制
  334. @State selectedFiles: Array<VideoItem> = [];
  335. @State isMultiSelect: boolean = false;
  336. @State isAllSelected: boolean = false;
  337. @State appName: string = ''
  338. @State isHasDir: boolean = false
  339. @State packName: string = ''
  340. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  341. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  342. .setTitleTextStyle(FontStyle.Normal)
  343. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  344. .setLeftIcon($r('app.media.menu'))
  345. .setLeftIconWidth(26)
  346. .setLeftIconHeight(26)
  347. .setTitleName('首页')
  348. .setTitleFontSize(18)
  349. .setTitleFontColor(Color.White)
  350. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  351. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  352. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  353. .setRightIcon($r('app.media.add'))
  354. .setOnRightClickListener(() => {
  355. this.showSheelDialog()
  356. })
  357. // .setOnTitleClickListener(() => {
  358. // this.showPupDialog()
  359. // })
  360. .setOnLeftClickListener(() => {
  361. this.doSwipBack()
  362. })
  363. doSwipBack() {
  364. if (this.modeType !== 0 && this.isCanBack) {
  365. this.onModeChange()
  366. this.isCanBack = false
  367. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  368. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  369. setTimeout(() => {
  370. if (this.modeType == 2) {
  371. if (this.isGridMusic) {
  372. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  373. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  374. } else {
  375. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  376. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  377. }
  378. } else if (this.modeType == 3) {
  379. if (this.isGridMusic) {
  380. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  381. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  382. } else {
  383. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  384. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  385. }
  386. }
  387. }, 200)
  388. return
  389. }
  390. if (this.isHistory || this.isFavMusic) {
  391. this.isHistory = false
  392. this.getSortedFiles(this.currentPath)
  393. return
  394. }
  395. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  396. animateTo({ duration: 555 }, () => {
  397. // 动画闭包内控制Image组件的出现和消失
  398. this.isShowDrawer = !this.isShowDrawer
  399. this.offsetX = 0
  400. })
  401. return
  402. }
  403. //返回上一级歌单的滚动位置
  404. setTimeout(() => {
  405. if (this.modeType == 0) {
  406. if (this.isGridMusic) {
  407. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  408. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  409. } else {
  410. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  411. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  412. }
  413. }
  414. }, 300)
  415. this.currentPath = Utility.getParentDirectory(this.currentPath)
  416. Logger.info('this.currentPath2 = ' + this.currentPath)
  417. this.getSortedFiles(this.currentPath)
  418. }
  419. // 组件生命周期
  420. aboutToAppear() {
  421. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  422. this.tipPopup = !this.tipPopup
  423. PreferencesUtil.putSync('isFirstTiped',false)
  424. }
  425. this.initSetting()
  426. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  427. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  428. Utility.getAppName(getContext(this)).then((appName: string) => {
  429. this.appName = appName
  430. })
  431. this.packName = AppUtil.getBundleName()
  432. this.loadCacheFromStorage(); // 加载缓存
  433. this.mkDownLoadDir()
  434. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  435. // 监听广播事件(打开其他应用处理)
  436. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  437. this.saveVideoDatas([eventData.data?.message], true)
  438. });
  439. //侧滑广播接收时间
  440. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  441. // 监听广播事件(打开其他应用处理)
  442. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  443. animateTo({ duration: 555 }, () => {
  444. this.doSwipBack()
  445. })
  446. });
  447. //ScanFilePage广播接收时间
  448. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  449. // 监听ScanFilePage广播事件(更新数据库)
  450. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  451. this.doUpdateData()
  452. });
  453. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  454. // 监听广播事件(通用设置配置更新)
  455. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  456. this.doChangeSetting()
  457. });
  458. let event: Callback<InterruptEvent> = (event) => {
  459. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  460. this.savePlaybackPosition()
  461. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  462. this.pause();
  463. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  464. this.startPlayOrResumePlay();
  465. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  466. this.stop();
  467. }
  468. }
  469. this.mIjkMediaPlayer.on('audioInterrupt', event);
  470. // 音频设备断连回调处理
  471. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  472. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  473. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  474. // this.pause();
  475. // }
  476. // }
  477. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  478. this.makeWorker()
  479. //折叠屏的屏幕显示模式变化
  480. display.on('foldDisplayModeChange', (data) => {
  481. this.doChangeBarHeight()
  482. });
  483. display.on('foldStatusChange', (data) => {
  484. Logger.info('onecold foldStatusChange ')
  485. });
  486. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  487. // 读取 themeMode 并同步 currentColorMode
  488. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  489. this.applyThemeMode(this.themeMode)
  490. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  491. AppStorage.setOrCreate('themeColor', themeColor);
  492. this.themeColor = themeColor;
  493. this.doChangeSetting()
  494. this.windowClass.on('windowSizeChange', (size) => {
  495. LogUtil.info('onecold windowSizeChange')
  496. this.doChangeBarHeight()
  497. let viewWidth = px2vp(size.width);
  498. let viewHeight = px2vp(size.height);
  499. if(this.isPhoneLan()){
  500. this.is_auto_hide_progress = false
  501. if(this.isHiCar()){
  502. return
  503. }
  504. setTimeout(() => {
  505. this.is_auto_hide_progress = true
  506. }, 6000)
  507. }else{
  508. this.startAutoHide()
  509. }
  510. });
  511. this.eventHub.on('onStateChange', (fg: boolean) => {
  512. if (fg && this.curState === 'STARTED') {
  513. this.stopPip();
  514. }
  515. });
  516. }
  517. startAutoHide() {
  518. if(this.isHiCar()){
  519. return
  520. }
  521. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  522. console.info('onecold startAutoHide')
  523. this.is_auto_hide_progress = false
  524. setTimeout(() => {
  525. this.is_auto_hide_progress = true
  526. }, 6000)
  527. }
  528. }
  529. applyThemeMode(mode: number) {
  530. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  531. if (mode === 1) {
  532. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  533. } else if (mode === 2) {
  534. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  535. }
  536. AppStorage.setOrCreate('currentColorMode', colorMode)
  537. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  538. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  539. AppStorage.setOrCreate('themeMode', mode)
  540. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  541. // 只有强制浅色/深色时才主动设置
  542. const context = getContext(this) as common.UIAbilityContext
  543. context.getApplicationContext().setColorMode(colorMode)
  544. }
  545. initSetting() {
  546. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  547. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  548. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  549. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  550. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  551. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  552. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  553. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  554. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  555. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  556. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  557. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  558. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  559. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  560. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  561. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  562. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  563. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  564. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  565. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  566. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  567. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  568. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  569. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, false)
  570. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  571. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  572. if(this.volumeSmall){
  573. this.volume = 0.5
  574. }else{
  575. this.volume = 1
  576. }
  577. //如果是hicar连接状态,这些都是false
  578. if(this.isHiCar()){
  579. this.isShowTitleBar = false//不显示导航栏
  580. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  581. {
  582. this.isShowHeader = false//二级菜单不显示头部
  583. this.isGridMusic= false//用list不用网格
  584. this.isCoverTopBig = false
  585. }
  586. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  587. }
  588. if (this.isSavePlayMode) {
  589. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  590. }
  591. if (this.isCustomizeBg) {
  592. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  593. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  594. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  595. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  596. } else {
  597. if (!this.isDarkMode) {
  598. this.titleBarModel.setTitleBarBackground(this.themeColor)
  599. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  600. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  601. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  602. } else {
  603. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  604. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  605. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  606. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  607. }
  608. }
  609. }
  610. doChangeSetting() {
  611. this.initSetting()
  612. this.deleteCache(this.currentPath)
  613. if (this.modeType === 0) {
  614. this.getSortedFiles(this.currentPath)
  615. }
  616. }
  617. doChangeBarHeight() {
  618. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  619. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  620. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  621. this.setBarHeightNormal()
  622. }
  623. }
  624. onPageShow() {
  625. this.knockController?.immersiveListening();
  626. app.setImageCacheCount(100);
  627. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  628. app.setImageRawDataCacheSize(104857600);
  629. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  630. }
  631. //开启线程查看各个数据库
  632. makeWorker() {
  633. setTimeout(() => {
  634. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  635. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  636. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  637. // workerInstance.postMessage({
  638. // code: 1,
  639. // data1: this.context,
  640. // data2: this.rootPath,
  641. // data3: this.lockPath,
  642. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  643. // });
  644. PreferencesUtil.putSync('isFirstApp', false)
  645. } else {
  646. workerInstance.postMessage({ code: 2, data: this.context });
  647. workerInstance.postMessage({ code: 3, data: this.context });
  648. workerInstance.postMessage({ code: 4, data: this.context });
  649. this.getHistoryList(false)
  650. }
  651. }, 1000)
  652. workerInstance.onmessage = (e: MessageEvents): void => {
  653. switch (e.data.code) {
  654. case 101: //第一次扫描文件夹入库
  655. ToastUtil.showToast('刷新同步数据库成功!')
  656. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  657. this.doUpdateData()
  658. break;
  659. case 102: //查询媒体库列表
  660. this.mediaKuList = e.data.data
  661. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  662. Utility.doSortListAscending(this.mediaKuList)
  663. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  664. if (this.modeType === 1) {
  665. this.updateListData(this.mediaKuList)
  666. }
  667. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  668. break;
  669. case 103: //收到查询艺术家列表
  670. this.artistMap = e.data.data1;
  671. this.artistList = e.data.data2;
  672. PreferencesUtil.putSync('artistCount', this.artistList.length)
  673. break;
  674. case 104: //收到查询专辑列表
  675. this.albumMap = e.data.data1;
  676. this.albumList = e.data.data2
  677. //查询完毕在启动是否自动播放
  678. if (this.isStartAutoPlay) {
  679. this.startPlayOrResumePlay()
  680. }
  681. PreferencesUtil.putSync('albumCount', this.albumList.length)
  682. break;
  683. }
  684. };
  685. // 在调用terminate后,执行onexit
  686. workerInstance.onexit = (code) => {
  687. console.log("main thread terminate");
  688. }
  689. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  690. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  691. workerInstance.onerror = (err: ErrorEvent) => {
  692. console.log("onerror" + err.message);
  693. }
  694. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  695. //碰一碰分享的监听
  696. this.knockController = KnockController.getInstance(this.context);
  697. this.knockController?.immersiveListening();
  698. }
  699. onPageHide(): void {
  700. this.knockController?.immersiveDisableListening();
  701. }
  702. @State isFirstStartPlay: boolean = false
  703. //获取download_path
  704. async mkDownLoadDir() {
  705. const documentViewPicker = new picker.DocumentViewPicker()
  706. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  707. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  708. // this.rootPath = this.download_path
  709. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  710. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  711. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  712. Logger.info('onecold rootPath = ' + this.rootPath)
  713. Logger.info('onecold lockPath = ' + this.lockPath)
  714. if (!FileUtil.accessSync(this.lockPath)) {
  715. FileUtil.mkdirSync(this.lockPath)
  716. }
  717. if (!FileUtil.accessSync(this.favPath)) {
  718. FileUtil.mkdirSync(this.favPath)
  719. }
  720. if (!FileUtil.accessSync(this.historyPath)) {
  721. FileUtil.mkdirSync(this.historyPath)
  722. }
  723. this.getSortedFiles(this.rootPath).then(() => {
  724. this.isFavMusic = false
  725. //穿山甲
  726. // this.loadBannerAd(CSJUtil.getBannerID())
  727. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  728. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  729. if (ArrayUtil.isEmpty(this.songList)) {
  730. this.songList = this.getCurFileList()
  731. } else {
  732. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  733. }
  734. if (ArrayUtil.isNotEmpty(this.songList)) {
  735. this.isFirstStartPlay = true
  736. this.sonDataSource.pushArrayData(this.songList)
  737. if (this.currentSong === undefined) {
  738. this.isFirstStartPlay = false
  739. this.currentSong = this.songList[0]
  740. }
  741. this.videoUrl = this.currentSong.filePath
  742. this.name = this.currentSong.name
  743. this.cover = this.currentSong.pixelMapPath
  744. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  745. } else {
  746. this.name = '空空如也'
  747. }
  748. })
  749. this.getFavList(false)
  750. }
  751. getFavList(isFavRefresh: boolean) {
  752. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  753. this.favList = result
  754. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  755. this.videoLocalList = this.favList
  756. this.updateListData(this.videoLocalList)
  757. }
  758. })
  759. }
  760. getHistoryList(isRefresh: boolean) {
  761. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  762. this.historyList = result
  763. // for (let i = 0; i < this.historyList.length; i++) {
  764. //
  765. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  766. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  767. // }
  768. if (isRefresh) {
  769. this.videoLocalList = this.historyList
  770. this.updateListData(this.videoLocalList, true)
  771. }
  772. })
  773. }
  774. // 组件消失生命周期
  775. aboutToDisappear() {
  776. console.info('LifeCycleComponent aboutToDisappear');
  777. this.knockController?.immersiveDisableListening();
  778. this.curIndex = 0
  779. emitter.off(2);
  780. emitter.off(101);
  781. emitter.off(888);
  782. emitter.off(333);
  783. this.mDestroyPage = true;
  784. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  785. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  786. this.stop();
  787. }
  788. this.mIjkMediaPlayer.off('audioInterrupt');
  789. if (workerInstance) {
  790. workerInstance.terminate();
  791. }
  792. this.stopPip();
  793. this.destroyPipController()
  794. }
  795. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  796. this.isFavMusic = false
  797. if (isWorkerPost) {
  798. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  799. }
  800. if (this.modeType !== 0) {
  801. return
  802. }
  803. this.isCanBack = false
  804. this.currentPath = curPath
  805. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  806. if (curPath === this.rootPath) {
  807. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  808. } else {
  809. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  810. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  811. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  812. }
  813. }
  814. // Get the current file list and calculate its hash
  815. this.fileList = FileUtil.listFileSync(curPath);
  816. const currentHash = simpleHash(this.fileList);
  817. // Check cache
  818. const cachedValue = this.findCache(curPath);
  819. Logger.info('onecold cachedValue = ' + cachedValue)
  820. const cachedHash = this.findStringCache(curPath + '_hash');
  821. const cachedDirList = this.findCache(curPath + "_dirList");
  822. if (cachedValue !== undefined) {
  823. // this.videoLocalList = cachedValue;
  824. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  825. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  826. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  827. }
  828. this.updateListData(cachedValue)
  829. }
  830. if (cachedDirList !== undefined) {
  831. this.dirList = cachedDirList
  832. }
  833. //通过当前hash值和缓存hash判断list有没有变化
  834. if (cachedValue && cachedHash === currentHash) {
  835. return;
  836. }
  837. this.fileList = FileUtil.listFileSync(curPath)
  838. let directories: Array<VideoItem> = [];
  839. let files: Array<VideoItem> = [];
  840. for (let i = 0; i < this.fileList.length; i++) {
  841. console.info(`The name of file: ${this.fileList[i]}`);
  842. let path = curPath + '/' + this.fileList[i]
  843. if (FileUtil.isDirectory(path)) {
  844. let item: VideoItem =
  845. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  846. '')
  847. if (this.isShowDir(item.name)) {
  848. directories.push(item);
  849. }
  850. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  851. // Utility.doSortListAscending(directories)
  852. } else {
  853. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  854. let item: VideoItem =
  855. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  856. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  857. files.push(item);
  858. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  859. // this.doSortListAscending(files)
  860. }
  861. }
  862. }
  863. }
  864. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  865. if (this.currentPath !== this.lockPath) {
  866. files = result;
  867. }
  868. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  869. Utility.doSortListAscending(files)
  870. if (this.currentPath === this.rootPath) {
  871. this.dirList = directories
  872. this.addCache(curPath + "_dirList", this.dirList);
  873. }
  874. //插入广告先注释掉
  875. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  876. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  877. // directories.push(adItem)
  878. // }
  879. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  880. this.videoLocalList = directories.concat(files);
  881. this.updateListData(this.videoLocalList)
  882. if (ArrayUtil.isNotEmpty(files)) {
  883. if (this.currentPath != this.rootPath) {
  884. if (files) {
  885. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  886. }
  887. }
  888. // 缓存结果
  889. this.addCache(curPath, this.videoLocalList);
  890. await this.saveCacheToStorage(); // 保存缓存至本地存储
  891. this.addStringCache(curPath + '_hash', currentHash);
  892. }
  893. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  894. // for (let i = 0; i < this.videoLocalList.length; i++) {
  895. //
  896. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  897. //
  898. // }
  899. // this.setButtonStatus()
  900. if (isOpen) {
  901. if (destPath === undefined) {
  902. // 处理 destPath 为 undefined 的情况
  903. return
  904. }
  905. if (destPath.endsWith('.lrc')) {
  906. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  907. if (StrUtil.isNotEmpty(this.videoUrl)) {
  908. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  909. this.initLyric(lyricPath);
  910. }
  911. return
  912. }
  913. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  914. this.doPlay(item2)
  915. this.isShowPlay = true
  916. }
  917. });
  918. }
  919. //扫描文件夹入库
  920. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  921. const files = FileUtil.listFileSync(curPath);
  922. let mediaItems: VideoItem[] = [];
  923. Logger.info('onecold scanDirectory start ')
  924. for (const file of files) {
  925. const fPath = `${curPath}/${file}`;
  926. if (fPath === this.lockPath) {
  927. Logger.info(`Skipping locked path: ${fPath}`);
  928. continue;
  929. }
  930. if (FileUtil.isDirectory(fPath)) {
  931. // Recursively scan subdirectories
  932. const subDirItems = await this.scanDirectory(fPath);
  933. mediaItems = mediaItems.concat(subDirItems);
  934. } else {
  935. Logger.info('onecold scanDirectory filePath = ' + fPath)
  936. // Process media files
  937. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  938. let mediaItem: VideoItem =
  939. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  940. mediaItems.push(mediaItem);
  941. this.table.insert(mediaItem, (id: number) => {
  942. });
  943. }
  944. }
  945. }
  946. return mediaItems;
  947. }
  948. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  949. animateTo({ duration: 888 }, () => {
  950. this.opacityItem = 0;
  951. });
  952. setTimeout(() => {
  953. this.videoLocalList = mList;
  954. if (!noSort) {
  955. if (this.modeType === 0 || this.modeType === 1) {
  956. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  957. this.doSortType(this.sortType)
  958. }
  959. }
  960. this.dataSource.pushArrayData(this.videoLocalList)
  961. animateTo({ duration: 888 }, () => {
  962. this.opacityItem = 1;
  963. });
  964. this.setButtonStatus()
  965. }, 200);
  966. }
  967. //排序模式和多选模式
  968. showPupDialog() {
  969. if (this.modeType === 2 || this.modeType === 3) {
  970. this.titleBarModel.setRightIcon(null)
  971. } else {
  972. this.titleBarModel.setRightIcon(($r('app.media.add')))
  973. }
  974. let dataBean = new BubbleBean()
  975. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  976. dataBean.color = this.themeColor
  977. dataBean.modeType = this.modeType
  978. dataBean.imageRes =
  979. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  980. $r('app.media.refresh')]
  981. let pup: XPopup;
  982. if (this.isDarkMode) {
  983. pup = XPopup.Builder()
  984. .setPopupPosition(PopupPosition.BOTTOM)
  985. .atView('pup_positon_music')
  986. .setBackgroundColor(Color.Black)
  987. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  988. .show()
  989. } else {
  990. pup = XPopup.Builder()
  991. .setPopupPosition(PopupPosition.BOTTOM)
  992. .atView('pup_positon_music')
  993. .setBackgroundColor(Color.White)
  994. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  995. .show()
  996. }
  997. dataBean.onItemClick = (i) => {
  998. XPopup.dismissTop()
  999. switch (i) {
  1000. case 0: //首页
  1001. this.modeType = 0
  1002. this.getSortedFiles(this.currentPath)
  1003. break
  1004. case 1:
  1005. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1006. this.modeType = 1
  1007. this.updateListData(this.mediaKuList)
  1008. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1009. break
  1010. case 2:
  1011. this.modeType = 2
  1012. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1013. this.updateListData(this.artistList)
  1014. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1015. break
  1016. case 3:
  1017. this.modeType = 3
  1018. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1019. this.updateListData(this.albumList)
  1020. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1021. break
  1022. case 4: //同步数据
  1023. this.asyncCurrentPathData()
  1024. break
  1025. }
  1026. }
  1027. }
  1028. getCurFileList(): Array<VideoItem> {
  1029. let files: Array<VideoItem> = [];
  1030. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1031. for (let i = 0; i < this.videoLocalList.length; i++) {
  1032. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1033. files.push(this.videoLocalList[i]);
  1034. }
  1035. }
  1036. }
  1037. return files
  1038. }
  1039. setButtonStatus() {
  1040. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1041. this.isZero = false
  1042. } else {
  1043. this.isZero = true
  1044. }
  1045. if (this.currentPath !== this.rootPath &&
  1046. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1047. this.isHasDir = true //不为空,说明有子文件夹
  1048. } else {
  1049. this.isHasDir = false
  1050. }
  1051. }
  1052. showRankDialog() {
  1053. if (this.modeType === 2 || this.modeType === 3) {
  1054. //动作面板
  1055. DialogHelper.showBottomSheetDialog({
  1056. title: "请选择排序模式",
  1057. maskColor: Color.Transparent,
  1058. // sheets: ["按名称升序", "按名称降序"],
  1059. sheets: [
  1060. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1061. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1062. ],
  1063. backgroundColor: $r('app.color.bg_card'),
  1064. height: '30%',
  1065. transition: AnimationHelper.transitionInDown(555),
  1066. onAction: (index) => {
  1067. switch (index) {
  1068. case 0:
  1069. Utility.doSortListAscending(this.videoLocalList)
  1070. break;
  1071. case 1:
  1072. Utility.doSortListDescending(this.videoLocalList)
  1073. break;
  1074. }
  1075. this.updateListData(this.videoLocalList)
  1076. }
  1077. })
  1078. return
  1079. }
  1080. //动作面板
  1081. DialogHelper.showBottomSheetDialog({
  1082. title: "请选择排序模式",
  1083. maskColor: Color.Transparent,
  1084. height: '75%',
  1085. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1086. sheets: [
  1087. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1088. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1089. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1090. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1091. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1092. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1093. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1094. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1095. ],
  1096. backgroundColor: $r('app.color.bg_card'),
  1097. transition: AnimationHelper.transitionInDown(555),
  1098. onAction: (index) => {
  1099. this.doSortType(index)
  1100. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1101. this.updateListData(this.videoLocalList, true)
  1102. }
  1103. })
  1104. }
  1105. doSortType(index: number) {
  1106. switch (index) {
  1107. case 0:
  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 artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1116. const artistB = b.artist?.trim() || '';
  1117. return artistA.localeCompare(artistB);
  1118. });
  1119. break;
  1120. case 1:
  1121. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1122. // 类型排序优先级
  1123. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1124. if (typeOrder !== 0) {
  1125. return typeOrder;
  1126. }
  1127. // 处理艺术家可能为undefined的字符串比较
  1128. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1129. const artistB = b.artist?.trim() || '';
  1130. return artistB.localeCompare(artistA);
  1131. });
  1132. break;
  1133. case 2:
  1134. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1135. // 类型排序优先级
  1136. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1137. if (typeOrder !== 0) {
  1138. return typeOrder;
  1139. }
  1140. // 处理专辑可能为undefined的字符串比较
  1141. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1142. const albumB = b.album?.trim() || '';
  1143. return albumA.localeCompare(albumB);
  1144. });
  1145. break;
  1146. case 3:
  1147. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1148. // 类型排序优先级
  1149. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1150. if (typeOrder !== 0) {
  1151. return typeOrder;
  1152. }
  1153. // 处理专辑可能为undefined的字符串比较
  1154. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1155. const albumB = b.album?.trim() || '';
  1156. return albumB.localeCompare(albumA);
  1157. });
  1158. break;
  1159. case 4:
  1160. Utility.doSortListAscending(this.videoLocalList)
  1161. break;
  1162. case 5:
  1163. Utility.doSortListDescending(this.videoLocalList)
  1164. break;
  1165. case 6:
  1166. this.videoLocalList.sort((a, b) => {
  1167. // First, sort by type
  1168. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1169. if (typeOrder !== 0) {
  1170. return typeOrder;
  1171. }
  1172. // If types are the same, sort by cTime in ascending order
  1173. return a.cTime.localeCompare(b.cTime);
  1174. });
  1175. break;
  1176. case 7:
  1177. this.videoLocalList.sort((a, b) => {
  1178. // First, sort by type
  1179. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1180. if (typeOrder !== 0) {
  1181. return typeOrder;
  1182. }
  1183. // If types are the same, sort by cTime in descending order
  1184. return b.cTime.localeCompare(a.cTime);
  1185. });
  1186. break;
  1187. }
  1188. }
  1189. showSheelDialog() {
  1190. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1191. // this.showTips()
  1192. // return
  1193. // }
  1194. this.showAddDialog()
  1195. }
  1196. showAddDialog() {
  1197. if (this.modeType === 2 || this.modeType === 3) {
  1198. return
  1199. }
  1200. DialogHelper.showActionSheetDialog({
  1201. title: "请选择添加方式(建议歌词文件一起导入)",
  1202. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1203. sheets: [
  1204. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1205. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1206. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1207. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1208. ],
  1209. maskColor: Color.Transparent,
  1210. backgroundColor: $r('app.color.bg_card'),
  1211. transition: AnimationHelper.transitionInDown(555),
  1212. onAction: (index) => {
  1213. switch (index) {
  1214. case 0:
  1215. if (this.modeType === 0) {
  1216. this.showMkDialog()
  1217. } else {
  1218. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1219. }
  1220. break;
  1221. case 1:
  1222. this.callFilePickerSelectFile()
  1223. break;
  1224. case 2:
  1225. this.showTips()
  1226. break;
  1227. case 3:
  1228. this.goSelectMusic()
  1229. break;
  1230. }
  1231. }
  1232. })
  1233. }
  1234. //拉起音频
  1235. goSelectMusic() {
  1236. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1237. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1238. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1239. ) {
  1240. ToastUtil.showToast('暂时不支持该设备')
  1241. return
  1242. }
  1243. try {
  1244. let documentSelectOptions = new picker.DocumentSelectOptions();
  1245. documentSelectOptions.authMode = true
  1246. documentSelectOptions.multiAuthMode = true
  1247. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1248. let documentPicker = new picker.DocumentViewPicker(this.context);
  1249. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1250. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1251. this.saveVideoDatas(documentSelectResult)
  1252. }
  1253. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1254. JSON.stringify(documentSelectResult));
  1255. }).catch((err: BusinessError) => {
  1256. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1257. });
  1258. } catch (error) {
  1259. let err: BusinessError = error as BusinessError;
  1260. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1261. }
  1262. }
  1263. async showTips() {
  1264. DialogHelper.showTipsDialog({
  1265. title: '使用提示:自动导入教程',
  1266. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1267. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1268. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1269. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1270. onAction: (action) => {
  1271. if (action == DialogAction.TWO) {
  1272. PreferencesUtil.putSync('isFirstMusic', false)
  1273. router.pushUrl({
  1274. url: 'pages/ScanFilePage'
  1275. });
  1276. }
  1277. }
  1278. })
  1279. }
  1280. showMkDialog() {
  1281. DialogHelper.showTextInputDialog({
  1282. title: '新建歌单',
  1283. maskColor: Color.Transparent,
  1284. text: '',
  1285. transition: AnimationHelper.transitionInDown(666),
  1286. onChange: (text) => {
  1287. console.error("onChange: " + text);
  1288. },
  1289. onAction: (action, dialogId, content) => {
  1290. // ToastUtil.showToast('content = ' +content)
  1291. if (action == DialogAction.TWO) {
  1292. const newName = content
  1293. const newPath = this.currentPath + '/' + newName
  1294. FileUtil.mkdir(newPath, true).then(() => {
  1295. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1296. this.getSortedFiles(this.currentPath)
  1297. }).catch((error: BusinessError) => {
  1298. console.error(error.message);
  1299. });
  1300. }
  1301. }
  1302. })
  1303. }
  1304. @State progress: number = 0;
  1305. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1306. if (ArrayUtil.isEmpty(uris)) {
  1307. return;
  1308. }
  1309. let newUris: string[] = [];
  1310. this.progress = 0
  1311. DialogHelper.showLoadingProgress({
  1312. progress: this.progress,
  1313. backCancel: false,
  1314. autoCancel: false,
  1315. loadColor: this.themeColor,
  1316. fontColor: this.themeColor
  1317. });
  1318. // 计算所有文件的总大小
  1319. let totalSize = 0;
  1320. for (let uri of uris) {
  1321. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1322. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1323. await fileIo.close(sourceFile.fd);
  1324. }
  1325. let totalRead = 0;
  1326. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1327. Logger.info(TAG, 'destPath uri: ' + destPath);
  1328. for (let i = 0; i < uris.length; i++) {
  1329. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1330. Logger.info(TAG, 'filePath uri: ' + filePath);
  1331. newUris.push(filePath);
  1332. try {
  1333. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1334. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1335. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1336. const buffer = new ArrayBuffer(buffSize);
  1337. let len = await fileIo.read(sourceFile.fd, buffer);
  1338. while (len > 0) {
  1339. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1340. totalRead += len;
  1341. // 计算总进度
  1342. this.progress = Math.floor((totalRead / totalSize) * 100);
  1343. DialogHelper.updateLoading('正在导入', this.progress);
  1344. len = await fileIo.read(sourceFile.fd, buffer);
  1345. }
  1346. await fileIo.close(sourceFile.fd);
  1347. await fileIo.close(destFile.fd);
  1348. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1349. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1350. let mediaItem: VideoItem =
  1351. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1352. this.table.insert(mediaItem, (id: number) => {
  1353. // 删除目标路径缓存
  1354. this.cache.delete(this.currentPath);
  1355. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1356. });
  1357. }
  1358. }
  1359. } catch (error) {
  1360. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1361. }
  1362. }
  1363. DialogHelper.closeLoading()
  1364. this.isZero = false
  1365. // setTimeout(() => {
  1366. // // 删除目标路径缓存
  1367. // this.cache.delete(this.currentPath);
  1368. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1369. // }, 500);
  1370. Logger.info(TAG, 'scan select video result:' + newUris)
  1371. }
  1372. //拉起音频
  1373. // goSelectMusic(){
  1374. //
  1375. // try {
  1376. // let audioSelectOptions = new picker.AudioSelectOptions();
  1377. // let audioPicker = new picker.AudioViewPicker(this.context);
  1378. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1379. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1380. // this.saveVideoDatas(audioSelectResult)
  1381. // }
  1382. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1383. // }).catch((err: BusinessError) => {
  1384. //
  1385. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1386. // });
  1387. // } catch (error) {
  1388. // let err: BusinessError = error as BusinessError;
  1389. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1390. // }
  1391. //
  1392. //
  1393. //
  1394. // }
  1395. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1396. if (!item) {
  1397. return undefined;
  1398. }
  1399. try {
  1400. let selectUris: Array<string> = [];
  1401. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1402. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1403. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1404. photoSelectOptions.maxSelectNumber = 1;
  1405. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1406. selectUris = photoSelectResult.photoUris;
  1407. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1408. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1409. console.info('file fd: ' + file.fd);
  1410. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1411. let imagePath = this.context.filesDir + FileUtil.separator + name
  1412. imagePath = fileUri.getUriFromPath(imagePath)
  1413. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1414. fileIo.copyFileSync(file.fd, file2.fd)
  1415. fileIo.closeSync(file);
  1416. fileIo.closeSync(file2);
  1417. if (item.filePath == this.currentSong?.filePath) {
  1418. this.cover = imagePath
  1419. }
  1420. if (item) {
  1421. item.pixelMapPath = imagePath
  1422. }
  1423. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1424. if (success) {
  1425. this.doUpdateData()
  1426. console.log("onecold 更新音乐封面成功,数据库已同步");
  1427. } else {
  1428. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1429. }
  1430. });
  1431. LogUtil.debug("onecold this.cover =" + this.cover)
  1432. return FileUtil.getFilePath(imagePath); // Return the image path here
  1433. } catch (err) {
  1434. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1435. return undefined;
  1436. }
  1437. }
  1438. // 拉起picker选择文件管理器
  1439. async callFilePickerSelectFile(): Promise<void> {
  1440. try {
  1441. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1442. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1443. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1444. } else {
  1445. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1446. }
  1447. let documentPicker = new picker.DocumentViewPicker();
  1448. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1449. Logger.info(TAG,
  1450. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1451. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1452. this.saveVideoDatas(DocumentSelectResult)
  1453. }
  1454. }).catch((err: BusinessError) => {
  1455. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1456. });
  1457. } catch (err) {
  1458. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1459. }
  1460. }
  1461. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1462. //操作确认类弹出框
  1463. DialogHelper.showAlertDialog({
  1464. maskColor: Color.Transparent,
  1465. content: "确定要删除这个文件吗?",
  1466. backgroundColor: Color.Grey,
  1467. transition: AnimationHelper.transitionInUp(555),
  1468. onAction: (action) => {
  1469. if (action == DialogAction.ONE) {
  1470. // ToastUtil.showToast(`您点击了取消按钮`);
  1471. } else if (action == DialogAction.TWO) {
  1472. // ToastUtil.showToast(`您点击了确认按钮`);
  1473. this.doDelete(item, index + '', filePath)
  1474. }
  1475. }
  1476. })
  1477. }
  1478. //删除单个索引index的视频
  1479. doDelete(item: VideoItem, index: string, filePath: string) {
  1480. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1481. Logger.info(TAG, 'delete filePath = ' + filePath);
  1482. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1483. //旧文件删除
  1484. this.table.deleteDataForParentPath(item.filePath, () => {
  1485. FileUtil.rmdir(filePath).then(() => {
  1486. this.videoLocalList.splice(Number(index), 1)
  1487. this.deleteCache(this.currentPath)
  1488. this.getSortedFiles(this.currentPath, true)
  1489. }).catch((error: BusinessError) => {
  1490. console.error(error.message);
  1491. });
  1492. });
  1493. } else {
  1494. this.table.deleteData(item, () => {
  1495. FileUtil.unlink(filePath)
  1496. .catch((error: BusinessError) => {
  1497. console.error(error.message);
  1498. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1499. })
  1500. .finally(() => {
  1501. this.videoLocalList.splice(Number(index), 1)
  1502. this.deleteCache(this.currentPath)
  1503. this.getSortedFiles(this.currentPath, true)
  1504. });
  1505. });
  1506. }
  1507. }
  1508. }
  1509. //重命名的对话框
  1510. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1511. DialogHelper.showTextInputDialog({
  1512. title: '重命名',
  1513. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1514. maskColor: Color.Transparent,
  1515. backgroundColor: Color.Grey,
  1516. transition: AnimationHelper.transitionInDown(666),
  1517. onChange: (text) => {
  1518. console.error("onChange: " + text);
  1519. },
  1520. onAction: (action, dialogId, content) => {
  1521. // ToastUtil.showToast('content = ' +content)
  1522. if (action == DialogAction.TWO) {
  1523. const newName = content
  1524. const newPath = this.currentPath + '/' + newName
  1525. console.log("onecold item = " + item.type);
  1526. this.doReName(index, newName, filePath, newPath, item)
  1527. }
  1528. }
  1529. })
  1530. }
  1531. //剪切 移动到另个文件夹的对话框
  1532. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1533. Logger.info('onecold showCutDialog')
  1534. let mList: Array<string> = []
  1535. let rPath = this.rootPath
  1536. if (isCurrent) {
  1537. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1538. rPath = this.currentPath
  1539. } else {
  1540. mList = Utility.getNameList(this.dirList);
  1541. rPath = this.rootPath
  1542. }
  1543. let dataBean = new BubbleBean()
  1544. dataBean.data = mList
  1545. dataBean.color = this.themeColor
  1546. dataBean.onItemClick = (i) => {
  1547. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1548. Logger.info('newPath = ' + newPath)
  1549. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1550. ToastUtil.showToast('移动成功')
  1551. this.table.deleteData(item, () => {
  1552. });
  1553. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1554. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1555. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1556. CommonConstants.TYPE_LOCAL, true);
  1557. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1558. this.table.insert(newItem, (id: number) => {
  1559. //加入数据库
  1560. });
  1561. }
  1562. this.cache.delete(this.currentPath); // 删除原路径缓存
  1563. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1564. this.getSortedFiles(this.currentPath, true)
  1565. }).catch((error: BusinessError) => {
  1566. console.error(error.message);
  1567. });
  1568. XPopup.dismissTop()
  1569. }
  1570. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1571. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1572. popupPosition = PopupPosition.TOP
  1573. }
  1574. if (index <= 3) {
  1575. popupPosition = PopupPosition.BOTTOM
  1576. }
  1577. let pup: XPopup
  1578. if (this.isDarkMode) {
  1579. pup = XPopup.Builder()
  1580. .setPopupPosition(popupPosition)
  1581. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1582. .setBackgroundColor(Color.Black)
  1583. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1584. .show()
  1585. } else {
  1586. pup = XPopup.Builder()
  1587. .setPopupPosition(popupPosition)
  1588. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1589. .setBackgroundColor(Color.White)
  1590. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1591. .show()
  1592. }
  1593. }
  1594. //复制 到另个文件夹的对话框
  1595. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1596. Logger.info('onecoldv showCopyDialog')
  1597. let mList: Array<string> = []
  1598. let rPath = this.rootPath
  1599. if (isCurrent) {
  1600. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1601. rPath = this.currentPath
  1602. } else {
  1603. mList = Utility.getNameList(this.dirList);
  1604. rPath = this.rootPath
  1605. }
  1606. let dataBean = new BubbleBean()
  1607. dataBean.data = mList
  1608. dataBean.isCopy = true
  1609. dataBean.color = this.themeColor
  1610. dataBean.onItemClick = (i) => {
  1611. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1612. Logger.info('newPath = ' + newPath)
  1613. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1614. ToastUtil.showToast('复制成功')
  1615. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1616. this.getSortedFiles(this.currentPath)
  1617. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1618. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1619. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1620. CommonConstants.TYPE_LOCAL, true);
  1621. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1622. this.table.insert(newItem, (id: number) => {
  1623. //加入数据库
  1624. });
  1625. }
  1626. }).catch((error: BusinessError) => {
  1627. console.error(error.message);
  1628. });
  1629. XPopup.dismissTop()
  1630. }
  1631. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1632. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1633. popupPosition = PopupPosition.TOP
  1634. }
  1635. if (index <= 3) {
  1636. popupPosition = PopupPosition.BOTTOM
  1637. }
  1638. let pup: XPopup
  1639. if (this.isDarkMode) {
  1640. pup = XPopup.Builder()
  1641. .setPopupPosition(popupPosition)
  1642. .atView(id)
  1643. .setMaxHeight('60%')
  1644. .setBackgroundColor(Color.Black)
  1645. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1646. .show();
  1647. } else {
  1648. pup = XPopup.Builder()
  1649. .setPopupPosition(popupPosition)
  1650. .atView(id)
  1651. .setMaxHeight('60%')
  1652. .setBackgroundColor(Color.White)
  1653. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1654. .show();
  1655. }
  1656. }
  1657. //重命名索引index的视频
  1658. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1659. FileUtil.rename(oldPath, newPath).then(async () => {
  1660. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1661. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1662. //如果是文件夹先删除源数据,再添加新数据
  1663. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1664. if (success) {
  1665. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1666. } else {
  1667. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1668. }
  1669. });
  1670. this.scanDirectory(newPath)
  1671. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1672. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1673. if (success) {
  1674. console.log(" onecold 重命名成功,数据库已同步");
  1675. } else {
  1676. console.error(" onecold 重命名数据库失败原因: " + error);
  1677. }
  1678. });
  1679. }
  1680. let mediaItem: VideoItem =
  1681. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1682. this.videoLocalList[index] = mediaItem;
  1683. }
  1684. this.cache.delete(this.currentPath)
  1685. this.getSortedFiles(this.currentPath, true)
  1686. }).catch((error: BusinessError) => {
  1687. console.error(error.message);
  1688. });
  1689. }
  1690. build() {
  1691. Scroll() {
  1692. Column() {
  1693. if (!this.isShowCoverHeader()) {
  1694. Column() {
  1695. Line().width('100%').height('100%')
  1696. }
  1697. .height(this.topRectHeight)
  1698. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1699. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1700. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1701. TitleBar({ model: $titleBarModel })
  1702. .id('pup_positon_music')
  1703. }
  1704. Stack() {
  1705. Column() {
  1706. XComponent({
  1707. id: 'xcomponentId',
  1708. type: 'surface',
  1709. libraryname: 'ijkplayer_napi',
  1710. controller: this.xcomponentController
  1711. })
  1712. .onLoad((event?: object) => {
  1713. if (!!event) {
  1714. this.initDelayPlay(event);
  1715. }
  1716. })
  1717. .onKeyEvent((event?: KeyEvent) => {
  1718. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1719. if (!event || event.type !== KeyType.Down) {
  1720. return;
  1721. }
  1722. //空格键 Space key controls pause/play
  1723. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1724. this.playOrPause()
  1725. }
  1726. // Right-click to fast forward
  1727. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1728. this.sessionFastForwardCallback(15);
  1729. }
  1730. // Left-click to rewind
  1731. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1732. this.sessionRewindCallback(15);
  1733. }
  1734. })
  1735. .onDestroy(() => {
  1736. })
  1737. .width('100%')// .width(this.videoWidth)
  1738. .aspectRatio(this.videoAspectRatio)
  1739. }
  1740. .aspectRatio(this.videoAspectRatio)
  1741. .justifyContent(FlexAlign.Center)
  1742. .backgroundColor(Color.Transparent)
  1743. .visibility(Visibility.Hidden)
  1744. .height(CommonConstants.FULL_PERCENT)
  1745. .width(CommonConstants.FULL_PERCENT)
  1746. Stack() {
  1747. Row() {
  1748. Blank()
  1749. .layoutWeight(1)
  1750. IndexerView(
  1751. {
  1752. indexArray: DEFAULT_INDEX,
  1753. selectedIndex: this.selectedIndex,
  1754. textSize: 12,
  1755. selectedColor: "#ff419ee5",
  1756. normalColor: "#ffa0a0a0",
  1757. floatSelectedTextColor: "#ffffff",
  1758. floatSelectedViewColor: "#ff419ee5",
  1759. onIndexChanged: (index) => {
  1760. this.listScroller.scrollToIndex(index)
  1761. }
  1762. })
  1763. .width(24)
  1764. .height("50%")
  1765. }.visibility(Visibility.None)
  1766. Column() {
  1767. if (!this.isShowCoverHeader()) {
  1768. this.tabTitle()
  1769. }
  1770. if (this.isGridMusic) {
  1771. this.getGridView()
  1772. } else {
  1773. this.getListView()
  1774. }
  1775. if (this.modeType == 0) {
  1776. Column() {
  1777. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1778. .width(130)
  1779. .height(50)
  1780. .margin({ top: 100, bottom: 40 })
  1781. .backgroundColor(this.themeColor)
  1782. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  1783. .onClick(() => {
  1784. this.asyncCurrentPathData()
  1785. })
  1786. }
  1787. .height(100)
  1788. .position({ top: 260 })
  1789. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  1790. .animation({ duration: 500 }),
  1791. TransitionEffect.scale({ x: 0, y: 0 })))
  1792. .justifyContent(FlexAlign.Center)
  1793. .opacity(this.isZero ? 1 : 0)
  1794. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  1795. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1796. .animation({
  1797. duration: 500,
  1798. curve: 'ease-in-out' // 可选动画曲线
  1799. })
  1800. .width('100%')
  1801. }
  1802. }
  1803. .layoutWeight(1)
  1804. .height('100%')
  1805. }
  1806. .layoutWeight(1)
  1807. .height('100%')
  1808. Row() {
  1809. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1810. .width('35%')
  1811. .height(60)
  1812. .margin({ top: 10, bottom: 10, right: 6 })
  1813. .backgroundColor(this.themeColor)
  1814. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1815. .onClick(() => {
  1816. if (this.isAllSelected) {
  1817. // 全不选
  1818. this.selectedFiles = [];
  1819. } else {
  1820. // 全选
  1821. this.selectedFiles = [...this.getCurFileList()];
  1822. }
  1823. this.isAllSelected = !this.isAllSelected;
  1824. })
  1825. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1826. .width('35%')
  1827. .height(60)
  1828. .id('music_cut')
  1829. .margin({ top: 10, bottom: 10, right: 6 })
  1830. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1831. .backgroundColor(this.themeColor)
  1832. .onClick(() => {
  1833. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1834. })
  1835. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1836. .width('35%')
  1837. .height(60)
  1838. .id('music_cut_current')
  1839. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1840. .margin({ top: 10, bottom: 10, right: 6 })
  1841. .backgroundColor(this.themeColor)
  1842. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1843. .onClick(() => {
  1844. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1845. })
  1846. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1847. .width('35%')
  1848. .height(60)
  1849. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1850. .margin({ top: 10, bottom: 10, right: 6 })
  1851. .backgroundColor(this.themeColor)
  1852. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1853. .onClick(() => {
  1854. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1855. })
  1856. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1857. .width('35%')
  1858. .height(60)
  1859. .margin({ top: 10, bottom: 10, right: 6 })
  1860. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  1861. .backgroundColor(this.themeColor)
  1862. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1863. .onClick(() => {
  1864. this.showWarnIsDelete()
  1865. })
  1866. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1867. .width('35%')
  1868. .height(60)
  1869. .margin({ top: 10, bottom: 10, right: 6 })
  1870. .backgroundColor(this.themeColor)
  1871. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1872. .onClick(() => {
  1873. this.selectedFiles = [];
  1874. this.isAllSelected = false
  1875. this.isMultiSelect = false
  1876. })
  1877. }
  1878. .width('100%')
  1879. .justifyContent(FlexAlign.Center)
  1880. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1881. .opacity(this.isMultiSelect ? 1 : 0)
  1882. .animation({
  1883. duration: 666,
  1884. curve: 'ease-in-out' // 可选动画曲线
  1885. })
  1886. .position(this.isShowCoverHeader() ? { bottom: 78 }
  1887. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  1888. }
  1889. .width('100%')
  1890. .height('100%')
  1891. .alignContent(Alignment.Top)
  1892. Column() {
  1893. this.PlayController()
  1894. }
  1895. .hitTestBehavior(HitTestMode.Transparent)
  1896. .position({ bottom: 0 }) // 将 Row 固定在底部
  1897. .opacity(this.barBottomOpacity)
  1898. }
  1899. .width('100%')
  1900. .height('100%')
  1901. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  1902. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  1903. .backgroundImagePosition(Alignment.Center)
  1904. .backdropBlur(this.blurValue)
  1905. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  1906. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1907. }
  1908. }
  1909. asyncCurrentPathData() {
  1910. if (this.modeType == 0) {
  1911. workerInstance.postMessage({
  1912. code: 1,
  1913. data1: this.context,
  1914. data2: this.currentPath,
  1915. data3: this.lockPath,
  1916. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1917. });
  1918. }
  1919. }
  1920. // 处理文件选择的函数
  1921. handleFileSelection(item: VideoItem, checked: boolean) {
  1922. if (checked) {
  1923. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1924. this.selectedFiles.push(item);
  1925. }
  1926. } else {
  1927. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1928. if (index > -1) {
  1929. this.selectedFiles.splice(index, 1);
  1930. }
  1931. }
  1932. }
  1933. showWarnIsDelete() {
  1934. //操作确认类弹出框
  1935. DialogHelper.showAlertDialog({
  1936. content: "确定要删除这些文件吗?",
  1937. transition: AnimationHelper.transitionInUp(666),
  1938. maskColor: Color.Transparent,
  1939. backgroundColor: Color.Grey,
  1940. onAction: (action) => {
  1941. if (action == DialogAction.ONE) {
  1942. // ToastUtil.showToast(`您点击了取消按钮`);
  1943. } else if (action == DialogAction.TWO) {
  1944. // ToastUtil.showToast(`您点击了确认按钮`);
  1945. this.deleteMultipleFiles()
  1946. }
  1947. }
  1948. })
  1949. }
  1950. //多选删除文件
  1951. deleteMultipleFiles() {
  1952. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1953. this.selectedFiles.forEach((item) => {
  1954. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1955. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1956. this.table.deleteDataForParentPath(item.filePath, () => {
  1957. FileUtil.rmdir(item.filePath).then(() => {
  1958. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1959. this.selectedFiles = [];
  1960. this.isMultiSelect = false
  1961. this.isAllSelected = false
  1962. this.cache.delete(this.currentPath);
  1963. this.getSortedFiles(this.currentPath, true);
  1964. }).catch((error: Error) => {
  1965. console.error(error.message);
  1966. });
  1967. });
  1968. } else {
  1969. this.table.deleteData(item, () => {
  1970. FileUtil.unlink(item.filePath).catch((error: Error) => {
  1971. console.error(error.message);
  1972. }).finally(() => {
  1973. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1974. this.selectedFiles = [];
  1975. this.isMultiSelect = false
  1976. this.isAllSelected = false
  1977. this.cache.delete(this.currentPath);
  1978. this.getSortedFiles(this.currentPath, true);
  1979. });
  1980. });
  1981. }
  1982. });
  1983. }
  1984. }
  1985. //多选移动文件
  1986. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1987. Logger.info('onecold showCutDialogForMultipleFiles')
  1988. let mList: Array<string> = []
  1989. let rPath = this.rootPath
  1990. if (isCurrent) {
  1991. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1992. rPath = this.currentPath
  1993. } else {
  1994. mList = Utility.getNameList(this.dirList);
  1995. rPath = this.rootPath
  1996. }
  1997. let dataBean = new BubbleBean();
  1998. dataBean.data = mList;
  1999. dataBean.color = this.themeColor
  2000. dataBean.onItemClick = (i) => {
  2001. const newDirPath = rPath + '/' + mList[i];
  2002. // Logger.info('newDirPath = ' + newDirPath)
  2003. this.selectedFiles.forEach((item) => {
  2004. const newPath = newDirPath + '/' + item.fileName;
  2005. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2006. ToastUtil.showToast('移动成功');
  2007. this.table.deleteData(item, () => {
  2008. this.cache.delete(this.currentPath); // 删除原路径缓存
  2009. this.cache.delete(newDirPath); // 删除目标路径缓存
  2010. this.getSortedFiles(this.currentPath, true);
  2011. });
  2012. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2013. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2014. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2015. CommonConstants.TYPE_LOCAL, true);
  2016. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2017. this.table.insert(newItem, (id: number) => {
  2018. //加入数据库
  2019. });
  2020. }
  2021. }).catch((error: Error) => {
  2022. console.error(error.message);
  2023. });
  2024. });
  2025. this.isMultiSelect = false
  2026. this.selectedFiles = [];
  2027. this.isAllSelected = false
  2028. XPopup.dismissTop();
  2029. };
  2030. let pup: XPopup
  2031. if (this.isDarkMode) {
  2032. pup = XPopup.Builder()
  2033. .setPopupPosition(PopupPosition.TOP)
  2034. .atView(viewId)
  2035. .setBackgroundColor(Color.Black)
  2036. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2037. .show();
  2038. } else {
  2039. pup = XPopup.Builder()
  2040. .setPopupPosition(PopupPosition.TOP)
  2041. .atView(viewId)
  2042. .setBackgroundColor(Color.White)
  2043. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2044. .show();
  2045. }
  2046. }
  2047. doFav(item: VideoItem) {
  2048. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2049. let isFav = 0
  2050. if (Utility.getIsFav(this.favList, item)) {
  2051. isFav = 0
  2052. } else {
  2053. isFav = 1
  2054. }
  2055. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2056. if (result) {
  2057. if (isFav === 1) {
  2058. ToastUtil.showToast('收藏成功');
  2059. } else {
  2060. ToastUtil.showToast('取消收藏成功');
  2061. }
  2062. this.deleteCache(this.currentPath)
  2063. this.getFavList(false)
  2064. if (this.modeType === 0 && !this.isFavMusic) {
  2065. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2066. this.getSortedFiles(this.currentPath)
  2067. }
  2068. workerInstance.postMessage({ code: 2, data: this.context });
  2069. workerInstance.postMessage({ code: 3, data: this.context });
  2070. workerInstance.postMessage({ code: 4, data: this.context });
  2071. }
  2072. })
  2073. }
  2074. //多选复制文件
  2075. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2076. console.log('onecold showCopyDialogForMultipleFiles');
  2077. let mList: Array<string> = []
  2078. let rPath = this.rootPath
  2079. if (isCurrent) {
  2080. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2081. rPath = this.currentPath
  2082. } else {
  2083. mList = Utility.getNameList(this.dirList);
  2084. rPath = this.rootPath
  2085. }
  2086. let dataBean = new BubbleBean();
  2087. dataBean.data = mList;
  2088. dataBean.isCopy = true
  2089. dataBean.color = this.themeColor
  2090. dataBean.onItemClick = (i) => {
  2091. const newDirPath = rPath + '/' + mList[i];
  2092. // Logger.info('newDirPath = ' + newDirPath)
  2093. this.selectedFiles.forEach((item) => {
  2094. const newPath = newDirPath + '/' + item.fileName;
  2095. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2096. ToastUtil.showToast('复制成功');
  2097. this.cache.delete(newDirPath); // 删除目标路径缓存
  2098. this.getSortedFiles(this.currentPath);
  2099. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2100. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2101. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2102. CommonConstants.TYPE_LOCAL, true);
  2103. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2104. this.table.insert(newItem, (id: number) => {
  2105. //加入数据库
  2106. });
  2107. }
  2108. }).catch((error: Error) => {
  2109. console.error(error.message);
  2110. });
  2111. });
  2112. this.isMultiSelect = false
  2113. this.selectedFiles = [];
  2114. this.isAllSelected = false
  2115. XPopup.dismissTop();
  2116. };
  2117. let pup: XPopup
  2118. if (this.isDarkMode) {
  2119. pup = XPopup.Builder()
  2120. .setPopupPosition(PopupPosition.TOP)
  2121. .atView(viewId)
  2122. .setBackgroundColor(Color.Black)
  2123. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2124. .show();
  2125. } else {
  2126. pup = XPopup.Builder()
  2127. .setPopupPosition(PopupPosition.TOP)
  2128. .atView(viewId)
  2129. .setBackgroundColor(Color.White)
  2130. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2131. .show();
  2132. }
  2133. }
  2134. @Builder
  2135. private DirItem(item: VideoItem, index?: number) {
  2136. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2137. Row() {
  2138. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2139. $r('app.media.music_group'))
  2140. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2141. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2142. .fillColor(this.themeColor)// .fontSize(33)
  2143. .alt($r('app.media.music_group'))
  2144. .borderRadius('100%')
  2145. .clip(true)
  2146. .margin({ left: 20, top: 8, bottom: 8 })
  2147. Column() {
  2148. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2149. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2150. .maxLines(1)// .width('88%')
  2151. .animation({
  2152. duration: 555,
  2153. curve: 'ease-in-out',
  2154. })
  2155. .transition({
  2156. type: TransitionType.Insert,
  2157. opacity: 0,
  2158. translate: { x: 160 }
  2159. })
  2160. .margin({ left: 10, right: 20 })
  2161. .fontColor($r('app.color.text_color'))
  2162. Row() {
  2163. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2164. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2165. .padding({ top: 8 })
  2166. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2167. .fontColor($r('app.color.text_color'))
  2168. .margin({ left: 10 })
  2169. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2170. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2171. .padding({ top: 8 })
  2172. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2173. .fontColor($r('app.color.text_color'))
  2174. .margin({ left: 10 })
  2175. Blank()
  2176. }
  2177. }
  2178. .height('100%')
  2179. .layoutWeight(1)
  2180. .justifyContent(FlexAlign.Center)
  2181. .alignItems(HorizontalAlign.Start)
  2182. Blank()
  2183. Image($r('app.media.arrow_right'))
  2184. .height(25)
  2185. .margin({ right: 10 })
  2186. .alignSelf(ItemAlign.Center)
  2187. .id(item.filePath)
  2188. }
  2189. }
  2190. .backgroundColor(Color.Transparent)
  2191. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2192. .width('100%')
  2193. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2194. .opacity(this.opacityItem) // 绑定透明度
  2195. }
  2196. isShowDir(dirName: string) {
  2197. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2198. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2199. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2200. if (dirName === undefined) {
  2201. return true
  2202. }
  2203. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2204. return this.isShowSimi
  2205. }
  2206. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2207. return this.isShowFAV
  2208. }
  2209. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2210. return this.isShowHistory
  2211. }
  2212. return true
  2213. }
  2214. @State opacityItem: number = 1; // 控制透明度的状态变量
  2215. @Builder
  2216. private MusicItem(item: VideoItem, index?: number) {
  2217. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2218. Row() {
  2219. Stack() {
  2220. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2221. .fillColor(this.themeColor)
  2222. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2223. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2224. .alt($r('app.media.music_red'))
  2225. .borderRadius('100%')
  2226. .clip(true)
  2227. .draggable(false)
  2228. .interpolation(ImageInterpolation.Medium)// 用于重采样后的抗锯齿
  2229. .autoResize(true) // 重采样,可减少内存占用
  2230. .opacity(this.opacityItem)// 绑定透明度
  2231. .margin({ left: 20 })
  2232. .gesture(LongPressGesture()
  2233. .onAction(async () => {
  2234. //如果是专辑和艺术家的首页,不能长按
  2235. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2236. return
  2237. //如果是我的收藏 最近播放等也不能长按
  2238. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2239. item.name === LocalMusic.STR_HISTORY_MUSIC
  2240. )
  2241. return
  2242. this.longItemFilePath = item.filePath
  2243. this.tempLyricContent = await this.getLyricContent(item)
  2244. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2245. })
  2246. .onActionEnd((event: GestureEvent) => {
  2247. }))
  2248. }
  2249. Column() {
  2250. Column() {
  2251. Text(item.name)
  2252. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2253. .maxLines(1)
  2254. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2255. .animation({
  2256. duration: 555,
  2257. curve: 'Linear',
  2258. })
  2259. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2260. $r('app.color.text_color'))
  2261. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2262. .bindPopup(this.longItemFilePath === item.filePath, {
  2263. builder: this.MenuBuilder(item,index,item.filePath),
  2264. placement: Placement.Top,
  2265. // autoCancel: true,
  2266. mask: {color:'#33000000'},
  2267. // popupColor: Color.Yellow,
  2268. enableArrow: false,//是否显示箭头
  2269. showInSubWindow: false,
  2270. onStateChange: (e) => {
  2271. if (!e.isVisible) {
  2272. this.longItemFilePath = ''
  2273. this.tempLyricContent = ''
  2274. }
  2275. }
  2276. })
  2277. .gesture(LongPressGesture()
  2278. .onAction(async () => {
  2279. //如果是专辑和艺术家的首页,不能长按
  2280. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2281. return
  2282. //如果是我的收藏 最近播放等也不能长按
  2283. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2284. item.name === LocalMusic.STR_HISTORY_MUSIC
  2285. )
  2286. return
  2287. this.longItemFilePath = item.filePath
  2288. this.tempLyricContent = await this.getLyricContent(item)
  2289. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2290. })
  2291. .onActionEnd((event: GestureEvent) => {
  2292. })
  2293. )
  2294. Row() {
  2295. Column(){
  2296. Text(item.md5Str?.includes('Lossless')?
  2297. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2298. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2299. .padding({ top: 3,right:6,left:6,bottom:3 })
  2300. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2301. $r('app.color.text_color'))
  2302. .fontWeight(500)
  2303. .borderRadius(12)
  2304. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2305. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2306. .backgroundColor('#FFC107')
  2307. }
  2308. .padding({ top: 8 })
  2309. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2310. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2311. .padding({ top: 8 })
  2312. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2313. $r('app.color.text_color'))
  2314. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2315. Blank()
  2316. Text(item.size)
  2317. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2318. .padding({ top: 8 })
  2319. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2320. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2321. $r('app.color.text_color'))
  2322. .margin({ left: 10 })
  2323. }
  2324. .gesture(LongPressGesture()
  2325. .onAction(async () => {
  2326. //如果是专辑和艺术家的首页,不能长按
  2327. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2328. return
  2329. //如果是我的收藏 最近播放等也不能长按
  2330. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2331. item.name === LocalMusic.STR_HISTORY_MUSIC
  2332. )
  2333. return
  2334. this.longItemFilePath = item.filePath
  2335. this.tempLyricContent = await this.getLyricContent(item)
  2336. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2337. })
  2338. .onActionEnd((event: GestureEvent) => {
  2339. })
  2340. )
  2341. }
  2342. .height('100%')
  2343. .width('100%')
  2344. .justifyContent(FlexAlign.Center)
  2345. .alignItems(HorizontalAlign.Start)
  2346. }
  2347. .height('100%')
  2348. .margin({ left: 5 })
  2349. .layoutWeight(1)
  2350. Column() {
  2351. Checkbox({ name: 'checkbox' + index })
  2352. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2353. .selectedColor(this.themeColor)
  2354. .shape(CheckBoxShape.CIRCLE)
  2355. .opacity(this.isMultiSelect ? 1 : 0)
  2356. .animation({
  2357. duration: 666,
  2358. curve: 'Smooth' // 可选动画曲线
  2359. })
  2360. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2361. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2362. .margin({ left: 20, top: 8, bottom: 8 })
  2363. .width(22)
  2364. .height(22)
  2365. ImageAnimator()
  2366. .images(this.imagesF)// 动画数组
  2367. .duration(1000)// 持续
  2368. .state(this.animationState)// 动画状态
  2369. .fillMode(FillMode.Forwards)
  2370. .width(18)
  2371. .margin({ right: 20, top: 8, bottom: 8 })
  2372. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2373. Visibility.None)
  2374. .height(18)
  2375. .iterations(-1) // 播放次数
  2376. }
  2377. }
  2378. }
  2379. .backgroundColor(Color.Transparent)
  2380. .width('100%')
  2381. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2382. }
  2383. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2384. @Builder
  2385. tabTitle() {
  2386. Column() {
  2387. // 使用 Stack 布局来实现绝对定位效果
  2388. Stack() {
  2389. // 背景动画容器
  2390. Row() {
  2391. ForEach(this.tabs, (i: string, index) => {
  2392. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2393. Flex()
  2394. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2395. .borderRadius(20)
  2396. .padding(10)
  2397. .margin(6)
  2398. .width('100%')
  2399. .height('100%')
  2400. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2401. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2402. .opacity(this.modeType === index ? 1 : 0)
  2403. .animation({
  2404. duration: 666,
  2405. playMode: PlayMode.Normal,
  2406. curve: 'ease-in-out'
  2407. });
  2408. }
  2409. .layoutWeight(1)
  2410. .margin({
  2411. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2412. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2413. });
  2414. });
  2415. }
  2416. .width('100%')
  2417. .height(50);
  2418. // 导航栏容器
  2419. Row() {
  2420. ForEach(this.tabs, (item: string, index) => {
  2421. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2422. Text(item)
  2423. .fontSize(16)
  2424. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2425. .padding(15)
  2426. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2427. .onClick(() => {
  2428. this.modeType = index;
  2429. this.onModeChange();
  2430. });
  2431. }
  2432. .layoutWeight(1)
  2433. .stateStyles({
  2434. pressed: { opacity: 0.6 } // 按压反馈
  2435. });
  2436. });
  2437. }
  2438. .width('100%')
  2439. .height(this.topBarHeight)
  2440. .opacity(this.barOpacity)
  2441. .backgroundColor(Color.Transparent);
  2442. }
  2443. .width('100%')
  2444. .height(this.topBarHeight)
  2445. .opacity(this.barOpacity)
  2446. Line()
  2447. .width('100%')
  2448. .height(1)
  2449. .backgroundColor($r('app.color.index_background'))
  2450. .opacity(this.barOpacity)
  2451. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2452. }
  2453. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2454. }
  2455. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2456. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2457. isShowCoverHeader() {
  2458. if (!this.isShowHeader) {
  2459. return false
  2460. }
  2461. if (this.modeType == 0) {
  2462. if (this.isHistory || this.isFavMusic) {
  2463. return true
  2464. }
  2465. if (this.currentPath != this.rootPath) {
  2466. return true
  2467. }
  2468. }
  2469. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2470. }
  2471. @Builder
  2472. coverHeader() {
  2473. if (this.isShowCoverHeader()) {
  2474. Column() {
  2475. Stack() {
  2476. // 居中标题
  2477. Text('')
  2478. .fontSize(18)
  2479. .fontColor(Color.White)
  2480. .align(Alignment.Center)
  2481. // 左右按钮
  2482. Row() {
  2483. Image($r('app.media.left_back_white'))
  2484. .width(28)
  2485. .height(28)
  2486. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2487. .margin({ left: 12, right: 8 })
  2488. .onClick(() => {
  2489. animateTo({ duration: 555 }, () => {
  2490. this.doSwipBack()
  2491. })
  2492. })
  2493. Blank().flexGrow(1)
  2494. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2495. Image($r('app.media.add'))
  2496. .width(25)
  2497. .height(25)
  2498. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2499. .margin({ left: 8, right: 15 })
  2500. .onClick(() => {
  2501. this.showAddDialog()
  2502. })
  2503. }
  2504. }
  2505. .height(48)
  2506. .width('100%')
  2507. .alignItems(VerticalAlign.Center)
  2508. }
  2509. .height(48)
  2510. .width('100%')
  2511. Row() {
  2512. Column() {
  2513. Image(this.currentTitleCover)
  2514. .height(100)
  2515. .width(100)
  2516. .alt(this.imageLabel)
  2517. .borderRadius(8)
  2518. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2519. }
  2520. .alignItems(HorizontalAlign.Start)
  2521. .margin({ left: 30, top: 3, bottom: 15 })
  2522. Column() {
  2523. Column() {
  2524. Text(this.currentTitleName)
  2525. .fontSize(16)
  2526. .maxLines(1)
  2527. .fontWeight(FontWeight.Bold)
  2528. .fontColor($r('app.color.text_color'))
  2529. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2530. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2531. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2532. .fontSize(14)
  2533. .padding({ top: 8 })
  2534. .maxLines(1)
  2535. .fontWeight(FontWeight.Bold)
  2536. .fontColor($r('app.color.text_color'))
  2537. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2538. if(this.videoLocalList[0].genre){
  2539. Text(`风格:${this.videoLocalList[0].genre}`)
  2540. .fontSize(14)
  2541. .padding({ top: 8 })
  2542. .maxLines(1)
  2543. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2544. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2545. ?Visibility.None:Visibility.Visible)
  2546. .fontWeight(FontWeight.Bold)
  2547. .fontColor($r('app.color.text_color'))
  2548. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2549. }
  2550. if(this.videoLocalList[0].year){
  2551. Text(`发行时间:${this.videoLocalList[0].year}`)
  2552. .fontSize(14)
  2553. .padding({ top: 8 })
  2554. .maxLines(1)
  2555. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2556. this.videoLocalList[0].year.includes(this.UNKONWN)
  2557. ?Visibility.None:Visibility.Visible)
  2558. .fontWeight(FontWeight.Bold)
  2559. .fontColor($r('app.color.text_color'))
  2560. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2561. }
  2562. }
  2563. if(this.modeType != 3){
  2564. Row() {
  2565. Text(`共${this.videoLocalList.length}首歌`)
  2566. .fontSize(13)
  2567. .fontWeight(FontWeight.Bold)
  2568. .padding({ top: 8 })
  2569. .fontColor($r('app.color.text_color'))
  2570. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2571. Blank()
  2572. }
  2573. }
  2574. }
  2575. .height('100%')
  2576. .width('100%')
  2577. .justifyContent(FlexAlign.Center)
  2578. .alignItems(HorizontalAlign.Start)
  2579. }
  2580. .height('100%')
  2581. .layoutWeight(1)
  2582. .margin({ left: 20 })
  2583. }
  2584. this.listViewTitle()
  2585. }
  2586. .backgroundImage(this.getCoverTitleBg())
  2587. .height(250)
  2588. .width('100%')
  2589. .backgroundImageSize({ height: '100%', width: '100%' })
  2590. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2591. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2592. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2593. .justifyContent(FlexAlign.SpaceBetween)
  2594. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2595. TransitionEffect.scale({ x: 0, y: 0 })))
  2596. } else {
  2597. this.listViewTitle()
  2598. }
  2599. }
  2600. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2601. if (this.isCustomizeBg) {
  2602. return ('rgba(255,255,255,0.2)')
  2603. }
  2604. if (this.isDarkMode) {
  2605. return $r('app.color.user_center_card_background')
  2606. }
  2607. return this.currentTitleCover
  2608. }
  2609. @Builder
  2610. listViewTitle() {
  2611. Column() {
  2612. Row({ space: 8 }) {
  2613. Row({ space: 8 }) {
  2614. Image($r("app.media.hm_playlist"))
  2615. .width(25)
  2616. .margin({ left: 8 })
  2617. .fillColor(this.themeColor)
  2618. Text(`共找到${this.artistList.length}位艺术家`)
  2619. .fontColor($r('app.color.text_color'))
  2620. .fontSize(14)
  2621. .opacity(this.opacityItem)
  2622. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2623. Text(`共找到${this.albumList.length}张专辑`)
  2624. .fontColor($r('app.color.text_color'))
  2625. .opacity(this.opacityItem)
  2626. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2627. .fontSize(14)
  2628. }
  2629. .layoutWeight(1)
  2630. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2631. Row() {
  2632. TextInput({
  2633. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2634. text: this.searchText
  2635. })
  2636. .height(35)
  2637. .onChange((value: string) => {
  2638. this.onSearchInput(value);
  2639. })
  2640. .layoutWeight(1)
  2641. Text(`取消`)
  2642. .margin({ left: 10, right: 10 })
  2643. .fontColor($r('app.color.text_color'))
  2644. .fontSize(16)
  2645. .onClick(() => {
  2646. this.isSearchMode = false
  2647. this.searchText = ''
  2648. if (this.modeType === 2) {
  2649. this.updateListData(this.artistList)
  2650. } else {
  2651. this.updateListData(this.albumList)
  2652. }
  2653. })
  2654. }
  2655. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2656. .animation({
  2657. duration: 666,
  2658. curve: 'ease-in-out' // 可选动画曲线
  2659. })
  2660. Blank()
  2661. Image($r("app.media.search"))
  2662. .width(25)
  2663. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2664. .animation({
  2665. duration: 666,
  2666. curve: 'ease-in-out' // 可选动画曲线
  2667. })// .opacity(this.opacityItem)
  2668. .fillColor(this.themeColor)
  2669. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2670. .onClick(() => {
  2671. this.isSearchMode = true
  2672. })
  2673. Image($r("app.media.top_rank"))
  2674. .width(25)// .opacity(this.opacityItem)
  2675. .fillColor(this.themeColor)
  2676. .animation({
  2677. duration: 666,
  2678. curve: 'ease-in-out' // 可选动画曲线
  2679. })
  2680. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2681. .onClick(() => {
  2682. this.showRankDialog()
  2683. })
  2684. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2685. .width(25)
  2686. .animation({
  2687. duration: 666,
  2688. curve: 'ease-in-out' // 可选动画曲线
  2689. })
  2690. .fillColor(this.themeColor)
  2691. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2692. .onClick(() => {
  2693. this.isGridMusic = !this.isGridMusic
  2694. })
  2695. }
  2696. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2697. Visibility.None)
  2698. .width('100%')
  2699. .padding(10)
  2700. .height(50)
  2701. .border({
  2702. width: { bottom: 1 },
  2703. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2704. })
  2705. Row({ space: 8 }) {
  2706. Row({ space: 8 }) {
  2707. Image($r("app.media.hm_play"))
  2708. .width(25)
  2709. .margin({ left: 8 })
  2710. .fillColor(this.themeColor)
  2711. Text(`播放全部`)
  2712. .fontColor($r('app.color.text_color'))
  2713. .fontSize(14)
  2714. .animation({
  2715. duration: 666,
  2716. curve: 'ease-in-out' // 可选动画曲线
  2717. })
  2718. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2719. .fontColor($r('app.color.text_color'))
  2720. .fontSize(14)
  2721. .opacity(this.opacityItem)
  2722. .animation({
  2723. duration: 666,
  2724. curve: 'ease-in-out' // 可选动画曲线
  2725. })
  2726. }
  2727. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2728. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2729. .animation({
  2730. duration: 666,
  2731. curve: 'ease-in-out' // 可选动画曲线
  2732. })
  2733. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2734. .onTouch((event: TouchEvent) => {
  2735. if (event.type === TouchType.Down) {
  2736. this.isClickedPLayAll = true;
  2737. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2738. this.isClickedPLayAll = false;
  2739. }
  2740. })
  2741. .onClick(() => {
  2742. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2743. if (this.modeType === 0) {
  2744. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2745. this.doPlay(this.getCurFileList()[0])
  2746. }
  2747. } else {
  2748. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2749. this.doPlay(this.mediaKuList[0])
  2750. }
  2751. }
  2752. })
  2753. Row() {
  2754. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2755. .height(35)
  2756. .onChange((value: string) => {
  2757. this.onSearchInput(value);
  2758. })
  2759. .layoutWeight(1)
  2760. Text(`取消`)
  2761. .margin({ left: 10, right: 10 })
  2762. .fontColor($r('app.color.text_color'))
  2763. .fontSize(16)
  2764. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2765. .onClick(() => {
  2766. this.isSearchMode = false
  2767. this.searchText = ''
  2768. this.updateListData(this.mediaKuList)
  2769. })
  2770. }
  2771. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2772. .animation({
  2773. duration: 666,
  2774. curve: 'ease-in-out' // 可选动画曲线
  2775. })
  2776. Blank()
  2777. Image($r("app.media.search"))
  2778. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2779. .animation({
  2780. duration: 666,
  2781. curve: 'ease-in-out' // 可选动画曲线
  2782. })// .opacity(this.opacityItem)
  2783. .fillColor(this.themeColor)
  2784. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2785. .onClick(() => {
  2786. this.isSearchMode = true
  2787. })
  2788. Image($r("app.media.refresh"))
  2789. .fillColor(this.themeColor)
  2790. .width(25)
  2791. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2792. .animation({
  2793. duration: 666,
  2794. curve: 'ease-in-out' // 可选动画曲线
  2795. })
  2796. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2797. .onClick(() => {
  2798. if (this.isFavMusic) {
  2799. this.getFavList(true)
  2800. } else {
  2801. if(this.modeType == 0){
  2802. this.asyncCurrentPathData()
  2803. }else if(this.modeType ==1){
  2804. workerInstance.postMessage({ code: 2, data: this.context });
  2805. }
  2806. }
  2807. })
  2808. Image($r("app.media.top_rank"))
  2809. .width(25)
  2810. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2811. Visibility.Visible)// .opacity(this.opacityItem)
  2812. .animation({
  2813. duration: 666,
  2814. curve: 'ease-in-out' // 可选动画曲线
  2815. })
  2816. .fillColor(this.themeColor)
  2817. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2818. .onClick(() => {
  2819. this.showRankDialog()
  2820. })
  2821. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2822. .width(24)
  2823. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2824. .animation({
  2825. duration: 666,
  2826. curve: 'ease-in-out' // 可选动画曲线
  2827. })
  2828. .fillColor(this.themeColor)
  2829. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2830. .onClick(() => {
  2831. this.isMultiSelect = !this.isMultiSelect
  2832. })
  2833. SymbolGlyph($r('sys.symbol.trash'))
  2834. .fontColor([this.themeColor])
  2835. .fontSize(25)
  2836. .effectStrategy(1)
  2837. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2838. .animation({
  2839. duration: 666,
  2840. curve: 'ease-in-out' // 可选动画曲线
  2841. })
  2842. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2843. .onClick(() => {
  2844. this.clearVideoHistory() //清空播放记录
  2845. })
  2846. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2847. .width(24)
  2848. .animation({
  2849. duration: 666,
  2850. curve: 'ease-in-out' // 可选动画曲线
  2851. })
  2852. .fillColor(this.themeColor)
  2853. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2854. .bindPopup($$this.tipPopup, {
  2855. builder: this.popupBuilder,
  2856. placement: Placement.Bottom,
  2857. maskColor: 0x33000000,
  2858. enableArrow: true,
  2859. onStateChange: (e) => {
  2860. if (!e.isVisible) {
  2861. this.tipPopup = false;
  2862. }
  2863. }
  2864. })
  2865. .onClick(() => {
  2866. this.isGridMusic = !this.isGridMusic
  2867. })
  2868. }
  2869. .width('100%')
  2870. .padding(10)
  2871. .height(50)
  2872. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2873. .border({
  2874. width: { bottom: 1 },
  2875. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2876. })
  2877. }
  2878. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  2879. }
  2880. // 第二步:popup构造器定义弹框内容
  2881. @Builder popupBuilder() {
  2882. Column({ space: 2 }) {
  2883. Text('友情提示:双指缩放可以放大缩小列表')
  2884. .fontSize(12)
  2885. .fontWeight(FontWeight.Regular)
  2886. .fontColor($r('app.color.text_color'))
  2887. }
  2888. .justifyContent(FlexAlign.SpaceAround)
  2889. .width(220)
  2890. .height(55)
  2891. .padding(15)
  2892. }
  2893. //搜索功能的实现
  2894. @State searchText: string = ''; // 用户输入内容
  2895. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2896. @State isSearchMode: boolean = false
  2897. // 实时搜索逻辑(带防抖)
  2898. private onSearchInput(value: string) {
  2899. this.searchText = value.trim();
  2900. let mSearchList: Array<VideoItem> = []
  2901. switch (this.modeType) {
  2902. case 0:
  2903. mSearchList = this.videoLocalList
  2904. break;
  2905. case 1:
  2906. mSearchList = this.mediaKuList
  2907. break;
  2908. case 2:
  2909. mSearchList = this.artistList
  2910. break;
  2911. case 3:
  2912. mSearchList = this.albumList
  2913. break;
  2914. }
  2915. // 新增条件判断:空输入时显示所有数据
  2916. if (this.searchText === '') {
  2917. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2918. } else {
  2919. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2920. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2921. });
  2922. }
  2923. this.updateListData(this.filteredList);
  2924. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2925. }
  2926. @State dragItem: number = -1
  2927. @State scaleItem: number = -1
  2928. @State neighborItem: number = -1
  2929. @State neighborScale: number = -1
  2930. @State offsetY: number = 0
  2931. private dragRefOffset: number = 0
  2932. private ITEM_INTV: number = 78
  2933. scaleSelect(item: number): number {
  2934. if (this.scaleItem === item) {
  2935. return 1.05
  2936. } else if (this.neighborItem === item) {
  2937. return this.neighborScale
  2938. } else {
  2939. return 1
  2940. }
  2941. }
  2942. itemMove(index: number, newIndex: number): void {
  2943. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2944. return;
  2945. }
  2946. let tmp = this.videoLocalList.splice(index, 1);
  2947. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2948. this.dataSource.pushArrayData(this.videoLocalList)
  2949. }
  2950. // Grid布局的开始
  2951. private dragRefOffSetX: number = 0;
  2952. private dragRefOffSetY: number = 0;
  2953. private FIX_VP_X: number = 180;
  2954. private FIX_VP_Y: number = 84;
  2955. isDraggable(index: number): boolean {
  2956. return index >= 0;
  2957. }
  2958. getRowEnd(item: number) {
  2959. if (item.toString() === '0') {
  2960. return 1;
  2961. } else {
  2962. return 0;
  2963. }
  2964. }
  2965. // [Start itemMove_start]
  2966. // itemMoveGrid(index: number, newIndex: number): void {
  2967. // if (!this.isDraggable(newIndex)) {
  2968. // return;
  2969. // }
  2970. // let tmp = this.videoLocalList.splice(index, 1);
  2971. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2972. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2973. // }
  2974. isInLeft(index: number) {
  2975. return index % 2 == 0;
  2976. }
  2977. down(index: number): void {
  2978. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2979. return;
  2980. }
  2981. this.offsetY -= this.FIX_VP_Y;
  2982. this.dragRefOffSetY += this.FIX_VP_Y;
  2983. this.itemMove(index, index + 1);
  2984. }
  2985. up(index: number): void {
  2986. if (!this.isDraggable(index - 2)) {
  2987. return;
  2988. }
  2989. this.offsetY += this.FIX_VP_Y;
  2990. this.dragRefOffSetY -= this.FIX_VP_Y;
  2991. this.itemMove(index, index - 1);
  2992. }
  2993. left(index: number): void {
  2994. if (this.isInLeft(index)) {
  2995. return;
  2996. }
  2997. if (!this.isDraggable(index - 1)) {
  2998. return;
  2999. }
  3000. this.offsetX += this.FIX_VP_X;
  3001. this.dragRefOffSetX -= this.FIX_VP_X;
  3002. this.itemMove(index, index - 1)
  3003. }
  3004. right(index: number): void {
  3005. if (!this.isInLeft(index)) {
  3006. return;
  3007. }
  3008. if (!this.isDraggable(index + 1)) {
  3009. return;
  3010. }
  3011. this.offsetX -= this.FIX_VP_X;
  3012. this.dragRefOffSetX += this.FIX_VP_X;
  3013. this.itemMove(index, index + 1)
  3014. }
  3015. private scroller: Scroller = new Scroller();
  3016. @State startIndex: number = 0
  3017. @State endIndex: number = 0
  3018. @State scaleValue: number = 1
  3019. @State pinchValue: number = 1
  3020. layoutOptionsForHeader: GridLayoutOptions = {
  3021. regularSize: [1, 1], // 只支持[1, 1]
  3022. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3023. };
  3024. @Builder
  3025. getGridView() {
  3026. Grid(this.scroller, this.layoutOptionsForHeader) {
  3027. GridItem() {
  3028. if (this.isShowCoverHeader()) {
  3029. this.coverHeader()
  3030. } else {
  3031. this.listViewTitle()
  3032. }
  3033. }
  3034. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3035. GridItem() {
  3036. Stack({ alignContent: Alignment.Center }) {
  3037. this.MusicItemGrid(item, index)
  3038. }
  3039. }
  3040. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3041. {
  3042. preview: MenuPreviewMode.IMAGE,
  3043. previewAnimationOptions: { scale: [0.8, 1.0] },
  3044. })
  3045. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3046. {
  3047. preview: MenuPreviewMode.IMAGE,
  3048. previewAnimationOptions: { scale: [0.8, 1.0] },
  3049. })
  3050. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3051. TransitionEffect.scale({ x: 0, y: 0 })))
  3052. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3053. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3054. .zIndex(this.dragItem === index ? 1 : 0)
  3055. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3056. // .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  3057. }, (item: VideoItem) => item.filePath)
  3058. }
  3059. .width(this.isShowHeader ? '100%' : '94%')
  3060. .height('100%')
  3061. .editMode(true)
  3062. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3063. .animation({ duration: 500, curve: Curve.Ease }))
  3064. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3065. .margin({
  3066. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3067. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3068. })
  3069. .layoutWeight(1)
  3070. .scrollBar(BarState.Off)
  3071. .supportAnimation(true)
  3072. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3073. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3074. .columnsTemplate(
  3075. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3076. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3077. )
  3078. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3079. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3080. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3081. .gesture(PinchGesture({ fingers: 2 })
  3082. .onActionEnd((event: GestureEvent) => {
  3083. this.setGridTwoFingers()
  3084. })
  3085. .onActionUpdate(e => {
  3086. this.scaleValue = this.pinchValue * e.scale
  3087. })
  3088. .onActionStart(e => {
  3089. }))
  3090. .enableScrollInteraction(true)
  3091. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3092. .onScrollIndex((start: number, end: number) => {
  3093. this.startIndex = start
  3094. this.endIndex = end
  3095. })
  3096. .onScrollFrameBegin((offset: number) => {
  3097. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3098. // if (this.isPhoneLan()) {
  3099. // this.setBarHeightHide(offset)
  3100. // } else
  3101. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3102. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3103. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3104. if (this.isScrollHide) {
  3105. this.setBarHeightHide2(offset)
  3106. } else {
  3107. this.setBarHeightNormal()
  3108. }
  3109. } else {
  3110. this.setBarHeightHide(offset)
  3111. }
  3112. return { offsetRemain: offset };
  3113. })
  3114. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3115. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3116. .onDrop((event?: DragEvent) => {
  3117. try {
  3118. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3119. if (dragData !== undefined) {
  3120. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3121. if (records.length > 0) {
  3122. for (let i = 0; i < records.length; i++) {
  3123. let types = records[i].getTypes();
  3124. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3125. const fileUriUds =
  3126. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3127. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3128. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3129. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3130. this.targetFile = fileUriUds.oriUri;
  3131. this.saveVideoDatas([this.targetFile])
  3132. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3133. }
  3134. }
  3135. }
  3136. } else {
  3137. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3138. }
  3139. } else {
  3140. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3141. }
  3142. } catch (error) {
  3143. const err = error as BusinessError;
  3144. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3145. }
  3146. })
  3147. }
  3148. @State targetFile: string = '';
  3149. setGridTwoFingers() {
  3150. this.pinchValue = this.scaleValue;
  3151. Logger.info('this.pinchValue = ' + this.pinchValue);
  3152. if (this.pinchValue >= 1) {
  3153. this.twoFingerType++
  3154. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3155. if (this.twoFingerType > 3) {
  3156. this.twoFingerType = 3
  3157. }
  3158. } else {
  3159. this.twoFingerType--
  3160. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3161. if (this.twoFingerType < 1) {
  3162. this.twoFingerType = 3
  3163. this.isGridMusic = false
  3164. }
  3165. }
  3166. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3167. this.pinchValue = 1;
  3168. this.scaleValue = 1;
  3169. }
  3170. @State longItemFilePath: string = ''
  3171. @State tempLyricContent: string = ''
  3172. @Builder
  3173. private MusicItemGrid(item: VideoItem, index: number) {
  3174. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3175. Stack() {
  3176. Column() {
  3177. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3178. .height(this.getGridHeight())
  3179. .width(this.getGridWight())
  3180. .draggable(false)
  3181. .interpolation(ImageInterpolation.Medium)// 用于重采样后的抗锯齿
  3182. .autoResize(true) // 重采样,可减少内存占用
  3183. .alt($r('app.media.ic_avatar2'))
  3184. .clip(true)
  3185. .borderRadius({
  3186. topLeft: 12,
  3187. topRight: 12,
  3188. bottomLeft: 0,
  3189. bottomRight: 0
  3190. })
  3191. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3192. height: '99%' ,
  3193. dragBar: true,
  3194. onDisappear: () => {
  3195. this.longItemFilePath = '';
  3196. this.tempLyricContent = ''
  3197. },
  3198. showClose: true,
  3199. preferType: SheetType.CENTER ,
  3200. title: { title: '编辑标签' }
  3201. })
  3202. .draggable(false)
  3203. .opacity(this.opacityItem)// 绑定透明度
  3204. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3205. // .animation({ duration: 500, curve: Curve.Ease }))
  3206. .animation({
  3207. duration: 666,
  3208. curve: 'ease-in-out' // 可选动画曲线
  3209. })
  3210. .margin({
  3211. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3212. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3213. })
  3214. Column() {
  3215. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3216. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3217. .maxLines(1)
  3218. .fontWeight(FontWeight.Bold)
  3219. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3220. .animation({
  3221. duration: 555,
  3222. curve: 'Linear',
  3223. })
  3224. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3225. height: '95%',
  3226. dragBar: true,
  3227. showClose: true,
  3228. onDisappear: () => {
  3229. this.longItemFilePathDetail = '';
  3230. },
  3231. blurStyle:BlurStyle.Thin,
  3232. backgroundColor:Color.Transparent,
  3233. preferType: SheetType.CENTER ,
  3234. title: { title: '详情' }
  3235. })
  3236. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3237. $r('app.color.text_color'))
  3238. Column() {
  3239. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3240. .fontSize(11)
  3241. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3242. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3243. .fontColor($r('app.color.text_color'))
  3244. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3245. .fontSize(11)
  3246. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3247. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3248. .fontColor($r('app.color.text_color'))
  3249. Row(){
  3250. Column(){
  3251. Text(item.md5Str?.includes('Lossless')?
  3252. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3253. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3254. .padding({ top: 3,right:6,left:6,bottom:3 })
  3255. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3256. $r('app.color.text_color'))
  3257. .fontWeight(500)
  3258. .borderRadius(12)
  3259. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3260. .backgroundColor('#FFC107')
  3261. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  3262. }
  3263. .margin({ top: 2 ,right:6})
  3264. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3265. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3266. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3267. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3268. .maxLines(1)
  3269. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3270. .margin({ top: 2})
  3271. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3272. || item.type == CommonConstants.TYPE_IS_ALBUM
  3273. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3274. .fontWeight(FontWeight.Medium)
  3275. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3276. $r('app.color.text_color'))
  3277. }
  3278. }
  3279. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3280. }
  3281. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  3282. .width(this.getGridWight())
  3283. .justifyContent(FlexAlign.Center)
  3284. .margin({
  3285. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3286. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3287. })
  3288. }
  3289. .width(this.getGridWight())
  3290. .borderRadius(12)
  3291. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3292. .backgroundImageSize({ height: '100%', width: '100%' })
  3293. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3294. .animation({ curve: Curve.Sharp, duration: 300 })
  3295. Checkbox({ name: 'checkbox' + index })
  3296. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3297. .selectedColor(this.themeColor)
  3298. .shape(CheckBoxShape.CIRCLE)
  3299. .opacity(this.isMultiSelect ? 1 : 0)
  3300. .animation({
  3301. duration: 666,
  3302. curve: 'Smooth' // 可选动画曲线
  3303. })
  3304. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3305. Visibility.None)
  3306. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3307. .margin({ left: 20, top: 8, bottom: 8 })
  3308. .width(38)
  3309. .height(38)
  3310. }
  3311. }
  3312. .backgroundColor(Color.Transparent)
  3313. .width('100%')
  3314. .padding({ top: 15 })
  3315. .height(this.getGridAllHeight())
  3316. .onClick(() => {
  3317. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3318. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3319. this.handleFileSelection(item, !isChecked);
  3320. } else {
  3321. this.doPlay(item, index)
  3322. }
  3323. })
  3324. }
  3325. getGridAllHeight() {
  3326. let heightG = 222
  3327. switch (this.twoFingerType) {
  3328. case 1:
  3329. heightG = 118
  3330. break;
  3331. case 2:
  3332. heightG = 168
  3333. break;
  3334. case 3:
  3335. heightG = 222
  3336. break;
  3337. }
  3338. return heightG
  3339. }
  3340. getGridHeight() {
  3341. let heightG = 150
  3342. switch (this.twoFingerType) {
  3343. case 1:
  3344. heightG = 55
  3345. break;
  3346. case 2:
  3347. heightG = 100
  3348. break;
  3349. case 3:
  3350. heightG = 150
  3351. break;
  3352. }
  3353. return heightG
  3354. }
  3355. getGridWight() {
  3356. let wightG = 158
  3357. switch (this.twoFingerType) {
  3358. case 1:
  3359. wightG = 80
  3360. break;
  3361. case 2:
  3362. wightG = 110
  3363. break;
  3364. case 3:
  3365. wightG = 158
  3366. break;
  3367. }
  3368. return wightG
  3369. }
  3370. @State isShowDetail:boolean = false
  3371. // @State isShowDetailGrid:boolean = false
  3372. // @State isShowEditGrid:boolean = false
  3373. @State longItemFilePathDetail:string =''
  3374. @Builder
  3375. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3376. if(
  3377. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3378. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3379. item.name === LocalMusic.STR_HISTORY_MUSIC)
  3380. ){
  3381. //如果是专辑和艺术家的首页,不能长按
  3382. //如果是我的收藏 最近播放等也不能长按
  3383. }else{
  3384. Scroll() {
  3385. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3386. Menu() {
  3387. MenuItem({
  3388. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3389. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3390. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3391. })
  3392. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3393. .onClick(() => {
  3394. if (item) {
  3395. this.doFav(item)
  3396. }
  3397. this.longItemFilePath = ''
  3398. })
  3399. MenuItem({
  3400. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3401. content: '下一首播放'
  3402. })
  3403. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3404. .onClick(() => {
  3405. this.addToNextPlay(item);
  3406. this.longItemFilePath = ''
  3407. })
  3408. if(Utility.isNoble()){
  3409. MenuItem({
  3410. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3411. content: '编辑标签'
  3412. })
  3413. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3414. height: '99%',
  3415. dragBar: true,
  3416. showClose: true,
  3417. preferType: SheetType.CENTER ,
  3418. title: { title: '编辑标签' }
  3419. })
  3420. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3421. .onClick(async() => {
  3422. this.setEditStrEmpty()
  3423. this.tempLyricContent = await this.getLyricContent(item);
  3424. // console.info('onecold 长按this.tempLyricContent' +this.tempLyricContent)
  3425. if(this.isGridMusic){
  3426. this.longItemFilePath = item.filePath
  3427. }else{
  3428. this.isShowEdit = !this.isShowEdit;
  3429. }
  3430. })
  3431. }
  3432. MenuItem({
  3433. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  3434. content: $r('app.string.select_all')
  3435. })
  3436. .onClick(() => {
  3437. this.isMultiSelect = !this.isMultiSelect
  3438. this.longItemFilePath = ''
  3439. this.selectedFiles.push(item)
  3440. })
  3441. MenuItem({
  3442. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3443. content: $r('app.string.rename')
  3444. })
  3445. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3446. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3447. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3448. .onClick(() => {
  3449. this.showReNameDialog(item, index + '', filePath)
  3450. this.longItemFilePath = ''
  3451. })
  3452. MenuItem({
  3453. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3454. content: $r('app.string.delete')
  3455. })
  3456. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3457. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3458. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3459. .onClick(() => {
  3460. this.showWarnIsDeleteFile(item, index + '', filePath)
  3461. this.longItemFilePath = ''
  3462. })
  3463. MenuItem({
  3464. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3465. content: $r('app.string.detail')
  3466. })
  3467. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3468. height:'95%',
  3469. dragBar: true,
  3470. showClose: true,
  3471. blurStyle:BlurStyle.Thin,
  3472. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3473. backgroundColor:Color.Transparent,
  3474. title: { title: '详情信息' }
  3475. })
  3476. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3477. .onClick(() => {
  3478. if(this.isGridMusic){
  3479. this.longItemFilePathDetail = item.filePath
  3480. }else{
  3481. this.isShowDetail = !this.isShowDetail
  3482. }
  3483. })
  3484. MenuItem({
  3485. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3486. content: $r('app.string.share')
  3487. })
  3488. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3489. .onClick(() => {
  3490. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3491. this.longItemFilePath = ''
  3492. })
  3493. }
  3494. .font({ size: 15, weight: FontWeight.Normal })
  3495. }
  3496. .width(180)
  3497. }
  3498. .height('auto')
  3499. }
  3500. }
  3501. private listMaxScrollOffsetY: number = 0
  3502. @State selectedIndex: number = -1
  3503. setlistTwoFingers() {
  3504. this.pinchValue = this.scaleValue;
  3505. Logger.info('this.pinchValue = ' + this.pinchValue);
  3506. if (this.pinchValue >= 1) {
  3507. this.twoFingerType++
  3508. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3509. if (this.twoFingerType > 3) {
  3510. this.twoFingerType = 1
  3511. this.isGridMusic = true
  3512. }
  3513. } else {
  3514. this.twoFingerType--
  3515. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3516. if (this.twoFingerType < 1) {
  3517. this.twoFingerType = 1
  3518. }
  3519. }
  3520. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3521. this.pinchValue = 1;
  3522. this.scaleValue = 1;
  3523. }
  3524. @Builder
  3525. getListView() {
  3526. List({ scroller: this.listScroller }) {
  3527. ListItemGroup({ header: this.coverHeader() }) {
  3528. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3529. ListItem() {
  3530. Column() {
  3531. if (item.type === CommonConstants.TYPE_IS_DIR
  3532. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3533. this.DirItem(item, index)
  3534. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3535. } else {
  3536. this.MusicItem(item, index)
  3537. }
  3538. }
  3539. .shadow(this.scaleItem === index ? {
  3540. radius: 70,
  3541. color: '#15000000',
  3542. offsetX: 0,
  3543. offsetY: 0
  3544. } :
  3545. {
  3546. radius: 0,
  3547. color: '#15000000',
  3548. offsetX: 0,
  3549. offsetY: 0
  3550. })
  3551. .animation({ curve: Curve.Sharp, duration: 300 })
  3552. }
  3553. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3554. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3555. .animation({ duration: 500 }),
  3556. TransitionEffect.scale({ x: 0, y: 0 })))
  3557. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3558. .swipeAction((
  3559. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3560. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3561. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3562. .onClick(() => {
  3563. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3564. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3565. this.handleFileSelection(item, !isChecked);
  3566. } else {
  3567. this.doPlay(item, index)
  3568. }
  3569. })
  3570. //拖动List关键代码开始
  3571. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3572. .zIndex(this.dragItem === index ? 1 : 0)
  3573. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3574. .gesture(
  3575. GestureGroup(GestureMode.Sequence,
  3576. LongPressGesture({ repeat: true })
  3577. .onAction((event?: GestureEvent) => {
  3578. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3579. this.scaleItem = index
  3580. })
  3581. })
  3582. .onActionEnd(() => {
  3583. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3584. this.scaleItem = -1
  3585. })
  3586. }),
  3587. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3588. .onActionStart(() => {
  3589. this.dragItem = index // 记录当前拖动项索引
  3590. this.dragRefOffset = 0 // 重置偏移基准
  3591. })
  3592. .onActionUpdate((event: GestureEvent) => {
  3593. this.offsetY = event.offsetY - this.dragRefOffset;
  3594. this.neighborItem = -1;
  3595. let indexA = this.videoLocalList.indexOf(item);
  3596. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3597. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3598. let value: number = 0;
  3599. if (this.offsetY < 0) {
  3600. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3601. this.neighborItem = indexA - 1;
  3602. this.neighborScale = 1 - value / 20;
  3603. } else if (this.offsetY > 0) {
  3604. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3605. this.neighborItem = indexA + 1;
  3606. this.neighborScale = 1 - value / 20;
  3607. }
  3608. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3609. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3610. this.offsetY -= this.ITEM_INTV;
  3611. this.dragRefOffset += this.ITEM_INTV;
  3612. this.itemMove(indexA, indexA + 1);
  3613. });
  3614. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3615. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3616. this.offsetY += this.ITEM_INTV;
  3617. this.dragRefOffset -= this.ITEM_INTV;
  3618. this.itemMove(indexA, indexA - 1);
  3619. });
  3620. }
  3621. let curListOffset = this.listScroller.currentOffset()
  3622. // 获取手指信息
  3623. let fingerInfo = event.fingerList[0]
  3624. let clickPercentY =
  3625. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3626. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3627. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3628. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3629. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  3630. }
  3631. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3632. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3633. if (curListOffset.yOffset > scrollVelocity + 5) {
  3634. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  3635. }
  3636. }
  3637. })
  3638. .onActionEnd((event: GestureEvent) => {
  3639. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3640. this.dragItem = -1
  3641. this.neighborItem = -1
  3642. })
  3643. animateTo({
  3644. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3645. }, () => {
  3646. this.scaleItem = -1
  3647. })
  3648. })
  3649. )
  3650. .onCancel(() => {
  3651. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3652. this.dragItem = -1
  3653. this.neighborItem = -1
  3654. })
  3655. animateTo({
  3656. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3657. }, () => {
  3658. this.scaleItem = -1
  3659. })
  3660. })
  3661. ) //拖动List关键代码结束
  3662. }, (item: VideoItem) => item.filePath)
  3663. }
  3664. }
  3665. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3666. .gesture(PinchGesture({ fingers: 2 })
  3667. .onActionEnd((event: GestureEvent) => {
  3668. this.setlistTwoFingers()
  3669. })
  3670. .onActionUpdate(e => {
  3671. this.scaleValue = this.pinchValue * e.scale
  3672. })
  3673. .onActionStart(e => {
  3674. }))
  3675. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3676. .margin({
  3677. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  3678. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+125)
  3679. })
  3680. .cachedCount(6)
  3681. .borderRadius(20)
  3682. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3683. TransitionEffect.scale({ x: 0, y: 0 })))
  3684. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3685. // .animation({ duration: 500, curve: Curve.Ease }))
  3686. .layoutWeight(1)
  3687. .onScrollIndex((start) => {
  3688. this.selectedIndex = start
  3689. })
  3690. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  3691. .lanes(
  3692. new BreakpointType<number>({
  3693. sm: 1,
  3694. md: 2,
  3695. lg: 2,
  3696. xl: 3,
  3697. xxl: 4
  3698. }).getValue(this.currentBreakpoint),
  3699. new BreakpointType<number>({
  3700. sm: 0,
  3701. md: 12,
  3702. lg: 12,
  3703. xl: 16,
  3704. xxl: 20
  3705. }).getValue(this.currentBreakpoint)
  3706. )
  3707. .onAreaChange((oldValue: Area, newValue: Area) => {
  3708. this.listArea = newValue
  3709. if (this.twoFingerType == 3) {
  3710. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3711. } else if (this.twoFingerType == 2) {
  3712. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3713. } else if (this.twoFingerType == 1) {
  3714. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3715. }
  3716. })
  3717. .onScrollFrameBegin((offset: number) => {
  3718. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3719. // if (this.isPhoneLan()) {
  3720. // this.setBarHeightHide(offset)
  3721. // } else
  3722. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3723. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3724. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3725. if (this.isScrollHide) {
  3726. this.setBarHeightHide2(offset)
  3727. } else {
  3728. this.setBarHeightNormal()
  3729. }
  3730. } else {
  3731. this.setBarHeightHide(offset)
  3732. }
  3733. return { offsetRemain: offset };
  3734. })
  3735. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3736. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3737. .onDrop((event?: DragEvent) => {
  3738. try {
  3739. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3740. if (dragData !== undefined) {
  3741. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3742. if (records.length > 0) {
  3743. for (let i = 0; i < records.length; i++) {
  3744. let types = records[i].getTypes();
  3745. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3746. const fileUriUds =
  3747. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3748. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3749. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3750. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3751. this.targetFile = fileUriUds.oriUri;
  3752. this.saveVideoDatas([this.targetFile])
  3753. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3754. }
  3755. }
  3756. }
  3757. } else {
  3758. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3759. }
  3760. } else {
  3761. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3762. }
  3763. } catch (error) {
  3764. const err = error as BusinessError;
  3765. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3766. }
  3767. })
  3768. }
  3769. setBarHeightNormal() {
  3770. this.hideDone = false;
  3771. this.getUIContext().animateTo({
  3772. duration: 300
  3773. }, () => {
  3774. this.bottomBarHeight = 55 + 0;
  3775. this.topBarHeight = 50 + 0;
  3776. this.barOpacity = 1;
  3777. this.barBottomOpacity = 1
  3778. this.currentYOffset = 0;
  3779. this.isHiding = false;
  3780. });
  3781. }
  3782. setBarHeightHide(offset: number) {
  3783. if (offset > 0 && !this.hideDone) {
  3784. this.currentYOffset += offset;
  3785. if (this.currentYOffset <= 100) {
  3786. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3787. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3788. this.barOpacity = 1 - this.currentYOffset / 100;
  3789. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3790. } else {
  3791. this.topBarHeight = 0;
  3792. this.bottomBarHeight = 0;
  3793. this.barBottomOpacity = 0
  3794. this.barOpacity = 0;
  3795. this.hideDone = true;
  3796. }
  3797. this.isHiding = true;
  3798. }
  3799. if (offset < 0 && this.isHiding) {
  3800. this.hideDone = false;
  3801. this.getUIContext().animateTo({
  3802. duration: 300
  3803. }, () => {
  3804. this.bottomBarHeight = 55 + 0;
  3805. this.topBarHeight = 50 + 0;
  3806. this.barOpacity = 1;
  3807. this.barBottomOpacity = 1
  3808. this.currentYOffset = 0;
  3809. this.isHiding = false;
  3810. });
  3811. }
  3812. }
  3813. //这个方法没隐藏bottomBar,只隐藏topbar
  3814. setBarHeightHide2(offset: number) {
  3815. if (offset > 0 && !this.hideDone) {
  3816. this.currentYOffset += offset;
  3817. if (this.currentYOffset <= 100) {
  3818. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3819. this.barOpacity = 1 - this.currentYOffset / 100;
  3820. } else {
  3821. this.topBarHeight = 0;
  3822. this.barOpacity = 0;
  3823. this.hideDone = true;
  3824. }
  3825. this.isHiding = true;
  3826. }
  3827. if (offset < 0 && this.isHiding) {
  3828. this.hideDone = false;
  3829. this.getUIContext().animateTo({
  3830. duration: 300
  3831. }, () => {
  3832. this.topBarHeight = 50 + 0;
  3833. this.barOpacity = 1;
  3834. this.currentYOffset = 0;
  3835. this.isHiding = false;
  3836. });
  3837. }
  3838. }
  3839. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3840. switch (item.type) {
  3841. case CommonConstants.TYPE_IS_DIR:
  3842. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  3843. let offsetB = 0
  3844. if (this.isGridMusic) {
  3845. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3846. let cur = this.scroller.currentOffset()
  3847. if (cur && typeof cur.yOffset === 'number') {
  3848. offsetB = cur.yOffset
  3849. }
  3850. }
  3851. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  3852. } else {
  3853. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3854. let cur = this.listScroller.currentOffset()
  3855. if (cur && typeof cur.yOffset === 'number') {
  3856. offsetB = cur.yOffset
  3857. }
  3858. }
  3859. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  3860. }
  3861. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3862. this.showVerifyDialog()
  3863. this.currentTitleName = '私密音频'
  3864. this.currentTitleCover = $r('app.media.ic_avatar5')
  3865. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3866. this.titleBarModel.setTitleName('最近播放')
  3867. this.currentTitleCover = $r('app.media.ic_avatar2')
  3868. this.currentTitleName = '最近播放'
  3869. //加载动画效果
  3870. this.updateListData(this.historyList, true)
  3871. // this.videoLocalList = this.historyList
  3872. if (ArrayUtil.isEmpty(this.historyList)) {
  3873. ToastUtil.showToast('最近播放记录空空如也')
  3874. } else {
  3875. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  3876. }
  3877. this.isHistory = true
  3878. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3879. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  3880. this.titleBarModel.setTitleName('我的收藏')
  3881. this.currentTitleName = '我的收藏'
  3882. this.currentTitleCover = $r('app.media.ic_avatar1')
  3883. //加载动画效果
  3884. this.updateListData(this.favList)
  3885. if (ArrayUtil.isEmpty(this.favList)) {
  3886. ToastUtil.showToast('无音乐收藏记录')
  3887. } else {
  3888. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  3889. }
  3890. this.isFavMusic = true
  3891. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3892. } else {
  3893. this.currentTitleName = item.name
  3894. this.currentPath = item.filePath
  3895. this.currentTitleCover = $r('app.media.ic_avatar5')
  3896. this.getSortedFiles(this.currentPath)
  3897. }
  3898. //进入歌单的时候的滚动位置在顶部
  3899. if (this.isGridMusic) {
  3900. this.scroller.scrollToIndex(0)
  3901. }
  3902. setTimeout(() => {
  3903. if (this.modeType == 0) {
  3904. if (!this.isGridMusic) {
  3905. this.listScroller.scrollToIndex(0)
  3906. }
  3907. }
  3908. }, 200)
  3909. break;
  3910. case CommonConstants.TYPE_IS_ARTIST:
  3911. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3912. let offsetA = 0
  3913. if (this.isGridMusic) {
  3914. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3915. let cur = this.scroller.currentOffset()
  3916. if (cur && typeof cur.yOffset === 'number') {
  3917. offsetA = cur.yOffset
  3918. }
  3919. }
  3920. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3921. } else {
  3922. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3923. let cur = this.listScroller.currentOffset()
  3924. if (cur && typeof cur.yOffset === 'number') {
  3925. offsetA = cur.yOffset
  3926. }
  3927. }
  3928. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3929. }
  3930. let mList = this.artistMap.get(item.name)
  3931. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3932. Utility.doSortListAscending(mList)
  3933. this.isCanBack = true
  3934. this.titleBarModel.setTitleName(item.name)
  3935. this.currentTitleName = '艺术家:' + item.name
  3936. if (item.pixelMapPath) {
  3937. this.currentTitleCover = item.pixelMapPath
  3938. }
  3939. this.updateListData(mList)
  3940. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3941. }
  3942. //进入歌单的时候的滚动位置在顶部
  3943. if (this.isGridMusic) {
  3944. this.scroller.scrollToIndex(0)
  3945. }
  3946. break;
  3947. case CommonConstants.TYPE_IS_ALBUM:
  3948. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3949. let offset = 0
  3950. if (this.isGridMusic) {
  3951. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3952. let cur = this.scroller.currentOffset()
  3953. if (cur && typeof cur.yOffset === 'number') {
  3954. offset = cur.yOffset
  3955. }
  3956. }
  3957. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3958. } else {
  3959. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3960. let cur = this.listScroller.currentOffset()
  3961. if (cur && typeof cur.yOffset === 'number') {
  3962. offset = cur.yOffset
  3963. }
  3964. }
  3965. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  3966. }
  3967. let albumList = this.albumMap.get(item.name)
  3968. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  3969. Utility.doSortListAscending(albumList)
  3970. this.isCanBack = true
  3971. this.titleBarModel.setTitleName(item.name)
  3972. this.currentTitleName = '专辑:' + item.name
  3973. if (item.pixelMapPath) {
  3974. this.currentTitleCover = item.pixelMapPath
  3975. }
  3976. this.updateListData(albumList)
  3977. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3978. this.mScrollMap.set(item.name, this.selectedIndex)
  3979. }
  3980. //进入歌单的时候的滚动位置在顶部
  3981. if (this.isGridMusic) {
  3982. this.scroller.scrollToIndex(0)
  3983. }
  3984. break;
  3985. case CommonConstants.TYPE_IS_CSJAD:
  3986. return
  3987. break;
  3988. case CommonConstants.TYPE_LOCAL:
  3989. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  3990. this.stop();
  3991. }
  3992. if (isFromSonPlayList) { //点击来自右下角的播放列表
  3993. this.currentSong = item
  3994. if (index !== undefined) {
  3995. this.curIndex = index
  3996. }
  3997. } else {
  3998. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  3999. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4000. this.songList = globalVideoList
  4001. this.sonDataSource.pushArrayData(this.songList)
  4002. this.currentSong = globalVideoList[this.curIndex]
  4003. }
  4004. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  4005. this.videoUrl = this.currentSong.filePath
  4006. this.name = this.currentSong.name
  4007. this.cover = this.currentSong.pixelMapPath
  4008. this.artist = this.currentSong.artist
  4009. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  4010. LogUtil.info('this.currentSong.sampleRate =' + this.currentSong.sampleRate)
  4011. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  4012. this.startPlayOrResumePlay()
  4013. break;
  4014. }
  4015. }
  4016. @Builder
  4017. PlayController() {
  4018. Column() {
  4019. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4020. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4021. Row() {
  4022. Row() {
  4023. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  4024. Column() {
  4025. Text(this.currentSong?.name)
  4026. .fontSize(16)
  4027. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4028. .maxLines(1)
  4029. .fontColor($r('app.color.text_color'))
  4030. .fontWeight(500)
  4031. Row() {
  4032. Text(this.currentSong?.artist)
  4033. .margin({ top: 2 })
  4034. .fontSize(13)
  4035. .maxLines(1)
  4036. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4037. .fontColor($r('app.color.text_color'))
  4038. }
  4039. }
  4040. .alignItems(HorizontalAlign.Start)
  4041. .margin({ right: 22 })
  4042. }
  4043. .padding({ right: 18 })
  4044. .layoutWeight(1)
  4045. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4046. .onClick(() => {
  4047. if (ArrayUtil.isNotEmpty(this.songList)) {
  4048. this.isShowPlay = true;
  4049. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4050. this.initLyric(lyricPath);
  4051. this.startAutoHide()
  4052. } else {
  4053. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4054. }
  4055. })
  4056. Row() {
  4057. Image($r('app.media.hm_previous'))
  4058. .height(28)
  4059. .width(28)
  4060. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4061. .margin({ left: 8, right: 16 })
  4062. .fillColor(this.themeColor)
  4063. .displayPriority(2)
  4064. .onClick(() => {
  4065. if (ArrayUtil.isNotEmpty(this.songList)) {
  4066. this.playPrevious()
  4067. } else {
  4068. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4069. }
  4070. })
  4071. //播放进度条
  4072. Stack() {
  4073. Progress({
  4074. value: Math.floor(this.progressValue),
  4075. type: ProgressType.Ring,
  4076. })
  4077. .color(this.themeColor)// 进度条前景色为灰色
  4078. .backgroundColor($r('app.color.index_background'))
  4079. .height(40)
  4080. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4081. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4082. .height(38)
  4083. .width(38)
  4084. .displayPriority(3)
  4085. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4086. .fillColor(this.themeColor)
  4087. .onClick(() => {
  4088. if (ArrayUtil.isNotEmpty(this.songList)) {
  4089. this.playOrPause()
  4090. } else {
  4091. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4092. }
  4093. })
  4094. }
  4095. Image($r('app.media.hm_next'))
  4096. .height(28)
  4097. .width(28)
  4098. .margin({
  4099. right: 16,
  4100. left: 16
  4101. })
  4102. .fillColor(this.themeColor)
  4103. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4104. .displayPriority(2)
  4105. .onClick(() => {
  4106. if (ArrayUtil.isNotEmpty(this.songList)) {
  4107. this.playNext()
  4108. } else {
  4109. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4110. }
  4111. })
  4112. Image($r('app.media.hm_playlist'))
  4113. .height(28)
  4114. .width(28)
  4115. .displayPriority(1)
  4116. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4117. .fillColor(this.themeColor)
  4118. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4119. height: '95%',
  4120. dragBar: true,
  4121. showClose: true,
  4122. blurStyle: BlurStyle.Thin,
  4123. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4124. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4125. title: {
  4126. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4127. + `(${this.songList.length}首)`
  4128. }
  4129. })
  4130. .onClick(() => {
  4131. if (ArrayUtil.isNotEmpty(this.songList)) {
  4132. this.isShowSheet = !this.isShowSheet;
  4133. this.isFrontWhite = false
  4134. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4135. this.scrollIndex()
  4136. } else {
  4137. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4138. }
  4139. })
  4140. }
  4141. }
  4142. .width('100%')
  4143. .height(this.bottomBarHeight)
  4144. .justifyContent(FlexAlign.Center)
  4145. .hitTestBehavior(HitTestMode.Transparent)
  4146. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4147. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4148. // modalTransition: ModalTransition.DEFAULT,
  4149. transition: AnimationHelper.transitionInDown(666),
  4150. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4151. })
  4152. .padding({
  4153. left: 16,
  4154. right: 16
  4155. })
  4156. Line()
  4157. .width('100%')
  4158. .height(25)
  4159. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4160. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4161. }
  4162. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4163. }
  4164. @State isFrontWhite: boolean = false
  4165. scrollIndex(){
  4166. if(this.curIndex>500)//条数太大的时候 滚动非常卡 导致闪退,先改为不滚
  4167. return
  4168. try {
  4169. setTimeout(() => {
  4170. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  4171. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  4172. })
  4173. }, 123)
  4174. }catch (error) {
  4175. console.error(`onecold scrollIndex出错: ${error}`);
  4176. }
  4177. }
  4178. //播放列表布局
  4179. @Builder
  4180. PlayListSheet() {
  4181. Column() {
  4182. this.PlayList()
  4183. }
  4184. .width('100%')
  4185. .height('100%')
  4186. }
  4187. @State titleStr: string = ''
  4188. @State ablumStr: string = ''
  4189. @State artistStr: string = ''
  4190. @State lyricConStr: string = ''
  4191. @State currentEditItem: string = ''
  4192. @State yearStr: string = ''
  4193. @State trackStr: string = ''
  4194. @State genreStr: string = ''
  4195. @State imagePathStr: string = ''
  4196. @State albumArtistStr: string = ''
  4197. @State composerStr: string = ''
  4198. @State lyricistStr: string = ''
  4199. @State commentStr: string = ''
  4200. @State discStr: string = ''
  4201. doUpdateData() {
  4202. setTimeout(() => {
  4203. if (this.modeType === 0) {
  4204. this.deleteCache(this.currentPath)
  4205. this.getSortedFiles(this.currentPath)
  4206. }
  4207. workerInstance.postMessage({ code: 2, data: this.context });
  4208. workerInstance.postMessage({ code: 3, data: this.context });
  4209. workerInstance.postMessage({ code: 4, data: this.context });
  4210. }, 999)
  4211. }
  4212. //编辑信息
  4213. async doEdit(item: VideoItem) {
  4214. if (!item) {
  4215. return
  4216. }
  4217. if (StrUtil.isEmpty(this.titleStr)) {
  4218. ToastUtil.showToast('标题不能为空')
  4219. return
  4220. }
  4221. // let doChangeLyric = false
  4222. // if(item.filePath==this.currentSong?.filePath){
  4223. // if(this.lyricConStr !== this.lyricContent){
  4224. // doChangeLyric = true
  4225. // }
  4226. // }else if(this.lyricConStr !== this.tempLyricContent){
  4227. // doChangeLyric = true
  4228. // }
  4229. //用户更改了封面,那就内嵌下封面
  4230. if(StrUtil.isNotEmpty(this.imagePathStr)){
  4231. const resultCover:boolean = await changeMusicCover(this.context,
  4232. item.filePath,this.imagePathStr,true);
  4233. this.imagePathStr = ''
  4234. if(resultCover){
  4235. ToastUtil.showToast('内嵌封面成功')
  4236. }
  4237. }
  4238. const metadata:FFMpegTags = {
  4239. title: this.titleStr,
  4240. artist: this.artistStr,
  4241. album: this.ablumStr,
  4242. // LYRICS:this.lyricConStr,
  4243. // USLT:this.lyricConStr,
  4244. TYER:this.yearStr,
  4245. genre:this.genreStr,
  4246. track:this.trackStr,
  4247. albumartist:this.albumArtistStr,
  4248. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  4249. COMPOSER:this.composerStr,
  4250. lyricist:this.lyricistStr,
  4251. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  4252. comment:this.commentStr,
  4253. // comm:this.commentStr,//ID3v2:使用 COMM(Comment)字段。
  4254. disc:this.discStr,
  4255. };
  4256. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  4257. const result:boolean = await repairAudioMetadata(
  4258. item.filePath,
  4259. this.lyricConStr,
  4260. metadata,
  4261. true
  4262. );
  4263. if (result) {
  4264. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  4265. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  4266. (success: boolean, error?: string) => {
  4267. // this.isShowEdit = false
  4268. if (success) {
  4269. console.log(" onecold 编辑信息成功,数据库已同步");
  4270. ToastUtil.showToast('内嵌音乐标签成功')
  4271. this.isShowMoreView = false
  4272. this.name = this.titleStr
  4273. if (item.filePath == this.currentSong?.filePath) {
  4274. this.currentSong.name = this.titleStr
  4275. this.artist = this.artistStr
  4276. this.currentSong.artist = this.artistStr
  4277. this.currentSong.album = this.ablumStr
  4278. this.currentSong.year = this.yearStr
  4279. this.currentSong.genre = this.genreStr
  4280. this.currentSong.track = this.trackStr
  4281. this.currentSong.ALBUMARTIST = this.albumArtistStr
  4282. this.currentSong.COMPOSER = this.composerStr
  4283. this.currentSong.LYRICIST = this.lyricistStr
  4284. this.currentSong.COMMENT = this.commentStr
  4285. }
  4286. this.doUpdateData()
  4287. } else {
  4288. // ToastUtil.showToast('保存失败' + error?.toString())
  4289. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4290. }
  4291. });
  4292. console.log(' onecold 元数据标签更新成功,');
  4293. } else {
  4294. ToastUtil.showToast('内嵌音乐标签失败')
  4295. console.log('onecold 内嵌音乐标签失败');
  4296. }
  4297. this.longItemFilePath = ''
  4298. this.tempLyricContent = ''
  4299. this.isShowEdit = false
  4300. }
  4301. updateLyricToDB() {
  4302. }
  4303. @Builder
  4304. editSheet(item: VideoItem) {
  4305. Scroll() {
  4306. Column() {
  4307. this.editDetail(item)
  4308. }
  4309. }
  4310. .width('100%')
  4311. .height('100%')
  4312. }
  4313. @Builder
  4314. editDetail(item: VideoItem) {
  4315. Column() {
  4316. if (item) {
  4317. Row() {
  4318. Stack() {
  4319. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  4320. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  4321. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4322. item.pixelMapPath)
  4323. .fillColor(this.themeColor)
  4324. .height(55)
  4325. .width(55)
  4326. .borderRadius('100%')
  4327. .clip(true)
  4328. .opacity(this.opacityItem)// 绑定透明度
  4329. .margin({ left: 25 })
  4330. }
  4331. .onClick(async () => {
  4332. const imagePath:string | undefined = await this.goSelectImage(item);
  4333. if (imagePath) {
  4334. //用户更改过图片
  4335. this.imagePathStr = imagePath
  4336. }
  4337. })
  4338. .width('18%')
  4339. Row() {
  4340. Column() {
  4341. Text(item.name)
  4342. .fontSize(14)
  4343. .maxLines(1)
  4344. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4345. .animation({
  4346. duration: 555,
  4347. curve: 'Linear',
  4348. })
  4349. .fontColor(this.themeColor)
  4350. .margin({ left: 18 })
  4351. Row() {
  4352. Text(item.artist)
  4353. .fontSize(11)
  4354. .maxLines(1)
  4355. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4356. .padding({ top: 8 })
  4357. .fontColor(this.themeColor)
  4358. .margin({ left: 18 })
  4359. }
  4360. }
  4361. .height('100%')
  4362. .width(100)
  4363. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4364. .justifyContent(FlexAlign.Center)
  4365. .alignItems(HorizontalAlign.Start)
  4366. Button('获取封面')
  4367. .fontColor(Color.White)
  4368. .fontSize(12)
  4369. .height(38)
  4370. .width(88)
  4371. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4372. .backgroundColor(this.themeColor)
  4373. .stateEffect(true)
  4374. .margin({ right: 5, left: 12 })
  4375. .onClick(async () => {
  4376. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  4377. this.showTipsDialog();
  4378. return; // Return empty string when no API is configured
  4379. }
  4380. const imagePath:string | undefined = await this.doSearchCover(item);
  4381. console.info('onecold imagePath = '+imagePath)
  4382. if (StrUtil.isNotEmpty(imagePath)) {
  4383. //用户更改过图片
  4384. this.imagePathStr = imagePath
  4385. ToastUtil.showToast('获取封面成功')
  4386. }else{
  4387. ToastUtil.showToast('获取封面失败,请重试')
  4388. }
  4389. })
  4390. Button('获取歌词')
  4391. .fontColor(Color.White)
  4392. .fontSize(12)
  4393. .height(38)
  4394. .width(88)
  4395. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4396. .backgroundColor(this.themeColor)
  4397. .stateEffect(true)
  4398. .margin({ right: 12, left: 5 })
  4399. .onClick(async () => {
  4400. //判断有没有设置api
  4401. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  4402. if (StrUtil.isEmpty(apiUrl)) {
  4403. this.isLyricSetting = false
  4404. this.showTipsDialog()
  4405. return
  4406. }
  4407. let artist = item.artist
  4408. let title = item.name
  4409. if(!artist)
  4410. artist = ''
  4411. if(!title)
  4412. title = ''
  4413. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  4414. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  4415. this.lyricConStr = res;
  4416. ToastUtil.showToast('获取歌词成功')
  4417. }else{
  4418. ToastUtil.showToast('获取歌词失败,请重试')
  4419. }
  4420. // let res : string | undefined = await getApiLyric(title, artist, false);
  4421. })
  4422. }
  4423. .height('100%')
  4424. .justifyContent(FlexAlign.Start)
  4425. .layoutWeight(1)
  4426. }
  4427. .width('100%')
  4428. .height(58)
  4429. Row() {
  4430. Text('标题:')
  4431. .fontSize(14)
  4432. .fontColor($r('app.color.text_color'))
  4433. .margin({ left: 22 })
  4434. TextInput({ text: item.name })
  4435. .height(40)
  4436. .maxLines(1)
  4437. .fontSize(14)
  4438. .layoutWeight(1)
  4439. .fontColor($r('app.color.text_color'))
  4440. .margin({ right: 20, left: 10 })
  4441. .onChange((val: string) => {
  4442. this.titleStr = val
  4443. })
  4444. }
  4445. .width('100%')
  4446. .margin({ top: 10, bottom: 10 })
  4447. .justifyContent(FlexAlign.Start)
  4448. Row() {
  4449. Text('艺术家:')
  4450. .fontSize(14)
  4451. .fontColor($r('app.color.text_color'))
  4452. .margin({ left: 22 })
  4453. TextInput({ text: item.artist })
  4454. .height(40)
  4455. .maxLines(1)
  4456. .fontSize(14)
  4457. .layoutWeight(1)
  4458. .fontColor($r('app.color.text_color'))
  4459. .margin({ right: 20, left: 10 })
  4460. .onChange((val: string) => {
  4461. this.artistStr = val
  4462. })
  4463. }
  4464. .width('100%')
  4465. .margin({ top: 10, bottom: 10 })
  4466. .justifyContent(FlexAlign.Start)
  4467. Row() {
  4468. Text('专辑名:')
  4469. .fontSize(14)
  4470. .fontColor($r('app.color.text_color'))
  4471. .margin({ left: 22 })
  4472. TextInput({ text: item.album })
  4473. .height(40)
  4474. .maxLines(1)
  4475. .fontSize(14)
  4476. .layoutWeight(1)
  4477. .fontColor($r('app.color.text_color'))
  4478. .margin({ right: 20, left: 10 })
  4479. .onChange((val: string) => {
  4480. this.ablumStr = val
  4481. })
  4482. }
  4483. .width('100%')
  4484. .margin({ top: 10, bottom: 10 })
  4485. .justifyContent(FlexAlign.Start)
  4486. Row() {
  4487. Text('年份:')
  4488. .fontSize(14)
  4489. .fontColor($r('app.color.text_color'))
  4490. .margin({ left: 22 })
  4491. TextInput({ text: item.year })
  4492. .height(40)
  4493. .maxLines(1)
  4494. .fontSize(14)
  4495. .type(InputType.Number)
  4496. .layoutWeight(1)
  4497. .fontColor($r('app.color.text_color'))
  4498. .margin({ right: 20, left: 10 })
  4499. .onChange((val: string) => {
  4500. this.yearStr = val
  4501. })
  4502. }
  4503. .width('100%')
  4504. .margin({ top: 10, bottom: 10 })
  4505. .justifyContent(FlexAlign.Start)
  4506. Row() {
  4507. Text('音轨号:')
  4508. .fontSize(14)
  4509. .fontColor($r('app.color.text_color'))
  4510. .margin({ left: 22 })
  4511. TextInput({ text:item.track=='未知'?'': item.track })
  4512. .height(40)
  4513. .maxLines(1)
  4514. .fontSize(14)
  4515. .type(InputType.Number)
  4516. .layoutWeight(1)
  4517. .fontColor($r('app.color.text_color'))
  4518. .margin({ right: 20, left: 10 })
  4519. .onChange((val: string) => {
  4520. this.trackStr = val
  4521. })
  4522. }
  4523. .width('100%')
  4524. .margin({ top: 10, bottom: 10 })
  4525. .justifyContent(FlexAlign.Start)
  4526. Row() {
  4527. Text('碟号:')
  4528. .fontSize(14)
  4529. .fontColor($r('app.color.text_color'))
  4530. .margin({ left: 22 })
  4531. TextInput({ text:item.disc })
  4532. .height(40)
  4533. .maxLines(1)
  4534. .fontSize(14)
  4535. .type(InputType.Number)
  4536. .layoutWeight(1)
  4537. .fontColor($r('app.color.text_color'))
  4538. .margin({ right: 20, left: 10 })
  4539. .onChange((val: string) => {
  4540. this.discStr = val
  4541. })
  4542. }
  4543. .width('100%')
  4544. .margin({ top: 10, bottom: 10 })
  4545. .justifyContent(FlexAlign.Start)
  4546. Row() {
  4547. Text('风格:')
  4548. .fontSize(14)
  4549. .fontColor($r('app.color.text_color'))
  4550. .margin({ left: 22 })
  4551. TextInput({ text: item.genre })
  4552. .height(40)
  4553. .maxLines(1)
  4554. .fontSize(14)
  4555. .layoutWeight(1)
  4556. .fontColor($r('app.color.text_color'))
  4557. .margin({ right: 20, left: 10 })
  4558. .onChange((val: string) => {
  4559. this.genreStr = val
  4560. })
  4561. }
  4562. .width('100%')
  4563. .margin({ top: 10, bottom: 10 })
  4564. .justifyContent(FlexAlign.Start)
  4565. Row() {
  4566. Text('专辑艺术家:')
  4567. .fontSize(14)
  4568. .fontColor($r('app.color.text_color'))
  4569. .margin({ left: 22 })
  4570. TextInput({ text: item.ALBUMARTIST })
  4571. .height(40)
  4572. .maxLines(1)
  4573. .fontSize(14)
  4574. .layoutWeight(1)
  4575. .fontColor($r('app.color.text_color'))
  4576. .margin({ right: 20, left: 10 })
  4577. .onChange((val: string) => {
  4578. this.albumArtistStr = val
  4579. })
  4580. }
  4581. .width('100%')
  4582. .margin({ top: 10, bottom: 10 })
  4583. .justifyContent(FlexAlign.Start)
  4584. Row() {
  4585. Text('作曲:')
  4586. .fontSize(14)
  4587. .fontColor($r('app.color.text_color'))
  4588. .margin({ left: 22 })
  4589. TextInput({ text: item.COMPOSER })
  4590. .height(40)
  4591. .maxLines(1)
  4592. .fontSize(14)
  4593. .layoutWeight(1)
  4594. .fontColor($r('app.color.text_color'))
  4595. .margin({ right: 20, left: 10 })
  4596. .onChange((val: string) => {
  4597. this.composerStr = val
  4598. })
  4599. }
  4600. .width('100%')
  4601. .margin({ top: 10, bottom: 10 })
  4602. .justifyContent(FlexAlign.Start)
  4603. Row() {
  4604. Text('作词:')
  4605. .fontSize(14)
  4606. .fontColor($r('app.color.text_color'))
  4607. .margin({ left: 22 })
  4608. TextInput({ text: item.LYRICIST })
  4609. .height(40)
  4610. .maxLines(1)
  4611. .fontSize(14)
  4612. .layoutWeight(1)
  4613. .fontColor($r('app.color.text_color'))
  4614. .margin({ right: 20, left: 10 })
  4615. .onChange((val: string) => {
  4616. this.lyricistStr = val
  4617. })
  4618. }
  4619. .width('100%')
  4620. .margin({ top: 10, bottom: 10 })
  4621. .justifyContent(FlexAlign.Start)
  4622. Row() {
  4623. Text('注释:')
  4624. .fontSize(14)
  4625. .fontColor($r('app.color.text_color'))
  4626. .margin({ left: 22 })
  4627. TextInput({ text: item.COMMENT })
  4628. .height(40)
  4629. .maxLines(1)
  4630. .fontSize(14)
  4631. .layoutWeight(1)
  4632. .fontColor($r('app.color.text_color'))
  4633. .margin({ right: 20, left: 10 })
  4634. .onChange((val: string) => {
  4635. this.commentStr = val
  4636. })
  4637. }
  4638. .width('100%')
  4639. .margin({ top: 10, bottom: 10 })
  4640. .justifyContent(FlexAlign.Start)
  4641. Row() {
  4642. Column(){
  4643. Text('歌词:')
  4644. .fontSize(14)
  4645. .fontColor($r('app.color.text_color'))
  4646. .margin({ left: 22 })
  4647. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4648. SymbolGlyph($r('sys.symbol.trash_fill'))
  4649. .fontSize(25)
  4650. .alignSelf(ItemAlign.Center)
  4651. .margin({ left: 22,top:15})
  4652. }
  4653. .backgroundColor(Color.Transparent)
  4654. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  4655. Visibility.None:Visibility.Visible)
  4656. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4657. .onClick(()=>{
  4658. this.lyricConStr = ''
  4659. this.lyricContent = ''
  4660. this.tempLyricContent = ''
  4661. })
  4662. }
  4663. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  4664. this.tempLyricContent })
  4665. .type(TextAreaType.NORMAL)
  4666. .height('auto')
  4667. .fontSize(14)
  4668. .layoutWeight(1)
  4669. .fontColor($r('app.color.text_color'))
  4670. .margin({ right: 20, left: 10 })
  4671. .onChange((val: string) => {
  4672. this.lyricConStr = val
  4673. })
  4674. }
  4675. .width('100%')
  4676. .margin({ top: 10, bottom: 10 })
  4677. .justifyContent(FlexAlign.Start)
  4678. Row() {
  4679. Button('保存')
  4680. .fontColor(Color.White)
  4681. .layoutWeight(1)
  4682. .height(50)
  4683. .width(100)
  4684. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4685. .backgroundColor(this.themeColor)
  4686. .stateEffect(true)
  4687. .margin({ right: 20, bottom: 20 })
  4688. .onClick(async () => {
  4689. this.doEdit(item)
  4690. })
  4691. Button('取消')
  4692. .fontColor(Color.White)
  4693. .layoutWeight(1)
  4694. .height(50)
  4695. .width(100)
  4696. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4697. .backgroundColor(this.themeColor)
  4698. .stateEffect(true)
  4699. .margin({ left: 20, bottom: 20 })
  4700. .onClick(async () => {
  4701. if(this.isGridMusic){
  4702. this.longItemFilePath =''
  4703. }else{
  4704. this.isShowEdit = false
  4705. }
  4706. this.setEditStrEmpty()
  4707. if(this.isShowPlay){
  4708. this.isShowEdit = false
  4709. }
  4710. })
  4711. }
  4712. .margin({
  4713. left: 38,
  4714. right: 38,
  4715. top: 10,
  4716. bottom: 10
  4717. })
  4718. .width(250)
  4719. .height(60)
  4720. }
  4721. }
  4722. .margin({ bottom: 20 })
  4723. }
  4724. setEditStrEmpty(){
  4725. this.imagePathStr = ''
  4726. this.lyricConStr = ''
  4727. this.artistStr = ''
  4728. this.titleStr = ''
  4729. this.ablumStr = ''
  4730. this.genreStr = ''
  4731. this.yearStr = ''
  4732. this.trackStr = ''
  4733. this.albumArtistStr = ''
  4734. this.composerStr = ''
  4735. this.lyricistStr = ''
  4736. this.commentStr = ''
  4737. this.discStr = ''
  4738. }
  4739. @Builder
  4740. detailSheet(item:VideoItem) {
  4741. Scroll() {
  4742. Column() {
  4743. this.songDetail(item)
  4744. }
  4745. }
  4746. .width('100%')
  4747. .height('100%')
  4748. }
  4749. @Builder
  4750. songDetail(currentItem:VideoItem) {
  4751. Column() {
  4752. if (currentItem) {
  4753. Row() {
  4754. Stack() {
  4755. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4756. currentItem.pixelMapPath)
  4757. .fillColor(this.themeColor)
  4758. .height(80)
  4759. .width(80)
  4760. .borderRadius(10)
  4761. .opacity(this.opacityItem)// 绑定透明度
  4762. .margin({ left: 22 })
  4763. }
  4764. Column() {
  4765. Column() {
  4766. Text(currentItem.name)
  4767. .fontSize(16)
  4768. .maxLines(1)
  4769. .animation({
  4770. duration: 555,
  4771. curve: 'Linear',
  4772. })
  4773. .fontColor($r('app.color.text_color'))
  4774. .margin({ left: 15 })
  4775. }
  4776. .height('100%')
  4777. .width('100%')
  4778. .justifyContent(FlexAlign.Center)
  4779. .alignItems(HorizontalAlign.Start)
  4780. }
  4781. .height('100%')
  4782. }
  4783. .width('100%')
  4784. .height(90)
  4785. .justifyContent(FlexAlign.SpaceBetween)
  4786. Row() {
  4787. Text('艺术家:')
  4788. .fontSize(14)
  4789. .fontColor($r('app.color.text_color'))
  4790. .margin({ left: 22 })
  4791. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4792. .fontSize(14)
  4793. .fontColor($r('app.color.text_color'))
  4794. .margin({ left: 10 })
  4795. .layoutWeight(1)
  4796. }
  4797. .width('100%')
  4798. .margin({ top: 10, bottom: 10 })
  4799. .justifyContent(FlexAlign.Start)
  4800. Row() {
  4801. Text('专辑名:')
  4802. .fontSize(14)
  4803. .fontColor($r('app.color.text_color'))
  4804. .margin({ left: 22 })
  4805. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4806. .fontSize(14)
  4807. .margin({ left: 10 })
  4808. .fontColor($r('app.color.text_color'))
  4809. .layoutWeight(1)
  4810. }
  4811. .width('100%')
  4812. .margin({ top: 10, bottom: 10 })
  4813. .justifyContent(FlexAlign.Start)
  4814. Row() {
  4815. Text('时长:')
  4816. .fontSize(14)
  4817. .fontColor($r('app.color.text_color'))
  4818. .margin({ left: 22 })
  4819. Text(StrUtil.isEmpty(currentItem.duration)?
  4820. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4821. .fontSize(14)
  4822. .margin({ left: 10 })
  4823. .fontColor($r('app.color.text_color'))
  4824. .layoutWeight(1)
  4825. }
  4826. .width('100%')
  4827. .margin({ top: 10, bottom: 10 })
  4828. .justifyContent(FlexAlign.Start)
  4829. Row() {
  4830. Text('采样率:')
  4831. .fontSize(14)
  4832. .fontColor($r('app.color.text_color'))
  4833. .margin({ left: 22 })
  4834. Text(Utility.convertToKHz(currentItem.sampleRate))
  4835. .fontSize(14)
  4836. .margin({ left: 10 })
  4837. .fontColor($r('app.color.text_color'))
  4838. .layoutWeight(1)
  4839. }
  4840. .width('100%')
  4841. .margin({ top: 10, bottom: 10 })
  4842. .justifyContent(FlexAlign.Start)
  4843. Row() {
  4844. Text('比特率:')
  4845. .fontSize(14)
  4846. .fontColor($r('app.color.text_color'))
  4847. .margin({ left: 22 })
  4848. Text(currentItem.bit_rate)
  4849. .fontSize(14)
  4850. .margin({ left: 10 })
  4851. .fontColor($r('app.color.text_color'))
  4852. .layoutWeight(1)
  4853. }
  4854. .width('100%')
  4855. .margin({ top: 10, bottom: 10 })
  4856. .justifyContent(FlexAlign.Start)
  4857. Row() {
  4858. Text('位深:')
  4859. .fontSize(14)
  4860. .fontColor($r('app.color.text_color'))
  4861. .margin({ left: 22 })
  4862. Text(`${currentItem.bits_per_raw_sample} bits`)
  4863. .fontSize(14)
  4864. .margin({ left: 10 })
  4865. .fontColor($r('app.color.text_color'))
  4866. .layoutWeight(1)
  4867. }
  4868. .width('100%')
  4869. .margin({ top: 10, bottom: 10 })
  4870. .justifyContent(FlexAlign.Start)
  4871. Row() {
  4872. Text('声道:')
  4873. .fontSize(14)
  4874. .fontColor($r('app.color.text_color'))
  4875. .margin({ left: 22 })
  4876. Text(`${currentItem.channels}`)
  4877. .fontSize(14)
  4878. .margin({ left: 10 })
  4879. .fontColor($r('app.color.text_color'))
  4880. .layoutWeight(1)
  4881. }
  4882. .width('100%')
  4883. .margin({ top: 10, bottom: 10 })
  4884. .justifyContent(FlexAlign.Start)
  4885. Row() {
  4886. Text('声道布局:')
  4887. .fontSize(14)
  4888. .fontColor($r('app.color.text_color'))
  4889. .margin({ left: 22 })
  4890. Text(`${currentItem.channel_layout}`)
  4891. .fontSize(14)
  4892. .margin({ left: 10 })
  4893. .fontColor($r('app.color.text_color'))
  4894. .layoutWeight(1)
  4895. }
  4896. .width('100%')
  4897. .margin({ top: 10, bottom: 10 })
  4898. .justifyContent(FlexAlign.Start)
  4899. Row() {
  4900. Text('起始播放点:')
  4901. .fontSize(14)
  4902. .fontColor($r('app.color.text_color'))
  4903. .margin({ left: 22 })
  4904. Text(`${currentItem.start_time}`)
  4905. .fontSize(14)
  4906. .margin({ left: 10 })
  4907. .fontColor($r('app.color.text_color'))
  4908. .layoutWeight(1)
  4909. }
  4910. .width('100%')
  4911. .margin({ top: 10, bottom: 10 })
  4912. .justifyContent(FlexAlign.Start)
  4913. Row() {
  4914. Text('风格:')
  4915. .fontSize(14)
  4916. .fontColor($r('app.color.text_color'))
  4917. .margin({ left: 22 })
  4918. Text(currentItem.genre)
  4919. .fontSize(14)
  4920. .margin({ left: 10 })
  4921. .fontColor($r('app.color.text_color'))
  4922. .layoutWeight(1)
  4923. }
  4924. .width('100%')
  4925. .margin({ top: 10, bottom: 10 })
  4926. .justifyContent(FlexAlign.Start)
  4927. Row() {
  4928. Text('发行时间:')
  4929. .fontSize(14)
  4930. .fontColor($r('app.color.text_color'))
  4931. .margin({ left: 22 })
  4932. Text(currentItem.year)
  4933. .fontSize(14)
  4934. .margin({ left: 10 })
  4935. .fontColor($r('app.color.text_color'))
  4936. .layoutWeight(1)
  4937. }
  4938. .width('100%')
  4939. .margin({ top: 10, bottom: 10 })
  4940. .justifyContent(FlexAlign.Start)
  4941. Row() {
  4942. Text('质量评分:')
  4943. .fontSize(14)
  4944. .fontColor($r('app.color.text_color'))
  4945. .margin({ left: 22 })
  4946. Text(currentItem.probe_score+"")
  4947. .fontSize(14)
  4948. .margin({ left: 10 })
  4949. .fontColor($r('app.color.text_color'))
  4950. .layoutWeight(1)
  4951. }
  4952. .width('100%')
  4953. .margin({ top: 10, bottom: 10 })
  4954. .justifyContent(FlexAlign.Start)
  4955. Row() {
  4956. Text('音轨号:')
  4957. .fontSize(14)
  4958. .fontColor($r('app.color.text_color'))
  4959. .margin({ left: 22 })
  4960. Text(currentItem.track)
  4961. .fontSize(14)
  4962. .margin({ left: 10 })
  4963. .fontColor($r('app.color.text_color'))
  4964. .layoutWeight(1)
  4965. }
  4966. .width('100%')
  4967. .margin({ top: 10, bottom: 10 })
  4968. .justifyContent(FlexAlign.Start)
  4969. Row() {
  4970. Text('碟号:')
  4971. .fontSize(14)
  4972. .fontColor($r('app.color.text_color'))
  4973. .margin({ left: 22 })
  4974. Text(currentItem.disc)
  4975. .fontSize(14)
  4976. .margin({ left: 10 })
  4977. .fontColor($r('app.color.text_color'))
  4978. .layoutWeight(1)
  4979. }
  4980. .width('100%')
  4981. .margin({ top: 10, bottom: 10 })
  4982. .justifyContent(FlexAlign.Start)
  4983. Row() {
  4984. Text('专辑艺术家:')
  4985. .fontSize(14)
  4986. .fontColor($r('app.color.text_color'))
  4987. .margin({ left: 22 })
  4988. Text(currentItem.ALBUMARTIST)
  4989. .fontSize(14)
  4990. .margin({ left: 10 })
  4991. .fontColor($r('app.color.text_color'))
  4992. .layoutWeight(1)
  4993. }
  4994. .width('100%')
  4995. .margin({ top: 10, bottom: 10 })
  4996. .justifyContent(FlexAlign.Start)
  4997. Row() {
  4998. Text('作曲家:')
  4999. .fontSize(14)
  5000. .fontColor($r('app.color.text_color'))
  5001. .margin({ left: 22 })
  5002. Text(currentItem.COMPOSER)
  5003. .fontSize(14)
  5004. .margin({ left: 10 })
  5005. .fontColor($r('app.color.text_color'))
  5006. .layoutWeight(1)
  5007. }
  5008. .width('100%')
  5009. .margin({ top: 10, bottom: 10 })
  5010. .justifyContent(FlexAlign.Start)
  5011. Row() {
  5012. Text('作词家:')
  5013. .fontSize(14)
  5014. .fontColor($r('app.color.text_color'))
  5015. .margin({ left: 22 })
  5016. Text(currentItem.LYRICIST)
  5017. .fontSize(14)
  5018. .margin({ left: 10 })
  5019. .fontColor($r('app.color.text_color'))
  5020. .layoutWeight(1)
  5021. }
  5022. .width('100%')
  5023. .margin({ top: 10, bottom: 10 })
  5024. .justifyContent(FlexAlign.Start)
  5025. Row() {
  5026. Text('注释:')
  5027. .fontSize(14)
  5028. .fontColor($r('app.color.text_color'))
  5029. .margin({ left: 22 })
  5030. Text(currentItem.COMMENT)
  5031. .fontSize(14)
  5032. .margin({ left: 10 })
  5033. .fontColor($r('app.color.text_color'))
  5034. .layoutWeight(1)
  5035. }
  5036. .width('100%')
  5037. .margin({ top: 10, bottom: 10 })
  5038. .justifyContent(FlexAlign.Start)
  5039. Row() {
  5040. Text('格式:')
  5041. .fontSize(14)
  5042. .fontColor($r('app.color.text_color'))
  5043. .margin({ left: 22 })
  5044. Text(Utility.formatMimeType(currentItem.mimeType))
  5045. .fontSize(14)
  5046. .margin({ left: 10 })
  5047. .fontColor($r('app.color.text_color'))
  5048. .layoutWeight(1)
  5049. }
  5050. .width('100%')
  5051. .margin({ top: 10, bottom: 10 })
  5052. .justifyContent(FlexAlign.Start)
  5053. Row() {
  5054. Text('播放次数:')
  5055. .fontSize(14)
  5056. .fontColor($r('app.color.text_color'))
  5057. .margin({ left: 22 })
  5058. Text(currentItem.playCount?.toString())
  5059. .fontSize(14)
  5060. .margin({ left: 10 })
  5061. .fontColor($r('app.color.text_color'))
  5062. .layoutWeight(1)
  5063. }
  5064. .width('100%')
  5065. .margin({ top: 10, bottom: 10 })
  5066. .justifyContent(FlexAlign.Start)
  5067. Row() {
  5068. Text('流数量:')
  5069. .fontSize(14)
  5070. .fontColor($r('app.color.text_color'))
  5071. .margin({ left: 22 })
  5072. Text(currentItem.nb_streams?.toString())
  5073. .fontSize(14)
  5074. .margin({ left: 10 })
  5075. .fontColor($r('app.color.text_color'))
  5076. .layoutWeight(1)
  5077. }
  5078. .width('100%')
  5079. .margin({ top: 10, bottom: 10 })
  5080. .justifyContent(FlexAlign.Start)
  5081. Row() {
  5082. Text('文件大小:')
  5083. .fontSize(14)
  5084. .fontColor($r('app.color.text_color'))
  5085. .margin({ left: 22 })
  5086. Text(currentItem.size)
  5087. .fontSize(14)
  5088. .margin({ left: 10 })
  5089. .fontColor($r('app.color.text_color'))
  5090. .layoutWeight(1)
  5091. }
  5092. .width('100%')
  5093. .margin({ top: 10, bottom: 10 })
  5094. .justifyContent(FlexAlign.Start)
  5095. Row() {
  5096. Text('文件名:')
  5097. .fontSize(14)
  5098. .fontColor($r('app.color.text_color'))
  5099. .margin({ left: 22 })
  5100. Text(currentItem.fileName)
  5101. .fontSize(14)
  5102. .margin({ left: 10 })
  5103. .fontColor($r('app.color.text_color'))
  5104. .layoutWeight(1)
  5105. }
  5106. .width('100%')
  5107. .margin({ top: 10, bottom: 10 })
  5108. .justifyContent(FlexAlign.Start)
  5109. Row() {
  5110. Text('修改时间:')
  5111. .fontSize(14)
  5112. .fontColor($r('app.color.text_color'))
  5113. .margin({ left: 22 })
  5114. Text(currentItem.cTime)
  5115. .fontSize(14)
  5116. .margin({ left: 10 })
  5117. .fontColor($r('app.color.text_color'))
  5118. .layoutWeight(1)
  5119. }
  5120. .width('100%')
  5121. .margin({ top: 10, bottom: 10 })
  5122. .justifyContent(FlexAlign.Start)
  5123. Row() {
  5124. Text('存放目录:')
  5125. .fontSize(14)
  5126. .fontColor($r('app.color.text_color'))
  5127. .margin({ left: 22 })
  5128. Text(currentItem.filePath)
  5129. .fontSize(12)
  5130. .margin({ left: 10 })
  5131. .fontColor($r('app.color.text_color'))
  5132. .layoutWeight(1)
  5133. }
  5134. .margin({ top: 10, bottom: 10 })
  5135. .width('100%')
  5136. .justifyContent(FlexAlign.Start)
  5137. }
  5138. }
  5139. .margin({ bottom: 20 })
  5140. }
  5141. //定时关闭布局
  5142. @Builder
  5143. TimeCloseSheet() {
  5144. Scroll() {
  5145. Column() {
  5146. this.TimeClose()
  5147. }
  5148. }
  5149. .width('100%')
  5150. .height('100%')
  5151. }
  5152. //倒计时关闭音乐,退出App功能实现。
  5153. @State selectedMinutes: number = 0 // 0表示未开启
  5154. @State remainingSeconds: number = 0
  5155. // 预设时间选项
  5156. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  5157. private formatTime(seconds: number): string {
  5158. const mins = Math.floor(seconds / 60)
  5159. const secs = seconds % 60
  5160. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  5161. }
  5162. // 开始倒计时
  5163. private handleTimeSelect(minutes: number) {
  5164. if (minutes === this.selectedMinutes) {
  5165. this.stopCountdown();
  5166. this.selectedMinutes = 0;
  5167. return;
  5168. }
  5169. this.selectedMinutes = minutes;
  5170. this.remainingSeconds = minutes * 60;
  5171. this.startCountdown(); // 新增调用
  5172. }
  5173. @Builder
  5174. TimeClose() {
  5175. Column() {
  5176. // 倒计时显示区域
  5177. Text(this.selectedMinutes > 0 ?
  5178. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  5179. "定时关闭未开启")
  5180. .fontSize(17)
  5181. .fontColor($r('app.color.text_color'))
  5182. .margin({ top: 2, bottom: 8 });
  5183. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  5184. ForEach(this.presetTimes, (minutes: number, index: number) => {
  5185. // 单行时间选项容器
  5186. Row() {
  5187. // 文字描述区域
  5188. Text(this.getDisplayText(minutes))
  5189. .fontSize(15)
  5190. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  5191. $r('app.color.text_color'))// 选中态颜色变化
  5192. .textAlign(TextAlign.Start)
  5193. .layoutWeight(1); // 占据剩余空间
  5194. // 复选框样式的选择器
  5195. Row() {
  5196. if (minutes === this.selectedMinutes) {
  5197. // 选中状态 - 带勾号的圆形复选框
  5198. Row() {
  5199. // 使用系统内置的勾号图标
  5200. Image($r('sys.media.ohos_ic_public_ok'))
  5201. .width(14)
  5202. .height(14)
  5203. .fillColor(Color.White)
  5204. }
  5205. .width(24)
  5206. .height(24)
  5207. .borderRadius(12)
  5208. .backgroundColor(this.themeColor)
  5209. .justifyContent(FlexAlign.Center)
  5210. .alignItems(VerticalAlign.Center)
  5211. } else {
  5212. // 未选中状态的圆形边框
  5213. Row()
  5214. .width(24)
  5215. .height(24)
  5216. .borderRadius(12)
  5217. .border({
  5218. width: 2,
  5219. color: $r('app.color.text_color'),
  5220. style: BorderStyle.Solid
  5221. })
  5222. .backgroundColor(Color.Transparent)
  5223. }
  5224. }
  5225. .width(24)
  5226. .height(24)
  5227. .margin({ left: 20 })
  5228. .justifyContent(FlexAlign.Center)
  5229. .alignItems(VerticalAlign.Center)
  5230. }
  5231. .width('100%')
  5232. .padding({
  5233. top: 18,
  5234. bottom: 18,
  5235. left: 18,
  5236. right: 18
  5237. })
  5238. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  5239. $r('app.color.bottom_control_background')) // 选中背景高亮
  5240. .borderRadius(12)
  5241. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  5242. .margin({ bottom: 18 })
  5243. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  5244. });
  5245. }
  5246. .width('100%')
  5247. .padding(16)
  5248. }
  5249. }
  5250. // 获取显示文本
  5251. private getDisplayText(minutes: number): string {
  5252. if (minutes === -1) {
  5253. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  5254. }
  5255. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  5256. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  5257. }
  5258. // 处理选择事件
  5259. private handleSelect(minutes: number): void {
  5260. if (minutes === -1) { // 自定义
  5261. // 弹出自定义时间对话框
  5262. DialogHelper.showTextInputDialog({
  5263. title: '自定义时间',
  5264. maskColor: Color.Transparent,
  5265. inputType: InputType.Number,
  5266. text: '',
  5267. onChange: (text) => {
  5268. console.error("onChange: " + text);
  5269. },
  5270. onAction: (action, dialogId, content) => {
  5271. if (action == DialogAction.TWO) {
  5272. const customMinutes = Number(content);
  5273. if (customMinutes > 0) {
  5274. this.handleTimeSelect(customMinutes); // 设置自定义时间
  5275. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  5276. }
  5277. }
  5278. }
  5279. });
  5280. } else {
  5281. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  5282. }
  5283. }
  5284. // 添加定时器引用
  5285. private timerId: number = -1;
  5286. // 启动/重置倒计时
  5287. private startCountdown() {
  5288. // 清除旧定时器
  5289. if (this.timerId !== -1) {
  5290. clearInterval(this.timerId);
  5291. }
  5292. // 创建新定时器
  5293. if (this.selectedMinutes > 0) {
  5294. this.timerId = setInterval(() => {
  5295. if (this.remainingSeconds === 15) {
  5296. this.showConfirmationDialog();
  5297. }
  5298. if (this.remainingSeconds > 0) {
  5299. this.remainingSeconds -= 1;
  5300. } else {
  5301. this.stopCountdown();
  5302. this.handleTimeout();
  5303. }
  5304. }, 1000);
  5305. }
  5306. }
  5307. // 15倒计时后再次提示显示确认是否关闭App对话框
  5308. private showConfirmationDialog() {
  5309. DialogHelper.showAlertDialog({
  5310. backgroundColor: $r('app.color.btn_green'),
  5311. title: '确认关闭',
  5312. maskColor: Color.Transparent,
  5313. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  5314. borderStyle: BorderStyle.Dashed,
  5315. primaryButton: '暂不关闭',
  5316. secondaryButton: '确定',
  5317. onAction: (action) => {
  5318. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  5319. this.stopCountdown();
  5320. this.selectedMinutes = 0
  5321. } else if (action == DialogAction.TWO) {
  5322. }
  5323. }
  5324. })
  5325. }
  5326. // 停止倒计时
  5327. private stopCountdown() {
  5328. if (this.timerId !== -1) {
  5329. clearInterval(this.timerId);
  5330. this.timerId = -1;
  5331. }
  5332. }
  5333. // 超时处理
  5334. private handleTimeout() {
  5335. // 执行播放器关闭逻辑
  5336. this.selectedMinutes = 0;
  5337. ToastUtil.showToast(" 定时关闭已完成");
  5338. this.stop(); // 假设存在的播放器实例
  5339. //退出APP
  5340. const mContext = getContext(this) as common.UIAbilityContext
  5341. mContext.terminateSelf();
  5342. AvSessionController.getInstance(true).unregisterSessionListener()
  5343. }
  5344. //倒计时关闭音乐,退出App功能实现结束。
  5345. //播放列表的拖动List 重新排序
  5346. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  5347. //左滑操作 移动文件 重命名 删除等操作
  5348. @Builder
  5349. sonButton(item: VideoItem, index: number, filePath: string) {
  5350. Row() {
  5351. //加入下一首播放
  5352. Button() {
  5353. Image($r('app.media.next_to_play'))
  5354. .fillColor(Color.White)
  5355. .width(20)
  5356. }
  5357. .width(40)
  5358. .height(40)
  5359. .type(ButtonType.Circle)
  5360. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5361. .backgroundColor(this.themeColor)
  5362. .margin(5)
  5363. .onClick(() => {
  5364. this.addToNextPlay(item);
  5365. })
  5366. Button() {
  5367. Image($r('app.media.close'))
  5368. .fillColor(Color.White)
  5369. .width(20)
  5370. }
  5371. .width(40)
  5372. .height(40)
  5373. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5374. .type(ButtonType.Circle)
  5375. .backgroundColor(this.themeColor)
  5376. .margin(5)
  5377. .onClick(() => {
  5378. this.songList.splice(Number(index), 1)
  5379. this.sonDataSource.pushArrayData(this.songList)
  5380. })
  5381. Button() {
  5382. Image($r('app.media.share2'))
  5383. .fillColor(Color.White)
  5384. .width(20)
  5385. }
  5386. .width(40)
  5387. .height(40)
  5388. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5389. .type(ButtonType.Circle)
  5390. .backgroundColor(this.themeColor)
  5391. .margin(5)
  5392. .onClick(() => {
  5393. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5394. })
  5395. }
  5396. }
  5397. itemMoveSon(index: number, newIndex: number): void {
  5398. if (newIndex < 0 || newIndex >= this.songList.length) {
  5399. return;
  5400. }
  5401. let tmp = this.songList.splice(index, 1);
  5402. this.songList.splice(newIndex, 0, tmp[0]);
  5403. this.sonDataSource.pushArrayData(this.songList)
  5404. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  5405. }
  5406. @Builder
  5407. PlayList() {
  5408. List({ scroller: this.playListScroller }) {
  5409. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  5410. ListItem() {
  5411. this.MusicItemSon(item, index)
  5412. }
  5413. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  5414. .animation({
  5415. duration: 666,
  5416. curve: 'ease-in-out' // 可选动画曲线
  5417. })
  5418. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  5419. TransitionEffect.scale({ x: 0, y: 0 })))
  5420. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  5421. //拖动List关键代码开始
  5422. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5423. .zIndex(this.dragItem === index ? 1 : 0)
  5424. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5425. .gesture(
  5426. GestureGroup(GestureMode.Sequence,
  5427. LongPressGesture({ repeat: true })
  5428. .onAction((event?: GestureEvent) => {
  5429. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5430. this.scaleItem = index
  5431. })
  5432. })
  5433. .onActionEnd(() => {
  5434. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5435. this.scaleItem = -1
  5436. })
  5437. }),
  5438. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5439. .onActionStart(() => {
  5440. this.dragItem = index // 记录当前拖动项索引
  5441. this.dragRefOffset = 0 // 重置偏移基准
  5442. })
  5443. .onActionUpdate((event: GestureEvent) => {
  5444. this.offsetY = event.offsetY - this.dragRefOffset;
  5445. this.neighborItem = -1;
  5446. let indexA = this.songList.indexOf(item);
  5447. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5448. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5449. let value: number = 0;
  5450. if (this.offsetY < 0) {
  5451. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5452. this.neighborItem = indexA - 1;
  5453. this.neighborScale = 1 - value / 20;
  5454. } else if (this.offsetY > 0) {
  5455. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5456. this.neighborItem = indexA + 1;
  5457. this.neighborScale = 1 - value / 20;
  5458. }
  5459. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  5460. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5461. this.offsetY -= this.ITEM_INTV;
  5462. this.dragRefOffset += this.ITEM_INTV;
  5463. this.itemMoveSon(indexA, indexA + 1);
  5464. });
  5465. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5466. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5467. this.offsetY += this.ITEM_INTV;
  5468. this.dragRefOffset -= this.ITEM_INTV;
  5469. this.itemMoveSon(indexA, indexA - 1);
  5470. });
  5471. }
  5472. })
  5473. .onActionEnd((event: GestureEvent) => {
  5474. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5475. this.dragItem = -1
  5476. this.neighborItem = -1
  5477. })
  5478. animateTo({
  5479. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5480. }, () => {
  5481. this.scaleItem = -1
  5482. })
  5483. })
  5484. )
  5485. .onCancel(() => {
  5486. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5487. this.dragItem = -1
  5488. this.neighborItem = -1
  5489. })
  5490. animateTo({
  5491. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5492. }, () => {
  5493. this.scaleItem = -1
  5494. })
  5495. })
  5496. ) //拖动List关键代码结束
  5497. .onClick(() => {
  5498. this.doPlay(item, index, true)
  5499. })
  5500. }, (item: VideoItem) => item.filePath)
  5501. }
  5502. .width('100%')
  5503. .height('100%')
  5504. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5505. // .animation({ duration: 500, curve: Curve.Ease }))
  5506. .cachedCount(10)
  5507. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5508. .gesture(PinchGesture({ fingers: 2 })
  5509. .onActionEnd((event: GestureEvent) => {
  5510. this.setlistTwoFingers()
  5511. })
  5512. .onActionUpdate(e => {
  5513. this.scaleValue = this.pinchValue * e.scale
  5514. })
  5515. .onActionStart(e => {
  5516. }))
  5517. .padding({
  5518. bottom: 0
  5519. })
  5520. }
  5521. @Builder
  5522. private MusicItemSon(item: VideoItem, index?: number) {
  5523. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5524. Row() {
  5525. Stack() {
  5526. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5527. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5528. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5529. .alt($r('app.media.music_red'))
  5530. .fillColor(this.themeColor)
  5531. .borderRadius('100%')
  5532. .clip(true)
  5533. .margin({ left: 20 })
  5534. }
  5535. .width('15%')
  5536. Column() {
  5537. Column() {
  5538. Text(item.name)
  5539. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5540. .fontColor(this.curIndex === index ? this.themeColor :
  5541. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5542. .maxLines(1)
  5543. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5544. Row() {
  5545. Column(){
  5546. Text(item.md5Str?.includes('Lossless')?
  5547. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5548. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5549. .padding({ top: 3,right:6,left:6,bottom:3 })
  5550. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5551. $r('app.color.text_color'))
  5552. .fontWeight(500)
  5553. .borderRadius(12)
  5554. .margin({ left: this.twoFingerType == 3 ? 12 : 10 })
  5555. .backgroundColor('#FFC107')
  5556. }
  5557. .padding({ top: 8 })
  5558. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5559. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5560. .padding({ top: 8 })
  5561. .fontColor(this.curIndex === index ? this.themeColor :
  5562. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5563. .margin({ left: this.twoFingerType == 3 ? 5 : 3 })
  5564. Blank()
  5565. Text(item.size)
  5566. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5567. .padding({ top: 8 })
  5568. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5569. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5570. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5571. .margin({ left: 10 })
  5572. }
  5573. }
  5574. .height('100%')
  5575. .width('100%')
  5576. .justifyContent(FlexAlign.Center)
  5577. .alignItems(HorizontalAlign.Start)
  5578. }
  5579. .height('100%')
  5580. .width('65%')
  5581. Column() {
  5582. ImageAnimator()
  5583. .images(this.imagesF)// 动画数组
  5584. .duration(1000)// 持续
  5585. .state(this.animationState)// 动画状态
  5586. .fillMode(FillMode.Forwards)
  5587. .width(18)
  5588. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5589. Visibility.None)
  5590. .height(18)
  5591. .iterations(-1) // 播放次数
  5592. }
  5593. .width('20%')
  5594. }
  5595. }
  5596. .backgroundColor(Color.Transparent)
  5597. .width('100%')
  5598. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5599. .shadow(this.scaleItem === index ? {
  5600. radius: 70,
  5601. color: '#15000000',
  5602. offsetX: 0,
  5603. offsetY: 0
  5604. } :
  5605. {
  5606. radius: 0,
  5607. color: '#15000000',
  5608. offsetX: 0,
  5609. offsetY: 0
  5610. })
  5611. .animation({ curve: Curve.Sharp, duration: 300 })
  5612. }
  5613. @Builder
  5614. MusicPlayBuilder() {
  5615. Column() {
  5616. this.IjkMusicPlayerView()
  5617. }
  5618. .height('100%')
  5619. .width('100%')
  5620. .onDisAppear(() => {
  5621. this.translateY = 0;
  5622. })
  5623. .translate({ y: this.translateY })
  5624. .gesture(
  5625. PanGesture(this.panOption)
  5626. .onActionUpdate((event?: GestureEvent) => {
  5627. if (event) {
  5628. // 只允许向下滑动,向上滑动时限制为0
  5629. this.translateY = Math.max(0, event.offsetY);
  5630. }
  5631. })
  5632. .onActionEnd((event?: GestureEvent) => {
  5633. // 使用更低的阈值和滑动速度判断
  5634. const minDistance = 100; // 最小滑动距离 100vp
  5635. const minVelocity = 500; // 最小滑动速度
  5636. // 获取滑动速度(如果可用)
  5637. const velocity = event?.velocityY || 0;
  5638. // 判断是否应该关闭:距离足够 或者 速度足够快
  5639. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5640. if (shouldClose) {
  5641. // 添加关闭动画
  5642. this.getUIContext().animateTo({
  5643. duration: 300,
  5644. curve: Curve.Smooth
  5645. }, () => {
  5646. this.isShowPlay = false;
  5647. this.translateY = 0;
  5648. })
  5649. } else {
  5650. // 回弹动画
  5651. this.getUIContext().animateTo({
  5652. duration: 300,
  5653. curve: Curve.Smooth
  5654. }, () => {
  5655. this.translateY = 0;
  5656. })
  5657. }
  5658. })
  5659. )
  5660. }
  5661. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5662. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5663. HeightBreakpoint.HEIGHT_LG;
  5664. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5665. @State topBarHeight: number = 50
  5666. @State barOpacity: number = 1
  5667. @State barBottomOpacity: number = 1
  5668. private hideDone: boolean = false;
  5669. @State currentYOffset: number = 0;
  5670. @State bottomBarHeight: number = 60;
  5671. private isHiding: boolean = false;
  5672. //是否是Pura X外屏,或者小屏幕
  5673. isPuraWP() {
  5674. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5675. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5676. }
  5677. //是否是Pura X外屏,或者小屏幕,手机横屏
  5678. /**
  5679. * 是否是Pura X外屏,或者小屏幕,手机横屏
  5680. * @returns
  5681. */
  5682. isCoverOpacity() {
  5683. if (this.isPuraWP()) {
  5684. return true
  5685. }
  5686. if (this.isPhoneLan()) {
  5687. return true
  5688. }
  5689. if (deviceInfo.marketName.includes('Pura X')
  5690. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5691. return true
  5692. }
  5693. return false
  5694. }
  5695. //是不是手机横屏
  5696. isPhoneLan() {
  5697. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5698. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5699. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5700. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5701. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  5702. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5703. if (this.isHiCarKuanBianPing()) {
  5704. return true
  5705. }
  5706. if (this.isHiCar()) {
  5707. return false
  5708. }
  5709. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5710. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5711. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  5712. return true
  5713. }
  5714. return false
  5715. }
  5716. //是不是1920x720的hicar的屏幕分辨率
  5717. isHiCarKuanBianPing(){
  5718. if(!this.isHiCar()){
  5719. return false
  5720. }
  5721. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5722. { ratio: 1920 / 720, name: "1920x720" },
  5723. ];
  5724. const currentRatio: number = this.windowWidth / this.windowHeight;
  5725. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  5726. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  5727. for (const hiCarRatio of hiCarAspectRatios) {
  5728. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  5729. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5730. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5731. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5732. return true;
  5733. }
  5734. }
  5735. return false;
  5736. }
  5737. //是不是hicar的屏幕分辨率
  5738. isHiCarSmall() {
  5739. if(!this.isHiCar()){
  5740. return false
  5741. }
  5742. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5743. return false
  5744. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5745. { ratio: 800 / 480, name: "800x480" },
  5746. { ratio: 1280 / 720, name: "1280x720" },
  5747. { ratio: 1920 / 1080, name: "1920x1080" },
  5748. ];
  5749. const currentRatio: number = this.windowWidth / this.windowHeight;
  5750. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  5751. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  5752. for (const hiCarRatio of hiCarAspectRatios) {
  5753. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  5754. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5755. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  5756. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5757. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5758. return true;
  5759. }
  5760. }
  5761. return false;
  5762. }
  5763. isHiCar() {
  5764. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  5765. }
  5766. //是不是正常的手机竖屏
  5767. isPhonePortrait() {
  5768. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5769. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5770. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5771. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5772. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5773. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5774. return true
  5775. }
  5776. return false
  5777. }
  5778. @State showSpeedDialog: boolean = false
  5779. @State longPressSpeed: number = 3 //长按默认倍数
  5780. @Builder
  5781. SpeedDialog() {
  5782. Stack() {
  5783. Column() {
  5784. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5785. .fontColor(Color.White)
  5786. .visibility(Visibility.Hidden)
  5787. }
  5788. .backgroundColor(Color.Black)
  5789. .borderRadius(20)
  5790. .padding({
  5791. top: 10,
  5792. right: 20,
  5793. left: 15,
  5794. bottom: 20
  5795. })
  5796. .opacity(0.6)
  5797. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5798. .fontColor(Color.White)
  5799. }
  5800. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5801. .zIndex(5)
  5802. .margin({ top: 80 })
  5803. }
  5804. @Builder
  5805. IjkMusicPlayerView() {
  5806. Column() {
  5807. Column() {
  5808. Column() {
  5809. //播放标题
  5810. Column() {
  5811. this.PlayTitle()
  5812. }
  5813. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5814. .width('100%')
  5815. .margin({ top: 0 })
  5816. .height(PlayConstants.HEIGHT)
  5817. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5818. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5819. if (this.showSpeedDialog) {
  5820. this.SpeedDialog()
  5821. }
  5822. Stack() {
  5823. //手势拖动快进
  5824. Column()
  5825. .width(CommonConstants.FULL_PERCENT)
  5826. .height('100%')
  5827. .gesture(
  5828. GestureGroup(GestureMode.Parallel,
  5829. // 长按屏幕倍数播放
  5830. LongPressGesture({ repeat: true })
  5831. .onAction(() => {
  5832. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5833. this.showSpeedDialog = true;
  5834. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  5835. }
  5836. })
  5837. .onActionEnd(() => {
  5838. this.showSpeedDialog = false;
  5839. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5840. }),
  5841. //双击屏幕暂停或者播放
  5842. TapGesture({ count: 2 })
  5843. .onAction((event: GestureEvent) => {
  5844. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5845. ToastUtil.showToast('已暂停')
  5846. }
  5847. this.playOrPause()
  5848. })
  5849. )
  5850. )
  5851. }
  5852. .height('65%')
  5853. Swiper() {
  5854. this.CoverInfo()
  5855. this.PlayerLyrics()
  5856. }
  5857. .onChange((index: number) => {
  5858. this.currentSwiperIndex = index
  5859. })
  5860. .indicator(false)
  5861. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5862. // new DotIndicator()
  5863. // .top(this.isCoverOpacity()?0:10)
  5864. //
  5865. // .selectedColor($r('app.color.select_swiper'))
  5866. // .color($r('app.color.slider_track')):false
  5867. // )
  5868. .displayCount(new BreakpointType({
  5869. sm: 1,
  5870. md: 2,
  5871. lg: 2,
  5872. xl: 2,
  5873. xxl: 2
  5874. }).getValue(this.currentBreakpoint))
  5875. .clip(false)
  5876. .loop(false)
  5877. .autoPlay(false)
  5878. // .interval(8000)
  5879. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5880. .height('100%')
  5881. .hitTestBehavior(HitTestMode.Transparent)
  5882. Image($r('app.media.icon_replay'))
  5883. .objectFit(ImageFit.Auto)
  5884. .width('120px')
  5885. .height('120px')
  5886. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5887. .border({ width: 0 })
  5888. .visibility(Visibility.None)
  5889. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5890. .onClick(() => {
  5891. this.startPlayOrResumePlay();
  5892. })
  5893. }
  5894. .width(CommonConstants.FULL_PERCENT)
  5895. .height(CommonConstants.FULL_PERCENT)
  5896. .justifyContent(FlexAlign.End)
  5897. }
  5898. .justifyContent(FlexAlign.End)
  5899. .margin({ bottom: 8 })
  5900. }
  5901. // .backgroundImage(this.imageLabelBg)
  5902. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5903. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5904. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5905. // .backgroundImagePosition(Alignment.Center)
  5906. .animation({
  5907. duration: 666,
  5908. curve: 'ease-in-out' // 可选动画曲线
  5909. })
  5910. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5911. BlurStyle.BACKGROUND_ULTRA_THICK)
  5912. .hitTestBehavior(HitTestMode.Transparent)
  5913. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5914. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5915. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5916. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5917. .onClick(() => {
  5918. // this.startAutoHide()
  5919. if(this.isHiCar())
  5920. return
  5921. if(this.is_auto_hide_progress){
  5922. this.is_auto_hide_progress = false
  5923. }
  5924. this.startAutoHide()
  5925. })
  5926. }
  5927. @State progressValue: number = 0;
  5928. @State currentTime: string = "00:00";
  5929. @State totalTime: string = "00:00";
  5930. @State loadingVisible: Visibility = Visibility.None;
  5931. @State replayVisible: Visibility = Visibility.None;
  5932. @State slideEnable: boolean = false;
  5933. @State aspRatio: number = 0.5;
  5934. @State mContext: object | undefined = undefined;
  5935. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  5936. @State mFirst: boolean = true;
  5937. @State mDestroyPage: boolean = false;
  5938. @State playSpeed: number = 1;
  5939. @State oldSeconds: number = 0;
  5940. @State isSeekTo: boolean = false;
  5941. @State isCurrentTime: boolean = false;
  5942. @State videoWidth: string = '100%';
  5943. @State videoHeight: string = '100%';
  5944. @State initAspectRatio: number = 1;
  5945. @State videoAspectRatio: number = this.initAspectRatio;
  5946. private videoUrl: string = '';
  5947. private last: number = 0;
  5948. @State videoParentAspectRatio: number = this.initAspectRatio;
  5949. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  5950. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  5951. @State PROGRESS_MAX_VALUE: number = 100;
  5952. @State updateProgressTimer: number = 0;
  5953. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  5954. @State name: string = '';
  5955. // @State loop: boolean = false;
  5956. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  5957. @State multiple: string = '1.0X';
  5958. xcomponentController: XComponentController = new XComponentController()
  5959. private panOptionBright: PanGestureOptions =
  5960. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  5961. private panOptionVolume: PanGestureOptions =
  5962. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  5963. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  5964. //手势的音量控制和亮度控制
  5965. private positionX: number = PlayConstants.POSITION_X;
  5966. private positionY: number = PlayConstants.POSITION_Y;
  5967. private windowClass: window.Window = globalThis.windowClass
  5968. @State volume: number = 0.5;
  5969. @State volumeSmall: boolean = false
  5970. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  5971. @State bright: number = PlayConstants.BRIGHT;
  5972. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  5973. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  5974. @State screenWidth: number = 0
  5975. @State screenHeight: number = 0
  5976. @State statusBarHeight: number = 0
  5977. @State isYesFull: boolean = false
  5978. private seekValue: number = 0
  5979. @State isVideoLock: boolean = false; // Whether the video playback is locked
  5980. eventHub = getContext().eventHub;
  5981. //投播组件
  5982. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  5983. private castController: avSession.AVCastController | undefined = undefined;
  5984. @State isCastPlaying: boolean = false;
  5985. @State currentTime2: number = 0;
  5986. @State currentStringTime: string = '00:00';
  5987. @State duration: number = 0;
  5988. @State isReady: boolean = false;
  5989. @State durationTime: number = 0;
  5990. @State durationStringTime: string = '00:00';
  5991. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  5992. // @State isPlaying: boolean = false;
  5993. private castSeek: boolean = false;
  5994. private castItem: avSession.AVQueueItem | undefined = undefined;
  5995. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  5996. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  5997. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  5998. @State rotateAngle2: number = 0
  5999. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  6000. @State cover: string | undefined = '';
  6001. @State artist: string | undefined = ''
  6002. // 1.初始化controller
  6003. private lyricController: LyricController = new LyricController()
  6004. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  6005. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  6006. private parser = new LyricParser()
  6007. @State randomColor: string = 'rgb(0,0,0)'
  6008. @State randomShakenX: number = 0
  6009. @State randomShakenY: number = 0
  6010. @State lyricTextSize: number = 24
  6011. @State lyricContent: string = ''
  6012. @State isDebug: boolean = false
  6013. @State isHightLightCenter: boolean = true
  6014. /**
  6015. * 初始化歌词加载与展示逻辑
  6016. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  6017. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  6018. * @param isApi2 是否使用API2获取歌词(可选)
  6019. *
  6020. * 主要流程:
  6021. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  6022. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  6023. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  6024. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  6025. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  6026. * 6. 解析失败或读取失败时,清空歌词显示。
  6027. *
  6028. * 注意事项:
  6029. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  6030. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  6031. * - 歌词内容解析后通过lyricController驱动UI渲染。
  6032. */
  6033. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  6034. if (StrUtil.isEmpty(lyricPath)) {
  6035. return
  6036. }
  6037. this.initPipLyricSetting()
  6038. this.lyricControllerSingle
  6039. .setTextSize(15)
  6040. .setCacheSize(4)
  6041. .setTextColor("#FFFFFF")
  6042. .setHighlightColor("#FFFFFF")
  6043. .setHighlightScale(1.2)
  6044. .setEmptyHint("")
  6045. .setAlignMode('center')
  6046. .setAnimationDuration(500)
  6047. .setSingleLine(true)
  6048. this.lyricContent = ''
  6049. this.lyricController
  6050. .setTextSize(this.currentLyricSize)
  6051. .setCacheSize(4)
  6052. .setTextColor("#DDDDDD")
  6053. .setHighlightColor("#FFFFFF")
  6054. .setEmptyHint("")
  6055. .setAnimationDuration(1000)
  6056. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  6057. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  6058. this.setBlurDegree(this.blurDegree, false)
  6059. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  6060. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  6061. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  6062. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  6063. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  6064. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  6065. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  6066. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6067. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  6068. this.lyricController.setTextWeight(this.lyricTextWeight)
  6069. this.showSingleLyric = false
  6070. this.timeOffset = 0
  6071. this.lyricController.setLyric(null)
  6072. this.lyricControllerSingle.setLyric(null)
  6073. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  6074. console.log("onecold lyricPath =" + lyricPath)
  6075. let neiqianLrc = ''
  6076. let lyContent = this.currentSong?.lyricContent
  6077. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  6078. neiqianLrc = lyContent
  6079. }
  6080. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  6081. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  6082. //赋值给this.lyricContent,播控中心才可以显示歌词
  6083. this.lyricContent = neiqianLrc
  6084. // 将文件内容按行分割成字符串数组
  6085. let lines = neiqianLrc.split('\n').map(line => line.trim());
  6086. // 3.解析歌词
  6087. let lyric = this.parser.parse(lines);
  6088. // 4.设置歌词
  6089. this.lyricController.setLyric(lyric);
  6090. this.lyricControllerXF.setLyric(lyric)
  6091. this.lyricControllerSingle.setLyric(lyric)
  6092. return
  6093. }
  6094. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  6095. && !Utility.isVideoByExtension(this.videoUrl))) {
  6096. if (this.currentSong !== undefined) {
  6097. // ToastUtil.showShort('正在为你搜索在线歌词!')
  6098. //判断是不是赞助会员,是会员的话才开启歌词功能
  6099. // if (!this.isDebug) {
  6100. // if (!Utility.isNoble()) {
  6101. // LogUtil.debug("onecold 不是赞助会员")
  6102. // return
  6103. // }
  6104. // if(!Utility.isPassInstallTime(33)){
  6105. // LogUtil.debug("onecold not pass time")
  6106. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  6107. // return
  6108. // }
  6109. // }
  6110. let artist = this.currentSong?.artist
  6111. if (artist === undefined) {
  6112. artist = ''
  6113. }
  6114. if (isApi2 === undefined) {
  6115. isApi2 = false
  6116. }
  6117. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  6118. // LogUtil.debug("onecold res =" + res)
  6119. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6120. if (StrUtil.isNotEmpty(res)) {
  6121. this.lyricContent = res
  6122. let lines = res.split('\n').map(line => line.trim());
  6123. // 3.解析歌词
  6124. let lyric = this.parser.parse(lines);
  6125. // 4.设置歌词
  6126. this.lyricController.setLyric(lyric);
  6127. this.lyricControllerXF.setLyric(lyric)
  6128. this.lyricControllerSingle.setLyric(lyric)
  6129. this.showSingleLyric = true
  6130. // 4.保存歌词文件lyric到本地
  6131. //2025年8月28日歌词不再加密下载
  6132. this.saveDataToFile(res, lyricPath, false)
  6133. } else {
  6134. this.lyricController.setLyric(null)
  6135. this.lyricControllerXF.setLyric(null)
  6136. this.lyricControllerSingle.setLyric(null)
  6137. if (isOnLineAndToast) {
  6138. ToastUtil.showShort('未获取到歌词!')
  6139. }
  6140. }
  6141. } else {
  6142. this.lyricController.setLyric(null)
  6143. this.lyricControllerXF.setLyric(null)
  6144. this.lyricControllerSingle.setLyric(null)
  6145. if (isOnLineAndToast) {
  6146. ToastUtil.showShort('未获取到歌词!')
  6147. }
  6148. }
  6149. })
  6150. } else {
  6151. this.lyricController.setLyric(null)
  6152. this.lyricControllerXF.setLyric(null)
  6153. this.lyricControllerSingle.setLyric(null)
  6154. if (isOnLineAndToast) {
  6155. ToastUtil.showShort('未获取到歌词!')
  6156. }
  6157. }
  6158. return
  6159. }
  6160. try {
  6161. let isJiaMi = false;
  6162. let realLyricPath = lyricPath
  6163. if (FileUtil.accessSync(jiaMilyricPath)) {
  6164. isJiaMi = true
  6165. realLyricPath = jiaMilyricPath
  6166. console.info("onecold 找到加密本地歌词 ");
  6167. } else {
  6168. isJiaMi = false
  6169. realLyricPath = lyricPath
  6170. console.info("onecold 找到本地歌词 ");
  6171. }
  6172. // 3.读取文件内容并指定编码为 UTF-8
  6173. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6174. const stat = await fileIo.stat(file.fd);
  6175. const arrayBuffer = new ArrayBuffer(stat.size);
  6176. fs.read(file.fd, arrayBuffer)
  6177. .then((readLen: number) => {
  6178. console.info("read file data succeed");
  6179. // let buf = buffer.from(arrayBuffer, 0, readLen);
  6180. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6181. // 检查 buf 是否为空
  6182. if (buf.length === 0) {
  6183. throw new Error("Buffer is empty after reading the file");
  6184. }
  6185. try {
  6186. // 检测文件编码
  6187. // let detectedEncoding = chardet.detect(buf);
  6188. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  6189. let detectedEncoding = this.detect(arrayBuffer)
  6190. console.info("onecoldT Detected encoding: " + detectedEncoding);
  6191. // 使用检测到的编码解码,解决中文乱码问题
  6192. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6193. console.info("onecoldT Detected textDecoder: " + textDecoder);
  6194. let fileContent = textDecoder.decode(buf);
  6195. console.info(`onecoldT The content of file1: ${fileContent}`);
  6196. //解密
  6197. if (isJiaMi) {
  6198. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  6199. }
  6200. console.info(`onecold The content of file2: ${fileContent}`);
  6201. this.lyricContent = fileContent
  6202. // 将文件内容按行分割成字符串数组
  6203. let lines = fileContent.split('\n').map(line => line.trim());
  6204. console.info(`onecold The content of file: ${fileContent}`);
  6205. // 3.解析歌词
  6206. let lyric = this.parser.parse(lines);
  6207. // 4.设置歌词
  6208. this.lyricController.setLyric(lyric);
  6209. this.lyricControllerXF.setLyric(lyric)
  6210. this.lyricControllerSingle.setLyric(lyric)
  6211. this.showSingleLyric = true
  6212. console.info(`The content of file: ${fileContent}`);
  6213. } catch (chardetError) {
  6214. console.error("chardet.detect failed with error: " + chardetError.message);
  6215. this.lyricController.setLyric(null);
  6216. this.lyricControllerXF.setLyric(null)
  6217. this.lyricControllerSingle.setLyric(null)
  6218. }
  6219. })
  6220. .catch((err: BusinessError) => {
  6221. this.lyricController.setLyric(null)
  6222. this.lyricControllerXF.setLyric(null)
  6223. this.lyricControllerSingle.setLyric(null)
  6224. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  6225. })
  6226. .catch((err: Error) => {
  6227. this.lyricController.setLyric(null)
  6228. this.lyricControllerXF.setLyric(null)
  6229. this.lyricControllerSingle.setLyric(null)
  6230. console.error("read file 2 data failed with error message: " + err.message);
  6231. })
  6232. .finally(() => {
  6233. fs.closeSync(file);
  6234. });
  6235. } catch (error) {
  6236. this.lyricController.setLyric(null)
  6237. this.lyricControllerSingle.setLyric(null)
  6238. this.lyricControllerXF.setLyric(null)
  6239. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  6240. }
  6241. }
  6242. detect(data: ArrayBuffer): string {
  6243. //创建检测对象
  6244. let detector: UniversalDetector = new UniversalDetector();
  6245. // 传入检测数据并实时判断编码格式
  6246. detector.handleData(data, 0, data.byteLength);
  6247. // 标记检测数据 读取结束
  6248. detector.dataEnd();
  6249. // 获取检测结果
  6250. let detected: string = detector.getDetectedCharset();
  6251. // 释放资源
  6252. detector.reset();
  6253. return detected;
  6254. }
  6255. //初始化悬浮歌词的自定义设置
  6256. initPipLyricSetting() {
  6257. this.lyricControllerXF
  6258. .setTextSize(this.currentLyricSize)
  6259. .setCacheSize(4)
  6260. .setTextColor("#DDDDDD")
  6261. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  6262. .setEmptyHint("")
  6263. .setAnimationDuration(1000)
  6264. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  6265. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  6266. this.setBlurDegree(this.blurDegreePip, true)
  6267. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  6268. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  6269. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  6270. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  6271. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  6272. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  6273. this.lyricControllerXF.setHightLightCenter(true)
  6274. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  6275. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  6276. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6277. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  6278. if (this.pipBgIndex === 0) {
  6279. if (this.cover) {
  6280. this.pipBg = this.cover
  6281. } else {
  6282. this.pipBg = this.imageColor
  6283. }
  6284. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6285. }
  6286. }
  6287. //根据item返回歌词内容
  6288. async getLyricContent(item: VideoItem): Promise<string> {
  6289. let neiqianLrc = ''
  6290. let lyContent = item?.lyricContent
  6291. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  6292. neiqianLrc = lyContent
  6293. return neiqianLrc
  6294. }
  6295. try {
  6296. let filePath = item.filePath;
  6297. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  6298. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  6299. let isJiaMi = false;
  6300. let realLyricPath = lyricPath;
  6301. if (FileUtil.accessSync(jiaMilyricPath)) {
  6302. isJiaMi = true;
  6303. realLyricPath = jiaMilyricPath;
  6304. console.info("onecold 找到加密本地歌词");
  6305. } else {
  6306. console.info("onecold 找到本地歌词");
  6307. }
  6308. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6309. const stat = await fileIo.stat(file.fd);
  6310. const arrayBuffer = new ArrayBuffer(stat.size);
  6311. const readLen = await fs.read(file.fd, arrayBuffer);
  6312. console.info("read file data succeed");
  6313. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6314. if (buf.length === 0) {
  6315. throw new Error("Buffer is empty after reading the file");
  6316. }
  6317. // let detectedEncoding = chardet.detect(buf);
  6318. let detectedEncoding = this.detect(arrayBuffer)
  6319. console.info("Detected encoding: " + detectedEncoding);
  6320. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6321. let fileContent = textDecoder.decode(buf);
  6322. console.info(`onecold The content of file1: ${fileContent}`);
  6323. if (isJiaMi) {
  6324. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  6325. }
  6326. console.info(`onecold The content of file2: ${fileContent}`);
  6327. fs.closeSync(file);
  6328. return fileContent;
  6329. } catch (error) {
  6330. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  6331. return '';
  6332. }
  6333. }
  6334. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  6335. if (StrUtil.isEmpty(filePath)) {
  6336. return
  6337. }
  6338. try {
  6339. //将content进行加密
  6340. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  6341. let lyricContent = ''
  6342. if (isJiaMi) {
  6343. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  6344. } else {
  6345. lyricContent = content
  6346. }
  6347. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  6348. // 清空文件内容
  6349. await fileIo.truncate(file.fd, 0);
  6350. await fileIo.write(file.fd, lyricContent);
  6351. await fileIo.close(file);
  6352. console.log('onecold lyric file Data saved successfully.');
  6353. } catch (error) {
  6354. console.error('onecold lyric file Failed to save data:', error);
  6355. }
  6356. }
  6357. /**
  6358. * Get largest proportion color of an image.
  6359. */
  6360. getImageColor() {
  6361. if (!this.context) {
  6362. return;
  6363. }
  6364. let bg = Utility.getMusisBg()
  6365. this.imageLabel = bg
  6366. ColorConversion.setSysBarLightBackground(true);
  6367. this.context.resourceManager.getMediaContent(bg)
  6368. .then((value: Uint8Array) => {
  6369. let buffer = value.buffer as ArrayBuffer;
  6370. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  6371. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  6372. if (error) {
  6373. Logger.error('Failed to create color picker.');
  6374. } else {
  6375. let color = colorPicker.getLargestProportionColor();
  6376. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  6377. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  6378. }
  6379. })
  6380. let headFilter = effectKit.createEffect(pixelMap);
  6381. if (headFilter !== null) {
  6382. headFilter.blur(15);
  6383. headFilter.getEffectPixelMap().then((value) => {
  6384. this.imageLabelBg = value;
  6385. })
  6386. }
  6387. })
  6388. .catch((error: BusinessError) => {
  6389. Logger.error(`${error.code} + ${error.message}`)
  6390. })
  6391. })
  6392. .catch((error: BusinessError) => {
  6393. Logger.error(`${error.code} + ${error.message}`)
  6394. })
  6395. }
  6396. setImageColor(cover: string) {
  6397. if (!this.context) {
  6398. return;
  6399. }
  6400. if (cover === undefined) {
  6401. return;
  6402. }
  6403. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  6404. let headFilter = effectKit.createEffect(value);
  6405. if (headFilter !== null) {
  6406. headFilter.blur(15);
  6407. headFilter.getEffectPixelMap().then((value) => {
  6408. this.imageLabelBg = value;
  6409. })
  6410. }
  6411. }).catch((error: BusinessError) => {
  6412. Logger.error(`${error.code} + ${error.message}`)
  6413. })
  6414. }
  6415. setImageColor2(cover: string) {
  6416. if (!this.context) {
  6417. return;
  6418. }
  6419. if (cover === undefined) {
  6420. return;
  6421. }
  6422. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  6423. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  6424. this.imageColor = data.imageColor;
  6425. if (data.blurPixelMap) {
  6426. this.imageLabelBg = data.blurPixelMap;
  6427. }
  6428. })
  6429. }
  6430. // 定义开始旋转的方法
  6431. // 定时器用于一百毫秒执行一次旋转角度
  6432. @State timer: number = 0
  6433. @State rotateAngle: number = 0
  6434. //封面旋转动画
  6435. animationRoFun() {
  6436. if (this.isPlaying && !this.isCoverRectangle) {
  6437. this.timer = setInterval(() => {
  6438. this.rotateAngle += 1
  6439. }, 100)
  6440. this.startRotation()
  6441. } else {
  6442. clearInterval(this.timer)
  6443. this.stopRotation()
  6444. }
  6445. }
  6446. // 定义开始旋转的方法
  6447. startRotation() {
  6448. if (this.isPlaying) {
  6449. animateTo({
  6450. duration: 777,
  6451. iterations: 1,
  6452. curve: Curve.Linear
  6453. }, () => {
  6454. this.rotateAngle2 = 0
  6455. })
  6456. }
  6457. }
  6458. // 回调,暂停和播放按钮回调,下一首和上一首
  6459. playChange() {
  6460. // if(this.isCoverRectangle){
  6461. // return
  6462. // }
  6463. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6464. this.setIsPlaying(true)
  6465. this.animationState = AnimationStatus.Running
  6466. } else {
  6467. this.setIsPlaying(false)
  6468. this.animationState = AnimationStatus.Paused
  6469. }
  6470. }
  6471. // 定义停止旋转的方法
  6472. stopRotation() {
  6473. if (this.isCoverRectangle) {
  6474. this.rotateAngle = 0
  6475. } else {
  6476. //唱针以左上角为点选择逆时针40度
  6477. animateTo({
  6478. duration: 1000,
  6479. curve: Curve.Linear,
  6480. iterations: 1,
  6481. }, () => {
  6482. this.rotateAngle2 = -40;
  6483. });
  6484. }
  6485. }
  6486. @Builder
  6487. private LyricsTopItem() {
  6488. Row() {
  6489. Stack() {
  6490. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6491. .height(55)
  6492. .width(55)
  6493. .alt(this.imageLabel)
  6494. .borderRadius(8)
  6495. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6496. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6497. }
  6498. .width('18%')
  6499. Column() {
  6500. Column() {
  6501. Text(this.name)
  6502. .fontSize(16)
  6503. .maxLines(1)
  6504. .fontWeight(FontWeight.Bolder)
  6505. .fontColor(this.currentLyricColor)
  6506. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6507. Row() {
  6508. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6509. .fontSize(13)
  6510. .fontWeight(FontWeight.Bold)
  6511. .padding({ top: 8 })
  6512. .fontColor(this.currentLyricColor)
  6513. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6514. Blank()
  6515. }
  6516. }
  6517. .height('100%')
  6518. .width('100%')
  6519. .justifyContent(FlexAlign.Center)
  6520. .alignItems(HorizontalAlign.Start)
  6521. }
  6522. .height('100%')
  6523. .width('65%')
  6524. Column() {
  6525. Image($r('app.media.lyric'))
  6526. .width(28)
  6527. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6528. .margin({ right: 30 })
  6529. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6530. .onClick(() => {
  6531. this.isLyricSetting = !this.isLyricSetting;
  6532. })
  6533. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6534. height: this.isCoverOpacity() ? '95%' : '88%',
  6535. dragBar: true,
  6536. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6537. showClose: true,
  6538. blurStyle: BlurStyle.Thin,
  6539. backgroundColor: Color.Transparent,
  6540. // title: { title: $r('app.string.lyric_setting') }
  6541. })
  6542. }
  6543. .width('18%')
  6544. }
  6545. .width('82%')
  6546. .height(58)
  6547. .justifyContent(FlexAlign.SpaceBetween)
  6548. }
  6549. //歌词显示
  6550. @Builder
  6551. PlayerLyrics() {
  6552. Column() {
  6553. Column() {
  6554. this.LyricsTopItem()
  6555. }
  6556. .height(this.isPuraWP() ? 15 : 58)
  6557. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6558. Visibility.None : Visibility.Visible)
  6559. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6560. .width("100%")
  6561. Column() {
  6562. LyricView2({
  6563. controller: this.lyricController,
  6564. enableSeek: true,
  6565. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6566. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6567. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6568. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6569. if (!this.isPlaying) {
  6570. this.startPlayOrResumePlay()
  6571. } else {
  6572. this.isSeekTo = true;
  6573. this.mDestroyPage = false;
  6574. this.showLoadIng();
  6575. this.seekTo(position + "");
  6576. this.isSeekTo = false;
  6577. }
  6578. return true
  6579. }
  6580. })
  6581. .width("100%")
  6582. .layoutWeight(1)
  6583. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6584. if (this.isPhoneLan()) {
  6585. Column() {
  6586. this.playProgressView()
  6587. // this.playCenterView()
  6588. }
  6589. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6590. }
  6591. }
  6592. .position({
  6593. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6594. (this.isPuraWP() ? 58 : 99)
  6595. })
  6596. .justifyContent(FlexAlign.Center)
  6597. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  6598. }
  6599. }
  6600. @Builder
  6601. SingleLyricView() {
  6602. Column() {
  6603. Column() {
  6604. LyricView2({
  6605. controller: this.lyricControllerSingle,
  6606. enableSeek: false,
  6607. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6608. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6609. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6610. })
  6611. }
  6612. .height(66)
  6613. .margin({ bottom: 20 })
  6614. }
  6615. }
  6616. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6617. @Builder
  6618. BottomControl() {
  6619. Column() {
  6620. this.TopPlayProgressView()
  6621. //播放 暂停,下一首,上一首
  6622. this.playCenterView()
  6623. //播放进度条
  6624. this.BottomView()
  6625. }
  6626. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  6627. }
  6628. //播放控制上一首 下一首 暂停和播放
  6629. @Builder
  6630. playCenterView(){
  6631. Row() {
  6632. Row({ space: 20 }) {
  6633. Button({type:ButtonType.Circle,stateEffect:true}){
  6634. //更多功能
  6635. Image($r('app.media.menu'))
  6636. .width(24)
  6637. .clickEffect({level:ClickEffectLevel.MIDDLE})
  6638. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6639. height: this.isCoverOpacity() ? '95%' : '93%',
  6640. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6641. dragBar: true,
  6642. showClose: true,
  6643. blurStyle: BlurStyle.Thin,
  6644. backgroundColor: Color.Transparent,
  6645. })
  6646. }
  6647. .margin({ left: 5 })
  6648. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6649. .backgroundColor(Color.Transparent)
  6650. .onClick(() => {
  6651. this.isShowMoreView = !this.isShowMoreView;
  6652. })
  6653. Button({type:ButtonType.Circle,stateEffect:true}){
  6654. Image($r('app.media.ic_previous'))
  6655. .width(33)
  6656. .clickEffect({level:ClickEffectLevel.HEAVY})
  6657. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6658. }
  6659. .onClick(async () => {
  6660. this.playPrevious()
  6661. })
  6662. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6663. .backgroundColor(Color.Transparent)
  6664. .margin({ left: 5 })
  6665. }
  6666. Button({type:ButtonType.Circle,stateEffect:true}){
  6667. Column() {
  6668. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6669. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  6670. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  6671. .width(this.isPhoneLan()?45:55)
  6672. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6673. .fillColor(Color.White)
  6674. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6675. .onClick(async () => {
  6676. this.playOrPause()
  6677. })
  6678. }
  6679. }
  6680. .backgroundColor(Color.Transparent)
  6681. .layoutWeight(1)
  6682. // .margin({ left: 38, right: 38 })
  6683. Row({ space: 20 }) {
  6684. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6685. Image($r('app.media.ic_next'))
  6686. .width(33)
  6687. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6688. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6689. .onClick(() => {
  6690. this.playNext();
  6691. })
  6692. }
  6693. .backgroundColor(Color.Transparent)
  6694. .margin({ right: 5 })
  6695. .width(33)
  6696. if(this.isPhoneLan()){
  6697. this.fullButton()
  6698. }else{
  6699. Button({type:ButtonType.Circle,stateEffect:true}){
  6700. //添加或取消收藏
  6701. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  6702. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  6703. .fontSize(23)
  6704. .fontColor([Color.White])
  6705. .alignSelf(ItemAlign.Center)
  6706. // .width(24)
  6707. .clickEffect({level:ClickEffectLevel.MIDDLE})
  6708. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6709. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6710. .onClick(async () => {
  6711. if(this.currentSong){
  6712. this.doFav(this.currentSong)
  6713. }
  6714. })
  6715. }
  6716. .backgroundColor(Color.Transparent)
  6717. .width(24)
  6718. }
  6719. }
  6720. // .margin({ left: 5 })
  6721. }
  6722. .width('95%')
  6723. .margin({ bottom:this.isCoverOpacity()?0:20 })
  6724. .justifyContent(FlexAlign.SpaceEvenly)
  6725. }
  6726. @Builder
  6727. TopPlayProgressView(){
  6728. Row() {
  6729. Column(){
  6730. Row(){
  6731. Slider({
  6732. value: this.progressValue,
  6733. min: 0,
  6734. max: this.PROGRESS_MAX_VALUE,
  6735. step: 1,
  6736. style: SliderStyle.InSet
  6737. })
  6738. .height(20)
  6739. .blockColor('rgba(255,255,255,1)')
  6740. .trackColor('rgba(255,255,255,0.3)')
  6741. .selectedColor(Color.White)
  6742. .trackThickness(4)
  6743. .layoutWeight(1)
  6744. .showSteps(false)
  6745. .showTips(true)
  6746. .alignSelf(ItemAlign.Center)
  6747. .enabled(this.slideEnable)
  6748. .onChange((value: number, mode: SliderChangeMode) => {
  6749. // if (mode == 2) {
  6750. this.isSeekTo = true;
  6751. this.mDestroyPage = false;
  6752. this.showLoadIng();
  6753. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6754. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6755. this.seekTo(seekValue + "");
  6756. // this.setProgress()
  6757. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6758. this.isSeekTo = false;
  6759. // }
  6760. })
  6761. }
  6762. .padding({ right: 7,left:20 })
  6763. Row(){
  6764. Text(this.currentTime)
  6765. .fontSize(10)
  6766. .fontColor(Color.White)
  6767. Blank()
  6768. .layoutWeight(1)
  6769. Text(this.totalTime)
  6770. .fontSize(10)
  6771. .fontColor(Color.White)
  6772. }
  6773. .justifyContent(FlexAlign.Start)
  6774. .padding({ right: 18,left:36 })
  6775. }
  6776. }
  6777. //x5的竖屏模式需要99%
  6778. .width(this.isLandscape?'80%':'93%')
  6779. .justifyContent(FlexAlign.Center)
  6780. .margin({bottom:6})
  6781. .animation({
  6782. duration: 666,
  6783. curve: 'ease-in-out' // 可选动画曲线
  6784. })
  6785. }
  6786. //播放进度条
  6787. @Builder
  6788. BottomView(){
  6789. Row() {
  6790. Button({type:ButtonType.Circle,stateEffect:true}){
  6791. Column() {
  6792. if (this.playType === 0) {
  6793. Image($r('app.media.loop'))
  6794. .width(27)
  6795. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6796. } else if (this.playType === 1) {
  6797. Image($r('app.media.single'))
  6798. .width(27)
  6799. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6800. } else if (this.playType === 2) {
  6801. Image($r('app.media.normal_play'))
  6802. .width(27)
  6803. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6804. } else if (this.playType === 3) {
  6805. Image($r('app.media.random'))
  6806. .width(27)
  6807. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6808. }
  6809. }
  6810. }
  6811. .layoutWeight(1)
  6812. .margin({ left: 5 })
  6813. .backgroundColor(Color.Transparent)
  6814. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6815. .onClick(async () => {
  6816. this.setLoopMode()
  6817. })
  6818. this.fullButton()
  6819. Button({type:ButtonType.Circle,stateEffect:true}){
  6820. Column() {
  6821. Image($r('app.media.lyric'))
  6822. .width(26)
  6823. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6824. }
  6825. }
  6826. .layoutWeight(1)
  6827. .backgroundColor(Color.Transparent)
  6828. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6829. .onClick(async () => {
  6830. this.isLyricSetting = !this.isLyricSetting;
  6831. })
  6832. //播放列表
  6833. Button({type:ButtonType.Circle,stateEffect:true}){
  6834. Image($r('app.media.hm_playlist'))
  6835. .width(24)
  6836. .fillColor(Color.White)
  6837. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6838. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6839. height: '95%',
  6840. dragBar: true,
  6841. showClose: true,
  6842. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6843. blurStyle: BlurStyle.Thin,
  6844. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  6845. title: {
  6846. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6847. + `(${this.songList.length}首)`
  6848. }
  6849. })
  6850. }
  6851. .layoutWeight(1)
  6852. .backgroundColor(Color.Transparent)
  6853. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6854. .onClick(() => {
  6855. this.isShowSheetView = !this.isShowSheetView;
  6856. if(this.isPlayListBgGrass){
  6857. this.isFrontWhite = true
  6858. }else{
  6859. this.isFrontWhite = false
  6860. }
  6861. this.scrollIndex()
  6862. })
  6863. }
  6864. .width(this.isLandscape?'88%':'95%')
  6865. .justifyContent(FlexAlign.SpaceAround)
  6866. .height(30)
  6867. .margin({top:3})
  6868. .animation({
  6869. duration: 666,
  6870. curve: 'ease-in-out' // 可选动画曲线
  6871. })
  6872. }
  6873. @Builder
  6874. fullButton(){
  6875. Button({type:ButtonType.Circle,stateEffect:true}){
  6876. Column() {
  6877. Image($r('app.media.full_4'))
  6878. .width(25)
  6879. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6880. }
  6881. }
  6882. .layoutWeight(1)
  6883. .backgroundColor(Color.Transparent)
  6884. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6885. .onClick(async () => {
  6886. if (this.isLandscape) {
  6887. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  6888. } else {
  6889. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  6890. }
  6891. })
  6892. }
  6893. //旧版本播放进度条
  6894. @Builder
  6895. playProgressView() {
  6896. Row() {
  6897. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6898. Column() {
  6899. if (this.playType === 0) {
  6900. Image($r('app.media.loop'))
  6901. .width($r('app.float.control_image_width'))
  6902. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6903. } else if (this.playType === 1) {
  6904. Image($r('app.media.single'))
  6905. .width($r('app.float.control_image_width'))
  6906. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6907. } else if (this.playType === 2) {
  6908. Image($r('app.media.normal_play'))
  6909. .width($r('app.float.control_image_width'))
  6910. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6911. } else if (this.playType === 3) {
  6912. Image($r('app.media.random'))
  6913. .width($r('app.float.control_image_width'))
  6914. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6915. }
  6916. }
  6917. }
  6918. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6919. .animation({
  6920. duration: 666,
  6921. curve: 'ease-in-out' // 可选动画曲线
  6922. })
  6923. .backgroundColor(Color.Transparent)
  6924. .margin({ right: 10 })
  6925. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6926. .onClick(async () => {
  6927. this.setLoopMode()
  6928. })
  6929. Text(this.currentTime)
  6930. .fontSize($r('app.float.slider_font_size'))
  6931. .fontColor(Color.White)
  6932. .margin(3)
  6933. Slider({
  6934. value: this.progressValue,
  6935. min: 0,
  6936. max: this.PROGRESS_MAX_VALUE,
  6937. step: 1,
  6938. style: SliderStyle.OutSet
  6939. })
  6940. .width('600px')
  6941. .blockColor('rgba(255,255,255,1)')
  6942. .trackColor('rgba(255,255,255,0.3)')
  6943. .selectedColor(Color.White)
  6944. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  6945. .layoutWeight(1)
  6946. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6947. .showSteps(false)
  6948. .showTips(true)
  6949. .enabled(this.slideEnable)
  6950. .onChange((value: number, mode: SliderChangeMode) => {
  6951. // if (mode == 2) {
  6952. this.isSeekTo = true;
  6953. this.mDestroyPage = false;
  6954. this.showLoadIng();
  6955. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6956. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6957. this.seekTo(seekValue + "");
  6958. // this.setProgress()
  6959. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6960. this.isSeekTo = false;
  6961. // }
  6962. })
  6963. Text(this.totalTime)
  6964. .fontSize($r('app.float.slider_font_size'))
  6965. .fontColor(Color.White)
  6966. .margin(3)
  6967. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6968. //播放列表
  6969. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6970. Image($r('app.media.hm_playlist'))
  6971. .width($r('app.float.control_image_width'))
  6972. .fillColor(Color.White)
  6973. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6974. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6975. height: '95%',
  6976. dragBar: true,
  6977. showClose: true,
  6978. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6979. blurStyle: BlurStyle.Thin,
  6980. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6981. title: {
  6982. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6983. + `(${this.songList.length}首)`
  6984. }
  6985. })
  6986. }
  6987. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6988. .animation({
  6989. duration: 666,
  6990. curve: 'ease-in-out' // 可选动画曲线
  6991. })
  6992. .backgroundColor(Color.Transparent)
  6993. .margin({ right: 20, left: 10 })
  6994. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6995. .onClick(() => {
  6996. this.isShowSheetView = !this.isShowSheetView;
  6997. if (this.isPlayListBgGrass) {
  6998. this.isFrontWhite = true
  6999. } else {
  7000. this.isFrontWhite = false
  7001. }
  7002. this.scrollIndex()
  7003. })
  7004. }
  7005. //x5的竖屏模式需要99%
  7006. .width(this.isPhonePortrait() ? '93.4%'
  7007. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  7008. .height(this.isPhoneLan() ? 25 : 33)
  7009. .animation({
  7010. duration: 666,
  7011. curve: 'ease-in-out' // 可选动画曲线
  7012. })
  7013. }
  7014. isBigScreen() {
  7015. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  7016. return true
  7017. }
  7018. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7019. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  7020. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  7021. return false
  7022. } else {
  7023. return true
  7024. }
  7025. return false
  7026. }
  7027. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  7028. @State isCoverRectangle: boolean = false
  7029. @State isCoverTop: boolean = true
  7030. // 添加控制缩放的状态变量
  7031. @State scaleValueImage: number = 1
  7032. @Builder
  7033. CoverInfo() {
  7034. Column() {
  7035. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  7036. if (this.isCoverRectangle) {
  7037. if (!this.isCoverTop) {
  7038. this.musicNameInfo(false)
  7039. }
  7040. } else {
  7041. this.musicNameInfo(false)
  7042. }
  7043. Stack() {
  7044. // 唱片旋转效果
  7045. Image($r('app.media.ic_music_disc'))
  7046. .width(245)
  7047. .height(245)
  7048. .margin({ right: 20, left: 20 })
  7049. .aspectRatio(1)
  7050. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7051. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7052. .borderRadius('100%')
  7053. .align(Alignment.Center)
  7054. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  7055. .rotate({
  7056. angle: this.rotateAngle,
  7057. centerX: "50%",
  7058. centerY: "50%",
  7059. })
  7060. .animation({
  7061. duration: 100,
  7062. curve: Curve.Linear
  7063. })
  7064. .shadow({
  7065. radius: 30,
  7066. color: this.randomColor
  7067. })
  7068. Column() {
  7069. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  7070. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  7071. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  7072. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7073. .alt(this.imageLabel)
  7074. .margin({ right: 8, left: 8, top: 8 })
  7075. .aspectRatio(1)
  7076. .opacity(this.opacityValueImage)
  7077. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7078. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7079. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7080. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7081. .align(Alignment.Center)//
  7082. .clip(true)
  7083. .rotate({
  7084. x: 0,
  7085. y: 0,
  7086. z: 1,
  7087. angle: this.rotateAngle
  7088. })
  7089. .onClick(() => {
  7090. this.getImageColor()
  7091. })
  7092. this.musicNameInfo(false)
  7093. } else {
  7094. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7095. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  7096. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7097. .alt(this.imageLabel)
  7098. .margin({ right: 20, left: 20 })
  7099. .aspectRatio(1)
  7100. .opacity(this.opacityValueImage)
  7101. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7102. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7103. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7104. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7105. .align(Alignment.Center)//
  7106. .clip(true)
  7107. .rotate({
  7108. x: 0,
  7109. y: 0,
  7110. z: 1,
  7111. angle: this.rotateAngle
  7112. })
  7113. .onClick(() => {
  7114. this.getImageColor()
  7115. })
  7116. if (this.isPhoneLan()) {
  7117. Text(this.name)
  7118. .fontSize(18)
  7119. .fontWeight(FontWeight.Bold)
  7120. .margin({ top: 13 })
  7121. .textOverflow({ overflow: TextOverflow.Ellipsis })
  7122. .maxLines(1)
  7123. .width('99%')
  7124. .textAlign(TextAlign.Center)
  7125. .fontColor(Color.White)
  7126. }
  7127. }
  7128. }
  7129. // 唱针以左上角为点选择逆时针40度
  7130. Image($r('app.media.ic_music_cover_hand'))
  7131. .height(130)
  7132. .margin({ bottom: 220, top: 0 })
  7133. .align(Alignment.Top)
  7134. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  7135. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7136. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7137. Column({ space: 8 }) {
  7138. Text(this.name)
  7139. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  7140. .fontWeight(FontWeight.Bold)
  7141. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7142. .maxLines(1)
  7143. .width('48%')
  7144. .textAlign(TextAlign.Center)
  7145. .fontColor(Color.White)
  7146. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7147. Text(this.artist)
  7148. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  7149. .fontColor(Color.White)
  7150. .fontWeight(FontWeight.Bold)
  7151. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7152. }
  7153. .justifyContent(FlexAlign.Start)
  7154. .zIndex(1)
  7155. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  7156. }
  7157. .margin({
  7158. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  7159. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  7160. top: this.isCoverOpacity() ? 0 : 20
  7161. })
  7162. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  7163. this.SingleLyricView()
  7164. }
  7165. if (this.isPhoneLan()) {
  7166. Column() {
  7167. this.playCenterView()
  7168. // this.playProgressView()
  7169. }
  7170. .position({ left: 28, bottom: 38 })
  7171. } else {
  7172. this.BottomControl()
  7173. }
  7174. }
  7175. .width(CommonConstants.FULL_PERCENT)
  7176. .clip(true)
  7177. }
  7178. @Builder
  7179. private musicNameInfo(isHidden: boolean) {
  7180. Column({ space: 8 }) {
  7181. Text(this.name)
  7182. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  7183. .fontWeight(FontWeight.Bold)
  7184. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7185. .maxLines(1)
  7186. .width('99%')
  7187. .textAlign(TextAlign.Center)
  7188. .fontColor(Color.White)
  7189. Text(this.artist + ' ' + this.currentSong?.album)
  7190. .fontSize(this.isCoverOpacity() ? 12 : 15)
  7191. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7192. .fontColor(Color.White)
  7193. .textAlign(TextAlign.Center)
  7194. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  7195. .width('99%')
  7196. .maxLines(1)
  7197. }
  7198. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  7199. .zIndex(1)
  7200. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7201. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  7202. }
  7203. @Builder
  7204. private PlayTitle() {
  7205. Row() {
  7206. Row() {
  7207. Image($r('app.media.ic_back_down'))
  7208. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  7209. .hitTestBehavior(HitTestMode.Transparent)
  7210. Text(this.name + ' ' + this.artist)
  7211. .fontColor(Color.White)
  7212. .fontSize($r('app.float.title_font_size'))
  7213. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7214. .maxLines(1)
  7215. .visibility(Visibility.None)
  7216. .margin({ left: 2, right: 30 })
  7217. }
  7218. .layoutWeight(1)
  7219. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7220. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  7221. .onClick(() => {
  7222. this.isShowPlay = false;
  7223. })
  7224. Column() {
  7225. AVCastPicker({
  7226. normalColor: Color.White,
  7227. onStateChange: this.onStateVastChange
  7228. })
  7229. .width(24)
  7230. .height(24)
  7231. }
  7232. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  7233. }
  7234. .width(PlayConstants.ROW_WIDTH)
  7235. }
  7236. @Builder
  7237. lyricSettingSheet(isPip: boolean) {
  7238. Scroll() {
  7239. this.lyricSetting(isPip)
  7240. }
  7241. .width('100%')
  7242. .height('100%')
  7243. }
  7244. @Builder
  7245. lyricSetting(isPip: boolean) {
  7246. Column() {
  7247. // 时间调节模块
  7248. if (!isPip) {
  7249. this.BuildTimeControls()
  7250. }
  7251. // 字号控制模块
  7252. this.BuildFontControls(isPip)
  7253. }
  7254. }
  7255. // 歌词时间偏移状态
  7256. @State timeOffset: number = 0.0
  7257. @State currentLyricColor: string = '#FFFFFF'
  7258. @State currentLyricColorPip: string = '#FFFFFF'
  7259. @State currentHighLightLyricColor: string = '#FF4081'
  7260. @State currentHighLightLyricColorPip: string = '#FF4081'
  7261. // 歌词字号状态
  7262. @State currentLyricSize: number = 20
  7263. @State currentLyricSizePip: number = 20
  7264. // 高亮歌词放大倍数
  7265. @State currentHightLyricSize: number = 1.2
  7266. @State currentHightLyricSizePip: number = 1.2
  7267. @State currentLyricLineSpace: number = 10
  7268. @State currentLyricLineSpacePip: number = 10
  7269. @State currentLyricAlignMode: number = 1
  7270. @State currentLyricAlignModePip: number = 1
  7271. @State blurDegree: number = 2
  7272. @State blurDegreePip: number = 2
  7273. @State isShowSelectColor: boolean = false
  7274. @State isShowHLSelectColor: boolean = false
  7275. @State isShowPipBgSelectColor: boolean = false
  7276. @State pipLyWidth: number = 330
  7277. @State pipLyHeight: number = 120
  7278. // 构建颜色选择器
  7279. @Builder
  7280. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  7281. Row({ space: 10 }) {
  7282. HSBColorPicker({
  7283. color: '#FFFFFF',
  7284. radius: 8,
  7285. layout: HSBColorPickerLayout.COLUMN,
  7286. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  7287. '#fa7105'],
  7288. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  7289. this.changeLyricColor(value, isPip, isBGPip)
  7290. })
  7291. .height(250)
  7292. .layoutWeight(1)
  7293. .padding(25)
  7294. }
  7295. .width('66%')
  7296. }
  7297. @State isOpenPip: boolean = false
  7298. @State pipBgIndex: number = 0
  7299. // 构建字号控制器
  7300. @Builder
  7301. BuildFontControls(isPip: boolean) {
  7302. Column() {
  7303. if (isPip) {
  7304. Column() {
  7305. Row() {
  7306. Text('悬浮歌词')
  7307. .margin({ left: 18 })
  7308. .fontSize(15)
  7309. .fontColor(Color.White)
  7310. .fontWeight(480)
  7311. .layoutWeight(1)
  7312. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  7313. .selectedColor(this.themeColor)
  7314. .switchPointColor(Color.White)
  7315. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7316. .margin({ right: 18 })
  7317. .onChange((checked: boolean) => {
  7318. this.isOpenPip = checked;
  7319. if (this.isOpenPip) {
  7320. this.startPip()
  7321. } else {
  7322. this.stopPip()
  7323. }
  7324. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  7325. })
  7326. .width(50)
  7327. .height(30);
  7328. }
  7329. .height(55)
  7330. }
  7331. .backgroundColor(Color.Transparent)
  7332. .borderRadius(15)
  7333. .margin({
  7334. left: 30,
  7335. right: 30,
  7336. top: 0,
  7337. bottom: 20
  7338. })
  7339. .padding(0)
  7340. .border({
  7341. color: Color.White,
  7342. width: 1.8
  7343. })
  7344. }
  7345. Row() {
  7346. Text(`歌词居中:`)
  7347. .fontSize(14)
  7348. .fontColor(Color.White)
  7349. .margin({ left: 2 })
  7350. Row() {
  7351. ForEach(['居中', '居左'], (size: string, index: number) => {
  7352. Button(size)
  7353. .width(60)
  7354. .height(28)
  7355. .fontSize(12)
  7356. .fontColor('#FFFFFF')
  7357. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  7358. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  7359. .border({
  7360. color: (!isPip && this.currentLyricAlignMode === index) ||
  7361. (isPip && this.currentLyricAlignModePip === index) ?
  7362. '#007DFF' : '#DDDDDD',
  7363. width: 1.8
  7364. })
  7365. .onClick(() => {
  7366. this.setLyricAlignMode(index, isPip)
  7367. })
  7368. .margin({ left: 10, right: 8 })
  7369. })
  7370. }
  7371. .width('76%')
  7372. Blank()
  7373. }
  7374. .margin({
  7375. top: 10,
  7376. bottom: 10,
  7377. right: 20,
  7378. left: 20
  7379. })
  7380. if (isPip) {
  7381. Row() {
  7382. Text(`悬浮背景:`)
  7383. .fontSize(14)
  7384. .fontColor(Color.White)
  7385. Select([
  7386. { value: CommonConstants.PIP_LYRIC_BG[0] },
  7387. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  7388. .font({ size: 13, weight: FontWeight.Medium })
  7389. .fontColor(Color.White)
  7390. .margin({ left: 10 })
  7391. .selected(this.pipBgIndex)
  7392. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  7393. .onSelect(async (_index: number, text?: string | undefined) => {
  7394. this.pipBgIndex = _index
  7395. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  7396. if (this.pipBgIndex === 0) {
  7397. if (this.cover) {
  7398. this.pipBg = this.cover
  7399. } else {
  7400. this.pipBg = this.imageColor
  7401. }
  7402. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7403. } else {
  7404. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7405. }
  7406. })
  7407. Column() {
  7408. }
  7409. .backgroundColor(this.pipBg)
  7410. .margin({ left: 10, right: 10 })
  7411. .borderRadius(20)
  7412. .height(28)
  7413. .width(28)
  7414. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7415. Row() {
  7416. SymbolGlyph($r('sys.symbol.paintbrush'))
  7417. .fontColor([Color.White])
  7418. .effectStrategy(1)
  7419. Text(`选择颜色`)
  7420. .fontSize(13)
  7421. .margin({ left: 10 })
  7422. .fontColor(Color.White)
  7423. }
  7424. }
  7425. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  7426. .backgroundColor(Color.Transparent)
  7427. .border({
  7428. color: '#FFFFFF',
  7429. radius: 20,
  7430. width: 1.8
  7431. })
  7432. .height(36)
  7433. .width(110)
  7434. .onClick(() => {
  7435. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  7436. })
  7437. .bindPopup(this.isShowPipBgSelectColor, {
  7438. builder: this.SelectColor(false, isPip, true),
  7439. placement: Placement.Top,
  7440. mask: { color: '#33000000' },
  7441. enableArrow: false, //是否显示箭头
  7442. showInSubWindow: false,
  7443. onStateChange: (e) => {
  7444. if (!e.isVisible) {
  7445. this.isShowPipBgSelectColor = false
  7446. }
  7447. }
  7448. })
  7449. }
  7450. .width('76%')
  7451. .margin({ bottom: 5, right: 45, left: 20 })
  7452. }
  7453. if (!isPip) {
  7454. Row() {
  7455. Text(`高亮居中:`)
  7456. .fontSize(14)
  7457. .fontColor(Color.White)
  7458. Column() {
  7459. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  7460. .selectedColor(this.themeColor)
  7461. .switchPointColor(Color.White)
  7462. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7463. .onChange((checked: boolean) => {
  7464. this.isHightLightCenter = checked;
  7465. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  7466. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7467. })
  7468. .width(50)
  7469. .height(30)
  7470. .alignSelf(ItemAlign.Start)
  7471. .margin({ left: 12 })
  7472. Blank()
  7473. }
  7474. .width('76%')
  7475. }
  7476. .margin({
  7477. left: 20,
  7478. right: 15,
  7479. top: 10,
  7480. bottom: 10
  7481. })
  7482. }
  7483. Row() {
  7484. Text(`歌词颜色:`)
  7485. .fontSize(14)
  7486. .fontColor(Color.White)
  7487. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7488. .fontSize(15)
  7489. .fontColor(Color.White)
  7490. .margin({ left: 12, right: 12 })
  7491. Column() {
  7492. }
  7493. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7494. .margin({ right: 12 })
  7495. .borderRadius(20)
  7496. .height(28)
  7497. .width(28)
  7498. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7499. Row() {
  7500. SymbolGlyph($r('sys.symbol.paintbrush'))
  7501. .fontColor([Color.White])
  7502. .effectStrategy(1)
  7503. Text(`选择颜色`)
  7504. .fontSize(13)
  7505. .margin({ left: 10 })
  7506. .fontColor(Color.White)
  7507. }
  7508. }
  7509. .backgroundColor(Color.Transparent)
  7510. .border({
  7511. color: '#FFFFFF',
  7512. radius: 20,
  7513. width: 1.8
  7514. })
  7515. .height(36)
  7516. .width(110)
  7517. .onClick(() => {
  7518. this.isShowSelectColor = !this.isShowSelectColor
  7519. })
  7520. .bindPopup(this.isShowSelectColor, {
  7521. builder: this.SelectColor(false, isPip),
  7522. placement: Placement.Top,
  7523. mask: { color: '#33000000' },
  7524. enableArrow: false, //是否显示箭头
  7525. showInSubWindow: false,
  7526. onStateChange: (e) => {
  7527. if (!e.isVisible) {
  7528. this.isShowSelectColor = false
  7529. }
  7530. }
  7531. })
  7532. }
  7533. .width('76%')
  7534. .margin({
  7535. top: 10,
  7536. bottom: 10,
  7537. right: 45,
  7538. left: 20
  7539. })
  7540. Row() {
  7541. Text(`高亮颜色:`)
  7542. .fontSize(14)
  7543. .fontColor(Color.White)
  7544. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7545. .fontSize(15)
  7546. .fontColor(Color.White)
  7547. .margin({ left: 12, right: 12 })
  7548. Column() {
  7549. }
  7550. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7551. .margin({ right: 12 })
  7552. .borderRadius(20)
  7553. .height(28)
  7554. .width(28)
  7555. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7556. Row() {
  7557. SymbolGlyph($r('sys.symbol.paintbrush'))
  7558. .fontColor([Color.White])
  7559. .effectStrategy(1)
  7560. Text(`选择颜色`)
  7561. .fontSize(13)
  7562. .margin({ left: 10 })
  7563. .fontColor(Color.White)
  7564. }
  7565. }
  7566. .backgroundColor(Color.Transparent)
  7567. .border({
  7568. color: '#FFFFFF',
  7569. radius: 20,
  7570. width: 1.8
  7571. })
  7572. .height(36)
  7573. .width(110)
  7574. .onClick(() => {
  7575. this.isShowHLSelectColor = !this.isShowHLSelectColor
  7576. })
  7577. .bindPopup(this.isShowHLSelectColor, {
  7578. builder: this.SelectColor(true, isPip),
  7579. placement: Placement.Top,
  7580. mask: { color: '#33000000' },
  7581. enableArrow: false, //是否显示箭头
  7582. showInSubWindow: false,
  7583. onStateChange: (e) => {
  7584. if (!e.isVisible) {
  7585. this.isShowHLSelectColor = false
  7586. }
  7587. }
  7588. })
  7589. }
  7590. .width('76%')
  7591. .margin({
  7592. top: 10,
  7593. bottom: 10,
  7594. right: 45,
  7595. left: 20
  7596. })
  7597. if (isPip) {
  7598. Row() {
  7599. Text(`显示宽度:`)
  7600. .fontSize(14)
  7601. .fontColor(Color.White)
  7602. Slider({
  7603. value: this.pipLyWidth,
  7604. min: 10,
  7605. max: 800,
  7606. step: 1,
  7607. style: SliderStyle.OutSet
  7608. })
  7609. .blockColor(this.themeColor)
  7610. .trackColor($r('app.color.speed_text_color'))
  7611. .selectedColor(Color.White)
  7612. .trackThickness(6)
  7613. .onChange((value: number) => {
  7614. this.pipLyWidth = value
  7615. if (this.pipController) {
  7616. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7617. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  7618. }
  7619. })
  7620. .width('76%')
  7621. }
  7622. .margin({
  7623. left: 20,
  7624. right: 15,
  7625. top: 5,
  7626. bottom: 5
  7627. })
  7628. Row() {
  7629. Text(`显示高度:`)
  7630. .fontSize(14)
  7631. .fontColor(Color.White)
  7632. Slider({
  7633. value: this.pipLyHeight,
  7634. min: 10,
  7635. max: 1000,
  7636. step: 1,
  7637. style: SliderStyle.OutSet
  7638. })
  7639. .blockColor(this.themeColor)
  7640. .trackColor($r('app.color.speed_text_color'))
  7641. .selectedColor(Color.White)
  7642. .trackThickness(6)
  7643. .onChange((value: number) => {
  7644. this.pipLyHeight = value
  7645. if (this.pipController) {
  7646. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7647. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7648. }
  7649. })
  7650. .width('76%')
  7651. }
  7652. .margin({
  7653. left: 20,
  7654. right: 15,
  7655. top: 5,
  7656. bottom: 5
  7657. })
  7658. }
  7659. Row() {
  7660. Text(`歌词字号:`)
  7661. .fontSize(14)
  7662. .fontColor(Color.White)
  7663. Slider({
  7664. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7665. min: 12,
  7666. max: 30,
  7667. step: 0.1,
  7668. style: SliderStyle.OutSet
  7669. })
  7670. .blockColor(this.themeColor)
  7671. .trackColor($r('app.color.speed_text_color'))
  7672. .selectedColor(Color.White)
  7673. .trackThickness(6)
  7674. .onChange((value: number) => {
  7675. this.setLyricTextSize(value, isPip)
  7676. })
  7677. .width('76%')
  7678. }
  7679. .margin({
  7680. left: 20,
  7681. right: 15,
  7682. top: 5,
  7683. bottom: 5
  7684. })
  7685. Row() {
  7686. Text(`高亮倍数:`)
  7687. .fontSize(14)
  7688. .fontColor(Color.White)
  7689. Slider({
  7690. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7691. min: 1,
  7692. max: 2,
  7693. step: 0.1,
  7694. style: SliderStyle.OutSet
  7695. })
  7696. .blockColor(this.themeColor)
  7697. .trackColor($r('app.color.speed_text_color'))
  7698. .selectedColor(Color.White)
  7699. .trackThickness(6)
  7700. .onChange((value: number) => {
  7701. this.setHighLyricTextSize(value, isPip)
  7702. })
  7703. .width('76%')
  7704. }
  7705. .margin({
  7706. left: 20,
  7707. right: 15,
  7708. top: 5,
  7709. bottom: 5
  7710. })
  7711. Row() {
  7712. Text(`歌词间隙:`)
  7713. .fontSize(14)
  7714. .fontColor(Color.White)
  7715. Slider({
  7716. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7717. min: 0,
  7718. max: 100,
  7719. step: 1,
  7720. style: SliderStyle.OutSet
  7721. })
  7722. .blockColor(this.themeColor)
  7723. .trackColor($r('app.color.speed_text_color'))
  7724. .selectedColor(Color.White)
  7725. .trackThickness(6)
  7726. .onChange((value: number) => {
  7727. this.setLyricLineSpace(value, isPip)
  7728. })
  7729. .width('76%')
  7730. }
  7731. .margin({
  7732. left: 20,
  7733. right: 15,
  7734. top: 5,
  7735. bottom: 5
  7736. })
  7737. //取值间隔为100,默认为400,取值越大,字体越粗
  7738. Row() {
  7739. Text(`歌词字重:`)
  7740. .fontSize(14)
  7741. .fontColor(Color.White)
  7742. Slider({
  7743. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7744. min: 100,
  7745. max: 900,
  7746. step: 100,
  7747. style: SliderStyle.OutSet
  7748. })
  7749. .blockColor(this.themeColor)
  7750. .trackColor($r('app.color.speed_text_color'))
  7751. .selectedColor(Color.White)
  7752. .trackThickness(6)
  7753. .onChange((value: number) => {
  7754. if (isPip) {
  7755. this.lyricTextWeightPip = value
  7756. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7757. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7758. } else {
  7759. this.lyricTextWeight = value
  7760. this.lyricController.setTextWeight(this.lyricTextWeight)
  7761. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7762. }
  7763. })
  7764. .width('76%')
  7765. }
  7766. .margin({
  7767. left: 20,
  7768. right: 15,
  7769. top: 5,
  7770. bottom: 5
  7771. })
  7772. if (!isPip) {
  7773. Row() {
  7774. Text(`歌词模糊:`)
  7775. .fontSize(14)
  7776. .fontColor(Color.White)
  7777. Slider({
  7778. value: isPip ? this.blurDegreePip : this.blurDegree,
  7779. min: 0,
  7780. max: 5,
  7781. step: 0.1,
  7782. style: SliderStyle.OutSet
  7783. })
  7784. .blockColor(this.themeColor)
  7785. .trackColor($r('app.color.speed_text_color'))
  7786. .selectedColor(Color.White)
  7787. .trackThickness(6)
  7788. .onChange((value: number) => {
  7789. this.setBlurDegree(value, isPip)
  7790. })
  7791. .width('76%')
  7792. }
  7793. .margin({
  7794. left: 20,
  7795. right: 15,
  7796. top: 5,
  7797. bottom: 15
  7798. })
  7799. }
  7800. Row() {
  7801. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7802. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7803. }
  7804. .justifyContent(FlexAlign.Center)
  7805. .margin({ top: 3, bottom: 10 })
  7806. }
  7807. }
  7808. private setBlurDegree(index: number, isPip: boolean) {
  7809. if (isPip) {
  7810. this.blurDegreePip = index
  7811. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7812. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7813. } else {
  7814. this.blurDegree = index
  7815. this.lyricController.setBlurDegree(this.blurDegree)
  7816. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7817. }
  7818. }
  7819. private setLyricAlignMode(index: number, isPip: boolean) {
  7820. if (isPip) {
  7821. this.currentLyricAlignModePip = index
  7822. if (this.currentLyricAlignModePip === 1) {
  7823. this.lyricControllerXF.setAlignMode("left")
  7824. } else {
  7825. this.lyricControllerXF.setAlignMode("center")
  7826. }
  7827. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7828. } else {
  7829. this.currentLyricAlignMode = index
  7830. if (this.currentLyricAlignMode === 1) {
  7831. this.lyricController.setAlignMode("left")
  7832. } else {
  7833. this.lyricController.setAlignMode("center")
  7834. }
  7835. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7836. }
  7837. }
  7838. private setLyricTextSize(index: number, isPip: boolean) {
  7839. if (isPip) {
  7840. this.currentLyricSizePip = index
  7841. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7842. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7843. } else {
  7844. this.currentLyricSize = index
  7845. this.lyricController.setTextSize(this.currentLyricSize)
  7846. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7847. }
  7848. }
  7849. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7850. if (isPip) {
  7851. this.currentHightLyricSizePip = scale
  7852. this.lyricControllerXF
  7853. .setHighlightScale(this.currentHightLyricSizePip)
  7854. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7855. } else {
  7856. this.currentHightLyricSize = scale
  7857. this.lyricController
  7858. .setHighlightScale(this.currentHightLyricSize)
  7859. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7860. }
  7861. }
  7862. private setLyricLineSpace(index: number, isPip: boolean) {
  7863. if (isPip) {
  7864. this.currentLyricLineSpacePip = index
  7865. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7866. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7867. } else {
  7868. this.currentLyricLineSpace = index
  7869. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7870. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7871. }
  7872. }
  7873. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7874. LogUtil.info('onecold isBG = ' + isBG)
  7875. if (isBG) { //如果是设置悬浮背景
  7876. this.pipBg = color
  7877. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7878. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7879. return
  7880. }
  7881. if (isPip) {
  7882. this.currentLyricColorPip = color
  7883. this.lyricControllerXF
  7884. .setTextColor(this.currentLyricColorPip)
  7885. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7886. } else {
  7887. this.currentLyricColor = color
  7888. this.lyricController
  7889. .setTextColor(this.currentLyricColor)
  7890. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7891. }
  7892. }
  7893. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7894. if (isPip) {
  7895. this.currentHighLightLyricColorPip = color
  7896. this.lyricControllerXF
  7897. .setHighlightColor(this.currentHighLightLyricColorPip)
  7898. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7899. } else {
  7900. this.currentHighLightLyricColor = color
  7901. this.lyricController
  7902. .setHighlightColor(this.currentHighLightLyricColor)
  7903. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7904. }
  7905. }
  7906. // 构建时间控制器
  7907. @Builder
  7908. BuildTimeControls() {
  7909. Column() {
  7910. // 时间显示
  7911. Text(this.getTimeText())
  7912. .fontSize(18)
  7913. .fontColor(Color.White)
  7914. .margin({ bottom: 10 })
  7915. Row() {
  7916. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  7917. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  7918. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  7919. }
  7920. .justifyContent(FlexAlign.Center)
  7921. }
  7922. .margin({ top: 12, bottom: 8 })
  7923. }
  7924. // 精度按钮组件
  7925. @Builder
  7926. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  7927. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7928. Column() {
  7929. Image(icon)
  7930. .width(28)
  7931. .margin({ bottom: 5 })
  7932. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  7933. Text(label)
  7934. .fontSize(12)
  7935. .fontColor('#FFFFFF')
  7936. }
  7937. }
  7938. .backgroundColor(Color.Transparent)
  7939. .enabled(!this.isButtonDisabled(step))
  7940. .onClick(() => this.handlePrecisionAdjust(step))
  7941. .padding(5)
  7942. .width(66)
  7943. .height(66)
  7944. .margin({ left: 18, right: 18 })
  7945. .border({
  7946. color: '#FFFFFF',
  7947. width: 1.8
  7948. })
  7949. }
  7950. private handlePrecisionAdjust(step: number) {
  7951. if (step === 0) {
  7952. this.timeOffset = 0
  7953. return
  7954. }
  7955. // 精度处理:保留1位小数
  7956. const newOffset = Number((this.timeOffset + step).toFixed(5))
  7957. // 边界保护(±15.0秒)
  7958. if (newOffset < -30.0 || newOffset > 30.0) {
  7959. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  7960. return
  7961. }
  7962. // 状态更新
  7963. this.timeOffset = newOffset
  7964. }
  7965. // 按钮禁用逻辑
  7966. private isButtonDisabled(step: number): boolean {
  7967. const futureOffset = this.timeOffset + step
  7968. return (futureOffset < -30.0) || (futureOffset > 30.0)
  7969. }
  7970. // 时间显示文本升级
  7971. private getTimeText(): string {
  7972. const absValue = Math.abs(this.timeOffset)
  7973. return this.timeOffset === 0
  7974. ? '歌词时间已重置'
  7975. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  7976. }
  7977. // 导入 本地歌词 搜索歌词
  7978. @Builder
  7979. pushLyricButton(icon: Resource, step: number, label: string) {
  7980. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7981. Row() {
  7982. Image(icon)
  7983. .width(14)
  7984. .margin({ left: 13 })
  7985. Text(label)
  7986. .fontSize(12)
  7987. .margin({ left: 6 })
  7988. .fontColor('#FFFFFF')
  7989. }
  7990. }
  7991. .onClick(() => {
  7992. switch (step) {
  7993. case 0:
  7994. this.callFilePickerSelectFileForLyric()
  7995. break;
  7996. case 1:
  7997. //判断有没有设置api
  7998. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  7999. this.isLyricSetting = false
  8000. this.showTipsDialog()
  8001. return
  8002. }
  8003. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8004. ToastUtil.showToast('正在获取')
  8005. this.isLyricSetting = false
  8006. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8007. this.initLyric(lyricPath, true);
  8008. }
  8009. break;
  8010. }
  8011. })
  8012. .padding(5)
  8013. .width(110)
  8014. .backgroundColor(Color.Transparent)
  8015. .height(40)
  8016. .margin({ left: 6, right: 6 })
  8017. .border({
  8018. color: '#FFFFFF',
  8019. radius: 20,
  8020. width: 1.8
  8021. })
  8022. }
  8023. showVipDialog() {
  8024. DialogHelper.showCustomContentDialog({
  8025. dialogId: 'vip',
  8026. title: "友情提示",
  8027. autoCancel: false, //点击遮障层时,不关闭弹窗
  8028. backCancel: true, //点击返回键,不关闭弹窗
  8029. contentBuilder: () => {
  8030. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  8031. },
  8032. buttons: [],
  8033. })
  8034. }
  8035. //去赞助的自定义内容
  8036. @Builder
  8037. customVipBuilder(content: string) {
  8038. Column() {
  8039. Text(content)
  8040. .fontColor(Color.Gray)
  8041. .fontSize(16)
  8042. .alignSelf(ItemAlign.Start)
  8043. .margin({ bottom: 15 })
  8044. .fontSize(16)
  8045. Row() {
  8046. Button('取消')
  8047. .fontColor(Color.White)
  8048. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8049. .height(50)
  8050. .layoutWeight(1)
  8051. .stateEffect(true)
  8052. .margin({ right: 6 })
  8053. .onClick(() => {
  8054. DialogHelper.closeDialog('vip'); //关闭弹框
  8055. })
  8056. Button('开通')
  8057. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8058. .layoutWeight(1)
  8059. .height(50)
  8060. .backgroundColor(this.themeColor)
  8061. .stateEffect(true)
  8062. .margin({ left: 6 })
  8063. .onClick(() => {
  8064. DialogHelper.closeDialog('vip'); //关闭弹框
  8065. this.isShowPlay = false
  8066. this.mType = 1 //跳转到用户中心
  8067. // router.pushUrl({
  8068. // url: 'pages/VipPage'
  8069. // }, router.RouterMode.Single);
  8070. })
  8071. }
  8072. }
  8073. .width("100%")
  8074. .padding(10)
  8075. }
  8076. showTipsDialog() {
  8077. DialogHelper.showCustomContentDialog({
  8078. dialogId: 'tips',
  8079. title: "友情提示",
  8080. autoCancel: false, //点击遮障层时,不关闭弹窗
  8081. backCancel: true, //点击返回键,不关闭弹窗
  8082. contentBuilder: () => {
  8083. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  8084. },
  8085. buttons: [],
  8086. })
  8087. }
  8088. @Builder
  8089. customTipsBuilder(content: string) {
  8090. Column() {
  8091. Text(content)
  8092. .fontColor(Color.Gray)
  8093. .fontSize(16)
  8094. .alignSelf(ItemAlign.Start)
  8095. .margin({ bottom: 15 })
  8096. .fontSize(16)
  8097. Row() {
  8098. Button('取消')
  8099. .fontColor(Color.White)
  8100. .backgroundColor(this.themeColor)
  8101. .height(50)
  8102. .layoutWeight(1)
  8103. .stateEffect(true)
  8104. .margin({ right: 6 })
  8105. .onClick(() => {
  8106. DialogHelper.closeDialog('tips'); //关闭弹框
  8107. })
  8108. Button('跳转')
  8109. .fontColor(Color.White)//
  8110. .layoutWeight(1)
  8111. .height(50)
  8112. .backgroundColor(this.themeColor)
  8113. .stateEffect(true)
  8114. .margin({ left: 6 })
  8115. .onClick(() => {
  8116. DialogHelper.closeDialog('tips'); //关闭弹框
  8117. this.isShowEdit = false
  8118. this.longItemFilePath = ''
  8119. // if(this.isGridMusic&&!this.isShowPlay){
  8120. // this.longItemFilePath== ''
  8121. // }else{
  8122. // this.isShowEdit = false
  8123. // }
  8124. this.isShowMoreView = false;
  8125. this.isShowPlay = false
  8126. this.mType = 4
  8127. // router.pushUrl({
  8128. // url: 'pages/SettingPage'
  8129. // }, router.RouterMode.Single);
  8130. })
  8131. }
  8132. }
  8133. .width("100%")
  8134. .padding(10)
  8135. }
  8136. @Builder
  8137. PlayMoreSheet() {
  8138. Column() {
  8139. this.MoreList()
  8140. }
  8141. .width('100%')
  8142. .height('100%')
  8143. }
  8144. @Builder
  8145. MoreList() {
  8146. Scroll() {
  8147. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  8148. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  8149. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8150. Row() {
  8151. if (more.id === 3&&this.currentSong) {
  8152. Image(more.image)
  8153. .width(24)
  8154. .height(24)
  8155. .margin({ left: 10, right: 10 })
  8156. Text(more.title)
  8157. .fontSize(16)
  8158. .fontColor(Color.White)
  8159. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  8160. height: this.isCoverOpacity() ? '95%' : '95%',
  8161. dragBar: true,
  8162. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8163. showClose: true,
  8164. blurStyle: BlurStyle.Thin,
  8165. backgroundColor: Color.Transparent,
  8166. title: { title: '歌曲信息' }
  8167. })
  8168. } else if (more.id === 15 && this.currentSong) { //编辑标签
  8169. Image(more.image)
  8170. .width(24)
  8171. .height(24)
  8172. .margin({ left: 10, right: 10 })
  8173. Text(more.title)
  8174. .fontSize(16)
  8175. .fontColor(Color.White)
  8176. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  8177. height: '99%',
  8178. dragBar: true,
  8179. showClose: true,
  8180. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8181. // blurStyle:BlurStyle.Thin,
  8182. // backgroundColor:Color.Transparent,
  8183. title: { title: '编辑标签' }
  8184. })
  8185. } else if (more.id === 5) { //定时关闭
  8186. Image(more.image)
  8187. .width(24)
  8188. .height(24)
  8189. .margin({ left: 10, right: 10 })
  8190. Text(more.title)
  8191. .fontSize(16)
  8192. .fontColor(Color.White)
  8193. .onClick(() => {
  8194. this.doMore(more.id)
  8195. })
  8196. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  8197. height: this.isCoverOpacity() ? '95%' : '95%',
  8198. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8199. dragBar: true,
  8200. showClose: true,
  8201. title: { title: $r('app.string.time_close') }
  8202. })
  8203. } else if (more.id === 2) { //歌词设置
  8204. Image(more.image)
  8205. .width(24)
  8206. .height(24)
  8207. .margin({ left: 10, right: 10 })
  8208. Text(more.title)
  8209. .fontSize(16)
  8210. .fontColor(Color.White)
  8211. } else if (more.id === 16) { //悬浮歌词设置
  8212. Image(more.image)
  8213. .width(24)
  8214. .height(24)
  8215. .margin({ left: 10, right: 10 })
  8216. Text(more.title)
  8217. .fontSize(16)
  8218. .fontColor(Color.White)
  8219. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  8220. height: this.isCoverOpacity() ? '95%' : '95%',
  8221. dragBar: true,
  8222. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8223. showClose: true,
  8224. blurStyle: BlurStyle.Thin,
  8225. backgroundColor: Color.Transparent,
  8226. title: { title: '悬浮歌词' }
  8227. })
  8228. } else if (more.id === 11) {
  8229. Image(more.image)
  8230. .width(24)
  8231. .height(24)
  8232. .margin({ left: 10, right: 10 })
  8233. Text(more.title)
  8234. .fontSize(16)
  8235. .fontColor(Color.White)
  8236. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  8237. height: this.isCoverOpacity() ? '95%' : '60%',
  8238. dragBar: true,
  8239. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8240. showClose: true,
  8241. blurStyle: BlurStyle.Thin,
  8242. backgroundColor: Color.Transparent,
  8243. title: { title: '跳过头尾' }
  8244. })
  8245. } else if (more.id === 12) { //投播
  8246. AVCastPicker({
  8247. customPicker: (): void => this.TPImageBuilder(more),
  8248. onStateChange: (state) => {
  8249. if (state == AVCastPickerState.STATE_APPEARING) {
  8250. console.log(' The picker starts showing.');
  8251. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8252. console.log(' The picker finishes presenting.');
  8253. }
  8254. },
  8255. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  8256. sessionType: 'video'
  8257. })
  8258. .id('AVCastPicker')
  8259. } else {
  8260. Image(more.image)
  8261. .width(24)
  8262. .height(24)
  8263. .margin({ left: 10, right: 10 })
  8264. .onClick(() => {
  8265. this.doMore(more.id)
  8266. })
  8267. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  8268. .fontSize(16)
  8269. .fontColor(Color.White)
  8270. .onClick(() => {
  8271. this.doMore(more.id)
  8272. })
  8273. Select([//倍速
  8274. { value: '0.25x' },
  8275. { value: '0.5x' },
  8276. { value: '0.75x' },
  8277. { value: '1x' },
  8278. { value: '1.25x' },
  8279. { value: '1.5x' },
  8280. { value: '1.75x' },
  8281. { value: '2x' },
  8282. { value: '3x' }])
  8283. .font({ size: 16, weight: FontWeight.Medium })
  8284. .fontColor($r('sys.color.white'))
  8285. .margin({ left: 25 })
  8286. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  8287. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  8288. .value(Utility.optimizedFormat(this.playSpeed))
  8289. .onSelect(async (_index: number, text?: string | undefined) => {
  8290. let speed = parseFloat(text?.replace('x', '') || '1');
  8291. if (!CommonConstants.video_speed_list.includes(speed)) {
  8292. speed = 1;
  8293. }
  8294. this.playSpeed = speed
  8295. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8296. })
  8297. Slider({
  8298. value: this.volume,
  8299. min: 0,
  8300. max: 1,
  8301. step: 0.1,
  8302. style: SliderStyle.OutSet
  8303. })
  8304. .margin({ left: 18, right: 8 })
  8305. .blockColor(this.themeColor)
  8306. .trackColor($r('app.color.speed_text_color'))
  8307. .selectedColor(Color.White)
  8308. .trackThickness(9)
  8309. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  8310. .onChange((value: number) => {
  8311. this.volume = value;
  8312. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  8313. PreferencesUtil.putSync('DefalutVolume',this.volume)
  8314. })
  8315. .layoutWeight(1)
  8316. Blank()
  8317. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  8318. .selectedColor(this.themeColor)
  8319. .switchPointColor(Color.White)
  8320. .margin({ right: 15 })
  8321. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8322. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  8323. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8324. if (more.id == 6) {
  8325. this.isMusicMemoryPlay = checked;
  8326. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  8327. if (this.isMusicMemoryPlay) {
  8328. ToastUtil.showToast('记忆播放已开启')
  8329. } else {
  8330. ToastUtil.showToast('记忆播放已关闭')
  8331. }
  8332. }
  8333. })
  8334. .width(48)
  8335. .height(24);
  8336. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  8337. .selectedColor(this.themeColor)
  8338. .switchPointColor(Color.White)
  8339. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8340. .margin({ right: 15 })
  8341. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  8342. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8343. if (more.id == 7) {
  8344. this.isMusicBGCover = checked;
  8345. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  8346. if (this.isMusicBGCover) {
  8347. ToastUtil.showToast('播放背景随音乐封面已开启')
  8348. } else {
  8349. ToastUtil.showToast('播放背景随音乐封面已关闭')
  8350. }
  8351. }
  8352. })
  8353. .width(48)
  8354. .height(24);
  8355. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  8356. .selectedColor(this.themeColor)
  8357. .switchPointColor(Color.White)
  8358. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8359. .margin({ right: 15 })
  8360. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  8361. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8362. if (more.id == 8) {
  8363. this.isSavePlayMode = checked;
  8364. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  8365. if (this.isSavePlayMode) {
  8366. ToastUtil.showToast('保存播放模式已开启')
  8367. } else {
  8368. ToastUtil.showToast('保存播放模式已关闭')
  8369. }
  8370. }
  8371. })
  8372. .width(48)
  8373. .height(24);
  8374. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  8375. .selectedColor(this.themeColor)
  8376. .switchPointColor(Color.White)
  8377. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8378. .margin({ right: 15 })
  8379. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  8380. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8381. if (more.id == 13) {
  8382. this.isCoverRectangle = checked;
  8383. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  8384. if (this.isCoverRectangle) {
  8385. ToastUtil.showToast('封面方形已开启')
  8386. this.animationRoFun()
  8387. } else {
  8388. ToastUtil.showToast('封面圆形已开启')
  8389. this.animationRoFun()
  8390. }
  8391. }
  8392. })
  8393. .width(48)
  8394. .height(24);
  8395. }
  8396. }
  8397. .width('100%')
  8398. .height(45)
  8399. .padding(15)
  8400. .backgroundColor(Color.Transparent)
  8401. .borderRadius(12)
  8402. .margin({ bottom: 6 })
  8403. }
  8404. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  8405. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8406. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  8407. .backgroundColor(Color.Transparent)
  8408. .onClick(() => {
  8409. this.doMore(more.id)
  8410. })
  8411. });
  8412. }
  8413. .width('100%')
  8414. .padding(16)
  8415. }.margin({ bottom: 18 })
  8416. }
  8417. @Builder
  8418. TPImageBuilder(more: MoreItem): void {
  8419. Row() {
  8420. Image($r('app.media.tuoping'))
  8421. .width(22)
  8422. .height(22)
  8423. .margin({ left: 10, right: 10 })
  8424. Text(more.title)
  8425. .fontSize(16)
  8426. .fontColor(Color.White)
  8427. }
  8428. .width('100%')
  8429. .layoutWeight(1)
  8430. .alignItems(VerticalAlign.Center)
  8431. .justifyContent(FlexAlign.Start)
  8432. }
  8433. private moreItems: MoreItem[] = [
  8434. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  8435. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  8436. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  8437. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  8438. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  8439. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  8440. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  8441. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  8442. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  8443. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  8444. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  8445. { id: 4, image: $r('app.media.share2'), title: '分享' },
  8446. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  8447. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  8448. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  8449. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  8450. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  8451. ];
  8452. @State isShowMoreView: boolean = false;
  8453. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  8454. @State isShowTimeCloseMore: boolean = false
  8455. @State isShowDetailMore: boolean = false
  8456. @State isMusicBGCover: boolean = true
  8457. @State isSavePlayMode: boolean = true
  8458. @State isLyricSetting: boolean = false
  8459. @State isJumpSetting: boolean = false
  8460. @State isShowEdit: boolean = false
  8461. @State showPipLyric: boolean = false
  8462. async setRingTone() {
  8463. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  8464. return
  8465. }
  8466. // 确定后的逻辑
  8467. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  8468. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  8469. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  8470. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  8471. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  8472. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  8473. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  8474. , this.videoUrl, this.name).then(res => {
  8475. LogUtil.info('onecold setFlag :' + res);
  8476. });
  8477. }
  8478. doMore(moreId: number) {
  8479. switch (moreId) {
  8480. case 2: //歌词
  8481. this.isLyricSetting = !this.isLyricSetting;
  8482. this.isShowMoreView = false
  8483. break;
  8484. case 3: //详情
  8485. this.isShowDetailMore = !this.isShowDetailMore;
  8486. break;
  8487. case 4: //分享
  8488. if (this.currentSong !== undefined) {
  8489. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  8490. }
  8491. this.isShowMoreView = false
  8492. break;
  8493. case 5: //定时关闭
  8494. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  8495. break;
  8496. case 10: //设为铃声
  8497. this.setRingTone()
  8498. this.isShowMoreView = false
  8499. break;
  8500. case 11: //跳过头尾
  8501. this.isJumpSetting = !this.isJumpSetting;
  8502. break;
  8503. case 13: //倍速
  8504. break;
  8505. case 14: //搜索封面
  8506. if (this.currentSong !== undefined) {
  8507. this.doSearchCover(this.currentSong)
  8508. }
  8509. this.isShowMoreView = false
  8510. break;
  8511. case 15: //编辑标签
  8512. this.setEditStrEmpty()
  8513. this.tempLyricContent = this.lyricContent
  8514. this.isShowEdit = !this.isShowEdit;
  8515. break;
  8516. case 16: //悬浮歌词
  8517. this.showPipLyric = !this.showPipLyric;
  8518. break;
  8519. case 17: //横屏模式
  8520. if (this.isLandscape) {
  8521. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8522. } else {
  8523. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8524. }
  8525. this.isShowMoreView = false
  8526. break;
  8527. }
  8528. }
  8529. /**
  8530. * 切换横竖屏
  8531. *
  8532. */
  8533. setOrientation(orientation: number) {
  8534. this.windowClass.setPreferredOrientation(orientation).then(() => {
  8535. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  8536. }).catch((err: BusinessError) => {
  8537. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  8538. });
  8539. }
  8540. /**
  8541. * 画中画功能(悬浮歌词功能)
  8542. *
  8543. */
  8544. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  8545. pipController?: PiPWindow.PiPController;
  8546. navigationId: string = '';
  8547. @State curState: string = '';
  8548. @State curError: ResourceStr = '';
  8549. @State pipBg: string = '#E8E8E8'
  8550. @State buttonAction: string = '';
  8551. //开启画中画功能
  8552. async startPip() {
  8553. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  8554. if (!this.pipController) {
  8555. await this.createPipController();
  8556. }
  8557. if (!this.pipController) {
  8558. Logger.info(`[${TAG}] pipController create error`);
  8559. return;
  8560. }
  8561. await this.pipController.startPiP();
  8562. }
  8563. async stopPip() {
  8564. if (!this.pipController) {
  8565. Logger.info(`[${TAG}] pipController is not exist`);
  8566. return;
  8567. }
  8568. this.isOpenPip = false
  8569. await this.pipController.stopPiP();
  8570. }
  8571. async createPipController() {
  8572. this.pipController = await PiPWindow.create({
  8573. context: getContext(this),
  8574. componentController: this.xcomponentController,
  8575. navigationId: this.navigationId,
  8576. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  8577. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  8578. customUIController: this.nodeController,
  8579. });
  8580. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  8581. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  8582. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8583. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  8584. this.onStateChange(state, reason);
  8585. });
  8586. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  8587. this.onActionEvent(event, status);
  8588. });
  8589. }
  8590. destroyPipController() {
  8591. if (!this.pipController) {
  8592. return;
  8593. }
  8594. this.pipController.off('stateChange');
  8595. this.pipController.off('controlPanelActionEvent');
  8596. this.pipController = undefined;
  8597. }
  8598. onStateChange(state: PiPWindow.PiPState, reason: string) {
  8599. switch (state) {
  8600. case PiPWindow.PiPState.ABOUT_TO_START:
  8601. this.curState = 'ABOUT_TO_START';
  8602. this.curError = $r('app.string.current_error_hint');
  8603. break;
  8604. case PiPWindow.PiPState.STARTED:
  8605. this.curState = 'STARTED';
  8606. this.curError = $r('app.string.current_error_hint');
  8607. break;
  8608. case PiPWindow.PiPState.ABOUT_TO_STOP:
  8609. this.curState = 'ABOUT_TO_STOP';
  8610. this.curError = $r('app.string.current_error_hint');
  8611. break;
  8612. case PiPWindow.PiPState.STOPPED:
  8613. this.curState = 'STOPPED';
  8614. this.curError = $r('app.string.current_error_hint');
  8615. this.stopPip()
  8616. this.destroyPipController()
  8617. break;
  8618. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  8619. this.curState = 'ABOUT_TO_RESTORE';
  8620. this.curError = $r('app.string.current_error_hint');
  8621. break;
  8622. case PiPWindow.PiPState.ERROR:
  8623. this.curState = 'ERROR';
  8624. this.curError = reason;
  8625. break;
  8626. default:
  8627. break;
  8628. }
  8629. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  8630. }
  8631. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  8632. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  8633. switch (event) {
  8634. case 'playbackStateChanged':
  8635. if (status === 0) {
  8636. this.pause();
  8637. } else {
  8638. this.startPlayOrResumePlay();
  8639. }
  8640. break;
  8641. case 'nextVideo':
  8642. // 切换到下一个视频
  8643. this.playNext()
  8644. break;
  8645. case 'previousVideo':
  8646. // 切换到上一个视频
  8647. this.playPrevious()
  8648. break;
  8649. case 'previousVideo':
  8650. // 切换到上一个视频
  8651. this.playPrevious()
  8652. break;
  8653. default:
  8654. }
  8655. this.buttonAction = event + `-status:${status}`;
  8656. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8657. }
  8658. /**
  8659. * 画中画功能(悬浮歌词功能)结束
  8660. *
  8661. */
  8662. async doSearchCover(item: VideoItem): Promise<string> {
  8663. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8664. this.isShowMoreView = false;
  8665. this.showTipsDialog();
  8666. return ''; // Return empty string when no API is configured
  8667. }
  8668. if (!item) {
  8669. return ''; // Return empty string if item is undefined
  8670. }
  8671. const artist = item?.artist || ''; // Use empty string if artist is missing
  8672. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  8673. }
  8674. /**
  8675. *api搜索封面
  8676. *item,根据title和artist
  8677. */
  8678. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  8679. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8680. LogUtil.debug("onecold res =" + res);
  8681. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8682. if (item.filePath == this.currentSong?.filePath) {
  8683. this.cover = res;
  8684. if (this.currentSong) {
  8685. this.currentSong.pixelMapPath = res;
  8686. }
  8687. }
  8688. // Update pixel map path but always return res regardless of success
  8689. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8690. if (success) {
  8691. this.doUpdateData();
  8692. console.log("onecold 更新音乐封面成功,数据库已同步");
  8693. } else {
  8694. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  8695. }
  8696. // Note: We don't resolve/reject here because we already returned res
  8697. });
  8698. LogUtil.debug("onecold this.cover =" + this.cover);
  8699. }
  8700. return res; // Always return res regardless of updatePixelMapPath result
  8701. });
  8702. }
  8703. @State jumpTopTime: number = 0
  8704. @State jumpEndTime: number = 0
  8705. @State isOpenJump: boolean = false
  8706. @Builder
  8707. JumpTopEndSheet() {
  8708. Scroll() {
  8709. Column() {
  8710. Column() {
  8711. Text('仅对本播放列表有效')
  8712. .fontSize(16)
  8713. .fontColor($r('app.color.text_color'))
  8714. // 跳过头尾
  8715. Column() {
  8716. Row() {
  8717. Text('跳过片头:')
  8718. .fontSize(16)
  8719. .fontColor($r('app.color.text_color'))
  8720. Text(this.jumpTopTime + 's')
  8721. .fontSize(16)
  8722. .fontColor($r('app.color.text_color'))
  8723. }
  8724. .margin({ bottom: 5 })
  8725. Row() {
  8726. Slider({
  8727. value: this.jumpTopTime,
  8728. min: 0,
  8729. max: 120,
  8730. step: 1,
  8731. style: SliderStyle.OutSet
  8732. })
  8733. .blockColor(this.themeColor)
  8734. .trackColor($r('app.color.speed_text_color'))
  8735. .selectedColor(Color.White)
  8736. .trackThickness(8)
  8737. .onChange((value: number) => {
  8738. this.jumpTopTime = value;
  8739. })
  8740. .width('85%')
  8741. }
  8742. .alignItems(VerticalAlign.Top)
  8743. }
  8744. .margin({ top: 10, bottom: 10 })
  8745. // 跳过头尾
  8746. Column() {
  8747. Row() {
  8748. Text('跳过片尾:')
  8749. .fontSize(16)
  8750. .fontColor($r('app.color.text_color'))
  8751. Text(this.jumpEndTime + 's')
  8752. .fontSize(16)
  8753. .fontColor($r('app.color.text_color'))
  8754. }
  8755. .margin({ bottom: 5 })
  8756. Row() {
  8757. Slider({
  8758. value: this.jumpEndTime,
  8759. min: 0,
  8760. max: 120,
  8761. step: 1,
  8762. style: SliderStyle.OutSet
  8763. })
  8764. .blockColor(this.themeColor)
  8765. .trackColor($r('app.color.speed_text_color'))
  8766. .selectedColor(Color.White)
  8767. .trackThickness(8)
  8768. .onChange((value: number) => {
  8769. this.jumpEndTime = value;
  8770. })
  8771. .width('85%')
  8772. }
  8773. .alignItems(VerticalAlign.Top)
  8774. }
  8775. .margin({ top: 10, bottom: 10 })
  8776. Row() {
  8777. Button('保存设置')
  8778. .fontColor(Color.White)
  8779. .layoutWeight(1)
  8780. .height(40)
  8781. .width(80)
  8782. .backgroundColor(this.themeColor)
  8783. .stateEffect(true)
  8784. .margin({ left: 0, bottom: 20 })
  8785. .onClick(async () => {
  8786. if (!Utility.isNoble()) {
  8787. this.isJumpSetting = false
  8788. this.isShowMoreView = false
  8789. this.showVipDialog()
  8790. return
  8791. }
  8792. if (this.currentSong === undefined) {
  8793. return
  8794. }
  8795. if (this.modeType === 0) {
  8796. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8797. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8798. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8799. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8800. } else if (this.modeType === 1) { //媒体库
  8801. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8802. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8803. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8804. } else if (this.modeType === 2) { //艺术家
  8805. if (this.currentSong?.artist) {
  8806. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8807. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8808. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8809. }
  8810. } else if (this.modeType === 3) { //专辑
  8811. if (this.currentSong?.album) {
  8812. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8813. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8814. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8815. }
  8816. }
  8817. ToastUtil.showShort("保存成功")
  8818. this.isJumpSetting = false
  8819. })
  8820. }
  8821. .margin({
  8822. left: 38,
  8823. right: 38,
  8824. top: 10,
  8825. bottom: 10
  8826. })
  8827. .width(120)
  8828. .height(50)
  8829. }
  8830. }
  8831. }
  8832. .width('100%')
  8833. .height('100%')
  8834. }
  8835. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8836. private onStateVastChange(state: AVCastPickerState) {
  8837. if (state == AVCastPickerState.STATE_APPEARING) {
  8838. console.log('The picker starts showing.');
  8839. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8840. console.log('The picker finishes presenting.');
  8841. }
  8842. }
  8843. private showSelectLyric() {
  8844. DialogHelper.showActionSheetDialog({
  8845. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  8846. // sheets: ["本地歌词", "搜索歌词"],
  8847. sheets: [
  8848. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  8849. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  8850. ],
  8851. maskColor: Color.Transparent,
  8852. backgroundColor: $r('app.color.bg_card'),
  8853. transition: AnimationHelper.transitionInDown(666),
  8854. onAction: (index) => {
  8855. switch (index) {
  8856. case 0:
  8857. this.callFilePickerSelectFileForLyric()
  8858. break;
  8859. case 1:
  8860. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8861. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8862. this.initLyric(lyricPath);
  8863. }
  8864. break;
  8865. }
  8866. }
  8867. })
  8868. }
  8869. // 拉起picker选择文件管理器
  8870. async callFilePickerSelectFileForLyric(): Promise<void> {
  8871. try {
  8872. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  8873. DocumentSelectOptions.maxSelectNumber = 1
  8874. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  8875. let documentPicker = new picker.DocumentViewPicker();
  8876. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  8877. Logger.info(TAG,
  8878. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  8879. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  8880. this.saveVideoDatasLyric(DocumentSelectResult)
  8881. }
  8882. }).catch((err: BusinessError) => {
  8883. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  8884. });
  8885. } catch (err) {
  8886. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  8887. }
  8888. }
  8889. async saveVideoDatasLyric(uris: string[]) {
  8890. if (ArrayUtil.isEmpty(uris)) {
  8891. return
  8892. }
  8893. let newUris: string[] = [];
  8894. for (let i = 0; i < uris.length; i++) {
  8895. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  8896. Logger.info(TAG, 'filePath uri: ' + filePath);
  8897. newUris.push(filePath)
  8898. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  8899. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  8900. fileIo.copyFileSync(file.fd, file2.fd)
  8901. fileIo.closeSync(file);
  8902. fileIo.closeSync(file2);
  8903. this.initLyric(filePath)
  8904. }
  8905. }
  8906. private initDelayPlay(context: object) {
  8907. this.mContext = context;
  8908. }
  8909. startPipLyric() {
  8910. if (this.pipController) {
  8911. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  8912. PiPWindow.PiPControlStatus.PLAY);
  8913. }
  8914. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  8915. if (this.isOpenPip) {
  8916. this.startPip()
  8917. } else {
  8918. this.stopPip()
  8919. }
  8920. }
  8921. private startPlayOrResumePlay() {
  8922. this.startPipLyric()
  8923. this.mDestroyPage = false;
  8924. this.animationState = AnimationStatus.Running
  8925. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  8926. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8927. this.stopProgressTask();
  8928. this.startProgressTask();
  8929. this.play(this.videoUrl.toString());
  8930. }
  8931. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  8932. this.mIjkMediaPlayer.start();
  8933. this.setProgress()
  8934. this.CONTROL_PlayStatus = PlayStatus.PLAY
  8935. }
  8936. this.setIsPlaying(true)
  8937. this.updateSessionPlayState(true)
  8938. this.watchStatus();
  8939. this.updateLastPlayTimeStr(this.videoUrl)
  8940. }
  8941. updateLastPlayTimeStr(filePath: string) {
  8942. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  8943. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  8944. if (success) {
  8945. this.getHistoryList(false)
  8946. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  8947. } else {
  8948. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  8949. }
  8950. });
  8951. }
  8952. private completionNum(num: number): string | number {
  8953. if (num < 10) {
  8954. return '0' + num;
  8955. } else {
  8956. return num;
  8957. }
  8958. }
  8959. private stringForTime(timeMs: number): string {
  8960. let totalSeconds: number | string = (timeMs / 1000);
  8961. let newSeconds: number | string = totalSeconds % 60;
  8962. let minutes: number | string = (totalSeconds / 60) % 60;
  8963. let hours: number | string = totalSeconds / 3600;
  8964. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  8965. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  8966. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  8967. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  8968. if (this.isCurrentTime) {
  8969. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  8970. this.oldSeconds = newSeconds
  8971. } else {
  8972. newSeconds = this.oldSeconds
  8973. }
  8974. }
  8975. newSeconds = this.completionNum(newSeconds);
  8976. if (hours > 0) {
  8977. return hours + ":" + minutes + ":" + newSeconds;
  8978. } else {
  8979. return minutes + ":" + newSeconds;
  8980. }
  8981. }
  8982. private setProgress() {
  8983. let position = this.mIjkMediaPlayer.getCurrentPosition();
  8984. let duration = this.mIjkMediaPlayer.getDuration();
  8985. let pos = 0;
  8986. if (duration > 0) {
  8987. this.slideEnable = true;
  8988. let curPercent = position / duration;
  8989. pos = curPercent * 100;
  8990. if (pos > this.PROGRESS_MAX_VALUE) {
  8991. this.progressValue = this.PROGRESS_MAX_VALUE
  8992. } else {
  8993. this.progressValue = pos;
  8994. }
  8995. }
  8996. // LogUtils.getInstance()
  8997. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8998. this.totalTime = this.stringForTime(duration);
  8999. if (position > duration) {
  9000. position = duration;
  9001. }
  9002. this.isCurrentTime = true;
  9003. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  9004. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  9005. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  9006. this.currentTime = this.stringForTime(position);
  9007. this.isCurrentTime = false
  9008. if (this.mIjkMediaPlayer.isPlaying()) {
  9009. this.randomColor =
  9010. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  9011. // 判断是否播放到结束时间
  9012. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  9013. if (position >= duration - this.jumpEndTime * 1000) {
  9014. this.playNext()
  9015. }
  9016. }
  9017. } else {
  9018. this.randomColor = 'rbg(0,0,0)'
  9019. }
  9020. }
  9021. private startProgressTask() {
  9022. let that = this;
  9023. this.updateProgressTimer = setInterval(() => {
  9024. //LogUtils.getInstance().LOGI("startProgressTask");
  9025. if (!that.mDestroyPage) {
  9026. that.setProgress();
  9027. }
  9028. }, 300);
  9029. }
  9030. private stopProgressTask() {
  9031. LogUtils.getInstance().LOGI("stopProgressTask");
  9032. clearInterval(this.updateProgressTimer);
  9033. }
  9034. private showLoadIng() {
  9035. this.loadingVisible = Visibility.Visible;
  9036. this.replayVisible = Visibility.None;
  9037. }
  9038. private hideLoadIng() {
  9039. this.loadingVisible = Visibility.None;
  9040. this.replayVisible = Visibility.None;
  9041. }
  9042. private showRePlay() {
  9043. this.loadingVisible = Visibility.None;
  9044. this.replayVisible = Visibility.Visible;
  9045. }
  9046. private async play(url: string) {
  9047. let that = this;
  9048. that.showLoadIng();
  9049. //设置XComponent回调的context
  9050. if (!!this.mContext) {
  9051. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  9052. }
  9053. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  9054. this.mIjkMediaPlayer.reset();
  9055. }
  9056. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  9057. //设置debug模式
  9058. this.mIjkMediaPlayer.setDebug(false);
  9059. //初始化配置
  9060. this.mIjkMediaPlayer.native_setup();
  9061. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  9062. if(this.volumeSmall){
  9063. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  9064. this.mIjkMediaPlayer.setVolume('1', '1');
  9065. }else{
  9066. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9067. }
  9068. }else{
  9069. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9070. }
  9071. //设置视频源
  9072. this.mIjkMediaPlayer.setDataSource(url);
  9073. //设置视频源http请求头
  9074. let headers = new Map([
  9075. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  9076. ["referer", "https://www.bilibili.com"]
  9077. ]);
  9078. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  9079. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  9080. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  9081. // }
  9082. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  9083. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  9084. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  9085. const fileSize = await this.getFileSize(this.videoUrl);
  9086. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  9087. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  9088. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  9089. }
  9090. // 使用软件解码(通常比硬件解码更节省内存)
  9091. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  9092. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  9093. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  9094. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  9095. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  9096. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  9097. //停止预读的最小帧数
  9098. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  9099. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  9100. // 设置其他缓冲相关选项
  9101. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  9102. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  9103. //启动预加载
  9104. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  9105. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  9106. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  9107. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  9108. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  9109. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  9110. // 因此需要播放器丢包,才不会累积延时
  9111. // 这个和第三个参数packet-buffering无关。
  9112. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  9113. // 无限制收流
  9114. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  9115. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  9116. // 屏幕常亮
  9117. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  9118. // 设置超时
  9119. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  9120. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  9121. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  9122. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  9123. // 变速播放
  9124. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  9125. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9126. let Speed = this.mIjkMediaPlayer.getSpeed()
  9127. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  9128. //是否开启循环播放
  9129. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  9130. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  9131. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  9132. if (height === 0) {
  9133. return;
  9134. }
  9135. const va = width / height;
  9136. const vpa = that.videoParentAspectRatio;
  9137. if (vpa > va) {
  9138. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  9139. } else {
  9140. that.videoWidth = '100%';
  9141. }
  9142. if (width && height) {
  9143. that.videoAspectRatio = width / height;
  9144. }
  9145. LogUtils.getInstance()
  9146. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  9147. that.hideLoadIng();
  9148. }
  9149. }
  9150. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  9151. let mOnPreparedListener: OnPreparedListener = {
  9152. onPrepared: async () => {
  9153. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  9154. try {
  9155. // this.cover = this.songList[this.curIndex].pixelMapPath
  9156. // this.artist = this.songList[this.curIndex].artist
  9157. // this.videoUrl = this.songList[this.curIndex].filePath
  9158. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  9159. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  9160. this.setImageColor2(this.cover)
  9161. } else {
  9162. this.getImageColor();
  9163. }
  9164. //保存碰一碰分享的当前的歌曲
  9165. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  9166. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9167. await this.initLyric(lyricPath);
  9168. setTimeout(() => {
  9169. this.avSessionController.initAvSession(false);
  9170. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  9171. this.setAvSessionListener();
  9172. this.updateSessionPlayState(true)
  9173. this.setCurrentPlayMode()
  9174. }, 500)
  9175. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  9176. let timeoutPlay = 0
  9177. if (StrUtil.isNotEmpty(this.videoUrl) &&
  9178. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  9179. timeoutPlay = 1000
  9180. }
  9181. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  9182. if (this.modeType === 0) { //文件夹
  9183. let parentPath = FileUtil.getParentPath(this.videoUrl)
  9184. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  9185. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  9186. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  9187. } else if (this.modeType === 1) { //媒体库
  9188. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  9189. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  9190. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  9191. } else if (this.modeType === 2) { //艺术家
  9192. if (this.currentSong?.artist) {
  9193. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  9194. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  9195. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  9196. }
  9197. } else if (this.modeType === 3) { //专辑
  9198. if (this.currentSong?.album) {
  9199. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  9200. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  9201. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  9202. }
  9203. }
  9204. this.duration = this.mIjkMediaPlayer.getDuration()
  9205. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  9206. if (this.mIjkMediaPlayer != null) {
  9207. if (this.jumpTopTime * 1000 <= this.duration) {
  9208. // 调用 seekTo 方法,跳到指定时间
  9209. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  9210. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  9211. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  9212. }
  9213. }, timeoutPlay)
  9214. } else {
  9215. // 提示用户无法跳过
  9216. ToastUtil.showToast('跳过时间超过视频时长');
  9217. }
  9218. }
  9219. } else {
  9220. this.jumpTopTime = 0
  9221. this.jumpEndTime = 0
  9222. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  9223. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  9224. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  9225. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  9226. //记忆播放(每一首都会记忆播放)
  9227. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  9228. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  9229. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  9230. this.restorePlaybackPosition() //读取播放记忆功能
  9231. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  9232. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  9233. this.restorePlaybackPosition() //读取播放记忆功能
  9234. }
  9235. this.isFirstStartPlay = false
  9236. }, timeoutPlay)
  9237. } else {
  9238. this.isFirstStartPlay = false
  9239. }
  9240. }
  9241. this.saveLastPlayList()
  9242. } catch (error) {
  9243. let err: BusinessError = error as BusinessError;
  9244. console.error('onecold failed with err: ' + JSON.stringify(err));
  9245. }
  9246. }
  9247. }
  9248. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  9249. let mOnTimedTextListener: OnTimedTextListener = {
  9250. onTimedText: () => {
  9251. }
  9252. }
  9253. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  9254. let mOnCompletionListener: OnCompletionListener = {
  9255. onCompletion: () => {
  9256. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  9257. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  9258. this.playNext()
  9259. } else if (this.playType == 1) { //1:单片重复播放
  9260. this.CONTROL_PlayStatus = PlayStatus.INIT
  9261. that.startPlayOrResumePlay();
  9262. } else if (this.playType == 2) { //2:正常播放,单曲播完
  9263. that.showRePlay();
  9264. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  9265. that.progressValue = this.PROGRESS_MAX_VALUE;
  9266. that.slideEnable = false;
  9267. that.stop();
  9268. // ToastUtil.showToast('开始重新播放')
  9269. } else if (this.playType == 3) { //3:随机播放
  9270. this.randomPlay()
  9271. }
  9272. }
  9273. }
  9274. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  9275. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  9276. onBufferingUpdate: (percent: number) => {
  9277. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  9278. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  9279. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  9280. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  9281. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  9282. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  9283. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  9284. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  9285. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  9286. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  9287. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  9288. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  9289. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  9290. let Looping = this.mIjkMediaPlayer.isLooping()
  9291. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  9292. }
  9293. }
  9294. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  9295. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  9296. onSeekComplete: () => {
  9297. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  9298. that.startPlayOrResumePlay();
  9299. }
  9300. }
  9301. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  9302. let mOnInfoListener: OnInfoListener = {
  9303. onInfo: (what: number, extra: number) => {
  9304. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  9305. that.hideLoadIng();
  9306. }
  9307. }
  9308. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  9309. let mOnErrorListener: OnErrorListener = {
  9310. onError: (what: number, extra: number) => {
  9311. this.stopProgressTask();
  9312. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  9313. that.hideLoadIng();
  9314. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  9315. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  9316. } else {
  9317. ToastUtil.showToast(getContext()
  9318. .resourceManager
  9319. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  9320. }
  9321. }
  9322. }
  9323. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  9324. this.mIjkMediaPlayer.setMessageListener();
  9325. this.mIjkMediaPlayer.prepareAsync();
  9326. this.mIjkMediaPlayer.start();
  9327. }
  9328. //保存最后播放的那首歌和已经对应的播放列表
  9329. saveLastPlayList() {
  9330. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  9331. PreferencesUtil.putSync('LastMusicList', this.songList)
  9332. }
  9333. // 清空播放记录
  9334. clearVideoHistory() {
  9335. this.table.clearPlayHistory((success: boolean, error?: string) => {
  9336. if (success) {
  9337. this.historyList = [];
  9338. this.updateListData(this.historyList)
  9339. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  9340. ToastUtil.showToast('清空播放记录成功')
  9341. } else {
  9342. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  9343. }
  9344. });
  9345. }
  9346. public async setAvSessionListener() {
  9347. if (!this.avSessionController) {
  9348. return;
  9349. }
  9350. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  9351. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  9352. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  9353. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  9354. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  9355. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  9356. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  9357. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  9358. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  9359. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  9360. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  9361. }
  9362. setLoopMode() {
  9363. let itype = this.playType + 1
  9364. if (itype >= 4) {
  9365. this.playType = 0
  9366. ToastUtil.showToast('连续播放')
  9367. } else if (itype === 1) {
  9368. this.playType = 1
  9369. ToastUtil.showToast('单曲循环')
  9370. } else if (itype === 2) {
  9371. this.playType = 2
  9372. ToastUtil.showToast('单曲播完')
  9373. } else if (itype === 3) {
  9374. this.playType = 3
  9375. ToastUtil.showToast('随机播放')
  9376. } else if (itype === 0) {
  9377. this.playType = 0
  9378. ToastUtil.showToast('连续播放')
  9379. }
  9380. PreferencesUtil.putSync('musicPlayType', this.playType)
  9381. this.setCurrentPlayMode()
  9382. }
  9383. private sessionSetLoopModeCallback = (mode: number) => {
  9384. if (this.mIjkMediaPlayer != null) {
  9385. ToastUtil.showToast('当前播放模式:' + mode)
  9386. Logger.info('onecold 当前播放模式= ' + mode)
  9387. let hmPlayMode = mode + 1
  9388. if (hmPlayMode >= 4) {
  9389. hmPlayMode = 0
  9390. }
  9391. if (hmPlayMode === 1) {
  9392. this.playType = 1
  9393. ToastUtil.showToast('单曲循环')
  9394. } else if (hmPlayMode === 0) {
  9395. this.playType = 2
  9396. ToastUtil.showToast('单曲播完')
  9397. } else if (hmPlayMode === 3) {
  9398. this.playType = 3
  9399. ToastUtil.showToast('随机播放')
  9400. } else if (hmPlayMode === 2) {
  9401. this.playType = 0
  9402. ToastUtil.showToast('连续播放')
  9403. }
  9404. PreferencesUtil.putSync('musicPlayType', this.playType)
  9405. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  9406. let playBackState: avSession.AVPlaybackState = {
  9407. loopMode: hmPlayMode,
  9408. };
  9409. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  9410. console.info(`set setLoopMode AVPlaybackState successfully`);
  9411. }).catch((err: BusinessError) => {
  9412. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9413. });
  9414. }
  9415. }
  9416. setCurrentPlayMode() {
  9417. if (!this.avSessionController) {
  9418. return;
  9419. }
  9420. let mLoopMode = 0
  9421. switch (this.playType) {
  9422. case 0:
  9423. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  9424. break;
  9425. case 1:
  9426. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  9427. break;
  9428. case 2:
  9429. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  9430. break;
  9431. case 3:
  9432. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  9433. break;
  9434. }
  9435. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  9436. let playBState: avSession.AVPlaybackState = {
  9437. loopMode: mLoopMode,
  9438. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  9439. };
  9440. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  9441. console.info(`set setLoopMode AVPlaybackState successfully`);
  9442. }).catch((err: BusinessError) => {
  9443. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9444. });
  9445. }
  9446. private sessionToggleFavoriteCallback = (assetId: string) => {
  9447. if (this.mIjkMediaPlayer != null && this.currentSong) {
  9448. console.info(`on toggleFavorite `);
  9449. // 应用收到收藏命令,进行收藏处理。
  9450. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  9451. this.doFav(this.currentSong)
  9452. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  9453. let playbackState: avSession.AVPlaybackState = {
  9454. isFavorite: !this.isFac,
  9455. };
  9456. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  9457. console.info(`SetAVPlaybackState successfully`);
  9458. }).catch((err: BusinessError) => {
  9459. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  9460. });
  9461. }
  9462. }
  9463. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  9464. device: avSession.OutputDeviceInfo) => {
  9465. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  9466. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9467. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  9468. await this.startCasting();
  9469. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9470. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  9471. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  9472. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  9473. if (device) {
  9474. this.endCasting();
  9475. }
  9476. }
  9477. };
  9478. private async startCasting() {
  9479. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9480. this.setPlaybackStateChangeListener();
  9481. this.pause();
  9482. this.initQueueItem();
  9483. this.prepare();
  9484. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9485. refToIsCasting?.set(true);
  9486. this.castSeek = true;
  9487. this.isCastPlaying = true;
  9488. }
  9489. async changeCasting() {
  9490. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9491. this.initQueueItem();
  9492. this.prepare();
  9493. this.setPlaybackStateChangeListener();
  9494. this.isCastPlaying = true;
  9495. this.castSeek = true;
  9496. }
  9497. public endCasting() {
  9498. this.avSessionController.getAvSession()?.stopCasting();
  9499. this.stopCast();
  9500. this.isCastPlaying = false;
  9501. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9502. refToIsCasting?.set(false);
  9503. this.pause();
  9504. this.setIsPlaying(false);
  9505. // if (this.curIndex === this.curSource.index) {
  9506. // this.play
  9507. // this.seek(this.currentTime * 1000);
  9508. // this.setIsPlaying(true);
  9509. // } else {
  9510. // this.pauseVideo();
  9511. // this.setIsPlaying(false);
  9512. // }
  9513. }
  9514. public setIsPlaying(isPlayer: boolean) {
  9515. this.isPlaying = isPlayer;
  9516. }
  9517. private setPlaybackStateChangeListener(): void {
  9518. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  9519. this.castController?.on('endOfStream', this.reloadCasting);
  9520. this.castController?.on('playNext', this.playNextCallback);
  9521. this.castController?.on('playPrevious', this.playPreviousCallback);
  9522. }
  9523. private updateSessionPlayState(isPlay: boolean): void {
  9524. // if(!this.isBgPlayOpen)
  9525. // return
  9526. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  9527. this.setAVSessionPlayState({
  9528. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  9529. position: {
  9530. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  9531. updateTime: new Date().getTime()
  9532. }
  9533. });
  9534. }
  9535. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  9536. this.avSessionController.setAvSessionPlayState(playbackState)
  9537. }
  9538. private positionChange(position: number) {
  9539. this.currentTime2 = position / 1000;
  9540. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  9541. }
  9542. private playDurationChange(duration: number) {
  9543. this.duration = duration;
  9544. this.durationTime = Math.floor(this.duration / 1000);
  9545. this.durationStringTime = secondToTime((this.durationTime));
  9546. }
  9547. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  9548. const duration = playbackState?.extras?.duration;
  9549. if (typeof duration === 'number') {
  9550. this.playDurationChange(duration as number);
  9551. }
  9552. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  9553. this.positionChange(playbackState?.position?.elapsedTime);
  9554. }
  9555. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  9556. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  9557. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  9558. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  9559. this.isCastPlaying = false;
  9560. }
  9561. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  9562. this.isCastPlaying = true;
  9563. }
  9564. };
  9565. private reloadCasting = async () => {
  9566. let item = this.songList[this.curIndex];
  9567. let uri = fileUri.getUriFromPath(item.filePath);
  9568. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  9569. // description.startPosition = 0;
  9570. this.castItem = {
  9571. itemId: this.curIndex,
  9572. description: {
  9573. assetId: item.filePath,
  9574. title: item.name,
  9575. artist: '',
  9576. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  9577. // mediaUri: item.filePath,
  9578. fdSrc: {
  9579. fd: file.fd
  9580. },
  9581. // 该字段大写,音频'AUDIO',视频'VIDEO'
  9582. mediaType: 'VIDEO',
  9583. mediaSize: item.videoSize,
  9584. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  9585. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  9586. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  9587. duration: this.duration,
  9588. // albumCoverUri: 'https://www.example.jpeg',
  9589. // albumTitle: '《ExampleAlbum》',
  9590. appName: this.appName,
  9591. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  9592. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9593. }
  9594. };
  9595. this.prepare();
  9596. this.isCastPlaying = true;
  9597. };
  9598. public playNextCallback = (): void => {
  9599. this.playNext()
  9600. };
  9601. public playPreviousCallback = (): void => {
  9602. this.playPrevious()
  9603. };
  9604. async prepare() {
  9605. await this.castController?.prepare(this.castItem);
  9606. await this.castController?.start(this.castItem);
  9607. }
  9608. public initQueueItem() {
  9609. let item = this.songList[this.curIndex];
  9610. let time = this.currentTime;
  9611. let uri = fileUri.getUriFromPath(item.filePath);
  9612. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  9613. this.castItem = {
  9614. itemId: this.curIndex,
  9615. description: {
  9616. assetId: item.filePath,
  9617. title: item.name,
  9618. artist: '',
  9619. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  9620. fdSrc: {
  9621. fd: file.fd
  9622. },
  9623. // 该字段大写,音频'AUDIO',视频'VIDEO'
  9624. mediaType: 'AUDIO',
  9625. mediaSize: item.videoSize,
  9626. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  9627. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  9628. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  9629. duration: this.duration,
  9630. // albumCoverUri: 'https://www.example.jpeg',
  9631. // albumTitle: '《ExampleAlbum》',
  9632. appName: this.appName,
  9633. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  9634. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9635. }
  9636. };
  9637. }
  9638. async stopCast() {
  9639. try {
  9640. this.castController?.off('playbackStateChange');
  9641. this.castController?.off('endOfStream');
  9642. this.castController?.off('playNext');
  9643. this.castController?.off('playPrevious');
  9644. this.castController?.off('error');
  9645. } catch (error) {
  9646. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  9647. }
  9648. }
  9649. private sessionPlayCallback = (): void => {
  9650. this.playOrPause()
  9651. };
  9652. private sessionPauseCallback = (): void => {
  9653. this.playOrPause()
  9654. };
  9655. private playOrPause() {
  9656. if (!this.debounce()) {
  9657. return;
  9658. }
  9659. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9660. this.pause();
  9661. } else {
  9662. this.startPlayOrResumePlay();
  9663. this.playChange()
  9664. }
  9665. }
  9666. private sessionPlayNextCallback = (): void => {
  9667. this.playNext()
  9668. };
  9669. private sessionPlayPreviousCallback = (): void => {
  9670. this.playPrevious()
  9671. };
  9672. private sessionStopCallback = (): void => {
  9673. this.stop()
  9674. };
  9675. private sessionFastForwardCallback = (time?: number) => {
  9676. if (!time) {
  9677. return;
  9678. }
  9679. if (this.mIjkMediaPlayer != null) {
  9680. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9681. let seeTime = curPosition + time * 1000;
  9682. // 限制 seekValue 在合法范围内
  9683. if (seeTime < 0) {
  9684. seeTime = 0;
  9685. } else if (seeTime > this.duration) {
  9686. seeTime = this.duration;
  9687. }
  9688. Logger.info('onecold seeTime= ' + seeTime)
  9689. this.setSeekToActionProgress(seeTime)
  9690. this.seekTo(seeTime + "")
  9691. }
  9692. };
  9693. /**
  9694. * Gesture method onActionUpdate.
  9695. *
  9696. * @param event Gesture event.手势拖动设置快进和后退
  9697. */
  9698. private setSeekToActionProgress(position: number) {
  9699. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  9700. let duration = this.mIjkMediaPlayer.getDuration();
  9701. let pos = 0;
  9702. if (duration > 0) {
  9703. this.slideEnable = true;
  9704. let curPercent = position / duration;
  9705. pos = curPercent * 100;
  9706. if (pos > this.PROGRESS_MAX_VALUE) {
  9707. this.progressValue = this.PROGRESS_MAX_VALUE
  9708. } else {
  9709. this.progressValue = pos;
  9710. }
  9711. }
  9712. // LogUtils.getInstance()
  9713. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9714. this.totalTime = this.stringForTime(duration);
  9715. if (position > duration) {
  9716. position = duration;
  9717. }
  9718. this.isCurrentTime = true;
  9719. this.currentTime = this.stringForTime(position);
  9720. this.isCurrentTime = false
  9721. }
  9722. private sessionRewindCallback = (time?: number) => {
  9723. if (!time) {
  9724. return;
  9725. }
  9726. if (this.mIjkMediaPlayer != null) {
  9727. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9728. let seeTime = curPosition - time * 1000;
  9729. // 限制 seekValue 在合法范围内
  9730. if (seeTime < 0) {
  9731. seeTime = 0;
  9732. } else if (seeTime > this.duration) {
  9733. seeTime = this.duration;
  9734. }
  9735. Logger.info('onecold seeTime= ' + seeTime)
  9736. this.setSeekToActionProgress(seeTime)
  9737. this.seekTo(seeTime + "")
  9738. }
  9739. };
  9740. private sessionSeekCallback = (seekTime: number) => {
  9741. if (this.mIjkMediaPlayer != null) {
  9742. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9743. this.seekTo(seekTime + "")
  9744. }
  9745. };
  9746. private async getFileSize(filePath: string): Promise<number> {
  9747. try {
  9748. const stat = await fs.stat(filePath);
  9749. return stat.size;
  9750. } catch (err) {
  9751. console.error('Failed to get file size: ' + err.message);
  9752. return 0;
  9753. }
  9754. }
  9755. private pause() {
  9756. if (this.mIjkMediaPlayer.isPlaying()) {
  9757. this.savePlaybackPosition();
  9758. this.mIjkMediaPlayer.pause();
  9759. this.setProgress();
  9760. this.mDestroyPage = true;
  9761. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9762. this.updateSessionPlayState(false)
  9763. this.playChange()
  9764. if (this.pipController) {
  9765. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9766. PiPWindow.PiPControlStatus.PAUSE);
  9767. }
  9768. }
  9769. }
  9770. private stop() {
  9771. this.savePlaybackPosition();
  9772. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9773. this.mIjkMediaPlayer.stop();
  9774. this.mIjkMediaPlayer.release();
  9775. this.stopProgressTask();
  9776. this.updateSessionPlayState(false)
  9777. this.playChange()
  9778. this.watchStatus();
  9779. }
  9780. //保持记忆播放功能
  9781. private savePlaybackPosition() {
  9782. if (this.mIjkMediaPlayer != null) {
  9783. const position = this.mIjkMediaPlayer.getCurrentPosition();
  9784. // ToastUtil.showToast('保存记忆播放 = ' + position)
  9785. const duration = this.mIjkMediaPlayer.getDuration();
  9786. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  9787. // 如果播放位置接近视频末尾,则保存 position 为 0
  9788. const playbackPosition = (duration - position < threshold) ? 0 : position;
  9789. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  9790. }
  9791. }
  9792. //获取记忆播放功能
  9793. private restorePlaybackPosition() {
  9794. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  9795. // ToastUtil.showToast('position = ' + position)
  9796. if (this.mIjkMediaPlayer != null && position > 0) {
  9797. // ToastUtil.showToast('seekTo = ' + position)
  9798. this.seekTo(position + "");
  9799. }
  9800. }
  9801. private seekTo(value: string) {
  9802. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  9803. ToastUtil.showToast('wma格式不支持拖动快进。')
  9804. return
  9805. }
  9806. this.mIjkMediaPlayer.seekTo(value);
  9807. // this.startPlayOrResumePlay()
  9808. // 在这里恢复计时器状态
  9809. this.setProgress()
  9810. // this.startProgressTask();
  9811. }
  9812. // 添加到下一首播放
  9813. private addToNextPlay(song: VideoItem) {
  9814. if (!this.debounce()) {
  9815. return;
  9816. }
  9817. if (this.currentSong) {
  9818. if (this.currentSong === song) {
  9819. ToastUtil.showToast('当前已经在播放这首歌了!')
  9820. return
  9821. }
  9822. }
  9823. // 如果未开始播放或队列为空
  9824. if (this.curIndex === -1 || this.songList.length === 0) {
  9825. this.songList = [song];
  9826. this.curIndex = 0;
  9827. this.doPlay(song)
  9828. return;
  9829. }
  9830. // 插入到当前索引+1的位置
  9831. const insertPos = this.curIndex + 1;
  9832. this.songList.splice(insertPos, 0, song);
  9833. this.songList = [...this.songList]; // 触发状态更新
  9834. this.sonDataSource.pushArrayData(this.songList)
  9835. ToastUtil.showToast('已添加至下一首播放')
  9836. }
  9837. //下一个
  9838. private playNext() {
  9839. if (!this.debounce()) {
  9840. return;
  9841. }
  9842. if (this.playType == 3) { //3:随机播放
  9843. this.randomPlay()
  9844. return;
  9845. }
  9846. if (ArrayUtil.isNotEmpty(this.songList)) {
  9847. if (this.curIndex == this.songList.length - 1) {
  9848. this.curIndex = 0;
  9849. } else {
  9850. this.curIndex++;
  9851. }
  9852. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9853. this.stop();
  9854. this.currentSong = this.songList[this.curIndex]
  9855. this.videoUrl = this.songList[this.curIndex].filePath;
  9856. this.artist = this.songList[this.curIndex].artist
  9857. this.name = this.songList[this.curIndex].name
  9858. //this.cover = this.songList[this.curIndex].pixelMapPath
  9859. this.changeImageAnimation()
  9860. }
  9861. }
  9862. changeImageAnimation() {
  9863. if(this.openSkipSongAnimate){
  9864. // 第一步:淡出动画
  9865. this.getUIContext()?.animateTo({
  9866. duration: 500,
  9867. curve: Curve.EaseOut,
  9868. }, () => {
  9869. this.opacityValueImage = 0.1;
  9870. if(this.isCoverRectangle){
  9871. this.scaleValueImage = 0.88
  9872. }
  9873. });
  9874. // 第二步:切换图片后淡入
  9875. setTimeout(() => {
  9876. this.cover = this.songList[this.curIndex].pixelMapPath
  9877. this.getUIContext()?.animateTo({
  9878. duration: 500,
  9879. curve: Curve.EaseIn,
  9880. }, () => {
  9881. this.opacityValueImage = 1;
  9882. this.scaleValueImage = 1 // 图标恢复到原始大小
  9883. this.startPlayOrResumePlay()
  9884. });
  9885. }, 500);
  9886. }else{
  9887. this.cover = this.songList[this.curIndex].pixelMapPath
  9888. this.startPlayOrResumePlay()
  9889. }
  9890. }
  9891. // 存储已播放的歌曲索引
  9892. private playedIndices: Set<number> = new Set();
  9893. //随机播放
  9894. private randomPlay() {
  9895. // if (!this.debounce()) {
  9896. // return;
  9897. // }
  9898. if (ArrayUtil.isNotEmpty(this.songList)) {
  9899. if (this.songList.length > 3) {
  9900. // 如果所有歌曲都播放过一次,清空已播放索引集合
  9901. if (this.playedIndices.size === this.songList.length) {
  9902. this.playedIndices.clear();
  9903. }
  9904. // 随机选择一个未播放的歌曲索引
  9905. let newIndex: number;
  9906. // 添加超时机制防止无限循环
  9907. let attempt = 0;
  9908. const maxAttempts = 100; // 根据需求调整
  9909. do {
  9910. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  9911. attempt++;
  9912. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  9913. if (attempt >= maxAttempts) {
  9914. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  9915. newIndex = Math.floor(Math.random() * this.songList.length);
  9916. }
  9917. this.curIndex = newIndex;
  9918. this.playedIndices.add(newIndex);
  9919. } else {
  9920. // 当歌曲数量小于或等于3时,直接播放下一首
  9921. if (this.curIndex == this.songList.length - 1) {
  9922. this.curIndex = 0;
  9923. } else {
  9924. this.curIndex++;
  9925. }
  9926. }
  9927. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9928. this.stop();
  9929. this.currentSong = this.songList[this.curIndex];
  9930. this.videoUrl = this.songList[this.curIndex].filePath;
  9931. this.name = this.songList[this.curIndex].name;
  9932. this.artist = this.songList[this.curIndex].artist
  9933. // this.cover = this.songList[this.curIndex].pixelMapPath
  9934. this.changeImageAnimation()
  9935. }
  9936. }
  9937. private playIndex(index: number) {
  9938. if (!this.debounce()) {
  9939. return;
  9940. }
  9941. if (ArrayUtil.isNotEmpty(this.songList)) {
  9942. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9943. this.stop();
  9944. this.currentSong = this.songList[this.curIndex]
  9945. this.videoUrl = this.songList[index].filePath;
  9946. this.name = this.songList[index].name
  9947. this.artist = this.songList[this.curIndex].artist
  9948. this.curIndex = index;
  9949. this.changeImageAnimation()
  9950. }
  9951. }
  9952. //上一个
  9953. private playPrevious() {
  9954. if (!this.debounce()) {
  9955. return;
  9956. }
  9957. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  9958. this.randomModePlayFromHistory()
  9959. return;
  9960. }
  9961. if (this.curIndex == 0) {
  9962. this.curIndex = this.songList.length - 1;
  9963. } else {
  9964. this.curIndex--;
  9965. }
  9966. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9967. this.stop();
  9968. this.currentSong = this.songList[this.curIndex]
  9969. this.videoUrl = this.songList[this.curIndex].filePath;
  9970. this.name = this.songList[this.curIndex].name
  9971. this.artist = this.songList[this.curIndex].artist
  9972. this.changeImageAnimation()
  9973. }
  9974. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  9975. private randomModePlayFromHistory() {
  9976. if (this.historyList.length >= 2) {
  9977. // 播放历史记录的第二首
  9978. const prevSong = this.historyList[1];
  9979. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  9980. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9981. this.stop();
  9982. this.currentSong = prevSong;
  9983. this.videoUrl = prevSong.filePath;
  9984. this.cover = prevSong.pixelMapPath
  9985. this.artist = prevSong.artist
  9986. this.name = prevSong.name;
  9987. this.startPlayOrResumePlay();
  9988. } else {
  9989. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  9990. if (this.curIndex === 0) {
  9991. this.curIndex = this.songList.length - 1;
  9992. } else {
  9993. this.curIndex--;
  9994. }
  9995. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9996. this.stop();
  9997. this.currentSong = this.songList[this.curIndex];
  9998. this.videoUrl = this.songList[this.curIndex].filePath;
  9999. this.artist = this.songList[this.curIndex].artist
  10000. this.name = this.songList[this.curIndex].name;
  10001. this.changeImageAnimation()
  10002. }
  10003. }
  10004. debounce() {
  10005. const delay = 600;
  10006. let cur = new Date().getTime();
  10007. if (cur - this.last > delay) {
  10008. this.last = cur;
  10009. return true;
  10010. }
  10011. return false;
  10012. }
  10013. /**
  10014. * Sets whether the screen is a constant based on the playback status.
  10015. */
  10016. watchStatus() {
  10017. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  10018. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10019. this.windowClass.setWindowKeepScreenOn(true);
  10020. } else {
  10021. this.windowClass.setWindowKeepScreenOn(false);
  10022. }
  10023. }
  10024. /**
  10025. * Volume gesture method onActionStart.
  10026. *
  10027. * @param event Gesture event.
  10028. */
  10029. private customDialogComponentIdMM: number = 0
  10030. @Builder
  10031. customDialogComponentMM() {
  10032. Column() {
  10033. Row() {
  10034. Blank()
  10035. Text('验证密码')
  10036. .fontSize(22)
  10037. .fontColor($r('app.color.pri_bg'))
  10038. .margin({ top: 18 })
  10039. Blank()
  10040. Image($r('app.media.close'))
  10041. .fillColor(Color.White)
  10042. .margin({ top: 18, right: 18 })
  10043. .width(20)
  10044. .onClick(() => {
  10045. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10046. })
  10047. }
  10048. .width('100%') // 使Row占据整个宽度
  10049. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  10050. Verify({
  10051. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  10052. });
  10053. }.height('60%')
  10054. .backgroundColor($r('app.color.index_background'))
  10055. .justifyContent(FlexAlign.SpaceBetween)
  10056. }
  10057. private handleVerifyCompleted(isSuccess: boolean) {
  10058. if (isSuccess) {
  10059. console.log('验证成功');
  10060. // 在这里处理验证成功后的逻辑
  10061. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10062. this.currentPath = this.lockPath
  10063. this.getSortedFiles(this.currentPath)
  10064. } else {
  10065. // console.log('验证失败');
  10066. ToastUtil.showToast('验证失败')
  10067. }
  10068. }
  10069. private showVerifyDialog() {
  10070. promptAction.openCustomDialog({
  10071. transition: TransitionEffect.asymmetric(
  10072. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  10073. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10074. ,
  10075. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  10076. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10077. ),
  10078. builder: () => {
  10079. this.customDialogComponentMM()
  10080. },
  10081. isModal: true,
  10082. autoCancel: true,
  10083. maskColor: Color.Transparent,
  10084. alignment: DialogAlignment.Bottom,
  10085. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  10086. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  10087. console.log("dialog onWillDismiss")
  10088. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  10089. dismissDialogAction.dismiss()
  10090. }
  10091. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  10092. dismissDialogAction.dismiss()
  10093. }
  10094. }
  10095. }).then((dialogId: number) => {
  10096. this.customDialogComponentIdMM = dialogId
  10097. })
  10098. }
  10099. //左滑操作 移动文件 重命名 删除等操作
  10100. @Builder
  10101. DeleteButton(item: VideoItem, index: number, filePath: string) {
  10102. Row() {
  10103. //加入收藏
  10104. Button() {
  10105. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  10106. .fillColor(Color.White)
  10107. .width(20)
  10108. }
  10109. .width(40)
  10110. .height(40)
  10111. .type(ButtonType.Circle)
  10112. .backgroundColor(this.themeColor)
  10113. .margin(5)
  10114. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10115. .onClick(() => {
  10116. if (item) {
  10117. this.doFav(item)
  10118. }
  10119. })
  10120. //加入下一首播放
  10121. Button() {
  10122. Image($r('app.media.next_to_play'))
  10123. .fillColor(Color.White)
  10124. .width(20)
  10125. }
  10126. .width(40)
  10127. .height(40)
  10128. .type(ButtonType.Circle)
  10129. .backgroundColor(this.themeColor)
  10130. .margin(5)
  10131. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10132. .onClick(() => {
  10133. this.addToNextPlay(item);
  10134. })
  10135. //复制文件
  10136. Button() {
  10137. Image($r('app.media.copy'))
  10138. .fillColor(Color.White)
  10139. .width(20)
  10140. }
  10141. .width(40)
  10142. .height(40)
  10143. .type(ButtonType.Circle)
  10144. .backgroundColor(this.themeColor)
  10145. .margin(5)
  10146. .id(filePath + 'copy')
  10147. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10148. .onClick(() => {
  10149. this.showCopyDialog(false, item, index, filePath + 'copy');
  10150. })
  10151. //移动文件
  10152. Button() {
  10153. Image($r('app.media.cut'))
  10154. .fillColor(Color.White)
  10155. .width(20)
  10156. }
  10157. .width(40)
  10158. .height(40)
  10159. .type(ButtonType.Circle)
  10160. .backgroundColor(this.themeColor)
  10161. .margin(5)
  10162. .id(filePath)
  10163. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10164. .onClick(() => {
  10165. this.showCutDialog(false, item, index, filePath);
  10166. })
  10167. Button() {
  10168. Image($r('app.media.cut_current'))
  10169. .fillColor(Color.White)
  10170. .width(20)
  10171. }
  10172. .width(40)
  10173. .height(40)
  10174. .type(ButtonType.Circle)
  10175. .backgroundColor(this.themeColor)
  10176. .margin(5)
  10177. .id(filePath + 'current')
  10178. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  10179. (this.isHasDir ? Visibility.Visible : Visibility.None))
  10180. .onClick(() => {
  10181. this.showCutDialog(true, item, index, filePath + 'current');
  10182. })
  10183. //重命名
  10184. Button() {
  10185. Image($r('app.media.rename2'))
  10186. .fillColor(Color.White)
  10187. .width(20)
  10188. }
  10189. .width(40)
  10190. .height(40)
  10191. .type(ButtonType.Circle)
  10192. .backgroundColor(this.themeColor)
  10193. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10194. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10195. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10196. .margin(5)
  10197. .onClick(() => {
  10198. this.showReNameDialog(item, index + '', filePath)
  10199. })
  10200. Button() {
  10201. Image($r('app.media.delete2'))
  10202. .fillColor(Color.White)
  10203. .width(20)
  10204. }
  10205. .width(40)
  10206. .height(40)
  10207. .type(ButtonType.Circle)
  10208. .backgroundColor(this.themeColor)
  10209. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10210. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10211. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10212. .margin(5)
  10213. .onClick(() => {
  10214. this.showWarnIsDeleteFile(item, index + '', filePath)
  10215. })
  10216. Button() {
  10217. Image($r('app.media.share2'))
  10218. .fillColor(Color.White)
  10219. .width(20)
  10220. }
  10221. .width(40)
  10222. .height(40)
  10223. .type(ButtonType.Circle)
  10224. .backgroundColor(this.themeColor)
  10225. .margin(5)
  10226. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10227. .onClick(() => {
  10228. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10229. })
  10230. }
  10231. }
  10232. /**
  10233. * 穿山甲banner广告
  10234. */
  10235. // private declare bannerAd: CSJNativeExpressAd;
  10236. // @State private status: string = "未加载"
  10237. // @State private isShowAd: boolean = false
  10238. // private declare mAdSlot: AdSlot;
  10239. // private mBiddingAdm = '' //服务端bidding才需要设置
  10240. // private expressLoadAdListener: NativeExpressAdListener = {
  10241. // /**
  10242. // * 加载失败的回调
  10243. // *
  10244. // * @param code
  10245. // * @param message
  10246. // */
  10247. // onError: (code: number, message: string) => {
  10248. // console.error("加载广告失败,code=" + code + ",message=" + message);
  10249. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  10250. // },
  10251. //
  10252. // /**
  10253. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  10254. // *
  10255. // * @param ads 返回的广告列表
  10256. // */
  10257. //
  10258. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  10259. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  10260. // if (ads && ads.length > 0) {
  10261. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  10262. // ad.setExpressInteractionListener({
  10263. // /**
  10264. // *广告的点击回调
  10265. // * @param type 广告的交互类型
  10266. // */
  10267. // onAdClicked: (type: number) => {
  10268. // console.log("BannerExpressAdPage==onAdClicked......");
  10269. // },
  10270. //
  10271. // /**
  10272. // * 广告的展示回调 每个广告仅回调一次
  10273. // * @param type 广告的交互类型
  10274. // */
  10275. // onAdShow: (type: number) => {
  10276. // console.log("BannerExpressAdPage==onAdShow......");
  10277. // },
  10278. //
  10279. // /**
  10280. // * 模板渲染失败
  10281. // */
  10282. // onRenderFail: (code: number, msg: string) => {
  10283. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  10284. // },
  10285. //
  10286. // /**
  10287. // * 模板渲染成功
  10288. // * @param width 返回view的宽 单位 vp
  10289. // * @param height 返回view的高 单位 vp
  10290. // */
  10291. // onRenderSuccess: (width: number, height: number) => {
  10292. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  10293. // this.bannerAd = ad;
  10294. // this.status = "广告加载完成待展示";
  10295. //
  10296. // this.showBannerAd()
  10297. // }
  10298. // })
  10299. // //渲染广告
  10300. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  10301. // this.setDislikeCallback(ad); //设置dislike
  10302. // ad.render(this.getUIContext())
  10303. // this.status = "广告加载中...";
  10304. // });
  10305. // }
  10306. // }
  10307. // }
  10308. //
  10309. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  10310. // ad.setDislikeCallback({
  10311. // /**
  10312. // * dislike show
  10313. // */
  10314. // onShow: () => {
  10315. // console.log("BannerExpressAdPage==dislike......show");
  10316. // },
  10317. //
  10318. // /**
  10319. // * @param position 选择的位置
  10320. // * @param value 选择的内容
  10321. // * @param enforceRemove 是否强制关闭广告
  10322. // */
  10323. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  10324. // this.isShowAd = false;
  10325. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  10326. // ",enforce=" + enforceRemove);
  10327. // },
  10328. //
  10329. // /**
  10330. // * 点击取消
  10331. // */
  10332. // onCancel: () => {
  10333. // console.log("BannerExpressAdPage==dislike......onCancel");
  10334. // }
  10335. //
  10336. // })
  10337. // }
  10338. /**
  10339. * 加载Banner广告
  10340. */
  10341. loadBannerAd(rit: string) {
  10342. // if (Utility.isNoble()) {
  10343. // return
  10344. // }
  10345. // if (!Utility.isPassInstallTime(2)) {
  10346. // return
  10347. // }
  10348. // this.isShowAd = false;
  10349. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  10350. // this.mAdSlot = new AdSlotBuilder()
  10351. // .setCodeId(rit)
  10352. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  10353. // .setAdCount(1)
  10354. // .setBidAdm(this.mBiddingAdm)
  10355. // .build()
  10356. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  10357. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  10358. // this.status = "广告加载中..."
  10359. }
  10360. /**
  10361. * 展示Banner广告
  10362. */
  10363. // showBannerAd() {
  10364. // if (!this.bannerAd) {
  10365. // return
  10366. // }
  10367. // this.isShowAd = true
  10368. // this.status = "已展示"
  10369. // }
  10370. /**
  10371. * 穿山甲广告代码结束
  10372. */
  10373. }
  10374. //视频气泡窗口的布局
  10375. @Builder
  10376. function customPopupBuilder(dataBu: BubbleBean) {
  10377. List() {
  10378. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  10379. ListItem() {
  10380. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10381. Row() {
  10382. Column() {
  10383. Image(dataBu.imageRes[index])
  10384. .height(28)
  10385. .fillColor(dataBu.color)
  10386. .alignSelf(ItemAlign.Center)
  10387. }
  10388. .width(32)
  10389. Text(item)
  10390. .padding({
  10391. top: 10,
  10392. bottom: 10,
  10393. right: 10,
  10394. left: 10
  10395. })
  10396. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  10397. .textAlign(TextAlign.Start)
  10398. .width("100%")
  10399. }
  10400. }
  10401. .backgroundColor($r('app.color.settings_background_main'))
  10402. .margin({ top: 6, bottom: 6 })
  10403. }
  10404. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10405. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  10406. TransitionEffect.scale({ x: 0, y: 0 })))
  10407. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10408. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10409. .onClick(() => {
  10410. dataBu.onItemClick?.(index)
  10411. })
  10412. })
  10413. }
  10414. .width(120)
  10415. .divider({
  10416. strokeWidth: 1,
  10417. color: "#22FFFFFF"
  10418. })
  10419. }
  10420. // Function to calculate a hash for the file list
  10421. function simpleHash(fileList: string[]): string {
  10422. let hash = 0;
  10423. const str = fileList.join(',');
  10424. for (let i = 0; i < str.length; i++) {
  10425. const char = str.charCodeAt(i);
  10426. hash = (hash << 5) - hash + char;
  10427. hash |= 0; // Convert to 32bit integer
  10428. }
  10429. return hash.toString();
  10430. }
  10431. interface MoreItem {
  10432. id: number;
  10433. image: Resource;
  10434. title: string;
  10435. }
  10436. //视频气泡窗口的布局
  10437. @Builder
  10438. function cutPopupBuilder(dataBu: BubbleBean) {
  10439. Column() {
  10440. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  10441. .padding({
  10442. top: 10,
  10443. bottom: 10,
  10444. right: 10,
  10445. left: 10
  10446. })
  10447. .textAlign(TextAlign.Start)
  10448. .width(160)
  10449. .fontWeight(666)
  10450. .fontSize(16)
  10451. List() {
  10452. ForEach(dataBu.data, (item: string, index: number) => {
  10453. ListItem() {
  10454. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10455. Row() {
  10456. Column() {
  10457. Image($r('app.media.music_group'))
  10458. .height(28)
  10459. .fillColor(dataBu.color)
  10460. .alignSelf(ItemAlign.Center)
  10461. }
  10462. .width(32)
  10463. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  10464. .padding({
  10465. top: 10,
  10466. bottom: 10,
  10467. right: 10,
  10468. left: 10
  10469. })
  10470. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  10471. .fontSize(15)
  10472. }
  10473. }
  10474. .backgroundColor(Color.Transparent)
  10475. .margin({ top: 7, bottom: 7 })
  10476. }
  10477. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10478. .animation({ duration: 500 }),
  10479. TransitionEffect.scale({ x: 0, y: 0 })))
  10480. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10481. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10482. .onClick(() => {
  10483. dataBu.onItemClick?.(index)
  10484. })
  10485. })
  10486. }
  10487. .width(150)
  10488. .divider({
  10489. strokeWidth: 1,
  10490. color: "#22FFFFFF"
  10491. })
  10492. }
  10493. .height(300)
  10494. .padding({
  10495. bottom: 30
  10496. })
  10497. }
  10498. function getFileDirName(filePath: string,rootPath:string): string{
  10499. if(filePath===rootPath){
  10500. return '首页'
  10501. }
  10502. let result = FileUtil.getFileName(filePath)
  10503. if(StrUtil.isEmpty(result))
  10504. return ''
  10505. if(result.startsWith('.'))
  10506. result = result.replace(/\./g, '')
  10507. return result
  10508. }