LocalMusic.ets 505 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484
  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 { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. AppUtil,
  8. ArrayUtil,
  9. Base64Util,
  10. DateUtil,
  11. DeviceUtil,
  12. FileUtil,
  13. GlobalContext,
  14. LogUtil,
  15. MD5,
  16. PreferencesUtil,
  17. RandomUtil,
  18. StrUtil,
  19. ToastUtil
  20. } from '@pura/harmony-utils';
  21. import { imagePathToPixelMap } from '../common/util/CommUtils';
  22. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  23. import { CommonConstants } from '../common/constants/CommonConstants';
  24. import { EventConstants } from '../common/constants/EventConstants';
  25. import Logger from '../common/util/Logger';
  26. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  27. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  28. import { BubbleBean } from '../viewmodel/BubbleBean';
  29. import { PopupPosition, XPopup } from '@chinalike/popup';
  30. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  31. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  32. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  33. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  34. import { Verify } from './Verify';
  35. import { taskpool } from '@kit.ArkTS';
  36. import { RotatingCover } from './RotatingCover';
  37. import { PlayConstants } from '../common/constants/PlayConstants';
  38. import { effectKit } from '@kit.ArkGraphics2D';
  39. import { ColorConversion } from '../common/util/ColorConversion';
  40. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  41. import { AvSessionController } from '../controller/AvSessionController';
  42. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  43. import { FFMpegTags,Utility } from '../common/util/Utility';
  44. import { TagsContentCover } from '../view/TagsContentCover';
  45. import {
  46. // DeviceChangeReason,
  47. IjkMediaPlayer,
  48. InterruptEvent,
  49. InterruptHintType,
  50. LogUtils,
  51. OnBufferingUpdateListener,
  52. OnCompletionListener,
  53. OnErrorListener,
  54. OnInfoListener,
  55. OnPreparedListener,
  56. OnSeekCompleteListener,
  57. OnTimedTextListener,
  58. OnVideoSizeChangedListener
  59. } from '@ohos/ijkplayer';
  60. import { PlayStatus } from '../common/PlayStatus';
  61. import fs from '@ohos.file.fs';
  62. import { image } from '@kit.ImageKit';
  63. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  64. import { UniversalDetector } from '@ohos/juniversalchardet';
  65. import { SettingPage } from '../pages/SettingPage';
  66. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  67. import { CommonConstants2 } from '../common/util/CommonConstants2';
  68. import { hilog } from '@kit.PerformanceAnalysisKit';
  69. import { LazyDataSource } from '../common/util/LazyDataSource';
  70. import MediaTable from '../common/util/MediaTable';
  71. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  72. import ImageUtils from '../common/util/ImageUtils';
  73. import { ringtone } from '@kit.RingtoneKit';
  74. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  75. import { resourceManager } from '@kit.LocalizationKit';
  76. import { deviceInfo } from '@kit.BasicServicesKit';
  77. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  78. import app from '@system.app';
  79. import { TextNodeController } from './PipLyricTextBuilder';
  80. import { IndexerView } from './IndexerView';
  81. import { KeyCode } from '@kit.InputKit';
  82. import { KnockController } from '../controller/KnockController';
  83. import { DeleteComptent } from '../view/DeleteComptent';
  84. import { ABLoopComptent } from '../view/ABLoopComptent';
  85. import { FixMessyView } from '../view/FixMessyView';
  86. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  87. import { CueComptent } from '../view/CueComptent';
  88. import PlaylistTable from '../common/util/PlaylistTable';
  89. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  90. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  91. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  92. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  93. import { Song } from '../viewmodel/Song';
  94. import { SongType } from '../common/enums/SongType';
  95. import { WebdavManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  96. buildHttpHeadersWithWebDav,
  97. WebDavAuthItem} from '../common/util/WebdavManager';
  98. import PermissionUtil from '../common/util/PermissionUtil'
  99. import { EditAudio, setRingTone } from './EditAudio';
  100. import { ExtractAccompaniment } from './ExtractAccompaniment';
  101. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  102. import { AudioFormatConverter } from './AudioFormatConverter';
  103. import { MergeAudio } from './MergeAudio';
  104. import { AIVoiceSeparation } from './AIVoiceSeparation';
  105. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  106. import {
  107. hdsEffect,
  108. HdsVisualComponent,
  109. HdsSceneController,
  110. HdsSceneType,
  111. HdsVisualComponentAttribute,
  112. } from '@kit.UIDesignKit';
  113. const TAG = 'LocalMusic';
  114. /**
  115. * 歌单播放事件数据
  116. */
  117. interface PlaylistEventData {
  118. playlistId: string;
  119. playlistName: string;
  120. songCount: number;
  121. startIndex: number;
  122. songFilePaths: string[];
  123. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  124. }
  125. const DEFAULT_INDEX =
  126. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  127. 'X', 'Y', 'Z']
  128. //排序类型
  129. function getTypeOrder(type: number) {
  130. switch (type) {
  131. case CommonConstants.TYPE_IS_DIR:
  132. return 1; // First
  133. case CommonConstants.TYPE_IS_CSJAD:
  134. return 2; // Middle
  135. case CommonConstants.TYPE_LOCAL:
  136. return 3; // Last
  137. default:
  138. return 4; // Unknown types, if any, go last
  139. }
  140. }
  141. /**
  142. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  143. * @param song 歌曲对象
  144. * @returns Promise<string> 完整的URL
  145. */
  146. /**
  147. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  148. * @param song 歌曲对象
  149. * @returns Promise<string> 完整的URL
  150. */
  151. async function setVideoUrlForSong(song: VideoItem): Promise<string> {
  152. if (song.type === CommonConstants.TYPE_WEBDAV && song.webdav_account_id) {
  153. try {
  154. // 优先使用远端相对路径,其次回退到 filePath
  155. const relativePath = song.remote_rel_path || song.filePath;
  156. const fullUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  157. if (fullUrl) {
  158. Logger.info(TAG, `WebDAV完整URL构建成功: ${fullUrl}`);
  159. return fullUrl.replace(/ /g, '%20');
  160. } else {
  161. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  162. return relativePath.replace(/ /g, '%20');
  163. }
  164. } catch (error) {
  165. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  166. const fallbackPath = song.remote_rel_path || song.filePath;
  167. return fallbackPath.replace(/ /g, '%20');
  168. }
  169. } else {
  170. // 非WebDAV文件或缺少webdav_account_id,直接使用原始路径
  171. if (song.type === CommonConstants.TYPE_WEBDAV) {
  172. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  173. }
  174. return song.type === CommonConstants.TYPE_WEBDAV ?
  175. song.filePath.replace(/ /g, '%20') :
  176. song.filePath;
  177. }
  178. }
  179. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  180. // 定义接口
  181. interface HiCarAspectRatio {
  182. ratio: number;
  183. name: string;
  184. }
  185. interface GeneratedObjectLiteralInterface_1 {
  186. assetId: string;
  187. title: string;
  188. artist: string;
  189. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  190. mediaUri: string;
  191. // 该字段大写,音频'AUDIO',视频'VIDEO'
  192. mediaType: string;
  193. mediaSize: number;
  194. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  195. startPosition: number;
  196. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  197. duration: number;
  198. albumCoverUri: string;
  199. albumTitle: string;
  200. appName: string;
  201. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  202. drmScheme: string;
  203. }
  204. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  205. const ITEM_HEIGHT: number = 65; // 列表项中高度
  206. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  207. //功能强大的音乐播放器
  208. @Preview
  209. @Component
  210. export struct LocalMusic {
  211. @State sceneBgController: HdsSceneController = new HdsSceneController()
  212. .setSceneParams({
  213. backgroundMaskColors: [Color.Green, Color.Red],
  214. firstEdgeFlowLight: {
  215. startPos: 0,
  216. endPos: 0.5,
  217. color: Color.Red
  218. },
  219. secondEdgeFlowLight: {
  220. startPos: 0,
  221. endPos: -0.5,
  222. color: Color.Green
  223. }
  224. })
  225. // @State controller: hdsEffect.ShaderEffectController = new hdsEffect.ShaderEffectController();
  226. @State isEditAudio:boolean = false
  227. @State isExtractAcc:boolean = false
  228. @State isConverter:boolean = false
  229. @State isAIVoiceSeparation:boolean = false
  230. @State isExtractAudio:boolean = false
  231. @State isMergeAudio:boolean = false
  232. @State isCopyFileToDownLoad: boolean = false
  233. @State offHeight: number = 75
  234. @State currentSongList: Array<VideoItem> = []//当前歌单
  235. @Consume currentSongListName:string //当前歌单名称
  236. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  237. @State isRefreshing: boolean = false;
  238. @State maxRefreshingHeight: number = 100.0;
  239. private contentNode?: ComponentContent<Object> = undefined;
  240. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  241. @State ratioL: number = 1;
  242. @State mediaKuCount: number = 0;
  243. @State albumCount: number = 0;
  244. @State artistCount: number = 0;
  245. @State fastForwardSeconds: string = '10'
  246. @State isShowBackFast: boolean = true//快进快退按钮
  247. @State isCanAuto:boolean = true
  248. @State opacityValueImage: number = 1;
  249. @State tipPopup:boolean = false
  250. @Consume mType: number;
  251. @StorageProp('themeColor') themeColor: string =
  252. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  253. themeMode: number = 0;
  254. @State titleName: string = '首页'
  255. @State textStr: string = ''
  256. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  257. // private download_path: string = '';
  258. @Consume rootPath: string //音频根目录
  259. @Consume currentPath: string
  260. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  261. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  262. @State lockPath: string = ''
  263. @State favPath: string = ''
  264. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  265. @State historyPath: string = ''
  266. @State historyList: Array<VideoItem> = []
  267. @Consume isHistory: boolean
  268. static readonly HISTORY_MUSIC: string = 'music_historyList';
  269. private table: MediaTable = new MediaTable(getContext(this))
  270. private playlistTable: PlaylistTable | null = null
  271. @State allPlaylists: Playlist[] = []
  272. @State isZero: boolean = false
  273. @State fileList: Array<string> = []
  274. @State dirList: Array<VideoItem> = []
  275. @Consume videoLocalList:VideoItem[]
  276. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  277. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  278. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  279. @State artistList: Array<VideoItem> = []; //艺术家文件
  280. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  281. @State albumList: Array<VideoItem> = []; //专辑文件
  282. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  283. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  284. @State imageOpacities: number[] = [];
  285. @Consume isCanBack: boolean
  286. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  287. @State showSingleLyric: boolean = false
  288. @State sortType: number = 4 //默认排序方式
  289. @State isShowSimi: boolean = false //是否显示私密音频
  290. @State isShowFAV: boolean = true //是否显示我的收藏
  291. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  292. @State isShowAllBar: boolean = true //是否显示播放全部条
  293. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  294. @State isShowHistory: boolean = true //是否显示最近播放
  295. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  296. @State isGridMusic: boolean = false //是否网格布局
  297. @State isCircleBtn: boolean = false //是否圆形播放按钮
  298. @State twoFingerType: number = 3 //双支放大缩小的类型
  299. @State isScrollHide: boolean = false //是否滚动隐藏
  300. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  301. @State isStartAutoPlay: boolean = false //启动后自动播放
  302. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  303. @State isShowHeader: boolean = true
  304. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  305. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  306. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  307. @State isSwipe: boolean = false //listItem的左滑开关
  308. @State openSkipSongAnimate: boolean = true//切歌动画效果
  309. @State customizeBgPath: string | undefined = '';
  310. @State isDarkMode: boolean = false
  311. @State lyricTextWeight: number = 400
  312. @State lyricTextWeightPip: number = 400
  313. @State currentSwiperIndex: number = 0
  314. @State blurValue: number = 0 //背景模糊
  315. @State bgBrightness: number = 0 //背景亮度
  316. private listScroller: ListScroller = new ListScroller()
  317. private playListScroller: Scroller = new Scroller()
  318. @State isOneKeyTags:boolean = false
  319. @State isFixMessy:boolean = false
  320. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  321. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  322. @StorageProp('bottomRectHeight') bottomRectHeight: number = 0;
  323. @StorageProp('windowWidth') windowWidth: number = 0;
  324. @StorageProp('windowHeight') windowHeight: number = 0;
  325. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  326. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  327. private UNKONWN:string = '';
  328. private listArea: Area = {
  329. width: 0,
  330. height: 0,
  331. position: {},
  332. globalPosition: {}
  333. }
  334. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  335. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  336. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  337. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  338. //瀑布流的列数横竖屏动态切换
  339. onIsLandscapeChange() {
  340. if(this.isLandscape){
  341. this.columns = 4
  342. }else{
  343. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  344. }
  345. }
  346. onColorModeChange() {
  347. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  348. if (this.isCustomizeBg) {
  349. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  350. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  351. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  352. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  353. this.tabOptions.selectedBackgroundColor = Color.Transparent
  354. } else {
  355. if (!this.isDarkMode) {
  356. this.titleBarModel.setTitleBarBackground(this.themeColor)
  357. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  358. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  359. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  360. this.tabOptions.selectedBackgroundColor = this.themeColor
  361. } else {
  362. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  363. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  364. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  365. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  366. this.tabOptions.selectedBackgroundColor = $r('app.color.silvery')
  367. }
  368. }
  369. }
  370. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  371. onTopBarhange(){
  372. if(this.isShowTitleBar){
  373. console.log('onecold 导航条显示')
  374. this.topBarHeight = 50
  375. this.offHeight = 75
  376. }else{
  377. console.log('onecold 导航条隐藏')
  378. this.topBarHeight = 0
  379. if(this.twoFingerType!=4){
  380. this.offHeight = 30
  381. }
  382. }
  383. }
  384. //点击某个歌单id发生变化的时候回调
  385. onIDChange(){
  386. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  387. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  388. if(this.modeType==4){
  389. this.isShowTitleBar = false
  390. this.titleBarModel.setTitleName(this.currentSongListName)
  391. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  392. //获取缓存
  393. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  394. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  395. if(StrUtil.isNotEmpty(cacheSongs)){
  396. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  397. this.updateListData(this.currentSongList, true)
  398. }
  399. this.doSongListTask()//获取歌单信息
  400. }
  401. }
  402. async doSongListTask() {
  403. // 初始化歌单数据库
  404. const playlistTable = new PlaylistTable(this.context);
  405. // 查询歌单中的所有歌曲
  406. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  407. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  408. if (ArrayUtil.isEmpty(playlistSongs)) {
  409. this.updateListData([], true)
  410. } else {
  411. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  412. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  413. this.updateListData(this.currentSongList, true)
  414. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  415. // 只保存前100条记录到缓存中
  416. let canceList = this.currentSongList.slice(0, 100);
  417. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  418. JSON.stringify(canceList))
  419. } else {
  420. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  421. }
  422. }
  423. this.isRefreshing = false
  424. }
  425. onModeChange() {
  426. this.isFavMusic = false
  427. if (this.modeType === 2 || this.modeType === 3|| this.modeType === 4) {
  428. this.titleBarModel.setRightIcon(null)
  429. } else {
  430. this.titleBarModel.setRightIcon(($r('app.media.add')))
  431. }
  432. LogUtil.info('onecold onModeChange = ' + this.modeType)
  433. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  434. switch (this.modeType) {
  435. case 0:
  436. this.getSortedFiles(this.currentPath)
  437. break
  438. case 1:
  439. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  440. this.updateListData(this.mediaKuList)
  441. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  442. break
  443. case 2:
  444. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  445. this.updateListData(this.artistList)
  446. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  447. break
  448. case 3:
  449. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  450. this.updateListData(this.albumList)
  451. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  452. break
  453. }
  454. }
  455. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  456. // @StorageLink('isPlay') isPlay: boolean = false;
  457. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  458. @StorageLink('songList') songList: Array<VideoItem> = [];
  459. @State translateY: number = 0;
  460. @State isShowSheet: boolean = false;
  461. @State isShowSheetView: boolean = false;
  462. @State isShowTimeCloseView: boolean = false;
  463. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  464. @StorageLink('currIndex') curIndex: number = 0;
  465. @Consume isShowDrawer: boolean;
  466. @Consume offsetX: number;
  467. @State isFac: boolean = false;
  468. @State favList: Array<VideoItem> = []
  469. @Consume isFavMusic: boolean
  470. @State isClickedPLayAll: boolean = false;
  471. private scrollerForlist: ListScroller = new ListScroller();
  472. private knockController: KnockController | undefined = undefined;
  473. imagesF: ImageFrameInfo[] = [
  474. { src: $r("app.media.app_loading0") },
  475. { src: $r("app.media.app_loading1") },
  476. { src: $r("app.media.app_loading2") },
  477. { src: $r("app.media.app_loading3") },
  478. ]
  479. @State animationState: AnimationStatus = AnimationStatus.Initial
  480. // 缓存机制
  481. private cache: Map<string, Array<VideoItem>> = new Map();
  482. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  483. // 持久化缓存
  484. private async saveCacheToStorage() {
  485. const cacheArray = Array.from(this.cache.entries());
  486. const stringCacheArray = Array.from(this.stringCache.entries());
  487. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  488. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  489. }
  490. // 载入缓存
  491. private async loadCacheFromStorage() {
  492. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  493. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  494. if (cacheString) {
  495. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  496. this.cache = new Map(cacheArray);
  497. }
  498. if (stringCacheString) {
  499. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  500. this.stringCache = new Map(stringCacheArray);
  501. }
  502. }
  503. // 查找缓存
  504. private findCache(key: string): Array<VideoItem> | undefined {
  505. return this.cache.get(key);
  506. }
  507. // 查找字符串缓存
  508. private findStringCache(key: string): string | undefined {
  509. return this.stringCache.get(key);
  510. }
  511. // 添加缓存
  512. private addCache(key: string, value: Array<VideoItem>) {
  513. this.cache.set(key, value);
  514. }
  515. // 添加字符串缓存
  516. private addStringCache(key: string, value: string) {
  517. this.stringCache.set(key, value);
  518. }
  519. // 删除缓存
  520. private deleteCache(key: string) {
  521. this.cache.delete(key);
  522. this.saveCacheToStorage()
  523. }
  524. // 删除字符串缓存
  525. private deleteStringCache(key: string) {
  526. this.stringCache.delete(key);
  527. }
  528. // 多选机制
  529. @State selectedFiles: Array<VideoItem> = [];
  530. @State isMultiSelect: boolean = false;
  531. @State isAllSelected: boolean = false;
  532. @State appName: string = ''
  533. @State isHasDir: boolean = false
  534. @State packName: string = ''
  535. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  536. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  537. .setTitleTextStyle(FontStyle.Normal)
  538. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  539. .setLeftIcon($r('app.media.menu'))
  540. .setLeftIconWidth(26)
  541. .setLeftIconHeight(26)
  542. .setTitleName('首页')
  543. .setTitleBarMinHeight(55)
  544. .setTitleFontSize(18)
  545. .setTitleFontColor(Color.White)
  546. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  547. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  548. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  549. .setRightIcon($r('app.media.add'))
  550. .setOnRightClickListener(() => {
  551. this.showSheelDialog()
  552. })
  553. // .setOnTitleClickListener(() => {
  554. // this.showPupDialog()
  555. // })
  556. .setOnLeftClickListener(() => {
  557. this.doSwipBack()
  558. })
  559. doSwipBack() {
  560. this.isZero = false
  561. if (this.modeType !== 0 && this.isCanBack) {
  562. this.onModeChange()
  563. this.isCanBack = false
  564. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  565. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  566. setTimeout(() => {
  567. if (this.modeType == 2) {
  568. if (this.isGridMusic||this.twoFingerType==4) {
  569. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  570. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  571. if(this.twoFingerType==4){
  572. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  573. }else{
  574. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  575. }
  576. } else {
  577. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  578. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  579. }
  580. } else if (this.modeType == 3) {
  581. if (this.isGridMusic||this.twoFingerType==4) {
  582. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  583. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  584. if(this.twoFingerType==4){
  585. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  586. }else{
  587. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  588. }
  589. } else {
  590. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  591. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  592. }
  593. }
  594. }, 200)
  595. return
  596. }
  597. if (this.isHistory || this.isFavMusic) {
  598. this.isHistory = false
  599. this.getSortedFiles(this.currentPath)
  600. return
  601. }
  602. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  603. animateTo({ duration: 555 }, () => {
  604. // 动画闭包内控制Image组件的出现和消失
  605. this.isShowDrawer = !this.isShowDrawer
  606. this.offsetX = 0
  607. })
  608. return
  609. }
  610. //返回上一级歌单的滚动位置
  611. setTimeout(() => {
  612. if (this.modeType == 0) {
  613. if (this.isGridMusic||this.twoFingerType==4) {
  614. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  615. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  616. if(this.twoFingerType==4){
  617. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  618. }else{
  619. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  620. }
  621. } else {
  622. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  623. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  624. }
  625. }
  626. }, 300)
  627. this.currentPath = Utility.getParentDirectory(this.currentPath)
  628. Logger.info('this.currentPath2 = ' + this.currentPath)
  629. this.getSortedFiles(this.currentPath)
  630. }
  631. // 组件生命周期
  632. aboutToAppear() {
  633. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  634. this.updateListData(this.videoLocalList)
  635. }
  636. // 初始化 PlaylistTable
  637. this.playlistTable = new PlaylistTable(getContext(this))
  638. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  639. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  640. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  641. this.tipPopup = !this.tipPopup
  642. PreferencesUtil.putSync('isFirstTiped',false)
  643. }
  644. this.initSetting()
  645. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  646. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  647. Utility.getAppName(getContext(this)).then((appName: string) => {
  648. this.appName = appName
  649. })
  650. this.packName = AppUtil.getBundleName()
  651. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  652. this.loadCacheFromStorage(); // 加载文件夹缓存
  653. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  654. this.initLoadCache()
  655. this.mkDownLoadDir()
  656. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  657. // 监听广播事件(打开其他应用处理)
  658. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  659. this.saveVideoDatas([eventData.data?.message], true)
  660. });
  661. //侧滑广播接收时间
  662. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  663. // 监听广播事件(打开其他应用处理)
  664. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  665. animateTo({ duration: 555 }, () => {
  666. this.doSwipBack()
  667. })
  668. });
  669. //ScanFilePage广播接收时间
  670. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  671. // 监听ScanFilePage广播事件(更新数据库)
  672. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  673. this.doUpdateData()
  674. });
  675. // 监听歌单播放请求事件
  676. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  677. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  678. const data = eventData.data as Record<string, Object>
  679. if (!data) {
  680. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  681. return
  682. }
  683. // 检查歌单播放数据结构
  684. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  685. const playlistData: PlaylistEventData = {
  686. playlistId: data.playlistId as string,
  687. playlistName: data.playlistName as string,
  688. songCount: data.songCount as number,
  689. startIndex: data.startIndex as number,
  690. songFilePaths: data.songFilePaths as string[]
  691. }
  692. await this.handlePlaylistPlayRequest(
  693. playlistData.playlistId,
  694. playlistData.playlistName,
  695. playlistData.songFilePaths,
  696. playlistData.startIndex
  697. )
  698. return
  699. }
  700. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  701. });
  702. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  703. // 监听广播事件(通用设置配置更新)
  704. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  705. if(this.modeType ==4){
  706. this.doSongListTask()//获取歌单信息
  707. }
  708. });
  709. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  710. // 监听广播事件(通用设置配置更新)
  711. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  712. this.doChangeSetting()
  713. });
  714. let event: Callback<InterruptEvent> = (event) => {
  715. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  716. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  717. this.savePlaybackPosition()
  718. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  719. this.pause();
  720. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  721. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  722. console.info('onecold startPlayOrResumePlay 514')
  723. this.startPlayOrResumePlay();
  724. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  725. this.stop();
  726. }
  727. }
  728. this.mIjkMediaPlayer.on('audioInterrupt', event);
  729. // 音频设备断连回调处理
  730. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  731. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  732. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  733. // this.pause();
  734. // }
  735. // }
  736. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  737. this.makeWorker()
  738. //折叠屏的屏幕显示模式变化
  739. display.on('foldDisplayModeChange', (data) => {
  740. this.doChangeBarHeight()
  741. });
  742. display.on('foldStatusChange', (data) => {
  743. Logger.info('onecold foldStatusChange ')
  744. });
  745. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  746. // 读取 themeMode 并同步 currentColorMode
  747. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  748. this.applyThemeMode(this.themeMode)
  749. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  750. AppStorage.setOrCreate('themeColor', themeColor);
  751. this.themeColor = themeColor;
  752. this.doChangeSetting()
  753. this.windowClass.on('windowSizeChange', (size) => {
  754. LogUtil.info('onecold windowSizeChange')
  755. this.doChangeBarHeight()
  756. let viewWidth = px2vp(size.width);
  757. let viewHeight = px2vp(size.height);
  758. if(this.isPhoneLan()){
  759. this.is_auto_hide_progress = false
  760. if(this.isHiCar()){
  761. return
  762. }
  763. setTimeout(() => {
  764. this.is_auto_hide_progress = true
  765. }, 6000)
  766. }else{
  767. this.startAutoHide()
  768. }
  769. });
  770. this.eventHub.on('onStateChange', (fg: boolean) => {
  771. if (fg && this.curState === 'STARTED') {
  772. this.stopPip();
  773. }
  774. });
  775. }
  776. //载入媒体库,艺术家,专辑等缓存
  777. initLoadCache(){
  778. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  779. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  780. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  781. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  782. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  783. if(ArrayUtil.isNotEmpty(cachedList)){
  784. this.mediaKuList = cachedList
  785. if(this.modeType==1){
  786. this.updateListData(this.mediaKuList)
  787. }
  788. }
  789. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  790. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  791. if(ArrayUtil.isNotEmpty(artistCachedList)){
  792. this.artistList = artistCachedList
  793. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  794. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  795. this.artistMap = new Map(parsedArray);
  796. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  797. if(this.modeType==2){
  798. this.updateListData(this.artistList)
  799. }
  800. }
  801. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  802. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  803. if(ArrayUtil.isNotEmpty(albumCachedList)){
  804. this.albumList = albumCachedList
  805. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  806. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  807. this.albumMap = new Map(parsedArray);
  808. if(this.modeType==3){
  809. this.updateListData(this.albumList)
  810. }
  811. }
  812. }
  813. startAutoHide() {
  814. if(this.isHiCar()){
  815. return
  816. }
  817. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  818. console.info('onecold startAutoHide')
  819. this.is_auto_hide_progress = false
  820. setTimeout(() => {
  821. this.is_auto_hide_progress = true
  822. }, 6000)
  823. }
  824. }
  825. applyThemeMode(mode: number) {
  826. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  827. if (mode === 1) {
  828. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  829. } else if (mode === 2) {
  830. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  831. }
  832. AppStorage.setOrCreate('currentColorMode', colorMode)
  833. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  834. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  835. AppStorage.setOrCreate('themeMode', mode)
  836. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  837. // 只有强制浅色/深色时才主动设置
  838. const context = getContext(this) as common.UIAbilityContext
  839. context.getApplicationContext().setColorMode(colorMode)
  840. }
  841. initSetting() {
  842. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  843. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  844. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  845. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  846. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  847. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  848. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  849. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  850. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  851. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  852. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  853. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  854. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  855. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  856. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  857. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  858. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  859. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  860. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  861. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  862. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  863. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  864. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  865. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  866. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  867. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  868. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  869. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  870. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  871. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  872. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  873. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  874. if(this.volumeSmall){
  875. this.volume = 0.5
  876. }else{
  877. this.volume = 1
  878. }
  879. //如果是hicar连接状态,这些都是false
  880. if(this.isHiCar()){
  881. this.isShowTitleBar = false//不显示导航栏
  882. this.columns=4
  883. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  884. {
  885. this.isShowHeader = false//二级菜单不显示头部
  886. this.isGridMusic= false//用list不用网格
  887. this.isCoverTopBig = false
  888. }
  889. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  890. }
  891. if (this.isSavePlayMode) {
  892. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  893. }
  894. if (this.isCustomizeBg) {
  895. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  896. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  897. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  898. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  899. } else {
  900. if (!this.isDarkMode) {
  901. this.titleBarModel.setTitleBarBackground(this.themeColor)
  902. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  903. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  904. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  905. } else {
  906. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  907. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  908. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  909. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  910. }
  911. }
  912. }
  913. doChangeSetting() {
  914. this.initSetting()
  915. this.deleteCache(this.currentPath)
  916. if (this.modeType === 0) {
  917. this.getSortedFiles(this.currentPath)
  918. }
  919. }
  920. doChangeBarHeight() {
  921. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  922. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  923. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  924. this.setBarHeightNormal()
  925. }
  926. }
  927. onPageShow() {
  928. this.knockController?.immersiveListening();
  929. app.setImageCacheCount(100);
  930. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  931. app.setImageRawDataCacheSize(104857600);
  932. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  933. }
  934. //开启线程查看各个数据库
  935. makeWorker() {
  936. setTimeout(() => {
  937. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  938. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  939. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  940. // workerInstance.postMessage({
  941. // code: 1,
  942. // data1: this.context,
  943. // data2: this.rootPath,
  944. // data3: this.lockPath,
  945. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  946. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  947. // });
  948. PreferencesUtil.putSync('isFirstApp', false)
  949. } else {
  950. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  951. workerInstance.postMessage({ code: 3, data: this.context });
  952. workerInstance.postMessage({ code: 4, data: this.context });
  953. this.getHistoryList(false)
  954. }
  955. }, 1000)
  956. workerInstance.onmessage = (e: MessageEvents): void => {
  957. switch (e.data.code) {
  958. case 101: //第一次扫描文件夹入库
  959. ToastUtil.showToast('刷新同步数据库成功!')
  960. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  961. this.doUpdateData()
  962. break;
  963. case 102: //查询媒体库列表
  964. this.isRefreshing = false
  965. this.mediaKuList = e.data.data
  966. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  967. Utility.doSortListAscending(this.mediaKuList)
  968. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  969. if (this.modeType === 1) {
  970. this.updateListData(this.mediaKuList)
  971. }
  972. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  973. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  974. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  975. // 只保存前100条记录到缓存中
  976. let truncatedList = this.mediaKuList.slice(0, 100);
  977. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  978. } else {
  979. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  980. }
  981. break;
  982. case 103: //收到查询艺术家列表
  983. this.isRefreshing = false
  984. this.artistMap = e.data.data1;
  985. this.artistList = e.data.data2;
  986. PreferencesUtil.putSync('artistCount', this.artistList.length)
  987. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  988. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  989. // 只保存前100条记录到缓存中
  990. let truncatedList = this.artistList.slice(0, 100);
  991. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  992. } else {
  993. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  994. }
  995. // 处理并缓存前60条艺术家数据
  996. const sortedEntries = Array.from(this.artistMap.entries())
  997. .sort((a, b) => b[1].length - a[1].length)
  998. .slice(0, 60);
  999. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1000. break;
  1001. case 104: //收到查询专辑列表
  1002. this.isRefreshing = false
  1003. this.albumMap = e.data.data1;
  1004. this.albumList = e.data.data2
  1005. //查询完毕在启动是否自动播放
  1006. if (this.isStartAutoPlay&&this.isCanAuto) {
  1007. this.isCanAuto = false
  1008. console.info('onecold startPlayOrResumePlay 757')
  1009. this.startPlayOrResumePlay()
  1010. }
  1011. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1012. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1013. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1014. // 只保存前100条记录到缓存中
  1015. let truncatedList = this.albumList.slice(0, 100);
  1016. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1017. } else {
  1018. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1019. }
  1020. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1021. .sort((a, b) => b[1].length - a[1].length)
  1022. .slice(0, 60);
  1023. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1024. break;
  1025. }
  1026. };
  1027. // 在调用terminate后,执行onexit
  1028. workerInstance.onexit = (code) => {
  1029. console.log("main thread terminate");
  1030. }
  1031. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  1032. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  1033. workerInstance.onerror = (err: ErrorEvent) => {
  1034. console.log("onerror" + err.message);
  1035. }
  1036. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  1037. //碰一碰分享的监听
  1038. this.knockController = KnockController.getInstance(this.context);
  1039. this.knockController?.immersiveListening();
  1040. }
  1041. onPageHide(): void {
  1042. this.knockController?.immersiveDisableListening();
  1043. }
  1044. @State isFirstStartPlay: boolean = false
  1045. //获取download_path
  1046. async mkDownLoadDir() {
  1047. const documentViewPicker = new picker.DocumentViewPicker()
  1048. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1049. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1050. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1051. this.currentPath = this.rootPath
  1052. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1053. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1054. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1055. Logger.info('onecold rootPath = ' + this.rootPath)
  1056. Logger.info('onecold lockPath = ' + this.lockPath)
  1057. if (!FileUtil.accessSync(this.lockPath)) {
  1058. FileUtil.mkdirSync(this.lockPath)
  1059. }
  1060. if (!FileUtil.accessSync(this.favPath)) {
  1061. FileUtil.mkdirSync(this.favPath)
  1062. }
  1063. if (!FileUtil.accessSync(this.historyPath)) {
  1064. FileUtil.mkdirSync(this.historyPath)
  1065. }
  1066. this.getSortedFiles(this.rootPath).then(async () => {
  1067. this.isFavMusic = false
  1068. //穿山甲
  1069. // this.loadBannerAd(CSJUtil.getBannerID())
  1070. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1071. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1072. if (ArrayUtil.isEmpty(this.songList)) {
  1073. this.songList = this.getCurFileList()
  1074. } else {
  1075. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1076. }
  1077. if (ArrayUtil.isNotEmpty(this.songList)) {
  1078. this.isFirstStartPlay = true
  1079. this.sonDataSource.pushArrayData(this.songList)
  1080. if (this.currentSong === undefined) {
  1081. this.isFirstStartPlay = false
  1082. this.currentSong = this.songList[0]
  1083. }
  1084. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1085. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  1086. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1087. this.name = this.currentSong.name
  1088. this.cover = this.currentSong.pixelMapPath
  1089. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1090. } else {
  1091. this.name = '空空如也'
  1092. }
  1093. })
  1094. this.getFavList(false)
  1095. }
  1096. getFavList(isFavRefresh: boolean) {
  1097. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1098. this.favList = result
  1099. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1100. this.videoLocalList = this.favList
  1101. this.updateListData(this.videoLocalList)
  1102. }
  1103. })
  1104. }
  1105. getHistoryList(isRefresh: boolean) {
  1106. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1107. this.historyList = result
  1108. // for (let i = 0; i < this.historyList.length; i++) {
  1109. //
  1110. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1111. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1112. // }
  1113. if (isRefresh) {
  1114. this.videoLocalList = this.historyList
  1115. this.updateListData(this.videoLocalList, true)
  1116. }
  1117. })
  1118. }
  1119. // 组件消失生命周期
  1120. aboutToDisappear() {
  1121. console.info('LifeCycleComponent aboutToDisappear');
  1122. this.knockController?.immersiveDisableListening();
  1123. this.curIndex = 0
  1124. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1125. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1126. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1127. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1128. this.mDestroyPage = true;
  1129. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1130. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1131. this.stop();
  1132. }
  1133. this.mIjkMediaPlayer.off('audioInterrupt');
  1134. if (workerInstance) {
  1135. workerInstance.terminate();
  1136. }
  1137. this.stopPip();
  1138. this.destroyPipController()
  1139. }
  1140. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  1141. this.isFavMusic = false
  1142. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1143. if (isWorkerPost) {
  1144. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1145. }
  1146. if (this.modeType !== 0) {
  1147. this.openMusic(isOpen, destPath)
  1148. return
  1149. }
  1150. console.info('onecold getSortedFiles 2')
  1151. this.isCanBack = false
  1152. this.currentPath = curPath
  1153. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1154. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  1155. if (curPath === this.rootPath) {
  1156. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1157. } else {
  1158. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1159. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1160. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  1161. }
  1162. }
  1163. // Get the current file list and calculate its hash
  1164. this.fileList = FileUtil.listFileSync(curPath);
  1165. const currentHash = simpleHash(this.fileList);
  1166. // Check cache
  1167. const cachedValue = this.findCache(curPath);
  1168. Logger.info('onecold cachedValue = ' + cachedValue)
  1169. const cachedHash = this.findStringCache(curPath + '_hash');
  1170. const cachedDirList = this.findCache(curPath + "_dirList");
  1171. if (cachedValue !== undefined&&!this.isRefreshing) {
  1172. // this.videoLocalList = cachedValue;
  1173. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1174. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1175. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1176. }
  1177. this.isRefreshing = false
  1178. this.updateListData(cachedValue)
  1179. }
  1180. if (cachedDirList !== undefined) {
  1181. this.dirList = cachedDirList
  1182. }
  1183. //通过当前hash值和缓存hash判断list有没有变化
  1184. if (cachedValue && cachedHash === currentHash) {
  1185. return;
  1186. }
  1187. this.fileList = FileUtil.listFileSync(curPath)
  1188. let directories: Array<VideoItem> = [];
  1189. let files: Array<VideoItem> = [];
  1190. for (let i = 0; i < this.fileList.length; i++) {
  1191. console.info(`The name of file: ${this.fileList[i]}`);
  1192. let path = curPath + '/' + this.fileList[i]
  1193. if (FileUtil.isDirectory(path)) {
  1194. let item: VideoItem =
  1195. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1196. '')
  1197. if (this.isShowDir(item.name)) {
  1198. directories.push(item);
  1199. }
  1200. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1201. // Utility.doSortListAscending(directories)
  1202. } else {
  1203. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1204. let item: VideoItem =
  1205. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1206. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1207. files.push(item);
  1208. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1209. // this.doSortListAscending(files)
  1210. }
  1211. }
  1212. }
  1213. }
  1214. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1215. if (this.currentPath !== this.lockPath) {
  1216. files = result;
  1217. }
  1218. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1219. Utility.doSortListAscending(files)
  1220. if (this.currentPath === this.rootPath) {
  1221. this.dirList = directories
  1222. this.addCache(curPath + "_dirList", this.dirList);
  1223. }
  1224. //插入广告先注释掉
  1225. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1226. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1227. // directories.push(adItem)
  1228. // }
  1229. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1230. this.videoLocalList = directories.concat(files);
  1231. this.updateListData(this.videoLocalList)
  1232. if (ArrayUtil.isNotEmpty(files)) {
  1233. if (this.currentPath != this.rootPath) {
  1234. if (files) {
  1235. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1236. }
  1237. }
  1238. // 缓存结果
  1239. this.addCache(curPath, this.videoLocalList);
  1240. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1241. this.addStringCache(curPath + '_hash', currentHash);
  1242. }
  1243. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1244. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1245. //
  1246. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1247. //
  1248. // }
  1249. // this.setButtonStatus()
  1250. this.openMusic(isOpen, destPath)
  1251. this.isRefreshing = false
  1252. });
  1253. }
  1254. //第三方app打开天天静听导入音乐后播放
  1255. openMusic(isOpen?: boolean, destPath?: string){
  1256. if (isOpen&&destPath) {
  1257. if (destPath === undefined) {
  1258. // 处理 destPath 为 undefined 的情况
  1259. return
  1260. }
  1261. if (destPath.endsWith('.lrc')) {
  1262. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1263. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1264. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1265. this.initLyric(lyricPath);
  1266. }
  1267. return
  1268. }
  1269. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  1270. this.doPlay(item2,0,false,true)
  1271. this.isShowPlay = true
  1272. }
  1273. }
  1274. //扫描文件夹入库
  1275. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1276. const files = FileUtil.listFileSync(curPath);
  1277. let mediaItems: VideoItem[] = [];
  1278. Logger.info('onecold scanDirectory start ')
  1279. for (const file of files) {
  1280. const fPath = `${curPath}/${file}`;
  1281. if (fPath === this.lockPath) {
  1282. Logger.info(`Skipping locked path: ${fPath}`);
  1283. continue;
  1284. }
  1285. if (FileUtil.isDirectory(fPath)) {
  1286. // Recursively scan subdirectories
  1287. const subDirItems = await this.scanDirectory(fPath);
  1288. mediaItems = mediaItems.concat(subDirItems);
  1289. } else {
  1290. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1291. // Process media files
  1292. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1293. let mediaItem: VideoItem =
  1294. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1295. mediaItems.push(mediaItem);
  1296. this.table.insert(mediaItem, (id: number) => {
  1297. });
  1298. }
  1299. }
  1300. }
  1301. return mediaItems;
  1302. }
  1303. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1304. animateTo({ duration: 666 }, () => {
  1305. this.opacityItem = 0.5;
  1306. });
  1307. setTimeout(() => {
  1308. this.videoLocalList = mList;
  1309. if (!noSort) {
  1310. if (this.modeType === 0 || this.modeType === 1) {
  1311. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1312. this.doSortType(this.sortType)
  1313. }
  1314. }
  1315. this.dataSource.pushArrayData(this.videoLocalList)
  1316. animateTo({ duration: 666 }, () => {
  1317. this.opacityItem = 1;
  1318. });
  1319. this.setButtonStatus()
  1320. }, 200);
  1321. }
  1322. //排序模式和多选模式
  1323. showPupDialog() {
  1324. if (this.modeType === 2 || this.modeType === 3) {
  1325. this.titleBarModel.setRightIcon(null)
  1326. } else {
  1327. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1328. }
  1329. let dataBean = new BubbleBean()
  1330. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1331. dataBean.color = this.themeColor
  1332. dataBean.modeType = this.modeType
  1333. dataBean.imageRes =
  1334. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1335. $r('app.media.refresh')]
  1336. let pup: XPopup;
  1337. if (this.isDarkMode) {
  1338. pup = XPopup.Builder()
  1339. .setPopupPosition(PopupPosition.BOTTOM)
  1340. .atView('pup_positon_music')
  1341. .setBackgroundColor(Color.Black)
  1342. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1343. .show()
  1344. } else {
  1345. pup = XPopup.Builder()
  1346. .setPopupPosition(PopupPosition.BOTTOM)
  1347. .atView('pup_positon_music')
  1348. .setBackgroundColor(Color.White)
  1349. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1350. .show()
  1351. }
  1352. dataBean.onItemClick = (i) => {
  1353. XPopup.dismissTop()
  1354. switch (i) {
  1355. case 0: //首页
  1356. this.modeType = 0
  1357. this.getSortedFiles(this.currentPath)
  1358. break
  1359. case 1:
  1360. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1361. this.modeType = 1
  1362. this.updateListData(this.mediaKuList)
  1363. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1364. break
  1365. case 2:
  1366. this.modeType = 2
  1367. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1368. this.updateListData(this.artistList)
  1369. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1370. break
  1371. case 3:
  1372. this.modeType = 3
  1373. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1374. this.updateListData(this.albumList)
  1375. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1376. break
  1377. case 4: //同步数据
  1378. // this.asyncCurrentPathData()
  1379. break
  1380. }
  1381. }
  1382. }
  1383. getCurFileList(): Array<VideoItem> {
  1384. if(this.isSearchMode){
  1385. return this.filteredList
  1386. }
  1387. let files: Array<VideoItem> = [];
  1388. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1389. for (let i = 0; i < this.videoLocalList.length; i++) {
  1390. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1391. files.push(this.videoLocalList[i]);
  1392. }
  1393. }
  1394. }
  1395. return files
  1396. }
  1397. setButtonStatus() {
  1398. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1399. this.isZero = false
  1400. } else {
  1401. this.isZero = true
  1402. }
  1403. if (this.currentPath !== this.rootPath &&
  1404. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1405. this.isHasDir = true //不为空,说明有子文件夹
  1406. } else {
  1407. this.isHasDir = false
  1408. }
  1409. }
  1410. showRankDialog() {
  1411. if ((this.modeType === 2&&!this.isCanBack) || (this.modeType === 3&&!this.isCanBack)) {
  1412. //动作面板
  1413. DialogHelper.showBottomSheetDialog({
  1414. title: "请选择排序模式",
  1415. maskColor: Color.Transparent,
  1416. // sheets: ["按名称升序", "按名称降序"],
  1417. sheets: [
  1418. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1419. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1420. { value: '按数量升序', fontColor: $r('app.color.text_color') },
  1421. { value: '按数量降序', fontColor: $r('app.color.text_color') },
  1422. ],
  1423. backgroundColor: $r('app.color.bg_card'),
  1424. height: '45%',
  1425. transition: AnimationHelper.transitionInDown(555),
  1426. onAction: (index) => {
  1427. switch (index) {
  1428. case 0:
  1429. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1430. break;
  1431. case 1:
  1432. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1433. break;
  1434. case 2:
  1435. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1436. // 1. Sort by type first
  1437. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1438. if (typeOrder !== 0) {
  1439. return typeOrder;
  1440. }
  1441. // 2. Then sort by artist count (numeric comparison)
  1442. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1443. if(this.modeType === 2){
  1444. sortMap = this.artistMap
  1445. }else{
  1446. sortMap = this.albumMap
  1447. }
  1448. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1449. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1450. return aArtistCount - bArtistCount;
  1451. });
  1452. break;
  1453. case 3:
  1454. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1455. // 1. Sort by type first
  1456. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1457. if (typeOrder !== 0) {
  1458. return typeOrder;
  1459. }
  1460. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1461. if(this.modeType === 2){
  1462. sortMap = this.artistMap
  1463. }else{
  1464. sortMap = this.albumMap
  1465. }
  1466. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1467. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1468. return bArtistCount - aArtistCount;
  1469. });
  1470. break;
  1471. }
  1472. this.updateListData(this.videoLocalList)
  1473. }
  1474. })
  1475. return
  1476. }
  1477. //动作面板
  1478. DialogHelper.showBottomSheetDialog({
  1479. title: "请选择排序模式",
  1480. maskColor: Color.Transparent,
  1481. height: '75%',
  1482. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1483. sheets: [
  1484. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1485. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1486. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1487. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1488. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1489. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1490. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1491. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1492. ],
  1493. backgroundColor: $r('app.color.bg_card'),
  1494. transition: AnimationHelper.transitionInDown(555),
  1495. onAction: (index) => {
  1496. this.doSortType(index)
  1497. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1498. this.updateListData(this.videoLocalList, true)
  1499. }
  1500. })
  1501. }
  1502. doSortType(index: number) {
  1503. switch (index) {
  1504. case 0:
  1505. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1506. // 类型排序优先级
  1507. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1508. if (typeOrder !== 0) {
  1509. return typeOrder;
  1510. }
  1511. // 处理艺术家可能为undefined的字符串比较
  1512. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1513. const artistB = b.artist?.trim() || '';
  1514. return artistA.localeCompare(artistB);
  1515. });
  1516. break;
  1517. case 1:
  1518. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1519. // 类型排序优先级
  1520. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1521. if (typeOrder !== 0) {
  1522. return typeOrder;
  1523. }
  1524. // 处理艺术家可能为undefined的字符串比较
  1525. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1526. const artistB = b.artist?.trim() || '';
  1527. return artistB.localeCompare(artistA);
  1528. });
  1529. break;
  1530. case 2:
  1531. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1532. // 类型排序优先级
  1533. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1534. if (typeOrder !== 0) {
  1535. return typeOrder;
  1536. }
  1537. // 处理专辑可能为undefined的字符串比较
  1538. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1539. const albumB = b.album?.trim() || '';
  1540. return albumA.localeCompare(albumB);
  1541. });
  1542. break;
  1543. case 3:
  1544. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1545. // 类型排序优先级
  1546. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1547. if (typeOrder !== 0) {
  1548. return typeOrder;
  1549. }
  1550. // 处理专辑可能为undefined的字符串比较
  1551. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1552. const albumB = b.album?.trim() || '';
  1553. return albumB.localeCompare(albumA);
  1554. });
  1555. break;
  1556. case 4:
  1557. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1558. break;
  1559. case 5:
  1560. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1561. break;
  1562. case 6:
  1563. this.videoLocalList.sort((a, b) => {
  1564. // First, sort by type
  1565. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1566. if (typeOrder !== 0) {
  1567. return typeOrder;
  1568. }
  1569. // If types are the same, sort by cTime in ascending order
  1570. return a.cTime.localeCompare(b.cTime);
  1571. });
  1572. break;
  1573. case 7:
  1574. this.videoLocalList.sort((a, b) => {
  1575. // First, sort by type
  1576. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1577. if (typeOrder !== 0) {
  1578. return typeOrder;
  1579. }
  1580. // If types are the same, sort by cTime in descending order
  1581. return b.cTime.localeCompare(a.cTime);
  1582. });
  1583. break;
  1584. }
  1585. }
  1586. showSheelDialog() {
  1587. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1588. // this.showTips()
  1589. // return
  1590. // }
  1591. this.showAddDialog()
  1592. }
  1593. showAddDialog() {
  1594. if (this.modeType === 2 || this.modeType === 3) {
  1595. return
  1596. }
  1597. DialogHelper.showActionSheetDialog({
  1598. title: "请选择添加方式(建议歌词文件一起导入)",
  1599. sheets: [
  1600. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  1601. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1602. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1603. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1604. ],
  1605. maskColor: Color.Transparent,
  1606. backgroundColor: $r('app.color.bg_card'),
  1607. transition: AnimationHelper.transitionInDown(555),
  1608. onAction: (index) => {
  1609. switch (index) {
  1610. case 0:
  1611. if (this.modeType === 0) {
  1612. this.showMkDialog()
  1613. } else {
  1614. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  1615. }
  1616. break;
  1617. case 1:
  1618. this.callFilePickerSelectFile()
  1619. break;
  1620. case 2:
  1621. this.showTips()
  1622. break;
  1623. case 3:
  1624. this.goSelectMusic()
  1625. break;
  1626. }
  1627. }
  1628. })
  1629. }
  1630. //拉起音频
  1631. goSelectMusic() {
  1632. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1633. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1634. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1635. ) {
  1636. ToastUtil.showToast('暂时不支持该设备')
  1637. return
  1638. }
  1639. try {
  1640. let documentSelectOptions = new picker.DocumentSelectOptions();
  1641. documentSelectOptions.authMode = true
  1642. documentSelectOptions.multiAuthMode = true
  1643. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1644. let documentPicker = new picker.DocumentViewPicker(this.context);
  1645. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1646. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1647. this.saveVideoDatas(documentSelectResult)
  1648. }
  1649. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1650. JSON.stringify(documentSelectResult));
  1651. }).catch((err: BusinessError) => {
  1652. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1653. });
  1654. } catch (error) {
  1655. let err: BusinessError = error as BusinessError;
  1656. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1657. }
  1658. }
  1659. async showTips() {
  1660. try {
  1661. this.getUIContext().getPromptAction().showDialog({
  1662. title: '导入指南',
  1663. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1664. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1665. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1666. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1667. buttons: [
  1668. {
  1669. text: '知道了',
  1670. color: '#000000'
  1671. },
  1672. ]
  1673. }, (err, data) => {
  1674. if (err) {
  1675. console.error('showDialog err: ' + err);
  1676. return;
  1677. }
  1678. console.info('showDialog success callback, click button: ' + data.index);
  1679. });
  1680. } catch (error) {
  1681. let message = (error as BusinessError).message;
  1682. let code = (error as BusinessError).code;
  1683. console.error(`showDialog args error code is ${code}, message is ${message}`);
  1684. };
  1685. // DialogHelper.showTipsDialog({
  1686. // title: '使用提示:自动导入教程',
  1687. //
  1688. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1689. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1690. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1691. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1692. // onAction: (action) => {
  1693. // if (action == DialogAction.TWO) {
  1694. // PreferencesUtil.putSync('isFirstMusic', false)
  1695. // router.pushUrl({
  1696. // url: 'pages/ScanFilePage'
  1697. // });
  1698. // }
  1699. // }
  1700. // })
  1701. }
  1702. showMkDialog() {
  1703. DialogHelper.showTextInputDialog({
  1704. title: '新建歌单',
  1705. maskColor: Color.Transparent,
  1706. text: '',
  1707. transition: AnimationHelper.transitionInDown(666),
  1708. onChange: (text) => {
  1709. console.error("onChange: " + text);
  1710. },
  1711. onAction: (action, dialogId, content) => {
  1712. // ToastUtil.showToast('content = ' +content)
  1713. if (action == DialogAction.TWO) {
  1714. const newName = content
  1715. const newPath = this.currentPath + '/' + newName
  1716. FileUtil.mkdir(newPath, true).then(() => {
  1717. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1718. this.getSortedFiles(this.currentPath)
  1719. }).catch((error: BusinessError) => {
  1720. console.error(error.message);
  1721. });
  1722. }
  1723. }
  1724. })
  1725. }
  1726. @State progress: number = 0;
  1727. async saveVideoDatas(uris:string[],isOpen?:boolean){
  1728. if (ArrayUtil.isEmpty(uris)) {
  1729. return;
  1730. }
  1731. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  1732. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath){
  1733. this.saveVideoDatasToDownLoad(uris,isOpen)
  1734. return
  1735. }
  1736. // 初始化进度条
  1737. this.progress = 0;
  1738. DialogHelper.showLoadingProgress({
  1739. progress: this.progress,
  1740. backCancel: false,
  1741. autoCancel: false,
  1742. loadColor: $r('app.color.title_bar_bg'),
  1743. fontColor: $r('app.color.title_bar_bg')
  1744. });
  1745. // 计算处理总数用于进度计算
  1746. const totalItems = uris.length;
  1747. let processedItems = 0;
  1748. for (let i = 0; i < uris.length; i++) {
  1749. let filePath = uris[i];
  1750. try {
  1751. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  1752. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1753. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  1754. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1755. console.info('onecold saveVideoDatas filePath = ' + filePath)
  1756. if (!filePath.includes(this.rootPath)) {
  1757. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  1758. mediaItem.parentPath = this.currentPath;
  1759. }
  1760. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  1761. this.table.insert(mediaItem, (id: number) => {
  1762. // 插入完成回调
  1763. });
  1764. }
  1765. }
  1766. // 更新进度
  1767. processedItems++;
  1768. this.progress = Math.floor((processedItems / totalItems) * 100);
  1769. DialogHelper.updateLoading(' 正在处理', this.progress);
  1770. } catch (error) {
  1771. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1772. // 即使出错也更新进度
  1773. processedItems++;
  1774. this.progress = Math.floor((processedItems / totalItems) * 100);
  1775. DialogHelper.updateLoading(' 正在处理', this.progress);
  1776. }
  1777. }
  1778. // 关闭进度条
  1779. DialogHelper.closeLoading();
  1780. this.isZero = false
  1781. // 删除目标路径缓存
  1782. setTimeout(() => {
  1783. this.cache.delete(this.currentPath);
  1784. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  1785. this.setButtonStatus()
  1786. }, 500);
  1787. }
  1788. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  1789. if (ArrayUtil.isEmpty(uris)) {
  1790. return;
  1791. }
  1792. let newUris: string[] = [];
  1793. this.progress = 0
  1794. DialogHelper.showLoadingProgress({
  1795. progress: this.progress,
  1796. backCancel: false,
  1797. autoCancel: false,
  1798. loadColor: this.themeColor,
  1799. fontColor: this.themeColor
  1800. });
  1801. // 计算所有文件的总大小
  1802. let totalSize = 0;
  1803. for (let uri of uris) {
  1804. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1805. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1806. await fileIo.close(sourceFile.fd);
  1807. }
  1808. let totalRead = 0;
  1809. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1810. Logger.info(TAG, 'destPath uri: ' + destPath);
  1811. for (let i = 0; i < uris.length; i++) {
  1812. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1813. Logger.info(TAG, 'filePath uri: ' + filePath);
  1814. newUris.push(filePath);
  1815. try {
  1816. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1817. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1818. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1819. const buffer = new ArrayBuffer(buffSize);
  1820. let len = await fileIo.read(sourceFile.fd, buffer);
  1821. while (len > 0) {
  1822. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1823. totalRead += len;
  1824. // 计算总进度
  1825. this.progress = Math.floor((totalRead / totalSize) * 100);
  1826. DialogHelper.updateLoading('正在导入', this.progress);
  1827. len = await fileIo.read(sourceFile.fd, buffer);
  1828. }
  1829. await fileIo.close(sourceFile.fd);
  1830. await fileIo.close(destFile.fd);
  1831. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1832. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1833. let mediaItem: VideoItem =
  1834. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1835. this.table.insert(mediaItem, (id: number) => {
  1836. // 删除目标路径缓存
  1837. this.cache.delete(this.currentPath);
  1838. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1839. });
  1840. }
  1841. }
  1842. } catch (error) {
  1843. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1844. }
  1845. }
  1846. DialogHelper.closeLoading()
  1847. this.isZero = false
  1848. // setTimeout(() => {
  1849. // // 删除目标路径缓存
  1850. // this.cache.delete(this.currentPath);
  1851. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1852. // }, 500);
  1853. Logger.info(TAG, 'scan select video result:' + newUris)
  1854. }
  1855. //拉起音频
  1856. // goSelectMusic(){
  1857. //
  1858. // try {
  1859. // let audioSelectOptions = new picker.AudioSelectOptions();
  1860. // let audioPicker = new picker.AudioViewPicker(this.context);
  1861. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1862. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1863. // this.saveVideoDatas(audioSelectResult)
  1864. // }
  1865. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1866. // }).catch((err: BusinessError) => {
  1867. //
  1868. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1869. // });
  1870. // } catch (error) {
  1871. // let err: BusinessError = error as BusinessError;
  1872. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1873. // }
  1874. //
  1875. //
  1876. //
  1877. // }
  1878. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1879. if (!item) {
  1880. return undefined;
  1881. }
  1882. try {
  1883. let selectUris: Array<string> = [];
  1884. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1885. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1886. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1887. photoSelectOptions.maxSelectNumber = 1;
  1888. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1889. selectUris = photoSelectResult.photoUris;
  1890. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1891. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1892. console.info('file fd: ' + file.fd);
  1893. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1894. let imagePath = this.context.filesDir + FileUtil.separator + name
  1895. imagePath = fileUri.getUriFromPath(imagePath)
  1896. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1897. fileIo.copyFileSync(file.fd, file2.fd)
  1898. fileIo.closeSync(file);
  1899. fileIo.closeSync(file2);
  1900. if (item.filePath == this.currentSong?.filePath) {
  1901. this.cover = imagePath
  1902. }
  1903. if (item) {
  1904. item.pixelMapPath = imagePath
  1905. }
  1906. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1907. if (success) {
  1908. this.doUpdateData()
  1909. console.log("onecold 更新音乐封面成功,数据库已同步");
  1910. } else {
  1911. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1912. }
  1913. });
  1914. LogUtil.debug("onecold this.cover =" + this.cover)
  1915. return FileUtil.getFilePath(imagePath); // Return the image path here
  1916. } catch (err) {
  1917. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1918. return undefined;
  1919. }
  1920. }
  1921. // 拉起picker选择文件管理器
  1922. async callFilePickerSelectFile(): Promise<void> {
  1923. try {
  1924. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1925. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1926. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1927. } else {
  1928. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1929. }
  1930. let documentPicker = new picker.DocumentViewPicker();
  1931. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1932. Logger.info(TAG,
  1933. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1934. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1935. this.saveVideoDatas(DocumentSelectResult)
  1936. }
  1937. }).catch((err: BusinessError) => {
  1938. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1939. });
  1940. } catch (err) {
  1941. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1942. }
  1943. }
  1944. //重命名的对话框
  1945. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1946. if(!item.filePath.includes(this.packName)){
  1947. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  1948. return
  1949. }
  1950. DialogHelper.showTextInputDialog({
  1951. title: '重命名',
  1952. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1953. maskColor: Color.Transparent,
  1954. backgroundColor: Color.Grey,
  1955. transition: AnimationHelper.transitionInDown(666),
  1956. onChange: (text) => {
  1957. console.error("onChange: " + text);
  1958. },
  1959. onAction: (action, dialogId, content) => {
  1960. // ToastUtil.showToast('content = ' +content)
  1961. if (action == DialogAction.TWO) {
  1962. const newName = content
  1963. const newPath = this.currentPath + '/' + newName
  1964. console.log("onecold item = " + item.type);
  1965. this.doReName(index, newName, filePath, newPath, item)
  1966. }
  1967. }
  1968. })
  1969. }
  1970. //剪切 移动到另个文件夹的对话框
  1971. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1972. Logger.info('onecold showCutDialog')
  1973. let mList: Array<string> = []
  1974. let rPath = this.rootPath
  1975. if (isCurrent) {
  1976. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1977. rPath = this.currentPath
  1978. } else {
  1979. mList = Utility.getNameList(this.dirList);
  1980. rPath = this.rootPath
  1981. }
  1982. let dataBean = new BubbleBean()
  1983. dataBean.data = mList
  1984. dataBean.color = this.themeColor
  1985. dataBean.onItemClick = (i) => {
  1986. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1987. Logger.info('newPath = ' + newPath)
  1988. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1989. ToastUtil.showToast('移动成功')
  1990. this.table.deleteData(item, () => {
  1991. });
  1992. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1993. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1994. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1995. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1996. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1997. this.table.insert(newItem, (id: number) => {
  1998. //加入数据库
  1999. });
  2000. }
  2001. this.cache.delete(this.currentPath); // 删除原路径缓存
  2002. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2003. this.getSortedFiles(this.currentPath, true)
  2004. }).catch((error: BusinessError) => {
  2005. console.error(error.message);
  2006. });
  2007. XPopup.dismissTop()
  2008. }
  2009. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2010. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2011. popupPosition = PopupPosition.TOP
  2012. }
  2013. if (index <= 3) {
  2014. popupPosition = PopupPosition.BOTTOM
  2015. }
  2016. let pup: XPopup
  2017. if (this.isDarkMode) {
  2018. pup = XPopup.Builder()
  2019. .setPopupPosition(popupPosition)
  2020. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2021. .setBackgroundColor(Color.Black)
  2022. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2023. .show()
  2024. } else {
  2025. pup = XPopup.Builder()
  2026. .setPopupPosition(popupPosition)
  2027. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2028. .setBackgroundColor(Color.White)
  2029. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2030. .show()
  2031. }
  2032. }
  2033. //复制 到另个文件夹的对话框
  2034. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2035. Logger.info('onecoldv showCopyDialog')
  2036. let mList: Array<string> = []
  2037. let rPath = this.rootPath
  2038. if (isCurrent) {
  2039. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2040. rPath = this.currentPath
  2041. } else {
  2042. mList = Utility.getNameList(this.dirList);
  2043. rPath = this.rootPath
  2044. }
  2045. let dataBean = new BubbleBean()
  2046. dataBean.data = mList
  2047. dataBean.isCopy = true
  2048. dataBean.color = this.themeColor
  2049. dataBean.onItemClick = (i) => {
  2050. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2051. Logger.info('newPath = ' + newPath)
  2052. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2053. ToastUtil.showToast('复制成功')
  2054. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2055. this.getSortedFiles(this.currentPath)
  2056. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2057. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2058. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2059. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2060. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2061. this.table.insert(newItem, (id: number) => {
  2062. //加入数据库
  2063. });
  2064. }
  2065. }).catch((error: BusinessError) => {
  2066. console.error(error.message);
  2067. });
  2068. XPopup.dismissTop()
  2069. }
  2070. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2071. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2072. popupPosition = PopupPosition.TOP
  2073. }
  2074. if (index <= 3) {
  2075. popupPosition = PopupPosition.BOTTOM
  2076. }
  2077. let pup: XPopup
  2078. if (this.isDarkMode) {
  2079. pup = XPopup.Builder()
  2080. .setPopupPosition(popupPosition)
  2081. .atView(id)
  2082. .setMaxHeight('60%')
  2083. .setBackgroundColor(Color.Black)
  2084. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2085. .show();
  2086. } else {
  2087. pup = XPopup.Builder()
  2088. .setPopupPosition(popupPosition)
  2089. .atView(id)
  2090. .setMaxHeight('60%')
  2091. .setBackgroundColor(Color.White)
  2092. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2093. .show();
  2094. }
  2095. }
  2096. //重命名索引index的视频
  2097. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2098. FileUtil.rename(oldPath, newPath).then(async () => {
  2099. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2100. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2101. //如果是文件夹先删除源数据,再添加新数据
  2102. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2103. if (success) {
  2104. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2105. } else {
  2106. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2107. }
  2108. });
  2109. this.scanDirectory(newPath)
  2110. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2111. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2112. if (success) {
  2113. console.log(" onecold 重命名成功,数据库已同步");
  2114. } else {
  2115. console.error(" onecold 重命名数据库失败原因: " + error);
  2116. }
  2117. });
  2118. }
  2119. let mediaItem: VideoItem =
  2120. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2121. this.videoLocalList[index] = mediaItem;
  2122. }
  2123. this.cache.delete(this.currentPath)
  2124. this.getSortedFiles(this.currentPath, true)
  2125. }).catch((error: BusinessError) => {
  2126. console.error(error.message);
  2127. });
  2128. }
  2129. build() {
  2130. Scroll() {
  2131. Column() {
  2132. if (!this.isShowCoverHeader()) {
  2133. Column() {
  2134. Line().width('100%').height('100%')
  2135. }
  2136. .height(this.topRectHeight)
  2137. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  2138. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  2139. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2140. TitleBar({ model: $titleBarModel })
  2141. .id('pup_positon_music')
  2142. }
  2143. Stack() {
  2144. Column() {
  2145. XComponent({
  2146. id: 'xcomponentId',
  2147. type: 'surface',
  2148. libraryname: 'ijkplayer_napi',
  2149. controller: this.xcomponentController
  2150. })
  2151. .onLoad((event?: object) => {
  2152. if (!!event) {
  2153. this.initDelayPlay(event);
  2154. }
  2155. })
  2156. .onKeyEvent((event?: KeyEvent) => {
  2157. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2158. if (!event || event.type !== KeyType.Down) {
  2159. return;
  2160. }
  2161. //空格键 Space key controls pause/play
  2162. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  2163. console.info('onecold playOrPause 1999')
  2164. this.playOrPause()
  2165. }
  2166. // Right-click to fast forward
  2167. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2168. this.sessionFastForwardCallback(15);
  2169. }
  2170. // Left-click to rewind
  2171. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2172. this.sessionRewindCallback(15);
  2173. }
  2174. })
  2175. .onDestroy(() => {
  2176. })
  2177. .width('100%')// .width(this.videoWidth)
  2178. .aspectRatio(this.videoAspectRatio)
  2179. }
  2180. .aspectRatio(this.videoAspectRatio)
  2181. .justifyContent(FlexAlign.Center)
  2182. .backgroundColor(Color.Transparent)
  2183. .visibility(Visibility.Hidden)
  2184. .height(CommonConstants.FULL_PERCENT)
  2185. .width(CommonConstants.FULL_PERCENT)
  2186. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2187. height:this.isLandscape?'80%': '43%',
  2188. dragBar: true,
  2189. showClose: true,
  2190. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2191. blurStyle:BlurStyle.Thin,
  2192. backgroundColor:Color.Transparent,
  2193. title: { title: 'AB循环' }
  2194. })
  2195. Stack() {
  2196. Row() {
  2197. Blank()
  2198. .layoutWeight(1)
  2199. IndexerView(
  2200. {
  2201. indexArray: DEFAULT_INDEX,
  2202. selectedIndex: this.selectedIndex,
  2203. textSize: 12,
  2204. selectedColor: "#ff419ee5",
  2205. normalColor: "#ffa0a0a0",
  2206. floatSelectedTextColor: "#ffffff",
  2207. floatSelectedViewColor: "#ff419ee5",
  2208. onIndexChanged: (index) => {
  2209. this.listScroller.scrollToIndex(index)
  2210. }
  2211. })
  2212. .width(24)
  2213. .height("50%")
  2214. }.visibility(Visibility.None)
  2215. Column() {
  2216. if (!this.isShowCoverHeader()) {
  2217. this.tabTitle()
  2218. }
  2219. if(this.twoFingerType==4){
  2220. this.getWaterView()
  2221. }else{
  2222. if(this.isGridMusic){
  2223. this.getGridView()
  2224. }else {
  2225. this.getList()
  2226. }
  2227. }
  2228. if (this.modeType ==0||this.modeType==4) {
  2229. Column() {
  2230. emptyView(this.themeColor)
  2231. }
  2232. .position({ top:this.isShowCoverHeader() ? 300 : 180 })
  2233. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2234. .animation({ duration: 500 }),
  2235. TransitionEffect.scale({ x: 0, y: 0 })))
  2236. .justifyContent(FlexAlign.Center)
  2237. .opacity(this.isZero ? 1 : 0)
  2238. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2239. ? Visibility.Visible : Visibility.None)
  2240. .animation({
  2241. duration: 500,
  2242. curve: 'ease-in-out' // 可选动画曲线
  2243. })
  2244. .width('100%')
  2245. }
  2246. }
  2247. .layoutWeight(1)
  2248. .height('100%')
  2249. }
  2250. .layoutWeight(1)
  2251. .height('100%')
  2252. Row() {
  2253. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2254. .width(50)
  2255. .height(50)
  2256. .fontSize(13)
  2257. .margin({ top: 10, bottom: 10, right: 6 })
  2258. .backgroundColor(this.themeColor)
  2259. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2260. .onClick(() => {
  2261. if (this.isAllSelected) {
  2262. // 全不选
  2263. this.selectedFiles = [];
  2264. } else {
  2265. // 全选
  2266. this.selectedFiles = [...this.getCurFileList()];
  2267. }
  2268. this.isAllSelected = !this.isAllSelected;
  2269. })
  2270. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2271. .width(90)
  2272. .height(50)
  2273. .fontSize(13)
  2274. .margin({ top: 10, bottom: 10, right: 6 })
  2275. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2276. .backgroundColor(this.themeColor)
  2277. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2278. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2279. })
  2280. .onClick(() => {
  2281. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2282. this.isOneKeyTags = !this.isOneKeyTags
  2283. // }else{
  2284. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌')
  2285. // }
  2286. })
  2287. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2288. .width(50)
  2289. .height(50)
  2290. .fontSize(11)
  2291. .margin({ top: 10, bottom: 10, right: 6 })
  2292. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2293. .backgroundColor(this.themeColor)
  2294. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2295. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2296. })
  2297. .onClick(() => {
  2298. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2299. this.isMergeAudio = !this.isMergeAudio
  2300. }else{
  2301. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2302. }
  2303. })
  2304. // Button('乱码修复', { type: ButtonType.Capsule, stateEffect: true })
  2305. // .width(90)
  2306. // .height(50)
  2307. // .fontSize(13)
  2308. // .margin({ top: 10, bottom: 10, right: 6 })
  2309. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2310. // .backgroundColor(this.themeColor)
  2311. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2312. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2313. // })
  2314. // .onClick(() => {
  2315. // this.isFixMessy = !this.isFixMessy
  2316. // })
  2317. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2318. // .width('35%')
  2319. // .height(60)
  2320. // .id('music_cut')
  2321. // .margin({ top: 10, bottom: 10, right: 6 })
  2322. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2323. // .backgroundColor(this.themeColor)
  2324. // .onClick(() => {
  2325. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2326. // })
  2327. //
  2328. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2329. // .width('35%')
  2330. // .height(60)
  2331. // .id('music_cut_current')
  2332. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2333. // .margin({ top: 10, bottom: 10, right: 6 })
  2334. // .backgroundColor(this.themeColor)
  2335. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2336. // .onClick(() => {
  2337. //
  2338. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2339. // })
  2340. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2341. // .width('35%')
  2342. // .height(60)
  2343. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2344. // .margin({ top: 10, bottom: 10, right: 6 })
  2345. // .backgroundColor(this.themeColor)
  2346. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2347. // .onClick(() => {
  2348. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2349. // })
  2350. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2351. .width(50)
  2352. .height(50)
  2353. .fontSize(13)
  2354. .margin({ top: 10, bottom: 10, right: 6 })
  2355. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2356. .backgroundColor(this.themeColor)
  2357. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2358. .onClick(() => {
  2359. this.showWarnIsDelete()
  2360. })
  2361. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2362. .width(50)
  2363. .height(50)
  2364. .fontSize(13)
  2365. .margin({ top: 10, bottom: 10, right: 6 })
  2366. .backgroundColor(this.themeColor)
  2367. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2368. .onClick(() => {
  2369. this.selectedFiles = [];
  2370. this.isAllSelected = false
  2371. this.isMultiSelect = false
  2372. })
  2373. }
  2374. .width('100%')
  2375. .justifyContent(FlexAlign.Center)
  2376. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2377. .opacity(this.isMultiSelect ? 1 : 0)
  2378. .animation({
  2379. duration: 666,
  2380. curve: 'ease-in-out' // 可选动画曲线
  2381. })
  2382. .position(this.isShowCoverHeader() ? { bottom: 78 }
  2383. : { bottom: this.isPhoneLan() ? 130 : 170 }) // 将 Row 固定在底部
  2384. }
  2385. .width('100%')
  2386. .height('100%')
  2387. .alignContent(Alignment.Top)
  2388. Column() {
  2389. this.PlayController()
  2390. }
  2391. .hitTestBehavior(HitTestMode.Transparent)
  2392. .position({ bottom: 0 }) // 将 Row 固定在底部
  2393. .opacity(this.barBottomOpacity)
  2394. }
  2395. .width('100%')
  2396. .height('100%')
  2397. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2398. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2399. .backgroundImagePosition(Alignment.Center)
  2400. .backdropBlur(this.blurValue)
  2401. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2402. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2403. }
  2404. }
  2405. @Builder
  2406. TagsContentCoverBuilder() {
  2407. Scroll() {
  2408. Column() {
  2409. TagsContentCover(
  2410. {
  2411. selectedFiles:this.selectedFiles,
  2412. isOneKeyTags:this.isOneKeyTags,
  2413. table:this.table,
  2414. onTagsResult:(result: boolean)=>{
  2415. this.isMultiSelect = false
  2416. if(result){//如果嵌入成功,更新数据
  2417. setTimeout(()=>{
  2418. this.doUpdateData()
  2419. },500)
  2420. }
  2421. }
  2422. }
  2423. )
  2424. }
  2425. }
  2426. .width('100%')
  2427. .height('100%')
  2428. }
  2429. @Builder
  2430. FixMessyViewBuilder() {
  2431. Scroll() {
  2432. Column() {
  2433. FixMessyView(
  2434. {
  2435. selectedFiles:this.selectedFiles,
  2436. isFixMessy:this.isFixMessy,
  2437. onFixResult:(result: boolean)=>{
  2438. this.isMultiSelect = false
  2439. if(result){//如果嵌入成功,更新数据
  2440. this.deleteCache(this.currentPath)
  2441. this.doUpdateData()
  2442. }
  2443. }
  2444. }
  2445. )
  2446. }
  2447. }
  2448. .width('100%')
  2449. .height('100%')
  2450. }
  2451. //剪辑音频
  2452. @Builder
  2453. EditAudioBuilder(item:VideoItem) {
  2454. Scroll() {
  2455. Column() {
  2456. EditAudio(
  2457. {
  2458. mVideoItem:item,
  2459. currentPath:this.currentPath,
  2460. videoUrl:this.videoUrl,
  2461. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2462. currentTime:this.currentTime,
  2463. progressValue:this.progressValue,
  2464. onBack:()=>{
  2465. this.isEditAudio = !this.isEditAudio
  2466. },
  2467. onSeeOutputPath:(outPutPath:string)=>{
  2468. this.isEditAudio = !this.isEditAudio
  2469. this.longItemFilePath = ''
  2470. this.modeType = 0
  2471. this.isShowFileName = true
  2472. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2473. },
  2474. onPlayOrPause:()=>{
  2475. if(this.videoUrl==item.filePath){
  2476. this.playOrPause()
  2477. }else{//如果不是当前播放的,则播放该文件
  2478. this.videoUrl==item.filePath
  2479. this.doPlay(item,0,false,true)
  2480. }
  2481. },
  2482. onSliderChange:(value:number)=>{
  2483. if(this.videoUrl!=item.filePath){
  2484. this.videoUrl==item.filePath
  2485. return
  2486. }
  2487. this.isSeekTo = true;
  2488. this.mDestroyPage = false;
  2489. this.showLoadIng();
  2490. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  2491. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2492. this.seekTo(seekValue + "");
  2493. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  2494. this.isSeekTo = false;
  2495. },
  2496. onResult:(result: boolean,outPath:string)=>{
  2497. if(result){//如果剪辑成功,更新数据
  2498. this.doUpdateData()
  2499. }else{
  2500. ToastUtil.showToast('剪辑失败')
  2501. }
  2502. }
  2503. }
  2504. )
  2505. }
  2506. }
  2507. .width('100%')
  2508. .height('100%')
  2509. }
  2510. //提取伴奏
  2511. @Builder
  2512. ConverterBuilder(item:VideoItem) {
  2513. Scroll() {
  2514. Column() {
  2515. AudioFormatConverter(
  2516. {
  2517. mVideoItem:item,
  2518. videoUrl:this.videoUrl,
  2519. currentPath:this.currentPath,
  2520. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2521. currentTime:this.currentTime,
  2522. progressValue:this.progressValue,
  2523. onBack:()=>{
  2524. this.isConverter = !this.isConverter
  2525. this.longItemFilePath = ''
  2526. },
  2527. onPlayOrPause:()=>{
  2528. if(this.videoUrl==item.filePath){
  2529. this.playOrPause()
  2530. }else{//如果不是当前播放的,则播放该文件
  2531. this.videoUrl==item.filePath
  2532. this.doPlay(item,0,false,true)
  2533. }
  2534. },
  2535. onSeeOutputPath:(outPutPath:string)=>{
  2536. this.isConverter = !this.isConverter
  2537. this.longItemFilePath = ''
  2538. this.modeType = 0
  2539. this.isShowFileName = true
  2540. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2541. },
  2542. onSliderChange:(value:number)=>{
  2543. if(this.videoUrl!=item.filePath){
  2544. this.videoUrl==item.filePath
  2545. return
  2546. }
  2547. this.isSeekTo = true;
  2548. this.mDestroyPage = false;
  2549. this.showLoadIng();
  2550. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2551. this.seekTo(seekValue + "");
  2552. this.isSeekTo = false;
  2553. },
  2554. onResult:(result: boolean,outPath:string)=>{
  2555. if(result){//如果成功,更新数据
  2556. this.doUpdateData()
  2557. }else{
  2558. ToastUtil.showToast('格式转化失败')
  2559. }
  2560. }
  2561. }
  2562. )
  2563. }
  2564. }
  2565. .width('100%')
  2566. .height('100%')
  2567. }
  2568. //提取伴奏
  2569. @Builder
  2570. ExtractAccBuilder(item:VideoItem) {
  2571. Scroll() {
  2572. Column() {
  2573. ExtractAccompaniment(
  2574. {
  2575. mVideoItem:item,
  2576. currentPath:this.currentPath,
  2577. videoUrl:this.videoUrl,
  2578. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2579. currentTime:this.currentTime,
  2580. progressValue:this.progressValue,
  2581. onBack:()=>{
  2582. this.isExtractAcc = !this.isExtractAcc
  2583. this.longItemFilePath = ''
  2584. },
  2585. onPlayOrPause:()=>{
  2586. if(this.videoUrl==item.filePath){
  2587. this.playOrPause()
  2588. }else{//如果不是当前播放的,则播放该文件
  2589. this.videoUrl==item.filePath
  2590. this.doPlay(item,0,false,true)
  2591. }
  2592. },
  2593. onSeeOutputPath:(outPutPath:string)=>{
  2594. this.isExtractAcc = !this.isExtractAcc
  2595. this.longItemFilePath = ''
  2596. this.modeType = 0
  2597. this.isShowFileName = true
  2598. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2599. },
  2600. onSliderChange:(value:number)=>{
  2601. if(this.videoUrl!=item.filePath){
  2602. this.videoUrl==item.filePath
  2603. return
  2604. }
  2605. this.isSeekTo = true;
  2606. this.mDestroyPage = false;
  2607. this.showLoadIng();
  2608. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2609. this.seekTo(seekValue + "");
  2610. this.isSeekTo = false;
  2611. },
  2612. onResult:(result: boolean,outPath:string)=>{
  2613. if(result){//如果成功,更新数据
  2614. this.doUpdateData()
  2615. }else{
  2616. ToastUtil.showToast('提取伴奏失败')
  2617. }
  2618. }
  2619. }
  2620. )
  2621. }
  2622. }
  2623. .width('100%')
  2624. .height('100%')
  2625. }
  2626. //AI人声分离
  2627. @Builder
  2628. AiBuilder(item:VideoItem) {
  2629. Scroll() {
  2630. Column() {
  2631. AIVoiceSeparation(
  2632. {
  2633. mVideoItem:item,
  2634. videoUrl:this.videoUrl,
  2635. currentPath:this.currentPath,
  2636. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2637. currentTime:this.currentTime,
  2638. progressValue:this.progressValue,
  2639. onBack:()=>{
  2640. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  2641. this.longItemFilePath = ''
  2642. },
  2643. onPlayOrPause:()=>{
  2644. if(this.videoUrl==item.filePath||this.isPlaying){
  2645. this.playOrPause()
  2646. }else{//如果不是当前播放的,则播放该文件
  2647. this.videoUrl==item.filePath
  2648. this.doPlay(item,0,false,true)
  2649. }
  2650. },
  2651. onPlayPath:(path:string)=>{
  2652. this.videoUrl==path
  2653. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  2654. if(itemP)
  2655. this.doPlay(itemP,0,false,true)
  2656. },
  2657. onSeeOutputPath:(outPutPath:string)=>{
  2658. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  2659. this.longItemFilePath = ''
  2660. this.modeType = 0
  2661. this.isShowFileName = true
  2662. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2663. },
  2664. onSliderChange:(value:number)=>{
  2665. if(this.videoUrl!=item.filePath){
  2666. this.videoUrl==item.filePath
  2667. return
  2668. }
  2669. this.isSeekTo = true;
  2670. this.mDestroyPage = false;
  2671. this.showLoadIng();
  2672. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2673. this.seekTo(seekValue + "");
  2674. this.isSeekTo = false;
  2675. },
  2676. onResult:(result: boolean,outPath:string)=>{
  2677. if(result){//如果成功,更新数据
  2678. this.doUpdateData()
  2679. }else{
  2680. ToastUtil.showToast('Ai人声分离失败')
  2681. }
  2682. }
  2683. }
  2684. )
  2685. }
  2686. }
  2687. .width('100%')
  2688. .height('100%')
  2689. }
  2690. //提取视频中的音频
  2691. @Builder
  2692. extractAudioFromVideoBuilder(item:VideoItem) {
  2693. Scroll() {
  2694. Column() {
  2695. ExtractAudioFromVideo(
  2696. {
  2697. mVideoItem:item,
  2698. currentPath:this.currentPath,
  2699. videoUrl:this.videoUrl,
  2700. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2701. currentTime:this.currentTime,
  2702. progressValue:this.progressValue,
  2703. onBack:()=>{
  2704. this.isExtractAudio = !this.isExtractAudio
  2705. this.longItemFilePath = ''
  2706. },
  2707. onPlayOrPause:()=>{
  2708. if(this.videoUrl==item.filePath){
  2709. this.playOrPause()
  2710. }else{//如果不是当前播放的,则播放该文件
  2711. this.videoUrl==item.filePath
  2712. this.doPlay(item,0,false,true)
  2713. }
  2714. },
  2715. onSeeOutputPath:(outPutPath:string)=>{
  2716. this.isExtractAudio = !this.isExtractAudio
  2717. this.longItemFilePath = ''
  2718. this.modeType = 0
  2719. this.isShowFileName = true
  2720. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2721. },
  2722. onSliderChange:(value:number)=>{
  2723. if(this.videoUrl!=item.filePath){
  2724. this.videoUrl==item.filePath
  2725. return
  2726. }
  2727. this.isSeekTo = true;
  2728. this.mDestroyPage = false;
  2729. this.showLoadIng();
  2730. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  2731. this.seekTo(seekValue + "");
  2732. this.isSeekTo = false;
  2733. },
  2734. onResult:(result: boolean,outPath:string)=>{
  2735. if(result){//如果成功,更新数据
  2736. this.doUpdateData()
  2737. }else{
  2738. ToastUtil.showToast('提取音频失败')
  2739. }
  2740. }
  2741. }
  2742. )
  2743. }
  2744. }
  2745. .width('100%')
  2746. .height('100%')
  2747. }
  2748. //合并音频
  2749. @Builder
  2750. MergeAudioBuilder() {
  2751. Scroll() {
  2752. Column() {
  2753. MergeAudio(
  2754. {
  2755. videoUrl:this.videoUrl,
  2756. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  2757. currentPath:this.currentPath,
  2758. selectedFiles:this.selectedFiles,
  2759. currentTime:this.currentTime,
  2760. progressValue:this.progressValue,
  2761. onBack:()=>{
  2762. this.isMergeAudio = !this.isMergeAudio
  2763. this.longItemFilePath = ''
  2764. },
  2765. // onPlayPath:(path:string)=>{
  2766. // if(this.videoUrl==item.filePath){
  2767. // this.playOrPause()
  2768. // }else{//如果不是当前播放的,则播放该文件
  2769. // this.videoUrl==item.filePath
  2770. // this.doPlay(item,0,false,true)
  2771. // }
  2772. //
  2773. // },
  2774. onSeeOutputPath:(outPutPath:string)=>{
  2775. this.isMergeAudio = !this.isMergeAudio
  2776. this.longItemFilePath = ''
  2777. this.modeType = 0
  2778. this.isShowFileName = true
  2779. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  2780. },
  2781. onResult:(result: boolean,outPath:string)=>{
  2782. if(result){//如果成功,更新数据
  2783. this.doUpdateData()
  2784. }else{
  2785. if(this.selectedFiles.length>=3){
  2786. ToastUtil.showToast('合并数量太多导致失败')
  2787. }else{
  2788. ToastUtil.showToast('合并失败')
  2789. }
  2790. }
  2791. }
  2792. }
  2793. )
  2794. }
  2795. }
  2796. .width('100%')
  2797. .height('100%')
  2798. }
  2799. asyncCurrentPathData() {
  2800. if (this.modeType == 0) {
  2801. workerInstance.postMessage({
  2802. code: 1,
  2803. data1: this.context,
  2804. data2: this.currentPath,
  2805. data3: this.lockPath,
  2806. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2807. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  2808. });
  2809. }
  2810. }
  2811. // 处理文件选择的函数
  2812. handleFileSelection(item: VideoItem, checked: boolean) {
  2813. if (checked) {
  2814. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2815. this.selectedFiles.push(item);
  2816. }
  2817. } else {
  2818. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2819. if (index > -1) {
  2820. this.selectedFiles.splice(index, 1);
  2821. }
  2822. }
  2823. }
  2824. private deleteComponentId: number = 0
  2825. //多选删除文件
  2826. showWarnIsDelete(){
  2827. this.getUIContext().getPromptAction().openCustomDialog({
  2828. builder: () => {
  2829. this.deleteComptentBuilder()
  2830. },
  2831. isModal:true,
  2832. showInSubWindow:false,
  2833. maskColor: Color.Transparent,
  2834. dialogTransition: // 设置弹窗内容显示的过渡效果
  2835. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  2836. .animation({ duration: 600, curve: Curve.Smooth }),
  2837. maskTransition: // 设置蒙层显示的过渡效果
  2838. TransitionEffect.opacity(0)
  2839. .animation({ duration: 600, curve: Curve.Smooth })
  2840. }).then((dialogId: number) => {
  2841. this.deleteComponentId = dialogId
  2842. })
  2843. .catch((error: BusinessError) => {
  2844. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  2845. })
  2846. }
  2847. @Builder
  2848. deleteComptentBuilder(){
  2849. DeleteComptent({
  2850. selectedFiles:this.selectedFiles,
  2851. onCancel:()=>{
  2852. this.isMultiSelect = false
  2853. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2854. },
  2855. onDeleteResult:(result: boolean)=>{
  2856. this.isMultiSelect = false
  2857. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2858. if(result){//如果删除成功,更新数据
  2859. this.selectedFiles = [];
  2860. this.isAllSelected = false
  2861. this.cache.delete(this.currentPath);
  2862. this.getSortedFiles(this.currentPath, true);
  2863. }
  2864. }
  2865. })
  2866. }
  2867. //多选移动文件
  2868. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2869. Logger.info('onecold showCutDialogForMultipleFiles')
  2870. let mList: Array<string> = []
  2871. let rPath = this.rootPath
  2872. if (isCurrent) {
  2873. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2874. rPath = this.currentPath
  2875. } else {
  2876. mList = Utility.getNameList(this.dirList);
  2877. rPath = this.rootPath
  2878. }
  2879. let dataBean = new BubbleBean();
  2880. dataBean.data = mList;
  2881. dataBean.color = this.themeColor
  2882. dataBean.onItemClick = (i) => {
  2883. const newDirPath = rPath + '/' + mList[i];
  2884. // Logger.info('newDirPath = ' + newDirPath)
  2885. this.selectedFiles.forEach((item) => {
  2886. const newPath = newDirPath + '/' + item.fileName;
  2887. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2888. ToastUtil.showToast('移动成功');
  2889. this.table.deleteData(item, () => {
  2890. this.cache.delete(this.currentPath); // 删除原路径缓存
  2891. this.cache.delete(newDirPath); // 删除目标路径缓存
  2892. this.getSortedFiles(this.currentPath, true);
  2893. });
  2894. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2895. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2896. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2897. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2898. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2899. this.table.insert(newItem, (id: number) => {
  2900. //加入数据库
  2901. });
  2902. }
  2903. }).catch((error: Error) => {
  2904. console.error(error.message);
  2905. });
  2906. });
  2907. this.isMultiSelect = false
  2908. this.selectedFiles = [];
  2909. this.isAllSelected = false
  2910. XPopup.dismissTop();
  2911. };
  2912. let pup: XPopup
  2913. if (this.isDarkMode) {
  2914. pup = XPopup.Builder()
  2915. .setPopupPosition(PopupPosition.TOP)
  2916. .atView(viewId)
  2917. .setBackgroundColor(Color.Black)
  2918. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2919. .show();
  2920. } else {
  2921. pup = XPopup.Builder()
  2922. .setPopupPosition(PopupPosition.TOP)
  2923. .atView(viewId)
  2924. .setBackgroundColor(Color.White)
  2925. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2926. .show();
  2927. }
  2928. }
  2929. /**
  2930. * 加载所有歌单
  2931. */
  2932. async loadAllPlaylists() {
  2933. try {
  2934. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  2935. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  2936. } catch (error) {
  2937. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  2938. }
  2939. }
  2940. /**
  2941. * 显示添加到歌单对话框
  2942. */
  2943. async showAddToPlaylistDialog(item: VideoItem) {
  2944. // 加载最新的歌单列表
  2945. await this.loadAllPlaylists()
  2946. showAddToPlaylistDialog(
  2947. item,
  2948. this.allPlaylists,
  2949. async (playlistId: string) => {
  2950. // 添加歌曲到歌单
  2951. const success = await this.playlistTable?.addSongToPlaylist(playlistId, item.filePath)
  2952. if (success) {
  2953. ToastUtil.showToast('已添加到歌单')
  2954. // 重新加载歌单列表
  2955. await this.loadAllPlaylists()
  2956. } else {
  2957. ToastUtil.showToast('歌曲已在该歌单中')
  2958. }
  2959. },
  2960. () => {
  2961. LogUtil.info('取消添加到歌单')
  2962. },
  2963. () => {
  2964. // 创建新歌单
  2965. showCreatePlaylistDialog(
  2966. async (name: string, description: string, coverPath?: string) => {
  2967. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  2968. if (success) {
  2969. ToastUtil.showToast('歌单创建成功')
  2970. // 重新加载歌单列表并打开添加对话框
  2971. await this.loadAllPlaylists()
  2972. await this.showAddToPlaylistDialog(item)
  2973. } else {
  2974. ToastUtil.showToast('歌单创建失败')
  2975. }
  2976. },
  2977. () => {
  2978. // 取消创建歌单
  2979. }
  2980. )
  2981. }
  2982. )
  2983. }
  2984. doFav(item: VideoItem) {
  2985. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2986. let isFav = 0
  2987. if (Utility.getIsFav(this.favList, item)) {
  2988. isFav = 0
  2989. } else {
  2990. isFav = 1
  2991. }
  2992. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2993. if (result) {
  2994. if (isFav === 1) {
  2995. ToastUtil.showToast('收藏成功');
  2996. } else {
  2997. ToastUtil.showToast('取消收藏成功');
  2998. }
  2999. this.deleteCache(this.currentPath)
  3000. this.getFavList(false)
  3001. if (this.modeType === 0 && !this.isFavMusic) {
  3002. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  3003. this.getSortedFiles(this.currentPath)
  3004. }
  3005. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3006. workerInstance.postMessage({ code: 3, data: this.context });
  3007. workerInstance.postMessage({ code: 4, data: this.context });
  3008. }
  3009. })
  3010. }
  3011. //多选复制文件
  3012. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3013. console.log('onecold showCopyDialogForMultipleFiles');
  3014. let mList: Array<string> = []
  3015. let rPath = this.rootPath
  3016. if (isCurrent) {
  3017. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3018. rPath = this.currentPath
  3019. } else {
  3020. mList = Utility.getNameList(this.dirList);
  3021. rPath = this.rootPath
  3022. }
  3023. let dataBean = new BubbleBean();
  3024. dataBean.data = mList;
  3025. dataBean.isCopy = true
  3026. dataBean.color = this.themeColor
  3027. dataBean.onItemClick = (i) => {
  3028. const newDirPath = rPath + '/' + mList[i];
  3029. // Logger.info('newDirPath = ' + newDirPath)
  3030. this.selectedFiles.forEach((item) => {
  3031. const newPath = newDirPath + '/' + item.fileName;
  3032. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3033. ToastUtil.showToast('复制成功');
  3034. this.cache.delete(newDirPath); // 删除目标路径缓存
  3035. this.getSortedFiles(this.currentPath);
  3036. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3037. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3038. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3039. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3040. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3041. this.table.insert(newItem, (id: number) => {
  3042. //加入数据库
  3043. });
  3044. }
  3045. }).catch((error: Error) => {
  3046. console.error(error.message);
  3047. });
  3048. });
  3049. this.isMultiSelect = false
  3050. this.selectedFiles = [];
  3051. this.isAllSelected = false
  3052. XPopup.dismissTop();
  3053. };
  3054. let pup: XPopup
  3055. if (this.isDarkMode) {
  3056. pup = XPopup.Builder()
  3057. .setPopupPosition(PopupPosition.TOP)
  3058. .atView(viewId)
  3059. .setBackgroundColor(Color.Black)
  3060. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3061. .show();
  3062. } else {
  3063. pup = XPopup.Builder()
  3064. .setPopupPosition(PopupPosition.TOP)
  3065. .atView(viewId)
  3066. .setBackgroundColor(Color.White)
  3067. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3068. .show();
  3069. }
  3070. }
  3071. @Builder
  3072. private DirItem(item: VideoItem, index?: number) {
  3073. Button({ type: ButtonType.Normal, stateEffect: true }) {
  3074. Row() {
  3075. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  3076. $r('app.media.music_group'))
  3077. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3078. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3079. .fillColor(this.themeColor)// .fontSize(33)
  3080. .alt($r('app.media.music_group'))
  3081. .borderRadius('100%')
  3082. .clip(true)
  3083. .margin({ left: 20, top: 8, bottom: 8 })
  3084. Column() {
  3085. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3086. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3087. .maxLines(1)// .width('88%')
  3088. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3089. .animation({
  3090. duration: 555,
  3091. curve: 'ease-in-out',
  3092. })
  3093. .transition({
  3094. type: TransitionType.Insert,
  3095. opacity: 0,
  3096. translate: { x: 160 }
  3097. })
  3098. .margin({ left: 10, right: 20 })
  3099. .fontColor($r('app.color.text_color'))
  3100. Row() {
  3101. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3102. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3103. .padding({ top: 8 })
  3104. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3105. .fontColor($r('app.color.text_color'))
  3106. .margin({ left: 10 })
  3107. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3108. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3109. .padding({ top: 8 })
  3110. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3111. .fontColor($r('app.color.text_color'))
  3112. .margin({ left: 10 })
  3113. Blank()
  3114. }
  3115. }
  3116. .height('100%')
  3117. .layoutWeight(1)
  3118. .justifyContent(FlexAlign.Center)
  3119. .alignItems(HorizontalAlign.Start)
  3120. Blank()
  3121. Image($r('app.media.arrow_right'))
  3122. .height(25)
  3123. .margin({ right: 10 })
  3124. .alignSelf(ItemAlign.Center)
  3125. .id(item.filePath)
  3126. }
  3127. }
  3128. .backgroundColor(Color.Transparent)
  3129. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  3130. .width('100%')
  3131. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  3132. .opacity(this.opacityItem) // 绑定透明度
  3133. }
  3134. isShowDir(dirName: string) {
  3135. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  3136. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  3137. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  3138. if (dirName === undefined) {
  3139. return true
  3140. }
  3141. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  3142. return this.isShowSimi
  3143. }
  3144. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  3145. return this.isShowFAV
  3146. }
  3147. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  3148. return this.isShowHistory
  3149. }
  3150. return true
  3151. }
  3152. @State opacityItem: number = 1; // 控制透明度的状态变量
  3153. @Builder
  3154. private MusicItem(item: VideoItem, index?: number) {
  3155. Button({ type: ButtonType.Normal, stateEffect: true }) {
  3156. Row() {
  3157. Stack() {
  3158. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  3159. .fillColor(this.themeColor)
  3160. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3161. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3162. .alt($r('app.media.music_red'))
  3163. .borderRadius('100%')
  3164. .clip(true)
  3165. .draggable(false)
  3166. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3167. .autoResize(true) // 重采样,可减少内存占用
  3168. .opacity(this.opacityItem)// 绑定透明度
  3169. .margin({ left: 20 })
  3170. .gesture(LongPressGesture()
  3171. .onAction(async () => {
  3172. //如果是专辑和艺术家的首页,不能长按
  3173. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3174. return
  3175. //如果是我的收藏 最近播放等也不能长按
  3176. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3177. item.name === LocalMusic.STR_HISTORY_MUSIC
  3178. )
  3179. return
  3180. this.longItemFilePath = item.filePath
  3181. this.tempLyricContent = await this.getLyricContent(item)
  3182. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  3183. })
  3184. .onActionEnd((event: GestureEvent) => {
  3185. }))
  3186. .onClick(()=>{
  3187. if (this.isMultiSelect) {
  3188. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3189. this.handleFileSelection(item, !isChecked);
  3190. } else {
  3191. this.doPlay(item,index)
  3192. this.isShowPlay = true
  3193. }
  3194. })
  3195. }
  3196. Column() {
  3197. Column() {
  3198. Text(this.isShowFileName?item.fileName :item.name)
  3199. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3200. .maxLines(1)
  3201. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3202. .animation({
  3203. duration: 555,
  3204. curve: 'Linear',
  3205. })
  3206. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3207. $r('app.color.text_color'))
  3208. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3209. .padding({right:25})
  3210. .bindPopup(this.longItemFilePath === item.filePath, {
  3211. builder: this.MenuBuilder(item,index,item.filePath),
  3212. placement: Placement.Top,
  3213. // autoCancel: true,
  3214. mask: {color:'#33000000'},
  3215. // popupColor: Color.Yellow,
  3216. enableArrow: false,//是否显示箭头
  3217. showInSubWindow: false,
  3218. onStateChange: (e) => {
  3219. if (!e.isVisible) {
  3220. this.longItemFilePath = ''
  3221. this.tempLyricContent = ''
  3222. }
  3223. }
  3224. })
  3225. .gesture(LongPressGesture()
  3226. .onAction(async () => {
  3227. //如果是专辑和艺术家的首页,不能长按
  3228. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3229. return
  3230. //如果是我的收藏 最近播放等也不能长按
  3231. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3232. item.name === LocalMusic.STR_HISTORY_MUSIC
  3233. )
  3234. return
  3235. this.longItemFilePath = item.filePath
  3236. this.tempLyricContent = await this.getLyricContent(item)
  3237. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  3238. })
  3239. .onActionEnd((event: GestureEvent) => {
  3240. })
  3241. )
  3242. Row() {
  3243. Column(){
  3244. Text(item.md5Str?.includes('Lossless')?
  3245. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3246. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3247. .padding({ top: 3,right:6,left:6,bottom:3 })
  3248. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3249. $r('app.color.text_color'))
  3250. .fontWeight(500)
  3251. .borderRadius(12)
  3252. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  3253. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3254. .backgroundColor('#FFC107')
  3255. }
  3256. .padding({ top: 8 })
  3257. Text(StrUtil.isEmpty(item.artist) ? item.duration
  3258. :this.twoFingerType==2? item.artist +' ' + item.duration
  3259. : item.artist + ' ' + item?.duration)
  3260. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3261. .padding({ top: 8 ,right:25})
  3262. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  3263. .maxLines(1)
  3264. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3265. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3266. Color.Gray)
  3267. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3268. Blank()
  3269. Text(this.isShowFileName?item.duration:item.size)
  3270. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  3271. .padding({ top: 8 })
  3272. .maxLines(1)
  3273. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  3274. ? Visibility.Visible : Visibility.None)
  3275. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3276. Color.Gray)
  3277. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  3278. }
  3279. .gesture(LongPressGesture()
  3280. .onAction(async () => {
  3281. //如果是专辑和艺术家的首页,不能长按
  3282. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3283. return
  3284. //如果是我的收藏 最近播放等也不能长按
  3285. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3286. item.name === LocalMusic.STR_HISTORY_MUSIC
  3287. )
  3288. return
  3289. this.longItemFilePath = item.filePath
  3290. this.tempLyricContent = await this.getLyricContent(item)
  3291. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  3292. })
  3293. .onActionEnd((event: GestureEvent) => {
  3294. })
  3295. )
  3296. }
  3297. .height('100%')
  3298. .width('100%')
  3299. .margin({ right: 10 })
  3300. .justifyContent(FlexAlign.Center)
  3301. .alignItems(HorizontalAlign.Start)
  3302. }
  3303. .height('100%')
  3304. .margin({ left: 5 })
  3305. .layoutWeight(1)
  3306. Column() {
  3307. Checkbox({ name: 'checkbox' + index })
  3308. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  3309. .selectedColor(this.themeColor)
  3310. .shape(CheckBoxShape.CIRCLE)
  3311. .opacity(this.isMultiSelect ? 1 : 0)
  3312. .animation({
  3313. duration: 666,
  3314. curve: 'Smooth' // 可选动画曲线
  3315. })
  3316. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3317. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3318. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  3319. .width(22)
  3320. .height(22)
  3321. ImageAnimator()
  3322. .images(this.imagesF)// 动画数组
  3323. .duration(1000)// 持续
  3324. .state(this.animationState)// 动画状态
  3325. .fillMode(FillMode.Forwards)
  3326. .width(18)
  3327. .margin({ right: 20, top: 8, bottom: 8 })
  3328. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  3329. Visibility.None)
  3330. .height(18)
  3331. .iterations(-1) // 播放次数
  3332. }
  3333. }
  3334. }
  3335. .backgroundColor(Color.Transparent)
  3336. .width('100%')
  3337. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  3338. }
  3339. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  3340. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  3341. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  3342. direction: Direction.Ltr,
  3343. buttonPadding:{top:12,bottom:12},
  3344. backgroundColor: Color.Transparent,
  3345. fontSize:14,
  3346. selectedFontSize:15,
  3347. selectedFontColor:Color.White,
  3348. selectedBackgroundColor: this.themeColor,
  3349. localizedTextPadding: {
  3350. end: LengthMetrics.vp(20),
  3351. start: LengthMetrics.vp(20)
  3352. }
  3353. })
  3354. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  3355. //当胶囊按钮的选择发生变化时调用此函数
  3356. capsuleSelectedIndexesChanged() {
  3357. this.modeType = this.tabSelectedIndexes[0]
  3358. }
  3359. @Builder
  3360. tabTitle() {
  3361. Column({ space: 2 }) {
  3362. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  3363. Line()
  3364. .width('100%')
  3365. .height(1)
  3366. .backgroundColor($r('app.color.index_background'))
  3367. .opacity(this.barOpacity)
  3368. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  3369. }
  3370. .width('100%')
  3371. .height(this.topBarHeight)
  3372. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  3373. }
  3374. // @Builder
  3375. // tabTitle() {
  3376. // Column() {
  3377. // // 使用 Stack 布局来实现绝对定位效果
  3378. // Stack() {
  3379. // // 背景动画容器
  3380. // Row() {
  3381. // ForEach(this.tabs, (i: string, index) => {
  3382. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  3383. // Flex()
  3384. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  3385. // .borderRadius(20)
  3386. // .padding(10)
  3387. // .margin(6)
  3388. // .width('100%')
  3389. // .height('100%')
  3390. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3391. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  3392. // .opacity(this.modeType === index ? 1 : 0)
  3393. // .animation({
  3394. // duration: 666,
  3395. // playMode: PlayMode.Normal,
  3396. // curve: 'ease-in-out'
  3397. // });
  3398. // }
  3399. // .layoutWeight(1)
  3400. // .margin({
  3401. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  3402. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  3403. // });
  3404. // });
  3405. // }
  3406. // .width('100%')
  3407. // .height(50);
  3408. //
  3409. // // 导航栏容器
  3410. // Row() {
  3411. // ForEach(this.tabs, (item: string, index) => {
  3412. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  3413. // Text(item)
  3414. // .fontSize(16)
  3415. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  3416. // .padding(15)
  3417. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3418. // .onClick(() => {
  3419. // this.modeType = index;
  3420. // // this.onModeChange();
  3421. // });
  3422. // }
  3423. // .layoutWeight(1)
  3424. // .stateStyles({
  3425. // pressed: { opacity: 0.6 } // 按压反馈
  3426. // });
  3427. // });
  3428. // }
  3429. // .width('100%')
  3430. // .height(this.topBarHeight)
  3431. // .opacity(this.barOpacity)
  3432. // .backgroundColor(Color.Transparent);
  3433. //
  3434. // }
  3435. // .width('100%')
  3436. // .height(this.topBarHeight)
  3437. // .opacity(this.barOpacity)
  3438. //
  3439. // Line()
  3440. // .width('100%')
  3441. // .height(1)
  3442. // .backgroundColor($r('app.color.index_background'))
  3443. // .opacity(this.barOpacity)
  3444. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  3445. // }
  3446. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  3447. // }
  3448. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  3449. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  3450. isShowCoverHeader() {
  3451. if (!this.isShowHeader) {
  3452. return false
  3453. }
  3454. if (this.modeType == 0) {
  3455. if (this.isHistory || this.isFavMusic) {
  3456. return true
  3457. }
  3458. if (this.currentPath != this.rootPath) {
  3459. return true
  3460. }
  3461. }
  3462. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  3463. }
  3464. @Builder
  3465. coverHeader() {
  3466. if (this.isShowCoverHeader()) {
  3467. Column() {
  3468. Stack() {
  3469. // 居中标题
  3470. Text('')
  3471. .fontSize(18)
  3472. .fontColor(Color.White)
  3473. .align(Alignment.Center)
  3474. // 左右按钮
  3475. Row() {
  3476. Image($r('app.media.left_back_white'))
  3477. .width(28)
  3478. .height(28)
  3479. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3480. .margin({ left: 12, right: 8 })
  3481. .onClick(() => {
  3482. animateTo({ duration: 555 }, () => {
  3483. this.doSwipBack()
  3484. })
  3485. })
  3486. Blank().flexGrow(1)
  3487. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  3488. Image($r('app.media.add'))
  3489. .width(25)
  3490. .height(25)
  3491. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3492. .margin({ left: 8, right: 15 })
  3493. .onClick(() => {
  3494. this.showAddDialog()
  3495. })
  3496. }
  3497. }
  3498. .height(48)
  3499. .width('100%')
  3500. .alignItems(VerticalAlign.Center)
  3501. }
  3502. .height(48)
  3503. .width('100%')
  3504. Row() {
  3505. Column() {
  3506. Image(this.currentTitleCover)
  3507. .height(100)
  3508. .width(100)
  3509. .alt(this.imageLabel)
  3510. .borderRadius(8)
  3511. .clickEffect({ level: ClickEffectLevel.HEAVY })
  3512. }
  3513. .alignItems(HorizontalAlign.Start)
  3514. .margin({ left: 30, top: 3, bottom: 15 })
  3515. Column() {
  3516. Column() {
  3517. Text(this.currentTitleName)
  3518. .fontSize(16)
  3519. .maxLines(1)
  3520. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3521. .fontWeight(FontWeight.Bold)
  3522. .fontColor($r('app.color.text_color'))
  3523. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3524. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3525. Text(`艺术家:${this.videoLocalList[0].artist}`)
  3526. .fontSize(14)
  3527. .padding({ top: 8 })
  3528. .maxLines(1)
  3529. .fontWeight(FontWeight.Bold)
  3530. .fontColor($r('app.color.text_color'))
  3531. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3532. if(this.videoLocalList[0].genre){
  3533. Text(`风格:${this.videoLocalList[0].genre}`)
  3534. .fontSize(14)
  3535. .padding({ top: 8 })
  3536. .maxLines(1)
  3537. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  3538. this.videoLocalList[0].genre.includes(this.UNKONWN)
  3539. ?Visibility.None:Visibility.Visible)
  3540. .fontWeight(FontWeight.Bold)
  3541. .fontColor($r('app.color.text_color'))
  3542. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3543. }
  3544. if(this.videoLocalList[0].year){
  3545. Text(`发行时间:${this.videoLocalList[0].year}`)
  3546. .fontSize(14)
  3547. .padding({ top: 8 })
  3548. .maxLines(1)
  3549. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  3550. this.videoLocalList[0].year.includes(this.UNKONWN)
  3551. ?Visibility.None:Visibility.Visible)
  3552. .fontWeight(FontWeight.Bold)
  3553. .fontColor($r('app.color.text_color'))
  3554. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3555. }
  3556. }
  3557. if(this.modeType != 3){
  3558. Row() {
  3559. Text(`共${this.videoLocalList.length}首歌`)
  3560. .fontSize(13)
  3561. .fontWeight(FontWeight.Bold)
  3562. .padding({ top: 8 })
  3563. .fontColor($r('app.color.text_color'))
  3564. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  3565. Blank()
  3566. }
  3567. }
  3568. }
  3569. .height('100%')
  3570. .width('100%')
  3571. .justifyContent(FlexAlign.Center)
  3572. .alignItems(HorizontalAlign.Start)
  3573. }
  3574. .height('100%')
  3575. .layoutWeight(1)
  3576. .margin({ left: 20 })
  3577. }
  3578. this.listViewTitle()
  3579. }
  3580. .backgroundImage(this.getCoverTitleBg())
  3581. .height(250)
  3582. .width('100%')
  3583. .backgroundImageSize({ height: '100%', width: '100%' })
  3584. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  3585. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  3586. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  3587. .justifyContent(FlexAlign.SpaceBetween)
  3588. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  3589. TransitionEffect.scale({ x: 0, y: 0 })))
  3590. } else {
  3591. this.listViewTitle()
  3592. }
  3593. }
  3594. getCoverTitleBg(): ResourceStr | image.PixelMap {
  3595. if (this.isCustomizeBg) {
  3596. return ('rgba(255,255,255,0.2)')
  3597. }
  3598. if (this.isDarkMode) {
  3599. return $r('app.color.user_center_card_background')
  3600. }
  3601. return this.currentTitleCover
  3602. }
  3603. @Builder
  3604. listViewTitle() {
  3605. Column() {
  3606. Row({ space: 8 }) {
  3607. Row({ space: 8 }) {
  3608. Image($r("app.media.hm_playlist"))
  3609. .width(25)
  3610. .margin({ left: 8 })
  3611. .fillColor(this.themeColor)
  3612. Text(this.artistList.length ==100 ? `共找到${this.artistCount}位艺术家`
  3613. :`共找到${this.artistList.length}位艺术家`)
  3614. .fontColor($r('app.color.text_color'))
  3615. .fontSize(14)
  3616. .opacity(this.opacityItem)
  3617. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3618. Text(this.albumList.length ==100 ? `共找到${this.albumCount+''}张专辑`
  3619. :`共找到${this.albumList.length}张专辑`)
  3620. .fontColor($r('app.color.text_color'))
  3621. .opacity(this.opacityItem)
  3622. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3623. .fontSize(14)
  3624. }
  3625. .layoutWeight(1)
  3626. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3627. Row() {
  3628. TextInput({
  3629. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  3630. text: this.searchText
  3631. })
  3632. .height(35)
  3633. .onChange((value: string) => {
  3634. this.onSearchInput(value);
  3635. })
  3636. .layoutWeight(1)
  3637. Text(`取消`)
  3638. .margin({ left: 10, right: 10 })
  3639. .fontColor($r('app.color.text_color'))
  3640. .fontSize(16)
  3641. .onClick(() => {
  3642. this.isSearchMode = false
  3643. this.searchText = ''
  3644. if (this.modeType === 2) {
  3645. this.updateListData(this.artistList)
  3646. } else {
  3647. this.updateListData(this.albumList)
  3648. }
  3649. })
  3650. }
  3651. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3652. .animation({
  3653. duration: 666,
  3654. curve: 'ease-in-out' // 可选动画曲线
  3655. })
  3656. Blank()
  3657. Image($r("app.media.search"))
  3658. .width(25)
  3659. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3660. .animation({
  3661. duration: 666,
  3662. curve: 'ease-in-out' // 可选动画曲线
  3663. })// .opacity(this.opacityItem)
  3664. .fillColor(this.themeColor)
  3665. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3666. .onClick(() => {
  3667. this.isSearchMode = true
  3668. })
  3669. Image($r("app.media.top_rank"))
  3670. .width(25)// .opacity(this.opacityItem)
  3671. .fillColor(this.themeColor)
  3672. .animation({
  3673. duration: 666,
  3674. curve: 'ease-in-out' // 可选动画曲线
  3675. })
  3676. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3677. .onClick(() => {
  3678. this.showRankDialog()
  3679. })
  3680. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3681. .width(25)
  3682. .animation({
  3683. duration: 666,
  3684. curve: 'ease-in-out' // 可选动画曲线
  3685. })
  3686. .fillColor(this.themeColor)
  3687. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3688. .onClick(() => {
  3689. this.isGridMusic = !this.isGridMusic
  3690. })
  3691. }
  3692. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  3693. Visibility.None)
  3694. .width('100%')
  3695. .padding(10)
  3696. .height(50)
  3697. .border({
  3698. width: { bottom: 1 },
  3699. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3700. })
  3701. Row({ space: 8 }) {
  3702. Row({ space: 8 }) {
  3703. Image($r("app.media.hm_play"))
  3704. .width(25)
  3705. .margin({ left: 8 })
  3706. .fillColor(this.themeColor)
  3707. Text(`播放全部`)
  3708. .fontColor($r('app.color.text_color'))
  3709. .fontSize(14)
  3710. .animation({
  3711. duration: 666,
  3712. curve: 'ease-in-out' // 可选动画曲线
  3713. })
  3714. if(Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length>0){
  3715. Text(this.modeType==1&&Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length==100?
  3716. `(${this.mediaKuCount}首)`
  3717. :`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  3718. .fontColor($r('app.color.text_color'))
  3719. .fontSize(14)
  3720. .opacity(this.opacityItem)
  3721. .animation({
  3722. duration: 666,
  3723. curve: 'ease-in-out' // 可选动画曲线
  3724. })
  3725. }
  3726. }
  3727. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3728. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3729. .animation({
  3730. duration: 666,
  3731. curve: 'ease-in-out' // 可选动画曲线
  3732. })
  3733. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  3734. .onTouch((event: TouchEvent) => {
  3735. if (event.type === TouchType.Down) {
  3736. this.isClickedPLayAll = true;
  3737. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  3738. this.isClickedPLayAll = false;
  3739. }
  3740. })
  3741. .onClick(() => {
  3742. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  3743. if (this.modeType === 0) {
  3744. const playList = this.getCurFileList();
  3745. const item = Utility.getPlayItem(playList, this.playType);
  3746. if (item) { // 显式检查undefined
  3747. this.doPlay(item);
  3748. }
  3749. } else {
  3750. const item = Utility.getPlayItem(this.mediaKuList, this.playType);
  3751. if (item) {
  3752. this.doPlay(item);
  3753. }
  3754. }
  3755. })
  3756. Row() {
  3757. TextInput({ placeholder: '输入名称...', text: this.searchText })
  3758. .height(35)
  3759. .onChange((value: string) => {
  3760. this.onSearchInput(value);
  3761. })
  3762. .layoutWeight(1)
  3763. Text(`取消`)
  3764. .margin({ left: 10, right: 10 })
  3765. .fontColor($r('app.color.text_color'))
  3766. .fontSize(16)
  3767. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3768. .onClick(() => {
  3769. this.isSearchMode = false
  3770. this.searchText = ''
  3771. if(this.modeType==0){
  3772. this.updateListData(this.videoLocalList)
  3773. } else if(this.modeType==1){
  3774. this.updateListData(this.mediaKuList)
  3775. } else if(this.modeType==2&&!this.isCanBack){
  3776. this.updateListData(this.artistList)
  3777. } else if(this.modeType==3&&!this.isCanBack){
  3778. this.updateListData(this.albumList)
  3779. }else if(this.modeType==4){
  3780. this.doSongListTask()
  3781. }
  3782. })
  3783. }
  3784. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3785. .animation({
  3786. duration: 666,
  3787. curve: 'ease-in-out' // 可选动画曲线
  3788. })
  3789. Blank()
  3790. Image($r("app.media.search"))
  3791. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  3792. .animation({
  3793. duration: 666,
  3794. curve: 'ease-in-out' // 可选动画曲线
  3795. })// .opacity(this.opacityItem)
  3796. .fillColor(this.themeColor)
  3797. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3798. .onClick(() => {
  3799. this.isSearchMode = true
  3800. })
  3801. Image($r("app.media.refresh"))
  3802. .fillColor(this.themeColor)
  3803. .width(25)
  3804. .visibility(this.modeType ==4||this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3805. .animation({
  3806. duration: 666,
  3807. curve: 'ease-in-out' // 可选动画曲线
  3808. })
  3809. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3810. .onClick(() => {
  3811. if (this.isFavMusic) {
  3812. this.getFavList(true)
  3813. } else {
  3814. if(this.modeType == 0){
  3815. this.asyncCurrentPathData()
  3816. }else if(this.modeType ==1){
  3817. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3818. }
  3819. }
  3820. })
  3821. Image($r("app.media.top_rank"))
  3822. .width(25)
  3823. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  3824. Visibility.Visible)// .opacity(this.opacityItem)
  3825. .animation({
  3826. duration: 666,
  3827. curve: 'ease-in-out' // 可选动画曲线
  3828. })
  3829. .fillColor(this.themeColor)
  3830. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3831. .onClick(() => {
  3832. this.showRankDialog()
  3833. })
  3834. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  3835. .width(24)
  3836. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3837. .animation({
  3838. duration: 666,
  3839. curve: 'ease-in-out' // 可选动画曲线
  3840. })
  3841. .fillColor(this.themeColor)
  3842. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3843. .onClick(() => {
  3844. this.isMultiSelect = !this.isMultiSelect
  3845. })
  3846. SymbolGlyph($r('sys.symbol.trash'))
  3847. .fontColor([this.themeColor])
  3848. .fontSize(25)
  3849. .effectStrategy(1)
  3850. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  3851. .animation({
  3852. duration: 666,
  3853. curve: 'ease-in-out' // 可选动画曲线
  3854. })
  3855. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3856. .onClick(() => {
  3857. this.clearVideoHistory() //清空播放记录
  3858. })
  3859. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3860. .width(24)
  3861. .animation({
  3862. duration: 666,
  3863. curve: 'ease-in-out' // 可选动画曲线
  3864. })
  3865. .fillColor(this.themeColor)
  3866. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3867. .bindPopup($$this.tipPopup, {
  3868. builder: this.popupBuilder,
  3869. placement: Placement.Bottom,
  3870. maskColor: 0x33000000,
  3871. enableArrow: true,
  3872. onStateChange: (e) => {
  3873. if (!e.isVisible) {
  3874. this.tipPopup = false;
  3875. }
  3876. }
  3877. })
  3878. .onClick(() => {
  3879. if(this.twoFingerType==4){
  3880. this.isGridMusic = false
  3881. this.twoFingerType=3
  3882. }else{
  3883. this.isGridMusic = !this.isGridMusic
  3884. }
  3885. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3886. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3887. })
  3888. }
  3889. .width('100%')
  3890. .padding(10)
  3891. .height(50)
  3892. .visibility(this.modeType === 0 || this.modeType === 1||this.modeType === 4
  3893. || this.isCanBack ? Visibility.Visible : Visibility.None)
  3894. .border({
  3895. width: { bottom: 1 },
  3896. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3897. })
  3898. }
  3899. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3900. }
  3901. // 第二步:popup构造器定义弹框内容
  3902. @Builder popupBuilder() {
  3903. Column({ space: 2 }) {
  3904. Text('友情提示:双指缩放可以放大缩小列表')
  3905. .fontSize(12)
  3906. .fontWeight(FontWeight.Regular)
  3907. .fontColor($r('app.color.text_color'))
  3908. }
  3909. .justifyContent(FlexAlign.SpaceAround)
  3910. .width(220)
  3911. .height(55)
  3912. .padding(15)
  3913. }
  3914. //搜索功能的实现
  3915. @State searchText: string = ''; // 用户输入内容
  3916. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3917. @State isSearchMode: boolean = false
  3918. // 实时搜索逻辑(带防抖)
  3919. private onSearchInput(value: string) {
  3920. this.searchText = value.trim();
  3921. let mSearchList: Array<VideoItem> = []
  3922. switch (this.modeType) {
  3923. case 0:
  3924. // mSearchList = this.videoLocalList
  3925. // break;
  3926. case 1:
  3927. mSearchList = this.mediaKuList
  3928. break;
  3929. case 2:
  3930. mSearchList = this.artistList
  3931. break;
  3932. case 3:
  3933. mSearchList = this.albumList
  3934. break;
  3935. }
  3936. // 新增条件判断:空输入时显示所有数据
  3937. if (this.searchText === '') {
  3938. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3939. } else {
  3940. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3941. //支持模糊匹配和艺术家 专辑匹配
  3942. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  3943. return regex.test(item.name.toLowerCase())||
  3944. regex.test(item.fileName?.toLowerCase() ?? "") ||
  3945. regex.test(item.artist?.toLowerCase() ?? "") ||
  3946. regex.test(item.album?.toLowerCase() ?? "")
  3947. });
  3948. }
  3949. this.updateListData(this.filteredList);
  3950. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3951. }
  3952. @State dragItem: number = -1
  3953. @State scaleItem: number = -1
  3954. @State neighborItem: number = -1
  3955. @State neighborScale: number = -1
  3956. @State offsetY: number = 0
  3957. private dragRefOffset: number = 0
  3958. private ITEM_INTV: number = 78
  3959. scaleSelect(item: number): number {
  3960. if (this.scaleItem === item) {
  3961. return 1.05
  3962. } else if (this.neighborItem === item) {
  3963. return this.neighborScale
  3964. } else {
  3965. return 1
  3966. }
  3967. }
  3968. itemMove(index: number, newIndex: number): void {
  3969. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3970. return;
  3971. }
  3972. let tmp = this.videoLocalList.splice(index, 1);
  3973. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3974. this.dataSource.pushArrayData(this.videoLocalList)
  3975. if(this.modeType==4&&this.playlistTable){
  3976. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  3977. }
  3978. }
  3979. //瀑布流布局 支持双指缩放
  3980. @State columns: number = 2;
  3981. @State waterFlowScale: number = 1;
  3982. @State imageScale: number = 1;
  3983. @State waterFlowOpacity: number = 1;
  3984. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  3985. private columnChanged: boolean = false;
  3986. private oldColumn: number = this.columns;
  3987. private pinchTime: number = 0;
  3988. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  3989. changeColumns(scale: number) {
  3990. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3991. this.columns--;
  3992. this.columnChanged = true;
  3993. } else if (scale < 1 && this.columns < 4) {
  3994. this.columns++;
  3995. this.columnChanged = true;
  3996. }
  3997. }
  3998. @Builder
  3999. getWaterView(){
  4000. Scroll(this.scroller) {
  4001. Column() {
  4002. if(this.isShowCoverHeader()){
  4003. this.coverHeader()
  4004. }else {
  4005. this.listViewTitle()
  4006. }
  4007. WaterFlow({
  4008. scroller:this.waterScroller,
  4009. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4010. }) {
  4011. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4012. FlowItem() {
  4013. this.MusicWaterCardItem(item,index)
  4014. }
  4015. .width('100%')
  4016. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4017. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4018. {
  4019. preview: MenuPreviewMode.IMAGE,
  4020. previewAnimationOptions: { scale: [0.8, 1.0] },
  4021. })
  4022. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4023. {
  4024. preview: MenuPreviewMode.IMAGE,
  4025. previewAnimationOptions: { scale: [0.8, 1.0] },
  4026. })
  4027. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4028. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4029. TransitionEffect.scale({ x: 0, y: 0 })))
  4030. .gesture(
  4031. GestureGroup(GestureMode.Exclusive,
  4032. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4033. .onAction((event: GestureEvent) => {
  4034. if (event) {
  4035. // this.sideBarController.openSideBar()
  4036. }
  4037. }),
  4038. TapGesture({ count: 1, fingers: 1 })
  4039. .onAction(async () => {
  4040. })
  4041. )
  4042. )
  4043. }, (item: VideoItem) => item.filePath)
  4044. }
  4045. // .columnsTemplate('repeat(auto-fit, 160)')
  4046. .id('waterflow') // 设置id用于截图
  4047. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4048. .columnsGap(12) // 列间距
  4049. .rowsGap(16) // 行间距
  4050. .cachedCount(6)
  4051. // .margin(
  4052. // this.isHiCar()?{bottom:this.bottomBarHeight+90}:
  4053. // {bottom:this.isShowCoverHeader()? this.topBarHeight+35:
  4054. // this.isCoverOpacity()?this.topBarHeight+this.bottomBarHeight+78
  4055. // :this.topBarHeight+this.bottomBarHeight+108})
  4056. .margin({
  4057. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  4058. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  4059. })
  4060. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4061. .animation({ duration: 500, curve: Curve.Ease }))
  4062. .scrollBar(BarState.Off)
  4063. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4064. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4065. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4066. .width('100%')
  4067. .height('100%')
  4068. .padding(10)
  4069. .opacity(this.waterFlowOpacity)
  4070. .scale({
  4071. x: this.waterFlowScale,
  4072. y: this.waterFlowScale,
  4073. centerX: 0,
  4074. centerY: 0
  4075. })
  4076. .onAppear(() => {
  4077. this.scroller.scrollEdge(Edge.Top)
  4078. })
  4079. .nestedScroll({
  4080. scrollForward: NestedScrollMode.PARENT_FIRST,
  4081. scrollBackward: NestedScrollMode.SELF_FIRST
  4082. })
  4083. .priorityGesture(
  4084. PinchGesture()
  4085. .onActionStart((event: GestureEvent) => {
  4086. // 双指捏合手势识别成功时截图
  4087. this.pinchTime = event.timestamp;
  4088. this.columnChanged = false;
  4089. this.oldColumn = this.columns;
  4090. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4091. if (error) {
  4092. console.info('error:' + JSON.stringify(error));
  4093. return;
  4094. }
  4095. this.waterFlowSnapshot = pixmap;
  4096. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4097. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4098. if (this.oldColumn ===4) {
  4099. this.twoFingerType =3
  4100. this.isGridMusic = true
  4101. }else if (this.oldColumn ===1) {
  4102. this.twoFingerType =1
  4103. this.isGridMusic = false
  4104. }
  4105. return;
  4106. }
  4107. })
  4108. })
  4109. .onActionUpdate((event: GestureEvent) => {
  4110. // 手势更新:处理缩放逻辑和视觉效果
  4111. // 边界限制:防止超出列数范围时继续缩放
  4112. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4113. return;
  4114. }
  4115. // 节流处理:避免过于频繁的更新,提升性能
  4116. if (event.timestamp - this.pinchTime < 10000000) {
  4117. return;
  4118. }
  4119. this.pinchTime = event.timestamp;
  4120. this.waterFlowScale = event.scale;
  4121. this.imageScale = event.scale;
  4122. // 根据缩放比例设置WaterFlow透明度
  4123. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4124. this.waterFlowOpacity *= 3;
  4125. if (!this.columnChanged) {
  4126. this.changeColumns(event.scale);
  4127. }
  4128. // 列数改变后的缩放比例调整:避免出现空白区域
  4129. if (this.columnChanged) {
  4130. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4131. // 限制缩放范围,确保视觉效果自然
  4132. if (event.scale < 1) {
  4133. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4134. } else {
  4135. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4136. }
  4137. }
  4138. })
  4139. .onActionEnd((event: GestureEvent) => {
  4140. // 手势结束:执行归位动画并保存状态
  4141. // 执行归位动画:平滑过渡到正常状态
  4142. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4143. this.waterFlowScale = 1;
  4144. this.waterFlowOpacity = 1;
  4145. })
  4146. // 持久化保存当前列数:下次启动时恢复
  4147. PreferencesUtil.putSync('lastColumns', this.columns);
  4148. })
  4149. )
  4150. //允许拖拽音乐和视频到List或Grid上自动导入视频
  4151. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4152. .onDrop((event?: DragEvent) => {
  4153. try {
  4154. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4155. if (dragData !== undefined) {
  4156. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4157. if (records.length > 0) {
  4158. for (let i = 0; i < records.length; i++) {
  4159. let types = records[i].getTypes();
  4160. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4161. const fileUriUds =
  4162. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4163. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4164. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4165. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4166. this.targetFile = fileUriUds.oriUri;
  4167. this.saveVideoDatas([this.targetFile])
  4168. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4169. }
  4170. }
  4171. }
  4172. } else {
  4173. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4174. }
  4175. } else {
  4176. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4177. }
  4178. } catch (error) {
  4179. const err = error as BusinessError;
  4180. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4181. }
  4182. })
  4183. }
  4184. }
  4185. .scrollBar(BarState.Off)
  4186. }
  4187. //瀑布流卡片布局
  4188. @Builder
  4189. private MusicWaterCardItem(item: VideoItem, index: number) {
  4190. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4191. Stack() {
  4192. Column() {
  4193. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  4194. .backgroundImageSize(ImageSize.Auto)
  4195. .borderRadius({
  4196. topLeft: 12,
  4197. topRight : 12,
  4198. bottomLeft: 0,
  4199. bottomRight: 0
  4200. })
  4201. .draggable(false)// 禁止长按手势拖动
  4202. // .autoResize(true) // 重采样,可减少内存占用
  4203. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4204. .width('100%')
  4205. .height('auto')
  4206. .objectFit(ImageFit.Auto)
  4207. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4208. height: '99%' ,
  4209. dragBar: true,
  4210. onDisappear: () => {
  4211. this.longItemFilePath = '';
  4212. this.tempLyricContent = ''
  4213. },
  4214. showClose: true,
  4215. preferType: SheetType.CENTER ,
  4216. title: { title: '编辑标签' }
  4217. })
  4218. .draggable(false)
  4219. .opacity(this.opacityItem)// 绑定透明度
  4220. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4221. // .animation({ duration: 500, curve: Curve.Ease }))
  4222. .animation({
  4223. duration: 666,
  4224. curve: 'ease-in-out' // 可选动画曲线
  4225. })
  4226. .margin({
  4227. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4228. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4229. })
  4230. Column() {
  4231. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4232. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  4233. .maxLines(1)
  4234. .fontWeight(FontWeight.Bold)
  4235. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4236. .animation({
  4237. duration: 555,
  4238. curve: 'Linear',
  4239. })
  4240. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4241. height: '95%',
  4242. dragBar: true,
  4243. showClose: true,
  4244. onDisappear: () => {
  4245. this.longItemFilePathDetail = '';
  4246. },
  4247. blurStyle:BlurStyle.Thin,
  4248. backgroundColor:Color.Transparent,
  4249. preferType: SheetType.CENTER ,
  4250. title: { title: '详情' }
  4251. })
  4252. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4253. $r('app.color.text_color'))
  4254. Column() {
  4255. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4256. .fontSize(11)
  4257. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4258. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4259. .fontColor($r('app.color.text_color'))
  4260. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4261. .fontSize(11)
  4262. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4263. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4264. .fontColor($r('app.color.text_color'))
  4265. Row(){
  4266. Column(){
  4267. Text(item.md5Str?.includes('Lossless')?
  4268. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4269. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  4270. .padding({ top: 3,right:6,left:6,bottom:3 })
  4271. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4272. $r('app.color.text_color'))
  4273. .fontWeight(500)
  4274. .borderRadius(12)
  4275. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4276. .backgroundColor('#FFC107')
  4277. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4278. }
  4279. .margin({ top: 2 ,right:6})
  4280. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4281. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4282. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4283. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  4284. .maxLines(1)
  4285. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4286. .margin({ top: 2})
  4287. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4288. || item.type == CommonConstants.TYPE_IS_ALBUM
  4289. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4290. .fontWeight(FontWeight.Medium)
  4291. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4292. $r('app.color.text_color'))
  4293. }
  4294. }
  4295. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4296. }
  4297. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  4298. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  4299. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  4300. .width('100%')
  4301. .justifyContent(FlexAlign.Center)
  4302. .margin({
  4303. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4304. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4305. })
  4306. }
  4307. .width('100%')
  4308. .borderRadius(12)
  4309. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  4310. .backgroundImageSize({ height: '100%', width: '100%' })
  4311. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4312. .animation({ curve: Curve.Sharp, duration: 300 })
  4313. Checkbox({ name: 'checkbox' + index })
  4314. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4315. .selectedColor(this.themeColor)
  4316. .shape(CheckBoxShape.CIRCLE)
  4317. .opacity(this.isMultiSelect ? 1 : 0)
  4318. .animation({
  4319. duration: 666,
  4320. curve: 'Smooth' // 可选动画曲线
  4321. })
  4322. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4323. Visibility.None)
  4324. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4325. .margin({ left: 20, top: 8, bottom: 8 })
  4326. .width(38)
  4327. .height(38)
  4328. }
  4329. }
  4330. .backgroundColor(Color.Transparent)
  4331. .width('100%')
  4332. .height('auto')
  4333. .padding({top:2})
  4334. .reuseId('card_item')
  4335. .onClick(() => {
  4336. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4337. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4338. this.handleFileSelection(item, !isChecked);
  4339. } else {
  4340. this.doPlay(item, index)
  4341. }
  4342. })
  4343. }
  4344. // Grid布局的开始
  4345. private dragRefOffSetX: number = 0;
  4346. private dragRefOffSetY: number = 0;
  4347. private FIX_VP_X: number = 180;
  4348. private FIX_VP_Y: number = 84;
  4349. isDraggable(index: number): boolean {
  4350. return index >= 0;
  4351. }
  4352. getRowEnd(item: number) {
  4353. if (item.toString() === '0') {
  4354. return 1;
  4355. } else {
  4356. return 0;
  4357. }
  4358. }
  4359. isInLeft(index: number) {
  4360. return index % 2 == 0;
  4361. }
  4362. down(index: number): void {
  4363. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  4364. return;
  4365. }
  4366. this.offsetY -= this.FIX_VP_Y;
  4367. this.dragRefOffSetY += this.FIX_VP_Y;
  4368. this.itemMove(index, index + 1);
  4369. }
  4370. up(index: number): void {
  4371. if (!this.isDraggable(index - 2)) {
  4372. return;
  4373. }
  4374. this.offsetY += this.FIX_VP_Y;
  4375. this.dragRefOffSetY -= this.FIX_VP_Y;
  4376. this.itemMove(index, index - 1);
  4377. }
  4378. left(index: number): void {
  4379. if (this.isInLeft(index)) {
  4380. return;
  4381. }
  4382. if (!this.isDraggable(index - 1)) {
  4383. return;
  4384. }
  4385. this.offsetX += this.FIX_VP_X;
  4386. this.dragRefOffSetX -= this.FIX_VP_X;
  4387. this.itemMove(index, index - 1)
  4388. }
  4389. right(index: number): void {
  4390. if (!this.isInLeft(index)) {
  4391. return;
  4392. }
  4393. if (!this.isDraggable(index + 1)) {
  4394. return;
  4395. }
  4396. this.offsetX -= this.FIX_VP_X;
  4397. this.dragRefOffSetX += this.FIX_VP_X;
  4398. this.itemMove(index, index + 1)
  4399. }
  4400. private scroller: Scroller = new Scroller();
  4401. private waterScroller: Scroller = new Scroller();
  4402. @State startIndex: number = 0
  4403. @State endIndex: number = 0
  4404. @State scaleValue: number = 1
  4405. @State pinchValue: number = 1
  4406. layoutOptionsForHeader: GridLayoutOptions = {
  4407. regularSize: [1, 1], // 只支持[1, 1]
  4408. irregularIndexes: [0], // 索引为0的GridItem占用一行
  4409. };
  4410. @Builder
  4411. getGridView() {
  4412. Grid(this.scroller, this.layoutOptionsForHeader) {
  4413. GridItem() {
  4414. if (this.isShowCoverHeader()) {
  4415. this.coverHeader()
  4416. } else {
  4417. this.listViewTitle()
  4418. }
  4419. }
  4420. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4421. GridItem() {
  4422. Stack({ alignContent: Alignment.Center }) {
  4423. this.MusicItemGrid(item, index)
  4424. }
  4425. }
  4426. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4427. {
  4428. preview: MenuPreviewMode.IMAGE,
  4429. previewAnimationOptions: { scale: [0.8, 1.0] },
  4430. })
  4431. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4432. {
  4433. preview: MenuPreviewMode.IMAGE,
  4434. previewAnimationOptions: { scale: [0.8, 1.0] },
  4435. })
  4436. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4437. TransitionEffect.scale({ x: 0, y: 0 })))
  4438. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4439. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  4440. .zIndex(this.dragItem === index ? 1 : 0)
  4441. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  4442. }, (item: VideoItem) => item.filePath)
  4443. }
  4444. .width(this.isShowHeader ? '100%' : '94%')
  4445. .height('100%')
  4446. .editMode(true)
  4447. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4448. .animation({ duration: 500, curve: Curve.Ease }))
  4449. .margin(
  4450. this.isHiCar()?{bottom:this.bottomBarHeight+98}:
  4451. {
  4452. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  4453. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  4454. })
  4455. .reuseId('grid_item')
  4456. .layoutWeight(1)
  4457. .scrollBar(BarState.Off)
  4458. .supportAnimation(true)
  4459. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  4460. .columnsTemplate(
  4461. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  4462. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  4463. )
  4464. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  4465. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  4466. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4467. .gesture(PinchGesture({ fingers: 2 })
  4468. .onActionEnd((event: GestureEvent) => {
  4469. this.setGridTwoFingers()
  4470. })
  4471. .onActionUpdate(e => {
  4472. this.scaleValue = this.pinchValue * e.scale
  4473. })
  4474. .onActionStart(e => {
  4475. }))
  4476. .enableScrollInteraction(true)
  4477. .onScrollIndex((start: number, end: number) => {
  4478. this.startIndex = start
  4479. this.endIndex = end
  4480. })
  4481. .onScrollFrameBegin((offset: number) => {
  4482. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4483. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4484. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4485. if (this.isScrollHide) {
  4486. this.setBarHeightHide2(offset)
  4487. } else {
  4488. this.setBarHeightNormal()
  4489. }
  4490. } else {
  4491. this.setBarHeightHide(offset)
  4492. }
  4493. return { offsetRemain: offset };
  4494. })
  4495. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4496. .onDrop((event?: DragEvent) => {
  4497. try {
  4498. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4499. if (dragData !== undefined) {
  4500. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4501. if (records.length > 0) {
  4502. for (let i = 0; i < records.length; i++) {
  4503. let types = records[i].getTypes();
  4504. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4505. const fileUriUds =
  4506. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4507. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4508. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4509. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4510. this.targetFile = fileUriUds.oriUri;
  4511. this.saveVideoDatas([this.targetFile])
  4512. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4513. }
  4514. }
  4515. }
  4516. } else {
  4517. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4518. }
  4519. } else {
  4520. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4521. }
  4522. } catch (error) {
  4523. const err = error as BusinessError;
  4524. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4525. }
  4526. })
  4527. }
  4528. @State targetFile: string = '';
  4529. setGridTwoFingers() {
  4530. this.pinchValue = this.scaleValue;
  4531. Logger.info('this.pinchValue = ' + this.pinchValue);
  4532. if (this.pinchValue >= 1) {
  4533. this.twoFingerType++
  4534. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4535. if(this.twoFingerType >= 4){
  4536. this.twoFingerType = 4//切换成瀑布流
  4537. this.columns = 4
  4538. }
  4539. } else {
  4540. this.twoFingerType--
  4541. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4542. if (this.twoFingerType < 1) {
  4543. this.twoFingerType = 3
  4544. this.isGridMusic = false
  4545. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4546. }
  4547. }
  4548. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4549. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4550. this.pinchValue = 1;
  4551. this.scaleValue = 1;
  4552. }
  4553. @State longItemFilePath: string = ''
  4554. @State tempLyricContent: string = ''
  4555. @Builder
  4556. private MusicItemGrid(item: VideoItem, index: number) {
  4557. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4558. Stack() {
  4559. Column() {
  4560. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  4561. .height(this.getGridHeight())
  4562. .width(this.getGridWight())
  4563. .draggable(false)
  4564. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4565. .autoResize(true) // 重采样,可减少内存占用
  4566. .alt($r('app.media.ic_avatar2'))
  4567. .clip(true)
  4568. .borderRadius({
  4569. topLeft: 12,
  4570. topRight: 12,
  4571. bottomLeft: 0,
  4572. bottomRight: 0
  4573. })
  4574. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4575. height: '99%' ,
  4576. dragBar: true,
  4577. onDisappear: () => {
  4578. this.longItemFilePath = '';
  4579. this.tempLyricContent = ''
  4580. },
  4581. showClose: true,
  4582. preferType: SheetType.CENTER ,
  4583. title: { title: '编辑标签' }
  4584. })
  4585. .draggable(false)
  4586. .opacity(this.opacityItem)// 绑定透明度
  4587. .animation({
  4588. duration: 666,
  4589. curve: 'ease-in-out' // 可选动画曲线
  4590. })
  4591. .margin({
  4592. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4593. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4594. })
  4595. Column() {
  4596. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4597. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4598. .maxLines(1)
  4599. .fontWeight(FontWeight.Bold)
  4600. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4601. .animation({
  4602. duration: 555,
  4603. curve: 'Linear',
  4604. })
  4605. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4606. height: '95%',
  4607. dragBar: true,
  4608. showClose: true,
  4609. onDisappear: () => {
  4610. this.longItemFilePathDetail = '';
  4611. },
  4612. blurStyle:BlurStyle.Thin,
  4613. backgroundColor:Color.Transparent,
  4614. preferType: SheetType.CENTER ,
  4615. title: { title: '详情' }
  4616. })
  4617. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4618. $r('app.color.text_color'))
  4619. Column() {
  4620. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4621. .fontSize(11)
  4622. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4623. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4624. .fontColor($r('app.color.text_color'))
  4625. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4626. .fontSize(11)
  4627. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4628. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4629. .fontColor($r('app.color.text_color'))
  4630. Row(){
  4631. Column(){
  4632. Text(item.md5Str?.includes('Lossless')?
  4633. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4634. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4635. .padding({ top: 3,right:6,left:6,bottom:3 })
  4636. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4637. $r('app.color.text_color'))
  4638. .fontWeight(500)
  4639. .borderRadius(12)
  4640. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4641. .backgroundColor('#FFC107')
  4642. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4643. }
  4644. .margin({ top: 2 ,right:6})
  4645. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4646. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4647. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4648. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  4649. .maxLines(1)
  4650. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4651. .margin({ top: 2})
  4652. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4653. || item.type == CommonConstants.TYPE_IS_ALBUM
  4654. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4655. .fontWeight(FontWeight.Medium)
  4656. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4657. $r('app.color.text_color'))
  4658. }
  4659. }
  4660. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4661. }
  4662. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  4663. .width(this.getGridWight())
  4664. .justifyContent(FlexAlign.Center)
  4665. .margin({
  4666. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4667. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4668. })
  4669. }
  4670. .width(this.getGridWight())
  4671. .borderRadius(12)
  4672. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  4673. .backgroundImageSize({ height: '100%', width: '100%' })
  4674. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4675. .animation({ curve: Curve.Sharp, duration: 300 })
  4676. Checkbox({ name: 'checkbox' + index })
  4677. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4678. .selectedColor(this.themeColor)
  4679. .shape(CheckBoxShape.CIRCLE)
  4680. .opacity(this.isMultiSelect ? 1 : 0)
  4681. .animation({
  4682. duration: 666,
  4683. curve: 'Smooth' // 可选动画曲线
  4684. })
  4685. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4686. Visibility.None)
  4687. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4688. .margin({ left: 20, top: 8, bottom: 8 })
  4689. .width(38)
  4690. .height(38)
  4691. }
  4692. }
  4693. .backgroundColor(Color.Transparent)
  4694. .width('100%')
  4695. .padding({ top: 15 })
  4696. .height(this.getGridAllHeight())
  4697. .onClick(() => {
  4698. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4699. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4700. this.handleFileSelection(item, !isChecked);
  4701. } else {
  4702. this.doPlay(item, index)
  4703. }
  4704. })
  4705. }
  4706. getGridAllHeight() {
  4707. let heightG = 222
  4708. switch (this.twoFingerType) {
  4709. case 1:
  4710. heightG = 143
  4711. break;
  4712. case 2:
  4713. heightG = 178
  4714. break;
  4715. case 3:
  4716. heightG = 222
  4717. break;
  4718. }
  4719. return heightG
  4720. }
  4721. getGridHeight() {
  4722. let heightG = 150
  4723. switch (this.twoFingerType) {
  4724. case 1:
  4725. heightG = 80
  4726. break;
  4727. case 2:
  4728. heightG = 110
  4729. break;
  4730. case 3:
  4731. heightG = 150
  4732. break;
  4733. }
  4734. return heightG
  4735. }
  4736. getGridWight() {
  4737. let wightG = 158
  4738. switch (this.twoFingerType) {
  4739. case 1:
  4740. wightG = 80
  4741. break;
  4742. case 2:
  4743. wightG = 110
  4744. break;
  4745. case 3:
  4746. wightG = 158
  4747. break;
  4748. }
  4749. return wightG
  4750. }
  4751. @State isShowDetail:boolean = false
  4752. @State longItemFilePathDetail:string =''
  4753. @Builder
  4754. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  4755. if(
  4756. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4757. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4758. item.name === LocalMusic.STR_HISTORY_MUSIC)
  4759. ){
  4760. //如果是专辑和艺术家的首页,不能长按
  4761. //如果是我的收藏 最近播放等也不能长按
  4762. }else{
  4763. Scroll() {
  4764. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  4765. Menu() {
  4766. MenuItem({
  4767. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  4768. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  4769. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  4770. })
  4771. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4772. .onClick(() => {
  4773. if (item) {
  4774. this.doFav(item)
  4775. }
  4776. this.longItemFilePath = ''
  4777. })
  4778. MenuItem({
  4779. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  4780. content: '下一首播放'
  4781. })
  4782. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4783. .onClick(() => {
  4784. this.addToNextPlay(item);
  4785. this.longItemFilePath = ''
  4786. })
  4787. MenuItem({
  4788. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  4789. content: '添加到歌单'
  4790. })
  4791. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4792. .onClick(async () => {
  4793. this.longItemFilePath = ''
  4794. await this.showAddToPlaylistDialog(item)
  4795. })
  4796. MenuItem({
  4797. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  4798. content: '编辑标签'
  4799. })
  4800. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  4801. height: '99%',
  4802. dragBar: true,
  4803. showClose: true,
  4804. preferType: SheetType.CENTER ,
  4805. title: { title: '编辑标签' }
  4806. })
  4807. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4808. .onClick(async() => {
  4809. this.setEditStrEmpty()
  4810. this.tempLyricContent = await this.getLyricContent(item);
  4811. if(this.isGridMusic||this.twoFingerType==4){
  4812. this.longItemFilePath = item.filePath
  4813. }else{
  4814. this.isShowEdit = !this.isShowEdit;
  4815. }
  4816. })
  4817. MenuItem({
  4818. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  4819. content: $r('app.string.select_all')
  4820. })
  4821. .onClick(() => {
  4822. this.isMultiSelect = !this.isMultiSelect
  4823. this.longItemFilePath = ''
  4824. this.selectedFiles.push(item)
  4825. })
  4826. MenuItem({
  4827. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  4828. content: $r('app.string.edit_audio')
  4829. })
  4830. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  4831. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4832. })
  4833. .onClick(() => {
  4834. this.isEditAudio = !this.isEditAudio
  4835. })
  4836. MenuItem({
  4837. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  4838. content: $r('app.string.extract_accompaniment')
  4839. })
  4840. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  4841. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4842. })
  4843. .onClick(() => {
  4844. this.isExtractAcc = !this.isExtractAcc
  4845. })
  4846. MenuItem({
  4847. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  4848. content: $r('app.string.converter_audio')
  4849. })
  4850. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  4851. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4852. })
  4853. .onClick(() => {
  4854. this.isConverter = !this.isConverter
  4855. })
  4856. MenuItem({
  4857. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  4858. content: $r('app.string.vocal_separation')
  4859. })
  4860. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  4861. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4862. })
  4863. .onClick(() => {
  4864. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4865. })
  4866. if(Utility.isVideoByExtension(item.filePath)){
  4867. MenuItem({
  4868. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  4869. content: $r('app.string.extract_audio')
  4870. })
  4871. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  4872. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  4873. })
  4874. .onClick(() => {
  4875. this.isExtractAudio = !this.isExtractAudio
  4876. })
  4877. }
  4878. MenuItem({
  4879. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  4880. content: $r('app.string.set_ring')
  4881. })
  4882. .onClick(async () => {
  4883. await PermissionUtil.activatePermission(item.filePath)
  4884. // if(item.filePath.includes(this.packName)){
  4885. setRingTone(this.context, item.filePath,item.name)
  4886. // }else{
  4887. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  4888. // }
  4889. this.longItemFilePath = ''
  4890. })
  4891. MenuItem({
  4892. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  4893. content: $r('app.string.rename')
  4894. })
  4895. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4896. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4897. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4898. .onClick(() => {
  4899. this.showReNameDialog(item, index + '', filePath)
  4900. this.longItemFilePath = ''
  4901. })
  4902. MenuItem({
  4903. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  4904. content: $r('app.string.delete')
  4905. })
  4906. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4907. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4908. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4909. .onClick(() => {
  4910. this.selectedFiles.push(item)
  4911. this.showWarnIsDelete()
  4912. this.longItemFilePath = ''
  4913. })
  4914. MenuItem({
  4915. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  4916. content: $r('app.string.detail')
  4917. })
  4918. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  4919. height:'95%',
  4920. dragBar: true,
  4921. showClose: true,
  4922. blurStyle:BlurStyle.Thin,
  4923. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4924. backgroundColor:Color.Transparent,
  4925. title: { title: '详情信息' }
  4926. })
  4927. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4928. .onClick(() => {
  4929. if(this.isGridMusic||this.twoFingerType==4){
  4930. this.longItemFilePathDetail = item.filePath
  4931. }else{
  4932. this.isShowDetail = !this.isShowDetail
  4933. }
  4934. })
  4935. MenuItem({
  4936. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  4937. content: $r('app.string.share')
  4938. })
  4939. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4940. .onClick(() => {
  4941. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4942. this.longItemFilePath = ''
  4943. })
  4944. }
  4945. .font({ size: 15, weight: FontWeight.Normal })
  4946. }
  4947. .width(180)
  4948. }
  4949. .height('auto')
  4950. }
  4951. }
  4952. private listMaxScrollOffsetY: number = 0
  4953. @State selectedIndex: number = -1
  4954. setlistTwoFingers() {
  4955. this.pinchValue = this.scaleValue;
  4956. Logger.info('this.pinchValue = ' + this.pinchValue);
  4957. if (this.pinchValue >= 1) {
  4958. this.twoFingerType++
  4959. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4960. if (this.twoFingerType > 3) {
  4961. this.twoFingerType = 1
  4962. this.isGridMusic = true
  4963. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4964. }
  4965. } else {
  4966. this.twoFingerType--
  4967. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4968. if (this.twoFingerType < 1) {
  4969. this.twoFingerType = 4
  4970. this.columns = 1
  4971. }
  4972. }
  4973. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4974. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4975. this.pinchValue = 1;
  4976. this.scaleValue = 1;
  4977. }
  4978. @Builder
  4979. getList(){
  4980. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  4981. this.getListView()
  4982. }
  4983. .pullDownRatio(this.ratioL)
  4984. .pullToRefresh(true)
  4985. .refreshOffset(0)
  4986. .onOffsetChange((offset: number) => {
  4987. // 越接近最大距离,下拉跟手系数越小。
  4988. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  4989. })
  4990. .onStateChange((refreshStatus: RefreshStatus) => {
  4991. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  4992. })
  4993. .onRefreshing(async () => {
  4994. if(this.modeType==0){
  4995. this.getHistoryList(false)
  4996. this.asyncCurrentPathOnlyFile()
  4997. }else if(this.modeType == 1){
  4998. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4999. }else if(this.modeType == 2){
  5000. workerInstance.postMessage({ code: 3, data: this.context });
  5001. }else if(this.modeType == 3){
  5002. workerInstance.postMessage({ code: 4, data: this.context });
  5003. }else if(this.modeType == 4){
  5004. this.doSongListTask()
  5005. }
  5006. console.log('onRefreshing test');
  5007. })
  5008. }
  5009. // 扫描当前目录下的文件,不扫描子目录
  5010. asyncCurrentPathOnlyFile(){
  5011. if(this.modeType==0){
  5012. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5013. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5014. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5015. if(this.modeType==0){
  5016. setTimeout(()=>{
  5017. this.isRefreshing =false
  5018. this.deleteCache(this.currentPath)
  5019. this.getSortedFiles(this.currentPath)
  5020. },500)
  5021. }
  5022. }).catch((e:object)=>{
  5023. this.isRefreshing =false
  5024. console.info("onecold task1 catch e: " + e);
  5025. })
  5026. }
  5027. }
  5028. @Builder
  5029. getListView() {
  5030. List({ scroller: this.listScroller }) {
  5031. ListItemGroup({ header: this.coverHeader() }) {
  5032. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5033. ListItem() {
  5034. Column() {
  5035. if (item.type === CommonConstants.TYPE_IS_DIR
  5036. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5037. this.DirItem(item, index)
  5038. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5039. } else {
  5040. this.MusicItem(item, index)
  5041. }
  5042. }
  5043. .shadow(this.scaleItem === index ? {
  5044. radius: 70,
  5045. color: '#15000000',
  5046. offsetX: 0,
  5047. offsetY: 0
  5048. } :
  5049. {
  5050. radius: 0,
  5051. color: '#15000000',
  5052. offsetX: 0,
  5053. offsetY: 0
  5054. })
  5055. .animation({ curve: Curve.Sharp, duration: 300 })
  5056. }
  5057. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5058. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  5059. .animation({ duration: 500 }),
  5060. TransitionEffect.scale({ x: 0, y: 0 })))
  5061. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5062. .swipeAction((
  5063. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5064. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5065. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5066. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5067. .onClick(() => {
  5068. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5069. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5070. this.handleFileSelection(item, !isChecked);
  5071. } else {
  5072. this.doPlay(item, index)
  5073. }
  5074. })
  5075. //拖动List关键代码开始
  5076. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5077. .zIndex(this.dragItem === index ? 1 : 0)
  5078. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5079. .gesture(
  5080. GestureGroup(GestureMode.Sequence,
  5081. LongPressGesture({ repeat: true })
  5082. .onAction((event?: GestureEvent) => {
  5083. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5084. this.scaleItem = index
  5085. })
  5086. })
  5087. .onActionEnd(() => {
  5088. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5089. this.scaleItem = -1
  5090. })
  5091. }),
  5092. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5093. .onActionStart(() => {
  5094. this.dragItem = index // 记录当前拖动项索引
  5095. this.dragRefOffset = 0 // 重置偏移基准
  5096. })
  5097. .onActionUpdate((event: GestureEvent) => {
  5098. this.offsetY = event.offsetY - this.dragRefOffset;
  5099. this.neighborItem = -1;
  5100. let indexA = this.videoLocalList.indexOf(item);
  5101. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5102. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5103. let value: number = 0;
  5104. if (this.offsetY < 0) {
  5105. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5106. this.neighborItem = indexA - 1;
  5107. this.neighborScale = 1 - value / 20;
  5108. } else if (this.offsetY > 0) {
  5109. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5110. this.neighborItem = indexA + 1;
  5111. this.neighborScale = 1 - value / 20;
  5112. }
  5113. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  5114. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5115. this.offsetY -= this.ITEM_INTV;
  5116. this.dragRefOffset += this.ITEM_INTV;
  5117. this.itemMove(indexA, indexA + 1);
  5118. });
  5119. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5120. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5121. this.offsetY += this.ITEM_INTV;
  5122. this.dragRefOffset -= this.ITEM_INTV;
  5123. this.itemMove(indexA, indexA - 1);
  5124. });
  5125. }
  5126. let curListOffset = this.listScroller.currentOffset()
  5127. // 获取手指信息
  5128. let fingerInfo = event.fingerList[0]
  5129. let clickPercentY =
  5130. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  5131. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  5132. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  5133. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  5134. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  5135. }
  5136. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  5137. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  5138. if (curListOffset.yOffset > scrollVelocity + 5) {
  5139. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  5140. }
  5141. }
  5142. })
  5143. .onActionEnd((event: GestureEvent) => {
  5144. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5145. this.dragItem = -1
  5146. this.neighborItem = -1
  5147. })
  5148. animateTo({
  5149. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5150. }, () => {
  5151. this.scaleItem = -1
  5152. })
  5153. })
  5154. )
  5155. .onCancel(() => {
  5156. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5157. this.dragItem = -1
  5158. this.neighborItem = -1
  5159. })
  5160. animateTo({
  5161. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5162. }, () => {
  5163. this.scaleItem = -1
  5164. })
  5165. })
  5166. ) //拖动List关键代码结束
  5167. }, (item: VideoItem) => item.filePath)
  5168. }
  5169. }
  5170. .scrollBar(BarState.Off)
  5171. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5172. .gesture(PinchGesture({ fingers: 2 })
  5173. .onActionEnd((event: GestureEvent) => {
  5174. this.setlistTwoFingers()
  5175. })
  5176. .onActionUpdate(e => {
  5177. this.scaleValue = this.pinchValue * e.scale
  5178. })
  5179. .onActionStart(e => {
  5180. }))
  5181. // .margin(
  5182. // this.isHiCar()&&(this.windowWidth>1800&&this.windowHeight>=1200)?{bottom:this.bottomBarHeight+98}:
  5183. // {
  5184. // bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  5185. // : (this.isShowCoverHeader() ? this.topBarHeight+35 :
  5186. // this.isHiCarSmall()||this.modeType==4?this.topBarHeight+90:this.topBarHeight+165)
  5187. // })
  5188. .margin({
  5189. bottom:this.isShowCoverHeader() ? this.bottomBarHeight+30
  5190. : this.bottomBarHeight+this.topRectHeight+this.topBarHeight+this.offHeight
  5191. })
  5192. .cachedCount(6)
  5193. .reuseId('list_item')
  5194. .borderRadius(20)
  5195. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5196. TransitionEffect.scale({ x: 0, y: 0 })))
  5197. .layoutWeight(1)
  5198. .onScrollIndex((start) => {
  5199. this.selectedIndex = start
  5200. })
  5201. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5202. .lanes(
  5203. new BreakpointType<number>({
  5204. sm: 1,
  5205. md: 2,
  5206. lg: 2,
  5207. xl: 3,
  5208. xxl: 4
  5209. }).getValue(this.currentBreakpoint),
  5210. new BreakpointType<number>({
  5211. sm: 0,
  5212. md: 12,
  5213. lg: 12,
  5214. xl: 16,
  5215. xxl: 20
  5216. }).getValue(this.currentBreakpoint)
  5217. )
  5218. .onAreaChange((oldValue: Area, newValue: Area) => {
  5219. this.listArea = newValue
  5220. if (this.twoFingerType == 3) {
  5221. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5222. } else if (this.twoFingerType == 2) {
  5223. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5224. } else if (this.twoFingerType == 1) {
  5225. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5226. }
  5227. })
  5228. .onScrollFrameBegin((offset: number) => {
  5229. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  5230. // if (this.isPhoneLan()) {
  5231. // this.setBarHeightHide(offset)
  5232. // } else
  5233. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5234. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5235. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5236. if (this.isScrollHide) {
  5237. this.setBarHeightHide2(offset)
  5238. } else {
  5239. this.setBarHeightNormal()
  5240. }
  5241. } else {
  5242. this.setBarHeightHide(offset)
  5243. }
  5244. return { offsetRemain: offset };
  5245. })
  5246. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  5247. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5248. .onDrop((event?: DragEvent) => {
  5249. try {
  5250. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5251. if (dragData !== undefined) {
  5252. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5253. if (records.length > 0) {
  5254. for (let i = 0; i < records.length; i++) {
  5255. let types = records[i].getTypes();
  5256. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  5257. const fileUriUds =
  5258. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  5259. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  5260. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  5261. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  5262. this.targetFile = fileUriUds.oriUri;
  5263. this.saveVideoDatas([this.targetFile])
  5264. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  5265. }
  5266. }
  5267. }
  5268. } else {
  5269. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  5270. }
  5271. } else {
  5272. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  5273. }
  5274. } catch (error) {
  5275. const err = error as BusinessError;
  5276. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  5277. }
  5278. })
  5279. }
  5280. setBarHeightNormal() {
  5281. this.hideDone = false;
  5282. this.getUIContext().animateTo({
  5283. duration: 300
  5284. }, () => {
  5285. this.bottomBarHeight = 55 + 0;
  5286. this.topBarHeight = 50 + 0;
  5287. this.barOpacity = 1;
  5288. this.barBottomOpacity = 1
  5289. this.currentYOffset = 0;
  5290. this.isHiding = false;
  5291. });
  5292. }
  5293. setBarHeightHide(offset: number) {
  5294. if (offset > 0 && !this.hideDone) {
  5295. this.currentYOffset += offset;
  5296. if (this.currentYOffset <= 100) {
  5297. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  5298. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5299. this.barOpacity = 1 - this.currentYOffset / 100;
  5300. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  5301. } else {
  5302. this.topBarHeight = 0;
  5303. this.bottomBarHeight = 0;
  5304. this.barBottomOpacity = 0
  5305. this.barOpacity = 0;
  5306. this.hideDone = true;
  5307. }
  5308. this.isHiding = true;
  5309. }
  5310. if (offset < 0 && this.isHiding) {
  5311. this.hideDone = false;
  5312. this.getUIContext().animateTo({
  5313. duration: 300
  5314. }, () => {
  5315. this.bottomBarHeight = 55 + 0;
  5316. this.topBarHeight = 50 + 0;
  5317. this.barOpacity = 1;
  5318. this.barBottomOpacity = 1
  5319. this.currentYOffset = 0;
  5320. this.isHiding = false;
  5321. });
  5322. }
  5323. }
  5324. //这个方法没隐藏bottomBar,只隐藏topbar
  5325. setBarHeightHide2(offset: number) {
  5326. if (offset > 0 && !this.hideDone) {
  5327. this.currentYOffset += offset;
  5328. if (this.currentYOffset <= 100) {
  5329. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5330. this.barOpacity = 1 - this.currentYOffset / 100;
  5331. } else {
  5332. this.topBarHeight = 0;
  5333. this.barOpacity = 0;
  5334. this.hideDone = true;
  5335. }
  5336. this.isHiding = true;
  5337. }
  5338. if (offset < 0 && this.isHiding) {
  5339. this.hideDone = false;
  5340. this.getUIContext().animateTo({
  5341. duration: 300
  5342. }, () => {
  5343. this.topBarHeight = 50 + 0;
  5344. this.barOpacity = 1;
  5345. this.currentYOffset = 0;
  5346. this.isHiding = false;
  5347. });
  5348. }
  5349. }
  5350. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  5351. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  5352. switch (item.type) {
  5353. case CommonConstants.TYPE_IS_DIR:
  5354. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  5355. let offsetB = 0
  5356. if(this.twoFingerType==4){
  5357. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5358. let cur = this.waterScroller.currentOffset()
  5359. if (cur && typeof cur.yOffset === 'number') {
  5360. offsetB = cur.yOffset
  5361. }
  5362. }
  5363. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  5364. }else
  5365. if (this.isGridMusic) {
  5366. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5367. let cur = this.scroller.currentOffset()
  5368. if (cur && typeof cur.yOffset === 'number') {
  5369. offsetB = cur.yOffset
  5370. }
  5371. }
  5372. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  5373. } else {
  5374. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5375. let cur = this.listScroller.currentOffset()
  5376. if (cur && typeof cur.yOffset === 'number') {
  5377. offsetB = cur.yOffset
  5378. }
  5379. }
  5380. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  5381. }
  5382. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  5383. this.showVerifyDialog()
  5384. this.currentTitleName = '私密音频'
  5385. this.currentTitleCover = $r('app.media.ic_avatar5')
  5386. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  5387. this.titleBarModel.setTitleName('最近播放')
  5388. this.currentTitleCover = $r('app.media.ic_avatar2')
  5389. this.currentTitleName = '最近播放'
  5390. //加载动画效果
  5391. this.updateListData(this.historyList, true)
  5392. // this.videoLocalList = this.historyList
  5393. if (ArrayUtil.isEmpty(this.historyList)) {
  5394. ToastUtil.showToast('最近播放记录空空如也')
  5395. } else {
  5396. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  5397. }
  5398. this.isHistory = true
  5399. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  5400. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  5401. this.titleBarModel.setTitleName('我的收藏')
  5402. this.currentTitleName = '我的收藏'
  5403. this.currentTitleCover = $r('app.media.ic_avatar1')
  5404. //加载动画效果
  5405. this.updateListData(this.favList)
  5406. if (ArrayUtil.isEmpty(this.favList)) {
  5407. ToastUtil.showToast('无音乐收藏记录')
  5408. } else {
  5409. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  5410. }
  5411. this.isFavMusic = true
  5412. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  5413. } else {
  5414. this.currentTitleName = item.name
  5415. this.currentPath = item.filePath
  5416. this.currentTitleCover = $r('app.media.ic_avatar5')
  5417. this.getSortedFiles(this.currentPath)
  5418. }
  5419. //进入歌单的时候的滚动位置在顶部
  5420. if(this.twoFingerType==4){
  5421. setTimeout(() => {
  5422. this.waterScroller.scrollEdge(Edge.Top)
  5423. this.scroller.scrollEdge(Edge.Top)
  5424. }, 380)
  5425. }else{
  5426. if (this.isGridMusic) {
  5427. this.scroller.scrollEdge(Edge.Top)
  5428. }else{
  5429. this.listScroller.scrollEdge(Edge.Top)
  5430. }
  5431. }
  5432. break;
  5433. case CommonConstants.TYPE_IS_ARTIST:
  5434. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  5435. let offsetA = 0
  5436. if(this.twoFingerType==4){
  5437. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5438. let cur = this.waterScroller.currentOffset()
  5439. if (cur && typeof cur.yOffset === 'number') {
  5440. offsetA = cur.yOffset
  5441. }
  5442. }
  5443. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  5444. }else
  5445. if (this.isGridMusic) {
  5446. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5447. let cur = this.scroller.currentOffset()
  5448. if (cur && typeof cur.yOffset === 'number') {
  5449. offsetA = cur.yOffset
  5450. }
  5451. }
  5452. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  5453. } else {
  5454. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5455. let cur = this.listScroller.currentOffset()
  5456. if (cur && typeof cur.yOffset === 'number') {
  5457. offsetA = cur.yOffset
  5458. }
  5459. }
  5460. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  5461. }
  5462. let mList = this.artistMap.get(item.name)
  5463. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  5464. Utility.doSortListAscending(mList)
  5465. this.isCanBack = true
  5466. this.titleBarModel.setTitleName(item.name)
  5467. this.currentTitleName = '艺术家:' + item.name
  5468. if (item.pixelMapPath) {
  5469. this.currentTitleCover = item.pixelMapPath
  5470. }
  5471. this.updateListData(mList)
  5472. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  5473. }
  5474. //进入歌单的时候的滚动位置在顶部
  5475. if(this.twoFingerType==4){
  5476. setTimeout(() => {
  5477. this.waterScroller.scrollEdge(Edge.Top)
  5478. this.scroller.scrollEdge(Edge.Top)
  5479. }, 380)
  5480. }else{
  5481. if (this.isGridMusic) {
  5482. this.scroller.scrollEdge(Edge.Top)
  5483. }else{
  5484. this.listScroller.scrollEdge(Edge.Top)
  5485. }
  5486. }
  5487. break;
  5488. case CommonConstants.TYPE_IS_ALBUM:
  5489. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  5490. let offset = 0
  5491. if(this.twoFingerType==4){
  5492. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5493. let cur = this.waterScroller.currentOffset()
  5494. if (cur && typeof cur.yOffset === 'number') {
  5495. offset = cur.yOffset
  5496. }
  5497. }
  5498. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  5499. }else
  5500. if (this.isGridMusic) {
  5501. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5502. let cur = this.scroller.currentOffset()
  5503. if (cur && typeof cur.yOffset === 'number') {
  5504. offset = cur.yOffset
  5505. }
  5506. }
  5507. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  5508. } else {
  5509. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5510. let cur = this.listScroller.currentOffset()
  5511. if (cur && typeof cur.yOffset === 'number') {
  5512. offset = cur.yOffset
  5513. }
  5514. }
  5515. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  5516. }
  5517. let albumList = this.albumMap.get(item.name)
  5518. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  5519. Utility.doSortListAscending(albumList)
  5520. this.isCanBack = true
  5521. this.titleBarModel.setTitleName(item.name)
  5522. this.currentTitleName = '专辑:' + item.name
  5523. if (item.pixelMapPath) {
  5524. this.currentTitleCover = item.pixelMapPath
  5525. }
  5526. this.updateListData(albumList)
  5527. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  5528. this.mScrollMap.set(item.name, this.selectedIndex)
  5529. }
  5530. //进入歌单的时候的滚动位置在顶部
  5531. if(this.twoFingerType==4){
  5532. setTimeout(() => {
  5533. this.waterScroller.scrollEdge(Edge.Top)
  5534. this.scroller.scrollEdge(Edge.Top)
  5535. }, 380)
  5536. }else{
  5537. if (this.isGridMusic) {
  5538. this.scroller.scrollEdge(Edge.Top)
  5539. }else{
  5540. this.listScroller.scrollEdge(Edge.Top)
  5541. }
  5542. }
  5543. break;
  5544. case CommonConstants.TYPE_IS_CSJAD:
  5545. return
  5546. break;
  5547. case CommonConstants.TYPE_LOCAL:
  5548. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  5549. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  5550. const cueTracks:CueTrack[] = cueinfo.tracks
  5551. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  5552. if(ArrayUtil.isNotEmpty(cueTracks)){
  5553. this.showCueDialog(cueTracks,cueinfo)
  5554. }
  5555. // this.showCueSheet = !this.showCueSheet
  5556. return
  5557. }
  5558. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5559. this.stop();
  5560. }
  5561. if (isOpen) {
  5562. this.currentSong = item
  5563. if (index !== undefined) {
  5564. this.curIndex = index
  5565. }
  5566. this.songList = []
  5567. this.songList.push(item)
  5568. this.sonDataSource.pushArrayData(this.songList)
  5569. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  5570. this.currentSong = item
  5571. if (index !== undefined) {
  5572. this.curIndex = index
  5573. }
  5574. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5575. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5576. }else {
  5577. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5578. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  5579. this.songList = globalVideoList
  5580. this.sonDataSource.pushArrayData(this.songList)
  5581. this.currentSong = globalVideoList[this.curIndex]
  5582. }
  5583. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5584. this.videoUrl = this.currentSong.filePath
  5585. this.name = this.currentSong.name
  5586. this.cover = this.currentSong.pixelMapPath
  5587. this.artist = this.currentSong.artist
  5588. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  5589. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  5590. this.startPlayOrResumePlay()
  5591. break;
  5592. case CommonConstants.TYPE_WEBDAV:
  5593. // 处理网络音频播放(WebDAV)
  5594. Logger.info(`heanup 处理网络音频播放: ${item.name}, URL: ${item.filePath}`)
  5595. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5596. this.stop();
  5597. }
  5598. if (isOpen) {
  5599. this.currentSong = item
  5600. if (index !== undefined) {
  5601. this.curIndex = index
  5602. }
  5603. this.songList = []
  5604. this.songList.push(item)
  5605. this.sonDataSource.pushArrayData(this.songList)
  5606. } else if (isFromSonPlayList) {
  5607. // 点击来自右下角的播放列表
  5608. this.currentSong = item
  5609. if (index !== undefined) {
  5610. this.curIndex = index
  5611. }
  5612. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5613. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5614. } else {
  5615. // 从全局网络音频列表中查找
  5616. let globalVideoList = this.videoLocalList.filter(video => video.type === CommonConstants.TYPE_WEBDAV) as VideoItem[];
  5617. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  5618. if (this.curIndex === -1 && index !== undefined) {
  5619. this.curIndex = index;
  5620. }
  5621. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  5622. this.currentSong = this.songList[this.curIndex];
  5623. this.sonDataSource.pushArrayData(this.songList)
  5624. }
  5625. AppStorage.setOrCreate('currentSong', this.currentSong);
  5626. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  5627. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  5628. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  5629. this.name = this.currentSong.name
  5630. this.cover = this.currentSong.pixelMapPath
  5631. this.artist = this.currentSong.artist
  5632. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  5633. this.startPlayOrResumePlay()
  5634. break;
  5635. }
  5636. }
  5637. private cueComponentId: number = 0
  5638. //显示cue分轨列表对话框
  5639. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  5640. this.getUIContext().getPromptAction().openCustomDialog({
  5641. builder: () => {
  5642. this.cueComptentBuilder(cueTracks,cueinfo)
  5643. },
  5644. isModal:true,
  5645. showInSubWindow:false,
  5646. maskColor: Color.Transparent,
  5647. dialogTransition: // 设置弹窗内容显示的过渡效果
  5648. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  5649. .animation({ duration: 600, curve: Curve.Smooth }),
  5650. maskTransition: // 设置蒙层显示的过渡效果
  5651. TransitionEffect.opacity(0.5)
  5652. .animation({ duration: 600, curve: Curve.Smooth })
  5653. }).then((dialogId: number) => {
  5654. this.cueComponentId = dialogId
  5655. })
  5656. .catch((error: BusinessError) => {
  5657. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5658. })
  5659. }
  5660. @Builder
  5661. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  5662. CueComptent({
  5663. title:cueinfo.title,
  5664. cueTracks:cueTracks,
  5665. isLongNameRoLL:this.isLongNameRoLL,
  5666. onCancel:()=>{
  5667. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  5668. },
  5669. onDoItemClick:(item: CueTrack, index: number)=>{
  5670. //获取cueinfo对应的filePath
  5671. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  5672. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  5673. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  5674. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  5675. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  5676. if (this.currentSong){
  5677. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5678. this.stop();//播放之前先停止之前播放。
  5679. }
  5680. this.songList = globalVideoList
  5681. this.sonDataSource.pushArrayData(this.songList)
  5682. if(this.currentSong.type==CommonConstants.TYPE_WEBDAV){
  5683. this.videoUrl = this.currentSong.filePath.replace(/ /g, '%20');
  5684. }else{
  5685. this.videoUrl = this.currentSong.filePath
  5686. }
  5687. this.name = item.title||this.currentSong.name
  5688. this.cover = this.currentSong.pixelMapPath
  5689. this.artist = item.performer||this.currentSong.artist
  5690. this.currentSong.name = this.name
  5691. this.currentSong.artist = this.artist
  5692. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5693. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  5694. }
  5695. }
  5696. })
  5697. }
  5698. @Builder
  5699. PlayController() {
  5700. Column() {
  5701. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  5702. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5703. Row() {
  5704. if(this.isHiCar()){
  5705. this.playConRigth()
  5706. Column(){
  5707. this.centerName()
  5708. }.layoutWeight(1)
  5709. .onClick(()=>{
  5710. this.showPlayerView()
  5711. })
  5712. this.playConLeft(false)
  5713. }else{
  5714. this.playConLeft()
  5715. this.playConRigth()
  5716. }
  5717. }
  5718. .width('100%')
  5719. .height(this.bottomBarHeight)
  5720. .justifyContent(FlexAlign.Center)
  5721. .hitTestBehavior(HitTestMode.Transparent)
  5722. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  5723. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  5724. // modalTransition: ModalTransition.DEFAULT,
  5725. transition: AnimationHelper.transitionInDown(666),
  5726. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  5727. })
  5728. .padding({
  5729. left: 16,
  5730. right: 16
  5731. })
  5732. Line()
  5733. .width('100%')
  5734. .height(25)
  5735. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  5736. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5737. }
  5738. .clickEffect({ level: ClickEffectLevel.HEAVY })
  5739. }
  5740. @State isFrontWhite: boolean = false
  5741. @Builder
  5742. centerName() {
  5743. Column() {
  5744. Text(this.currentSong?.name)
  5745. .fontSize(16)
  5746. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5747. .maxLines(1)
  5748. .fontColor($r('app.color.text_color'))
  5749. .fontWeight(500);
  5750. Row() {
  5751. Text(this.currentSong?.artist)
  5752. .margin({ top: 2 })
  5753. .fontSize(13)
  5754. .textAlign(TextAlign.Start)
  5755. .maxLines(1)
  5756. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5757. .fontColor($r('app.color.text_color'));
  5758. }
  5759. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5760. }
  5761. .alignItems(HorizontalAlign.Center)
  5762. }
  5763. @Builder
  5764. playConLeft(isLeft: boolean = true) {
  5765. Row() {
  5766. RotatingCover({ songLabel: this.currentSong?.pixelMapPath });
  5767. Column() {
  5768. Text(this.currentSong?.name)
  5769. .fontSize(16)
  5770. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5771. .maxLines(1)
  5772. .fontColor($r('app.color.text_color'))
  5773. .fontWeight(500);
  5774. Row() {
  5775. Text(this.currentSong?.artist)
  5776. .margin({ top: 2 })
  5777. .fontSize(13)
  5778. .textAlign(TextAlign.Start)
  5779. .maxLines(1)
  5780. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5781. .fontColor($r('app.color.text_color'));
  5782. }
  5783. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5784. }
  5785. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  5786. .margin({ right: isLeft?22:10 })
  5787. .visibility(isLeft? Visibility.Visible:Visibility.None)
  5788. }
  5789. .padding({ right: 18 })
  5790. .layoutWeight(isLeft?1:0)
  5791. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5792. .onClick(() => {
  5793. this.showPlayerView()
  5794. })
  5795. }
  5796. //打开播放页
  5797. showPlayerView() {
  5798. if (ArrayUtil.isNotEmpty(this.songList)) {
  5799. this.isShowPlay = true;
  5800. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  5801. this.initLyric(lyricPath);
  5802. this.startAutoHide();
  5803. } else {
  5804. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  5805. }
  5806. }
  5807. @Builder
  5808. playConRigth() {
  5809. Row() {
  5810. Image($r('app.media.hm_previous'))
  5811. .height(28)
  5812. .width(28)
  5813. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5814. .margin({ left: 8, right: 16 })
  5815. .fillColor(this.themeColor)
  5816. .displayPriority(2)
  5817. .onClick(() => {
  5818. if (ArrayUtil.isNotEmpty(this.songList)) {
  5819. this.playPrevious()
  5820. } else {
  5821. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5822. }
  5823. })
  5824. //播放进度条
  5825. Stack() {
  5826. Progress({
  5827. value: Math.floor(this.progressValue),
  5828. type: ProgressType.Ring,
  5829. })
  5830. .color(this.themeColor)// 进度条前景色为灰色
  5831. .backgroundColor($r('app.color.index_background'))
  5832. .height(40)
  5833. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5834. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  5835. .height(38)
  5836. .width(38)
  5837. .displayPriority(3)
  5838. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5839. .fillColor(this.themeColor)
  5840. .onClick(() => {
  5841. if (ArrayUtil.isNotEmpty(this.songList)) {
  5842. console.info('onecold playOrPause 4642')
  5843. this.playOrPause()
  5844. } else {
  5845. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5846. }
  5847. })
  5848. }
  5849. Image($r('app.media.hm_next'))
  5850. .height(28)
  5851. .width(28)
  5852. .margin({
  5853. right: 16,
  5854. left: 16
  5855. })
  5856. .fillColor(this.themeColor)
  5857. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5858. .displayPriority(2)
  5859. .onClick(() => {
  5860. if (ArrayUtil.isNotEmpty(this.songList)) {
  5861. this.playNext()
  5862. } else {
  5863. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5864. }
  5865. })
  5866. Image($r('app.media.hm_playlist'))
  5867. .height(28)
  5868. .width(28)
  5869. .displayPriority(1)
  5870. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5871. .fillColor(this.themeColor)
  5872. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  5873. height: '95%',
  5874. dragBar: true,
  5875. showClose: true,
  5876. blurStyle: BlurStyle.Thin,
  5877. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5878. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  5879. title: {
  5880. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5881. + `(${this.songList.length}首)`
  5882. }
  5883. })
  5884. .onClick(() => {
  5885. if (ArrayUtil.isNotEmpty(this.songList)) {
  5886. this.isShowSheet = !this.isShowSheet;
  5887. this.isFrontWhite = false
  5888. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  5889. this.scrollIndex()
  5890. } else {
  5891. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5892. }
  5893. })
  5894. }
  5895. }
  5896. scrollIndex(){
  5897. try {
  5898. setTimeout(() => {
  5899. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  5900. if(this.curIndex>60){
  5901. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  5902. }else{
  5903. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5904. }
  5905. })
  5906. }, 123)
  5907. }catch (error) {
  5908. console.error(`onecold scrollIndex出错: ${error}`);
  5909. }
  5910. }
  5911. //播放列表布局
  5912. @Builder
  5913. PlayListSheet() {
  5914. Column() {
  5915. this.PlayList()
  5916. }
  5917. .width('100%')
  5918. .height('100%')
  5919. }
  5920. @State titleStr: string = ''
  5921. @State ablumStr: string = ''
  5922. @State artistStr: string = ''
  5923. @State lyricConStr: string = ''
  5924. @State currentEditItem: string = ''
  5925. @State yearStr: string = ''
  5926. @State trackStr: string = ''
  5927. @State genreStr: string = ''
  5928. @State imagePathStr: string = ''
  5929. @State albumArtistStr: string = ''
  5930. @State composerStr: string = ''
  5931. @State lyricistStr: string = ''
  5932. @State commentStr: string = ''
  5933. @State discStr: string = ''
  5934. doUpdateData() {
  5935. setTimeout(() => {
  5936. if (this.modeType === 0) {
  5937. this.deleteCache(this.currentPath)
  5938. this.getSortedFiles(this.currentPath)
  5939. }
  5940. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5941. workerInstance.postMessage({ code: 3, data: this.context });
  5942. workerInstance.postMessage({ code: 4, data: this.context });
  5943. }, 999)
  5944. }
  5945. //编辑信息
  5946. async doEdit(item: VideoItem) {
  5947. if (!item) {
  5948. return
  5949. }
  5950. if (StrUtil.isEmpty(this.titleStr)) {
  5951. ToastUtil.showToast('标题不能为空')
  5952. return
  5953. }
  5954. DialogHelper.showLoadingDialog()
  5955. await PermissionUtil.activatePermission(item.filePath)
  5956. let tempOutPath = ''
  5957. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  5958. if(!item.filePath.toLowerCase().includes(this.packName)){
  5959. tempOutPath = this.currentPath + '/' + item.fileName
  5960. }
  5961. console.info('onecold tempOutPath ='+tempOutPath)
  5962. //用户更改了封面,那就内嵌下封面
  5963. if(StrUtil.isNotEmpty(this.imagePathStr)){
  5964. const resultCover:boolean = await changeMusicCover(this.context,
  5965. item.filePath,this.imagePathStr,true,tempOutPath);
  5966. this.imagePathStr = ''
  5967. if(resultCover){
  5968. ToastUtil.showToast('内嵌封面成功')
  5969. }
  5970. }
  5971. const metadata:FFMpegTags = {
  5972. title: this.titleStr,
  5973. artist: this.artistStr,
  5974. album: this.ablumStr,
  5975. TYER:this.yearStr,
  5976. genre:this.genreStr,
  5977. track:this.trackStr,
  5978. album_artist:this.albumArtistStr,
  5979. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  5980. COMPOSER:this.composerStr,
  5981. lyricist:this.lyricistStr,
  5982. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  5983. comment:this.commentStr,
  5984. disc:this.discStr,
  5985. };
  5986. let newInput = item.filePath
  5987. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  5988. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  5989. newInput = tempOutPath
  5990. tempOutPath = ''
  5991. }
  5992. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  5993. const result:boolean = await repairAudioMetadata(
  5994. newInput,
  5995. this.lyricConStr,
  5996. metadata,
  5997. true,
  5998. tempOutPath
  5999. );
  6000. if (result) {
  6001. if(!item.filePath.includes(this.packName)){
  6002. //内嵌成功的歌路径如果不是包含包名,则要入库
  6003. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6004. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6005. this.table.insert(newItem, (id: number) => {
  6006. //加入数据库
  6007. if(this.modeType==0){
  6008. this.deleteCache(this.currentPath)
  6009. this.getSortedFiles(this.currentPath)
  6010. }
  6011. });
  6012. }
  6013. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  6014. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  6015. (success: boolean, error?: string) => {
  6016. // this.isShowEdit = false
  6017. if (success) {
  6018. console.log(" onecold 编辑信息成功,数据库已同步");
  6019. ToastUtil.showToast('内嵌音乐标签成功')
  6020. this.isShowMoreView = false
  6021. this.name = this.titleStr
  6022. if (item.filePath == this.currentSong?.filePath) {
  6023. this.currentSong.name = this.titleStr
  6024. this.artist = this.artistStr
  6025. this.currentSong.artist = this.artistStr
  6026. this.currentSong.album = this.ablumStr
  6027. this.currentSong.year = this.yearStr
  6028. this.currentSong.genre = this.genreStr
  6029. this.currentSong.track = this.trackStr
  6030. this.currentSong.lyricContent = this.lyricConStr
  6031. this.initLyric(item.filePath)
  6032. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6033. this.currentSong.COMPOSER = this.composerStr
  6034. this.currentSong.LYRICIST = this.lyricistStr
  6035. this.currentSong.COMMENT = this.commentStr
  6036. }
  6037. this.doUpdateData()
  6038. } else {
  6039. // ToastUtil.showToast('保存失败' + error?.toString())
  6040. console.error(" onecold 编辑信息数据库失败原因: " + error);
  6041. }
  6042. // 关闭进度条
  6043. DialogHelper.closeLoading();
  6044. });
  6045. console.log(' onecold 元数据标签更新成功,');
  6046. } else {
  6047. // 关闭进度条
  6048. DialogHelper.closeLoading();
  6049. ToastUtil.showToast('内嵌音乐标签失败')
  6050. console.log('onecold 内嵌音乐标签失败');
  6051. }
  6052. this.longItemFilePath = ''
  6053. this.tempLyricContent = ''
  6054. this.isShowEdit = false
  6055. }
  6056. updateLyricToDB() {
  6057. }
  6058. @Builder
  6059. editSheet(item: VideoItem) {
  6060. Scroll() {
  6061. Column() {
  6062. this.editDetail(item)
  6063. }
  6064. }
  6065. .width('100%')
  6066. .height('100%')
  6067. }
  6068. @Builder
  6069. editDetail(item: VideoItem) {
  6070. Column() {
  6071. if (item) {
  6072. Row() {
  6073. Stack() {
  6074. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6075. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6076. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6077. item.pixelMapPath)
  6078. .fillColor(this.themeColor)
  6079. .height(88)
  6080. .width(88)
  6081. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6082. .borderRadius(12)
  6083. .clip(true)
  6084. .opacity(this.opacityItem)// 绑定透明度
  6085. .margin({ left: 25 })
  6086. }
  6087. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6088. .onClick(async () => {
  6089. const imagePath:string | undefined = await this.goSelectImage(item);
  6090. if (imagePath) {
  6091. //用户更改过图片
  6092. this.imagePathStr = imagePath
  6093. }
  6094. })
  6095. .width('28%')
  6096. Row() {
  6097. Column() {
  6098. Text(item.name)
  6099. .fontSize(17)
  6100. .maxLines(1)
  6101. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6102. .animation({
  6103. duration: 555,
  6104. curve: 'Linear',
  6105. })
  6106. .fontColor(this.themeColor)
  6107. .margin({ left: 8 })
  6108. Row() {
  6109. Text(item.artist)
  6110. .fontSize(14)
  6111. .maxLines(1)
  6112. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6113. .padding({ top: 8 })
  6114. .fontColor(this.themeColor)
  6115. .margin({ left: 8 })
  6116. }
  6117. }
  6118. .height('100%')
  6119. .width(100)
  6120. .layoutWeight(1)
  6121. .justifyContent(FlexAlign.Center)
  6122. .alignItems(HorizontalAlign.Start)
  6123. Column() {
  6124. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6125. Row(){
  6126. SymbolGlyph($r('sys.symbol.picture'))
  6127. .fontSize(18)
  6128. .fontColor([Color.White])
  6129. Text('获取封面')
  6130. .margin({ left: 4 })
  6131. .fontSize(11)
  6132. .fontColor(Color.White)
  6133. .fontWeight(480)
  6134. .textAlign(TextAlign.Center)
  6135. }
  6136. .justifyContent(FlexAlign.Center)
  6137. }
  6138. .height(38)
  6139. .width(100)
  6140. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6141. .backgroundColor(this.themeColor)
  6142. .stateEffect(true)
  6143. .margin({ right: 35 })
  6144. .onClick(async () => {
  6145. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6146. this.showTipsDialog();
  6147. return; // Return empty string when no API is configured
  6148. }
  6149. const imagePath:string | undefined = await this.doSearchCover(item);
  6150. console.info('onecold imagePath = '+imagePath)
  6151. if (StrUtil.isNotEmpty(imagePath)) {
  6152. //用户更改过图片
  6153. this.imagePathStr = imagePath
  6154. ToastUtil.showToast('获取封面成功')
  6155. }else{
  6156. ToastUtil.showToast('获取封面失败,请重试')
  6157. }
  6158. })
  6159. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6160. Row(){
  6161. SymbolGlyph($r('sys.symbol.input_mode'))
  6162. .fontSize(18)
  6163. .fontColor([Color.White])
  6164. Text('获取歌词')
  6165. .margin({ left: 4 })
  6166. .fontSize(11)
  6167. .fontColor(Color.White)
  6168. .fontWeight(480)
  6169. .textAlign(TextAlign.Center)
  6170. }
  6171. .justifyContent(FlexAlign.Center)
  6172. }
  6173. .height(38)
  6174. .width(100)
  6175. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6176. .backgroundColor(this.themeColor)
  6177. .stateEffect(true)
  6178. .margin({ top: 9, right: 35 })
  6179. .onClick(async () => {
  6180. //判断有没有设置api
  6181. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6182. if (StrUtil.isEmpty(apiUrl)) {
  6183. this.isLyricSetting = false
  6184. this.showTipsDialog()
  6185. return
  6186. }
  6187. let artist = item.artist
  6188. let title = item.name
  6189. if(!artist)
  6190. artist = ''
  6191. if(!title)
  6192. title = ''
  6193. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  6194. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6195. this.lyricConStr = res;
  6196. ToastUtil.showToast('获取歌词成功')
  6197. }else{
  6198. ToastUtil.showToast('获取歌词失败,请重试')
  6199. }
  6200. })
  6201. }
  6202. .justifyContent(FlexAlign.Start)
  6203. }
  6204. .height('100%')
  6205. .justifyContent(FlexAlign.Start)
  6206. .layoutWeight(1)
  6207. }
  6208. .width('100%')
  6209. .height(98)
  6210. Row() {
  6211. Text('标题:')
  6212. .fontSize(14)
  6213. .fontColor($r('app.color.text_color'))
  6214. .margin({ left: 22 })
  6215. TextInput({ text: item.name })
  6216. .height(40)
  6217. .maxLines(1)
  6218. .fontSize(14)
  6219. .layoutWeight(1)
  6220. .fontColor($r('app.color.text_color'))
  6221. .margin({ right: 20, left: 10 })
  6222. .onChange((val: string) => {
  6223. this.titleStr = val
  6224. })
  6225. }
  6226. .width('100%')
  6227. .margin({ top: 10, bottom: 10 })
  6228. .justifyContent(FlexAlign.Start)
  6229. Row() {
  6230. Text('艺术家:')
  6231. .fontSize(14)
  6232. .fontColor($r('app.color.text_color'))
  6233. .margin({ left: 22 })
  6234. TextInput({ text: item.artist })
  6235. .height(40)
  6236. .maxLines(1)
  6237. .fontSize(14)
  6238. .layoutWeight(1)
  6239. .fontColor($r('app.color.text_color'))
  6240. .margin({ right: 20, left: 10 })
  6241. .onChange((val: string) => {
  6242. this.artistStr = val
  6243. })
  6244. }
  6245. .width('100%')
  6246. .margin({ top: 10, bottom: 10 })
  6247. .justifyContent(FlexAlign.Start)
  6248. Row() {
  6249. Text('专辑名:')
  6250. .fontSize(14)
  6251. .fontColor($r('app.color.text_color'))
  6252. .margin({ left: 22 })
  6253. TextInput({ text: item.album })
  6254. .height(40)
  6255. .maxLines(1)
  6256. .fontSize(14)
  6257. .layoutWeight(1)
  6258. .fontColor($r('app.color.text_color'))
  6259. .margin({ right: 20, left: 10 })
  6260. .onChange((val: string) => {
  6261. this.ablumStr = val
  6262. })
  6263. }
  6264. .width('100%')
  6265. .margin({ top: 10, bottom: 10 })
  6266. .justifyContent(FlexAlign.Start)
  6267. Row() {
  6268. Column(){
  6269. Column(){
  6270. Text('歌词:')
  6271. .fontSize(14)
  6272. .fontColor($r('app.color.text_color'))
  6273. .margin({ top:9,left: 22 })
  6274. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6275. SymbolGlyph($r('sys.symbol.trash_fill'))
  6276. .fontSize(25)
  6277. .alignSelf(ItemAlign.Center)
  6278. .margin({ left: 22,top:25})
  6279. }
  6280. .backgroundColor(Color.Transparent)
  6281. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6282. Visibility.None:Visibility.Visible)
  6283. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6284. .onClick(()=>{
  6285. this.lyricConStr = ''
  6286. this.lyricContent = ''
  6287. this.tempLyricContent = ''
  6288. })
  6289. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6290. SymbolGlyph($r('sys.symbol.plus'))
  6291. .fontSize(25)
  6292. .alignSelf(ItemAlign.Center)
  6293. .margin({ left: 22,top:25})
  6294. }
  6295. .backgroundColor(Color.Transparent)
  6296. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6297. .onClick( ()=>{
  6298. this.callFilePickerSelectFileForLyric()
  6299. })
  6300. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6301. SymbolGlyph($r('sys.symbol.traditional_square'))
  6302. .fontSize(25)
  6303. .alignSelf(ItemAlign.Center)
  6304. .margin({ left: 22,top:25})
  6305. }
  6306. .backgroundColor(Color.Transparent)
  6307. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6308. Visibility.None:Visibility.Visible)
  6309. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6310. .onClick( ()=>{
  6311. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6312. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  6313. })
  6314. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6315. Image($r('app.media.jianti'))
  6316. .height(25)
  6317. .fillColor($r('app.color.text_color'))
  6318. .alignSelf(ItemAlign.Center)
  6319. .margin({ left: 22,top:25})
  6320. }
  6321. .backgroundColor(Color.Transparent)
  6322. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6323. Visibility.None:Visibility.Visible)
  6324. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6325. .onClick( ()=>{
  6326. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6327. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  6328. })
  6329. }
  6330. .layoutWeight(1)
  6331. }
  6332. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  6333. this.tempLyricContent })
  6334. .type(TextAreaType.NORMAL)
  6335. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  6336. .fontSize(14)
  6337. .layoutWeight(1)
  6338. .fontColor($r('app.color.text_color'))
  6339. .margin({ right: 20, left: 10 })
  6340. .onChange((val: string) => {
  6341. this.lyricConStr = val
  6342. })
  6343. }
  6344. .width('100%')
  6345. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  6346. .margin({ top: 10, bottom: 10 })
  6347. .justifyContent(FlexAlign.Start)
  6348. Row() {
  6349. Text('年份:')
  6350. .fontSize(14)
  6351. .fontColor($r('app.color.text_color'))
  6352. .margin({ left: 22 })
  6353. TextInput({ text: item.year })
  6354. .height(40)
  6355. .maxLines(1)
  6356. .fontSize(14)
  6357. .type(InputType.Number)
  6358. .layoutWeight(1)
  6359. .fontColor($r('app.color.text_color'))
  6360. .margin({ right: 20, left: 10 })
  6361. .onChange((val: string) => {
  6362. this.yearStr = val
  6363. })
  6364. }
  6365. .width('100%')
  6366. .margin({ top: 10, bottom: 10 })
  6367. .justifyContent(FlexAlign.Start)
  6368. Row() {
  6369. Text('音轨号:')
  6370. .fontSize(14)
  6371. .fontColor($r('app.color.text_color'))
  6372. .margin({ left: 22 })
  6373. TextInput({ text:item.track=='未知'?'': item.track })
  6374. .height(40)
  6375. .maxLines(1)
  6376. .fontSize(14)
  6377. .type(InputType.Number)
  6378. .layoutWeight(1)
  6379. .fontColor($r('app.color.text_color'))
  6380. .margin({ right: 20, left: 10 })
  6381. .onChange((val: string) => {
  6382. this.trackStr = val
  6383. })
  6384. }
  6385. .width('100%')
  6386. .margin({ top: 10, bottom: 10 })
  6387. .justifyContent(FlexAlign.Start)
  6388. Row() {
  6389. Text('碟号:')
  6390. .fontSize(14)
  6391. .fontColor($r('app.color.text_color'))
  6392. .margin({ left: 22 })
  6393. TextInput({ text:item.disc })
  6394. .height(40)
  6395. .maxLines(1)
  6396. .fontSize(14)
  6397. .type(InputType.Number)
  6398. .layoutWeight(1)
  6399. .fontColor($r('app.color.text_color'))
  6400. .margin({ right: 20, left: 10 })
  6401. .onChange((val: string) => {
  6402. this.discStr = val
  6403. })
  6404. }
  6405. .width('100%')
  6406. .margin({ top: 10, bottom: 10 })
  6407. .justifyContent(FlexAlign.Start)
  6408. Row() {
  6409. Text('风格:')
  6410. .fontSize(14)
  6411. .fontColor($r('app.color.text_color'))
  6412. .margin({ left: 22 })
  6413. TextInput({ text: item.genre })
  6414. .height(40)
  6415. .maxLines(1)
  6416. .fontSize(14)
  6417. .layoutWeight(1)
  6418. .fontColor($r('app.color.text_color'))
  6419. .margin({ right: 20, left: 10 })
  6420. .onChange((val: string) => {
  6421. this.genreStr = val
  6422. })
  6423. }
  6424. .width('100%')
  6425. .margin({ top: 10, bottom: 10 })
  6426. .justifyContent(FlexAlign.Start)
  6427. Row() {
  6428. Text('专辑艺术家:')
  6429. .fontSize(14)
  6430. .fontColor($r('app.color.text_color'))
  6431. .margin({ left: 22 })
  6432. TextInput({ text: item.ALBUMARTIST })
  6433. .height(40)
  6434. .maxLines(1)
  6435. .fontSize(14)
  6436. .layoutWeight(1)
  6437. .fontColor($r('app.color.text_color'))
  6438. .margin({ right: 20, left: 10 })
  6439. .onChange((val: string) => {
  6440. this.albumArtistStr = val
  6441. })
  6442. }
  6443. .width('100%')
  6444. .margin({ top: 10, bottom: 10 })
  6445. .justifyContent(FlexAlign.Start)
  6446. Row() {
  6447. Text('作曲:')
  6448. .fontSize(14)
  6449. .fontColor($r('app.color.text_color'))
  6450. .margin({ left: 22 })
  6451. TextInput({ text: item.COMPOSER })
  6452. .height(40)
  6453. .maxLines(1)
  6454. .fontSize(14)
  6455. .layoutWeight(1)
  6456. .fontColor($r('app.color.text_color'))
  6457. .margin({ right: 20, left: 10 })
  6458. .onChange((val: string) => {
  6459. this.composerStr = val
  6460. })
  6461. }
  6462. .width('100%')
  6463. .margin({ top: 10, bottom: 10 })
  6464. .justifyContent(FlexAlign.Start)
  6465. Row() {
  6466. Text('作词:')
  6467. .fontSize(14)
  6468. .fontColor($r('app.color.text_color'))
  6469. .margin({ left: 22 })
  6470. TextInput({ text: item.LYRICIST })
  6471. .height(40)
  6472. .maxLines(1)
  6473. .fontSize(14)
  6474. .layoutWeight(1)
  6475. .fontColor($r('app.color.text_color'))
  6476. .margin({ right: 20, left: 10 })
  6477. .onChange((val: string) => {
  6478. this.lyricistStr = val
  6479. })
  6480. }
  6481. .width('100%')
  6482. .margin({ top: 10, bottom: 10 })
  6483. .justifyContent(FlexAlign.Start)
  6484. Row() {
  6485. Text('注释:')
  6486. .fontSize(14)
  6487. .fontColor($r('app.color.text_color'))
  6488. .margin({ left: 22 })
  6489. TextInput({ text: item.COMMENT })
  6490. .height(40)
  6491. .maxLines(1)
  6492. .fontSize(14)
  6493. .layoutWeight(1)
  6494. .fontColor($r('app.color.text_color'))
  6495. .margin({ right: 20, left: 10 })
  6496. .onChange((val: string) => {
  6497. this.commentStr = val
  6498. })
  6499. }
  6500. .width('100%')
  6501. .margin({ top: 10, bottom: 10 })
  6502. .justifyContent(FlexAlign.Start)
  6503. Row() {
  6504. Button('保存')
  6505. .fontColor(Color.White)
  6506. .layoutWeight(1)
  6507. .height(50)
  6508. .width(100)
  6509. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6510. .backgroundColor(this.themeColor)
  6511. .stateEffect(true)
  6512. .margin({ right: 20, bottom: 20 })
  6513. .onClick(async () => {
  6514. this.doEdit(item)
  6515. })
  6516. Button('取消')
  6517. .fontColor(Color.White)
  6518. .layoutWeight(1)
  6519. .height(50)
  6520. .width(100)
  6521. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6522. .backgroundColor(this.themeColor)
  6523. .stateEffect(true)
  6524. .margin({ left: 20, bottom: 20 })
  6525. .onClick(async () => {
  6526. if(this.isGridMusic){
  6527. this.longItemFilePath =''
  6528. }else{
  6529. this.isShowEdit = false
  6530. }
  6531. this.setEditStrEmpty()
  6532. if(this.isShowPlay){
  6533. this.isShowEdit = false
  6534. }
  6535. })
  6536. }
  6537. .margin({
  6538. left: 38,
  6539. right: 38,
  6540. top: 10,
  6541. bottom: 10
  6542. })
  6543. .width(250)
  6544. .height(60)
  6545. }
  6546. }
  6547. .margin({ bottom: 20 })
  6548. }
  6549. setEditStrEmpty(){
  6550. this.imagePathStr = ''
  6551. this.lyricConStr = ''
  6552. this.artistStr = ''
  6553. this.titleStr = ''
  6554. this.ablumStr = ''
  6555. this.genreStr = ''
  6556. this.yearStr = ''
  6557. this.trackStr = ''
  6558. this.albumArtistStr = ''
  6559. this.composerStr = ''
  6560. this.lyricistStr = ''
  6561. this.commentStr = ''
  6562. this.discStr = ''
  6563. }
  6564. @Builder
  6565. detailSheet(item:VideoItem) {
  6566. Scroll() {
  6567. Column() {
  6568. this.songDetail(item)
  6569. }
  6570. }
  6571. .width('100%')
  6572. .height('100%')
  6573. }
  6574. @Builder
  6575. songDetail(currentItem:VideoItem) {
  6576. Column() {
  6577. if (currentItem) {
  6578. Row() {
  6579. Stack() {
  6580. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  6581. currentItem.pixelMapPath)
  6582. .fillColor(this.themeColor)
  6583. .height(80)
  6584. .width(80)
  6585. .borderRadius(10)
  6586. .opacity(this.opacityItem)// 绑定透明度
  6587. .margin({ left: 22 })
  6588. }
  6589. Column() {
  6590. Column() {
  6591. Text(currentItem.name)
  6592. .fontSize(16)
  6593. .maxLines(1)
  6594. .animation({
  6595. duration: 555,
  6596. curve: 'Linear',
  6597. })
  6598. .fontColor($r('app.color.text_color'))
  6599. .margin({ left: 15 })
  6600. }
  6601. .height('100%')
  6602. .width('100%')
  6603. .justifyContent(FlexAlign.Center)
  6604. .alignItems(HorizontalAlign.Start)
  6605. }
  6606. .height('100%')
  6607. }
  6608. .width('100%')
  6609. .height(90)
  6610. .justifyContent(FlexAlign.SpaceBetween)
  6611. Row() {
  6612. Text('艺术家:')
  6613. .fontSize(14)
  6614. .fontColor($r('app.color.text_color'))
  6615. .margin({ left: 22 })
  6616. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  6617. .fontSize(14)
  6618. .fontColor($r('app.color.text_color'))
  6619. .margin({ left: 10 })
  6620. .layoutWeight(1)
  6621. }
  6622. .width('100%')
  6623. .margin({ top: 10, bottom: 10 })
  6624. .justifyContent(FlexAlign.Start)
  6625. Row() {
  6626. Text('专辑名:')
  6627. .fontSize(14)
  6628. .fontColor($r('app.color.text_color'))
  6629. .margin({ left: 22 })
  6630. Text(currentItem?.album ?currentItem.album : '未知专辑')
  6631. .fontSize(14)
  6632. .margin({ left: 10 })
  6633. .fontColor($r('app.color.text_color'))
  6634. .layoutWeight(1)
  6635. }
  6636. .width('100%')
  6637. .margin({ top: 10, bottom: 10 })
  6638. .justifyContent(FlexAlign.Start)
  6639. Row() {
  6640. Text('时长:')
  6641. .fontSize(14)
  6642. .fontColor($r('app.color.text_color'))
  6643. .margin({ left: 22 })
  6644. Text(StrUtil.isEmpty(currentItem.duration)?
  6645. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  6646. .fontSize(14)
  6647. .margin({ left: 10 })
  6648. .fontColor($r('app.color.text_color'))
  6649. .layoutWeight(1)
  6650. }
  6651. .width('100%')
  6652. .margin({ top: 10, bottom: 10 })
  6653. .justifyContent(FlexAlign.Start)
  6654. Row() {
  6655. Text('采样率:')
  6656. .fontSize(14)
  6657. .fontColor($r('app.color.text_color'))
  6658. .margin({ left: 22 })
  6659. Text(Utility.convertToKHz(currentItem.sampleRate))
  6660. .fontSize(14)
  6661. .margin({ left: 10 })
  6662. .fontColor($r('app.color.text_color'))
  6663. .layoutWeight(1)
  6664. }
  6665. .width('100%')
  6666. .margin({ top: 10, bottom: 10 })
  6667. .justifyContent(FlexAlign.Start)
  6668. Row() {
  6669. Text('比特率:')
  6670. .fontSize(14)
  6671. .fontColor($r('app.color.text_color'))
  6672. .margin({ left: 22 })
  6673. Text(currentItem.bit_rate)
  6674. .fontSize(14)
  6675. .margin({ left: 10 })
  6676. .fontColor($r('app.color.text_color'))
  6677. .layoutWeight(1)
  6678. }
  6679. .width('100%')
  6680. .margin({ top: 10, bottom: 10 })
  6681. .justifyContent(FlexAlign.Start)
  6682. Row() {
  6683. Text('位深:')
  6684. .fontSize(14)
  6685. .fontColor($r('app.color.text_color'))
  6686. .margin({ left: 22 })
  6687. Text(`${currentItem.bits_per_raw_sample} bits`)
  6688. .fontSize(14)
  6689. .margin({ left: 10 })
  6690. .fontColor($r('app.color.text_color'))
  6691. .layoutWeight(1)
  6692. }
  6693. .width('100%')
  6694. .margin({ top: 10, bottom: 10 })
  6695. .justifyContent(FlexAlign.Start)
  6696. Row() {
  6697. Text('声道:')
  6698. .fontSize(14)
  6699. .fontColor($r('app.color.text_color'))
  6700. .margin({ left: 22 })
  6701. Text(`${currentItem.channels}`)
  6702. .fontSize(14)
  6703. .margin({ left: 10 })
  6704. .fontColor($r('app.color.text_color'))
  6705. .layoutWeight(1)
  6706. }
  6707. .width('100%')
  6708. .margin({ top: 10, bottom: 10 })
  6709. .justifyContent(FlexAlign.Start)
  6710. Row() {
  6711. Text('声道布局:')
  6712. .fontSize(14)
  6713. .fontColor($r('app.color.text_color'))
  6714. .margin({ left: 22 })
  6715. Text(`${currentItem.channel_layout}`)
  6716. .fontSize(14)
  6717. .margin({ left: 10 })
  6718. .fontColor($r('app.color.text_color'))
  6719. .layoutWeight(1)
  6720. }
  6721. .width('100%')
  6722. .margin({ top: 10, bottom: 10 })
  6723. .justifyContent(FlexAlign.Start)
  6724. Row() {
  6725. Text('起始播放点:')
  6726. .fontSize(14)
  6727. .fontColor($r('app.color.text_color'))
  6728. .margin({ left: 22 })
  6729. Text(`${currentItem.start_time}`)
  6730. .fontSize(14)
  6731. .margin({ left: 10 })
  6732. .fontColor($r('app.color.text_color'))
  6733. .layoutWeight(1)
  6734. }
  6735. .width('100%')
  6736. .margin({ top: 10, bottom: 10 })
  6737. .justifyContent(FlexAlign.Start)
  6738. Row() {
  6739. Text('风格:')
  6740. .fontSize(14)
  6741. .fontColor($r('app.color.text_color'))
  6742. .margin({ left: 22 })
  6743. Text(currentItem.genre)
  6744. .fontSize(14)
  6745. .margin({ left: 10 })
  6746. .fontColor($r('app.color.text_color'))
  6747. .layoutWeight(1)
  6748. }
  6749. .width('100%')
  6750. .margin({ top: 10, bottom: 10 })
  6751. .justifyContent(FlexAlign.Start)
  6752. Row() {
  6753. Text('发行时间:')
  6754. .fontSize(14)
  6755. .fontColor($r('app.color.text_color'))
  6756. .margin({ left: 22 })
  6757. Text(currentItem.year)
  6758. .fontSize(14)
  6759. .margin({ left: 10 })
  6760. .fontColor($r('app.color.text_color'))
  6761. .layoutWeight(1)
  6762. }
  6763. .width('100%')
  6764. .margin({ top: 10, bottom: 10 })
  6765. .justifyContent(FlexAlign.Start)
  6766. Row() {
  6767. Text('质量评分:')
  6768. .fontSize(14)
  6769. .fontColor($r('app.color.text_color'))
  6770. .margin({ left: 22 })
  6771. Text(currentItem.probe_score+"")
  6772. .fontSize(14)
  6773. .margin({ left: 10 })
  6774. .fontColor($r('app.color.text_color'))
  6775. .layoutWeight(1)
  6776. }
  6777. .width('100%')
  6778. .margin({ top: 10, bottom: 10 })
  6779. .justifyContent(FlexAlign.Start)
  6780. Row() {
  6781. Text('音轨号:')
  6782. .fontSize(14)
  6783. .fontColor($r('app.color.text_color'))
  6784. .margin({ left: 22 })
  6785. Text(currentItem.track)
  6786. .fontSize(14)
  6787. .margin({ left: 10 })
  6788. .fontColor($r('app.color.text_color'))
  6789. .layoutWeight(1)
  6790. }
  6791. .width('100%')
  6792. .margin({ top: 10, bottom: 10 })
  6793. .justifyContent(FlexAlign.Start)
  6794. Row() {
  6795. Text('碟号:')
  6796. .fontSize(14)
  6797. .fontColor($r('app.color.text_color'))
  6798. .margin({ left: 22 })
  6799. Text(currentItem.disc)
  6800. .fontSize(14)
  6801. .margin({ left: 10 })
  6802. .fontColor($r('app.color.text_color'))
  6803. .layoutWeight(1)
  6804. }
  6805. .width('100%')
  6806. .margin({ top: 10, bottom: 10 })
  6807. .justifyContent(FlexAlign.Start)
  6808. Row() {
  6809. Text('专辑艺术家:')
  6810. .fontSize(14)
  6811. .fontColor($r('app.color.text_color'))
  6812. .margin({ left: 22 })
  6813. Text(currentItem.ALBUMARTIST)
  6814. .fontSize(14)
  6815. .margin({ left: 10 })
  6816. .fontColor($r('app.color.text_color'))
  6817. .layoutWeight(1)
  6818. }
  6819. .width('100%')
  6820. .margin({ top: 10, bottom: 10 })
  6821. .justifyContent(FlexAlign.Start)
  6822. Row() {
  6823. Text('作曲家:')
  6824. .fontSize(14)
  6825. .fontColor($r('app.color.text_color'))
  6826. .margin({ left: 22 })
  6827. Text(currentItem.COMPOSER)
  6828. .fontSize(14)
  6829. .margin({ left: 10 })
  6830. .fontColor($r('app.color.text_color'))
  6831. .layoutWeight(1)
  6832. }
  6833. .width('100%')
  6834. .margin({ top: 10, bottom: 10 })
  6835. .justifyContent(FlexAlign.Start)
  6836. Row() {
  6837. Text('作词家:')
  6838. .fontSize(14)
  6839. .fontColor($r('app.color.text_color'))
  6840. .margin({ left: 22 })
  6841. Text(currentItem.LYRICIST)
  6842. .fontSize(14)
  6843. .margin({ left: 10 })
  6844. .fontColor($r('app.color.text_color'))
  6845. .layoutWeight(1)
  6846. }
  6847. .width('100%')
  6848. .margin({ top: 10, bottom: 10 })
  6849. .justifyContent(FlexAlign.Start)
  6850. Row() {
  6851. Text('注释:')
  6852. .fontSize(14)
  6853. .fontColor($r('app.color.text_color'))
  6854. .margin({ left: 22 })
  6855. Text(currentItem.COMMENT)
  6856. .fontSize(14)
  6857. .margin({ left: 10 })
  6858. .fontColor($r('app.color.text_color'))
  6859. .layoutWeight(1)
  6860. }
  6861. .width('100%')
  6862. .margin({ top: 10, bottom: 10 })
  6863. .justifyContent(FlexAlign.Start)
  6864. Row() {
  6865. Text('格式:')
  6866. .fontSize(14)
  6867. .fontColor($r('app.color.text_color'))
  6868. .margin({ left: 22 })
  6869. Text(Utility.formatMimeType(currentItem.mimeType))
  6870. .fontSize(14)
  6871. .margin({ left: 10 })
  6872. .fontColor($r('app.color.text_color'))
  6873. .layoutWeight(1)
  6874. }
  6875. .width('100%')
  6876. .margin({ top: 10, bottom: 10 })
  6877. .justifyContent(FlexAlign.Start)
  6878. Row() {
  6879. Text('播放次数:')
  6880. .fontSize(14)
  6881. .fontColor($r('app.color.text_color'))
  6882. .margin({ left: 22 })
  6883. Text(currentItem.playCount?.toString())
  6884. .fontSize(14)
  6885. .margin({ left: 10 })
  6886. .fontColor($r('app.color.text_color'))
  6887. .layoutWeight(1)
  6888. }
  6889. .width('100%')
  6890. .margin({ top: 10, bottom: 10 })
  6891. .justifyContent(FlexAlign.Start)
  6892. Row() {
  6893. Text('流数量:')
  6894. .fontSize(14)
  6895. .fontColor($r('app.color.text_color'))
  6896. .margin({ left: 22 })
  6897. Text(currentItem.nb_streams?.toString())
  6898. .fontSize(14)
  6899. .margin({ left: 10 })
  6900. .fontColor($r('app.color.text_color'))
  6901. .layoutWeight(1)
  6902. }
  6903. .width('100%')
  6904. .margin({ top: 10, bottom: 10 })
  6905. .justifyContent(FlexAlign.Start)
  6906. Row() {
  6907. Text('文件大小:')
  6908. .fontSize(14)
  6909. .fontColor($r('app.color.text_color'))
  6910. .margin({ left: 22 })
  6911. Text(currentItem.size)
  6912. .fontSize(14)
  6913. .margin({ left: 10 })
  6914. .fontColor($r('app.color.text_color'))
  6915. .layoutWeight(1)
  6916. }
  6917. .width('100%')
  6918. .margin({ top: 10, bottom: 10 })
  6919. .justifyContent(FlexAlign.Start)
  6920. Row() {
  6921. Text('文件名:')
  6922. .fontSize(14)
  6923. .fontColor($r('app.color.text_color'))
  6924. .margin({ left: 22 })
  6925. Text(currentItem.fileName)
  6926. .fontSize(14)
  6927. .margin({ left: 10 })
  6928. .fontColor($r('app.color.text_color'))
  6929. .layoutWeight(1)
  6930. }
  6931. .width('100%')
  6932. .margin({ top: 10, bottom: 10 })
  6933. .justifyContent(FlexAlign.Start)
  6934. Row() {
  6935. Text('修改时间:')
  6936. .fontSize(14)
  6937. .fontColor($r('app.color.text_color'))
  6938. .margin({ left: 22 })
  6939. Text(currentItem.cTime)
  6940. .fontSize(14)
  6941. .margin({ left: 10 })
  6942. .fontColor($r('app.color.text_color'))
  6943. .layoutWeight(1)
  6944. }
  6945. .width('100%')
  6946. .margin({ top: 10, bottom: 10 })
  6947. .justifyContent(FlexAlign.Start)
  6948. Row() {
  6949. Text('存放目录:')
  6950. .fontSize(14)
  6951. .fontColor($r('app.color.text_color'))
  6952. .margin({ left: 22 })
  6953. Text(currentItem.filePath)
  6954. .fontSize(12)
  6955. .margin({ left: 10 })
  6956. .fontColor($r('app.color.text_color'))
  6957. .layoutWeight(1)
  6958. }
  6959. .margin({ top: 10, bottom: 10 })
  6960. .width('100%')
  6961. .justifyContent(FlexAlign.Start)
  6962. Row() {
  6963. Text('内嵌歌词:')
  6964. .fontSize(14)
  6965. .fontColor($r('app.color.text_color'))
  6966. .margin({ left: 22 })
  6967. Text(currentItem.lyricContent)
  6968. .fontSize(12)
  6969. .copyOption(CopyOptions.InApp)
  6970. .margin({ left: 10 })
  6971. .fontColor($r('app.color.text_color'))
  6972. .layoutWeight(1)
  6973. }
  6974. .margin({ top: 10, bottom: 10 })
  6975. .width('100%')
  6976. .justifyContent(FlexAlign.Start)
  6977. }
  6978. }
  6979. .margin({ bottom: 20 })
  6980. }
  6981. //定时关闭布局
  6982. @Builder
  6983. TimeCloseSheet() {
  6984. Scroll() {
  6985. Column() {
  6986. this.TimeClose()
  6987. }
  6988. }
  6989. .width('100%')
  6990. .height('100%')
  6991. }
  6992. //倒计时关闭音乐,退出App功能实现。
  6993. @State selectedMinutes: number = 0 // 0表示未开启
  6994. @State remainingSeconds: number = 0
  6995. // 预设时间选项
  6996. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  6997. private formatTime(seconds: number): string {
  6998. const mins = Math.floor(seconds / 60)
  6999. const secs = seconds % 60
  7000. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7001. }
  7002. // 开始倒计时
  7003. private handleTimeSelect(minutes: number) {
  7004. if (minutes === this.selectedMinutes) {
  7005. this.stopCountdown();
  7006. this.selectedMinutes = 0;
  7007. return;
  7008. }
  7009. this.selectedMinutes = minutes;
  7010. this.remainingSeconds = minutes * 60;
  7011. this.startCountdown(); // 新增调用
  7012. }
  7013. @Builder
  7014. TimeClose() {
  7015. Column() {
  7016. // 倒计时显示区域
  7017. Text(this.selectedMinutes > 0 ?
  7018. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7019. "定时关闭未开启")
  7020. .fontSize(17)
  7021. .fontColor($r('app.color.text_color'))
  7022. .margin({ top: 2, bottom: 8 });
  7023. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7024. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7025. // 单行时间选项容器
  7026. Row() {
  7027. // 文字描述区域
  7028. Text(this.getDisplayText(minutes))
  7029. .fontSize(15)
  7030. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7031. $r('app.color.text_color'))// 选中态颜色变化
  7032. .textAlign(TextAlign.Start)
  7033. .layoutWeight(1); // 占据剩余空间
  7034. // 复选框样式的选择器
  7035. Row() {
  7036. if (minutes === this.selectedMinutes) {
  7037. // 选中状态 - 带勾号的圆形复选框
  7038. Row() {
  7039. // 使用系统内置的勾号图标
  7040. Image($r('sys.media.ohos_ic_public_ok'))
  7041. .width(14)
  7042. .height(14)
  7043. .fillColor(Color.White)
  7044. }
  7045. .width(24)
  7046. .height(24)
  7047. .borderRadius(12)
  7048. .backgroundColor(this.themeColor)
  7049. .justifyContent(FlexAlign.Center)
  7050. .alignItems(VerticalAlign.Center)
  7051. } else {
  7052. // 未选中状态的圆形边框
  7053. Row()
  7054. .width(24)
  7055. .height(24)
  7056. .borderRadius(12)
  7057. .border({
  7058. width: 2,
  7059. color: $r('app.color.text_color'),
  7060. style: BorderStyle.Solid
  7061. })
  7062. .backgroundColor(Color.Transparent)
  7063. }
  7064. }
  7065. .width(24)
  7066. .height(24)
  7067. .margin({ left: 20 })
  7068. .justifyContent(FlexAlign.Center)
  7069. .alignItems(VerticalAlign.Center)
  7070. }
  7071. .width('100%')
  7072. .padding({
  7073. top: 18,
  7074. bottom: 18,
  7075. left: 18,
  7076. right: 18
  7077. })
  7078. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7079. $r('app.color.bottom_control_background')) // 选中背景高亮
  7080. .borderRadius(12)
  7081. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7082. .margin({ bottom: 18 })
  7083. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7084. });
  7085. }
  7086. .width('100%')
  7087. .padding(16)
  7088. }
  7089. }
  7090. // 获取显示文本
  7091. private getDisplayText(minutes: number): string {
  7092. if (minutes === -1) {
  7093. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7094. }
  7095. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7096. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7097. }
  7098. // 处理选择事件
  7099. private handleSelect(minutes: number): void {
  7100. if (minutes === -1) { // 自定义
  7101. // 弹出自定义时间对话框
  7102. DialogHelper.showTextInputDialog({
  7103. title: '自定义时间',
  7104. maskColor: Color.Transparent,
  7105. inputType: InputType.Number,
  7106. text: '',
  7107. onChange: (text) => {
  7108. console.error("onChange: " + text);
  7109. },
  7110. onAction: (action, dialogId, content) => {
  7111. if (action == DialogAction.TWO) {
  7112. const customMinutes = Number(content);
  7113. if (customMinutes > 0) {
  7114. this.handleTimeSelect(customMinutes); // 设置自定义时间
  7115. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  7116. }
  7117. }
  7118. }
  7119. });
  7120. } else {
  7121. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  7122. }
  7123. }
  7124. // 添加定时器引用
  7125. private timerId: number = -1;
  7126. // 启动/重置倒计时
  7127. private startCountdown() {
  7128. // 清除旧定时器
  7129. if (this.timerId !== -1) {
  7130. clearInterval(this.timerId);
  7131. }
  7132. // 创建新定时器
  7133. if (this.selectedMinutes > 0) {
  7134. this.timerId = setInterval(() => {
  7135. if (this.remainingSeconds === 15) {
  7136. this.showConfirmationDialog();
  7137. }
  7138. if (this.remainingSeconds > 0) {
  7139. this.remainingSeconds -= 1;
  7140. } else {
  7141. this.stopCountdown();
  7142. this.handleTimeout();
  7143. }
  7144. }, 1000);
  7145. }
  7146. }
  7147. // 15倒计时后再次提示显示确认是否关闭App对话框
  7148. private showConfirmationDialog() {
  7149. DialogHelper.showAlertDialog({
  7150. backgroundColor: $r('app.color.btn_green'),
  7151. title: '确认关闭',
  7152. maskColor: Color.Transparent,
  7153. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  7154. borderStyle: BorderStyle.Dashed,
  7155. primaryButton: '暂不关闭',
  7156. secondaryButton: '确定',
  7157. onAction: (action) => {
  7158. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  7159. this.stopCountdown();
  7160. this.selectedMinutes = 0
  7161. } else if (action == DialogAction.TWO) {
  7162. }
  7163. }
  7164. })
  7165. }
  7166. // 停止倒计时
  7167. private stopCountdown() {
  7168. if (this.timerId !== -1) {
  7169. clearInterval(this.timerId);
  7170. this.timerId = -1;
  7171. }
  7172. }
  7173. // 超时处理
  7174. private handleTimeout() {
  7175. // 执行播放器关闭逻辑
  7176. this.selectedMinutes = 0;
  7177. ToastUtil.showToast(" 定时关闭已完成");
  7178. this.stop(); // 假设存在的播放器实例
  7179. //退出APP
  7180. const mContext = getContext(this) as common.UIAbilityContext
  7181. mContext.terminateSelf();
  7182. AvSessionController.getInstance(true).unregisterSessionListener()
  7183. }
  7184. //倒计时关闭音乐,退出App功能实现结束。
  7185. //播放列表的拖动List 重新排序
  7186. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  7187. //左滑操作 移动文件 重命名 删除等操作
  7188. @Builder
  7189. sonButton(item: VideoItem, index: number, filePath: string) {
  7190. Row() {
  7191. //加入下一首播放
  7192. Button() {
  7193. Image($r('app.media.next_to_play'))
  7194. .fillColor(Color.White)
  7195. .width(20)
  7196. }
  7197. .width(40)
  7198. .height(40)
  7199. .type(ButtonType.Circle)
  7200. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7201. .backgroundColor(this.themeColor)
  7202. .margin(5)
  7203. .onClick(() => {
  7204. this.addToNextPlay(item);
  7205. })
  7206. Button() {
  7207. Image($r('app.media.close'))
  7208. .fillColor(Color.White)
  7209. .width(20)
  7210. }
  7211. .width(40)
  7212. .height(40)
  7213. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7214. .type(ButtonType.Circle)
  7215. .backgroundColor(this.themeColor)
  7216. .margin(5)
  7217. .onClick(() => {
  7218. this.songList.splice(Number(index), 1)
  7219. this.sonDataSource.pushArrayData(this.songList)
  7220. })
  7221. Button() {
  7222. Image($r('app.media.share2'))
  7223. .fillColor(Color.White)
  7224. .width(20)
  7225. }
  7226. .width(40)
  7227. .height(40)
  7228. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7229. .type(ButtonType.Circle)
  7230. .backgroundColor(this.themeColor)
  7231. .margin(5)
  7232. .onClick(() => {
  7233. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  7234. })
  7235. }
  7236. }
  7237. itemMoveSon(index: number, newIndex: number): void {
  7238. if (newIndex < 0 || newIndex >= this.songList.length) {
  7239. return;
  7240. }
  7241. let tmp = this.songList.splice(index, 1);
  7242. this.songList.splice(newIndex, 0, tmp[0]);
  7243. this.sonDataSource.pushArrayData(this.songList)
  7244. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  7245. if(this.modeType==4&&this.playlistTable){
  7246. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  7247. }
  7248. }
  7249. @Builder
  7250. PlayList() {
  7251. List({ scroller: this.playListScroller }) {
  7252. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  7253. ListItem() {
  7254. this.MusicItemSon(item, index)
  7255. }
  7256. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  7257. .animation({
  7258. duration: 666,
  7259. curve: 'ease-in-out' // 可选动画曲线
  7260. })
  7261. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  7262. TransitionEffect.scale({ x: 0, y: 0 })))
  7263. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  7264. //拖动List关键代码开始
  7265. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  7266. .zIndex(this.dragItem === index ? 1 : 0)
  7267. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  7268. .gesture(
  7269. GestureGroup(GestureMode.Sequence,
  7270. LongPressGesture({ repeat: true })
  7271. .onAction((event?: GestureEvent) => {
  7272. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7273. this.scaleItem = index
  7274. })
  7275. })
  7276. .onActionEnd(() => {
  7277. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7278. this.scaleItem = -1
  7279. })
  7280. }),
  7281. PanGesture({ fingers: 1, direction: null, distance: 0 })
  7282. .onActionStart(() => {
  7283. this.dragItem = index // 记录当前拖动项索引
  7284. this.dragRefOffset = 0 // 重置偏移基准
  7285. })
  7286. .onActionUpdate((event: GestureEvent) => {
  7287. this.offsetY = event.offsetY - this.dragRefOffset;
  7288. this.neighborItem = -1;
  7289. let indexA = this.songList.indexOf(item);
  7290. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  7291. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  7292. let value: number = 0;
  7293. if (this.offsetY < 0) {
  7294. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  7295. this.neighborItem = indexA - 1;
  7296. this.neighborScale = 1 - value / 20;
  7297. } else if (this.offsetY > 0) {
  7298. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  7299. this.neighborItem = indexA + 1;
  7300. this.neighborScale = 1 - value / 20;
  7301. }
  7302. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  7303. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7304. this.offsetY -= this.ITEM_INTV;
  7305. this.dragRefOffset += this.ITEM_INTV;
  7306. this.itemMoveSon(indexA, indexA + 1);
  7307. });
  7308. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  7309. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7310. this.offsetY += this.ITEM_INTV;
  7311. this.dragRefOffset -= this.ITEM_INTV;
  7312. this.itemMoveSon(indexA, indexA - 1);
  7313. });
  7314. }
  7315. })
  7316. .onActionEnd((event: GestureEvent) => {
  7317. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7318. this.dragItem = -1
  7319. this.neighborItem = -1
  7320. })
  7321. animateTo({
  7322. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7323. }, () => {
  7324. this.scaleItem = -1
  7325. })
  7326. })
  7327. )
  7328. .onCancel(() => {
  7329. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7330. this.dragItem = -1
  7331. this.neighborItem = -1
  7332. })
  7333. animateTo({
  7334. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  7335. }, () => {
  7336. this.scaleItem = -1
  7337. })
  7338. })
  7339. ) //拖动List关键代码结束
  7340. .onClick(() => {
  7341. this.doPlay(item, index, true)
  7342. })
  7343. }, (item: VideoItem) => item.filePath)
  7344. }
  7345. .width('100%')
  7346. .height('100%')
  7347. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7348. // .animation({ duration: 500, curve: Curve.Ease }))
  7349. .cachedCount(10)
  7350. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7351. .gesture(PinchGesture({ fingers: 2 })
  7352. .onActionEnd((event: GestureEvent) => {
  7353. this.setSonListTwoFingers()
  7354. })
  7355. .onActionUpdate(e => {
  7356. this.scaleValue = this.pinchValue * e.scale
  7357. })
  7358. .onActionStart(e => {
  7359. }))
  7360. .padding({
  7361. bottom: 0
  7362. })
  7363. }
  7364. setSonListTwoFingers() {
  7365. this.pinchValue = this.scaleValue;
  7366. Logger.info('this.pinchValue = ' + this.pinchValue);
  7367. if (this.pinchValue >= 1) {
  7368. this.sonTwoFingerType++
  7369. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  7370. if (this.sonTwoFingerType > 3) {
  7371. this.sonTwoFingerType = 1
  7372. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  7373. }
  7374. } else {
  7375. this.sonTwoFingerType--
  7376. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  7377. if (this.sonTwoFingerType < 1) {
  7378. this.sonTwoFingerType = 1
  7379. }
  7380. }
  7381. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  7382. this.pinchValue = 1;
  7383. this.scaleValue = 1;
  7384. }
  7385. @State sonTwoFingerType:number = 3
  7386. @Builder
  7387. private MusicItemSon(item: VideoItem, index?: number) {
  7388. Button({ type: ButtonType.Normal, stateEffect: true }) {
  7389. Row() {
  7390. Stack() {
  7391. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  7392. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7393. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  7394. .alt($r('app.media.music_red'))
  7395. .fillColor(this.themeColor)
  7396. .borderRadius('100%')
  7397. .clip(true)
  7398. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  7399. .draggable(false)// 禁止长按手势拖动
  7400. .autoResize(true) // 重采样,可减少内存占用
  7401. .margin({ left: 20 })
  7402. }
  7403. .width('15%')
  7404. Column() {
  7405. Column() {
  7406. Text(this.isShowFileName?item.fileName :item.name)
  7407. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  7408. .fontColor(this.curIndex === index ? this.themeColor :
  7409. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  7410. .maxLines(1)
  7411. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  7412. Row() {
  7413. Column(){
  7414. Text(item.md5Str?.includes('Lossless')?
  7415. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  7416. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  7417. .padding({ top: 3,right:6,left:6,bottom:3 })
  7418. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  7419. $r('app.color.text_color'))
  7420. .fontWeight(500)
  7421. .borderRadius(12)
  7422. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  7423. .backgroundColor('#FFC107')
  7424. }
  7425. .padding({ top: 8 })
  7426. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  7427. item.artist + ' ' + item?.duration)
  7428. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7429. .padding({ top: 8 })
  7430. .maxLines(1)
  7431. .fontColor(this.curIndex === index ? this.themeColor :
  7432. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7433. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  7434. Blank()
  7435. Text(item.size)
  7436. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  7437. .padding({ top: 8 })
  7438. .maxLines(1)
  7439. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  7440. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  7441. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  7442. .margin({ left: 10 })
  7443. }
  7444. }
  7445. .height('100%')
  7446. .width('100%')
  7447. .justifyContent(FlexAlign.Center)
  7448. .alignItems(HorizontalAlign.Start)
  7449. }
  7450. .height('100%')
  7451. .width('65%')
  7452. Column() {
  7453. ImageAnimator()
  7454. .images(this.imagesF)// 动画数组
  7455. .duration(1000)// 持续
  7456. .state(this.animationState)// 动画状态
  7457. .fillMode(FillMode.Forwards)
  7458. .width(18)
  7459. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  7460. Visibility.None)
  7461. .height(18)
  7462. .iterations(-1) // 播放次数
  7463. }
  7464. .width('20%')
  7465. }
  7466. }
  7467. .backgroundColor(Color.Transparent)
  7468. .width('100%')
  7469. .reuseId('son_item')
  7470. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  7471. .shadow(this.scaleItem === index ? {
  7472. radius: 70,
  7473. color: '#15000000',
  7474. offsetX: 0,
  7475. offsetY: 0
  7476. } :
  7477. {
  7478. radius: 0,
  7479. color: '#15000000',
  7480. offsetX: 0,
  7481. offsetY: 0
  7482. })
  7483. .animation({ curve: Curve.Sharp, duration: 300 })
  7484. }
  7485. @Builder
  7486. MusicPlayBuilder() {
  7487. Column() {
  7488. this.IjkMusicPlayerView()
  7489. }
  7490. .height('100%')
  7491. .width('100%')
  7492. .onDisAppear(() => {
  7493. this.translateY = 0;
  7494. })
  7495. .translate({ y: this.translateY })
  7496. .gesture(
  7497. PanGesture(this.panOption)
  7498. .onActionUpdate((event?: GestureEvent) => {
  7499. if (event) {
  7500. // 只允许向下滑动,向上滑动时限制为0
  7501. this.translateY = Math.max(0, event.offsetY);
  7502. }
  7503. })
  7504. .onActionEnd((event?: GestureEvent) => {
  7505. // 使用更低的阈值和滑动速度判断
  7506. const minDistance = 100; // 最小滑动距离 100vp
  7507. const minVelocity = 500; // 最小滑动速度
  7508. // 获取滑动速度(如果可用)
  7509. const velocity = event?.velocityY || 0;
  7510. // 判断是否应该关闭:距离足够 或者 速度足够快
  7511. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  7512. if (shouldClose) {
  7513. // 添加关闭动画
  7514. this.getUIContext().animateTo({
  7515. duration: 300,
  7516. curve: Curve.Smooth
  7517. }, () => {
  7518. this.isShowPlay = false;
  7519. this.translateY = 0;
  7520. })
  7521. } else {
  7522. // 回弹动画
  7523. this.getUIContext().animateTo({
  7524. duration: 300,
  7525. curve: Curve.Smooth
  7526. }, () => {
  7527. this.translateY = 0;
  7528. })
  7529. }
  7530. })
  7531. )
  7532. }
  7533. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  7534. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  7535. HeightBreakpoint.HEIGHT_LG;
  7536. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  7537. @State topBarHeight: number = 50
  7538. @State barOpacity: number = 1
  7539. @State barBottomOpacity: number = 1
  7540. private hideDone: boolean = false;
  7541. @State currentYOffset: number = 0;
  7542. @State bottomBarHeight: number = 55;
  7543. private isHiding: boolean = false;
  7544. //是否是Pura X外屏,或者小屏幕
  7545. isPuraWP() {
  7546. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  7547. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  7548. }
  7549. //是否是Pura X外屏,或者小屏幕,手机横屏
  7550. /**
  7551. * 是否是Pura X外屏,或者小屏幕,手机横屏
  7552. * @returns
  7553. */
  7554. isCoverOpacity() {
  7555. if (this.isPuraWP()) {
  7556. return true
  7557. }
  7558. if (this.isPhoneLan()) {
  7559. return true
  7560. }
  7561. if (deviceInfo.marketName.includes('Pura X')
  7562. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  7563. return true
  7564. }
  7565. return false
  7566. }
  7567. //是不是手机横屏
  7568. isPhoneLan() {
  7569. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  7570. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  7571. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  7572. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  7573. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  7574. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  7575. if (this.isHiCarKuanBianPing()) {
  7576. return true
  7577. }
  7578. if (this.isHiCar()) {
  7579. return false
  7580. }
  7581. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7582. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  7583. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  7584. return true
  7585. }
  7586. return false
  7587. }
  7588. //是不是1920x720的hicar的屏幕分辨率
  7589. isHiCarKuanBianPing(){
  7590. if(!this.isHiCar()){
  7591. return false
  7592. }
  7593. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7594. { ratio: 1920 / 720, name: "1920x720" },
  7595. ];
  7596. const currentRatio: number = this.windowWidth / this.windowHeight;
  7597. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7598. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  7599. for (const hiCarRatio of hiCarAspectRatios) {
  7600. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  7601. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7602. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7603. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7604. //宽扁平的尺寸设置列表展示
  7605. this.twoFingerType ==3
  7606. this.isGridMusic = false
  7607. return true;
  7608. }
  7609. }
  7610. return false;
  7611. }
  7612. //是不是hicar的屏幕分辨率
  7613. isHiCarSmall() {
  7614. if(!this.isHiCar()){
  7615. return false
  7616. }
  7617. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  7618. {
  7619. this.columns = 6
  7620. return false
  7621. }
  7622. const hiCarAspectRatios: HiCarAspectRatio[] = [
  7623. { ratio: 800 / 480, name: "800x480" },
  7624. { ratio: 1280 / 720, name: "1280x720" },
  7625. { ratio: 1920 / 1080, name: "1920x1080" },
  7626. ];
  7627. const currentRatio: number = this.windowWidth / this.windowHeight;
  7628. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  7629. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  7630. for (const hiCarRatio of hiCarAspectRatios) {
  7631. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  7632. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  7633. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  7634. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  7635. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  7636. //宽扁平的尺寸设置列表展示
  7637. return true;
  7638. }
  7639. }
  7640. return false;
  7641. }
  7642. isHiCar() {
  7643. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  7644. }
  7645. //是不是正常的手机竖屏
  7646. isPhonePortrait() {
  7647. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  7648. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  7649. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  7650. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7651. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  7652. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  7653. return true
  7654. }
  7655. return false
  7656. }
  7657. @State showSpeedDialog: boolean = false
  7658. @State longPressSpeed: number = 3 //长按默认倍数
  7659. @Builder
  7660. SpeedDialog() {
  7661. Stack() {
  7662. Column() {
  7663. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7664. .fontColor(Color.White)
  7665. .visibility(Visibility.Hidden)
  7666. }
  7667. .backgroundColor(Color.Black)
  7668. .borderRadius(20)
  7669. .padding({
  7670. top: 10,
  7671. right: 20,
  7672. left: 15,
  7673. bottom: 20
  7674. })
  7675. .opacity(0.6)
  7676. Text('已切换至' + this.longPressSpeed + '倍速播放')
  7677. .fontColor(Color.White)
  7678. }
  7679. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  7680. .zIndex(5)
  7681. .margin({ top: 80 })
  7682. }
  7683. @Builder
  7684. IjkMusicPlayerView() {
  7685. Stack() {
  7686. HdsVisualComponent()
  7687. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  7688. console.info('Succeeded in finishing');
  7689. })
  7690. .width('100%')
  7691. .height('100%')
  7692. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  7693. Column() {
  7694. Column() {
  7695. //播放标题
  7696. Column() {
  7697. this.PlayTitle()
  7698. }
  7699. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  7700. .width('100%')
  7701. .margin({ top: 0 })
  7702. .height(PlayConstants.HEIGHT)
  7703. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  7704. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  7705. if (this.showSpeedDialog) {
  7706. this.SpeedDialog()
  7707. }
  7708. Stack() {
  7709. //手势拖动快进
  7710. Column()
  7711. .width(CommonConstants.FULL_PERCENT)
  7712. .height('100%')
  7713. .gesture(
  7714. GestureGroup(GestureMode.Parallel,
  7715. // 长按屏幕倍数播放
  7716. LongPressGesture({ repeat: true })
  7717. .onAction(() => {
  7718. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7719. this.showSpeedDialog = true;
  7720. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  7721. }
  7722. })
  7723. .onActionEnd(() => {
  7724. this.showSpeedDialog = false;
  7725. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7726. }),
  7727. //双击屏幕暂停或者播放
  7728. TapGesture({ count: 2 })
  7729. .onAction((event: GestureEvent) => {
  7730. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7731. ToastUtil.showToast('已暂停')
  7732. }
  7733. console.info('onecold playOrPause 6693')
  7734. this.playOrPause()
  7735. })
  7736. )
  7737. )
  7738. }
  7739. .height('65%')
  7740. Swiper() {
  7741. this.CoverInfo()
  7742. this.PlayerLyrics()
  7743. }
  7744. .onChange((index: number) => {
  7745. this.currentSwiperIndex = index
  7746. })
  7747. .indicator(false)
  7748. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  7749. // new DotIndicator()
  7750. // .top(this.isCoverOpacity()?0:10)
  7751. //
  7752. // .selectedColor($r('app.color.select_swiper'))
  7753. // .color($r('app.color.slider_track')):false
  7754. // )
  7755. .displayCount(new BreakpointType({
  7756. sm: 1,
  7757. md: 2,
  7758. lg: 2,
  7759. xl: 2,
  7760. xxl: 2
  7761. }).getValue(this.currentBreakpoint))
  7762. .clip(false)
  7763. .loop(false)
  7764. .autoPlay(false)
  7765. // .interval(8000)
  7766. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  7767. .height('100%')
  7768. .hitTestBehavior(HitTestMode.Transparent)
  7769. Image($r('app.media.icon_replay'))
  7770. .objectFit(ImageFit.Auto)
  7771. .width('120px')
  7772. .height('120px')
  7773. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  7774. .border({ width: 0 })
  7775. .visibility(Visibility.None)
  7776. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  7777. .onClick(() => {
  7778. console.info('onecold startPlayOrResumePlay 6744')
  7779. this.startPlayOrResumePlay();
  7780. })
  7781. }
  7782. .width(CommonConstants.FULL_PERCENT)
  7783. .height(CommonConstants.FULL_PERCENT)
  7784. .justifyContent(FlexAlign.End)
  7785. }
  7786. .justifyContent(FlexAlign.End)
  7787. .margin({ bottom: 8 })
  7788. }
  7789. .backgroundImage(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7790. // .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  7791. // (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  7792. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  7793. // .backgroundImagePosition(Alignment.Center)
  7794. .animation({
  7795. duration: 666,
  7796. curve: 'ease-in-out' // 可选动画曲线
  7797. })
  7798. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  7799. BlurStyle.BACKGROUND_ULTRA_THICK)
  7800. .hitTestBehavior(HitTestMode.Transparent)
  7801. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  7802. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  7803. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  7804. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  7805. .onClick(() => {
  7806. // this.startAutoHide()
  7807. if(this.isHiCar())
  7808. return
  7809. if(this.is_auto_hide_progress){
  7810. this.is_auto_hide_progress = false
  7811. }
  7812. this.startAutoHide()
  7813. })
  7814. }
  7815. @State progressValue: number = 0;
  7816. @State currentTime: string = "00:00";
  7817. @State totalTime: string = "00:00";
  7818. @State loadingVisible: Visibility = Visibility.None;
  7819. @State replayVisible: Visibility = Visibility.None;
  7820. @State slideEnable: boolean = false;
  7821. @State aspRatio: number = 0.5;
  7822. @State mContext: object | undefined = undefined;
  7823. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  7824. @State mFirst: boolean = true;
  7825. @State mDestroyPage: boolean = false;
  7826. @State playSpeed: number = 1;
  7827. @State oldSeconds: number = 0;
  7828. @State isSeekTo: boolean = false;
  7829. @State isCurrentTime: boolean = false;
  7830. @State videoWidth: string = '100%';
  7831. @State videoHeight: string = '100%';
  7832. @State initAspectRatio: number = 1;
  7833. @State videoAspectRatio: number = this.initAspectRatio;
  7834. @State videoUrl: string = '';
  7835. private last: number = 0;
  7836. @State videoParentAspectRatio: number = this.initAspectRatio;
  7837. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  7838. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  7839. @State PROGRESS_MAX_VALUE: number = 100;
  7840. @State updateProgressTimer: number = 0;
  7841. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  7842. @State name: string = '';
  7843. // @State loop: boolean = false;
  7844. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  7845. @State multiple: string = '1.0X';
  7846. xcomponentController: XComponentController = new XComponentController()
  7847. private panOptionBright: PanGestureOptions =
  7848. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  7849. private panOptionVolume: PanGestureOptions =
  7850. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  7851. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  7852. //手势的音量控制和亮度控制
  7853. private positionX: number = PlayConstants.POSITION_X;
  7854. private positionY: number = PlayConstants.POSITION_Y;
  7855. private windowClass: window.Window = globalThis.windowClass
  7856. @State volume: number = 0.5;
  7857. @State volumeSmall: boolean = false
  7858. @State autoParseMusicName: boolean = true
  7859. @State isShowFileName: boolean = false
  7860. @State isLongNameRoLL: boolean = true//长歌名滚动
  7861. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  7862. @State bright: number = PlayConstants.BRIGHT;
  7863. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  7864. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  7865. @State screenWidth: number = 0
  7866. @State screenHeight: number = 0
  7867. @State statusBarHeight: number = 0
  7868. @State isYesFull: boolean = false
  7869. private seekValue: number = 0
  7870. @State isVideoLock: boolean = false; // Whether the video playback is locked
  7871. eventHub = getContext().eventHub;
  7872. //投播组件
  7873. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  7874. private castController: avSession.AVCastController | undefined = undefined;
  7875. @State isCastPlaying: boolean = false;
  7876. @State currentTime2: number = 0;
  7877. @State currentStringTime: string = '00:00';
  7878. @State duration: number = 0;
  7879. @State isReady: boolean = false;
  7880. @State durationTime: number = 0;
  7881. @State durationStringTime: string = '00:00';
  7882. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  7883. // @State isPlaying: boolean = false;
  7884. private castSeek: boolean = false;
  7885. private castItem: avSession.AVQueueItem | undefined = undefined;
  7886. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  7887. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  7888. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  7889. @State rotateAngle2: number = -9
  7890. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  7891. @State cover: string | undefined = '';
  7892. @State artist: string | undefined = ''
  7893. // 1.初始化controller
  7894. private lyricController: LyricController = new LyricController()
  7895. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  7896. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  7897. private parser = new LyricParser()
  7898. @State randomColor: string = 'rgb(0,0,0)'
  7899. @State randomShakenX: number = 0
  7900. @State randomShakenY: number = 0
  7901. @State lyricTextSize: number = 24
  7902. @State lyricContent: string = ''
  7903. @State isDebug: boolean = false
  7904. @State isHightLightCenter: boolean = true
  7905. /**
  7906. * 初始化歌词加载与展示逻辑
  7907. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  7908. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  7909. * @param isApi2 是否使用API2获取歌词(可选)
  7910. *
  7911. * 主要流程:
  7912. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  7913. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  7914. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  7915. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  7916. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  7917. * 6. 解析失败或读取失败时,清空歌词显示。
  7918. *
  7919. * 注意事项:
  7920. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  7921. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  7922. * - 歌词内容解析后通过lyricController驱动UI渲染。
  7923. */
  7924. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  7925. if (StrUtil.isEmpty(lyricPath)) {
  7926. return
  7927. }
  7928. this.initPipLyricSetting()
  7929. this.lyricControllerSingle
  7930. .setTextSize(15)
  7931. .setCacheSize(4)
  7932. .setTextColor("#FFFFFF")
  7933. .setHighlightColor("#FFFFFF")
  7934. .setHighlightScale(1.2)
  7935. .setEmptyHint("")
  7936. .setAlignMode('center')
  7937. .setAnimationDuration(500)
  7938. .setSingleLine(true)
  7939. this.lyricContent = ''
  7940. this.lyricController
  7941. .setTextSize(this.currentLyricSize)
  7942. .setCacheSize(4)
  7943. .setTextColor("#DDDDDD")
  7944. .setHighlightColor("#FFFFFF")
  7945. .setEmptyHint("")
  7946. .setAnimationDuration(1000)
  7947. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  7948. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  7949. this.setBlurDegree(this.blurDegree, false)
  7950. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  7951. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  7952. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  7953. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  7954. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  7955. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  7956. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  7957. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7958. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  7959. this.lyricController.setTextWeight(this.lyricTextWeight)
  7960. this.showSingleLyric = false
  7961. this.timeOffset = 0
  7962. this.lyricController.setLyric(null)
  7963. this.lyricControllerSingle.setLyric(null)
  7964. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  7965. console.log("onecold lyricPath =" + lyricPath)
  7966. let neiqianLrc = ''
  7967. let lyContent = this.currentSong?.lyricContent
  7968. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  7969. neiqianLrc = lyContent
  7970. }
  7971. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  7972. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  7973. //赋值给this.lyricContent,播控中心才可以显示歌词
  7974. this.lyricContent = neiqianLrc
  7975. // 将文件内容按行分割成字符串数组
  7976. let lines = neiqianLrc.split('\n').map(line => line.trim());
  7977. // 3.解析歌词
  7978. let lyric = this.parser.parse(lines);
  7979. // 4.设置歌词
  7980. this.lyricController.setLyric(lyric);
  7981. this.lyricControllerXF.setLyric(lyric)
  7982. this.lyricControllerSingle.setLyric(lyric)
  7983. return
  7984. }
  7985. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  7986. && !Utility.isVideoByExtension(this.videoUrl))) {
  7987. if (this.currentSong !== undefined) {
  7988. // ToastUtil.showShort('正在为你搜索在线歌词!')
  7989. //判断是不是赞助会员,是会员的话才开启歌词功能
  7990. // if (!this.isDebug) {
  7991. // if (!Utility.isNoble()) {
  7992. // LogUtil.debug("onecold 不是赞助会员")
  7993. // return
  7994. // }
  7995. // if(!Utility.isPassInstallTime(33)){
  7996. // LogUtil.debug("onecold not pass time")
  7997. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  7998. // return
  7999. // }
  8000. // }
  8001. let artist = this.currentSong?.artist
  8002. if (artist === undefined) {
  8003. artist = ''
  8004. }
  8005. if (isApi2 === undefined) {
  8006. isApi2 = false
  8007. }
  8008. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8009. // LogUtil.debug("onecold res =" + res)
  8010. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8011. if (StrUtil.isNotEmpty(res)) {
  8012. this.lyricContent = res
  8013. let lines = res.split('\n').map(line => line.trim());
  8014. // 3.解析歌词
  8015. let lyric = this.parser.parse(lines);
  8016. // 4.设置歌词
  8017. this.lyricController.setLyric(lyric);
  8018. this.lyricControllerXF.setLyric(lyric)
  8019. this.lyricControllerSingle.setLyric(lyric)
  8020. this.showSingleLyric = true
  8021. // 4.保存歌词文件lyric到本地
  8022. //2025年8月28日歌词不再加密下载
  8023. this.saveDataToFile(res, lyricPath, false)
  8024. } else {
  8025. this.lyricController.setLyric(null)
  8026. this.lyricControllerXF.setLyric(null)
  8027. this.lyricControllerSingle.setLyric(null)
  8028. if (isOnLineAndToast) {
  8029. ToastUtil.showShort('未获取到歌词!')
  8030. }
  8031. }
  8032. } else {
  8033. this.lyricController.setLyric(null)
  8034. this.lyricControllerXF.setLyric(null)
  8035. this.lyricControllerSingle.setLyric(null)
  8036. if (isOnLineAndToast) {
  8037. ToastUtil.showShort('未获取到歌词!')
  8038. }
  8039. }
  8040. })
  8041. } else {
  8042. this.lyricController.setLyric(null)
  8043. this.lyricControllerXF.setLyric(null)
  8044. this.lyricControllerSingle.setLyric(null)
  8045. if (isOnLineAndToast) {
  8046. ToastUtil.showShort('未获取到歌词!')
  8047. }
  8048. }
  8049. return
  8050. }
  8051. try {
  8052. let isJiaMi = false;
  8053. let realLyricPath = lyricPath
  8054. if (FileUtil.accessSync(jiaMilyricPath)) {
  8055. isJiaMi = true
  8056. realLyricPath = jiaMilyricPath
  8057. console.info("onecold 找到加密本地歌词 ");
  8058. } else {
  8059. isJiaMi = false
  8060. realLyricPath = lyricPath
  8061. console.info("onecold 找到本地歌词 ");
  8062. }
  8063. // 3.读取文件内容并指定编码为 UTF-8
  8064. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8065. const stat = await fileIo.stat(file.fd);
  8066. const arrayBuffer = new ArrayBuffer(stat.size);
  8067. fs.read(file.fd, arrayBuffer)
  8068. .then((readLen: number) => {
  8069. console.info("read file data succeed");
  8070. // let buf = buffer.from(arrayBuffer, 0, readLen);
  8071. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8072. // 检查 buf 是否为空
  8073. if (buf.length === 0) {
  8074. throw new Error("Buffer is empty after reading the file");
  8075. }
  8076. try {
  8077. // 检测文件编码
  8078. // let detectedEncoding = chardet.detect(buf);
  8079. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  8080. let detectedEncoding = this.detect(arrayBuffer)
  8081. console.info("onecoldT Detected encoding: " + detectedEncoding);
  8082. // 使用检测到的编码解码,解决中文乱码问题
  8083. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8084. console.info("onecoldT Detected textDecoder: " + textDecoder);
  8085. let fileContent = textDecoder.decode(buf);
  8086. console.info(`onecoldT The content of file1: ${fileContent}`);
  8087. //解密
  8088. if (isJiaMi) {
  8089. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  8090. }
  8091. console.info(`onecold The content of file2: ${fileContent}`);
  8092. this.lyricContent = fileContent
  8093. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  8094. this.lyricConStr = fileContent
  8095. }
  8096. // 将文件内容按行分割成字符串数组
  8097. let lines = fileContent.split('\n').map(line => line.trim());
  8098. console.info(`onecold The content of file: ${fileContent}`);
  8099. // 3.解析歌词
  8100. let lyric = this.parser.parse(lines);
  8101. // 4.设置歌词
  8102. this.lyricController.setLyric(lyric);
  8103. this.lyricControllerXF.setLyric(lyric)
  8104. this.lyricControllerSingle.setLyric(lyric)
  8105. this.showSingleLyric = true
  8106. console.info(`The content of file: ${fileContent}`);
  8107. } catch (chardetError) {
  8108. console.error("chardet.detect failed with error: " + chardetError.message);
  8109. this.lyricController.setLyric(null);
  8110. this.lyricControllerXF.setLyric(null)
  8111. this.lyricControllerSingle.setLyric(null)
  8112. }
  8113. })
  8114. .catch((err: BusinessError) => {
  8115. this.lyricController.setLyric(null)
  8116. this.lyricControllerXF.setLyric(null)
  8117. this.lyricControllerSingle.setLyric(null)
  8118. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  8119. })
  8120. .catch((err: Error) => {
  8121. this.lyricController.setLyric(null)
  8122. this.lyricControllerXF.setLyric(null)
  8123. this.lyricControllerSingle.setLyric(null)
  8124. console.error("read file 2 data failed with error message: " + err.message);
  8125. })
  8126. .finally(() => {
  8127. fs.closeSync(file);
  8128. });
  8129. } catch (error) {
  8130. this.lyricController.setLyric(null)
  8131. this.lyricControllerSingle.setLyric(null)
  8132. this.lyricControllerXF.setLyric(null)
  8133. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  8134. }
  8135. }
  8136. detect(data: ArrayBuffer): string {
  8137. //创建检测对象
  8138. let detector: UniversalDetector = new UniversalDetector();
  8139. // 传入检测数据并实时判断编码格式
  8140. detector.handleData(data, 0, data.byteLength);
  8141. // 标记检测数据 读取结束
  8142. detector.dataEnd();
  8143. // 获取检测结果
  8144. let detected: string = detector.getDetectedCharset();
  8145. // 释放资源
  8146. detector.reset();
  8147. return detected;
  8148. }
  8149. //初始化悬浮歌词的自定义设置
  8150. initPipLyricSetting() {
  8151. this.lyricControllerXF
  8152. .setTextSize(this.currentLyricSize)
  8153. .setCacheSize(4)
  8154. .setTextColor("#DDDDDD")
  8155. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  8156. .setEmptyHint("")
  8157. .setAnimationDuration(1000)
  8158. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  8159. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  8160. this.setBlurDegree(this.blurDegreePip, true)
  8161. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  8162. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  8163. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  8164. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  8165. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  8166. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  8167. this.lyricControllerXF.setHightLightCenter(true)
  8168. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  8169. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8170. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8171. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  8172. if (this.pipBgIndex === 0) {
  8173. if (this.cover) {
  8174. this.pipBg = this.cover
  8175. } else {
  8176. this.pipBg = this.imageColor
  8177. }
  8178. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8179. }
  8180. }
  8181. //根据item返回歌词内容
  8182. async getLyricContent(item: VideoItem): Promise<string> {
  8183. let neiqianLrc = ''
  8184. let lyContent = item?.lyricContent
  8185. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  8186. neiqianLrc = lyContent
  8187. return neiqianLrc
  8188. }
  8189. try {
  8190. //取数据库里面的歌词lyContent
  8191. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  8192. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  8193. console.log("onecold Lyrics:", lyricContent);
  8194. neiqianLrc = lyricContent
  8195. return neiqianLrc
  8196. }
  8197. } catch (error) {
  8198. console.error("Error fetching lyrics:", error);
  8199. }
  8200. try {
  8201. let filePath = item.filePath;
  8202. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  8203. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  8204. let isJiaMi = false;
  8205. let realLyricPath = lyricPath;
  8206. if (FileUtil.accessSync(jiaMilyricPath)) {
  8207. isJiaMi = true;
  8208. realLyricPath = jiaMilyricPath;
  8209. console.info("onecold 找到加密本地歌词");
  8210. } else {
  8211. console.info("onecold 找到本地歌词");
  8212. }
  8213. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8214. const stat = await fileIo.stat(file.fd);
  8215. const arrayBuffer = new ArrayBuffer(stat.size);
  8216. const readLen = await fs.read(file.fd, arrayBuffer);
  8217. console.info("read file data succeed");
  8218. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8219. if (buf.length === 0) {
  8220. throw new Error("Buffer is empty after reading the file");
  8221. }
  8222. // let detectedEncoding = chardet.detect(buf);
  8223. let detectedEncoding = this.detect(arrayBuffer)
  8224. console.info("Detected encoding: " + detectedEncoding);
  8225. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8226. let fileContent = textDecoder.decode(buf);
  8227. console.info(`onecold The content of file1: ${fileContent}`);
  8228. if (isJiaMi) {
  8229. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  8230. }
  8231. console.info(`onecold The content of file2: ${fileContent}`);
  8232. fs.closeSync(file);
  8233. return fileContent;
  8234. } catch (error) {
  8235. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  8236. return '';
  8237. }
  8238. }
  8239. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  8240. if (StrUtil.isEmpty(filePath)) {
  8241. return
  8242. }
  8243. try {
  8244. //将content进行加密
  8245. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  8246. let lyricContent = ''
  8247. if (isJiaMi) {
  8248. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  8249. } else {
  8250. lyricContent = content
  8251. }
  8252. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  8253. // 清空文件内容
  8254. await fileIo.truncate(file.fd, 0);
  8255. await fileIo.write(file.fd, lyricContent);
  8256. await fileIo.close(file);
  8257. console.log('onecold lyric file Data saved successfully.');
  8258. } catch (error) {
  8259. console.error('onecold lyric file Failed to save data:', error);
  8260. }
  8261. }
  8262. /**
  8263. * Get largest proportion color of an image.
  8264. */
  8265. getImageColor() {
  8266. if (!this.context) {
  8267. return;
  8268. }
  8269. let bg = Utility.getMusisBg()
  8270. this.imageLabel = bg
  8271. ColorConversion.setSysBarLightBackground(true);
  8272. this.context.resourceManager.getMediaContent(bg)
  8273. .then((value: Uint8Array) => {
  8274. let buffer = value.buffer as ArrayBuffer;
  8275. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  8276. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  8277. if (error) {
  8278. Logger.error('Failed to create color picker.');
  8279. } else {
  8280. let color = colorPicker.getLargestProportionColor();
  8281. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  8282. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  8283. }
  8284. })
  8285. let headFilter = effectKit.createEffect(pixelMap);
  8286. if (headFilter !== null) {
  8287. headFilter.blur(15);
  8288. headFilter.getEffectPixelMap().then((value) => {
  8289. this.imageLabelBg = value;
  8290. })
  8291. }
  8292. })
  8293. .catch((error: BusinessError) => {
  8294. Logger.error(`${error.code} + ${error.message}`)
  8295. })
  8296. })
  8297. .catch((error: BusinessError) => {
  8298. Logger.error(`${error.code} + ${error.message}`)
  8299. })
  8300. }
  8301. setImageColor(cover: string) {
  8302. if (!this.context) {
  8303. return;
  8304. }
  8305. if (cover === undefined) {
  8306. return;
  8307. }
  8308. imagePathToPixelMap(cover).then((value) => {
  8309. let headFilter = effectKit.createEffect(value);
  8310. if (headFilter !== null) {
  8311. headFilter.blur(15);
  8312. headFilter.getEffectPixelMap().then((value) => {
  8313. this.imageLabelBg = value;
  8314. })
  8315. }
  8316. }).catch((error: BusinessError) => {
  8317. Logger.error(`${error.code} + ${error.message}`)
  8318. })
  8319. }
  8320. setImageColor2(cover: string) {
  8321. if (!this.context) {
  8322. return;
  8323. }
  8324. if (cover === undefined) {
  8325. return;
  8326. }
  8327. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  8328. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  8329. this.imageColor = data.imageColor;
  8330. if (data.blurPixelMap) {
  8331. this.imageLabelBg = data.blurPixelMap;
  8332. }
  8333. })
  8334. }
  8335. // 定义开始旋转的方法
  8336. // 定时器用于一百毫秒执行一次旋转角度
  8337. @State timer: number = 0
  8338. @State rotateAngle: number = 0
  8339. //封面旋转动画
  8340. animationRoFun() {
  8341. if (this.isPlaying && !this.isCoverRectangle) {
  8342. this.timer = setInterval(() => {
  8343. this.rotateAngle += 1
  8344. }, 100)
  8345. this.startRotation()
  8346. } else {
  8347. clearInterval(this.timer)
  8348. this.stopRotation()
  8349. }
  8350. }
  8351. // 定义开始旋转的方法
  8352. startRotation() {
  8353. if (this.isPlaying) {
  8354. animateTo({
  8355. duration: 777,
  8356. iterations: 1,
  8357. curve: Curve.Linear
  8358. }, () => {
  8359. this.rotateAngle2 = -9
  8360. })
  8361. }
  8362. }
  8363. // 回调,暂停和播放按钮回调,下一首和上一首
  8364. playChange() {
  8365. // if(this.isCoverRectangle){
  8366. // return
  8367. // }
  8368. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8369. this.setIsPlaying(true)
  8370. this.animationState = AnimationStatus.Running
  8371. } else {
  8372. this.setIsPlaying(false)
  8373. this.animationState = AnimationStatus.Paused
  8374. }
  8375. }
  8376. // 定义停止旋转的方法
  8377. stopRotation() {
  8378. if (this.isCoverRectangle) {
  8379. this.rotateAngle = 0
  8380. } else {
  8381. //唱针以左上角为点选择逆时针40度
  8382. animateTo({
  8383. duration: 1000,
  8384. curve: Curve.Linear,
  8385. iterations: 1,
  8386. }, () => {
  8387. this.rotateAngle2 = -45;
  8388. });
  8389. }
  8390. }
  8391. @Builder
  8392. private LyricsTopItem() {
  8393. Row() {
  8394. Stack() {
  8395. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8396. .height(58)
  8397. .width(58)
  8398. .alt(this.imageLabel)
  8399. .borderRadius(8)
  8400. .clickEffect({ level: ClickEffectLevel.HEAVY })
  8401. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  8402. .shadow({
  8403. radius: 22,
  8404. type: ShadowType.BLUR,
  8405. color: 'on_primary'
  8406. })
  8407. }
  8408. .width('18%')
  8409. Column() {
  8410. Column() {
  8411. Text(this.name)
  8412. .fontSize(16)
  8413. .maxLines(1)
  8414. .fontWeight(FontWeight.Bolder)
  8415. .fontColor(this.currentLyricColor)
  8416. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8417. Row() {
  8418. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  8419. .fontSize(13)
  8420. .fontWeight(FontWeight.Bold)
  8421. .padding({ top: 8 })
  8422. .fontColor(this.currentLyricColor)
  8423. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  8424. Blank()
  8425. }
  8426. }
  8427. .height('100%')
  8428. .width('100%')
  8429. .justifyContent(FlexAlign.Center)
  8430. .alignItems(HorizontalAlign.Start)
  8431. }
  8432. .height('100%')
  8433. .width('65%')
  8434. Column() {
  8435. Image($r('app.media.lyric'))
  8436. .width(28)
  8437. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8438. .margin({ right: 30 })
  8439. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8440. .onClick(() => {
  8441. this.isLyricSetting = !this.isLyricSetting;
  8442. })
  8443. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  8444. height: '95%',
  8445. dragBar: true,
  8446. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8447. showClose: true,
  8448. blurStyle: BlurStyle.Thin,
  8449. backgroundColor: Color.Transparent,
  8450. // title: { title: $r('app.string.lyric_setting') }
  8451. })
  8452. }
  8453. .width('18%')
  8454. }
  8455. .width('82%')
  8456. .height(58)
  8457. .justifyContent(FlexAlign.SpaceBetween)
  8458. }
  8459. //歌词显示
  8460. @Builder
  8461. PlayerLyrics() {
  8462. Column() {
  8463. Column() {
  8464. this.LyricsTopItem()
  8465. }
  8466. .height(this.isPuraWP() ? 15 : 58)
  8467. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  8468. Visibility.None : Visibility.Visible)
  8469. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  8470. .width("100%")
  8471. Column() {
  8472. LyricView2({
  8473. controller: this.lyricController,
  8474. enableSeek: true,
  8475. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8476. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8477. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8478. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  8479. if (!this.isPlaying) {
  8480. console.info('onecold startPlayOrResumePlay 7527')
  8481. this.startPlayOrResumePlay()
  8482. }
  8483. else {
  8484. this.isSeekTo = true;
  8485. this.mDestroyPage = false;
  8486. this.showLoadIng();
  8487. this.seekTo(position + "");
  8488. this.isSeekTo = false;
  8489. }
  8490. return true
  8491. }
  8492. })
  8493. .width("100%")
  8494. .layoutWeight(1)
  8495. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  8496. if (this.isPhoneLan()) {
  8497. Column() {
  8498. this.playProgressView()
  8499. // this.playCenterView()
  8500. }
  8501. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  8502. }
  8503. }
  8504. .position({
  8505. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  8506. (this.isPuraWP() ? 58 : 99)
  8507. })
  8508. .justifyContent(FlexAlign.Center)
  8509. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  8510. }
  8511. }
  8512. @Builder
  8513. SingleLyricView() {
  8514. Column() {
  8515. Column() {
  8516. LyricView2({
  8517. controller: this.lyricControllerSingle,
  8518. enableSeek: false,
  8519. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  8520. seekLineColor: "#80ffffff", // 滑动定位线颜色
  8521. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  8522. })
  8523. }
  8524. .height(66)
  8525. .margin({ bottom: 20 })
  8526. }
  8527. }
  8528. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  8529. @Builder
  8530. BottomControl() {
  8531. Column() {
  8532. this.TopPlayProgressView()
  8533. //播放 暂停,下一首,上一首
  8534. this.playCenterView()
  8535. //播放进度条
  8536. this.BottomView()
  8537. }
  8538. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  8539. }
  8540. //播放控制上一首 下一首 暂停和播放
  8541. @Builder
  8542. playCenterView(){
  8543. Row() {
  8544. Row({ space: 20 }) {
  8545. Button({type:ButtonType.Circle,stateEffect:true}){
  8546. //更多功能
  8547. Image($r('app.media.menu'))
  8548. .width(24)
  8549. .clickEffect({level:ClickEffectLevel.MIDDLE})
  8550. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  8551. height: this.isCoverOpacity() ? '95%' : '93%',
  8552. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  8553. dragBar: true,
  8554. showClose: true,
  8555. blurStyle: BlurStyle.Thin,
  8556. backgroundColor: Color.Transparent,
  8557. })
  8558. }
  8559. .margin({ left: 5 })
  8560. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8561. .backgroundColor(Color.Transparent)
  8562. .onClick(() => {
  8563. this.isShowMoreView = !this.isShowMoreView;
  8564. })
  8565. Button({type:ButtonType.Circle,stateEffect:true}){
  8566. Image($r('app.media.ic_previous'))
  8567. .width(33)
  8568. .clickEffect({level:ClickEffectLevel.HEAVY})
  8569. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8570. }
  8571. .onClick(async () => {
  8572. await this.playPrevious()
  8573. })
  8574. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8575. .backgroundColor(Color.Transparent)
  8576. .margin({ left: 5 })
  8577. }
  8578. Button({type:ButtonType.Circle,stateEffect:true}){
  8579. Column() {
  8580. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  8581. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  8582. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  8583. .width(this.isPhoneLan()?45:55)
  8584. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8585. .fillColor(Color.White)
  8586. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8587. .onClick(async () => {
  8588. console.info('onecold playOrPause 7651')
  8589. this.playOrPause()
  8590. })
  8591. }
  8592. }
  8593. .backgroundColor(Color.Transparent)
  8594. .layoutWeight(1)
  8595. // .margin({ left: 38, right: 38 })
  8596. Row({ space: 20 }) {
  8597. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8598. Image($r('app.media.ic_next'))
  8599. .width(33)
  8600. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8601. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8602. .onClick(async () => {
  8603. await this.playNext();
  8604. })
  8605. }
  8606. .backgroundColor(Color.Transparent)
  8607. .margin({ right: 5 })
  8608. .width(33)
  8609. if(this.isPhoneLan()){
  8610. this.fullButton()
  8611. }else{
  8612. Button({type:ButtonType.Circle,stateEffect:true}){
  8613. //添加或取消收藏
  8614. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  8615. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  8616. .fontSize(23)
  8617. .fontColor([Color.White])
  8618. .alignSelf(ItemAlign.Center)
  8619. // .width(24)
  8620. .clickEffect({level:ClickEffectLevel.MIDDLE})
  8621. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8622. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8623. .onClick(async () => {
  8624. if(this.currentSong){
  8625. this.doFav(this.currentSong)
  8626. }
  8627. })
  8628. }
  8629. .backgroundColor(Color.Transparent)
  8630. .width(24)
  8631. }
  8632. }
  8633. // .margin({ left: 5 })
  8634. }
  8635. .width('95%')
  8636. .margin({ bottom:this.isCoverOpacity()?0:20 })
  8637. .justifyContent(FlexAlign.SpaceEvenly)
  8638. }
  8639. @Builder
  8640. TopPlayProgressView(){
  8641. Row() {
  8642. Column(){
  8643. Row(){
  8644. Stack(){
  8645. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  8646. .fontColor([Color.White])
  8647. .fontSize(21)
  8648. .effectStrategy(1)
  8649. Text(this.fastForwardSeconds)
  8650. .fontColor(Color.White)
  8651. .fontSize(10)
  8652. .fontWeight(FontWeight.Bold)
  8653. }
  8654. .margin({left:12,bottom:6})
  8655. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8656. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8657. .onClick(()=>{
  8658. this.backForward()
  8659. })
  8660. Slider({
  8661. value: this.progressValue,
  8662. min: 0,
  8663. max: this.PROGRESS_MAX_VALUE,
  8664. step: 1,
  8665. style: SliderStyle.InSet
  8666. })
  8667. .height(20)
  8668. .blockColor('rgba(255,255,255,1)')
  8669. .trackColor('rgba(255,255,255,0.3)')
  8670. .selectedColor(Color.White)
  8671. .trackThickness(4)
  8672. .layoutWeight(1)
  8673. .showSteps(false)
  8674. .showTips(true)
  8675. .alignSelf(ItemAlign.Center)
  8676. .enabled(this.slideEnable)
  8677. .onChange((value: number, mode: SliderChangeMode) => {
  8678. // if (mode == 2) {
  8679. this.isSeekTo = true;
  8680. this.mDestroyPage = false;
  8681. this.showLoadIng();
  8682. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8683. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8684. this.seekTo(seekValue + "");
  8685. // this.setProgress()
  8686. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8687. this.isSeekTo = false;
  8688. // }
  8689. })
  8690. Stack(){
  8691. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  8692. .fontColor([Color.White])
  8693. .fontSize(21)
  8694. .effectStrategy(1)
  8695. Text(this.fastForwardSeconds)
  8696. .fontColor(Color.White)
  8697. .fontSize(10)
  8698. .fontWeight(FontWeight.Bold)
  8699. }
  8700. .margin({right:10,bottom:6})
  8701. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  8702. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8703. .onClick(()=>{
  8704. this.fastForward()
  8705. })
  8706. }
  8707. .padding({ right: 7,left:22 })
  8708. Row(){
  8709. Text(this.currentTime)
  8710. .fontSize(10)
  8711. .fontColor(Color.White)
  8712. Blank()
  8713. .layoutWeight(1)
  8714. Text(this.totalTime)
  8715. .fontSize(10)
  8716. .fontColor(Color.White)
  8717. }
  8718. .justifyContent(FlexAlign.Start)
  8719. .padding({ right: 18,left:36 })
  8720. }
  8721. }
  8722. //x5的竖屏模式需要99%
  8723. .width(this.isLandscape?'80%':'93%')
  8724. .justifyContent(FlexAlign.Center)
  8725. .margin({bottom:6})
  8726. .animation({
  8727. duration: 666,
  8728. curve: 'ease-in-out' // 可选动画曲线
  8729. })
  8730. }
  8731. //播放进度条
  8732. @Builder
  8733. BottomView(){
  8734. Row() {
  8735. Button({type:ButtonType.Circle,stateEffect:true}){
  8736. Column() {
  8737. if (this.playType === 0) {
  8738. Image($r('app.media.loop'))
  8739. .width(27)
  8740. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8741. } else if (this.playType === 1) {
  8742. Image($r('app.media.single'))
  8743. .width(27)
  8744. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8745. } else if (this.playType === 2) {
  8746. Image($r('app.media.normal_play'))
  8747. .width(27)
  8748. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8749. } else if (this.playType === 3) {
  8750. Image($r('app.media.random'))
  8751. .width(27)
  8752. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8753. }
  8754. }
  8755. }
  8756. .layoutWeight(1)
  8757. .margin({ left: 5 })
  8758. .backgroundColor(Color.Transparent)
  8759. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8760. .onClick(async () => {
  8761. this.setLoopMode()
  8762. })
  8763. this.fullButton()
  8764. Button({type:ButtonType.Circle,stateEffect:true}){
  8765. Column() {
  8766. Image($r('app.media.lyric'))
  8767. .width(26)
  8768. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8769. }
  8770. }
  8771. .layoutWeight(1)
  8772. .backgroundColor(Color.Transparent)
  8773. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8774. .onClick(async () => {
  8775. this.isLyricSetting = !this.isLyricSetting;
  8776. })
  8777. //播放列表
  8778. Button({type:ButtonType.Circle,stateEffect:true}){
  8779. Image($r('app.media.hm_playlist'))
  8780. .width(24)
  8781. .fillColor(Color.White)
  8782. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8783. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8784. height: '95%',
  8785. dragBar: true,
  8786. showClose: true,
  8787. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8788. blurStyle: BlurStyle.Thin,
  8789. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  8790. title: {
  8791. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8792. + `(${this.songList.length}首)`
  8793. }
  8794. })
  8795. }
  8796. .layoutWeight(1)
  8797. .backgroundColor(Color.Transparent)
  8798. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8799. .onClick(() => {
  8800. this.isShowSheetView = !this.isShowSheetView;
  8801. if(this.isPlayListBgGrass){
  8802. this.isFrontWhite = true
  8803. }else{
  8804. this.isFrontWhite = false
  8805. }
  8806. this.scrollIndex()
  8807. })
  8808. }
  8809. .width(this.isLandscape?'88%':'95%')
  8810. .justifyContent(FlexAlign.SpaceAround)
  8811. .height(30)
  8812. .margin({top:3})
  8813. .animation({
  8814. duration: 666,
  8815. curve: 'ease-in-out' // 可选动画曲线
  8816. })
  8817. }
  8818. @Builder
  8819. fullButton(){
  8820. Button({type:ButtonType.Circle,stateEffect:true}){
  8821. Column() {
  8822. Image($r('app.media.full_4'))
  8823. .width(25)
  8824. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8825. }
  8826. }
  8827. .layoutWeight(1)
  8828. .backgroundColor(Color.Transparent)
  8829. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8830. .onClick(async () => {
  8831. if (this.isLandscape) {
  8832. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8833. } else {
  8834. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8835. }
  8836. })
  8837. }
  8838. //旧版本播放进度条
  8839. @Builder
  8840. playProgressView() {
  8841. Row() {
  8842. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8843. Column() {
  8844. if (this.playType === 0) {
  8845. Image($r('app.media.loop'))
  8846. .width($r('app.float.control_image_width'))
  8847. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8848. } else if (this.playType === 1) {
  8849. Image($r('app.media.single'))
  8850. .width($r('app.float.control_image_width'))
  8851. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8852. } else if (this.playType === 2) {
  8853. Image($r('app.media.normal_play'))
  8854. .width($r('app.float.control_image_width'))
  8855. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8856. } else if (this.playType === 3) {
  8857. Image($r('app.media.random'))
  8858. .width($r('app.float.control_image_width'))
  8859. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8860. }
  8861. }
  8862. }
  8863. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8864. .animation({
  8865. duration: 666,
  8866. curve: 'ease-in-out' // 可选动画曲线
  8867. })
  8868. .backgroundColor(Color.Transparent)
  8869. .margin({ right: 10 })
  8870. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8871. .onClick(async () => {
  8872. this.setLoopMode()
  8873. })
  8874. Text(this.currentTime)
  8875. .fontSize($r('app.float.slider_font_size'))
  8876. .fontColor(Color.White)
  8877. .margin(3)
  8878. Slider({
  8879. value: this.progressValue,
  8880. min: 0,
  8881. max: this.PROGRESS_MAX_VALUE,
  8882. step: 1,
  8883. style: SliderStyle.OutSet
  8884. })
  8885. .width('600px')
  8886. .blockColor('rgba(255,255,255,1)')
  8887. .trackColor('rgba(255,255,255,0.3)')
  8888. .selectedColor(Color.White)
  8889. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  8890. .layoutWeight(1)
  8891. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8892. .showSteps(false)
  8893. .showTips(true)
  8894. .enabled(this.slideEnable)
  8895. .onChange((value: number, mode: SliderChangeMode) => {
  8896. // if (mode == 2) {
  8897. this.isSeekTo = true;
  8898. this.mDestroyPage = false;
  8899. this.showLoadIng();
  8900. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8901. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8902. this.seekTo(seekValue + "");
  8903. // this.setProgress()
  8904. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8905. this.isSeekTo = false;
  8906. // }
  8907. })
  8908. Text(this.totalTime)
  8909. .fontSize($r('app.float.slider_font_size'))
  8910. .fontColor(Color.White)
  8911. .margin(3)
  8912. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8913. //播放列表
  8914. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8915. Image($r('app.media.hm_playlist'))
  8916. .width($r('app.float.control_image_width'))
  8917. .fillColor(Color.White)
  8918. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8919. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8920. height: '95%',
  8921. dragBar: true,
  8922. showClose: true,
  8923. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8924. blurStyle: BlurStyle.Thin,
  8925. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  8926. title: {
  8927. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8928. + `(${this.songList.length}首)`
  8929. }
  8930. })
  8931. }
  8932. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8933. .animation({
  8934. duration: 666,
  8935. curve: 'ease-in-out' // 可选动画曲线
  8936. })
  8937. .backgroundColor(Color.Transparent)
  8938. .margin({ right: 20, left: 10 })
  8939. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8940. .onClick(() => {
  8941. this.isShowSheetView = !this.isShowSheetView;
  8942. if (this.isPlayListBgGrass) {
  8943. this.isFrontWhite = true
  8944. } else {
  8945. this.isFrontWhite = false
  8946. }
  8947. this.scrollIndex()
  8948. })
  8949. }
  8950. //x5的竖屏模式需要99%
  8951. .width(this.isPhonePortrait() ? '93.4%'
  8952. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  8953. .height(this.isPhoneLan() ? 25 : 33)
  8954. .animation({
  8955. duration: 666,
  8956. curve: 'ease-in-out' // 可选动画曲线
  8957. })
  8958. }
  8959. isBigScreen() {
  8960. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  8961. return true
  8962. }
  8963. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8964. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8965. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  8966. return false
  8967. } else {
  8968. return true
  8969. }
  8970. return false
  8971. }
  8972. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  8973. @State isCoverRectangle: boolean = false
  8974. @State isCoverTop: boolean = true
  8975. // 添加控制缩放的状态变量
  8976. @State scaleValueImage: number = 1
  8977. @Builder
  8978. CoverInfo() {
  8979. Column() {
  8980. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  8981. if (this.isCoverRectangle) {
  8982. if (!this.isCoverTop) {
  8983. this.musicNameInfo(false)
  8984. }
  8985. } else {
  8986. this.musicNameInfo(false)
  8987. }
  8988. Stack() {
  8989. // 唱片旋转效果
  8990. Image($r('app.media.ic_music_disc'))
  8991. .width(245)
  8992. .height(245)
  8993. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  8994. .aspectRatio(1)
  8995. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8996. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8997. .borderRadius('100%')
  8998. .align(Alignment.Center)
  8999. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9000. .rotate({
  9001. angle: this.rotateAngle,
  9002. centerX: "50%",
  9003. centerY: "50%",
  9004. })
  9005. .animation({
  9006. duration: 100,
  9007. curve: Curve.Linear
  9008. })
  9009. .shadow({
  9010. radius: 22,
  9011. type: ShadowType.BLUR,
  9012. color: 'on_primary'
  9013. })
  9014. Column() {
  9015. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  9016. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  9017. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  9018. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9019. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9020. .alt(this.imageLabel)
  9021. .margin({ right: 8, left: 8, top: 8 })
  9022. .aspectRatio(1)
  9023. .opacity(this.opacityValueImage)
  9024. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  9025. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9026. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9027. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9028. .align(Alignment.Center)//
  9029. .clip(true)
  9030. .rotate({
  9031. x: 0,
  9032. y: 0,
  9033. z: 1,
  9034. angle: this.rotateAngle
  9035. })
  9036. .shadow({
  9037. radius: 22,
  9038. type: ShadowType.BLUR,
  9039. color: 'on_primary'
  9040. })
  9041. .onClick(() => {
  9042. this.getImageColor()
  9043. })
  9044. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  9045. // .shaderEffect({
  9046. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  9047. // animation: {
  9048. // duration: 4000,
  9049. // iterations: -1,
  9050. // autoPlay: true,
  9051. // onFinish: () => {
  9052. // console.info('Succeeded in finishing');
  9053. // }
  9054. // },
  9055. // controller: this.controller,
  9056. // params: {
  9057. // firstEdgeFlowLight: {
  9058. // startPos: 0,
  9059. // endPos: 1.0,
  9060. // color: '#1AD0F1',
  9061. // },
  9062. // secondEdgeFlowLight: {
  9063. // startPos: 0.5,
  9064. // endPos: 1.5,
  9065. // color: '#FFA4E5',
  9066. // }
  9067. // }
  9068. // })
  9069. // .buildEffect())
  9070. this.musicNameInfo(false)
  9071. } else {
  9072. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  9073. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9074. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  9075. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9076. .alt(this.imageLabel)
  9077. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  9078. .aspectRatio(1)
  9079. .opacity(this.opacityValueImage)
  9080. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  9081. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9082. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9083. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9084. .align(Alignment.Center)//
  9085. .clip(true)
  9086. .shadow({
  9087. radius: 22,
  9088. type: ShadowType.BLUR,
  9089. color: 'on_primary'
  9090. })
  9091. .rotate({
  9092. x: 0,
  9093. y: 0,
  9094. z: 1,
  9095. angle: this.rotateAngle
  9096. })
  9097. .onClick(() => {
  9098. this.getImageColor()
  9099. })
  9100. if (this.isPhoneLan()) {
  9101. Text(this.name)
  9102. .fontSize(18)
  9103. .fontWeight(FontWeight.Bold)
  9104. .margin({ top: 13 })
  9105. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9106. .maxLines(1)
  9107. .width('99%')
  9108. .textAlign(TextAlign.Center)
  9109. .fontColor(Color.White)
  9110. }
  9111. }
  9112. }
  9113. // 唱针以左上角为点选择逆时针40度
  9114. Image($r('app.media.ic_music_cover_hand'))
  9115. .height(130)
  9116. .margin({ bottom: 220, top: 0 })
  9117. .align(Alignment.Top)
  9118. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  9119. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9120. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9121. Column({ space: 8 }) {
  9122. Text(this.name)
  9123. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9124. .fontWeight(FontWeight.Bold)
  9125. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9126. .maxLines(1)
  9127. .width('48%')
  9128. .textAlign(TextAlign.Center)
  9129. .fontColor(Color.White)
  9130. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9131. Text(this.artist)
  9132. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9133. .fontColor(Color.White)
  9134. .fontWeight(FontWeight.Bold)
  9135. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9136. }
  9137. .justifyContent(FlexAlign.Start)
  9138. .zIndex(1)
  9139. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9140. }
  9141. .margin({
  9142. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9143. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9144. top: this.isCoverOpacity() ? 0 : 20
  9145. })
  9146. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9147. this.SingleLyricView()
  9148. }
  9149. if (this.isPhoneLan()) {
  9150. Column() {
  9151. this.playCenterView()
  9152. // this.playProgressView()
  9153. }
  9154. .position({ left: 28, bottom: 38 })
  9155. } else {
  9156. this.BottomControl()
  9157. }
  9158. }
  9159. .width(CommonConstants.FULL_PERCENT)
  9160. .clip(true)
  9161. }
  9162. @Builder
  9163. private musicNameInfo(isHidden: boolean) {
  9164. Column({ space: 8 }) {
  9165. Text(this.isShowFileName&&this.currentSong?this.currentSong.fileName :this.name)
  9166. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  9167. .fontWeight(FontWeight.Bold)
  9168. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9169. .maxLines(1)
  9170. .width('99%')
  9171. .textAlign(TextAlign.Center)
  9172. .fontColor(Color.White)
  9173. Text(this.artist + ' ' + this.currentSong?.album||'')
  9174. .fontSize(this.isCoverOpacity() ? 12 : 15)
  9175. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9176. .fontColor(Color.White)
  9177. .textAlign(TextAlign.Center)
  9178. .visibility(StrUtil.isEmpty(this.artist)||this.isShowFileName?Visibility.None:Visibility.Visible)
  9179. .width('99%')
  9180. .maxLines(1)
  9181. }
  9182. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  9183. .zIndex(1)
  9184. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  9185. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  9186. }
  9187. @Builder
  9188. private PlayTitle() {
  9189. Row() {
  9190. Row() {
  9191. Image($r('app.media.ic_back_down'))
  9192. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  9193. .hitTestBehavior(HitTestMode.Transparent)
  9194. Text(this.name + ' ' + this.artist)
  9195. .fontColor(Color.White)
  9196. .fontSize($r('app.float.title_font_size'))
  9197. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9198. .maxLines(1)
  9199. .visibility(Visibility.None)
  9200. .margin({ left: 2, right: 30 })
  9201. }
  9202. .layoutWeight(1)
  9203. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9204. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  9205. .onClick(() => {
  9206. this.isShowPlay = false;
  9207. })
  9208. Column() {
  9209. AVCastPicker({
  9210. normalColor: Color.White,
  9211. onStateChange: this.onStateVastChange
  9212. })
  9213. .width(24)
  9214. .height(24)
  9215. }
  9216. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  9217. }
  9218. .width(PlayConstants.ROW_WIDTH)
  9219. }
  9220. @Builder
  9221. lyricSettingSheet(isPip: boolean) {
  9222. Scroll() {
  9223. this.lyricSetting(isPip)
  9224. }
  9225. .width('100%')
  9226. .height('100%')
  9227. }
  9228. @Builder
  9229. lyricSetting(isPip: boolean) {
  9230. Column() {
  9231. // 时间调节模块
  9232. if (!isPip) {
  9233. this.BuildTimeControls()
  9234. }
  9235. // 字号控制模块
  9236. this.BuildFontControls(isPip)
  9237. }
  9238. }
  9239. // 歌词时间偏移状态
  9240. @State timeOffset: number = 0.0
  9241. @State currentLyricColor: string = '#FFFFFF'
  9242. @State currentLyricColorPip: string = '#FFFFFF'
  9243. @State currentHighLightLyricColor: string = '#FF4081'
  9244. @State currentHighLightLyricColorPip: string = '#FF4081'
  9245. // 歌词字号状态
  9246. @State currentLyricSize: number = 20
  9247. @State currentLyricSizePip: number = 20
  9248. // 高亮歌词放大倍数
  9249. @State currentHightLyricSize: number = 1.2
  9250. @State currentHightLyricSizePip: number = 1.2
  9251. @State currentLyricLineSpace: number = 10
  9252. @State currentLyricLineSpacePip: number = 10
  9253. @State currentLyricAlignMode: number = 1
  9254. @State currentLyricAlignModePip: number = 1
  9255. @State blurDegree: number = 2
  9256. @State blurDegreePip: number = 2
  9257. @State isShowSelectColor: boolean = false
  9258. @State isShowHLSelectColor: boolean = false
  9259. @State isShowPipBgSelectColor: boolean = false
  9260. @State pipLyWidth: number = 330
  9261. @State pipLyHeight: number = 120
  9262. // 构建颜色选择器
  9263. @Builder
  9264. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  9265. Row({ space: 10 }) {
  9266. HSBColorPicker({
  9267. color: '#FFFFFF',
  9268. radius: 8,
  9269. layout: HSBColorPickerLayout.COLUMN,
  9270. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  9271. '#fa7105'],
  9272. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  9273. this.changeLyricColor(value, isPip, isBGPip)
  9274. })
  9275. .height(250)
  9276. .layoutWeight(1)
  9277. .padding(25)
  9278. }
  9279. .width('66%')
  9280. }
  9281. @State isOpenPip: boolean = false
  9282. @State pipBgIndex: number = 0
  9283. // 构建字号控制器
  9284. @Builder
  9285. BuildFontControls(isPip: boolean) {
  9286. Column() {
  9287. if (isPip) {
  9288. Column() {
  9289. Row() {
  9290. Text('悬浮歌词')
  9291. .margin({ left: 18 })
  9292. .fontSize(15)
  9293. .fontColor(Color.White)
  9294. .fontWeight(480)
  9295. .layoutWeight(1)
  9296. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  9297. .selectedColor(this.themeColor)
  9298. .switchPointColor(Color.White)
  9299. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9300. .margin({ right: 18 })
  9301. .onChange((checked: boolean) => {
  9302. this.isOpenPip = checked;
  9303. if (this.isOpenPip) {
  9304. this.startPip()
  9305. } else {
  9306. this.stopPip()
  9307. }
  9308. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  9309. })
  9310. .width(50)
  9311. .height(30);
  9312. }
  9313. .height(55)
  9314. }
  9315. .backgroundColor(Color.Transparent)
  9316. .borderRadius(15)
  9317. .margin({
  9318. left: 30,
  9319. right: 30,
  9320. top: 0,
  9321. bottom: 20
  9322. })
  9323. .padding(0)
  9324. .border({
  9325. color: Color.White,
  9326. width: 1.8
  9327. })
  9328. }else{
  9329. Column() {
  9330. Row() {
  9331. Text('单行歌词')
  9332. .margin({ left: 18 })
  9333. .fontSize(15)
  9334. .fontColor(Color.White)
  9335. .fontWeight(480)
  9336. .layoutWeight(1)
  9337. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  9338. .selectedColor(this.themeColor)
  9339. .switchPointColor(Color.White)
  9340. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9341. .margin({ right: 18 })
  9342. .onChange((checked: boolean) => {
  9343. this.isShowSingleLineLyric = checked;
  9344. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  9345. })
  9346. .width(50)
  9347. .height(30);
  9348. }
  9349. .height(55)
  9350. }
  9351. .backgroundColor(Color.Transparent)
  9352. .borderRadius(15)
  9353. .margin({
  9354. left: 30,
  9355. right: 30,
  9356. top: 10,
  9357. bottom: 10
  9358. })
  9359. .padding(0)
  9360. .border({
  9361. color: Color.White,
  9362. width: 1.8
  9363. })
  9364. }
  9365. Row() {
  9366. Text(`歌词居中:`)
  9367. .fontSize(14)
  9368. .fontColor(Color.White)
  9369. .margin({ left: 2 })
  9370. Row() {
  9371. ForEach(['居中', '居左'], (size: string, index: number) => {
  9372. Button(size)
  9373. .width(60)
  9374. .height(28)
  9375. .fontSize(12)
  9376. .fontColor('#FFFFFF')
  9377. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  9378. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  9379. .border({
  9380. color: (!isPip && this.currentLyricAlignMode === index) ||
  9381. (isPip && this.currentLyricAlignModePip === index) ?
  9382. '#007DFF' : '#DDDDDD',
  9383. width: 1.8
  9384. })
  9385. .onClick(() => {
  9386. this.setLyricAlignMode(index, isPip)
  9387. })
  9388. .margin({ left: 10, right: 8 })
  9389. })
  9390. }
  9391. .width('76%')
  9392. Blank()
  9393. }
  9394. .margin({
  9395. top: 10,
  9396. bottom: 10,
  9397. right: 20,
  9398. left: 20
  9399. })
  9400. if (isPip) {
  9401. Row() {
  9402. Text(`悬浮背景:`)
  9403. .fontSize(14)
  9404. .fontColor(Color.White)
  9405. Select([
  9406. { value: CommonConstants.PIP_LYRIC_BG[0] },
  9407. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  9408. .font({ size: 13, weight: FontWeight.Medium })
  9409. .fontColor(Color.White)
  9410. .margin({ left: 10 })
  9411. .selected(this.pipBgIndex)
  9412. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  9413. .onSelect(async (_index: number, text?: string | undefined) => {
  9414. this.pipBgIndex = _index
  9415. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  9416. if (this.pipBgIndex === 0) {
  9417. if (this.cover) {
  9418. this.pipBg = this.cover
  9419. } else {
  9420. this.pipBg = this.imageColor
  9421. }
  9422. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9423. } else {
  9424. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9425. }
  9426. })
  9427. Column() {
  9428. }
  9429. .backgroundColor(this.pipBg)
  9430. .margin({ left: 10, right: 10 })
  9431. .borderRadius(20)
  9432. .height(28)
  9433. .width(28)
  9434. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9435. Row() {
  9436. SymbolGlyph($r('sys.symbol.paintbrush'))
  9437. .fontColor([Color.White])
  9438. .effectStrategy(1)
  9439. Text(`选择颜色`)
  9440. .fontSize(13)
  9441. .margin({ left: 10 })
  9442. .fontColor(Color.White)
  9443. }
  9444. }
  9445. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  9446. .backgroundColor(Color.Transparent)
  9447. .border({
  9448. color: '#FFFFFF',
  9449. radius: 20,
  9450. width: 1.8
  9451. })
  9452. .height(36)
  9453. .width(110)
  9454. .onClick(() => {
  9455. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  9456. })
  9457. .bindPopup(this.isShowPipBgSelectColor, {
  9458. builder: this.SelectColor(false, isPip, true),
  9459. placement: Placement.Top,
  9460. mask: { color: '#33000000' },
  9461. enableArrow: false, //是否显示箭头
  9462. showInSubWindow: false,
  9463. onStateChange: (e) => {
  9464. if (!e.isVisible) {
  9465. this.isShowPipBgSelectColor = false
  9466. }
  9467. }
  9468. })
  9469. }
  9470. .width('76%')
  9471. .margin({ bottom: 5, right: 45, left: 20 })
  9472. }
  9473. if (!isPip) {
  9474. Row() {
  9475. Text(`高亮居中:`)
  9476. .fontSize(14)
  9477. .fontColor(Color.White)
  9478. Column() {
  9479. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  9480. .selectedColor(this.themeColor)
  9481. .switchPointColor(Color.White)
  9482. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9483. .onChange((checked: boolean) => {
  9484. this.isHightLightCenter = checked;
  9485. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  9486. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  9487. })
  9488. .width(50)
  9489. .height(30)
  9490. .alignSelf(ItemAlign.Start)
  9491. .margin({ left: 12 })
  9492. Blank()
  9493. }
  9494. .width('76%')
  9495. }
  9496. .margin({
  9497. left: 20,
  9498. right: 15,
  9499. top: 10,
  9500. bottom: 10
  9501. })
  9502. }
  9503. Row() {
  9504. Text(`歌词颜色:`)
  9505. .fontSize(14)
  9506. .fontColor(Color.White)
  9507. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9508. .fontSize(15)
  9509. .fontColor(Color.White)
  9510. .margin({ left: 12, right: 12 })
  9511. Column() {
  9512. }
  9513. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  9514. .margin({ right: 12 })
  9515. .borderRadius(20)
  9516. .height(28)
  9517. .width(28)
  9518. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9519. Row() {
  9520. SymbolGlyph($r('sys.symbol.paintbrush'))
  9521. .fontColor([Color.White])
  9522. .effectStrategy(1)
  9523. Text(`选择颜色`)
  9524. .fontSize(13)
  9525. .margin({ left: 10 })
  9526. .fontColor(Color.White)
  9527. }
  9528. }
  9529. .backgroundColor(Color.Transparent)
  9530. .border({
  9531. color: '#FFFFFF',
  9532. radius: 20,
  9533. width: 1.8
  9534. })
  9535. .height(36)
  9536. .width(110)
  9537. .onClick(() => {
  9538. this.isShowSelectColor = !this.isShowSelectColor
  9539. })
  9540. .bindPopup(this.isShowSelectColor, {
  9541. builder: this.SelectColor(false, isPip),
  9542. placement: Placement.Top,
  9543. mask: { color: '#33000000' },
  9544. enableArrow: false, //是否显示箭头
  9545. showInSubWindow: false,
  9546. onStateChange: (e) => {
  9547. if (!e.isVisible) {
  9548. this.isShowSelectColor = false
  9549. }
  9550. }
  9551. })
  9552. }
  9553. .width('76%')
  9554. .margin({
  9555. top: 10,
  9556. bottom: 10,
  9557. right: 45,
  9558. left: 20
  9559. })
  9560. Row() {
  9561. Text(`高亮颜色:`)
  9562. .fontSize(14)
  9563. .fontColor(Color.White)
  9564. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  9565. .fontSize(15)
  9566. .fontColor(Color.White)
  9567. .margin({ left: 12, right: 12 })
  9568. Column() {
  9569. }
  9570. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  9571. .margin({ right: 12 })
  9572. .borderRadius(20)
  9573. .height(28)
  9574. .width(28)
  9575. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9576. Row() {
  9577. SymbolGlyph($r('sys.symbol.paintbrush'))
  9578. .fontColor([Color.White])
  9579. .effectStrategy(1)
  9580. Text(`选择颜色`)
  9581. .fontSize(13)
  9582. .margin({ left: 10 })
  9583. .fontColor(Color.White)
  9584. }
  9585. }
  9586. .backgroundColor(Color.Transparent)
  9587. .border({
  9588. color: '#FFFFFF',
  9589. radius: 20,
  9590. width: 1.8
  9591. })
  9592. .height(36)
  9593. .width(110)
  9594. .onClick(() => {
  9595. this.isShowHLSelectColor = !this.isShowHLSelectColor
  9596. })
  9597. .bindPopup(this.isShowHLSelectColor, {
  9598. builder: this.SelectColor(true, isPip),
  9599. placement: Placement.Top,
  9600. mask: { color: '#33000000' },
  9601. enableArrow: false, //是否显示箭头
  9602. showInSubWindow: false,
  9603. onStateChange: (e) => {
  9604. if (!e.isVisible) {
  9605. this.isShowHLSelectColor = false
  9606. }
  9607. }
  9608. })
  9609. }
  9610. .width('76%')
  9611. .margin({
  9612. top: 10,
  9613. bottom: 10,
  9614. right: 45,
  9615. left: 20
  9616. })
  9617. if (isPip) {
  9618. Row() {
  9619. Text(`显示宽度:`)
  9620. .fontSize(14)
  9621. .fontColor(Color.White)
  9622. Slider({
  9623. value: this.pipLyWidth,
  9624. min: 10,
  9625. max: 800,
  9626. step: 1,
  9627. style: SliderStyle.OutSet
  9628. })
  9629. .blockColor(this.themeColor)
  9630. .trackColor($r('app.color.speed_text_color'))
  9631. .selectedColor(Color.White)
  9632. .trackThickness(6)
  9633. .onChange((value: number) => {
  9634. this.pipLyWidth = value
  9635. if (this.pipController) {
  9636. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9637. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  9638. }
  9639. })
  9640. .width('76%')
  9641. }
  9642. .margin({
  9643. left: 20,
  9644. right: 15,
  9645. top: 5,
  9646. bottom: 5
  9647. })
  9648. Row() {
  9649. Text(`显示高度:`)
  9650. .fontSize(14)
  9651. .fontColor(Color.White)
  9652. Slider({
  9653. value: this.pipLyHeight,
  9654. min: 10,
  9655. max: 1000,
  9656. step: 1,
  9657. style: SliderStyle.OutSet
  9658. })
  9659. .blockColor(this.themeColor)
  9660. .trackColor($r('app.color.speed_text_color'))
  9661. .selectedColor(Color.White)
  9662. .trackThickness(6)
  9663. .onChange((value: number) => {
  9664. this.pipLyHeight = value
  9665. if (this.pipController) {
  9666. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9667. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  9668. }
  9669. })
  9670. .width('76%')
  9671. }
  9672. .margin({
  9673. left: 20,
  9674. right: 15,
  9675. top: 5,
  9676. bottom: 5
  9677. })
  9678. }
  9679. Row() {
  9680. Text(`歌词字号:`)
  9681. .fontSize(14)
  9682. .fontColor(Color.White)
  9683. Slider({
  9684. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  9685. min: 12,
  9686. max: 30,
  9687. step: 0.1,
  9688. style: SliderStyle.OutSet
  9689. })
  9690. .blockColor(this.themeColor)
  9691. .trackColor($r('app.color.speed_text_color'))
  9692. .selectedColor(Color.White)
  9693. .trackThickness(6)
  9694. .onChange((value: number) => {
  9695. this.setLyricTextSize(value, isPip)
  9696. })
  9697. .width('76%')
  9698. }
  9699. .margin({
  9700. left: 20,
  9701. right: 15,
  9702. top: 5,
  9703. bottom: 5
  9704. })
  9705. Row() {
  9706. Text(`高亮倍数:`)
  9707. .fontSize(14)
  9708. .fontColor(Color.White)
  9709. Slider({
  9710. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  9711. min: 1,
  9712. max: 2,
  9713. step: 0.1,
  9714. style: SliderStyle.OutSet
  9715. })
  9716. .blockColor(this.themeColor)
  9717. .trackColor($r('app.color.speed_text_color'))
  9718. .selectedColor(Color.White)
  9719. .trackThickness(6)
  9720. .onChange((value: number) => {
  9721. this.setHighLyricTextSize(value, isPip)
  9722. })
  9723. .width('76%')
  9724. }
  9725. .margin({
  9726. left: 20,
  9727. right: 15,
  9728. top: 5,
  9729. bottom: 5
  9730. })
  9731. Row() {
  9732. Text(`歌词间隙:`)
  9733. .fontSize(14)
  9734. .fontColor(Color.White)
  9735. Slider({
  9736. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  9737. min: 0,
  9738. max: 100,
  9739. step: 1,
  9740. style: SliderStyle.OutSet
  9741. })
  9742. .blockColor(this.themeColor)
  9743. .trackColor($r('app.color.speed_text_color'))
  9744. .selectedColor(Color.White)
  9745. .trackThickness(6)
  9746. .onChange((value: number) => {
  9747. this.setLyricLineSpace(value, isPip)
  9748. })
  9749. .width('76%')
  9750. }
  9751. .margin({
  9752. left: 20,
  9753. right: 15,
  9754. top: 5,
  9755. bottom: 5
  9756. })
  9757. //取值间隔为100,默认为400,取值越大,字体越粗
  9758. Row() {
  9759. Text(`歌词字重:`)
  9760. .fontSize(14)
  9761. .fontColor(Color.White)
  9762. Slider({
  9763. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  9764. min: 100,
  9765. max: 900,
  9766. step: 100,
  9767. style: SliderStyle.OutSet
  9768. })
  9769. .blockColor(this.themeColor)
  9770. .trackColor($r('app.color.speed_text_color'))
  9771. .selectedColor(Color.White)
  9772. .trackThickness(6)
  9773. .onChange((value: number) => {
  9774. if (isPip) {
  9775. this.lyricTextWeightPip = value
  9776. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9777. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  9778. } else {
  9779. this.lyricTextWeight = value
  9780. this.lyricController.setTextWeight(this.lyricTextWeight)
  9781. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  9782. }
  9783. })
  9784. .width('76%')
  9785. }
  9786. .margin({
  9787. left: 20,
  9788. right: 15,
  9789. top: 5,
  9790. bottom: 5
  9791. })
  9792. if (!isPip) {
  9793. Row() {
  9794. Text(`歌词模糊:`)
  9795. .fontSize(14)
  9796. .fontColor(Color.White)
  9797. Slider({
  9798. value: isPip ? this.blurDegreePip : this.blurDegree,
  9799. min: 0,
  9800. max: 5,
  9801. step: 0.1,
  9802. style: SliderStyle.OutSet
  9803. })
  9804. .blockColor(this.themeColor)
  9805. .trackColor($r('app.color.speed_text_color'))
  9806. .selectedColor(Color.White)
  9807. .trackThickness(6)
  9808. .onChange((value: number) => {
  9809. this.setBlurDegree(value, isPip)
  9810. })
  9811. .width('76%')
  9812. }
  9813. .margin({
  9814. left: 20,
  9815. right: 15,
  9816. top: 5,
  9817. bottom: 15
  9818. })
  9819. }
  9820. Row() {
  9821. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  9822. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  9823. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  9824. }
  9825. .justifyContent(FlexAlign.Center)
  9826. .margin({ top: 3, bottom: 10 })
  9827. }
  9828. }
  9829. private setBlurDegree(index: number, isPip: boolean) {
  9830. if (isPip) {
  9831. this.blurDegreePip = index
  9832. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  9833. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  9834. } else {
  9835. this.blurDegree = index
  9836. this.lyricController.setBlurDegree(this.blurDegree)
  9837. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  9838. }
  9839. }
  9840. private setLyricAlignMode(index: number, isPip: boolean) {
  9841. if (isPip) {
  9842. this.currentLyricAlignModePip = index
  9843. if (this.currentLyricAlignModePip === 1) {
  9844. this.lyricControllerXF.setAlignMode("left")
  9845. } else {
  9846. this.lyricControllerXF.setAlignMode("center")
  9847. }
  9848. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  9849. } else {
  9850. this.currentLyricAlignMode = index
  9851. if (this.currentLyricAlignMode === 1) {
  9852. this.lyricController.setAlignMode("left")
  9853. } else {
  9854. this.lyricController.setAlignMode("center")
  9855. }
  9856. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  9857. }
  9858. }
  9859. private setLyricTextSize(index: number, isPip: boolean) {
  9860. if (isPip) {
  9861. this.currentLyricSizePip = index
  9862. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  9863. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  9864. } else {
  9865. this.currentLyricSize = index
  9866. this.lyricController.setTextSize(this.currentLyricSize)
  9867. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  9868. }
  9869. }
  9870. private setHighLyricTextSize(scale: number, isPip: boolean) {
  9871. if (isPip) {
  9872. this.currentHightLyricSizePip = scale
  9873. this.lyricControllerXF
  9874. .setHighlightScale(this.currentHightLyricSizePip)
  9875. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  9876. } else {
  9877. this.currentHightLyricSize = scale
  9878. this.lyricController
  9879. .setHighlightScale(this.currentHightLyricSize)
  9880. PreferencesUtil.putSync('HighLyricTextSize', scale)
  9881. }
  9882. }
  9883. private setLyricLineSpace(index: number, isPip: boolean) {
  9884. if (isPip) {
  9885. this.currentLyricLineSpacePip = index
  9886. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  9887. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  9888. } else {
  9889. this.currentLyricLineSpace = index
  9890. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  9891. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  9892. }
  9893. }
  9894. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  9895. LogUtil.info('onecold isBG = ' + isBG)
  9896. if (isBG) { //如果是设置悬浮背景
  9897. this.pipBg = color
  9898. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  9899. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9900. return
  9901. }
  9902. if (isPip) {
  9903. this.currentLyricColorPip = color
  9904. this.lyricControllerXF
  9905. .setTextColor(this.currentLyricColorPip)
  9906. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  9907. } else {
  9908. this.currentLyricColor = color
  9909. this.lyricController
  9910. .setTextColor(this.currentLyricColor)
  9911. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  9912. }
  9913. }
  9914. private changeLyricHightLightColor(color: string, isPip: boolean) {
  9915. if (isPip) {
  9916. this.currentHighLightLyricColorPip = color
  9917. this.lyricControllerXF
  9918. .setHighlightColor(this.currentHighLightLyricColorPip)
  9919. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  9920. } else {
  9921. this.currentHighLightLyricColor = color
  9922. this.lyricController
  9923. .setHighlightColor(this.currentHighLightLyricColor)
  9924. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  9925. }
  9926. }
  9927. // 构建时间控制器
  9928. @Builder
  9929. BuildTimeControls() {
  9930. Column() {
  9931. // 时间显示
  9932. Text(this.getTimeText())
  9933. .fontSize(18)
  9934. .fontColor(Color.White)
  9935. .margin({ bottom: 10 })
  9936. Row() {
  9937. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  9938. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  9939. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  9940. }
  9941. .justifyContent(FlexAlign.Center)
  9942. }
  9943. .margin({ top: 12, bottom: 8 })
  9944. }
  9945. // 精度按钮组件
  9946. @Builder
  9947. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  9948. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9949. Column() {
  9950. Image(icon)
  9951. .width(28)
  9952. .margin({ bottom: 5 })
  9953. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  9954. Text(label)
  9955. .fontSize(12)
  9956. .fontColor('#FFFFFF')
  9957. }
  9958. }
  9959. .backgroundColor(Color.Transparent)
  9960. .enabled(!this.isButtonDisabled(step))
  9961. .onClick(() => this.handlePrecisionAdjust(step))
  9962. .padding(5)
  9963. .width(66)
  9964. .height(66)
  9965. .margin({ left: 18, right: 18 })
  9966. .border({
  9967. color: '#FFFFFF',
  9968. width: 1.8
  9969. })
  9970. }
  9971. private handlePrecisionAdjust(step: number) {
  9972. if (step === 0) {
  9973. this.timeOffset = 0
  9974. return
  9975. }
  9976. // 精度处理:保留1位小数
  9977. const newOffset = Number((this.timeOffset + step).toFixed(5))
  9978. // 边界保护(±15.0秒)
  9979. if (newOffset < -30.0 || newOffset > 30.0) {
  9980. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  9981. return
  9982. }
  9983. // 状态更新
  9984. this.timeOffset = newOffset
  9985. }
  9986. // 按钮禁用逻辑
  9987. private isButtonDisabled(step: number): boolean {
  9988. const futureOffset = this.timeOffset + step
  9989. return (futureOffset < -30.0) || (futureOffset > 30.0)
  9990. }
  9991. // 时间显示文本升级
  9992. private getTimeText(): string {
  9993. const absValue = Math.abs(this.timeOffset)
  9994. return this.timeOffset === 0
  9995. ? '歌词时间已重置'
  9996. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  9997. }
  9998. // 导入 本地歌词 搜索歌词
  9999. @Builder
  10000. pushLyricButton(icon: Resource, step: number, label: string) {
  10001. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10002. Row() {
  10003. Image(icon)
  10004. .width(14)
  10005. .margin({ left: 13 })
  10006. Text(label)
  10007. .fontSize(12)
  10008. .margin({ left: 6 })
  10009. .fontColor('#FFFFFF')
  10010. }
  10011. }
  10012. .onClick(() => {
  10013. switch (step) {
  10014. case 0:
  10015. this.callFilePickerSelectFileForLyric()
  10016. break;
  10017. case 1:
  10018. //判断有没有设置api
  10019. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10020. this.isLyricSetting = false
  10021. this.showTipsDialog()
  10022. return
  10023. }
  10024. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10025. ToastUtil.showToast('正在获取')
  10026. this.isLyricSetting = false
  10027. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10028. this.initLyric(lyricPath, true);
  10029. }
  10030. break;
  10031. }
  10032. })
  10033. .padding(5)
  10034. .width(110)
  10035. .backgroundColor(Color.Transparent)
  10036. .height(40)
  10037. .margin({ left: 6, right: 6 })
  10038. .border({
  10039. color: '#FFFFFF',
  10040. radius: 20,
  10041. width: 1.8
  10042. })
  10043. }
  10044. showVipDialog() {
  10045. DialogHelper.showCustomContentDialog({
  10046. dialogId: 'vip',
  10047. title: "友情提示",
  10048. autoCancel: false, //点击遮障层时,不关闭弹窗
  10049. backCancel: true, //点击返回键,不关闭弹窗
  10050. contentBuilder: () => {
  10051. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10052. },
  10053. buttons: [],
  10054. })
  10055. }
  10056. //去赞助的自定义内容
  10057. @Builder
  10058. customVipBuilder(content: string) {
  10059. Column() {
  10060. Text(content)
  10061. .fontColor(Color.Gray)
  10062. .fontSize(16)
  10063. .alignSelf(ItemAlign.Start)
  10064. .margin({ bottom: 15 })
  10065. .fontSize(16)
  10066. Row() {
  10067. Button('取消')
  10068. .fontColor(Color.White)
  10069. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10070. .height(50)
  10071. .layoutWeight(1)
  10072. .stateEffect(true)
  10073. .margin({ right: 6 })
  10074. .onClick(() => {
  10075. DialogHelper.closeDialog('vip'); //关闭弹框
  10076. })
  10077. Button('开通')
  10078. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10079. .layoutWeight(1)
  10080. .height(50)
  10081. .backgroundColor(this.themeColor)
  10082. .stateEffect(true)
  10083. .margin({ left: 6 })
  10084. .onClick(() => {
  10085. DialogHelper.closeDialog('vip'); //关闭弹框
  10086. this.isShowPlay = false
  10087. this.mType = 1 //跳转到用户中心
  10088. // router.pushUrl({
  10089. // url: 'pages/VipPage'
  10090. // }, router.RouterMode.Single);
  10091. })
  10092. }
  10093. }
  10094. .width("100%")
  10095. .padding(10)
  10096. }
  10097. showTipsDialog() {
  10098. DialogHelper.showCustomContentDialog({
  10099. dialogId: 'tips',
  10100. title: "友情提示",
  10101. autoCancel: false, //点击遮障层时,不关闭弹窗
  10102. backCancel: true, //点击返回键,不关闭弹窗
  10103. contentBuilder: () => {
  10104. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10105. },
  10106. buttons: [],
  10107. })
  10108. }
  10109. @Builder
  10110. customTipsBuilder(content: string) {
  10111. Column() {
  10112. Text(content)
  10113. .fontColor(Color.Gray)
  10114. .fontSize(16)
  10115. .alignSelf(ItemAlign.Start)
  10116. .margin({ bottom: 15 })
  10117. .fontSize(16)
  10118. Row() {
  10119. Button('取消')
  10120. .fontColor(Color.White)
  10121. .backgroundColor(this.themeColor)
  10122. .height(50)
  10123. .layoutWeight(1)
  10124. .stateEffect(true)
  10125. .margin({ right: 6 })
  10126. .onClick(() => {
  10127. DialogHelper.closeDialog('tips'); //关闭弹框
  10128. })
  10129. Button('跳转')
  10130. .fontColor(Color.White)//
  10131. .layoutWeight(1)
  10132. .height(50)
  10133. .backgroundColor(this.themeColor)
  10134. .stateEffect(true)
  10135. .margin({ left: 6 })
  10136. .onClick(() => {
  10137. DialogHelper.closeDialog('tips'); //关闭弹框
  10138. this.isShowEdit = false
  10139. this.longItemFilePath = ''
  10140. // if(this.isGridMusic&&!this.isShowPlay){
  10141. // this.longItemFilePath== ''
  10142. // }else{
  10143. // this.isShowEdit = false
  10144. // }
  10145. this.isShowMoreView = false;
  10146. this.isShowPlay = false
  10147. this.mType = 4
  10148. // router.pushUrl({
  10149. // url: 'pages/SettingPage'
  10150. // }, router.RouterMode.Single);
  10151. })
  10152. }
  10153. }
  10154. .width("100%")
  10155. .padding(10)
  10156. }
  10157. @Builder
  10158. PlayMoreSheet() {
  10159. Column() {
  10160. this.MoreList()
  10161. }
  10162. .width('100%')
  10163. .height('100%')
  10164. }
  10165. @Builder
  10166. MoreList() {
  10167. Scroll() {
  10168. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10169. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  10170. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10171. Row() {
  10172. if (more.id === 3&&this.currentSong) {
  10173. Image(more.image)
  10174. .width(24)
  10175. .height(24)
  10176. .margin({ left: 10, right: 10 })
  10177. Text(more.title)
  10178. .fontSize(16)
  10179. .fontColor(Color.White)
  10180. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  10181. height: this.isCoverOpacity() ? '95%' : '95%',
  10182. dragBar: true,
  10183. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10184. showClose: true,
  10185. blurStyle: BlurStyle.Thin,
  10186. backgroundColor: Color.Transparent,
  10187. title: { title: '歌曲信息' }
  10188. })
  10189. } else if (more.id === 15 && this.currentSong) { //编辑标签
  10190. Image(more.image)
  10191. .width(24)
  10192. .height(24)
  10193. .margin({ left: 10, right: 10 })
  10194. Text(more.title)
  10195. .fontSize(16)
  10196. .fontColor(Color.White)
  10197. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  10198. height: '99%',
  10199. dragBar: true,
  10200. showClose: true,
  10201. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10202. // blurStyle:BlurStyle.Thin,
  10203. // backgroundColor:Color.Transparent,
  10204. title: { title: '编辑标签' }
  10205. })
  10206. } else if (more.id === 5) { //定时关闭
  10207. Image(more.image)
  10208. .width(24)
  10209. .height(24)
  10210. .margin({ left: 10, right: 10 })
  10211. Text(more.title)
  10212. .fontSize(16)
  10213. .fontColor(Color.White)
  10214. .onClick(() => {
  10215. this.doMore(more.id)
  10216. })
  10217. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  10218. height: this.isCoverOpacity() ? '95%' : '95%',
  10219. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10220. dragBar: true,
  10221. showClose: true,
  10222. title: { title: $r('app.string.time_close') }
  10223. })
  10224. } else if (more.id === 2) { //歌词设置
  10225. Image(more.image)
  10226. .width(24)
  10227. .height(24)
  10228. .margin({ left: 10, right: 10 })
  10229. Text(more.title)
  10230. .fontSize(16)
  10231. .fontColor(Color.White)
  10232. } else if (more.id === 16) { //悬浮歌词设置
  10233. Image(more.image)
  10234. .width(24)
  10235. .height(24)
  10236. .margin({ left: 10, right: 10 })
  10237. Text(more.title)
  10238. .fontSize(16)
  10239. .fontColor(Color.White)
  10240. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  10241. height: this.isCoverOpacity() ? '95%' : '95%',
  10242. dragBar: true,
  10243. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10244. showClose: true,
  10245. blurStyle: BlurStyle.Thin,
  10246. backgroundColor: Color.Transparent,
  10247. title: { title: '悬浮歌词' }
  10248. })
  10249. } else if (more.id === 11) {
  10250. Image(more.image)
  10251. .width(24)
  10252. .height(24)
  10253. .margin({ left: 10, right: 10 })
  10254. Text(more.title)
  10255. .fontSize(16)
  10256. .fontColor(Color.White)
  10257. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  10258. height: this.isCoverOpacity() ? '95%' : '60%',
  10259. dragBar: true,
  10260. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10261. showClose: true,
  10262. blurStyle: BlurStyle.Thin,
  10263. backgroundColor: Color.Transparent,
  10264. title: { title: '跳过头尾' }
  10265. })
  10266. } else if (more.id === 12) { //投播
  10267. AVCastPicker({
  10268. customPicker: (): void => this.TPImageBuilder(more),
  10269. onStateChange: (state) => {
  10270. if (state == AVCastPickerState.STATE_APPEARING) {
  10271. console.log(' The picker starts showing.');
  10272. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10273. console.log(' The picker finishes presenting.');
  10274. }
  10275. },
  10276. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  10277. sessionType: 'video'
  10278. })
  10279. .id('AVCastPicker')
  10280. } else {
  10281. Image(more.image)
  10282. .width(24)
  10283. .height(24)
  10284. .fillColor(Color.White)
  10285. .margin({ left: 10, right: 10 })
  10286. .onClick(() => {
  10287. this.doMore(more.id)
  10288. })
  10289. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  10290. .fontSize(16)
  10291. .fontColor(Color.White)
  10292. .onClick(() => {
  10293. this.doMore(more.id)
  10294. })
  10295. Select([//倍速
  10296. { value: '0.25x' },
  10297. { value: '0.5x' },
  10298. { value: '0.75x' },
  10299. { value: '1x' },
  10300. { value: '1.25x' },
  10301. { value: '1.5x' },
  10302. { value: '1.75x' },
  10303. { value: '2x' },
  10304. { value: '3x' }])
  10305. .font({ size: 16, weight: FontWeight.Medium })
  10306. .fontColor($r('sys.color.white'))
  10307. .margin({ left: 25 })
  10308. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  10309. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  10310. .value(Utility.optimizedFormat(this.playSpeed))
  10311. .onSelect(async (_index: number, text?: string | undefined) => {
  10312. let speed = parseFloat(text?.replace('x', '') || '1');
  10313. if (!CommonConstants.video_speed_list.includes(speed)) {
  10314. speed = 1;
  10315. }
  10316. this.playSpeed = speed
  10317. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10318. })
  10319. Slider({
  10320. value: this.volume,
  10321. min: 0,
  10322. max: 1,
  10323. step: 0.1,
  10324. style: SliderStyle.OutSet
  10325. })
  10326. .margin({ left: 18, right: 8 })
  10327. .blockColor(this.themeColor)
  10328. .trackColor($r('app.color.speed_text_color'))
  10329. .selectedColor(Color.White)
  10330. .trackThickness(9)
  10331. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  10332. .onChange((value: number) => {
  10333. this.volume = value;
  10334. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10335. PreferencesUtil.putSync('DefalutVolume',this.volume)
  10336. })
  10337. .layoutWeight(1)
  10338. Blank()
  10339. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  10340. .selectedColor(this.themeColor)
  10341. .switchPointColor(Color.White)
  10342. .margin({ right: 15 })
  10343. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10344. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  10345. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10346. if (more.id == 6) {
  10347. this.isMusicMemoryPlay = checked;
  10348. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  10349. if (this.isMusicMemoryPlay) {
  10350. ToastUtil.showToast('记忆播放已开启')
  10351. } else {
  10352. ToastUtil.showToast('记忆播放已关闭')
  10353. }
  10354. }
  10355. })
  10356. .width(48)
  10357. .height(24);
  10358. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  10359. .selectedColor(this.themeColor)
  10360. .switchPointColor(Color.White)
  10361. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10362. .margin({ right: 15 })
  10363. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  10364. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10365. if (more.id == 7) {
  10366. this.isMusicBGCover = checked;
  10367. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  10368. if (this.isMusicBGCover) {
  10369. ToastUtil.showToast('播放背景随音乐封面已开启')
  10370. } else {
  10371. ToastUtil.showToast('播放背景随音乐封面已关闭')
  10372. }
  10373. }
  10374. })
  10375. .width(48)
  10376. .height(24);
  10377. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  10378. .selectedColor(this.themeColor)
  10379. .switchPointColor(Color.White)
  10380. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10381. .margin({ right: 15 })
  10382. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  10383. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10384. if (more.id == 8) {
  10385. this.isSavePlayMode = checked;
  10386. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  10387. if (this.isSavePlayMode) {
  10388. ToastUtil.showToast('保存播放模式已开启')
  10389. } else {
  10390. ToastUtil.showToast('保存播放模式已关闭')
  10391. }
  10392. }
  10393. })
  10394. .width(48)
  10395. .height(24);
  10396. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  10397. .selectedColor(this.themeColor)
  10398. .switchPointColor(Color.White)
  10399. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10400. .margin({ right: 15 })
  10401. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  10402. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  10403. if (more.id == 13) {
  10404. this.isCoverRectangle = checked;
  10405. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  10406. if (this.isCoverRectangle) {
  10407. ToastUtil.showToast('封面方形已开启')
  10408. this.animationRoFun()
  10409. } else {
  10410. ToastUtil.showToast('封面圆形已开启')
  10411. this.animationRoFun()
  10412. }
  10413. }
  10414. })
  10415. .width(48)
  10416. .height(24);
  10417. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  10418. .selectedColor(this.themeColor)
  10419. .switchPointColor(Color.White)
  10420. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10421. .margin({ right: 15 })
  10422. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  10423. .onChange((checked: boolean) => { // 是否开启背景流光效果
  10424. if (more.id == 21) {
  10425. this.isShowBgLiuGUANG = checked;
  10426. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  10427. }
  10428. })
  10429. .width(48)
  10430. .height(24);
  10431. }
  10432. }
  10433. .width('100%')
  10434. .height(45)
  10435. .padding(15)
  10436. .backgroundColor(Color.Transparent)
  10437. .borderRadius(12)
  10438. .margin({ bottom: 6 })
  10439. }
  10440. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  10441. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10442. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  10443. .backgroundColor(Color.Transparent)
  10444. .onClick(() => {
  10445. this.doMore(more.id)
  10446. })
  10447. });
  10448. }
  10449. .width('100%')
  10450. .padding(16)
  10451. }.margin({ bottom: 18 })
  10452. }
  10453. @Builder
  10454. TPImageBuilder(more: MoreItem): void {
  10455. Row() {
  10456. Image($r('app.media.tuoping'))
  10457. .width(22)
  10458. .height(22)
  10459. .margin({ left: 10, right: 10 })
  10460. Text(more.title)
  10461. .fontSize(16)
  10462. .fontColor(Color.White)
  10463. }
  10464. .width('100%')
  10465. .layoutWeight(1)
  10466. .alignItems(VerticalAlign.Center)
  10467. .justifyContent(FlexAlign.Start)
  10468. }
  10469. private moreItems: MoreItem[] = [
  10470. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  10471. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  10472. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  10473. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  10474. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  10475. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  10476. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  10477. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  10478. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  10479. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  10480. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  10481. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  10482. { id: 4, image: $r('app.media.share2'), title: '分享' },
  10483. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  10484. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  10485. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  10486. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  10487. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  10488. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  10489. ];
  10490. @State isShowBgLiuGUANG: boolean = true;
  10491. @State isShowMoreView: boolean = false;
  10492. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  10493. @State isShowTimeCloseMore: boolean = false
  10494. @State isShowDetailMore: boolean = false
  10495. @State isMusicBGCover: boolean = true
  10496. @State isSavePlayMode: boolean = true
  10497. @State isLyricSetting: boolean = false
  10498. @State isJumpSetting: boolean = false
  10499. @State isShowEdit: boolean = false
  10500. @State showPipLyric: boolean = false
  10501. async setRingTone() {
  10502. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  10503. return
  10504. }
  10505. // 确定后的逻辑
  10506. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  10507. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  10508. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  10509. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  10510. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  10511. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  10512. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  10513. , this.videoUrl, this.name).then(res => {
  10514. LogUtil.info('onecold setFlag :' + res);
  10515. });
  10516. }
  10517. doMore(moreId: number) {
  10518. switch (moreId) {
  10519. case 2: //歌词
  10520. this.isLyricSetting = !this.isLyricSetting;
  10521. this.isShowMoreView = false
  10522. break;
  10523. case 3: //详情
  10524. this.isShowDetailMore = !this.isShowDetailMore;
  10525. break;
  10526. case 4: //分享
  10527. if (this.currentSong !== undefined) {
  10528. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  10529. }
  10530. this.isShowMoreView = false
  10531. break;
  10532. case 5: //定时关闭
  10533. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  10534. break;
  10535. case 10: //设为铃声
  10536. this.setRingTone()
  10537. this.isShowMoreView = false
  10538. break;
  10539. case 11: //跳过头尾
  10540. this.isJumpSetting = !this.isJumpSetting;
  10541. break;
  10542. case 13: //倍速
  10543. break;
  10544. case 14: //搜索封面
  10545. if (this.currentSong !== undefined) {
  10546. this.doSearchCover(this.currentSong)
  10547. }
  10548. this.isShowMoreView = false
  10549. break;
  10550. case 15: //编辑标签
  10551. this.setEditStrEmpty()
  10552. this.tempLyricContent = this.lyricContent
  10553. this.isShowEdit = !this.isShowEdit;
  10554. break;
  10555. case 16: //悬浮歌词
  10556. this.showPipLyric = !this.showPipLyric;
  10557. break;
  10558. case 17: //横屏模式
  10559. if (this.isLandscape) {
  10560. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  10561. } else {
  10562. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  10563. }
  10564. this.isShowMoreView = false
  10565. break;
  10566. case 20://AB循环
  10567. this.isABSheet = !this.isABSheet
  10568. break;
  10569. }
  10570. }
  10571. //AB循环
  10572. @State isOpenAB:boolean = false
  10573. @State jumpATime:number = 0
  10574. @State jumpBTime:number = 0
  10575. @State isABSheet:boolean = false
  10576. @Builder
  10577. ABLoopSheet() {
  10578. ABLoopComptent({
  10579. jumpATime:this.jumpATime,
  10580. jumpBTime:this.jumpBTime,
  10581. onClickAItem: async ()=>{
  10582. if(this.mIjkMediaPlayer){
  10583. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  10584. }
  10585. },
  10586. onClickBItem: async ()=>{
  10587. if(this.mIjkMediaPlayer){
  10588. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  10589. if(this.jumpBTime<=this.jumpATime){
  10590. ToastUtil.showToast('设置B点时间不能小于A点时间')
  10591. this.jumpBTime = 0
  10592. }
  10593. }
  10594. },
  10595. onCancleButtonClick: async ()=>{
  10596. this.isOpenAB = false
  10597. this.isABSheet = false
  10598. },
  10599. onStartButtonClick: async ()=>{
  10600. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  10601. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  10602. return
  10603. }
  10604. this.isABSheet = false
  10605. this.startABLoop()
  10606. },
  10607. })
  10608. }
  10609. //开始AB循环
  10610. startABLoop(){
  10611. if(this.mIjkMediaPlayer){
  10612. this.seekTo(this.jumpATime+'')
  10613. this.isOpenAB = true
  10614. }
  10615. }
  10616. /**
  10617. * 切换横竖屏
  10618. *
  10619. */
  10620. setOrientation(orientation: number) {
  10621. this.windowClass.setPreferredOrientation(orientation).then(() => {
  10622. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  10623. }).catch((err: BusinessError) => {
  10624. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  10625. });
  10626. }
  10627. /**
  10628. * 画中画功能(悬浮歌词功能)
  10629. *
  10630. */
  10631. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  10632. pipController?: PiPWindow.PiPController;
  10633. navigationId: string = '';
  10634. @State curState: string = '';
  10635. @State curError: ResourceStr = '';
  10636. @State pipBg: string = '#E8E8E8'
  10637. @State buttonAction: string = '';
  10638. //开启画中画功能
  10639. async startPip() {
  10640. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  10641. if (!this.pipController) {
  10642. await this.createPipController();
  10643. }
  10644. if (!this.pipController) {
  10645. Logger.info(`[${TAG}] pipController create error`);
  10646. return;
  10647. }
  10648. await this.pipController.startPiP();
  10649. }
  10650. async stopPip() {
  10651. if (!this.pipController) {
  10652. Logger.info(`[${TAG}] pipController is not exist`);
  10653. return;
  10654. }
  10655. this.isOpenPip = false
  10656. await this.pipController.stopPiP();
  10657. }
  10658. async createPipController() {
  10659. this.pipController = await PiPWindow.create({
  10660. context: getContext(this),
  10661. componentController: this.xcomponentController,
  10662. navigationId: this.navigationId,
  10663. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  10664. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  10665. customUIController: this.nodeController,
  10666. });
  10667. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  10668. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  10669. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10670. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  10671. this.onStateChange(state, reason);
  10672. });
  10673. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  10674. this.onActionEvent(event, status);
  10675. });
  10676. }
  10677. destroyPipController() {
  10678. if (!this.pipController) {
  10679. return;
  10680. }
  10681. this.pipController.off('stateChange');
  10682. this.pipController.off('controlPanelActionEvent');
  10683. this.pipController = undefined;
  10684. }
  10685. onStateChange(state: PiPWindow.PiPState, reason: string) {
  10686. switch (state) {
  10687. case PiPWindow.PiPState.ABOUT_TO_START:
  10688. this.curState = 'ABOUT_TO_START';
  10689. this.curError = $r('app.string.current_error_hint');
  10690. break;
  10691. case PiPWindow.PiPState.STARTED:
  10692. this.curState = 'STARTED';
  10693. this.curError = $r('app.string.current_error_hint');
  10694. break;
  10695. case PiPWindow.PiPState.ABOUT_TO_STOP:
  10696. this.curState = 'ABOUT_TO_STOP';
  10697. this.curError = $r('app.string.current_error_hint');
  10698. break;
  10699. case PiPWindow.PiPState.STOPPED:
  10700. this.curState = 'STOPPED';
  10701. this.curError = $r('app.string.current_error_hint');
  10702. this.stopPip()
  10703. this.destroyPipController()
  10704. break;
  10705. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  10706. this.curState = 'ABOUT_TO_RESTORE';
  10707. this.curError = $r('app.string.current_error_hint');
  10708. break;
  10709. case PiPWindow.PiPState.ERROR:
  10710. this.curState = 'ERROR';
  10711. this.curError = reason;
  10712. break;
  10713. default:
  10714. break;
  10715. }
  10716. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  10717. }
  10718. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  10719. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  10720. switch (event) {
  10721. case 'playbackStateChanged':
  10722. if (status === 0) {
  10723. this.pause();
  10724. } else {
  10725. console.info('onecold startPlayOrResumePlay 9869')
  10726. this.startPlayOrResumePlay();
  10727. }
  10728. break;
  10729. case 'nextVideo':
  10730. // 切换到下一个视频
  10731. this.playNext().catch(() => {
  10732. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  10733. });
  10734. break;
  10735. case 'previousVideo':
  10736. // 切换到上一个视频
  10737. this.playPrevious().catch(() => {
  10738. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  10739. });
  10740. break;
  10741. case 'previousVideo':
  10742. // 切换到上一个视频
  10743. this.playPrevious().catch(() => {
  10744. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  10745. });
  10746. break;
  10747. default:
  10748. }
  10749. this.buttonAction = event + `-status:${status}`;
  10750. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  10751. }
  10752. /**
  10753. * 画中画功能(悬浮歌词功能)结束
  10754. *
  10755. */
  10756. async doSearchCover(item: VideoItem): Promise<string> {
  10757. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  10758. this.isShowMoreView = false;
  10759. this.showTipsDialog();
  10760. return ''; // Return empty string when no API is configured
  10761. }
  10762. if (!item) {
  10763. return ''; // Return empty string if item is undefined
  10764. }
  10765. const artist = item?.artist || ''; // Use empty string if artist is missing
  10766. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  10767. }
  10768. /**
  10769. *api搜索封面
  10770. *item,根据title和artist
  10771. */
  10772. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  10773. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  10774. LogUtil.debug("onecold res =" + res);
  10775. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10776. if (item.filePath == this.currentSong?.filePath) {
  10777. this.cover = res;
  10778. if (this.currentSong) {
  10779. this.currentSong.pixelMapPath = res;
  10780. }
  10781. }
  10782. // Update pixel map path but always return res regardless of success
  10783. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  10784. if (success) {
  10785. this.doUpdateData();
  10786. console.log("onecold 更新音乐封面成功,数据库已同步");
  10787. } else {
  10788. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  10789. }
  10790. // Note: We don't resolve/reject here because we already returned res
  10791. });
  10792. LogUtil.debug("onecold this.cover =" + this.cover);
  10793. }
  10794. return res; // Always return res regardless of updatePixelMapPath result
  10795. });
  10796. }
  10797. @State jumpTopTime: number = 0
  10798. @State jumpEndTime: number = 0
  10799. @State isOpenJump: boolean = false
  10800. @Builder
  10801. JumpTopEndSheet() {
  10802. Scroll() {
  10803. Column() {
  10804. Column() {
  10805. Text('仅对本播放列表有效')
  10806. .fontSize(16)
  10807. .fontColor($r('app.color.text_color'))
  10808. // 跳过头尾
  10809. Column() {
  10810. Row() {
  10811. Text('跳过片头:')
  10812. .fontSize(16)
  10813. .fontColor($r('app.color.text_color'))
  10814. Text(this.jumpTopTime + 's')
  10815. .fontSize(16)
  10816. .fontColor($r('app.color.text_color'))
  10817. }
  10818. .margin({ bottom: 5 })
  10819. Row() {
  10820. Slider({
  10821. value: this.jumpTopTime,
  10822. min: 0,
  10823. max: 120,
  10824. step: 1,
  10825. style: SliderStyle.OutSet
  10826. })
  10827. .blockColor(this.themeColor)
  10828. .trackColor($r('app.color.speed_text_color'))
  10829. .selectedColor(Color.White)
  10830. .trackThickness(8)
  10831. .onChange((value: number) => {
  10832. this.jumpTopTime = value;
  10833. })
  10834. .width('85%')
  10835. }
  10836. .alignItems(VerticalAlign.Top)
  10837. }
  10838. .margin({ top: 10, bottom: 10 })
  10839. // 跳过头尾
  10840. Column() {
  10841. Row() {
  10842. Text('跳过片尾:')
  10843. .fontSize(16)
  10844. .fontColor($r('app.color.text_color'))
  10845. Text(this.jumpEndTime + 's')
  10846. .fontSize(16)
  10847. .fontColor($r('app.color.text_color'))
  10848. }
  10849. .margin({ bottom: 5 })
  10850. Row() {
  10851. Slider({
  10852. value: this.jumpEndTime,
  10853. min: 0,
  10854. max: 120,
  10855. step: 1,
  10856. style: SliderStyle.OutSet
  10857. })
  10858. .blockColor(this.themeColor)
  10859. .trackColor($r('app.color.speed_text_color'))
  10860. .selectedColor(Color.White)
  10861. .trackThickness(8)
  10862. .onChange((value: number) => {
  10863. this.jumpEndTime = value;
  10864. })
  10865. .width('85%')
  10866. }
  10867. .alignItems(VerticalAlign.Top)
  10868. }
  10869. .margin({ top: 10, bottom: 10 })
  10870. Row() {
  10871. Button('保存设置')
  10872. .fontColor(Color.White)
  10873. .layoutWeight(1)
  10874. .height(40)
  10875. .width(80)
  10876. .backgroundColor(this.themeColor)
  10877. .stateEffect(true)
  10878. .margin({ left: 0, bottom: 20 })
  10879. .onClick(async () => {
  10880. if (!Utility.isNoble()) {
  10881. this.isJumpSetting = false
  10882. this.isShowMoreView = false
  10883. this.showVipDialog()
  10884. return
  10885. }
  10886. if (this.currentSong === undefined) {
  10887. return
  10888. }
  10889. if (this.modeType === 0) {
  10890. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10891. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  10892. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  10893. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  10894. } else if (this.modeType === 1) { //媒体库
  10895. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  10896. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  10897. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  10898. } else if (this.modeType === 2) { //艺术家
  10899. if (this.currentSong?.artist) {
  10900. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  10901. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  10902. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  10903. }
  10904. } else if (this.modeType === 3) { //专辑
  10905. if (this.currentSong?.album) {
  10906. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  10907. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  10908. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  10909. }
  10910. }
  10911. ToastUtil.showShort("保存成功")
  10912. this.isJumpSetting = false
  10913. })
  10914. }
  10915. .margin({
  10916. left: 38,
  10917. right: 38,
  10918. top: 10,
  10919. bottom: 10
  10920. })
  10921. .width(120)
  10922. .height(50)
  10923. }
  10924. }
  10925. }
  10926. .width('100%')
  10927. .height('100%')
  10928. }
  10929. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  10930. private onStateVastChange(state: AVCastPickerState) {
  10931. if (state == AVCastPickerState.STATE_APPEARING) {
  10932. console.log('The picker starts showing.');
  10933. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10934. console.log('The picker finishes presenting.');
  10935. }
  10936. }
  10937. private showSelectLyric() {
  10938. DialogHelper.showActionSheetDialog({
  10939. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  10940. // sheets: ["本地歌词", "搜索歌词"],
  10941. sheets: [
  10942. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  10943. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  10944. ],
  10945. maskColor: Color.Transparent,
  10946. backgroundColor: $r('app.color.bg_card'),
  10947. transition: AnimationHelper.transitionInDown(666),
  10948. onAction: (index) => {
  10949. switch (index) {
  10950. case 0:
  10951. this.callFilePickerSelectFileForLyric()
  10952. break;
  10953. case 1:
  10954. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10955. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10956. this.initLyric(lyricPath);
  10957. }
  10958. break;
  10959. }
  10960. }
  10961. })
  10962. }
  10963. // 拉起picker选择文件管理器
  10964. async callFilePickerSelectFileForLyric(): Promise<void> {
  10965. try {
  10966. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  10967. DocumentSelectOptions.maxSelectNumber = 1
  10968. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  10969. let documentPicker = new picker.DocumentViewPicker();
  10970. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  10971. Logger.info(TAG,
  10972. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  10973. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  10974. this.saveVideoDatasLyric(DocumentSelectResult)
  10975. }
  10976. }).catch((err: BusinessError) => {
  10977. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  10978. });
  10979. } catch (err) {
  10980. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  10981. }
  10982. }
  10983. async saveVideoDatasLyric(uris: string[]) {
  10984. if (ArrayUtil.isEmpty(uris)) {
  10985. return
  10986. }
  10987. let newUris: string[] = [];
  10988. for (let i = 0; i < uris.length; i++) {
  10989. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  10990. Logger.info(TAG, 'filePath uri: ' + filePath);
  10991. newUris.push(filePath)
  10992. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  10993. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  10994. fileIo.copyFileSync(file.fd, file2.fd)
  10995. fileIo.closeSync(file);
  10996. fileIo.closeSync(file2);
  10997. this.initLyric(filePath,false,false,true)
  10998. }
  10999. }
  11000. private initDelayPlay(context: object) {
  11001. this.mContext = context;
  11002. }
  11003. startPipLyric() {
  11004. if (this.pipController) {
  11005. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11006. PiPWindow.PiPControlStatus.PLAY);
  11007. }
  11008. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11009. if (this.isOpenPip) {
  11010. this.startPip()
  11011. } else {
  11012. this.stopPip()
  11013. }
  11014. }
  11015. //startOffset 从cue分轨时间开始播
  11016. private startPlayOrResumePlay(startOffset?:number) {
  11017. //针对dsf文件高采样率sampleRate>441000,统一转wav播放
  11018. const sampleRate = this.currentSong?.sampleRate||0
  11019. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11020. console.info('onecold 采样率 ='+sampleRate)
  11021. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11022. console.info('onecold newDsfPath ='+newDsfPath)
  11023. if(!FileUtil.accessSync(newDsfPath)){
  11024. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11025. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11026. this.videoUrl = newDsfPath
  11027. this.startPlay(startOffset)
  11028. }).catch((e:object)=>{
  11029. console.info("task1 catch e: " + e);
  11030. })
  11031. }else{
  11032. this.videoUrl = newDsfPath
  11033. this.startPlay(startOffset)
  11034. }
  11035. }else{
  11036. this.startPlay(startOffset)
  11037. }
  11038. }
  11039. startPlay(startOffset?:number) {
  11040. this.startPipLyric()
  11041. this.mDestroyPage = false;
  11042. this.animationState = AnimationStatus.Running
  11043. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11044. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11045. this.stopProgressTask();
  11046. this.startProgressTask();
  11047. this.play(this.videoUrl.toString(),startOffset);
  11048. }
  11049. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11050. this.mIjkMediaPlayer.start();
  11051. this.setProgress()
  11052. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11053. }
  11054. this.setIsPlaying(true)
  11055. this.updateSessionPlayState(true)
  11056. this.watchStatus();
  11057. this.updateLastPlayTimeStr(this.videoUrl)
  11058. }
  11059. updateLastPlayTimeStr(filePath: string) {
  11060. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11061. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  11062. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11063. return;
  11064. }
  11065. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11066. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11067. if (success) {
  11068. this.getHistoryList(false)
  11069. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11070. } else {
  11071. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11072. }
  11073. });
  11074. }
  11075. private completionNum(num: number): string | number {
  11076. if (num < 10) {
  11077. return '0' + num;
  11078. } else {
  11079. return num;
  11080. }
  11081. }
  11082. private stringForTime(timeMs: number): string {
  11083. let totalSeconds: number | string = (timeMs / 1000);
  11084. let newSeconds: number | string = totalSeconds % 60;
  11085. let minutes: number | string = (totalSeconds / 60) % 60;
  11086. let hours: number | string = totalSeconds / 3600;
  11087. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11088. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11089. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11090. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11091. if (this.isCurrentTime) {
  11092. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11093. this.oldSeconds = newSeconds
  11094. } else {
  11095. newSeconds = this.oldSeconds
  11096. }
  11097. }
  11098. newSeconds = this.completionNum(newSeconds);
  11099. if (hours > 0) {
  11100. return hours + ":" + minutes + ":" + newSeconds;
  11101. } else {
  11102. return minutes + ":" + newSeconds;
  11103. }
  11104. }
  11105. private setProgress() {
  11106. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11107. let duration = this.mIjkMediaPlayer.getDuration();
  11108. let pos = 0;
  11109. if (duration > 0) {
  11110. this.slideEnable = true;
  11111. let curPercent = position / duration;
  11112. pos = curPercent * 100;
  11113. if (pos > this.PROGRESS_MAX_VALUE) {
  11114. this.progressValue = this.PROGRESS_MAX_VALUE
  11115. } else {
  11116. this.progressValue = pos;
  11117. }
  11118. }
  11119. // LogUtils.getInstance()
  11120. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11121. this.totalTime = this.stringForTime(duration);
  11122. if (position > duration) {
  11123. position = duration;
  11124. }
  11125. this.isCurrentTime = true;
  11126. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  11127. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  11128. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  11129. this.currentTime = this.stringForTime(position);
  11130. this.isCurrentTime = false
  11131. if (this.mIjkMediaPlayer.isPlaying()) {
  11132. this.randomColor =
  11133. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  11134. //如果是开启AB循环
  11135. if(this.isOpenAB){
  11136. if(position >=this.jumpBTime){
  11137. this.seekTo(this.jumpATime+'')
  11138. return
  11139. }
  11140. }
  11141. // 判断是否播放到结束时间
  11142. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  11143. if (position >= duration - this.jumpEndTime * 1000) {
  11144. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  11145. this.CONTROL_PlayStatus = PlayStatus.INIT
  11146. this.startPlayOrResumePlay();
  11147. }else if (this.playType == 2) { //2:正常播放,单曲播完
  11148. this.showRePlay();
  11149. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  11150. this.progressValue = this.PROGRESS_MAX_VALUE;
  11151. this.slideEnable = false;
  11152. this.stop();
  11153. // ToastUtil.showToast('开始重新播放')
  11154. }else{
  11155. this.playNext().catch(() => {
  11156. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  11157. });
  11158. }
  11159. }
  11160. }
  11161. } else {
  11162. this.randomColor = 'rbg(0,0,0)'
  11163. }
  11164. }
  11165. private startProgressTask() {
  11166. let that = this;
  11167. this.updateProgressTimer = setInterval(() => {
  11168. //LogUtils.getInstance().LOGI("startProgressTask");
  11169. if (!that.mDestroyPage) {
  11170. that.setProgress();
  11171. }
  11172. }, 300);
  11173. }
  11174. private stopProgressTask() {
  11175. LogUtils.getInstance().LOGI("stopProgressTask");
  11176. clearInterval(this.updateProgressTimer);
  11177. }
  11178. private showLoadIng() {
  11179. this.loadingVisible = Visibility.Visible;
  11180. this.replayVisible = Visibility.None;
  11181. }
  11182. private hideLoadIng() {
  11183. this.loadingVisible = Visibility.None;
  11184. this.replayVisible = Visibility.None;
  11185. }
  11186. private showRePlay() {
  11187. this.loadingVisible = Visibility.None;
  11188. this.replayVisible = Visibility.Visible;
  11189. }
  11190. private async play(url: string,startOffset?:number) {
  11191. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  11192. console.info('onecold this.url 1= '+url)
  11193. if(!url.toLowerCase().startsWith('http')){
  11194. let hasPermission = await PermissionUtil.activatePermission(url)
  11195. console.info('onecold this.hasPermission 1= '+hasPermission)
  11196. if(!url.includes(this.packName)){
  11197. const file = fs.openSync(url)
  11198. this.videoUrl = file.path
  11199. url= this.videoUrl
  11200. }
  11201. console.info('onecold this.hasPermission 1= '+hasPermission)
  11202. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  11203. }
  11204. let that = this;
  11205. that.showLoadIng();
  11206. this.isOpenAB = false
  11207. //设置XComponent回调的context
  11208. if (!!this.mContext) {
  11209. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  11210. }
  11211. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11212. this.mIjkMediaPlayer.reset();
  11213. }
  11214. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  11215. //设置debug模式
  11216. this.mIjkMediaPlayer.setDebug(false);
  11217. //初始化配置
  11218. this.mIjkMediaPlayer.native_setup();
  11219. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  11220. if(this.volumeSmall){
  11221. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11222. this.mIjkMediaPlayer.setVolume('1', '1');
  11223. }else{
  11224. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11225. }
  11226. }else{
  11227. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11228. }
  11229. //设置视频源
  11230. this.mIjkMediaPlayer.setDataSource(url);
  11231. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  11232. const headers = new Map<string, string>();
  11233. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  11234. headers.set("Accept", "*/*");
  11235. headers.set("Range", "bytes=0-");
  11236. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  11237. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  11238. //如果封面为空,则搜索封面
  11239. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  11240. }
  11241. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  11242. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  11243. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  11244. if (this.currentSong.webdav_account_id) {
  11245. try {
  11246. const webdavManager = WebdavManager.getInstance();
  11247. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  11248. if (webDavHeaders && webDavHeaders.size > 0) {
  11249. webDavHeaders.forEach((value, key) => headers.set(key, value));
  11250. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  11251. } else {
  11252. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  11253. }
  11254. } catch (error) {
  11255. const err = error as Error;
  11256. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  11257. }
  11258. } else {
  11259. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  11260. }
  11261. }
  11262. // 统一设置带认证的请求头
  11263. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  11264. if (this.currentSong&&this.currentSong.type === CommonConstants.TYPE_WEBDAV) {
  11265. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  11266. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  11267. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  11268. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  11269. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  11270. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  11271. // 缓冲和播放优化设置
  11272. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  11273. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  11274. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  11275. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  11276. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  11277. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  11278. // 网络相关设置
  11279. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  11280. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  11281. // 重连设置
  11282. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  11283. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  11284. }
  11285. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  11286. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  11287. // }
  11288. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  11289. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  11290. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  11291. const fileSize = await this.getFileSize(this.videoUrl);
  11292. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  11293. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  11294. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  11295. }
  11296. // 使用软件解码(通常比硬件解码更节省内存)
  11297. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  11298. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  11299. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  11300. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  11301. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  11302. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  11303. //停止预读的最小帧数
  11304. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  11305. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  11306. // 设置其他缓冲相关选项
  11307. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  11308. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  11309. //启动预加载
  11310. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  11311. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  11312. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  11313. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  11314. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  11315. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  11316. // 因此需要播放器丢包,才不会累积延时
  11317. // 这个和第三个参数packet-buffering无关。
  11318. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  11319. // 无限制收流
  11320. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  11321. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  11322. // 屏幕常亮
  11323. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  11324. // 设置超时
  11325. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  11326. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  11327. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  11328. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  11329. // 变速播放
  11330. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  11331. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11332. let Speed = this.mIjkMediaPlayer.getSpeed()
  11333. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  11334. //是否开启循环播放
  11335. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  11336. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  11337. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  11338. if (height === 0) {
  11339. return;
  11340. }
  11341. const va = width / height;
  11342. const vpa = that.videoParentAspectRatio;
  11343. if (vpa > va) {
  11344. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  11345. } else {
  11346. that.videoWidth = '100%';
  11347. }
  11348. if (width && height) {
  11349. that.videoAspectRatio = width / height;
  11350. }
  11351. LogUtils.getInstance()
  11352. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  11353. that.hideLoadIng();
  11354. }
  11355. }
  11356. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  11357. let mOnPreparedListener: OnPreparedListener = {
  11358. onPrepared: async () => {
  11359. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  11360. try {
  11361. // this.cover = this.songList[this.curIndex].pixelMapPath
  11362. // this.artist = this.songList[this.curIndex].artist
  11363. // this.videoUrl = this.songList[this.curIndex].filePath
  11364. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  11365. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  11366. this.setImageColor2(this.cover)
  11367. } else {
  11368. this.getImageColor();
  11369. }
  11370. //保存碰一碰分享的当前的歌曲
  11371. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  11372. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11373. await this.initLyric(lyricPath);
  11374. setTimeout(() => {
  11375. this.avSessionController.initAvSession(false);
  11376. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  11377. this.setAvSessionListener();
  11378. this.updateSessionPlayState(true)
  11379. this.setCurrentPlayMode()
  11380. }, 500)
  11381. if(startOffset&&startOffset>0){//cue分轨播放
  11382. this.seekTo(startOffset + "");
  11383. this.saveLastPlayList()
  11384. return
  11385. }
  11386. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11387. let timeoutPlay = 0
  11388. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11389. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  11390. timeoutPlay = 1000
  11391. }
  11392. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  11393. if (this.modeType === 0) { //文件夹
  11394. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11395. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  11396. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  11397. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  11398. } else if (this.modeType === 1) { //媒体库
  11399. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  11400. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  11401. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  11402. } else if (this.modeType === 2) { //艺术家
  11403. if (this.currentSong?.artist) {
  11404. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  11405. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  11406. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  11407. }
  11408. } else if (this.modeType === 3) { //专辑
  11409. if (this.currentSong?.album) {
  11410. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  11411. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  11412. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  11413. }
  11414. }
  11415. this.duration = this.mIjkMediaPlayer.getDuration()
  11416. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  11417. if (this.mIjkMediaPlayer != null) {
  11418. let jumpTopTimeMs = this.jumpTopTime*1000;
  11419. if (jumpTopTimeMs <= this.duration) {
  11420. // 调用 seekTo 方法,跳到指定时间
  11421. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  11422. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  11423. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11424. console.log('onecold position = '+position);
  11425. if (position > jumpTopTimeMs) {
  11426. jumpTopTimeMs = position
  11427. }
  11428. }
  11429. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11430. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11431. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  11432. }
  11433. }, timeoutPlay)
  11434. } else {
  11435. // 提示用户无法跳过
  11436. ToastUtil.showToast('跳过时间超过视频时长');
  11437. }
  11438. }
  11439. } else {
  11440. this.jumpTopTime = 0
  11441. this.jumpEndTime = 0
  11442. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  11443. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  11444. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  11445. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  11446. //记忆播放(每一首都会记忆播放)
  11447. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  11448. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  11449. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  11450. this.restorePlaybackPosition() //读取播放记忆功能
  11451. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  11452. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  11453. this.restorePlaybackPosition() //读取播放记忆功能
  11454. }
  11455. this.isFirstStartPlay = false
  11456. }, timeoutPlay)
  11457. } else {
  11458. this.isFirstStartPlay = false
  11459. }
  11460. }
  11461. this.saveLastPlayList()
  11462. } catch (error) {
  11463. let err: BusinessError = error as BusinessError;
  11464. console.error('onecold failed with err: ' + JSON.stringify(err));
  11465. }
  11466. }
  11467. }
  11468. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  11469. let mOnTimedTextListener: OnTimedTextListener = {
  11470. onTimedText: () => {
  11471. }
  11472. }
  11473. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  11474. let mOnCompletionListener: OnCompletionListener = {
  11475. onCompletion: () => {
  11476. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  11477. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  11478. // 异步调用playNext
  11479. this.playNext().catch(() => {
  11480. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  11481. });
  11482. } else if (this.playType == 1) { //1:单片重复播放
  11483. this.CONTROL_PlayStatus = PlayStatus.INIT
  11484. console.info('onecold startPlayOrResumePlay 10592')
  11485. that.startPlayOrResumePlay();
  11486. } else if (this.playType == 2) { //2:正常播放,单曲播完
  11487. that.showRePlay();
  11488. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  11489. that.progressValue = this.PROGRESS_MAX_VALUE;
  11490. that.slideEnable = false;
  11491. that.stop();
  11492. // ToastUtil.showToast('开始重新播放')
  11493. } else if (this.playType == 3) { //3:随机播放
  11494. // 异步调用randomPlay
  11495. this.randomPlay().catch(() => {
  11496. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  11497. });
  11498. }
  11499. }
  11500. }
  11501. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  11502. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  11503. onBufferingUpdate: (percent: number) => {
  11504. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  11505. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  11506. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  11507. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  11508. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  11509. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  11510. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  11511. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  11512. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  11513. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  11514. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  11515. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  11516. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  11517. let Looping = this.mIjkMediaPlayer.isLooping()
  11518. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  11519. }
  11520. }
  11521. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  11522. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  11523. onSeekComplete: () => {
  11524. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  11525. console.info('onecold startPlayOrResumePlay 10643')
  11526. that.startPlayOrResumePlay();
  11527. }
  11528. }
  11529. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  11530. let mOnInfoListener: OnInfoListener = {
  11531. onInfo: (what: number, extra: number) => {
  11532. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  11533. that.hideLoadIng();
  11534. }
  11535. }
  11536. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  11537. let mOnErrorListener: OnErrorListener = {
  11538. onError: (what: number, extra: number) => {
  11539. this.stopProgressTask();
  11540. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  11541. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  11542. // 检查是否为WebDAV播放错误
  11543. let isWebDavError = false;
  11544. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_WEBDAV && this.currentSong.filePath) {
  11545. try {
  11546. const globalContext = GlobalContext.getContext();
  11547. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  11548. if (webDavAuthInfo) {
  11549. isWebDavError = true;
  11550. }
  11551. } catch (error) {
  11552. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  11553. }
  11554. }
  11555. if (isWebDavError) {
  11556. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  11557. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  11558. // this.currentWebDavAuthInfo = null;
  11559. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  11560. // 根据错误代码提供更具体的错误信息
  11561. let errorMessage = "WebDAV播放失败";
  11562. if (what === -1) { // 网络错误
  11563. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  11564. } else if (what === -1004) { // HTTP 404
  11565. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  11566. } else if (what === -1001) { // 超时
  11567. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  11568. } else if (what === -1003) { // 无法解析主机
  11569. errorMessage = "无法连接到WebDAV服务器";
  11570. }
  11571. ToastUtil.showToast(errorMessage);
  11572. } else {
  11573. if (StrUtil.isNotEmpty(this.videoUrl) &&
  11574. !this.videoUrl.startsWith('http://') &&
  11575. !this.videoUrl.startsWith('https://') &&
  11576. !FileUtil.accessSync(this.videoUrl)) {
  11577. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  11578. } else {
  11579. ToastUtil.showToast(getContext()
  11580. .resourceManager
  11581. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  11582. }
  11583. }
  11584. that.hideLoadIng();
  11585. }
  11586. }
  11587. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  11588. this.mIjkMediaPlayer.setMessageListener();
  11589. this.mIjkMediaPlayer.prepareAsync();
  11590. this.mIjkMediaPlayer.start();
  11591. }
  11592. //保存最后播放的那首歌和已经对应的播放列表
  11593. saveLastPlayList() {
  11594. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  11595. PreferencesUtil.putSync('LastMusicList', this.songList)
  11596. }
  11597. // 清空播放记录
  11598. clearVideoHistory() {
  11599. this.table.clearPlayHistory((success: boolean, error?: string) => {
  11600. if (success) {
  11601. this.historyList = [];
  11602. this.updateListData(this.historyList)
  11603. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  11604. ToastUtil.showToast('清空播放记录成功')
  11605. } else {
  11606. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  11607. }
  11608. });
  11609. }
  11610. public async setAvSessionListener() {
  11611. if (!this.avSessionController) {
  11612. return;
  11613. }
  11614. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  11615. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  11616. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  11617. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  11618. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  11619. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  11620. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  11621. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  11622. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  11623. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  11624. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  11625. }
  11626. setLoopMode() {
  11627. let itype = this.playType + 1
  11628. if (itype >= 4) {
  11629. this.playType = 0
  11630. ToastUtil.showToast('连续播放')
  11631. } else if (itype === 1) {
  11632. this.playType = 1
  11633. ToastUtil.showToast('单曲循环')
  11634. } else if (itype === 2) {
  11635. this.playType = 2
  11636. ToastUtil.showToast('单曲播完')
  11637. } else if (itype === 3) {
  11638. this.playType = 3
  11639. ToastUtil.showToast('随机播放')
  11640. } else if (itype === 0) {
  11641. this.playType = 0
  11642. ToastUtil.showToast('连续播放')
  11643. }
  11644. PreferencesUtil.putSync('musicPlayType', this.playType)
  11645. this.setCurrentPlayMode()
  11646. }
  11647. private sessionSetLoopModeCallback = (mode: number) => {
  11648. if (this.mIjkMediaPlayer != null) {
  11649. ToastUtil.showToast('当前播放模式:' + mode)
  11650. Logger.info('onecold 当前播放模式= ' + mode)
  11651. let hmPlayMode = mode + 1
  11652. if (hmPlayMode >= 4) {
  11653. hmPlayMode = 0
  11654. }
  11655. if (hmPlayMode === 1) {
  11656. this.playType = 1
  11657. ToastUtil.showToast('单曲循环')
  11658. } else if (hmPlayMode === 0) {
  11659. this.playType = 2
  11660. ToastUtil.showToast('单曲播完')
  11661. } else if (hmPlayMode === 3) {
  11662. this.playType = 3
  11663. ToastUtil.showToast('随机播放')
  11664. } else if (hmPlayMode === 2) {
  11665. this.playType = 0
  11666. ToastUtil.showToast('连续播放')
  11667. }
  11668. PreferencesUtil.putSync('musicPlayType', this.playType)
  11669. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  11670. let playBackState: avSession.AVPlaybackState = {
  11671. loopMode: hmPlayMode,
  11672. };
  11673. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  11674. console.info(`set setLoopMode AVPlaybackState successfully`);
  11675. }).catch((err: BusinessError) => {
  11676. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11677. });
  11678. }
  11679. }
  11680. setCurrentPlayMode() {
  11681. if (!this.avSessionController) {
  11682. return;
  11683. }
  11684. let mLoopMode = 0
  11685. switch (this.playType) {
  11686. case 0:
  11687. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  11688. break;
  11689. case 1:
  11690. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  11691. break;
  11692. case 2:
  11693. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  11694. break;
  11695. case 3:
  11696. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  11697. break;
  11698. }
  11699. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  11700. let playBState: avSession.AVPlaybackState = {
  11701. loopMode: mLoopMode,
  11702. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  11703. };
  11704. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  11705. console.info(`set setLoopMode AVPlaybackState successfully`);
  11706. }).catch((err: BusinessError) => {
  11707. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  11708. });
  11709. }
  11710. private sessionToggleFavoriteCallback = (assetId: string) => {
  11711. if (this.mIjkMediaPlayer != null && this.currentSong) {
  11712. console.info(`on toggleFavorite `);
  11713. // 应用收到收藏命令,进行收藏处理。
  11714. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  11715. this.doFav(this.currentSong)
  11716. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  11717. let playbackState: avSession.AVPlaybackState = {
  11718. isFavorite: !this.isFac,
  11719. };
  11720. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  11721. console.info(`SetAVPlaybackState successfully`);
  11722. }).catch((err: BusinessError) => {
  11723. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  11724. });
  11725. }
  11726. }
  11727. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  11728. device: avSession.OutputDeviceInfo) => {
  11729. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  11730. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11731. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  11732. await this.startCasting();
  11733. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  11734. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  11735. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  11736. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  11737. if (device) {
  11738. this.endCasting();
  11739. }
  11740. }
  11741. };
  11742. private async startCasting() {
  11743. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11744. this.setPlaybackStateChangeListener();
  11745. this.pause();
  11746. this.initQueueItem();
  11747. this.prepare();
  11748. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11749. refToIsCasting?.set(true);
  11750. this.castSeek = true;
  11751. this.isCastPlaying = true;
  11752. }
  11753. async changeCasting() {
  11754. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  11755. this.initQueueItem();
  11756. this.prepare();
  11757. this.setPlaybackStateChangeListener();
  11758. this.isCastPlaying = true;
  11759. this.castSeek = true;
  11760. }
  11761. public endCasting() {
  11762. this.avSessionController.getAvSession()?.stopCasting();
  11763. this.stopCast();
  11764. this.isCastPlaying = false;
  11765. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  11766. refToIsCasting?.set(false);
  11767. this.pause();
  11768. this.setIsPlaying(false);
  11769. // if (this.curIndex === this.curSource.index) {
  11770. // this.play
  11771. // this.seek(this.currentTime * 1000);
  11772. // this.setIsPlaying(true);
  11773. // } else {
  11774. // this.pauseVideo();
  11775. // this.setIsPlaying(false);
  11776. // }
  11777. }
  11778. public setIsPlaying(isPlayer: boolean) {
  11779. this.isPlaying = isPlayer;
  11780. // 发送播放状态变化事件给歌单详情页面
  11781. try {
  11782. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  11783. const currentFilePath = this.currentSong?.filePath || ''
  11784. const eventData: emitter.EventData = {
  11785. data: {
  11786. isPlaying: this.isPlaying,
  11787. curIndex: this.curIndex,
  11788. currentFilePath: currentFilePath
  11789. }
  11790. };
  11791. emitter.emit(eventPlaybackStatus, eventData)
  11792. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  11793. } catch (error) {
  11794. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  11795. }
  11796. }
  11797. private setPlaybackStateChangeListener(): void {
  11798. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  11799. this.castController?.on('endOfStream', this.reloadCasting);
  11800. this.castController?.on('playNext', this.playNextCallback);
  11801. this.castController?.on('playPrevious', this.playPreviousCallback);
  11802. }
  11803. private updateSessionPlayState(isPlay: boolean): void {
  11804. // if(!this.isBgPlayOpen)
  11805. // return
  11806. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  11807. this.setAVSessionPlayState({
  11808. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  11809. position: {
  11810. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  11811. updateTime: new Date().getTime()
  11812. }
  11813. });
  11814. }
  11815. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  11816. this.avSessionController.setAvSessionPlayState(playbackState)
  11817. }
  11818. private positionChange(position: number) {
  11819. this.currentTime2 = position / 1000;
  11820. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  11821. }
  11822. private playDurationChange(duration: number) {
  11823. this.duration = duration;
  11824. this.durationTime = Math.floor(this.duration / 1000);
  11825. this.durationStringTime = secondToTime((this.durationTime));
  11826. }
  11827. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  11828. const duration = playbackState?.extras?.duration;
  11829. if (typeof duration === 'number') {
  11830. this.playDurationChange(duration as number);
  11831. }
  11832. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  11833. this.positionChange(playbackState?.position?.elapsedTime);
  11834. }
  11835. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  11836. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  11837. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  11838. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  11839. this.isCastPlaying = false;
  11840. }
  11841. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  11842. this.isCastPlaying = true;
  11843. }
  11844. };
  11845. private reloadCasting = async () => {
  11846. let item = this.songList[this.curIndex];
  11847. let uri = fileUri.getUriFromPath(item.filePath);
  11848. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11849. // description.startPosition = 0;
  11850. this.castItem = {
  11851. itemId: this.curIndex,
  11852. description: {
  11853. assetId: item.filePath,
  11854. title: item.name,
  11855. artist: '',
  11856. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11857. // mediaUri: item.filePath,
  11858. fdSrc: {
  11859. fd: file.fd
  11860. },
  11861. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11862. mediaType: 'VIDEO',
  11863. mediaSize: item.videoSize,
  11864. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11865. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11866. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11867. duration: this.duration,
  11868. // albumCoverUri: 'https://www.example.jpeg',
  11869. // albumTitle: '《ExampleAlbum》',
  11870. appName: this.appName,
  11871. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11872. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11873. }
  11874. };
  11875. this.prepare();
  11876. this.isCastPlaying = true;
  11877. };
  11878. public playNextCallback = (): void => {
  11879. this.playNext().catch(() => {
  11880. Logger.error('heanup playNextCallback', `播放下一首失败`);
  11881. });
  11882. };
  11883. public playPreviousCallback = (): void => {
  11884. this.playPrevious().catch(() => {
  11885. Logger.error('heanup playNextCallback', `播放上一首失败`);
  11886. });
  11887. };
  11888. async prepare() {
  11889. await this.castController?.prepare(this.castItem);
  11890. await this.castController?.start(this.castItem);
  11891. }
  11892. public initQueueItem() {
  11893. let item = this.songList[this.curIndex];
  11894. let time = this.currentTime;
  11895. let uri = fileUri.getUriFromPath(item.filePath);
  11896. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  11897. this.castItem = {
  11898. itemId: this.curIndex,
  11899. description: {
  11900. assetId: item.filePath,
  11901. title: item.name,
  11902. artist: '',
  11903. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  11904. fdSrc: {
  11905. fd: file.fd
  11906. },
  11907. // 该字段大写,音频'AUDIO',视频'VIDEO'
  11908. mediaType: 'AUDIO',
  11909. mediaSize: item.videoSize,
  11910. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  11911. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  11912. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  11913. duration: this.duration,
  11914. // albumCoverUri: 'https://www.example.jpeg',
  11915. // albumTitle: '《ExampleAlbum》',
  11916. appName: this.appName,
  11917. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  11918. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  11919. }
  11920. };
  11921. }
  11922. async stopCast() {
  11923. try {
  11924. this.castController?.off('playbackStateChange');
  11925. this.castController?.off('endOfStream');
  11926. this.castController?.off('playNext');
  11927. this.castController?.off('playPrevious');
  11928. this.castController?.off('error');
  11929. } catch (error) {
  11930. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  11931. }
  11932. }
  11933. private sessionPlayCallback = (): void => {
  11934. console.info('onecold playOrPause 11050')
  11935. this.playOrPause()
  11936. };
  11937. private sessionPauseCallback = (): void => {
  11938. console.info('onecold playOrPause 11054')
  11939. this.pause()
  11940. };
  11941. private playOrPause() {
  11942. if (!this.debounce()) {
  11943. return;
  11944. }
  11945. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11946. this.pause();
  11947. } else {
  11948. console.info('onecold startPlayOrResumePlay 11064')
  11949. this.startPlayOrResumePlay();
  11950. this.playChange()
  11951. }
  11952. }
  11953. private sessionPlayNextCallback = (): void => {
  11954. this.playNext().catch(() => {
  11955. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  11956. });
  11957. };
  11958. private sessionPlayPreviousCallback = (): void => {
  11959. this.playPrevious().catch(() => {
  11960. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  11961. });
  11962. };
  11963. private sessionStopCallback = (): void => {
  11964. this.stop()
  11965. };
  11966. private sessionFastForwardCallback = (time?: number) => {
  11967. if (!time) {
  11968. return;
  11969. }
  11970. if (this.mIjkMediaPlayer != null) {
  11971. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11972. let seeTime = curPosition + time * 1000;
  11973. // 限制 seekValue 在合法范围内
  11974. if (seeTime < 0) {
  11975. seeTime = 0;
  11976. } else if (seeTime > this.duration) {
  11977. seeTime = this.duration;
  11978. }
  11979. Logger.info('onecold seeTime= ' + seeTime)
  11980. this.setSeekToActionProgress(seeTime)
  11981. this.seekTo(seeTime + "")
  11982. }
  11983. };
  11984. /**
  11985. * Gesture method onActionUpdate.
  11986. *
  11987. * @param event Gesture event.手势拖动设置快进和后退
  11988. */
  11989. private setSeekToActionProgress(position: number) {
  11990. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  11991. let duration = this.mIjkMediaPlayer.getDuration();
  11992. let pos = 0;
  11993. if (duration > 0) {
  11994. this.slideEnable = true;
  11995. let curPercent = position / duration;
  11996. pos = curPercent * 100;
  11997. if (pos > this.PROGRESS_MAX_VALUE) {
  11998. this.progressValue = this.PROGRESS_MAX_VALUE
  11999. } else {
  12000. this.progressValue = pos;
  12001. }
  12002. }
  12003. // LogUtils.getInstance()
  12004. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12005. this.totalTime = this.stringForTime(duration);
  12006. if (position > duration) {
  12007. position = duration;
  12008. }
  12009. this.isCurrentTime = true;
  12010. this.currentTime = this.stringForTime(position);
  12011. this.isCurrentTime = false
  12012. }
  12013. private sessionRewindCallback = (time?: number) => {
  12014. if (!time) {
  12015. return;
  12016. }
  12017. if (this.mIjkMediaPlayer != null) {
  12018. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12019. let seeTime = curPosition - time * 1000;
  12020. // 限制 seekValue 在合法范围内
  12021. if (seeTime < 0) {
  12022. seeTime = 0;
  12023. } else if (seeTime > this.duration) {
  12024. seeTime = this.duration;
  12025. }
  12026. Logger.info('onecold seeTime= ' + seeTime)
  12027. this.setSeekToActionProgress(seeTime)
  12028. this.seekTo(seeTime + "")
  12029. }
  12030. };
  12031. private sessionSeekCallback = (seekTime: number) => {
  12032. if (this.mIjkMediaPlayer != null) {
  12033. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12034. this.seekTo(seekTime + "")
  12035. }
  12036. };
  12037. private async getFileSize(filePath: string): Promise<number> {
  12038. try {
  12039. const stat = await fs.stat(filePath);
  12040. return stat.size;
  12041. } catch (err) {
  12042. console.error('Failed to get file size: ' + err.message);
  12043. return 0;
  12044. }
  12045. }
  12046. private pause() {
  12047. if (this.mIjkMediaPlayer.isPlaying()) {
  12048. this.savePlaybackPosition();
  12049. this.mIjkMediaPlayer.pause();
  12050. this.setProgress();
  12051. this.mDestroyPage = true;
  12052. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12053. this.updateSessionPlayState(false)
  12054. this.playChange()
  12055. if (this.pipController) {
  12056. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12057. PiPWindow.PiPControlStatus.PAUSE);
  12058. }
  12059. }
  12060. }
  12061. private stop() {
  12062. this.savePlaybackPosition();
  12063. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12064. this.mIjkMediaPlayer.stop();
  12065. this.mIjkMediaPlayer.release();
  12066. this.stopProgressTask();
  12067. this.updateSessionPlayState(false)
  12068. this.playChange()
  12069. this.watchStatus();
  12070. }
  12071. //保持记忆播放功能
  12072. private savePlaybackPosition() {
  12073. if (this.mIjkMediaPlayer != null) {
  12074. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12075. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12076. const duration = this.mIjkMediaPlayer.getDuration();
  12077. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12078. // 如果播放位置接近视频末尾,则保存 position 为 0
  12079. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12080. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12081. }
  12082. }
  12083. //获取记忆播放功能
  12084. private restorePlaybackPosition() {
  12085. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12086. // ToastUtil.showToast('position = ' + position)
  12087. if (this.mIjkMediaPlayer != null && position > 0) {
  12088. // ToastUtil.showToast('seekTo = ' + position)
  12089. this.seekTo(position + "");
  12090. }
  12091. }
  12092. private seekTo(value: string) {
  12093. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12094. ToastUtil.showToast('wma格式不支持拖动快进。')
  12095. return
  12096. }
  12097. this.isSeekTo = true
  12098. this.mIjkMediaPlayer.seekTo(value);
  12099. console.info('onecold startPlayOrResumePlay 11227')
  12100. // this.startPlayOrResumePlay()
  12101. // 在这里恢复计时器状态
  12102. this.setProgress()
  12103. this.isSeekTo = false
  12104. }
  12105. // 添加到下一首播放
  12106. private addToNextPlay(song: VideoItem) {
  12107. if (!this.debounce()) {
  12108. return;
  12109. }
  12110. if (this.currentSong) {
  12111. if (this.currentSong === song) {
  12112. ToastUtil.showToast('当前已经在播放这首歌了!')
  12113. return
  12114. }
  12115. }
  12116. // 如果未开始播放或队列为空
  12117. if (this.curIndex === -1 || this.songList.length === 0) {
  12118. this.songList = [song];
  12119. this.curIndex = 0;
  12120. this.doPlay(song)
  12121. return;
  12122. }
  12123. // 插入到当前索引+1的位置
  12124. const insertPos = this.curIndex + 1;
  12125. this.songList.splice(insertPos, 0, song);
  12126. this.songList = [...this.songList]; // 触发状态更新
  12127. this.sonDataSource.pushArrayData(this.songList)
  12128. ToastUtil.showToast('已添加至下一首播放')
  12129. }
  12130. //后退10s,可再设置设置默认几秒
  12131. backForward() {
  12132. if(this.mIjkMediaPlayer){
  12133. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12134. let value = pos - Number(this.fastForwardSeconds) * 1000;
  12135. this.seekTo(value+"");
  12136. }
  12137. }
  12138. //快进10s,可再设置设置默认几秒
  12139. fastForward() {
  12140. if(this.mIjkMediaPlayer){
  12141. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12142. let value = pos + Number(this.fastForwardSeconds) * 1000;
  12143. this.seekTo(value+"");
  12144. }
  12145. }
  12146. //下一个
  12147. private async playNext() {
  12148. if (!this.debounce()) {
  12149. return;
  12150. }
  12151. if (this.playType == 3) { //3:随机播放
  12152. await this.randomPlay()
  12153. return;
  12154. }
  12155. if (ArrayUtil.isNotEmpty(this.songList)) {
  12156. if (this.curIndex == this.songList.length - 1) {
  12157. this.curIndex = 0;
  12158. } else {
  12159. this.curIndex++;
  12160. }
  12161. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12162. this.stop();
  12163. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12164. this.currentSong = this.songList[this.curIndex];
  12165. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12166. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12167. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12168. this.artist = this.songList[this.curIndex].artist
  12169. this.name = this.songList[this.curIndex].name
  12170. //this.cover = this.songList[this.curIndex].pixelMapPath
  12171. this.changeImageAnimation()
  12172. }
  12173. }
  12174. changeImageAnimation() {
  12175. if(this.openSkipSongAnimate){
  12176. // 第一步:淡出动画
  12177. this.getUIContext()?.animateTo({
  12178. duration: 500,
  12179. curve: Curve.EaseOut,
  12180. }, () => {
  12181. this.opacityValueImage = 0.1;
  12182. if(this.isCoverRectangle){
  12183. this.scaleValueImage = 0.88
  12184. }
  12185. });
  12186. // 第二步:切换图片后淡入
  12187. setTimeout(() => {
  12188. this.cover = this.songList[this.curIndex].pixelMapPath
  12189. this.getUIContext()?.animateTo({
  12190. duration: 500,
  12191. curve: Curve.EaseIn,
  12192. }, () => {
  12193. this.opacityValueImage = 1;
  12194. this.scaleValueImage = 1 // 图标恢复到原始大小
  12195. this.startPlayOrResumePlay()
  12196. });
  12197. }, 500);
  12198. }else{
  12199. this.cover = this.songList[this.curIndex].pixelMapPath
  12200. this.startPlayOrResumePlay()
  12201. }
  12202. }
  12203. // 存储已播放的歌曲索引
  12204. private playedIndices: Set<number> = new Set();
  12205. //随机播放
  12206. private async randomPlay() {
  12207. // if (!this.debounce()) {
  12208. // return;
  12209. // }
  12210. if (ArrayUtil.isNotEmpty(this.songList)) {
  12211. if (this.songList.length > 3) {
  12212. // 如果所有歌曲都播放过一次,清空已播放索引集合
  12213. if (this.playedIndices.size === this.songList.length) {
  12214. this.playedIndices.clear();
  12215. }
  12216. // 随机选择一个未播放的歌曲索引
  12217. let newIndex: number;
  12218. // 添加超时机制防止无限循环
  12219. let attempt = 0;
  12220. const maxAttempts = 100; // 根据需求调整
  12221. do {
  12222. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  12223. attempt++;
  12224. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  12225. if (attempt >= maxAttempts) {
  12226. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  12227. newIndex = Math.floor(Math.random() * this.songList.length);
  12228. }
  12229. this.curIndex = newIndex;
  12230. this.playedIndices.add(newIndex);
  12231. } else {
  12232. // 当歌曲数量小于或等于3时,直接播放下一首
  12233. if (this.curIndex == this.songList.length - 1) {
  12234. this.curIndex = 0;
  12235. } else {
  12236. this.curIndex++;
  12237. }
  12238. }
  12239. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12240. this.stop();
  12241. this.currentSong = this.songList[this.curIndex];
  12242. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12243. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12244. this.name = this.songList[this.curIndex].name;
  12245. this.artist = this.songList[this.curIndex].artist
  12246. // this.cover = this.songList[this.curIndex].pixelMapPath
  12247. this.changeImageAnimation()
  12248. }
  12249. }
  12250. private async playIndex(index: number) {
  12251. if (!this.debounce()) {
  12252. return;
  12253. }
  12254. if (ArrayUtil.isNotEmpty(this.songList)) {
  12255. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12256. this.stop();
  12257. this.curIndex = index;
  12258. this.currentSong = this.songList[index];
  12259. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12260. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12261. this.name = this.currentSong.name
  12262. this.artist = this.currentSong.artist
  12263. this.changeImageAnimation()
  12264. }
  12265. }
  12266. //上一个
  12267. private async playPrevious() {
  12268. if (!this.debounce()) {
  12269. return;
  12270. }
  12271. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  12272. this.randomModePlayFromHistory()
  12273. return;
  12274. }
  12275. if (this.curIndex == 0) {
  12276. this.curIndex = this.songList.length - 1;
  12277. } else {
  12278. this.curIndex--;
  12279. }
  12280. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12281. this.stop();
  12282. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12283. this.currentSong = this.songList[this.curIndex];
  12284. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12285. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12286. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12287. this.name = this.songList[this.curIndex].name
  12288. this.artist = this.songList[this.curIndex].artist
  12289. this.changeImageAnimation()
  12290. }
  12291. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  12292. private async randomModePlayFromHistory() {
  12293. if (this.historyList.length >= 2) {
  12294. // 播放历史记录的第二首
  12295. const prevSong = this.historyList[1];
  12296. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  12297. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12298. this.stop();
  12299. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  12300. this.currentSong = prevSong;
  12301. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  12302. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12303. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12304. this.cover = prevSong.pixelMapPath
  12305. this.artist = prevSong.artist
  12306. this.name = prevSong.name;
  12307. console.info('onecold startPlayOrResumePlay 11434')
  12308. this.startPlayOrResumePlay();
  12309. } else {
  12310. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  12311. if (this.curIndex === 0) {
  12312. this.curIndex = this.songList.length - 1;
  12313. } else {
  12314. this.curIndex--;
  12315. }
  12316. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12317. this.stop();
  12318. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12319. this.currentSong = this.songList[this.curIndex];
  12320. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12321. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12322. this.videoUrl = await setVideoUrlForSong(this.currentSong);
  12323. this.artist = this.songList[this.curIndex].artist
  12324. this.name = this.songList[this.curIndex].name;
  12325. this.changeImageAnimation()
  12326. }
  12327. }
  12328. debounce() {
  12329. const delay = 600;
  12330. let cur = new Date().getTime();
  12331. if (cur - this.last > delay) {
  12332. this.last = cur;
  12333. return true;
  12334. }
  12335. return false;
  12336. }
  12337. /**
  12338. * Sets whether the screen is a constant based on the playback status.
  12339. */
  12340. watchStatus() {
  12341. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  12342. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12343. this.windowClass.setWindowKeepScreenOn(true);
  12344. } else {
  12345. this.windowClass.setWindowKeepScreenOn(false);
  12346. }
  12347. }
  12348. /**
  12349. * Volume gesture method onActionStart.
  12350. *
  12351. * @param event Gesture event.
  12352. */
  12353. private customDialogComponentIdMM: number = 0
  12354. @Builder
  12355. customDialogComponentMM() {
  12356. Column() {
  12357. Row() {
  12358. Blank()
  12359. Text('验证密码')
  12360. .fontSize(22)
  12361. .fontColor($r('app.color.pri_bg'))
  12362. .margin({ top: 18 })
  12363. Blank()
  12364. Image($r('app.media.close'))
  12365. .fillColor(Color.White)
  12366. .margin({ top: 18, right: 18 })
  12367. .width(20)
  12368. .onClick(() => {
  12369. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12370. })
  12371. }
  12372. .width('100%') // 使Row占据整个宽度
  12373. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  12374. Verify({
  12375. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  12376. });
  12377. }.height('60%')
  12378. .backgroundColor($r('app.color.index_background'))
  12379. .justifyContent(FlexAlign.SpaceBetween)
  12380. }
  12381. private handleVerifyCompleted(isSuccess: boolean) {
  12382. if (isSuccess) {
  12383. console.log('验证成功');
  12384. // 在这里处理验证成功后的逻辑
  12385. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  12386. this.currentPath = this.lockPath
  12387. this.getSortedFiles(this.currentPath)
  12388. } else {
  12389. // console.log('验证失败');
  12390. ToastUtil.showToast('验证失败')
  12391. }
  12392. }
  12393. private showVerifyDialog() {
  12394. promptAction.openCustomDialog({
  12395. transition: TransitionEffect.asymmetric(
  12396. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  12397. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12398. ,
  12399. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  12400. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  12401. ),
  12402. builder: () => {
  12403. this.customDialogComponentMM()
  12404. },
  12405. isModal: true,
  12406. autoCancel: true,
  12407. maskColor: Color.Transparent,
  12408. alignment: DialogAlignment.Bottom,
  12409. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  12410. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  12411. console.log("dialog onWillDismiss")
  12412. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  12413. dismissDialogAction.dismiss()
  12414. }
  12415. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  12416. dismissDialogAction.dismiss()
  12417. }
  12418. }
  12419. }).then((dialogId: number) => {
  12420. this.customDialogComponentIdMM = dialogId
  12421. })
  12422. }
  12423. //左滑操作 移动文件 重命名 删除等操作
  12424. @Builder
  12425. DeleteButton(item: VideoItem, index: number, filePath: string) {
  12426. Row() {
  12427. //加入收藏
  12428. Button() {
  12429. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  12430. .fillColor(Color.White)
  12431. .width(20)
  12432. }
  12433. .width(40)
  12434. .height(40)
  12435. .type(ButtonType.Circle)
  12436. .backgroundColor(this.themeColor)
  12437. .margin(5)
  12438. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12439. .onClick(() => {
  12440. if (item) {
  12441. this.doFav(item)
  12442. }
  12443. })
  12444. //加入下一首播放
  12445. Button() {
  12446. Image($r('app.media.next_to_play'))
  12447. .fillColor(Color.White)
  12448. .width(20)
  12449. }
  12450. .width(40)
  12451. .height(40)
  12452. .type(ButtonType.Circle)
  12453. .backgroundColor(this.themeColor)
  12454. .margin(5)
  12455. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12456. .onClick(() => {
  12457. this.addToNextPlay(item);
  12458. })
  12459. //复制文件
  12460. Button() {
  12461. Image($r('app.media.copy'))
  12462. .fillColor(Color.White)
  12463. .width(20)
  12464. }
  12465. .width(40)
  12466. .height(40)
  12467. .type(ButtonType.Circle)
  12468. .backgroundColor(this.themeColor)
  12469. .margin(5)
  12470. .id(filePath + 'copy')
  12471. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12472. .onClick(() => {
  12473. this.showCopyDialog(false, item, index, filePath + 'copy');
  12474. })
  12475. //移动文件
  12476. Button() {
  12477. Image($r('app.media.cut'))
  12478. .fillColor(Color.White)
  12479. .width(20)
  12480. }
  12481. .width(40)
  12482. .height(40)
  12483. .type(ButtonType.Circle)
  12484. .backgroundColor(this.themeColor)
  12485. .margin(5)
  12486. .id(filePath)
  12487. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12488. .onClick(() => {
  12489. this.showCutDialog(false, item, index, filePath);
  12490. })
  12491. Button() {
  12492. Image($r('app.media.cut_current'))
  12493. .fillColor(Color.White)
  12494. .width(20)
  12495. }
  12496. .width(40)
  12497. .height(40)
  12498. .type(ButtonType.Circle)
  12499. .backgroundColor(this.themeColor)
  12500. .margin(5)
  12501. .id(filePath + 'current')
  12502. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  12503. (this.isHasDir ? Visibility.Visible : Visibility.None))
  12504. .onClick(() => {
  12505. this.showCutDialog(true, item, index, filePath + 'current');
  12506. })
  12507. //重命名
  12508. Button() {
  12509. Image($r('app.media.rename2'))
  12510. .fillColor(Color.White)
  12511. .width(20)
  12512. }
  12513. .width(40)
  12514. .height(40)
  12515. .type(ButtonType.Circle)
  12516. .backgroundColor(this.themeColor)
  12517. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12518. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  12519. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  12520. .margin(5)
  12521. .onClick(() => {
  12522. this.showReNameDialog(item, index + '', filePath)
  12523. })
  12524. Button() {
  12525. Image($r('app.media.delete2'))
  12526. .fillColor(Color.White)
  12527. .width(20)
  12528. }
  12529. .width(40)
  12530. .height(40)
  12531. .type(ButtonType.Circle)
  12532. .backgroundColor(this.themeColor)
  12533. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  12534. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  12535. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  12536. .margin(5)
  12537. .onClick(() => {
  12538. this.selectedFiles.push(item)
  12539. this.showWarnIsDelete()
  12540. // this.showWarnIsDeleteFile(item, index + '', filePath)
  12541. })
  12542. Button() {
  12543. Image($r('app.media.share2'))
  12544. .fillColor(Color.White)
  12545. .width(20)
  12546. }
  12547. .width(40)
  12548. .height(40)
  12549. .type(ButtonType.Circle)
  12550. .backgroundColor(this.themeColor)
  12551. .margin(5)
  12552. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  12553. .onClick(() => {
  12554. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  12555. })
  12556. }
  12557. }
  12558. /**
  12559. * 穿山甲banner广告
  12560. */
  12561. // private declare bannerAd: CSJNativeExpressAd;
  12562. // @State private status: string = "未加载"
  12563. // @State private isShowAd: boolean = false
  12564. // private declare mAdSlot: AdSlot;
  12565. // private mBiddingAdm = '' //服务端bidding才需要设置
  12566. // private expressLoadAdListener: NativeExpressAdListener = {
  12567. // /**
  12568. // * 加载失败的回调
  12569. // *
  12570. // * @param code
  12571. // * @param message
  12572. // */
  12573. // onError: (code: number, message: string) => {
  12574. // console.error("加载广告失败,code=" + code + ",message=" + message);
  12575. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  12576. // },
  12577. //
  12578. // /**
  12579. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  12580. // *
  12581. // * @param ads 返回的广告列表
  12582. // */
  12583. //
  12584. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  12585. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  12586. // if (ads && ads.length > 0) {
  12587. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  12588. // ad.setExpressInteractionListener({
  12589. // /**
  12590. // *广告的点击回调
  12591. // * @param type 广告的交互类型
  12592. // */
  12593. // onAdClicked: (type: number) => {
  12594. // console.log("BannerExpressAdPage==onAdClicked......");
  12595. // },
  12596. //
  12597. // /**
  12598. // * 广告的展示回调 每个广告仅回调一次
  12599. // * @param type 广告的交互类型
  12600. // */
  12601. // onAdShow: (type: number) => {
  12602. // console.log("BannerExpressAdPage==onAdShow......");
  12603. // },
  12604. //
  12605. // /**
  12606. // * 模板渲染失败
  12607. // */
  12608. // onRenderFail: (code: number, msg: string) => {
  12609. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  12610. // },
  12611. //
  12612. // /**
  12613. // * 模板渲染成功
  12614. // * @param width 返回view的宽 单位 vp
  12615. // * @param height 返回view的高 单位 vp
  12616. // */
  12617. // onRenderSuccess: (width: number, height: number) => {
  12618. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  12619. // this.bannerAd = ad;
  12620. // this.status = "广告加载完成待展示";
  12621. //
  12622. // this.showBannerAd()
  12623. // }
  12624. // })
  12625. // //渲染广告
  12626. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  12627. // this.setDislikeCallback(ad); //设置dislike
  12628. // ad.render(this.getUIContext())
  12629. // this.status = "广告加载中...";
  12630. // });
  12631. // }
  12632. // }
  12633. // }
  12634. //
  12635. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  12636. // ad.setDislikeCallback({
  12637. // /**
  12638. // * dislike show
  12639. // */
  12640. // onShow: () => {
  12641. // console.log("BannerExpressAdPage==dislike......show");
  12642. // },
  12643. //
  12644. // /**
  12645. // * @param position 选择的位置
  12646. // * @param value 选择的内容
  12647. // * @param enforceRemove 是否强制关闭广告
  12648. // */
  12649. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  12650. // this.isShowAd = false;
  12651. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  12652. // ",enforce=" + enforceRemove);
  12653. // },
  12654. //
  12655. // /**
  12656. // * 点击取消
  12657. // */
  12658. // onCancel: () => {
  12659. // console.log("BannerExpressAdPage==dislike......onCancel");
  12660. // }
  12661. //
  12662. // })
  12663. // }
  12664. /**
  12665. * 加载Banner广告
  12666. */
  12667. loadBannerAd(rit: string) {
  12668. // if (Utility.isNoble()) {
  12669. // return
  12670. // }
  12671. // if (!Utility.isPassInstallTime(2)) {
  12672. // return
  12673. // }
  12674. // this.isShowAd = false;
  12675. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  12676. // this.mAdSlot = new AdSlotBuilder()
  12677. // .setCodeId(rit)
  12678. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  12679. // .setAdCount(1)
  12680. // .setBidAdm(this.mBiddingAdm)
  12681. // .build()
  12682. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  12683. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  12684. // this.status = "广告加载中..."
  12685. }
  12686. /**
  12687. * 展示Banner广告
  12688. */
  12689. // showBannerAd() {
  12690. // if (!this.bannerAd) {
  12691. // return
  12692. // }
  12693. // this.isShowAd = true
  12694. // this.status = "已展示"
  12695. // }
  12696. /**
  12697. * 穿山甲广告代码结束
  12698. */
  12699. /**
  12700. * 处理歌单播放请求
  12701. */
  12702. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  12703. string, songFilePaths: string[], startIndex: number) {
  12704. try {
  12705. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  12706. // 检查是否为WebDAV播放请求
  12707. if (playlistId === 'webdav-playlist') {
  12708. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  12709. // 从全局内存读取videoItems数据
  12710. const videoItems = getWebdavVideoItems();
  12711. const currentPlayIndex = getWebdavCurrentPlayIndex();
  12712. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  12713. if (videoItems && videoItems.length > 0) {
  12714. // 验证webdav_account_id设置情况
  12715. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  12716. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  12717. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  12718. return
  12719. } else {
  12720. return
  12721. }
  12722. }
  12723. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  12724. const songMap: Map<number, VideoItem> = new Map()
  12725. let completedQueries = 0
  12726. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  12727. // 遍历所有文件路径,使用索引记录位置
  12728. for (let i = 0; i < songFilePaths.length; i++) {
  12729. const filePath = songFilePaths[i]
  12730. const index = i
  12731. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  12732. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  12733. const queryPromise = this.table.queryVideoByFilePath(filePath)
  12734. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  12735. queryPromise.then((videoItem) => {
  12736. completedQueries++
  12737. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  12738. if (videoItem) {
  12739. // 使用索引作为key保存到Map中,保持原始顺序
  12740. songMap.set(index, videoItem)
  12741. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  12742. } else {
  12743. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  12744. }
  12745. // 检查是否所有歌曲都已加载完成
  12746. if (completedQueries === songFilePaths.length) {
  12747. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  12748. // 按照索引顺序重建歌曲数组
  12749. const songs: VideoItem[] = []
  12750. for (let j = 0; j < songFilePaths.length; j++) {
  12751. const song = songMap.get(j)
  12752. if (song) {
  12753. songs.push(song)
  12754. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  12755. }
  12756. }
  12757. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  12758. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12759. }
  12760. }).catch((error: Error) => {
  12761. completedQueries++
  12762. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  12763. // 即使出错也要检查是否完成所有查询
  12764. if (completedQueries === songFilePaths.length) {
  12765. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  12766. // 按照索引顺序重建歌曲数组
  12767. const songs: VideoItem[] = []
  12768. for (let j = 0; j < songFilePaths.length; j++) {
  12769. const song = songMap.get(j)
  12770. if (song) {
  12771. songs.push(song)
  12772. }
  12773. }
  12774. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  12775. }
  12776. })
  12777. }
  12778. } catch (error) {
  12779. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  12780. ToastUtil.showToast('播放失败')
  12781. }
  12782. }
  12783. /**
  12784. * 完成歌单加载并开始播放
  12785. */
  12786. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  12787. if (songs.length === 0) {
  12788. Logger.error('heanup 没有找到任何可播放的歌曲')
  12789. ToastUtil.showToast('没有找到可播放的歌曲')
  12790. return
  12791. }
  12792. this.songList = songs
  12793. this.sonDataSource.pushArrayData(songs)
  12794. this.sonDataSource.notifyDataReload()
  12795. this.curIndex = startIndex
  12796. if (songs[startIndex]) {
  12797. // 确保当前播放的歌曲也更新到存储
  12798. AppStorage.setOrCreate('currentSong', songs[startIndex])
  12799. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  12800. this.doPlay(songs[startIndex], startIndex, true)
  12801. }
  12802. PreferencesUtil.putSync('LastMusicList', this.songList)
  12803. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  12804. }
  12805. }
  12806. //视频气泡窗口的布局
  12807. @Builder
  12808. function customPopupBuilder(dataBu: BubbleBean) {
  12809. List() {
  12810. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  12811. ListItem() {
  12812. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12813. Row() {
  12814. Column() {
  12815. Image(dataBu.imageRes[index])
  12816. .height(28)
  12817. .fillColor(dataBu.color)
  12818. .alignSelf(ItemAlign.Center)
  12819. }
  12820. .width(32)
  12821. Text(item)
  12822. .padding({
  12823. top: 10,
  12824. bottom: 10,
  12825. right: 10,
  12826. left: 10
  12827. })
  12828. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  12829. .textAlign(TextAlign.Start)
  12830. .width("100%")
  12831. }
  12832. }
  12833. .backgroundColor($r('app.color.settings_background_main'))
  12834. .margin({ top: 6, bottom: 6 })
  12835. }
  12836. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12837. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  12838. TransitionEffect.scale({ x: 0, y: 0 })))
  12839. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12840. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12841. .onClick(() => {
  12842. dataBu.onItemClick?.(index)
  12843. })
  12844. })
  12845. }
  12846. .scrollBar(BarState.Off)
  12847. .width(120)
  12848. .divider({
  12849. strokeWidth: 1,
  12850. color: "#22FFFFFF"
  12851. })
  12852. }
  12853. // Function to calculate a hash for the file list
  12854. function simpleHash(fileList: string[]): string {
  12855. let hash = 0;
  12856. const str = fileList.join(',');
  12857. for (let i = 0; i < str.length; i++) {
  12858. const char = str.charCodeAt(i);
  12859. hash = (hash << 5) - hash + char;
  12860. hash |= 0; // Convert to 32bit integer
  12861. }
  12862. return hash.toString();
  12863. }
  12864. interface MoreItem {
  12865. id: number;
  12866. image: Resource;
  12867. title: string;
  12868. }
  12869. //视频气泡窗口的布局
  12870. @Builder
  12871. function cutPopupBuilder(dataBu: BubbleBean) {
  12872. Column() {
  12873. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  12874. .padding({
  12875. top: 10,
  12876. bottom: 10,
  12877. right: 10,
  12878. left: 10
  12879. })
  12880. .textAlign(TextAlign.Start)
  12881. .width(160)
  12882. .fontWeight(666)
  12883. .fontSize(16)
  12884. List() {
  12885. ForEach(dataBu.data, (item: string, index: number) => {
  12886. ListItem() {
  12887. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12888. Row() {
  12889. Column() {
  12890. Image($r('app.media.music_group'))
  12891. .height(28)
  12892. .fillColor(dataBu.color)
  12893. .alignSelf(ItemAlign.Center)
  12894. }
  12895. .width(32)
  12896. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  12897. .padding({
  12898. top: 10,
  12899. bottom: 10,
  12900. right: 10,
  12901. left: 10
  12902. })
  12903. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  12904. .fontSize(15)
  12905. }
  12906. }
  12907. .backgroundColor(Color.Transparent)
  12908. .margin({ top: 7, bottom: 7 })
  12909. }
  12910. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  12911. .animation({ duration: 500 }),
  12912. TransitionEffect.scale({ x: 0, y: 0 })))
  12913. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  12914. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  12915. .onClick(() => {
  12916. dataBu.onItemClick?.(index)
  12917. })
  12918. })
  12919. }
  12920. .scrollBar(BarState.Off)
  12921. .width(150)
  12922. .divider({
  12923. strokeWidth: 1,
  12924. color: "#22FFFFFF"
  12925. })
  12926. }
  12927. .height(300)
  12928. .padding({
  12929. bottom: 30
  12930. })
  12931. }
  12932. function getFileDirName(filePath: string,rootPath:string): string{
  12933. if(filePath===rootPath){
  12934. return '首页'
  12935. }
  12936. let result = FileUtil.getFileName(filePath)
  12937. if(StrUtil.isEmpty(result))
  12938. return ''
  12939. if(result.startsWith('.'))
  12940. result = result.replace(/\./g, '')
  12941. return result
  12942. }
  12943. //只扫描当前目录下文件(不扫描子文件夹)的方法
  12944. @Concurrent
  12945. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  12946. const table: MediaTable = new MediaTable(context);
  12947. try {
  12948. // 直接获取当前目录下的文件列表
  12949. const files = FileUtil.listFileSync(dirPath);
  12950. await Promise.all(files.map(async (file) => {
  12951. const fPath = `${dirPath}/${file}`;
  12952. // 跳过目录,只处理文件
  12953. if (FileUtil.isDirectory(fPath)) {
  12954. return;
  12955. }
  12956. // 跳过特定格式文件
  12957. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  12958. return;
  12959. }
  12960. // 检查是否为媒体文件
  12961. if (Utility.isMeidaByExtension(fPath)) {
  12962. let mType = CommonConstants.TYPE_LOCAL;
  12963. if (fPath.includes(lockPath)) {
  12964. mType = CommonConstants.TYPE_LOCK;
  12965. }
  12966. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  12967. context, fPath, mType, true
  12968. );
  12969. table.insert(mediaItem, (id: number) => {
  12970. // 插入回调函数
  12971. }, cover_api);
  12972. }
  12973. }));
  12974. } catch (error) {
  12975. console.error(' 扫描当前目录失败:', error);
  12976. }
  12977. }