LocalMusic.ets 295 KB

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