LocalMusic.ets 255 KB

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