LocalMusic.ets 426 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442
  1. import TitleBar from './TitleBar'
  2. import { curves, display, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import {
  5. AppUtil,
  6. ArrayUtil,
  7. Base64Util,
  8. DateUtil,
  9. DeviceUtil,
  10. DisplayUtil,
  11. FileUtil,
  12. ImageUtil,
  13. LogUtil,
  14. MD5,
  15. PreferencesUtil,
  16. RandomUtil,
  17. StrUtil,
  18. ToastUtil
  19. } from '@pura/harmony-utils';
  20. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  21. import { CommonConstants } from '../common/constants/CommonConstants';
  22. import Logger from '../common/util/Logger';
  23. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  24. import { Utility } from '../common/util/Utility';
  25. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  26. import commonEventManager from '@ohos.commonEventManager';
  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 { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  33. import { Verify } from './Verify';
  34. import { RotatingCover } from './RotatingCover';
  35. import { PlayConstants } from '../common/constants/PlayConstants';
  36. import { effectKit } from '@kit.ArkGraphics2D';
  37. import { ColorConversion } from '../common/util/ColorConversion';
  38. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  39. import { AvSessionController } from '../controller/AvSessionController';
  40. import { AvSessionWidgetListener } from '../common/widget/AvSessionWidgetListener';
  41. import { WidgetData, PlayProgress, PlayState, SongInfo, PlaylistState, PlayerStateBroadcastData } from '../common/widget/WidgetTypes';
  42. import { PlayerStateListener, PlayerState, PlayerError } from '../common/service/PlayerStateModel';
  43. import {
  44. WIDGET_CONTROL_EVENT,
  45. WIDGET_REQUEST_STATE_EVENT,
  46. PLAYER_STATE_CHANGED_EVENT,
  47. PLAYER_SONG_CHANGED_EVENT,
  48. PLAYER_PROGRESS_CHANGED_EVENT
  49. } from '../common/widget/WidgetEventConstants';
  50. import {
  51. IjkMediaPlayer,
  52. // DeviceChangeReason,
  53. InterruptEvent,
  54. InterruptHintType,
  55. LogUtils
  56. } from '@ohos/ijkplayer';
  57. import { PlayStatus } from '../common/PlayStatus';
  58. import fs from '@ohos.file.fs';
  59. import { image } from '@kit.ImageKit';
  60. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  61. import { UniversalDetector } from '@ohos/juniversalchardet';
  62. import { SettingPage } from '../pages/SettingPage';
  63. import { secondToTime } from '../common/util/CommUtils';
  64. import { CommonConstants2 } from '../common/util/CommonConstants2';
  65. import { hilog } from '@kit.PerformanceAnalysisKit';
  66. import { LazyDataSource } from '../common/util/LazyDataSource';
  67. import MediaTable from '../common/util/MediaTable';
  68. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  69. import ImageUtils from '../common/util/ImageUtils';
  70. import { ringtone } from '@kit.RingtoneKit';
  71. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  72. import { resourceManager } from '@kit.LocalizationKit';
  73. import { deviceInfo } from '@kit.BasicServicesKit';
  74. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  75. import app from '@system.app';
  76. import { TextNodeController } from './PipLyricTextBuilder';
  77. import { IndexerView } from './IndexerView';
  78. import { KeyCode } from '@kit.InputKit';
  79. import { KnockController } from '../controller/KnockController';
  80. import { WidgetCommand, EventData, WidgetControlParams } from '../common/widget/WidgetTypes';
  81. import { UnifiedPlayerService, IPlayerService } from '../common/service/UnifiedPlayerService';
  82. // import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  83. const TAG = 'LocalMusic';
  84. const DEFAULT_INDEX =
  85. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  86. 'X', 'Y', 'Z']
  87. //排序类型
  88. function getTypeOrder(type: number) {
  89. switch (type) {
  90. case CommonConstants.TYPE_IS_DIR:
  91. return 1; // First
  92. case CommonConstants.TYPE_IS_CSJAD:
  93. return 2; // Middle
  94. case CommonConstants.TYPE_LOCAL:
  95. return 3; // Last
  96. default:
  97. return 4; // Unknown types, if any, go last
  98. }
  99. }
  100. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  101. // 定义接口
  102. interface HiCarAspectRatio {
  103. ratio: number;
  104. name: string;
  105. }
  106. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  107. const ITEM_HEIGHT: number = 58; // 列表项中高度
  108. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  109. //功能强大的音乐播放器
  110. @Preview
  111. @Component
  112. export struct LocalMusic {
  113. @State opacityValueImage: number = 1;
  114. @State tipPopup:boolean = false
  115. @Consume mType: number;
  116. @StorageProp('themeColor') themeColor: string =
  117. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  118. themeMode: number = 0;
  119. @State titleName: string = '首页'
  120. @State textStr: string = ''
  121. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  122. // private download_path: string = '';
  123. @Consume rootPath: string //音频根目录
  124. @Consume currentPath: string
  125. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  126. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  127. @State lockPath: string = ''
  128. @State favPath: string = ''
  129. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  130. @State historyPath: string = ''
  131. @State historyList: Array<VideoItem> = []
  132. @Consume isHistory: boolean
  133. static readonly HISTORY_MUSIC: string = 'music_historyList';
  134. private table: MediaTable = new MediaTable(getContext(this))
  135. @State isZero: boolean = false
  136. @State fileList: Array<string> = []
  137. @State dirList: Array<VideoItem> = []
  138. @Consume videoLocalList: Array<VideoItem>
  139. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  140. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  141. @State artistList: Array<VideoItem> = []; //艺术家文件
  142. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  143. @State albumList: Array<VideoItem> = []; //专辑文件
  144. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  145. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  146. @State imageOpacities: number[] = [];
  147. @Consume isCanBack: boolean
  148. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  149. @State showSingleLyric: boolean = false
  150. @State sortType: number = 4 //默认排序方式
  151. @State isShowSimi: boolean = false //是否显示私密音频
  152. @State isShowFAV: boolean = true //是否显示我的收藏
  153. @State isShowTitleBar: boolean = true //是否显示分类导航条
  154. @State isShowAllBar: boolean = true //是否显示播放全部条
  155. @State isShowHistory: boolean = true //是否显示最近播放
  156. @State isCustomizeBg: boolean = false //自定义背景界面
  157. @State isGridMusic: boolean = false //是否网格布局
  158. @State isCircleBtn: boolean = false //是否圆形播放按钮
  159. @State twoFingerType: number = 3 //双支放大缩小的类型
  160. @State isScrollHide: boolean = false //是否滚动隐藏
  161. private widgetEventSubscriber: commonEventManager.CommonEventSubscriber | null = null; // 卡片事件订阅者
  162. private lastProgressBroadcastTime: number = 0; // 上次进度广播时间
  163. private readonly PROGRESS_BROADCAST_INTERVAL: number = 1000; // 进度广播间隔(1秒)
  164. private lastStateBroadcastTime: number = 0; // 上次状态广播时间
  165. private readonly STATE_BROADCAST_INTERVAL: number = 500; // 状态广播间隔(0.5秒)
  166. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  167. @State isStartAutoPlay: boolean = false //启动后自动播放
  168. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  169. @State isShowHeader: boolean = true
  170. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  171. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  172. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  173. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  174. @State isSwipe: boolean = false //listItem的左滑开关
  175. @State openSkipSongAnimate: boolean = true//切歌动画效果
  176. @State customizeBgPath: string | undefined = '';
  177. @State isDarkMode: boolean = false
  178. @State lyricTextWeight: number = 400
  179. @State lyricTextWeightPip: number = 400
  180. @State currentSwiperIndex: number = 0
  181. @State blurValue: number = 0 //背景模糊
  182. @State bgBrightness: number = 0 //背景亮度
  183. private listScroller: ListScroller = new ListScroller()
  184. private playListScroller: Scroller = new Scroller()
  185. @StorageProp('isLandscape') isLandscape: boolean = false;
  186. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  187. @StorageProp('windowWidth') windowWidth: number = 0;
  188. @StorageProp('windowHeight') windowHeight: number = 0;
  189. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  190. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  191. private UNKONWN:string = '';
  192. private listArea: Area = {
  193. width: 0,
  194. height: 0,
  195. position: {},
  196. globalPosition: {}
  197. }
  198. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  199. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  200. onColorModeChange() {
  201. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  202. if (this.isCustomizeBg) {
  203. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  204. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  205. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  206. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  207. } else {
  208. if (!this.isDarkMode) {
  209. this.titleBarModel.setTitleBarBackground(this.themeColor)
  210. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  211. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  212. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  213. } else {
  214. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  215. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  216. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  217. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  218. }
  219. }
  220. }
  221. onModeChange() {
  222. this.isFavMusic = false
  223. if (this.modeType === 2 || this.modeType === 3) {
  224. this.titleBarModel.setRightIcon(null)
  225. } else {
  226. this.titleBarModel.setRightIcon(($r('app.media.add')))
  227. }
  228. LogUtil.info('onecold onModeChange = ' + this.modeType)
  229. switch (this.modeType) {
  230. case 0:
  231. this.getSortedFiles(this.currentPath)
  232. break
  233. case 1:
  234. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  235. this.updateListData(this.mediaKuList)
  236. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  237. break
  238. case 2:
  239. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  240. this.updateListData(this.artistList)
  241. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  242. break
  243. case 3:
  244. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  245. this.updateListData(this.albumList)
  246. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  247. break
  248. }
  249. }
  250. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  251. // @StorageLink('isPlay') isPlay: boolean = false;
  252. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  253. @StorageLink('songList') songList: Array<VideoItem> = [];
  254. @State translateY: number = 0;
  255. @State isShowSheet: boolean = false;
  256. @State isShowSheetView: boolean = false;
  257. @State isShowTimeCloseView: boolean = false;
  258. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  259. @StorageLink('currIndex') curIndex: number = 0;
  260. @Consume isShowDrawer: boolean;
  261. @Consume offsetX: number;
  262. @State isFac: boolean = false;
  263. @State favList: Array<VideoItem> = []
  264. @Consume isFavMusic: boolean
  265. @State isClickedPLayAll: boolean = false;
  266. private knockController: KnockController | undefined = undefined;
  267. imagesF: ImageFrameInfo[] = [
  268. { src: $r("app.media.app_loading0") },
  269. { src: $r("app.media.app_loading1") },
  270. { src: $r("app.media.app_loading2") },
  271. { src: $r("app.media.app_loading3") },
  272. ]
  273. @State animationState: AnimationStatus = AnimationStatus.Initial
  274. // 缓存机制
  275. private cache: Map<string, Array<VideoItem>> = new Map();
  276. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  277. // 持久化缓存
  278. private async saveCacheToStorage() {
  279. const cacheArray = Array.from(this.cache.entries());
  280. const stringCacheArray = Array.from(this.stringCache.entries());
  281. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  282. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  283. }
  284. // 载入缓存
  285. private async loadCacheFromStorage() {
  286. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  287. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  288. if (cacheString) {
  289. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  290. this.cache = new Map(cacheArray);
  291. }
  292. if (stringCacheString) {
  293. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  294. this.stringCache = new Map(stringCacheArray);
  295. }
  296. }
  297. // 查找缓存
  298. private findCache(key: string): Array<VideoItem> | undefined {
  299. return this.cache.get(key);
  300. }
  301. // 查找字符串缓存
  302. private findStringCache(key: string): string | undefined {
  303. return this.stringCache.get(key);
  304. }
  305. // 添加缓存
  306. private addCache(key: string, value: Array<VideoItem>) {
  307. this.cache.set(key, value);
  308. }
  309. // 添加字符串缓存
  310. private addStringCache(key: string, value: string) {
  311. this.stringCache.set(key, value);
  312. }
  313. // 删除缓存
  314. private deleteCache(key: string) {
  315. this.cache.delete(key);
  316. this.saveCacheToStorage()
  317. }
  318. // 多选机制
  319. @State selectedFiles: Array<VideoItem> = [];
  320. @State isMultiSelect: boolean = false;
  321. @State isAllSelected: boolean = false;
  322. @State appName: string = ''
  323. @State isHasDir: boolean = false
  324. @State packName: string = ''
  325. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  326. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  327. .setTitleTextStyle(FontStyle.Normal)
  328. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  329. .setLeftIcon($r('app.media.menu'))
  330. .setLeftIconWidth(26)
  331. .setLeftIconHeight(26)
  332. .setTitleName('首页')
  333. .setTitleFontSize(18)
  334. .setTitleFontColor(Color.White)
  335. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  336. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  337. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  338. .setRightIcon($r('app.media.add'))
  339. .setOnRightClickListener(() => {
  340. this.showSheelDialog()
  341. })
  342. // .setOnTitleClickListener(() => {
  343. // this.showPupDialog()
  344. // })
  345. .setOnLeftClickListener(() => {
  346. this.doSwipBack()
  347. })
  348. doSwipBack() {
  349. if (this.modeType !== 0 && this.isCanBack) {
  350. this.onModeChange()
  351. this.isCanBack = false
  352. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  353. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  354. setTimeout(() => {
  355. if (this.modeType == 2) {
  356. if (this.isGridMusic) {
  357. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  358. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  359. } else {
  360. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  361. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  362. }
  363. } else if (this.modeType == 3) {
  364. if (this.isGridMusic) {
  365. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  366. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  367. } else {
  368. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  369. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  370. }
  371. }
  372. }, 200)
  373. return
  374. }
  375. if (this.isHistory || this.isFavMusic) {
  376. this.isHistory = false
  377. this.getSortedFiles(this.currentPath)
  378. return
  379. }
  380. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  381. animateTo({ duration: 555 }, () => {
  382. // 动画闭包内控制Image组件的出现和消失
  383. this.isShowDrawer = !this.isShowDrawer
  384. this.offsetX = 0
  385. })
  386. return
  387. }
  388. //返回上一级歌单的滚动位置
  389. setTimeout(() => {
  390. if (this.modeType == 0) {
  391. if (this.isGridMusic) {
  392. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  393. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  394. } else {
  395. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  396. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  397. }
  398. }
  399. }, 300)
  400. this.currentPath = Utility.getParentDirectory(this.currentPath)
  401. Logger.info('this.currentPath2 = ' + this.currentPath)
  402. this.getSortedFiles(this.currentPath)
  403. }
  404. // 初始化统一播放器服务
  405. private async initUnifiedPlayerService(): Promise<void> {
  406. try {
  407. await this.unifiedPlayerService.initialize(this.context);
  408. // 等待数据恢复完成后再获取播放列表
  409. LogUtils.getInstance().LOGI('LocalMusic: Waiting for UnifiedPlayerService data restoration...');
  410. await this.unifiedPlayerService.waitForDataRestoration(5000);
  411. // 从UnifiedPlayerService恢复播放列表和状态
  412. const restoredPlaylist = this.unifiedPlayerService.getPlaylist();
  413. const restoredIndex = this.unifiedPlayerService.getCurrentIndex();
  414. const restoredSong = this.unifiedPlayerService.getCurrentSong();
  415. if (ArrayUtil.isNotEmpty(restoredPlaylist)) {
  416. // 恢复播放列表到LocalMusic
  417. this.songList = restoredPlaylist;
  418. this.curIndex = restoredIndex;
  419. this.currentSong = restoredSong || undefined;
  420. // 更新UI数据源
  421. this.sonDataSource.pushArrayData(this.songList);
  422. // 如果有当前歌曲,更新UI显示
  423. if (this.currentSong) {
  424. this.videoUrl = this.currentSong.filePath;
  425. this.name = this.currentSong.name;
  426. this.artist = this.currentSong.artist;
  427. this.cover = this.currentSong.pixelMapPath;
  428. }
  429. LogUtils.getInstance().LOGI(`LocalMusic: Restored playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
  430. } else {
  431. LogUtils.getInstance().LOGI('LocalMusic: No playlist restored from UnifiedPlayerService, songList length = ' + this.songList.length);
  432. if (ArrayUtil.isNotEmpty(this.songList)) {
  433. // 如果LocalMusic有播放列表但UnifiedPlayerService没有,设置到服务中
  434. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  435. LogUtils.getInstance().LOGI(`LocalMusic: Set existing playlist to UnifiedPlayerService - ${this.songList.length} songs`);
  436. }
  437. }
  438. // 添加状态监听器,保持UI同步
  439. class LocalMusicStateListener implements PlayerStateListener {
  440. private localMusic: LocalMusic;
  441. constructor(localMusic: LocalMusic) {
  442. this.localMusic = localMusic;
  443. }
  444. onStateChanged(state: PlayerState): void {
  445. LogUtils.getInstance().LOGI(`LocalMusic: StateListener triggered - isPlaying: ${state.isPlaying}, isPaused: ${state.isPaused}`);
  446. // 直接使用状态模型的状态,这是最权威的状态源
  447. const isPlaying = state.isPlaying;
  448. const isPaused = state.isPaused;
  449. // 同步播放状态到LocalMusic的UI状态
  450. const previousStatus: PlayStatus = this.localMusic.CONTROL_PlayStatus;
  451. // 根据状态模型确定UI状态
  452. if (isPlaying) {
  453. this.localMusic.CONTROL_PlayStatus = PlayStatus.PLAY;
  454. } else if (isPaused) {
  455. this.localMusic.CONTROL_PlayStatus = PlayStatus.PAUSE;
  456. } else {
  457. this.localMusic.CONTROL_PlayStatus = PlayStatus.INIT;
  458. }
  459. // 更新播放状态相关的UI
  460. this.localMusic.setIsPlaying(isPlaying);
  461. this.localMusic.updateSessionPlayState(isPlaying);
  462. LogUtils.getInstance().LOGI(`LocalMusic: State sync - Previous: ${previousStatus}, New: ${this.localMusic.CONTROL_PlayStatus}, isPlaying: ${isPlaying}`);
  463. // 强制触发UI更新,无论状态是否变化
  464. this.localMusic.playChange();
  465. this.localMusic.watchStatus();
  466. // 更新动画状态
  467. if (isPlaying) {
  468. this.localMusic.animationState = AnimationStatus.Running;
  469. this.localMusic.mDestroyPage = false;
  470. } else {
  471. this.localMusic.animationState = AnimationStatus.Paused;
  472. this.localMusic.mDestroyPage = true;
  473. }
  474. LogUtils.getInstance().LOGI(`LocalMusic: UI update completed - CONTROL_PlayStatus: ${this.localMusic.CONTROL_PlayStatus}, globalIsPlaying: ${this.localMusic.isPlaying}`);
  475. // 同步播放模式
  476. if (this.localMusic.playType !== state.playMode) {
  477. this.localMusic.playType = state.playMode;
  478. this.localMusic.setCurrentPlayMode();
  479. }
  480. // 同步音量和速度
  481. this.localMusic.volume = state.volume;
  482. this.localMusic.playSpeed = state.speed;
  483. LogUtils.getInstance().LOGI(`LocalMusic: State synchronized - isPlaying=${state.isPlaying}, mode=${state.playMode}`);
  484. }
  485. onSongChanged(song: VideoItem): void {
  486. // 立即重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  487. this.localMusic.oldSeconds = 0;
  488. this.localMusic.currentTime = "00:00";
  489. this.localMusic.lastSongPath = song.filePath; // 更新当前歌曲路径
  490. this.localMusic.justSwitched = true; // 标记歌曲刚刚切换
  491. // 同步当前歌曲信息
  492. this.localMusic.currentSong = song;
  493. this.localMusic.videoUrl = song.filePath;
  494. this.localMusic.name = song.name;
  495. this.localMusic.artist = song.artist;
  496. this.localMusic.cover = song.pixelMapPath;
  497. // 更新当前索引
  498. const currentIndex: number = this.localMusic.unifiedPlayerService.getCurrentIndex();
  499. this.localMusic.curIndex = currentIndex;
  500. // 更新最近播放时间
  501. this.localMusic.updateLastPlayTimeStr(song.filePath);
  502. }
  503. onProgressChanged(progress: PlayProgress): void {
  504. // 同步进度更新到UI
  505. this.localMusic.syncProgressFromService(progress);
  506. // 广播进度更新到卡片
  507. this.localMusic.broadcastProgressIfNeeded();
  508. }
  509. onError(error: PlayerError): void {
  510. this.localMusic.handlePlaybackError();
  511. }
  512. }
  513. const stateListener = new LocalMusicStateListener(this);
  514. this.unifiedPlayerService.addStateListener(stateListener);
  515. // 不设置LocalMusic自己的AVSession监听器,完全依赖UnifiedPlayerService
  516. // UnifiedPlayerService已经设置了AVSession监听器,状态变化会通过StateListener传播到LocalMusic
  517. LogUtils.getInstance().LOGI('LocalMusic: Relying on UnifiedPlayerService for AVSession handling');
  518. // 初始化完成后,立即同步当前状态到UI
  519. setTimeout(() => {
  520. try {
  521. const currentState = this.unifiedPlayerService.getCurrentState();
  522. const actuallyPlaying = this.unifiedPlayerService.getActualPlayingState();
  523. LogUtils.getInstance().LOGI(`LocalMusic: Syncing current state - StateModel: ${currentState.isPlaying}, ActualPlayer: ${actuallyPlaying}`);
  524. // 手动触发状态同步,确保UI显示正确(使用实际播放器状态)
  525. stateListener.onStateChanged(currentState);
  526. } catch (error) {
  527. LogUtils.getInstance().LOGI(`LocalMusic: Failed to sync current state: ${error}`);
  528. }
  529. }, 200); // 短延迟,确保组件完全初始化
  530. LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService initialized successfully');
  531. // 初始化完成后,开始加载本地文件
  532. this.loadLocalFilesAfterServiceInit();
  533. } catch (error) {
  534. LogUtils.getInstance().LOGI(`LocalMusic: Failed to initialize UnifiedPlayerService: ${error}`);
  535. ToastUtil.showToast('播放器服务初始化失败');
  536. // 即使服务初始化失败,也要加载本地文件
  537. this.loadLocalFilesAfterServiceInit();
  538. }
  539. }
  540. private loadLocalFilesAfterServiceInit() {
  541. // 加载本地文件,然后恢复播放列表
  542. this.getSortedFiles(this.rootPath).then(async () => {
  543. this.isFavMusic = false;
  544. // 数据恢复已在initUnifiedPlayerService中完成,直接获取播放列表
  545. LogUtils.getInstance().LOGI('LocalMusic: Getting playlist from UnifiedPlayerService after file loading');
  546. // 尝试从UnifiedPlayerService恢复播放列表
  547. const unifiedPlaylist = this.unifiedPlayerService.getPlaylist();
  548. const unifiedIndex = this.unifiedPlayerService.getCurrentIndex();
  549. const unifiedSong = this.unifiedPlayerService.getCurrentSong();
  550. if (ArrayUtil.isNotEmpty(unifiedPlaylist)) {
  551. // 使用UnifiedPlayerService的数据
  552. this.songList = unifiedPlaylist;
  553. this.curIndex = unifiedIndex;
  554. this.currentSong = unifiedSong || undefined;
  555. LogUtils.getInstance().LOGI(`LocalMusic: Using playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
  556. } else {
  557. // 回退到旧的存储方式
  558. LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService playlist empty, falling back to legacy storage');
  559. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  560. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  561. if (ArrayUtil.isEmpty(this.songList)) {
  562. const currentFileList = this.getCurFileList();
  563. LogUtils.getInstance().LOGI(`LocalMusic: No legacy playlist found, current directory has ${currentFileList.length} songs`);
  564. LogUtils.getInstance().LOGI(`LocalMusic: Current path: ${this.currentPath}, Root path: ${this.rootPath}`);
  565. this.songList = currentFileList;
  566. LogUtils.getInstance().LOGI(`LocalMusic: Using current file list as fallback - ${this.songList.length} songs`);
  567. } else {
  568. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  569. LogUtils.getInstance().LOGI(`LocalMusic: Using legacy playlist storage - ${this.songList.length} songs, index ${this.curIndex}`);
  570. }
  571. }
  572. if (ArrayUtil.isNotEmpty(this.songList)) {
  573. this.isFirstStartPlay = true
  574. this.sonDataSource.pushArrayData(this.songList)
  575. if (this.currentSong === undefined) {
  576. this.isFirstStartPlay = false
  577. this.currentSong = this.songList[0]
  578. }
  579. this.videoUrl = this.currentSong.filePath
  580. this.name = this.currentSong.name
  581. this.cover = this.currentSong.pixelMapPath
  582. this.artist = this.currentSong.artist
  583. }
  584. });
  585. }
  586. // 组件生命周期
  587. aboutToAppear() {
  588. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  589. this.tipPopup = !this.tipPopup
  590. PreferencesUtil.putSync('isFirstTiped',false)
  591. }
  592. this.initSetting()
  593. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  594. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  595. Utility.getAppName(getContext(this)).then((appName: string) => {
  596. this.appName = appName
  597. })
  598. this.packName = AppUtil.getBundleName()
  599. this.loadCacheFromStorage(); // 加载缓存
  600. // 初始化统一播放器服务,然后加载文件
  601. this.initUnifiedPlayerService().then(() => {
  602. this.mkDownLoadDir();
  603. });
  604. // 注意:getSortedFiles的调用已经移到initUnifiedPlayerService完成后
  605. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  606. // 监听广播事件(打开其他应用处理)
  607. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  608. this.saveVideoDatas([eventData.data?.message], true)
  609. });
  610. this.setAvSessionListener();
  611. //侧滑广播接收时间
  612. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  613. // 监听广播事件(打开其他应用处理)
  614. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  615. animateTo({ duration: 555 }, () => {
  616. this.doSwipBack()
  617. })
  618. });
  619. //ScanFilePage广播接收时间
  620. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  621. // 监听ScanFilePage广播事件(更新数据库)
  622. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  623. this.doUpdateData()
  624. });
  625. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  626. // 监听广播事件(通用设置配置更新)
  627. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  628. this.doChangeSetting()
  629. });
  630. // 监听卡片控制事件(来自EntryAbility的转发)
  631. let eventWidgetControl: emitter.InnerEvent = { eventId: 9001 }
  632. emitter.on(eventWidgetControl, (eventData: emitter.EventData) => {
  633. LogUtils.getInstance().LOGI(`🎵 LocalMusic received widget control via emitter: ${JSON.stringify(eventData.data)}`);
  634. if (eventData.data && (eventData.data as Record<string, Object>)['command']) {
  635. // 将data转换为EventData类型
  636. const widgetEventData = eventData.data as Record<string, Object>;
  637. const typedEventData: EventData = {
  638. command: widgetEventData['command'] as WidgetCommand,
  639. params: (widgetEventData['params'] as WidgetControlParams) || {},
  640. timestamp: (widgetEventData['timestamp'] as number) || Date.now(),
  641. source: (widgetEventData['source'] as string) || 'unknown'
  642. };
  643. }
  644. });
  645. let event: Callback<InterruptEvent> = (event) => {
  646. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  647. this.savePlaybackPosition()
  648. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  649. this.pause();
  650. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  651. this.startPlayOrResumePlay();
  652. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  653. // 对于STOP事件,使用pause而不是stop,保持播放状态以便恢复
  654. LogUtils.getInstance().LOGI('onecold 音频冲突STOP事件,使用pause保持播放状态');
  655. this.pause();
  656. }
  657. }
  658. // 直接在LocalMusic中处理音频中断,响应更快
  659. this.unifiedPlayerService.getIjkPlayer()?.on('audioInterrupt', event);
  660. // 音频设备断连回调处理
  661. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  662. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  663. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  664. // this.pause();
  665. // }
  666. // }
  667. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  668. this.makeWorker()
  669. //折叠屏的屏幕显示模式变化
  670. display.on('foldDisplayModeChange', (data) => {
  671. this.doChangeBarHeight()
  672. });
  673. display.on('foldStatusChange', (data) => {
  674. Logger.info('onecold foldStatusChange ')
  675. });
  676. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  677. // 读取 themeMode 并同步 currentColorMode
  678. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  679. this.applyThemeMode(this.themeMode)
  680. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  681. AppStorage.setOrCreate('themeColor', themeColor);
  682. this.themeColor = themeColor;
  683. this.doChangeSetting()
  684. // 安全地注册窗口大小变化监听器
  685. if (this.windowClass) {
  686. this.windowClass.on('windowSizeChange', (size) => {
  687. LogUtil.info('onecold windowSizeChange')
  688. this.doChangeBarHeight()
  689. let viewWidth = px2vp(size.width);
  690. let viewHeight = px2vp(size.height);
  691. if(this.isPhoneLan()){
  692. this.is_auto_hide_progress = false
  693. if(this.isHiCar()){
  694. return
  695. }
  696. setTimeout(() => {
  697. this.is_auto_hide_progress = true
  698. }, 6000)
  699. }else{
  700. this.startAutoHide()
  701. }
  702. });
  703. }
  704. this.eventHub.on('onStateChange', (fg: boolean) => {
  705. if (fg && this.curState === 'STARTED') {
  706. this.stopPip();
  707. }
  708. });
  709. }
  710. startAutoHide() {
  711. if(this.isHiCar()){
  712. return
  713. }
  714. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  715. console.info('onecold startAutoHide')
  716. this.is_auto_hide_progress = false
  717. setTimeout(() => {
  718. this.is_auto_hide_progress = true
  719. }, 6000)
  720. }
  721. }
  722. applyThemeMode(mode: number) {
  723. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  724. if (mode === 1) {
  725. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  726. } else if (mode === 2) {
  727. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  728. }
  729. AppStorage.setOrCreate('currentColorMode', colorMode)
  730. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  731. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  732. AppStorage.setOrCreate('themeMode', mode)
  733. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  734. // 只有强制浅色/深色时才主动设置
  735. const context = getContext(this) as common.UIAbilityContext
  736. context.getApplicationContext().setColorMode(colorMode)
  737. }
  738. initSetting() {
  739. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  740. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  741. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  742. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  743. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  744. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  745. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  746. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  747. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  748. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  749. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  750. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  751. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  752. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  753. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  754. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  755. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  756. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  757. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  758. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  759. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  760. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  761. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  762. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  763. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  764. //如果是hicar连接状态,这些都是false
  765. if(this.isHiCar()){
  766. this.isShowTitleBar = false//不显示导航栏
  767. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  768. {
  769. this.isShowHeader = false//二级菜单不显示头部
  770. this.isGridMusic= false//用list不用网格
  771. this.isCoverTopBig = false
  772. }
  773. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  774. }
  775. if (this.isSavePlayMode) {
  776. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  777. }
  778. if (this.isCustomizeBg) {
  779. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  780. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  781. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  782. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  783. } else {
  784. if (!this.isDarkMode) {
  785. this.titleBarModel.setTitleBarBackground(this.themeColor)
  786. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  787. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  788. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  789. } else {
  790. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  791. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  792. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  793. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  794. }
  795. }
  796. }
  797. doChangeSetting() {
  798. this.initSetting()
  799. this.deleteCache(this.currentPath)
  800. if (this.modeType === 0) {
  801. this.getSortedFiles(this.currentPath)
  802. }
  803. }
  804. doChangeBarHeight() {
  805. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  806. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  807. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  808. this.setBarHeightNormal()
  809. }
  810. }
  811. onPageShow() {
  812. this.knockController?.immersiveListening();
  813. app.setImageCacheCount(100);
  814. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  815. app.setImageRawDataCacheSize(104857600);
  816. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  817. // 修复音频中断后的状态同步问题
  818. this.syncPlaybackStateOnShow();
  819. }
  820. /**
  821. * 页面显示时同步播放状态,修复音频中断后的状态不一致问题
  822. */
  823. private syncPlaybackStateOnShow(): void {
  824. try {
  825. const currentState = this.unifiedPlayerService.getCurrentState();
  826. const actualPlaying = this.unifiedPlayerService.getActualPlayingState();
  827. LogUtils.getInstance().LOGI(`onPageShow state sync - StateModel: isPlaying=${currentState.isPlaying}, isPaused=${currentState.isPaused}, Actual: ${actualPlaying}`);
  828. // 如果状态不一致,强制同步
  829. if (currentState.isPlaying !== actualPlaying) {
  830. LogUtils.getInstance().LOGI(`State inconsistency detected, forcing sync`);
  831. this.setIsPlaying(actualPlaying);
  832. this.CONTROL_PlayStatus = actualPlaying ? PlayStatus.PLAY : PlayStatus.INIT;
  833. this.playChange();
  834. this.watchStatus();
  835. }
  836. } catch (error) {
  837. LogUtils.getInstance().LOGI(`syncPlaybackStateOnShow error: ${error}`);
  838. }
  839. }
  840. //开启线程查看各个数据库
  841. makeWorker() {
  842. setTimeout(() => {
  843. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  844. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  845. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  846. // workerInstance.postMessage({
  847. // code: 1,
  848. // data1: this.context,
  849. // data2: this.rootPath,
  850. // data3: this.lockPath,
  851. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  852. // });
  853. PreferencesUtil.putSync('isFirstApp', false)
  854. } else {
  855. workerInstance.postMessage({ code: 2, data: this.context });
  856. workerInstance.postMessage({ code: 3, data: this.context });
  857. workerInstance.postMessage({ code: 4, data: this.context });
  858. this.getHistoryList(false)
  859. }
  860. }, 1000)
  861. workerInstance.onmessage = (e: MessageEvents): void => {
  862. switch (e.data.code) {
  863. case 101: //第一次扫描文件夹入库
  864. ToastUtil.showToast('刷新同步数据库成功!')
  865. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  866. this.doUpdateData()
  867. break;
  868. case 102: //查询媒体库列表
  869. this.mediaKuList = e.data.data
  870. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  871. Utility.doSortListAscending(this.mediaKuList)
  872. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  873. if (this.modeType === 1) {
  874. this.updateListData(this.mediaKuList)
  875. }
  876. break;
  877. case 103: //收到查询艺术家列表
  878. this.artistMap = e.data.data1;
  879. this.artistList = e.data.data2;
  880. break;
  881. case 104: //收到查询专辑列表
  882. this.albumMap = e.data.data1;
  883. this.albumList = e.data.data2
  884. //查询完毕在启动是否自动播放
  885. if (this.isStartAutoPlay) {
  886. this.startPlayOrResumePlay()
  887. }
  888. break;
  889. }
  890. };
  891. // 在调用terminate后,执行onexit
  892. workerInstance.onexit = (code) => {
  893. console.log("main thread terminate");
  894. }
  895. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  896. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  897. workerInstance.onerror = (err: ErrorEvent) => {
  898. console.log("onerror" + err.message);
  899. }
  900. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  901. //碰一碰分享的监听
  902. this.knockController = KnockController.getInstance(this.context);
  903. this.knockController?.immersiveListening();
  904. }
  905. onPageHide(): void {
  906. this.knockController?.immersiveDisableListening();
  907. }
  908. @State isFirstStartPlay: boolean = false
  909. //获取download_path
  910. async mkDownLoadDir() {
  911. const documentViewPicker = new picker.DocumentViewPicker()
  912. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  913. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  914. // this.rootPath = this.download_path
  915. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  916. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  917. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  918. Logger.info('onecold rootPath = ' + this.rootPath)
  919. Logger.info('onecold lockPath = ' + this.lockPath)
  920. if (!FileUtil.accessSync(this.lockPath)) {
  921. FileUtil.mkdirSync(this.lockPath)
  922. }
  923. if (!FileUtil.accessSync(this.favPath)) {
  924. FileUtil.mkdirSync(this.favPath)
  925. }
  926. if (!FileUtil.accessSync(this.historyPath)) {
  927. FileUtil.mkdirSync(this.historyPath)
  928. }
  929. this.getSortedFiles(this.rootPath).then(() => {
  930. this.isFavMusic = false
  931. //穿山甲
  932. // this.loadBannerAd(CSJUtil.getBannerID())
  933. LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - Files loaded, skipping playlist restoration (already done in initUnifiedPlayerService)');
  934. // 播放列表恢复逻辑已经在 initUnifiedPlayerService 中完成,这里不需要重复
  935. // 只需要确保UI状态是最新的
  936. if (ArrayUtil.isNotEmpty(this.songList)) {
  937. this.isFirstStartPlay = true
  938. this.sonDataSource.pushArrayData(this.songList)
  939. // 不要强制设置为第一首歌曲,保持从UnifiedPlayerService恢复的状态
  940. // 只有在完全没有当前歌曲且没有有效索引时才设置默认值
  941. if (this.currentSong === undefined && this.curIndex < 0 && this.songList.length > 0) {
  942. this.isFirstStartPlay = false
  943. this.curIndex = 0
  944. this.currentSong = this.songList[0]
  945. LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - No current song found, setting to first song as fallback');
  946. } else if (this.currentSong === undefined && this.curIndex >= 0 && this.curIndex < this.songList.length) {
  947. // 如果有有效索引但没有当前歌曲,从索引恢复
  948. this.currentSong = this.songList[this.curIndex]
  949. LogUtils.getInstance().LOGI(`LocalMusic: mkDownLoadDir - Restored current song from index ${this.curIndex}: ${this.currentSong.name}`);
  950. }
  951. if (this.currentSong) {
  952. this.videoUrl = this.currentSong.filePath
  953. this.name = this.currentSong.name
  954. this.cover = this.currentSong.pixelMapPath
  955. AppStorage.setOrCreate('currentSong',this.currentSong);
  956. }
  957. LogUtils.getInstance().LOGI(`LocalMusic: mkDownLoadDir - UI updated with existing playlist: ${this.songList.length} songs, current index: ${this.curIndex}, current song: ${this.currentSong?.name || 'none'}`);
  958. } else {
  959. this.name = '空空如也'
  960. LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - No playlist available, showing empty state');
  961. }
  962. })
  963. this.getFavList(false)
  964. }
  965. getFavList(isFavRefresh: boolean) {
  966. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  967. this.favList = result
  968. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  969. this.videoLocalList = this.favList
  970. this.updateListData(this.videoLocalList)
  971. }
  972. })
  973. }
  974. getHistoryList(isRefresh: boolean) {
  975. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  976. this.historyList = result
  977. // for (let i = 0; i < this.historyList.length; i++) {
  978. //
  979. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  980. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  981. // }
  982. if (isRefresh) {
  983. this.videoLocalList = this.historyList
  984. this.updateListData(this.videoLocalList, true)
  985. }
  986. })
  987. }
  988. // 组件消失生命周期
  989. aboutToDisappear() {
  990. console.info('LifeCycleComponent aboutToDisappear');
  991. this.knockController?.immersiveDisableListening();
  992. // 移除 this.curIndex = 0,避免重置当前播放索引
  993. // 保持当前播放状态,让UnifiedPlayerService管理播放状态的持久化
  994. emitter.off(2);
  995. emitter.off(101);
  996. emitter.off(888);
  997. emitter.off(333);
  998. this.mDestroyPage = true;
  999. // UnifiedPlayerService会自动管理屏幕常亮状态
  1000. // this.mIjkMediaPlayer.setScreenOnWhilePlaying(false); // 已移除,使用UnifiedPlayerService
  1001. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1002. this.stop();
  1003. }
  1004. // 移除音频中断监听器
  1005. this.unifiedPlayerService.getIjkPlayer()?.off('audioInterrupt');
  1006. if (workerInstance) {
  1007. workerInstance.terminate();
  1008. }
  1009. this.stopPip();
  1010. this.destroyPipController();
  1011. this.syncPlaybackStateOnShow();
  1012. // 清理卡片事件监听器
  1013. if (this.widgetEventSubscriber) {
  1014. try {
  1015. commonEventManager.unsubscribe(this.widgetEventSubscriber, (err: BusinessError | undefined) => {
  1016. if (err) {
  1017. LogUtils.getInstance().error(`Failed to unsubscribe widget events: ${JSON.stringify(err)}`);
  1018. } else {
  1019. LogUtils.getInstance().LOGI('Widget event listener unsubscribed successfully');
  1020. }
  1021. });
  1022. } catch (error) {
  1023. LogUtils.getInstance().error(`Error during widget event cleanup: ${error}`);
  1024. }
  1025. }
  1026. this.avSessionController.unregisterSessionListener();
  1027. }
  1028. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  1029. this.isFavMusic = false
  1030. if (isWorkerPost) {
  1031. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  1032. }
  1033. if (this.modeType !== 0) {
  1034. return
  1035. }
  1036. this.isCanBack = false
  1037. this.currentPath = curPath
  1038. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  1039. if (curPath === this.rootPath) {
  1040. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1041. } else {
  1042. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1043. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1044. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  1045. }
  1046. }
  1047. // Get the current file list and calculate its hash
  1048. this.fileList = FileUtil.listFileSync(curPath);
  1049. const currentHash = simpleHash(this.fileList);
  1050. // Check cache
  1051. const cachedValue = this.findCache(curPath);
  1052. Logger.info('onecold cachedValue = ' + cachedValue)
  1053. const cachedHash = this.findStringCache(curPath + '_hash');
  1054. const cachedDirList = this.findCache(curPath + "_dirList");
  1055. if (cachedValue !== undefined) {
  1056. // this.videoLocalList = cachedValue;
  1057. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1058. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1059. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1060. }
  1061. this.updateListData(cachedValue)
  1062. }
  1063. if (cachedDirList !== undefined) {
  1064. this.dirList = cachedDirList
  1065. }
  1066. //通过当前hash值和缓存hash判断list有没有变化
  1067. if (cachedValue && cachedHash === currentHash) {
  1068. return;
  1069. }
  1070. this.fileList = FileUtil.listFileSync(curPath)
  1071. let directories: Array<VideoItem> = [];
  1072. let files: Array<VideoItem> = [];
  1073. for (let i = 0; i < this.fileList.length; i++) {
  1074. console.info(`The name of file: ${this.fileList[i]}`);
  1075. let path = curPath + '/' + this.fileList[i]
  1076. if (FileUtil.isDirectory(path)) {
  1077. let item: VideoItem =
  1078. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1079. '')
  1080. if (this.isShowDir(item.name)) {
  1081. directories.push(item);
  1082. }
  1083. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1084. // Utility.doSortListAscending(directories)
  1085. } else {
  1086. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1087. let item: VideoItem =
  1088. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1089. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1090. files.push(item);
  1091. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1092. // this.doSortListAscending(files)
  1093. }
  1094. }
  1095. }
  1096. }
  1097. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1098. if (this.currentPath !== this.lockPath) {
  1099. files = result;
  1100. }
  1101. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1102. Utility.doSortListAscending(files)
  1103. if (this.currentPath === this.rootPath) {
  1104. this.dirList = directories
  1105. this.addCache(curPath + "_dirList", this.dirList);
  1106. }
  1107. //插入广告先注释掉
  1108. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1109. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1110. // directories.push(adItem)
  1111. // }
  1112. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1113. this.videoLocalList = directories.concat(files);
  1114. this.updateListData(this.videoLocalList)
  1115. if (ArrayUtil.isNotEmpty(files)) {
  1116. if (this.currentPath != this.rootPath) {
  1117. if (files) {
  1118. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1119. }
  1120. }
  1121. // 缓存结果
  1122. this.addCache(curPath, this.videoLocalList);
  1123. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1124. this.addStringCache(curPath + '_hash', currentHash);
  1125. }
  1126. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1127. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1128. //
  1129. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1130. //
  1131. // }
  1132. // this.setButtonStatus()
  1133. if (isOpen) {
  1134. if (destPath === undefined) {
  1135. // 处理 destPath 为 undefined 的情况
  1136. return
  1137. }
  1138. if (destPath.endsWith('.lrc')) {
  1139. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1140. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1141. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1142. this.initLyric(lyricPath);
  1143. }
  1144. return
  1145. }
  1146. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  1147. this.doPlay(item2)
  1148. this.isShowPlay = true
  1149. }
  1150. });
  1151. }
  1152. //扫描文件夹入库
  1153. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1154. const files = FileUtil.listFileSync(curPath);
  1155. let mediaItems: VideoItem[] = [];
  1156. Logger.info('onecold scanDirectory start ')
  1157. for (const file of files) {
  1158. const fPath = `${curPath}/${file}`;
  1159. if (fPath === this.lockPath) {
  1160. Logger.info(`Skipping locked path: ${fPath}`);
  1161. continue;
  1162. }
  1163. if (FileUtil.isDirectory(fPath)) {
  1164. // Recursively scan subdirectories
  1165. const subDirItems = await this.scanDirectory(fPath);
  1166. mediaItems = mediaItems.concat(subDirItems);
  1167. } else {
  1168. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1169. // Process media files
  1170. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1171. let mediaItem: VideoItem =
  1172. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  1173. mediaItems.push(mediaItem);
  1174. this.table.insert(mediaItem, (id: number) => {
  1175. });
  1176. }
  1177. }
  1178. }
  1179. return mediaItems;
  1180. }
  1181. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1182. animateTo({ duration: 888 }, () => {
  1183. this.opacityItem = 0;
  1184. });
  1185. setTimeout(() => {
  1186. this.videoLocalList = mList;
  1187. if (!noSort) {
  1188. if (this.modeType === 0 || this.modeType === 1) {
  1189. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1190. this.doSortType(this.sortType)
  1191. }
  1192. }
  1193. this.dataSource.pushArrayData(this.videoLocalList)
  1194. // 如果当前有播放列表,检查是否需要更新播放列表到统一播放器服务
  1195. if (ArrayUtil.isNotEmpty(this.songList)) {
  1196. const globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  1197. // 只有在没有现有播放列表时,才使用当前目录的文件列表
  1198. // 避免在文件列表更新时破坏用户的播放列表
  1199. if (ArrayUtil.isEmpty(this.songList) && ArrayUtil.isNotEmpty(globalVideoList)) {
  1200. this.songList = globalVideoList;
  1201. this.sonDataSource.pushArrayData(this.songList);
  1202. // 同步到统一播放器服务进行持久化
  1203. this.syncPlaylistToService();
  1204. }
  1205. }
  1206. animateTo({ duration: 888 }, () => {
  1207. this.opacityItem = 1;
  1208. });
  1209. this.setButtonStatus()
  1210. }, 200);
  1211. }
  1212. //排序模式和多选模式
  1213. showPupDialog() {
  1214. if (this.modeType === 2 || this.modeType === 3) {
  1215. this.titleBarModel.setRightIcon(null)
  1216. } else {
  1217. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1218. }
  1219. let dataBean = new BubbleBean()
  1220. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1221. dataBean.color = this.themeColor
  1222. dataBean.modeType = this.modeType
  1223. dataBean.imageRes =
  1224. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1225. $r('app.media.refresh')]
  1226. let pup: XPopup;
  1227. if (this.isDarkMode) {
  1228. pup = XPopup.Builder()
  1229. .setPopupPosition(PopupPosition.BOTTOM)
  1230. .atView('pup_positon_music')
  1231. .setBackgroundColor(Color.Black)
  1232. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1233. .show()
  1234. } else {
  1235. pup = XPopup.Builder()
  1236. .setPopupPosition(PopupPosition.BOTTOM)
  1237. .atView('pup_positon_music')
  1238. .setBackgroundColor(Color.White)
  1239. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1240. .show()
  1241. }
  1242. dataBean.onItemClick = (i) => {
  1243. XPopup.dismissTop()
  1244. switch (i) {
  1245. case 0: //首页
  1246. this.modeType = 0
  1247. this.getSortedFiles(this.currentPath)
  1248. break
  1249. case 1:
  1250. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1251. this.modeType = 1
  1252. this.updateListData(this.mediaKuList)
  1253. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1254. break
  1255. case 2:
  1256. this.modeType = 2
  1257. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1258. this.updateListData(this.artistList)
  1259. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1260. break
  1261. case 3:
  1262. this.modeType = 3
  1263. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1264. this.updateListData(this.albumList)
  1265. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1266. break
  1267. case 4: //同步数据
  1268. this.asyncCurrentPathData()
  1269. break
  1270. }
  1271. }
  1272. }
  1273. getCurFileList(): Array<VideoItem> {
  1274. let files: Array<VideoItem> = [];
  1275. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1276. for (let i = 0; i < this.videoLocalList.length; i++) {
  1277. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1278. files.push(this.videoLocalList[i]);
  1279. }
  1280. }
  1281. }
  1282. return files
  1283. }
  1284. /**
  1285. * 刷新播放列表中歌曲的封面信息(从当前文件列表同步最新封面)
  1286. */
  1287. async refreshPlaylistCovers(): Promise<void> {
  1288. if (ArrayUtil.isEmpty(this.songList)) {
  1289. return;
  1290. }
  1291. try {
  1292. // 获取当前目录的最新文件列表(包含最新的封面信息)
  1293. const currentFileList = this.getCurFileList();
  1294. // 如果当前文件列表为空,直接返回
  1295. if (ArrayUtil.isEmpty(currentFileList)) {
  1296. return;
  1297. }
  1298. // 为播放列表中的每首歌曲更新封面信息
  1299. let hasUpdates = false;
  1300. this.songList.forEach((song, index) => {
  1301. // 在当前文件列表中查找对应的歌曲
  1302. const matchedSong = currentFileList.find(file => file.filePath === song.filePath);
  1303. if (matchedSong && StrUtil.isNotEmpty(matchedSong.pixelMapPath) &&
  1304. matchedSong.pixelMapPath !== song.pixelMapPath) {
  1305. // 更新播放列表中的封面信息
  1306. this.songList[index].pixelMapPath = matchedSong.pixelMapPath;
  1307. hasUpdates = true;
  1308. LogUtils.getInstance().LOGI(`LocalMusic: Updated cover for ${song.name}: ${matchedSong.pixelMapPath}`);
  1309. }
  1310. });
  1311. // 如果有更新,刷新UI数据源
  1312. if (hasUpdates) {
  1313. this.sonDataSource.pushArrayData(this.songList);
  1314. LogUtils.getInstance().LOGI(`LocalMusic: Refreshed covers for playlist with ${this.songList.length} songs`);
  1315. }
  1316. } catch (error) {
  1317. LogUtils.getInstance().LOGI(`LocalMusic: Error refreshing playlist covers: ${error.message}`);
  1318. }
  1319. }
  1320. setButtonStatus() {
  1321. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1322. this.isZero = false
  1323. } else {
  1324. this.isZero = true
  1325. }
  1326. if (this.currentPath !== this.rootPath &&
  1327. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1328. this.isHasDir = true //不为空,说明有子文件夹
  1329. } else {
  1330. this.isHasDir = false
  1331. }
  1332. }
  1333. showRankDialog() {
  1334. if (this.modeType === 2 || this.modeType === 3) {
  1335. //动作面板
  1336. DialogHelper.showBottomSheetDialog({
  1337. title: "请选择排序模式",
  1338. maskColor: Color.Transparent,
  1339. // sheets: ["按名称升序", "按名称降序"],
  1340. sheets: [
  1341. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1342. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1343. ],
  1344. backgroundColor: $r('app.color.bg_card'),
  1345. height: '30%',
  1346. transition: AnimationHelper.transitionInDown(555),
  1347. onAction: (index) => {
  1348. switch (index) {
  1349. case 0:
  1350. Utility.doSortListAscending(this.videoLocalList)
  1351. break;
  1352. case 1:
  1353. Utility.doSortListDescending(this.videoLocalList)
  1354. break;
  1355. }
  1356. this.updateListData(this.videoLocalList)
  1357. }
  1358. })
  1359. return
  1360. }
  1361. //动作面板
  1362. DialogHelper.showBottomSheetDialog({
  1363. title: "请选择排序模式",
  1364. maskColor: Color.Transparent,
  1365. height: '75%',
  1366. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1367. sheets: [
  1368. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1369. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1370. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1371. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1372. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1373. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1374. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1375. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1376. ],
  1377. backgroundColor: $r('app.color.bg_card'),
  1378. transition: AnimationHelper.transitionInDown(555),
  1379. onAction: (index) => {
  1380. this.doSortType(index)
  1381. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1382. this.updateListData(this.videoLocalList, true)
  1383. }
  1384. })
  1385. }
  1386. doSortType(index: number) {
  1387. switch (index) {
  1388. case 0:
  1389. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1390. // 类型排序优先级
  1391. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1392. if (typeOrder !== 0) {
  1393. return typeOrder;
  1394. }
  1395. // 处理艺术家可能为undefined的字符串比较
  1396. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1397. const artistB = b.artist?.trim() || '';
  1398. return artistA.localeCompare(artistB);
  1399. });
  1400. break;
  1401. case 1:
  1402. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1403. // 类型排序优先级
  1404. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1405. if (typeOrder !== 0) {
  1406. return typeOrder;
  1407. }
  1408. // 处理艺术家可能为undefined的字符串比较
  1409. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1410. const artistB = b.artist?.trim() || '';
  1411. return artistB.localeCompare(artistA);
  1412. });
  1413. break;
  1414. case 2:
  1415. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1416. // 类型排序优先级
  1417. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1418. if (typeOrder !== 0) {
  1419. return typeOrder;
  1420. }
  1421. // 处理专辑可能为undefined的字符串比较
  1422. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1423. const albumB = b.album?.trim() || '';
  1424. return albumA.localeCompare(albumB);
  1425. });
  1426. break;
  1427. case 3:
  1428. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1429. // 类型排序优先级
  1430. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1431. if (typeOrder !== 0) {
  1432. return typeOrder;
  1433. }
  1434. // 处理专辑可能为undefined的字符串比较
  1435. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1436. const albumB = b.album?.trim() || '';
  1437. return albumB.localeCompare(albumA);
  1438. });
  1439. break;
  1440. case 4:
  1441. Utility.doSortListAscending(this.videoLocalList)
  1442. break;
  1443. case 5:
  1444. Utility.doSortListDescending(this.videoLocalList)
  1445. break;
  1446. case 6:
  1447. this.videoLocalList.sort((a, b) => {
  1448. // First, sort by type
  1449. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1450. if (typeOrder !== 0) {
  1451. return typeOrder;
  1452. }
  1453. // If types are the same, sort by cTime in ascending order
  1454. return a.cTime.localeCompare(b.cTime);
  1455. });
  1456. break;
  1457. case 7:
  1458. this.videoLocalList.sort((a, b) => {
  1459. // First, sort by type
  1460. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1461. if (typeOrder !== 0) {
  1462. return typeOrder;
  1463. }
  1464. // If types are the same, sort by cTime in descending order
  1465. return b.cTime.localeCompare(a.cTime);
  1466. });
  1467. break;
  1468. }
  1469. }
  1470. showSheelDialog() {
  1471. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1472. // this.showTips()
  1473. // return
  1474. // }
  1475. this.showAddDialog()
  1476. }
  1477. showAddDialog() {
  1478. if (this.modeType === 2 || this.modeType === 3) {
  1479. return
  1480. }
  1481. DialogHelper.showActionSheetDialog({
  1482. title: "请选择添加方式(建议歌词文件一起导入)",
  1483. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1484. sheets: [
  1485. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1486. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1487. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1488. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1489. ],
  1490. maskColor: Color.Transparent,
  1491. backgroundColor: $r('app.color.bg_card'),
  1492. transition: AnimationHelper.transitionInDown(555),
  1493. onAction: (index) => {
  1494. switch (index) {
  1495. case 0:
  1496. if (this.modeType === 0) {
  1497. this.showMkDialog()
  1498. } else {
  1499. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1500. }
  1501. break;
  1502. case 1:
  1503. this.callFilePickerSelectFile()
  1504. break;
  1505. case 2:
  1506. this.showTips()
  1507. break;
  1508. case 3:
  1509. this.goSelectMusic()
  1510. break;
  1511. }
  1512. }
  1513. })
  1514. }
  1515. //拉起音频
  1516. goSelectMusic() {
  1517. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1518. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1519. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1520. ) {
  1521. ToastUtil.showToast('暂时不支持该设备')
  1522. return
  1523. }
  1524. try {
  1525. let documentSelectOptions = new picker.DocumentSelectOptions();
  1526. documentSelectOptions.authMode = true
  1527. documentSelectOptions.multiAuthMode = true
  1528. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1529. let documentPicker = new picker.DocumentViewPicker(this.context);
  1530. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1531. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1532. this.saveVideoDatas(documentSelectResult)
  1533. }
  1534. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1535. JSON.stringify(documentSelectResult));
  1536. }).catch((err: BusinessError) => {
  1537. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1538. });
  1539. } catch (error) {
  1540. let err: BusinessError = error as BusinessError;
  1541. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1542. }
  1543. }
  1544. async showTips() {
  1545. DialogHelper.showTipsDialog({
  1546. title: '使用提示:自动导入教程',
  1547. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1548. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1549. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1550. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1551. onAction: (action) => {
  1552. if (action == DialogAction.TWO) {
  1553. PreferencesUtil.putSync('isFirstMusic', false)
  1554. router.pushUrl({
  1555. url: 'pages/ScanFilePage'
  1556. });
  1557. }
  1558. }
  1559. })
  1560. }
  1561. showMkDialog() {
  1562. DialogHelper.showTextInputDialog({
  1563. title: '新建歌单',
  1564. maskColor: Color.Transparent,
  1565. text: '',
  1566. transition: AnimationHelper.transitionInDown(666),
  1567. onChange: (text) => {
  1568. console.error("onChange: " + text);
  1569. },
  1570. onAction: (action, dialogId, content) => {
  1571. // ToastUtil.showToast('content = ' +content)
  1572. if (action == DialogAction.TWO) {
  1573. const newName = content
  1574. const newPath = this.currentPath + '/' + newName
  1575. FileUtil.mkdir(newPath, true).then(() => {
  1576. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1577. this.getSortedFiles(this.currentPath)
  1578. }).catch((error: BusinessError) => {
  1579. console.error(error.message);
  1580. });
  1581. }
  1582. }
  1583. })
  1584. }
  1585. @State progress: number = 0;
  1586. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1587. if (ArrayUtil.isEmpty(uris)) {
  1588. return;
  1589. }
  1590. let newUris: string[] = [];
  1591. this.progress = 0
  1592. DialogHelper.showLoadingProgress({
  1593. progress: this.progress,
  1594. backCancel: false,
  1595. autoCancel: false,
  1596. loadColor: this.themeColor,
  1597. fontColor: this.themeColor
  1598. });
  1599. // 计算所有文件的总大小
  1600. let totalSize = 0;
  1601. for (let uri of uris) {
  1602. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1603. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1604. await fileIo.close(sourceFile.fd);
  1605. }
  1606. let totalRead = 0;
  1607. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1608. Logger.info(TAG, 'destPath uri: ' + destPath);
  1609. for (let i = 0; i < uris.length; i++) {
  1610. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1611. Logger.info(TAG, 'filePath uri: ' + filePath);
  1612. newUris.push(filePath);
  1613. try {
  1614. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1615. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1616. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1617. const buffer = new ArrayBuffer(buffSize);
  1618. let len = await fileIo.read(sourceFile.fd, buffer);
  1619. while (len > 0) {
  1620. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1621. totalRead += len;
  1622. // 计算总进度
  1623. this.progress = Math.floor((totalRead / totalSize) * 100);
  1624. DialogHelper.updateLoading('正在导入', this.progress);
  1625. len = await fileIo.read(sourceFile.fd, buffer);
  1626. }
  1627. await fileIo.close(sourceFile.fd);
  1628. await fileIo.close(destFile.fd);
  1629. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1630. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1631. let mediaItem: VideoItem =
  1632. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1633. this.table.insert(mediaItem, (id: number) => {
  1634. // 删除目标路径缓存
  1635. this.cache.delete(this.currentPath);
  1636. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1637. });
  1638. }
  1639. }
  1640. } catch (error) {
  1641. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1642. }
  1643. }
  1644. DialogHelper.closeLoading()
  1645. this.isZero = false
  1646. // setTimeout(() => {
  1647. // // 删除目标路径缓存
  1648. // this.cache.delete(this.currentPath);
  1649. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1650. // }, 500);
  1651. Logger.info(TAG, 'scan select video result:' + newUris)
  1652. }
  1653. //拉起音频
  1654. // goSelectMusic(){
  1655. //
  1656. // try {
  1657. // let audioSelectOptions = new picker.AudioSelectOptions();
  1658. // let audioPicker = new picker.AudioViewPicker(this.context);
  1659. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1660. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1661. // this.saveVideoDatas(audioSelectResult)
  1662. // }
  1663. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1664. // }).catch((err: BusinessError) => {
  1665. //
  1666. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1667. // });
  1668. // } catch (error) {
  1669. // let err: BusinessError = error as BusinessError;
  1670. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1671. // }
  1672. //
  1673. //
  1674. //
  1675. // }
  1676. goSelectImage(item: VideoItem) {
  1677. if (!item) {
  1678. return
  1679. }
  1680. let selectUris: Array<string> = [];
  1681. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1682. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1683. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1684. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1685. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1686. //用一个全局变量存储返回的uri
  1687. selectUris = photoSelectResult.photoUris;
  1688. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1689. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1690. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1691. console.info('file fd: ' + file.fd);
  1692. let name = await MD5.digestSync(this.videoUrl)
  1693. let imagePath = this.context.filesDir + FileUtil.separator + name
  1694. imagePath = fileUri.getUriFromPath(imagePath)
  1695. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1696. fileIo.copyFileSync(file.fd, file2.fd)
  1697. fileIo.closeSync(file);
  1698. fileIo.closeSync(file2);
  1699. if (item.filePath == this.currentSong?.filePath) {
  1700. this.cover = imagePath
  1701. }
  1702. if (item) {
  1703. item.pixelMapPath = imagePath
  1704. }
  1705. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1706. if (success) {
  1707. this.doUpdateData()
  1708. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1709. } else {
  1710. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1711. }
  1712. });
  1713. LogUtil.debug("onecold this.cover =" + this.cover)
  1714. }).catch((err: BusinessError) => {
  1715. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1716. })
  1717. }
  1718. // 拉起picker选择文件管理器
  1719. async callFilePickerSelectFile(): Promise<void> {
  1720. try {
  1721. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1722. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1723. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1724. } else {
  1725. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1726. }
  1727. let documentPicker = new picker.DocumentViewPicker();
  1728. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1729. Logger.info(TAG,
  1730. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1731. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1732. this.saveVideoDatas(DocumentSelectResult)
  1733. }
  1734. }).catch((err: BusinessError) => {
  1735. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1736. });
  1737. } catch (err) {
  1738. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1739. }
  1740. }
  1741. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1742. //操作确认类弹出框
  1743. DialogHelper.showAlertDialog({
  1744. maskColor: Color.Transparent,
  1745. content: "确定要删除这个文件吗?",
  1746. backgroundColor: Color.Grey,
  1747. transition: AnimationHelper.transitionInUp(555),
  1748. onAction: (action) => {
  1749. if (action == DialogAction.ONE) {
  1750. // ToastUtil.showToast(`您点击了取消按钮`);
  1751. } else if (action == DialogAction.TWO) {
  1752. // ToastUtil.showToast(`您点击了确认按钮`);
  1753. this.doDelete(item, index + '', filePath)
  1754. }
  1755. }
  1756. })
  1757. }
  1758. //删除单个索引index的视频
  1759. doDelete(item: VideoItem, index: string, filePath: string) {
  1760. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1761. Logger.info(TAG, 'delete filePath = ' + filePath);
  1762. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1763. //旧文件删除
  1764. this.table.deleteDataForParentPath(item.filePath, () => {
  1765. FileUtil.rmdir(filePath).then(() => {
  1766. this.videoLocalList.splice(Number(index), 1)
  1767. this.deleteCache(this.currentPath)
  1768. this.getSortedFiles(this.currentPath, true)
  1769. }).catch((error: BusinessError) => {
  1770. console.error(error.message);
  1771. });
  1772. });
  1773. } else {
  1774. this.table.deleteData(item, () => {
  1775. FileUtil.unlink(filePath)
  1776. .catch((error: BusinessError) => {
  1777. console.error(error.message);
  1778. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1779. })
  1780. .finally(() => {
  1781. this.videoLocalList.splice(Number(index), 1)
  1782. this.deleteCache(this.currentPath)
  1783. this.getSortedFiles(this.currentPath, true)
  1784. });
  1785. });
  1786. }
  1787. }
  1788. }
  1789. //重命名的对话框
  1790. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1791. DialogHelper.showTextInputDialog({
  1792. title: '重命名',
  1793. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1794. maskColor: Color.Transparent,
  1795. backgroundColor: Color.Grey,
  1796. transition: AnimationHelper.transitionInDown(666),
  1797. onChange: (text) => {
  1798. console.error("onChange: " + text);
  1799. },
  1800. onAction: (action, dialogId, content) => {
  1801. // ToastUtil.showToast('content = ' +content)
  1802. if (action == DialogAction.TWO) {
  1803. const newName = content
  1804. const newPath = this.currentPath + '/' + newName
  1805. console.log("onecold item = " + item.type);
  1806. this.doReName(index, newName, filePath, newPath, item)
  1807. }
  1808. }
  1809. })
  1810. }
  1811. //剪切 移动到另个文件夹的对话框
  1812. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1813. Logger.info('onecold showCutDialog')
  1814. let mList: Array<string> = []
  1815. let rPath = this.rootPath
  1816. if (isCurrent) {
  1817. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1818. rPath = this.currentPath
  1819. } else {
  1820. mList = Utility.getNameList(this.dirList);
  1821. rPath = this.rootPath
  1822. }
  1823. let dataBean = new BubbleBean()
  1824. dataBean.data = mList
  1825. dataBean.color = this.themeColor
  1826. dataBean.onItemClick = (i) => {
  1827. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1828. Logger.info('newPath = ' + newPath)
  1829. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1830. ToastUtil.showToast('移动成功')
  1831. this.table.deleteData(item, () => {
  1832. });
  1833. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1834. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1835. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1836. CommonConstants.TYPE_LOCAL, true);
  1837. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1838. this.table.insert(newItem, (id: number) => {
  1839. //加入数据库
  1840. });
  1841. }
  1842. this.cache.delete(this.currentPath); // 删除原路径缓存
  1843. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1844. this.getSortedFiles(this.currentPath, true)
  1845. }).catch((error: BusinessError) => {
  1846. console.error(error.message);
  1847. });
  1848. XPopup.dismissTop()
  1849. }
  1850. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1851. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1852. popupPosition = PopupPosition.TOP
  1853. }
  1854. if (index <= 3) {
  1855. popupPosition = PopupPosition.BOTTOM
  1856. }
  1857. let pup: XPopup
  1858. if (this.isDarkMode) {
  1859. pup = XPopup.Builder()
  1860. .setPopupPosition(popupPosition)
  1861. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1862. .setBackgroundColor(Color.Black)
  1863. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1864. .show()
  1865. } else {
  1866. pup = XPopup.Builder()
  1867. .setPopupPosition(popupPosition)
  1868. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1869. .setBackgroundColor(Color.White)
  1870. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1871. .show()
  1872. }
  1873. }
  1874. //复制 到另个文件夹的对话框
  1875. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1876. Logger.info('onecoldv showCopyDialog')
  1877. let mList: Array<string> = []
  1878. let rPath = this.rootPath
  1879. if (isCurrent) {
  1880. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1881. rPath = this.currentPath
  1882. } else {
  1883. mList = Utility.getNameList(this.dirList);
  1884. rPath = this.rootPath
  1885. }
  1886. let dataBean = new BubbleBean()
  1887. dataBean.data = mList
  1888. dataBean.isCopy = true
  1889. dataBean.color = this.themeColor
  1890. dataBean.onItemClick = (i) => {
  1891. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1892. Logger.info('newPath = ' + newPath)
  1893. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1894. ToastUtil.showToast('复制成功')
  1895. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1896. this.getSortedFiles(this.currentPath)
  1897. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1898. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1899. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1900. CommonConstants.TYPE_LOCAL, true);
  1901. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1902. this.table.insert(newItem, (id: number) => {
  1903. //加入数据库
  1904. });
  1905. }
  1906. }).catch((error: BusinessError) => {
  1907. console.error(error.message);
  1908. });
  1909. XPopup.dismissTop()
  1910. }
  1911. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1912. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1913. popupPosition = PopupPosition.TOP
  1914. }
  1915. if (index <= 3) {
  1916. popupPosition = PopupPosition.BOTTOM
  1917. }
  1918. let pup: XPopup
  1919. if (this.isDarkMode) {
  1920. pup = XPopup.Builder()
  1921. .setPopupPosition(popupPosition)
  1922. .atView(id)
  1923. .setMaxHeight('60%')
  1924. .setBackgroundColor(Color.Black)
  1925. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1926. .show();
  1927. } else {
  1928. pup = XPopup.Builder()
  1929. .setPopupPosition(popupPosition)
  1930. .atView(id)
  1931. .setMaxHeight('60%')
  1932. .setBackgroundColor(Color.White)
  1933. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1934. .show();
  1935. }
  1936. }
  1937. //重命名索引index的视频
  1938. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1939. FileUtil.rename(oldPath, newPath).then(async () => {
  1940. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1941. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1942. //如果是文件夹先删除源数据,再添加新数据
  1943. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1944. if (success) {
  1945. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1946. } else {
  1947. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1948. }
  1949. });
  1950. this.scanDirectory(newPath)
  1951. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1952. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1953. if (success) {
  1954. console.log(" onecold 重命名成功,数据库已同步");
  1955. } else {
  1956. console.error(" onecold 重命名数据库失败原因: " + error);
  1957. }
  1958. });
  1959. }
  1960. let mediaItem: VideoItem =
  1961. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1962. this.videoLocalList[index] = mediaItem;
  1963. }
  1964. this.cache.delete(this.currentPath)
  1965. this.getSortedFiles(this.currentPath, true)
  1966. }).catch((error: BusinessError) => {
  1967. console.error(error.message);
  1968. });
  1969. }
  1970. build() {
  1971. Scroll() {
  1972. Column() {
  1973. if (!this.isShowCoverHeader()) {
  1974. Column() {
  1975. Line().width('100%').height('100%')
  1976. }
  1977. .height(this.topRectHeight)
  1978. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1979. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1980. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1981. TitleBar({ model: $titleBarModel })
  1982. .id('pup_positon_music')
  1983. }
  1984. Stack() {
  1985. Column() {
  1986. XComponent({
  1987. id: 'xcomponentId',
  1988. type: 'surface',
  1989. libraryname: 'ijkplayer_napi',
  1990. controller: this.xcomponentController
  1991. })
  1992. .onLoad((event?: object) => {
  1993. if (!!event) {
  1994. this.initDelayPlay(event);
  1995. }
  1996. })
  1997. .onKeyEvent((event?: KeyEvent) => {
  1998. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1999. if (!event || event.type !== KeyType.Down) {
  2000. return;
  2001. }
  2002. //空格键 Space key controls pause/play
  2003. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  2004. this.playOrPause()
  2005. }
  2006. // Right-click to fast forward
  2007. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2008. this.sessionFastForwardCallback(15);
  2009. }
  2010. // Left-click to rewind
  2011. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2012. this.sessionRewindCallback(15);
  2013. }
  2014. })
  2015. .onDestroy(() => {
  2016. })
  2017. .width('100%')// .width(this.videoWidth)
  2018. .aspectRatio(this.videoAspectRatio)
  2019. }
  2020. .aspectRatio(this.videoAspectRatio)
  2021. .justifyContent(FlexAlign.Center)
  2022. .backgroundColor(Color.Transparent)
  2023. .visibility(Visibility.Hidden)
  2024. .height(CommonConstants.FULL_PERCENT)
  2025. .width(CommonConstants.FULL_PERCENT)
  2026. Stack() {
  2027. Row() {
  2028. Blank()
  2029. .layoutWeight(1)
  2030. IndexerView(
  2031. {
  2032. indexArray: DEFAULT_INDEX,
  2033. selectedIndex: this.selectedIndex,
  2034. textSize: 12,
  2035. selectedColor: "#ff419ee5",
  2036. normalColor: "#ffa0a0a0",
  2037. floatSelectedTextColor: "#ffffff",
  2038. floatSelectedViewColor: "#ff419ee5",
  2039. onIndexChanged: (index) => {
  2040. this.listScroller.scrollToIndex(index)
  2041. }
  2042. })
  2043. .width(24)
  2044. .height("50%")
  2045. }.visibility(Visibility.None)
  2046. Column() {
  2047. if (!this.isShowCoverHeader()) {
  2048. this.tabTitle()
  2049. }
  2050. if (this.isGridMusic) {
  2051. this.getGridView()
  2052. } else {
  2053. this.getListView()
  2054. }
  2055. if (this.modeType == 0) {
  2056. Column() {
  2057. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  2058. .width(130)
  2059. .height(50)
  2060. .margin({ top: 100, bottom: 40 })
  2061. .backgroundColor(this.themeColor)
  2062. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2063. .onClick(() => {
  2064. this.asyncCurrentPathData()
  2065. })
  2066. }
  2067. .height(100)
  2068. .position({ top: 260 })
  2069. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2070. .animation({ duration: 500 }),
  2071. TransitionEffect.scale({ x: 0, y: 0 })))
  2072. .justifyContent(FlexAlign.Center)
  2073. .opacity(this.isZero ? 1 : 0)
  2074. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2075. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  2076. .animation({
  2077. duration: 500,
  2078. curve: 'ease-in-out' // 可选动画曲线
  2079. })
  2080. .width('100%')
  2081. }
  2082. }
  2083. .layoutWeight(1)
  2084. .height('100%')
  2085. }
  2086. .layoutWeight(1)
  2087. .height('100%')
  2088. Row() {
  2089. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2090. .width('35%')
  2091. .height(60)
  2092. .margin({ top: 10, bottom: 10, right: 6 })
  2093. .backgroundColor(this.themeColor)
  2094. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2095. .onClick(() => {
  2096. if (this.isAllSelected) {
  2097. // 全不选
  2098. this.selectedFiles = [];
  2099. } else {
  2100. // 全选
  2101. this.selectedFiles = [...this.getCurFileList()];
  2102. }
  2103. this.isAllSelected = !this.isAllSelected;
  2104. })
  2105. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2106. .width('35%')
  2107. .height(60)
  2108. .id('music_cut')
  2109. .margin({ top: 10, bottom: 10, right: 6 })
  2110. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2111. .backgroundColor(this.themeColor)
  2112. .onClick(() => {
  2113. this.showCutDialogForMultipleFiles(false, 'music_cut')
  2114. })
  2115. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2116. .width('35%')
  2117. .height(60)
  2118. .id('music_cut_current')
  2119. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2120. .margin({ top: 10, bottom: 10, right: 6 })
  2121. .backgroundColor(this.themeColor)
  2122. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2123. .onClick(() => {
  2124. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2125. })
  2126. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2127. .width('35%')
  2128. .height(60)
  2129. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2130. .margin({ top: 10, bottom: 10, right: 6 })
  2131. .backgroundColor(this.themeColor)
  2132. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2133. .onClick(() => {
  2134. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2135. })
  2136. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2137. .width('35%')
  2138. .height(60)
  2139. .margin({ top: 10, bottom: 10, right: 6 })
  2140. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2141. .backgroundColor(this.themeColor)
  2142. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2143. .onClick(() => {
  2144. this.showWarnIsDelete()
  2145. })
  2146. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2147. .width('35%')
  2148. .height(60)
  2149. .margin({ top: 10, bottom: 10, right: 6 })
  2150. .backgroundColor(this.themeColor)
  2151. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2152. .onClick(() => {
  2153. this.selectedFiles = [];
  2154. this.isAllSelected = false
  2155. this.isMultiSelect = false
  2156. })
  2157. }
  2158. .width('100%')
  2159. .justifyContent(FlexAlign.Center)
  2160. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2161. .opacity(this.isMultiSelect ? 1 : 0)
  2162. .animation({
  2163. duration: 666,
  2164. curve: 'ease-in-out' // 可选动画曲线
  2165. })
  2166. .position(this.isShowCoverHeader() ? { bottom: 78 }
  2167. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  2168. }
  2169. .width('100%')
  2170. .height('100%')
  2171. .alignContent(Alignment.Top)
  2172. Column() {
  2173. this.PlayController()
  2174. }
  2175. .hitTestBehavior(HitTestMode.Transparent)
  2176. .position({ bottom: 0 }) // 将 Row 固定在底部
  2177. .opacity(this.barBottomOpacity)
  2178. }
  2179. .width('100%')
  2180. .height('100%')
  2181. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2182. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2183. .backgroundImagePosition(Alignment.Center)
  2184. .backdropBlur(this.blurValue)
  2185. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2186. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2187. }
  2188. }
  2189. asyncCurrentPathData() {
  2190. if (this.modeType == 0) {
  2191. workerInstance.postMessage({
  2192. code: 1,
  2193. data1: this.context,
  2194. data2: this.currentPath,
  2195. data3: this.lockPath,
  2196. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2197. });
  2198. }
  2199. }
  2200. // 处理文件选择的函数
  2201. handleFileSelection(item: VideoItem, checked: boolean) {
  2202. if (checked) {
  2203. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2204. this.selectedFiles.push(item);
  2205. }
  2206. } else {
  2207. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2208. if (index > -1) {
  2209. this.selectedFiles.splice(index, 1);
  2210. }
  2211. }
  2212. }
  2213. showWarnIsDelete() {
  2214. //操作确认类弹出框
  2215. DialogHelper.showAlertDialog({
  2216. content: "确定要删除这些文件吗?",
  2217. transition: AnimationHelper.transitionInUp(666),
  2218. maskColor: Color.Transparent,
  2219. backgroundColor: Color.Grey,
  2220. onAction: (action) => {
  2221. if (action == DialogAction.ONE) {
  2222. // ToastUtil.showToast(`您点击了取消按钮`);
  2223. } else if (action == DialogAction.TWO) {
  2224. // ToastUtil.showToast(`您点击了确认按钮`);
  2225. this.deleteMultipleFiles()
  2226. }
  2227. }
  2228. })
  2229. }
  2230. //多选删除文件
  2231. deleteMultipleFiles() {
  2232. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  2233. this.selectedFiles.forEach((item) => {
  2234. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  2235. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2236. this.table.deleteDataForParentPath(item.filePath, () => {
  2237. FileUtil.rmdir(item.filePath).then(() => {
  2238. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  2239. this.selectedFiles = [];
  2240. this.isMultiSelect = false
  2241. this.isAllSelected = false
  2242. this.cache.delete(this.currentPath);
  2243. this.getSortedFiles(this.currentPath, true);
  2244. }).catch((error: Error) => {
  2245. console.error(error.message);
  2246. });
  2247. });
  2248. } else {
  2249. this.table.deleteData(item, () => {
  2250. FileUtil.unlink(item.filePath).catch((error: Error) => {
  2251. console.error(error.message);
  2252. }).finally(() => {
  2253. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  2254. this.selectedFiles = [];
  2255. this.isMultiSelect = false
  2256. this.isAllSelected = false
  2257. this.cache.delete(this.currentPath);
  2258. this.getSortedFiles(this.currentPath, true);
  2259. });
  2260. });
  2261. }
  2262. });
  2263. }
  2264. }
  2265. //多选移动文件
  2266. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2267. Logger.info('onecold showCutDialogForMultipleFiles')
  2268. let mList: Array<string> = []
  2269. let rPath = this.rootPath
  2270. if (isCurrent) {
  2271. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2272. rPath = this.currentPath
  2273. } else {
  2274. mList = Utility.getNameList(this.dirList);
  2275. rPath = this.rootPath
  2276. }
  2277. let dataBean = new BubbleBean();
  2278. dataBean.data = mList;
  2279. dataBean.color = this.themeColor
  2280. dataBean.onItemClick = (i) => {
  2281. const newDirPath = rPath + '/' + mList[i];
  2282. // Logger.info('newDirPath = ' + newDirPath)
  2283. this.selectedFiles.forEach((item) => {
  2284. const newPath = newDirPath + '/' + item.fileName;
  2285. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2286. ToastUtil.showToast('移动成功');
  2287. this.table.deleteData(item, () => {
  2288. this.cache.delete(this.currentPath); // 删除原路径缓存
  2289. this.cache.delete(newDirPath); // 删除目标路径缓存
  2290. this.getSortedFiles(this.currentPath, true);
  2291. });
  2292. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2293. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2294. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2295. CommonConstants.TYPE_LOCAL, true);
  2296. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2297. this.table.insert(newItem, (id: number) => {
  2298. //加入数据库
  2299. });
  2300. }
  2301. }).catch((error: Error) => {
  2302. console.error(error.message);
  2303. });
  2304. });
  2305. this.isMultiSelect = false
  2306. this.selectedFiles = [];
  2307. this.isAllSelected = false
  2308. XPopup.dismissTop();
  2309. };
  2310. let pup: XPopup
  2311. if (this.isDarkMode) {
  2312. pup = XPopup.Builder()
  2313. .setPopupPosition(PopupPosition.TOP)
  2314. .atView(viewId)
  2315. .setBackgroundColor(Color.Black)
  2316. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2317. .show();
  2318. } else {
  2319. pup = XPopup.Builder()
  2320. .setPopupPosition(PopupPosition.TOP)
  2321. .atView(viewId)
  2322. .setBackgroundColor(Color.White)
  2323. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2324. .show();
  2325. }
  2326. }
  2327. doFav(item: VideoItem) {
  2328. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2329. let isFav = 0
  2330. if (Utility.getIsFav(this.favList, item)) {
  2331. isFav = 0
  2332. } else {
  2333. isFav = 1
  2334. }
  2335. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2336. if (result) {
  2337. if (isFav === 1) {
  2338. ToastUtil.showToast('收藏成功');
  2339. } else {
  2340. ToastUtil.showToast('取消收藏成功');
  2341. }
  2342. // 先更新收藏列表和其他UI
  2343. this.deleteCache(this.currentPath)
  2344. this.getFavList(false)
  2345. if (this.modeType === 0 && !this.isFavMusic) {
  2346. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2347. this.getSortedFiles(this.currentPath)
  2348. }
  2349. workerInstance.postMessage({ code: 2, data: this.context });
  2350. workerInstance.postMessage({ code: 3, data: this.context });
  2351. workerInstance.postMessage({ code: 4, data: this.context });
  2352. // 刷新UnifiedPlayerService的收藏状态,这会自动更新AVSession
  2353. await this.unifiedPlayerService.refreshFavoriteStatus();
  2354. }
  2355. })
  2356. }
  2357. //多选复制文件
  2358. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2359. console.log('onecold showCopyDialogForMultipleFiles');
  2360. let mList: Array<string> = []
  2361. let rPath = this.rootPath
  2362. if (isCurrent) {
  2363. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2364. rPath = this.currentPath
  2365. } else {
  2366. mList = Utility.getNameList(this.dirList);
  2367. rPath = this.rootPath
  2368. }
  2369. let dataBean = new BubbleBean();
  2370. dataBean.data = mList;
  2371. dataBean.isCopy = true
  2372. dataBean.color = this.themeColor
  2373. dataBean.onItemClick = (i) => {
  2374. const newDirPath = rPath + '/' + mList[i];
  2375. // Logger.info('newDirPath = ' + newDirPath)
  2376. this.selectedFiles.forEach((item) => {
  2377. const newPath = newDirPath + '/' + item.fileName;
  2378. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2379. ToastUtil.showToast('复制成功');
  2380. this.cache.delete(newDirPath); // 删除目标路径缓存
  2381. this.getSortedFiles(this.currentPath);
  2382. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2383. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2384. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2385. CommonConstants.TYPE_LOCAL, true);
  2386. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2387. this.table.insert(newItem, (id: number) => {
  2388. //加入数据库
  2389. });
  2390. }
  2391. }).catch((error: Error) => {
  2392. console.error(error.message);
  2393. });
  2394. });
  2395. this.isMultiSelect = false
  2396. this.selectedFiles = [];
  2397. this.isAllSelected = false
  2398. XPopup.dismissTop();
  2399. };
  2400. let pup: XPopup
  2401. if (this.isDarkMode) {
  2402. pup = XPopup.Builder()
  2403. .setPopupPosition(PopupPosition.TOP)
  2404. .atView(viewId)
  2405. .setBackgroundColor(Color.Black)
  2406. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2407. .show();
  2408. } else {
  2409. pup = XPopup.Builder()
  2410. .setPopupPosition(PopupPosition.TOP)
  2411. .atView(viewId)
  2412. .setBackgroundColor(Color.White)
  2413. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2414. .show();
  2415. }
  2416. }
  2417. @Builder
  2418. private DirItem(item: VideoItem, index?: number) {
  2419. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2420. Row() {
  2421. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2422. $r('app.media.music_group'))
  2423. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2424. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2425. .fillColor(this.themeColor)// .fontSize(33)
  2426. .alt($r('app.media.music_group'))
  2427. .borderRadius('100%')
  2428. .clip(true)
  2429. .margin({ left: 20, top: 8, bottom: 8 })
  2430. Column() {
  2431. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2432. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2433. .maxLines(1)// .width('88%')
  2434. .animation({
  2435. duration: 555,
  2436. curve: 'ease-in-out',
  2437. })
  2438. .transition({
  2439. type: TransitionType.Insert,
  2440. opacity: 0,
  2441. translate: { x: 160 }
  2442. })
  2443. .margin({ left: 10, right: 20 })
  2444. .fontColor($r('app.color.text_color'))
  2445. Row() {
  2446. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2447. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2448. .padding({ top: 8 })
  2449. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2450. .fontColor($r('app.color.text_color'))
  2451. .margin({ left: 10 })
  2452. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2453. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2454. .padding({ top: 8 })
  2455. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2456. .fontColor($r('app.color.text_color'))
  2457. .margin({ left: 10 })
  2458. Blank()
  2459. }
  2460. }
  2461. .height('100%')
  2462. .layoutWeight(1)
  2463. .justifyContent(FlexAlign.Center)
  2464. .alignItems(HorizontalAlign.Start)
  2465. Blank()
  2466. Image($r('app.media.arrow_right'))
  2467. .height(25)
  2468. .margin({ right: 10 })
  2469. .alignSelf(ItemAlign.Center)
  2470. .id(item.filePath)
  2471. }
  2472. }
  2473. .backgroundColor(Color.Transparent)
  2474. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2475. .width('100%')
  2476. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2477. .opacity(this.opacityItem) // 绑定透明度
  2478. }
  2479. isShowDir(dirName: string) {
  2480. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2481. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2482. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2483. if (dirName === undefined) {
  2484. return true
  2485. }
  2486. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2487. return this.isShowSimi
  2488. }
  2489. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2490. return this.isShowFAV
  2491. }
  2492. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2493. return this.isShowHistory
  2494. }
  2495. return true
  2496. }
  2497. @State opacityItem: number = 1; // 控制透明度的状态变量
  2498. @Builder
  2499. private MusicItem(item: VideoItem, index?: number) {
  2500. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2501. Row() {
  2502. Stack() {
  2503. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2504. .fillColor(this.themeColor)
  2505. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2506. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2507. .alt($r('app.media.music_red'))
  2508. .borderRadius('100%')
  2509. .clip(true)
  2510. .opacity(this.opacityItem)// 绑定透明度
  2511. .margin({ left: 20 })
  2512. }
  2513. Column() {
  2514. Column() {
  2515. Text(item.name)
  2516. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2517. .maxLines(1)
  2518. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2519. .animation({
  2520. duration: 555,
  2521. curve: 'Linear',
  2522. })
  2523. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2524. $r('app.color.text_color'))
  2525. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2526. .bindPopup(this.longItemFilePath === item.filePath, {
  2527. builder: this.MenuBuilder(item,index,item.filePath),
  2528. placement: Placement.Top,
  2529. // autoCancel: true,
  2530. mask: {color:'#33000000'},
  2531. // popupColor: Color.Yellow,
  2532. enableArrow: false,//是否显示箭头
  2533. showInSubWindow: false,
  2534. onStateChange: (e) => {
  2535. if (!e.isVisible) {
  2536. this.longItemFilePath = ''
  2537. this.tempLyricContent = ''
  2538. }
  2539. }
  2540. })
  2541. .gesture(LongPressGesture()
  2542. .onAction(async () => {
  2543. //如果是专辑和艺术家的首页,不能长按
  2544. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2545. return
  2546. //如果是我的收藏 最近播放等也不能长按
  2547. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2548. item.name === LocalMusic.STR_HISTORY_MUSIC
  2549. )
  2550. return
  2551. this.longItemFilePath = item.filePath
  2552. this.tempLyricContent = await this.getLyricContent(item)
  2553. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2554. })
  2555. .onActionEnd((event: GestureEvent) => {
  2556. })
  2557. )
  2558. Row() {
  2559. Column(){
  2560. Text(item.md5Str?.includes('Lossless')?
  2561. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2562. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2563. .padding({ top: 3,right:6,left:6,bottom:3 })
  2564. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2565. $r('app.color.text_color'))
  2566. .fontWeight(500)
  2567. .borderRadius(12)
  2568. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2569. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2570. .backgroundColor('#FFC107')
  2571. }
  2572. .padding({ top: 8 })
  2573. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2574. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2575. .padding({ top: 8 })
  2576. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2577. $r('app.color.text_color'))
  2578. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2579. Blank()
  2580. Text(item.size)
  2581. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2582. .padding({ top: 8 })
  2583. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2584. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2585. $r('app.color.text_color'))
  2586. .margin({ left: 10 })
  2587. }
  2588. .gesture(LongPressGesture()
  2589. .onAction(async () => {
  2590. //如果是专辑和艺术家的首页,不能长按
  2591. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2592. return
  2593. //如果是我的收藏 最近播放等也不能长按
  2594. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2595. item.name === LocalMusic.STR_HISTORY_MUSIC
  2596. )
  2597. return
  2598. this.longItemFilePath = item.filePath
  2599. this.tempLyricContent = await this.getLyricContent(item)
  2600. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2601. })
  2602. .onActionEnd((event: GestureEvent) => {
  2603. })
  2604. )
  2605. }
  2606. .height('100%')
  2607. .width('100%')
  2608. .justifyContent(FlexAlign.Center)
  2609. .alignItems(HorizontalAlign.Start)
  2610. }
  2611. .height('100%')
  2612. .margin({ left: 5 })
  2613. .layoutWeight(1)
  2614. Column() {
  2615. Checkbox({ name: 'checkbox' + index })
  2616. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2617. .selectedColor(this.themeColor)
  2618. .shape(CheckBoxShape.CIRCLE)
  2619. .opacity(this.isMultiSelect ? 1 : 0)
  2620. .animation({
  2621. duration: 666,
  2622. curve: 'Smooth' // 可选动画曲线
  2623. })
  2624. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2625. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2626. .margin({ left: 20, top: 8, bottom: 8 })
  2627. .width(22)
  2628. .height(22)
  2629. ImageAnimator()
  2630. .images(this.imagesF)// 动画数组
  2631. .duration(1000)// 持续
  2632. .state(this.animationState)// 动画状态
  2633. .fillMode(FillMode.Forwards)
  2634. .width(18)
  2635. .margin({ right: 20, top: 8, bottom: 8 })
  2636. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2637. Visibility.None)
  2638. .height(18)
  2639. .iterations(-1) // 播放次数
  2640. }
  2641. }
  2642. }
  2643. .backgroundColor(Color.Transparent)
  2644. .width('100%')
  2645. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2646. }
  2647. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2648. @Builder
  2649. tabTitle() {
  2650. Column() {
  2651. // 使用 Stack 布局来实现绝对定位效果
  2652. Stack() {
  2653. // 背景动画容器
  2654. Row() {
  2655. ForEach(this.tabs, (i: string, index) => {
  2656. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2657. Flex()
  2658. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2659. .borderRadius(20)
  2660. .padding(10)
  2661. .margin(6)
  2662. .width('100%')
  2663. .height('100%')
  2664. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2665. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2666. .opacity(this.modeType === index ? 1 : 0)
  2667. .animation({
  2668. duration: 666,
  2669. playMode: PlayMode.Normal,
  2670. curve: 'ease-in-out'
  2671. });
  2672. }
  2673. .layoutWeight(1)
  2674. .margin({
  2675. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2676. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2677. });
  2678. });
  2679. }
  2680. .width('100%')
  2681. .height(50);
  2682. // 导航栏容器
  2683. Row() {
  2684. ForEach(this.tabs, (item: string, index) => {
  2685. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2686. Text(item)
  2687. .fontSize(16)
  2688. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2689. .padding(15)
  2690. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2691. .onClick(() => {
  2692. this.modeType = index;
  2693. this.onModeChange();
  2694. });
  2695. }
  2696. .layoutWeight(1)
  2697. .stateStyles({
  2698. pressed: { opacity: 0.6 } // 按压反馈
  2699. });
  2700. });
  2701. }
  2702. .width('100%')
  2703. .height(this.topBarHeight)
  2704. .opacity(this.barOpacity)
  2705. .backgroundColor(Color.Transparent);
  2706. }
  2707. .width('100%')
  2708. .height(this.topBarHeight)
  2709. .opacity(this.barOpacity)
  2710. Line()
  2711. .width('100%')
  2712. .height(1)
  2713. .backgroundColor($r('app.color.index_background'))
  2714. .opacity(this.barOpacity)
  2715. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2716. }
  2717. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2718. }
  2719. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2720. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2721. isShowCoverHeader() {
  2722. if (!this.isShowHeader) {
  2723. return false
  2724. }
  2725. if (this.modeType == 0) {
  2726. if (this.isHistory || this.isFavMusic) {
  2727. return true
  2728. }
  2729. if (this.currentPath != this.rootPath) {
  2730. return true
  2731. }
  2732. }
  2733. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2734. }
  2735. @Builder
  2736. coverHeader() {
  2737. if (this.isShowCoverHeader()) {
  2738. Column() {
  2739. Stack() {
  2740. // 居中标题
  2741. Text('')
  2742. .fontSize(18)
  2743. .fontColor(Color.White)
  2744. .align(Alignment.Center)
  2745. // 左右按钮
  2746. Row() {
  2747. Image($r('app.media.left_back_white'))
  2748. .width(28)
  2749. .height(28)
  2750. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2751. .margin({ left: 12, right: 8 })
  2752. .onClick(() => {
  2753. animateTo({ duration: 555 }, () => {
  2754. this.doSwipBack()
  2755. })
  2756. })
  2757. Blank().flexGrow(1)
  2758. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2759. Image($r('app.media.add'))
  2760. .width(25)
  2761. .height(25)
  2762. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2763. .margin({ left: 8, right: 15 })
  2764. .onClick(() => {
  2765. this.showAddDialog()
  2766. })
  2767. }
  2768. }
  2769. .height(48)
  2770. .width('100%')
  2771. .alignItems(VerticalAlign.Center)
  2772. }
  2773. .height(48)
  2774. .width('100%')
  2775. Row() {
  2776. Column() {
  2777. Image(this.currentTitleCover)
  2778. .height(100)
  2779. .width(100)
  2780. .alt(this.imageLabel)
  2781. .borderRadius(8)
  2782. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2783. }
  2784. .alignItems(HorizontalAlign.Start)
  2785. .margin({ left: 30, top: 3, bottom: 15 })
  2786. Column() {
  2787. Column() {
  2788. Text(this.currentTitleName)
  2789. .fontSize(16)
  2790. .maxLines(1)
  2791. .fontWeight(FontWeight.Bold)
  2792. .fontColor($r('app.color.text_color'))
  2793. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2794. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2795. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2796. .fontSize(14)
  2797. .padding({ top: 8 })
  2798. .maxLines(1)
  2799. .fontWeight(FontWeight.Bold)
  2800. .fontColor($r('app.color.text_color'))
  2801. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2802. if(this.videoLocalList[0].genre){
  2803. Text(`风格:${this.videoLocalList[0].genre}`)
  2804. .fontSize(14)
  2805. .padding({ top: 8 })
  2806. .maxLines(1)
  2807. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2808. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2809. ?Visibility.None:Visibility.Visible)
  2810. .fontWeight(FontWeight.Bold)
  2811. .fontColor($r('app.color.text_color'))
  2812. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2813. }
  2814. if(this.videoLocalList[0].year){
  2815. Text(`发行时间:${this.videoLocalList[0].year}`)
  2816. .fontSize(14)
  2817. .padding({ top: 8 })
  2818. .maxLines(1)
  2819. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2820. this.videoLocalList[0].year.includes(this.UNKONWN)
  2821. ?Visibility.None:Visibility.Visible)
  2822. .fontWeight(FontWeight.Bold)
  2823. .fontColor($r('app.color.text_color'))
  2824. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2825. }
  2826. }
  2827. if(this.modeType != 3){
  2828. Row() {
  2829. Text(`共${this.videoLocalList.length}首歌`)
  2830. .fontSize(13)
  2831. .fontWeight(FontWeight.Bold)
  2832. .padding({ top: 8 })
  2833. .fontColor($r('app.color.text_color'))
  2834. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2835. Blank()
  2836. }
  2837. }
  2838. }
  2839. .height('100%')
  2840. .width('100%')
  2841. .justifyContent(FlexAlign.Center)
  2842. .alignItems(HorizontalAlign.Start)
  2843. }
  2844. .height('100%')
  2845. .layoutWeight(1)
  2846. .margin({ left: 20 })
  2847. }
  2848. this.listViewTitle()
  2849. }
  2850. .backgroundImage(this.getCoverTitleBg())
  2851. .height(250)
  2852. .width('100%')
  2853. .backgroundImageSize({ height: '100%', width: '100%' })
  2854. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2855. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2856. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2857. .justifyContent(FlexAlign.SpaceBetween)
  2858. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2859. TransitionEffect.scale({ x: 0, y: 0 })))
  2860. } else {
  2861. this.listViewTitle()
  2862. }
  2863. }
  2864. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2865. if (this.isCustomizeBg) {
  2866. return ('rgba(255,255,255,0.2)')
  2867. }
  2868. if (this.isDarkMode) {
  2869. return $r('app.color.user_center_card_background')
  2870. }
  2871. return this.currentTitleCover
  2872. }
  2873. @Builder
  2874. listViewTitle() {
  2875. Column() {
  2876. Row({ space: 8 }) {
  2877. Row({ space: 8 }) {
  2878. Image($r("app.media.hm_playlist"))
  2879. .width(25)
  2880. .margin({ left: 8 })
  2881. .fillColor(this.themeColor)
  2882. Text(`共找到${this.artistList.length}位艺术家`)
  2883. .fontColor($r('app.color.text_color'))
  2884. .fontSize(14)
  2885. .opacity(this.opacityItem)
  2886. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2887. Text(`共找到${this.albumList.length}张专辑`)
  2888. .fontColor($r('app.color.text_color'))
  2889. .opacity(this.opacityItem)
  2890. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2891. .fontSize(14)
  2892. }
  2893. .layoutWeight(1)
  2894. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2895. Row() {
  2896. TextInput({
  2897. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2898. text: this.searchText
  2899. })
  2900. .height(35)
  2901. .onChange((value: string) => {
  2902. this.onSearchInput(value);
  2903. })
  2904. .layoutWeight(1)
  2905. Text(`取消`)
  2906. .margin({ left: 10, right: 10 })
  2907. .fontColor($r('app.color.text_color'))
  2908. .fontSize(16)
  2909. .onClick(() => {
  2910. this.isSearchMode = false
  2911. this.searchText = ''
  2912. if (this.modeType === 2) {
  2913. this.updateListData(this.artistList)
  2914. } else {
  2915. this.updateListData(this.albumList)
  2916. }
  2917. })
  2918. }
  2919. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2920. .animation({
  2921. duration: 666,
  2922. curve: 'ease-in-out' // 可选动画曲线
  2923. })
  2924. Blank()
  2925. Image($r("app.media.search"))
  2926. .width(25)
  2927. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2928. .animation({
  2929. duration: 666,
  2930. curve: 'ease-in-out' // 可选动画曲线
  2931. })// .opacity(this.opacityItem)
  2932. .fillColor(this.themeColor)
  2933. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2934. .onClick(() => {
  2935. this.isSearchMode = true
  2936. })
  2937. Image($r("app.media.top_rank"))
  2938. .width(25)// .opacity(this.opacityItem)
  2939. .fillColor(this.themeColor)
  2940. .animation({
  2941. duration: 666,
  2942. curve: 'ease-in-out' // 可选动画曲线
  2943. })
  2944. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2945. .onClick(() => {
  2946. this.showRankDialog()
  2947. })
  2948. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2949. .width(25)
  2950. .animation({
  2951. duration: 666,
  2952. curve: 'ease-in-out' // 可选动画曲线
  2953. })
  2954. .fillColor(this.themeColor)
  2955. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2956. .onClick(() => {
  2957. this.isGridMusic = !this.isGridMusic
  2958. })
  2959. }
  2960. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2961. Visibility.None)
  2962. .width('100%')
  2963. .padding(10)
  2964. .height(50)
  2965. .border({
  2966. width: { bottom: 1 },
  2967. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2968. })
  2969. Row({ space: 8 }) {
  2970. Row({ space: 8 }) {
  2971. Image($r("app.media.hm_play"))
  2972. .width(25)
  2973. .margin({ left: 8 })
  2974. .fillColor(this.themeColor)
  2975. Text(`播放全部`)
  2976. .fontColor($r('app.color.text_color'))
  2977. .fontSize(14)
  2978. .animation({
  2979. duration: 666,
  2980. curve: 'ease-in-out' // 可选动画曲线
  2981. })
  2982. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2983. .fontColor($r('app.color.text_color'))
  2984. .fontSize(14)
  2985. .opacity(this.opacityItem)
  2986. .animation({
  2987. duration: 666,
  2988. curve: 'ease-in-out' // 可选动画曲线
  2989. })
  2990. }
  2991. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2992. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2993. .animation({
  2994. duration: 666,
  2995. curve: 'ease-in-out' // 可选动画曲线
  2996. })
  2997. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2998. .onTouch((event: TouchEvent) => {
  2999. if (event.type === TouchType.Down) {
  3000. this.isClickedPLayAll = true;
  3001. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  3002. this.isClickedPLayAll = false;
  3003. }
  3004. })
  3005. .onClick(() => {
  3006. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  3007. if (this.modeType === 0) {
  3008. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  3009. this.doPlay(this.getCurFileList()[0])
  3010. }
  3011. } else {
  3012. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  3013. this.doPlay(this.mediaKuList[0])
  3014. }
  3015. }
  3016. })
  3017. Row() {
  3018. TextInput({ placeholder: '输入名称...', text: this.searchText })
  3019. .height(35)
  3020. .onChange((value: string) => {
  3021. this.onSearchInput(value);
  3022. })
  3023. .layoutWeight(1)
  3024. Text(`取消`)
  3025. .margin({ left: 10, right: 10 })
  3026. .fontColor($r('app.color.text_color'))
  3027. .fontSize(16)
  3028. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3029. .onClick(() => {
  3030. this.isSearchMode = false
  3031. this.searchText = ''
  3032. this.updateListData(this.mediaKuList)
  3033. })
  3034. }
  3035. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3036. .animation({
  3037. duration: 666,
  3038. curve: 'ease-in-out' // 可选动画曲线
  3039. })
  3040. Blank()
  3041. Image($r("app.media.search"))
  3042. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  3043. .animation({
  3044. duration: 666,
  3045. curve: 'ease-in-out' // 可选动画曲线
  3046. })// .opacity(this.opacityItem)
  3047. .fillColor(this.themeColor)
  3048. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3049. .onClick(() => {
  3050. this.isSearchMode = true
  3051. })
  3052. Image($r("app.media.refresh"))
  3053. .fillColor(this.themeColor)
  3054. .width(25)
  3055. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3056. .animation({
  3057. duration: 666,
  3058. curve: 'ease-in-out' // 可选动画曲线
  3059. })
  3060. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3061. .onClick(() => {
  3062. if (this.isFavMusic) {
  3063. this.getFavList(true)
  3064. } else {
  3065. if(this.modeType == 0){
  3066. this.asyncCurrentPathData()
  3067. }else if(this.modeType ==1){
  3068. workerInstance.postMessage({ code: 2, data: this.context });
  3069. }
  3070. }
  3071. })
  3072. Image($r("app.media.top_rank"))
  3073. .width(25)
  3074. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  3075. Visibility.Visible)// .opacity(this.opacityItem)
  3076. .animation({
  3077. duration: 666,
  3078. curve: 'ease-in-out' // 可选动画曲线
  3079. })
  3080. .fillColor(this.themeColor)
  3081. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3082. .onClick(() => {
  3083. this.showRankDialog()
  3084. })
  3085. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  3086. .width(24)
  3087. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3088. .animation({
  3089. duration: 666,
  3090. curve: 'ease-in-out' // 可选动画曲线
  3091. })
  3092. .fillColor(this.themeColor)
  3093. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3094. .onClick(() => {
  3095. this.isMultiSelect = !this.isMultiSelect
  3096. })
  3097. SymbolGlyph($r('sys.symbol.trash'))
  3098. .fontColor([this.themeColor])
  3099. .fontSize(25)
  3100. .effectStrategy(1)
  3101. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  3102. .animation({
  3103. duration: 666,
  3104. curve: 'ease-in-out' // 可选动画曲线
  3105. })
  3106. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3107. .onClick(() => {
  3108. this.clearVideoHistory() //清空播放记录
  3109. })
  3110. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3111. .width(24)
  3112. .animation({
  3113. duration: 666,
  3114. curve: 'ease-in-out' // 可选动画曲线
  3115. })
  3116. .fillColor(this.themeColor)
  3117. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3118. .bindPopup($$this.tipPopup, {
  3119. builder: this.popupBuilder,
  3120. placement: Placement.Bottom,
  3121. maskColor: 0x33000000,
  3122. enableArrow: true,
  3123. onStateChange: (e) => {
  3124. if (!e.isVisible) {
  3125. this.tipPopup = false;
  3126. }
  3127. }
  3128. })
  3129. .onClick(() => {
  3130. this.isGridMusic = !this.isGridMusic
  3131. })
  3132. }
  3133. .width('100%')
  3134. .padding(10)
  3135. .height(50)
  3136. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  3137. .border({
  3138. width: { bottom: 1 },
  3139. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3140. })
  3141. }
  3142. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3143. }
  3144. // 第二步:popup构造器定义弹框内容
  3145. @Builder popupBuilder() {
  3146. Column({ space: 2 }) {
  3147. Text('友情提示:双指缩放可以放大缩小列表')
  3148. .fontSize(12)
  3149. .fontWeight(FontWeight.Regular)
  3150. .fontColor($r('app.color.text_color'))
  3151. }
  3152. .justifyContent(FlexAlign.SpaceAround)
  3153. .width(220)
  3154. .height(55)
  3155. .padding(15)
  3156. }
  3157. //搜索功能的实现
  3158. @State searchText: string = ''; // 用户输入内容
  3159. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3160. @State isSearchMode: boolean = false
  3161. // 实时搜索逻辑(带防抖)
  3162. private onSearchInput(value: string) {
  3163. this.searchText = value.trim();
  3164. let mSearchList: Array<VideoItem> = []
  3165. switch (this.modeType) {
  3166. case 0:
  3167. mSearchList = this.videoLocalList
  3168. break;
  3169. case 1:
  3170. mSearchList = this.mediaKuList
  3171. break;
  3172. case 2:
  3173. mSearchList = this.artistList
  3174. break;
  3175. case 3:
  3176. mSearchList = this.albumList
  3177. break;
  3178. }
  3179. // 新增条件判断:空输入时显示所有数据
  3180. if (this.searchText === '') {
  3181. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3182. } else {
  3183. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3184. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  3185. });
  3186. }
  3187. this.updateListData(this.filteredList);
  3188. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3189. }
  3190. @State dragItem: number = -1
  3191. @State scaleItem: number = -1
  3192. @State neighborItem: number = -1
  3193. @State neighborScale: number = -1
  3194. @State offsetY: number = 0
  3195. private dragRefOffset: number = 0
  3196. private ITEM_INTV: number = 78
  3197. scaleSelect(item: number): number {
  3198. if (this.scaleItem === item) {
  3199. return 1.05
  3200. } else if (this.neighborItem === item) {
  3201. return this.neighborScale
  3202. } else {
  3203. return 1
  3204. }
  3205. }
  3206. itemMove(index: number, newIndex: number): void {
  3207. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3208. return;
  3209. }
  3210. let tmp = this.videoLocalList.splice(index, 1);
  3211. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3212. this.dataSource.pushArrayData(this.videoLocalList)
  3213. }
  3214. // Grid布局的开始
  3215. private dragRefOffSetX: number = 0;
  3216. private dragRefOffSetY: number = 0;
  3217. private FIX_VP_X: number = 180;
  3218. private FIX_VP_Y: number = 84;
  3219. isDraggable(index: number): boolean {
  3220. return index >= 0;
  3221. }
  3222. getRowEnd(item: number) {
  3223. if (item.toString() === '0') {
  3224. return 1;
  3225. } else {
  3226. return 0;
  3227. }
  3228. }
  3229. // [Start itemMove_start]
  3230. // itemMoveGrid(index: number, newIndex: number): void {
  3231. // if (!this.isDraggable(newIndex)) {
  3232. // return;
  3233. // }
  3234. // let tmp = this.videoLocalList.splice(index, 1);
  3235. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3236. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  3237. // }
  3238. isInLeft(index: number) {
  3239. return index % 2 == 0;
  3240. }
  3241. down(index: number): void {
  3242. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  3243. return;
  3244. }
  3245. this.offsetY -= this.FIX_VP_Y;
  3246. this.dragRefOffSetY += this.FIX_VP_Y;
  3247. this.itemMove(index, index + 1);
  3248. }
  3249. up(index: number): void {
  3250. if (!this.isDraggable(index - 2)) {
  3251. return;
  3252. }
  3253. this.offsetY += this.FIX_VP_Y;
  3254. this.dragRefOffSetY -= this.FIX_VP_Y;
  3255. this.itemMove(index, index - 1);
  3256. }
  3257. left(index: number): void {
  3258. if (this.isInLeft(index)) {
  3259. return;
  3260. }
  3261. if (!this.isDraggable(index - 1)) {
  3262. return;
  3263. }
  3264. this.offsetX += this.FIX_VP_X;
  3265. this.dragRefOffSetX -= this.FIX_VP_X;
  3266. this.itemMove(index, index - 1)
  3267. }
  3268. right(index: number): void {
  3269. if (!this.isInLeft(index)) {
  3270. return;
  3271. }
  3272. if (!this.isDraggable(index + 1)) {
  3273. return;
  3274. }
  3275. this.offsetX -= this.FIX_VP_X;
  3276. this.dragRefOffSetX += this.FIX_VP_X;
  3277. this.itemMove(index, index + 1)
  3278. }
  3279. private scroller: Scroller = new Scroller();
  3280. @State startIndex: number = 0
  3281. @State endIndex: number = 0
  3282. @State scaleValue: number = 1
  3283. @State pinchValue: number = 1
  3284. layoutOptionsForHeader: GridLayoutOptions = {
  3285. regularSize: [1, 1], // 只支持[1, 1]
  3286. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3287. };
  3288. @Builder
  3289. getGridView() {
  3290. Grid(this.scroller, this.layoutOptionsForHeader) {
  3291. GridItem() {
  3292. if (this.isShowCoverHeader()) {
  3293. this.coverHeader()
  3294. } else {
  3295. this.listViewTitle()
  3296. }
  3297. }
  3298. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3299. GridItem() {
  3300. Stack({ alignContent: Alignment.Center }) {
  3301. this.MusicItemGrid(item, index)
  3302. }
  3303. }
  3304. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3305. TransitionEffect.scale({ x: 0, y: 0 })))
  3306. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3307. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3308. .zIndex(this.dragItem === index ? 1 : 0)
  3309. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3310. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  3311. //长按拖动代码
  3312. .gesture(
  3313. GestureGroup(GestureMode.Sequence,
  3314. LongPressGesture({ repeat: true })
  3315. .onAction(() => {
  3316. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3317. this.scaleItem = index;
  3318. })
  3319. })
  3320. .onActionEnd(() => {
  3321. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3322. this.scaleItem = -1;
  3323. })
  3324. }),
  3325. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3326. .onActionStart(() => {
  3327. this.dragItem = index;
  3328. this.dragRefOffSetX = 0;
  3329. this.dragRefOffSetY = 0;
  3330. })
  3331. .onActionUpdate((event: GestureEvent) => {
  3332. this.offsetX = event.offsetX - this.dragRefOffSetX;
  3333. this.offsetY = event.offsetY - this.dragRefOffSetY;
  3334. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3335. let index = this.videoLocalList.indexOf(item);
  3336. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3337. this.down(index);
  3338. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3339. this.up(index);
  3340. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3341. this.right(index);
  3342. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3343. this.left(index);
  3344. }
  3345. })
  3346. // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  3347. // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  3348. // }
  3349. })
  3350. .onActionEnd(() => {
  3351. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3352. this.dragItem = -1;
  3353. })
  3354. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3355. this.scaleItem = -1;
  3356. })
  3357. })
  3358. )
  3359. .onCancel(() => {
  3360. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3361. this.dragItem = -1;
  3362. })
  3363. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3364. this.scaleItem = -1;
  3365. })
  3366. })
  3367. )
  3368. // [End gesture_start]
  3369. // [EndExclude GridItem_start]
  3370. }, (item: VideoItem) => item.filePath)
  3371. }
  3372. .width(this.isShowHeader ? '100%' : '94%')
  3373. .height('100%')
  3374. .editMode(true)
  3375. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3376. .animation({ duration: 500, curve: Curve.Ease }))
  3377. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3378. .margin({
  3379. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3380. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3381. })
  3382. .layoutWeight(1)
  3383. .scrollBar(BarState.Off)
  3384. .supportAnimation(true)
  3385. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3386. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3387. .columnsTemplate(
  3388. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3389. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3390. )
  3391. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3392. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3393. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3394. .gesture(PinchGesture({ fingers: 2 })
  3395. .onActionEnd((event: GestureEvent) => {
  3396. this.setGridTwoFingers()
  3397. })
  3398. .onActionUpdate(e => {
  3399. this.scaleValue = this.pinchValue * e.scale
  3400. })
  3401. .onActionStart(e => {
  3402. }))
  3403. .enableScrollInteraction(true)
  3404. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3405. .onScrollIndex((start: number, end: number) => {
  3406. this.startIndex = start
  3407. this.endIndex = end
  3408. })
  3409. .onScrollFrameBegin((offset: number) => {
  3410. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3411. // if (this.isPhoneLan()) {
  3412. // this.setBarHeightHide(offset)
  3413. // } else
  3414. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3415. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3416. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3417. if (this.isScrollHide) {
  3418. this.setBarHeightHide2(offset)
  3419. } else {
  3420. this.setBarHeightNormal()
  3421. }
  3422. } else {
  3423. this.setBarHeightHide(offset)
  3424. }
  3425. return { offsetRemain: offset };
  3426. })
  3427. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3428. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3429. .onDrop((event?: DragEvent) => {
  3430. try {
  3431. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3432. if (dragData !== undefined) {
  3433. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3434. if (records.length > 0) {
  3435. for (let i = 0; i < records.length; i++) {
  3436. let types = records[i].getTypes();
  3437. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3438. const fileUriUds =
  3439. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3440. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3441. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3442. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3443. this.targetFile = fileUriUds.oriUri;
  3444. this.saveVideoDatas([this.targetFile])
  3445. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3446. }
  3447. }
  3448. }
  3449. } else {
  3450. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3451. }
  3452. } else {
  3453. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3454. }
  3455. } catch (error) {
  3456. const err = error as BusinessError;
  3457. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3458. }
  3459. })
  3460. }
  3461. @State targetFile: string = '';
  3462. setGridTwoFingers() {
  3463. this.pinchValue = this.scaleValue;
  3464. Logger.info('this.pinchValue = ' + this.pinchValue);
  3465. if (this.pinchValue >= 1) {
  3466. this.twoFingerType++
  3467. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3468. if (this.twoFingerType > 3) {
  3469. this.twoFingerType = 3
  3470. }
  3471. } else {
  3472. this.twoFingerType--
  3473. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3474. if (this.twoFingerType < 1) {
  3475. this.twoFingerType = 3
  3476. this.isGridMusic = false
  3477. }
  3478. }
  3479. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3480. this.pinchValue = 1;
  3481. this.scaleValue = 1;
  3482. }
  3483. @State longItemFilePath: string = ''
  3484. @State tempLyricContent: string = ''
  3485. @Builder
  3486. private MusicItemGrid(item: VideoItem, index: number) {
  3487. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3488. Stack() {
  3489. Column() {
  3490. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3491. .height(this.getGridHeight())
  3492. .width(this.getGridWight())
  3493. .alt($r('app.media.ic_avatar2'))
  3494. .clip(true)
  3495. .borderRadius({
  3496. topLeft: 12,
  3497. topRight: 12,
  3498. bottomLeft: 0,
  3499. bottomRight: 0
  3500. })
  3501. .draggable(false)
  3502. .opacity(this.opacityItem)// 绑定透明度
  3503. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3504. // .animation({ duration: 500, curve: Curve.Ease }))
  3505. .animation({
  3506. duration: 666,
  3507. curve: 'ease-in-out' // 可选动画曲线
  3508. })
  3509. .margin({
  3510. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3511. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3512. })
  3513. Column() {
  3514. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3515. .fontSize(this.twoFingerType == 1 ? 14 : this.twoFingerType == 2 ? 16 : 18)
  3516. .maxLines(1)
  3517. .fontWeight(FontWeight.Bold)
  3518. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3519. .animation({
  3520. duration: 555,
  3521. curve: 'Linear',
  3522. })
  3523. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3524. $r('app.color.text_color'))
  3525. Column() {
  3526. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3527. .fontSize(11)
  3528. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3529. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3530. .fontColor($r('app.color.text_color'))
  3531. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3532. .fontSize(11)
  3533. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3534. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3535. .fontColor($r('app.color.text_color'))
  3536. Row(){
  3537. Column(){
  3538. Text(item.md5Str?.includes('Lossless')?
  3539. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3540. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3541. .padding({ top: 3,right:6,left:6,bottom:3 })
  3542. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3543. $r('app.color.text_color'))
  3544. .fontWeight(500)
  3545. .borderRadius(12)
  3546. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3547. .backgroundColor('#FFC107')
  3548. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  3549. }
  3550. .margin({ top: 2 ,right:6})
  3551. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3552. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3553. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3554. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3555. .maxLines(1)
  3556. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3557. .margin({ top: 2})
  3558. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3559. || item.type == CommonConstants.TYPE_IS_ALBUM
  3560. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3561. .fontWeight(FontWeight.Medium)
  3562. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3563. $r('app.color.text_color'))
  3564. }
  3565. }
  3566. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3567. }
  3568. .bindPopup(this.longItemFilePath === item.filePath, {
  3569. builder: this.MenuBuilder(item, index, item.filePath),
  3570. placement: Placement.Top,
  3571. // autoCancel: true,
  3572. mask: { color: '#33000000' },
  3573. // popupColor: Color.Yellow,
  3574. enableArrow: false, //是否显示箭头
  3575. showInSubWindow: false,
  3576. onStateChange: (e) => {
  3577. if (!e.isVisible) {
  3578. this.longItemFilePath = ''
  3579. this.tempLyricContent = ''
  3580. }
  3581. }
  3582. })
  3583. .gesture(LongPressGesture()
  3584. .onAction(async () => {
  3585. //如果是专辑和艺术家的首页,不能长按
  3586. if ((this.modeType === 2 || this.modeType == 3) && !this.isCanBack) {
  3587. return
  3588. }
  3589. //如果是我的收藏 最近播放等也不能长按
  3590. if (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3591. item.name === LocalMusic.STR_HISTORY_MUSIC
  3592. ) {
  3593. return
  3594. }
  3595. this.longItemFilePath = item.filePath
  3596. this.tempLyricContent = await this.getLyricContent(item)
  3597. LogUtil.info('长按this.tempLyricContent = ' + this.tempLyricContent)
  3598. })
  3599. .onActionEnd((event: GestureEvent) => {
  3600. })
  3601. )
  3602. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 55 : 42)
  3603. .width(this.getGridWight())
  3604. .justifyContent(FlexAlign.Center)
  3605. .margin({
  3606. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3607. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3608. })
  3609. }
  3610. .width(this.getGridWight())
  3611. .borderRadius(12)
  3612. .backgroundImage(item.pixelMapPath)
  3613. .backgroundImageSize({ height: '100%', width: '100%' })
  3614. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3615. .animation({ curve: Curve.Sharp, duration: 300 })
  3616. Checkbox({ name: 'checkbox' + index })
  3617. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3618. .selectedColor(this.themeColor)
  3619. .shape(CheckBoxShape.CIRCLE)
  3620. .opacity(this.isMultiSelect ? 1 : 0)
  3621. .animation({
  3622. duration: 666,
  3623. curve: 'Smooth' // 可选动画曲线
  3624. })
  3625. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3626. Visibility.None)
  3627. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3628. .margin({ left: 20, top: 8, bottom: 8 })
  3629. .width(38)
  3630. .height(38)
  3631. }
  3632. }
  3633. .backgroundColor(Color.Transparent)
  3634. .width('100%')
  3635. .padding({ top: 15 })
  3636. .height(this.getGridAllHeight())
  3637. .onClick(() => {
  3638. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3639. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3640. this.handleFileSelection(item, !isChecked);
  3641. } else {
  3642. this.doPlay(item, index)
  3643. }
  3644. })
  3645. }
  3646. getGridAllHeight() {
  3647. let heightG = 222
  3648. switch (this.twoFingerType) {
  3649. case 1:
  3650. heightG = 118
  3651. break;
  3652. case 2:
  3653. heightG = 168
  3654. break;
  3655. case 3:
  3656. heightG = 222
  3657. break;
  3658. }
  3659. return heightG
  3660. }
  3661. getGridHeight() {
  3662. let heightG = 150
  3663. switch (this.twoFingerType) {
  3664. case 1:
  3665. heightG = 55
  3666. break;
  3667. case 2:
  3668. heightG = 100
  3669. break;
  3670. case 3:
  3671. heightG = 150
  3672. break;
  3673. }
  3674. return heightG
  3675. }
  3676. getGridWight() {
  3677. let wightG = 158
  3678. switch (this.twoFingerType) {
  3679. case 1:
  3680. wightG = 80
  3681. break;
  3682. case 2:
  3683. wightG = 110
  3684. break;
  3685. case 3:
  3686. wightG = 158
  3687. break;
  3688. }
  3689. return wightG
  3690. }
  3691. @State isShowDetail:boolean = false
  3692. @Builder
  3693. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3694. Scroll() {
  3695. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3696. Menu() {
  3697. MenuItem({
  3698. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3699. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3700. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3701. })
  3702. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3703. .onClick(() => {
  3704. if (item) {
  3705. this.doFav(item)
  3706. }
  3707. this.longItemFilePath = ''
  3708. })
  3709. MenuItem({
  3710. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3711. content: '下一首播放'
  3712. })
  3713. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3714. .onClick(() => {
  3715. this.addToNextPlay(item);
  3716. this.longItemFilePath = ''
  3717. })
  3718. MenuItem({
  3719. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3720. content: '编辑信息'
  3721. })
  3722. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3723. height: this.isCoverOpacity() ? '95%' : '88%',
  3724. dragBar: true,
  3725. showClose: true,
  3726. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3727. title: { title: '编辑信息' }
  3728. })
  3729. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3730. .onClick(() => {
  3731. this.isShowEdit = !this.isShowEdit;
  3732. })
  3733. MenuItem({
  3734. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3735. content: $r('app.string.rename')
  3736. })
  3737. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3738. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3739. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3740. .onClick(() => {
  3741. this.showReNameDialog(item, index + '', filePath)
  3742. this.longItemFilePath = ''
  3743. })
  3744. MenuItem({
  3745. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3746. content: $r('app.string.delete')
  3747. })
  3748. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3749. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3750. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3751. .onClick(() => {
  3752. this.showWarnIsDeleteFile(item, index + '', filePath)
  3753. this.longItemFilePath = ''
  3754. })
  3755. MenuItem({
  3756. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3757. content: $r('app.string.detail')
  3758. })
  3759. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3760. height:this.isCoverOpacity()?'95%': '95%',
  3761. dragBar: true,
  3762. showClose: true,
  3763. blurStyle:BlurStyle.Thin,
  3764. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3765. backgroundColor:Color.Transparent,
  3766. title: { title: '详情信息' }
  3767. })
  3768. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3769. .onClick(() => {
  3770. this.isShowDetail = !this.isShowDetail
  3771. })
  3772. MenuItem({
  3773. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3774. content: $r('app.string.share')
  3775. })
  3776. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3777. .onClick(() => {
  3778. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3779. this.longItemFilePath = ''
  3780. })
  3781. }
  3782. .font({ size: 15, weight: FontWeight.Normal })
  3783. }
  3784. .width(180)
  3785. }
  3786. .height(item.type === CommonConstants.TYPE_IS_DIR ? 150 : 400)
  3787. }
  3788. private listMaxScrollOffsetY: number = 0
  3789. @State selectedIndex: number = -1
  3790. setlistTwoFingers() {
  3791. this.pinchValue = this.scaleValue;
  3792. Logger.info('this.pinchValue = ' + this.pinchValue);
  3793. if (this.pinchValue >= 1) {
  3794. this.twoFingerType++
  3795. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3796. if (this.twoFingerType > 3) {
  3797. this.twoFingerType = 1
  3798. this.isGridMusic = true
  3799. }
  3800. } else {
  3801. this.twoFingerType--
  3802. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3803. if (this.twoFingerType < 1) {
  3804. this.twoFingerType = 1
  3805. }
  3806. }
  3807. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3808. this.pinchValue = 1;
  3809. this.scaleValue = 1;
  3810. }
  3811. @Builder
  3812. getListView() {
  3813. List({ scroller: this.listScroller }) {
  3814. ListItemGroup({ header: this.coverHeader() }) {
  3815. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3816. ListItem() {
  3817. Column() {
  3818. if (item.type === CommonConstants.TYPE_IS_DIR
  3819. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3820. this.DirItem(item, index)
  3821. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3822. } else {
  3823. this.MusicItem(item, index)
  3824. }
  3825. }
  3826. .shadow(this.scaleItem === index ? {
  3827. radius: 70,
  3828. color: '#15000000',
  3829. offsetX: 0,
  3830. offsetY: 0
  3831. } :
  3832. {
  3833. radius: 0,
  3834. color: '#15000000',
  3835. offsetX: 0,
  3836. offsetY: 0
  3837. })
  3838. .animation({ curve: Curve.Sharp, duration: 300 })
  3839. }
  3840. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3841. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3842. .animation({ duration: 500 }),
  3843. TransitionEffect.scale({ x: 0, y: 0 })))
  3844. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3845. .swipeAction((
  3846. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3847. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3848. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3849. .onClick(() => {
  3850. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3851. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3852. this.handleFileSelection(item, !isChecked);
  3853. } else {
  3854. this.doPlay(item, index)
  3855. }
  3856. })
  3857. //拖动List关键代码开始
  3858. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3859. .zIndex(this.dragItem === index ? 1 : 0)
  3860. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3861. .gesture(
  3862. GestureGroup(GestureMode.Sequence,
  3863. LongPressGesture({ repeat: true })
  3864. .onAction((event?: GestureEvent) => {
  3865. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3866. this.scaleItem = index
  3867. })
  3868. })
  3869. .onActionEnd(() => {
  3870. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3871. this.scaleItem = -1
  3872. })
  3873. }),
  3874. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3875. .onActionStart(() => {
  3876. this.dragItem = index // 记录当前拖动项索引
  3877. this.dragRefOffset = 0 // 重置偏移基准
  3878. })
  3879. .onActionUpdate((event: GestureEvent) => {
  3880. this.offsetY = event.offsetY - this.dragRefOffset;
  3881. this.neighborItem = -1;
  3882. let indexA = this.videoLocalList.indexOf(item);
  3883. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3884. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3885. let value: number = 0;
  3886. if (this.offsetY < 0) {
  3887. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3888. this.neighborItem = indexA - 1;
  3889. this.neighborScale = 1 - value / 20;
  3890. } else if (this.offsetY > 0) {
  3891. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3892. this.neighborItem = indexA + 1;
  3893. this.neighborScale = 1 - value / 20;
  3894. }
  3895. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3896. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3897. this.offsetY -= this.ITEM_INTV;
  3898. this.dragRefOffset += this.ITEM_INTV;
  3899. this.itemMove(indexA, indexA + 1);
  3900. });
  3901. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3902. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3903. this.offsetY += this.ITEM_INTV;
  3904. this.dragRefOffset -= this.ITEM_INTV;
  3905. this.itemMove(indexA, indexA - 1);
  3906. });
  3907. }
  3908. let curListOffset = this.listScroller.currentOffset()
  3909. // 获取手指信息
  3910. let fingerInfo = event.fingerList[0]
  3911. let clickPercentY =
  3912. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3913. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3914. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3915. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3916. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  3917. }
  3918. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3919. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3920. if (curListOffset.yOffset > scrollVelocity + 5) {
  3921. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  3922. }
  3923. }
  3924. })
  3925. .onActionEnd((event: GestureEvent) => {
  3926. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3927. this.dragItem = -1
  3928. this.neighborItem = -1
  3929. })
  3930. animateTo({
  3931. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3932. }, () => {
  3933. this.scaleItem = -1
  3934. })
  3935. })
  3936. )
  3937. .onCancel(() => {
  3938. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3939. this.dragItem = -1
  3940. this.neighborItem = -1
  3941. })
  3942. animateTo({
  3943. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3944. }, () => {
  3945. this.scaleItem = -1
  3946. })
  3947. })
  3948. ) //拖动List关键代码结束
  3949. }, (item: VideoItem) => item.filePath)
  3950. }
  3951. }
  3952. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3953. .gesture(PinchGesture({ fingers: 2 })
  3954. .onActionEnd((event: GestureEvent) => {
  3955. this.setlistTwoFingers()
  3956. })
  3957. .onActionUpdate(e => {
  3958. this.scaleValue = this.pinchValue * e.scale
  3959. })
  3960. .onActionStart(e => {
  3961. }))
  3962. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3963. .margin({
  3964. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  3965. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+125)
  3966. })
  3967. .cachedCount(6)
  3968. .borderRadius(20)
  3969. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3970. TransitionEffect.scale({ x: 0, y: 0 })))
  3971. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3972. // .animation({ duration: 500, curve: Curve.Ease }))
  3973. .layoutWeight(1)
  3974. .onScrollIndex((start) => {
  3975. this.selectedIndex = start
  3976. })
  3977. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  3978. .lanes(
  3979. new BreakpointType<number>({
  3980. sm: 1,
  3981. md: 2,
  3982. lg: 2,
  3983. xl: 3,
  3984. xxl: 4
  3985. }).getValue(this.currentBreakpoint),
  3986. new BreakpointType<number>({
  3987. sm: 0,
  3988. md: 12,
  3989. lg: 12,
  3990. xl: 16,
  3991. xxl: 20
  3992. }).getValue(this.currentBreakpoint)
  3993. )
  3994. .onAreaChange((oldValue: Area, newValue: Area) => {
  3995. this.listArea = newValue
  3996. if (this.twoFingerType == 3) {
  3997. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3998. } else if (this.twoFingerType == 2) {
  3999. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  4000. } else if (this.twoFingerType == 1) {
  4001. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  4002. }
  4003. })
  4004. .onScrollFrameBegin((offset: number) => {
  4005. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  4006. // if (this.isPhoneLan()) {
  4007. // this.setBarHeightHide(offset)
  4008. // } else
  4009. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4010. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4011. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4012. if (this.isScrollHide) {
  4013. this.setBarHeightHide2(offset)
  4014. } else {
  4015. this.setBarHeightNormal()
  4016. }
  4017. } else {
  4018. this.setBarHeightHide(offset)
  4019. }
  4020. return { offsetRemain: offset };
  4021. })
  4022. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  4023. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4024. .onDrop((event?: DragEvent) => {
  4025. try {
  4026. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4027. if (dragData !== undefined) {
  4028. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4029. if (records.length > 0) {
  4030. for (let i = 0; i < records.length; i++) {
  4031. let types = records[i].getTypes();
  4032. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4033. const fileUriUds =
  4034. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4035. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4036. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4037. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4038. this.targetFile = fileUriUds.oriUri;
  4039. this.saveVideoDatas([this.targetFile])
  4040. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4041. }
  4042. }
  4043. }
  4044. } else {
  4045. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4046. }
  4047. } else {
  4048. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4049. }
  4050. } catch (error) {
  4051. const err = error as BusinessError;
  4052. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4053. }
  4054. })
  4055. }
  4056. setBarHeightNormal() {
  4057. this.hideDone = false;
  4058. this.getUIContext().animateTo({
  4059. duration: 300
  4060. }, () => {
  4061. this.bottomBarHeight = 55 + 0;
  4062. this.topBarHeight = 50 + 0;
  4063. this.barOpacity = 1;
  4064. this.barBottomOpacity = 1
  4065. this.currentYOffset = 0;
  4066. this.isHiding = false;
  4067. });
  4068. }
  4069. setBarHeightHide(offset: number) {
  4070. if (offset > 0 && !this.hideDone) {
  4071. this.currentYOffset += offset;
  4072. if (this.currentYOffset <= 100) {
  4073. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  4074. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4075. this.barOpacity = 1 - this.currentYOffset / 100;
  4076. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  4077. } else {
  4078. this.topBarHeight = 0;
  4079. this.bottomBarHeight = 0;
  4080. this.barBottomOpacity = 0
  4081. this.barOpacity = 0;
  4082. this.hideDone = true;
  4083. }
  4084. this.isHiding = true;
  4085. }
  4086. if (offset < 0 && this.isHiding) {
  4087. this.hideDone = false;
  4088. this.getUIContext().animateTo({
  4089. duration: 300
  4090. }, () => {
  4091. this.bottomBarHeight = 55 + 0;
  4092. this.topBarHeight = 50 + 0;
  4093. this.barOpacity = 1;
  4094. this.barBottomOpacity = 1
  4095. this.currentYOffset = 0;
  4096. this.isHiding = false;
  4097. });
  4098. }
  4099. }
  4100. //这个方法没隐藏bottomBar,只隐藏topbar
  4101. setBarHeightHide2(offset: number) {
  4102. if (offset > 0 && !this.hideDone) {
  4103. this.currentYOffset += offset;
  4104. if (this.currentYOffset <= 100) {
  4105. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4106. this.barOpacity = 1 - this.currentYOffset / 100;
  4107. } else {
  4108. this.topBarHeight = 0;
  4109. this.barOpacity = 0;
  4110. this.hideDone = true;
  4111. }
  4112. this.isHiding = true;
  4113. }
  4114. if (offset < 0 && this.isHiding) {
  4115. this.hideDone = false;
  4116. this.getUIContext().animateTo({
  4117. duration: 300
  4118. }, () => {
  4119. this.topBarHeight = 50 + 0;
  4120. this.barOpacity = 1;
  4121. this.currentYOffset = 0;
  4122. this.isHiding = false;
  4123. });
  4124. }
  4125. }
  4126. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  4127. switch (item.type) {
  4128. case CommonConstants.TYPE_IS_DIR:
  4129. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  4130. let offsetB = 0
  4131. if (this.isGridMusic) {
  4132. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4133. let cur = this.scroller.currentOffset()
  4134. if (cur && typeof cur.yOffset === 'number') {
  4135. offsetB = cur.yOffset
  4136. }
  4137. }
  4138. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  4139. } else {
  4140. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4141. let cur = this.listScroller.currentOffset()
  4142. if (cur && typeof cur.yOffset === 'number') {
  4143. offsetB = cur.yOffset
  4144. }
  4145. }
  4146. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  4147. }
  4148. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  4149. this.showVerifyDialog()
  4150. this.currentTitleName = '私密音频'
  4151. this.currentTitleCover = $r('app.media.ic_avatar5')
  4152. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  4153. this.titleBarModel.setTitleName('最近播放')
  4154. this.currentTitleCover = $r('app.media.ic_avatar2')
  4155. this.currentTitleName = '最近播放'
  4156. //加载动画效果
  4157. this.updateListData(this.historyList, true)
  4158. // this.videoLocalList = this.historyList
  4159. if (ArrayUtil.isEmpty(this.historyList)) {
  4160. ToastUtil.showToast('最近播放记录空空如也')
  4161. } else {
  4162. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  4163. }
  4164. this.isHistory = true
  4165. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4166. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  4167. this.titleBarModel.setTitleName('我的收藏')
  4168. this.currentTitleName = '我的收藏'
  4169. this.currentTitleCover = $r('app.media.ic_avatar1')
  4170. //加载动画效果
  4171. this.updateListData(this.favList)
  4172. if (ArrayUtil.isEmpty(this.favList)) {
  4173. ToastUtil.showToast('无音乐收藏记录')
  4174. } else {
  4175. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  4176. }
  4177. this.isFavMusic = true
  4178. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4179. } else {
  4180. this.currentTitleName = item.name
  4181. this.currentPath = item.filePath
  4182. this.currentTitleCover = $r('app.media.ic_avatar5')
  4183. this.getSortedFiles(this.currentPath)
  4184. }
  4185. //进入歌单的时候的滚动位置在顶部
  4186. if (this.isGridMusic) {
  4187. this.scroller.scrollToIndex(0)
  4188. }
  4189. setTimeout(() => {
  4190. if (this.modeType == 0) {
  4191. if (!this.isGridMusic) {
  4192. this.listScroller.scrollToIndex(0)
  4193. }
  4194. }
  4195. }, 200)
  4196. break;
  4197. case CommonConstants.TYPE_IS_ARTIST:
  4198. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  4199. let offsetA = 0
  4200. if (this.isGridMusic) {
  4201. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4202. let cur = this.scroller.currentOffset()
  4203. if (cur && typeof cur.yOffset === 'number') {
  4204. offsetA = cur.yOffset
  4205. }
  4206. }
  4207. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  4208. } else {
  4209. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4210. let cur = this.listScroller.currentOffset()
  4211. if (cur && typeof cur.yOffset === 'number') {
  4212. offsetA = cur.yOffset
  4213. }
  4214. }
  4215. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  4216. }
  4217. let mList = this.artistMap.get(item.name)
  4218. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  4219. Utility.doSortListAscending(mList)
  4220. this.isCanBack = true
  4221. this.titleBarModel.setTitleName(item.name)
  4222. this.currentTitleName = '艺术家:' + item.name
  4223. if (item.pixelMapPath) {
  4224. this.currentTitleCover = item.pixelMapPath
  4225. }
  4226. this.updateListData(mList)
  4227. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4228. }
  4229. //进入歌单的时候的滚动位置在顶部
  4230. if (this.isGridMusic) {
  4231. this.scroller.scrollToIndex(0)
  4232. }
  4233. break;
  4234. case CommonConstants.TYPE_IS_ALBUM:
  4235. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  4236. let offset = 0
  4237. if (this.isGridMusic) {
  4238. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4239. let cur = this.scroller.currentOffset()
  4240. if (cur && typeof cur.yOffset === 'number') {
  4241. offset = cur.yOffset
  4242. }
  4243. }
  4244. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  4245. } else {
  4246. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4247. let cur = this.listScroller.currentOffset()
  4248. if (cur && typeof cur.yOffset === 'number') {
  4249. offset = cur.yOffset
  4250. }
  4251. }
  4252. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4253. }
  4254. let albumList = this.albumMap.get(item.name)
  4255. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4256. Utility.doSortListAscending(albumList)
  4257. this.isCanBack = true
  4258. this.titleBarModel.setTitleName(item.name)
  4259. this.currentTitleName = '专辑:' + item.name
  4260. if (item.pixelMapPath) {
  4261. this.currentTitleCover = item.pixelMapPath
  4262. }
  4263. this.updateListData(albumList)
  4264. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4265. this.mScrollMap.set(item.name, this.selectedIndex)
  4266. }
  4267. //进入歌单的时候的滚动位置在顶部
  4268. if (this.isGridMusic) {
  4269. this.scroller.scrollToIndex(0)
  4270. }
  4271. break;
  4272. case CommonConstants.TYPE_IS_CSJAD:
  4273. return
  4274. case CommonConstants.TYPE_LOCAL:
  4275. // 移除自动停止逻辑,让UnifiedPlayerService处理播放器状态管理
  4276. // if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4277. // this.stop();
  4278. // }
  4279. // 检查是否正在投播
  4280. if (this.isCurrentlyCasting()) {
  4281. // 更新当前歌曲信息
  4282. this.curIndex = index as number;
  4283. this.currentSong = item;
  4284. this.videoUrl = this.currentSong.filePath;
  4285. this.artist = this.currentSong.artist;
  4286. this.name = this.currentSong.name;
  4287. this.cover = this.currentSong.pixelMapPath;
  4288. this.changeCasting();
  4289. return;
  4290. }
  4291. if (isFromSonPlayList) { //点击来自右下角的播放列表
  4292. this.currentSong = item
  4293. if (index !== undefined) {
  4294. this.curIndex = index
  4295. }
  4296. } else {
  4297. // 点击文件列表中的歌曲,需要判断是否要创建新的播放列表
  4298. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4299. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4300. // 检查当前播放列表是否包含这首歌
  4301. const currentSongIndex = this.songList.findIndex(song => song.filePath === item.filePath);
  4302. if (currentSongIndex >= 0 && ArrayUtil.isNotEmpty(this.songList)) {
  4303. // 如果当前播放列表已经包含这首歌,使用现有播放列表
  4304. this.curIndex = currentSongIndex;
  4305. this.currentSong = this.songList[this.curIndex];
  4306. } else {
  4307. // 如果当前播放列表不包含这首歌,或者没有播放列表,则创建新的
  4308. this.songList = globalVideoList;
  4309. this.sonDataSource.pushArrayData(this.songList);
  4310. this.currentSong = globalVideoList[this.curIndex];
  4311. }
  4312. }
  4313. this.videoUrl = this.currentSong.filePath
  4314. this.name = this.currentSong.name
  4315. this.cover = this.currentSong.pixelMapPath
  4316. this.artist = this.currentSong.artist
  4317. // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  4318. this.oldSeconds = 0;
  4319. this.currentTime = "00:00";
  4320. this.currentTime = "00:00";
  4321. this.lastSongPath = this.currentSong.filePath;
  4322. this.justSwitched = true; // 标记歌曲刚刚切换
  4323. // 同步播放列表到UnifiedPlayerService
  4324. this.syncPlaylistToService();
  4325. this.startPlayOrResumePlay()
  4326. break;
  4327. }
  4328. }
  4329. @Builder
  4330. PlayController() {
  4331. Column() {
  4332. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4333. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4334. Row() {
  4335. Row() {
  4336. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  4337. Column() {
  4338. Text(this.currentSong?.name)
  4339. .fontSize(16)
  4340. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4341. .maxLines(1)
  4342. .fontColor($r('app.color.text_color'))
  4343. .fontWeight(500)
  4344. Row() {
  4345. Text(this.currentSong?.artist)
  4346. .margin({ top: 2 })
  4347. .fontSize(13)
  4348. .maxLines(1)
  4349. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4350. .fontColor($r('app.color.text_color'))
  4351. }
  4352. }
  4353. .alignItems(HorizontalAlign.Start)
  4354. .margin({ right: 22 })
  4355. }
  4356. .padding({ right: 18 })
  4357. .layoutWeight(1)
  4358. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4359. .onClick(() => {
  4360. if (ArrayUtil.isNotEmpty(this.songList)) {
  4361. this.isShowPlay = true;
  4362. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4363. this.initLyric(lyricPath);
  4364. this.startAutoHide()
  4365. } else {
  4366. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4367. }
  4368. })
  4369. Row() {
  4370. Image($r('app.media.hm_previous'))
  4371. .height(28)
  4372. .width(28)
  4373. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4374. .margin({ left: 8, right: 16 })
  4375. .fillColor(this.themeColor)
  4376. .displayPriority(2)
  4377. .onClick(() => {
  4378. if (ArrayUtil.isNotEmpty(this.songList)) {
  4379. this.playPrevious()
  4380. } else {
  4381. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4382. }
  4383. })
  4384. //播放进度条
  4385. Stack() {
  4386. Progress({
  4387. value: Math.floor(this.progressValue),
  4388. type: ProgressType.Ring,
  4389. })
  4390. .color(this.themeColor)// 进度条前景色为灰色
  4391. .backgroundColor($r('app.color.index_background'))
  4392. .height(40)
  4393. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4394. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4395. .height(38)
  4396. .width(38)
  4397. .displayPriority(3)
  4398. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4399. .fillColor(this.themeColor)
  4400. .onClick(() => {
  4401. if (ArrayUtil.isNotEmpty(this.songList)) {
  4402. this.playOrPause()
  4403. } else {
  4404. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4405. }
  4406. })
  4407. }
  4408. Image($r('app.media.hm_next'))
  4409. .height(28)
  4410. .width(28)
  4411. .margin({
  4412. right: 16,
  4413. left: 16
  4414. })
  4415. .fillColor(this.themeColor)
  4416. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4417. .displayPriority(2)
  4418. .onClick(() => {
  4419. if (ArrayUtil.isNotEmpty(this.songList)) {
  4420. this.playNext()
  4421. } else {
  4422. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4423. }
  4424. })
  4425. Image($r('app.media.hm_playlist'))
  4426. .height(28)
  4427. .width(28)
  4428. .displayPriority(1)
  4429. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4430. .fillColor(this.themeColor)
  4431. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4432. height: '95%',
  4433. dragBar: true,
  4434. showClose: true,
  4435. blurStyle: BlurStyle.Thin,
  4436. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4437. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4438. title: {
  4439. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4440. + `(${this.songList.length}首)`
  4441. }
  4442. })
  4443. .onClick(() => {
  4444. if (ArrayUtil.isNotEmpty(this.songList)) {
  4445. this.isShowSheet = !this.isShowSheet;
  4446. this.isFrontWhite = false
  4447. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4448. setTimeout(() => {
  4449. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  4450. }, 123)
  4451. } else {
  4452. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4453. }
  4454. })
  4455. }
  4456. }
  4457. .width('100%')
  4458. .height(this.bottomBarHeight)
  4459. .justifyContent(FlexAlign.Center)
  4460. .hitTestBehavior(HitTestMode.Transparent)
  4461. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4462. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4463. // modalTransition: ModalTransition.DEFAULT,
  4464. transition: AnimationHelper.transitionInDown(666),
  4465. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4466. })
  4467. .padding({
  4468. left: 16,
  4469. right: 16
  4470. })
  4471. Line()
  4472. .width('100%')
  4473. .height(25)
  4474. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4475. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4476. }
  4477. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4478. }
  4479. @State isFrontWhite: boolean = false
  4480. //播放列表布局
  4481. @Builder
  4482. PlayListSheet() {
  4483. Column() {
  4484. this.PlayList()
  4485. }
  4486. .width('100%')
  4487. .height('100%')
  4488. .onAppear(() => {
  4489. // 播放列表显示时刷新封面信息
  4490. this.refreshPlaylistCovers();
  4491. })
  4492. }
  4493. @State titleStr: string = ''
  4494. @State ablumStr: string = ''
  4495. @State artistStr: string = ''
  4496. @State lyricConStr: string = ''
  4497. @State currentEditItem: string = ''
  4498. doUpdateData() {
  4499. setTimeout(() => {
  4500. if (this.modeType === 0) {
  4501. this.deleteCache(this.currentPath)
  4502. this.getSortedFiles(this.currentPath)
  4503. }
  4504. workerInstance.postMessage({ code: 2, data: this.context });
  4505. workerInstance.postMessage({ code: 3, data: this.context });
  4506. workerInstance.postMessage({ code: 4, data: this.context });
  4507. }, 999)
  4508. }
  4509. //编辑信息
  4510. doEdit(item: VideoItem) {
  4511. if (!item) {
  4512. return
  4513. }
  4514. if (StrUtil.isEmpty(this.titleStr)) {
  4515. ToastUtil.showToast('标题不能为空')
  4516. return
  4517. }
  4518. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  4519. (success: boolean, error?: string) => {
  4520. this.isShowEdit = false
  4521. if (success) {
  4522. console.log(" onecold 编辑信息成功,数据库已同步");
  4523. ToastUtil.showToast('保存成功')
  4524. this.isShowMoreView = false
  4525. this.name = this.titleStr
  4526. if (item.filePath == this.currentSong?.filePath) {
  4527. this.currentSong.name = this.titleStr
  4528. this.artist = this.artistStr
  4529. this.currentSong.artist = this.artistStr
  4530. this.currentSong.album = this.ablumStr
  4531. }
  4532. this.doUpdateData()
  4533. } else {
  4534. ToastUtil.showToast('保存失败' + error?.toString())
  4535. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4536. }
  4537. });
  4538. let doChangeLyric = false
  4539. if (item.filePath == this.currentSong?.filePath) {
  4540. if (this.lyricConStr !== this.lyricContent) {
  4541. doChangeLyric = true
  4542. }
  4543. } else if (this.lyricConStr !== this.tempLyricContent) {
  4544. doChangeLyric = true
  4545. }
  4546. if (doChangeLyric) {
  4547. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4548. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4549. let isJiaMi = false;
  4550. let realLyricPath = lyricPath
  4551. if (FileUtil.accessSync(jiaMilyricPath)) {
  4552. isJiaMi = true
  4553. realLyricPath = jiaMilyricPath
  4554. console.info("onecold doEdit找到加密本地歌词 ");
  4555. } else {
  4556. isJiaMi = false
  4557. realLyricPath = lyricPath
  4558. console.info("onecold doEdit本地歌词 ");
  4559. }
  4560. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  4561. }
  4562. }
  4563. updateLyricToDB() {
  4564. }
  4565. @Builder
  4566. editSheet(item: VideoItem) {
  4567. Scroll() {
  4568. Column() {
  4569. this.editDetail(item)
  4570. }
  4571. }
  4572. .width('100%')
  4573. .height('100%')
  4574. }
  4575. @Builder
  4576. editDetail(item: VideoItem) {
  4577. Column() {
  4578. if (item) {
  4579. Row() {
  4580. Stack() {
  4581. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4582. item.pixelMapPath)
  4583. .fillColor(this.themeColor)
  4584. .height(33)
  4585. .width(33)
  4586. .borderRadius('100%')
  4587. .clip(true)
  4588. .opacity(this.opacityItem)// 绑定透明度
  4589. .margin({ left: 20 })
  4590. }
  4591. .width('15%')
  4592. Row() {
  4593. Column() {
  4594. Text(item.name)
  4595. .fontSize(14)
  4596. .maxLines(1)
  4597. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4598. .animation({
  4599. duration: 555,
  4600. curve: 'Linear',
  4601. })
  4602. .fontColor(this.themeColor)
  4603. .margin({ left: 10 })
  4604. Row() {
  4605. Text(item.artist)
  4606. .fontSize(11)
  4607. .maxLines(1)
  4608. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4609. .padding({ top: 8 })
  4610. .fontColor(this.themeColor)
  4611. .margin({ left: 10 })
  4612. }
  4613. }
  4614. .height('100%')
  4615. .width(100)
  4616. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4617. .justifyContent(FlexAlign.Center)
  4618. .alignItems(HorizontalAlign.Start)
  4619. Button('本地封面')
  4620. .fontColor(Color.White)
  4621. .fontSize(12)
  4622. .height(38)
  4623. .width(88)
  4624. .backgroundColor(this.themeColor)
  4625. .stateEffect(true)
  4626. .margin({ right: 5, left: 12 })
  4627. .onClick(async () => {
  4628. this.goSelectImage(item)
  4629. })
  4630. Button('获取封面')
  4631. .fontColor(Color.White)
  4632. .fontSize(12)
  4633. .height(38)
  4634. .width(88)
  4635. .backgroundColor(this.themeColor)
  4636. .stateEffect(true)
  4637. .margin({ right: 12, left: 5 })
  4638. .onClick(async () => {
  4639. this.doSearchCover(item)
  4640. })
  4641. }
  4642. .height('100%')
  4643. .justifyContent(FlexAlign.Start)
  4644. .layoutWeight(1)
  4645. }
  4646. .width('100%')
  4647. .height(58)
  4648. Row() {
  4649. Text('标题:')
  4650. .fontSize(14)
  4651. .fontColor($r('app.color.text_color'))
  4652. .margin({ left: 22 })
  4653. TextInput({ text: item.name })
  4654. .height(40)
  4655. .maxLines(1)
  4656. .fontSize(14)
  4657. .layoutWeight(1)
  4658. .fontColor($r('app.color.text_color'))
  4659. .margin({ right: 20, left: 10 })
  4660. .onChange((val: string) => {
  4661. this.titleStr = val
  4662. })
  4663. }
  4664. .width('100%')
  4665. .margin({ top: 10, bottom: 10 })
  4666. .justifyContent(FlexAlign.Start)
  4667. Row() {
  4668. Text('艺术家:')
  4669. .fontSize(14)
  4670. .fontColor($r('app.color.text_color'))
  4671. .margin({ left: 22 })
  4672. TextInput({ text: item.artist })
  4673. .height(40)
  4674. .maxLines(1)
  4675. .fontSize(14)
  4676. .layoutWeight(1)
  4677. .fontColor($r('app.color.text_color'))
  4678. .margin({ right: 20, left: 10 })
  4679. .onChange((val: string) => {
  4680. this.artistStr = val
  4681. })
  4682. }
  4683. .width('100%')
  4684. .margin({ top: 10, bottom: 10 })
  4685. .justifyContent(FlexAlign.Start)
  4686. Row() {
  4687. Text('专辑名:')
  4688. .fontSize(14)
  4689. .fontColor($r('app.color.text_color'))
  4690. .margin({ left: 22 })
  4691. TextInput({ text: item.album })
  4692. .height(40)
  4693. .maxLines(1)
  4694. .fontSize(14)
  4695. .layoutWeight(1)
  4696. .fontColor($r('app.color.text_color'))
  4697. .margin({ right: 20, left: 10 })
  4698. .onChange((val: string) => {
  4699. this.ablumStr = val
  4700. })
  4701. }
  4702. .width('100%')
  4703. .margin({ top: 10, bottom: 10 })
  4704. .justifyContent(FlexAlign.Start)
  4705. Row() {
  4706. Text('歌词:')
  4707. .fontSize(14)
  4708. .fontColor($r('app.color.text_color'))
  4709. .margin({ left: 22 })
  4710. TextArea({ text: item.filePath === this.currentSong?.filePath ? this.lyricContent : this.tempLyricContent })
  4711. .type(TextAreaType.NORMAL)
  4712. .height(275)
  4713. .fontSize(14)
  4714. .layoutWeight(1)
  4715. .fontColor($r('app.color.text_color'))
  4716. .margin({ right: 20, left: 10 })
  4717. .onChange((val: string) => {
  4718. this.lyricConStr = val
  4719. })
  4720. }
  4721. .width('100%')
  4722. .margin({ top: 10, bottom: 10 })
  4723. .justifyContent(FlexAlign.Start)
  4724. Row() {
  4725. Button('保存')
  4726. .fontColor(Color.White)
  4727. .layoutWeight(1)
  4728. .height(50)
  4729. .width(100)
  4730. .backgroundColor(this.themeColor)
  4731. .stateEffect(true)
  4732. .margin({ right: 20, bottom: 20 })
  4733. .onClick(async () => {
  4734. this.doEdit(item)
  4735. })
  4736. Button('取消')
  4737. .fontColor(Color.White)
  4738. .layoutWeight(1)
  4739. .height(50)
  4740. .width(100)
  4741. .backgroundColor(this.themeColor)
  4742. .stateEffect(true)
  4743. .margin({ left: 20, bottom: 20 })
  4744. .onClick(async () => {
  4745. this.isShowEdit = false
  4746. })
  4747. }
  4748. .margin({
  4749. left: 38,
  4750. right: 38,
  4751. top: 10,
  4752. bottom: 10
  4753. })
  4754. .width(250)
  4755. .height(60)
  4756. }
  4757. }
  4758. .margin({ bottom: 20 })
  4759. }
  4760. @Builder
  4761. detailSheet(item:VideoItem) {
  4762. Scroll() {
  4763. Column() {
  4764. this.songDetail(item)
  4765. }
  4766. }
  4767. .width('100%')
  4768. .height('100%')
  4769. }
  4770. @Builder
  4771. songDetail(currentItem:VideoItem) {
  4772. Column() {
  4773. if (currentItem) {
  4774. Row() {
  4775. Stack() {
  4776. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4777. currentItem.pixelMapPath)
  4778. .fillColor(this.themeColor)
  4779. .height(33)
  4780. .width(33)
  4781. .borderRadius('100%')
  4782. .clip(true)
  4783. .opacity(this.opacityItem)// 绑定透明度
  4784. .margin({ left: 20 })
  4785. }
  4786. .width('15%')
  4787. Column() {
  4788. Column() {
  4789. Text(currentItem.name)
  4790. .fontSize(14)
  4791. .maxLines(1)
  4792. .animation({
  4793. duration: 555,
  4794. curve: 'Linear',
  4795. })
  4796. .fontColor($r('app.color.text_color'))
  4797. .margin({ left: 10 })
  4798. Row() {
  4799. Text(StrUtil.isEmpty(currentItem.artist) ? currentItem.cTime :
  4800. currentItem.artist + ' ' + currentItem?.album)
  4801. .fontSize(11)
  4802. .padding({ top: 8 })
  4803. .fontColor($r('app.color.text_color'))
  4804. .margin({ left: 10 })
  4805. }
  4806. }
  4807. .height('100%')
  4808. .width('100%')
  4809. .justifyContent(FlexAlign.Center)
  4810. .alignItems(HorizontalAlign.Start)
  4811. }
  4812. .height('100%')
  4813. }
  4814. .width('100%')
  4815. .height(58)
  4816. .justifyContent(FlexAlign.SpaceBetween)
  4817. Row() {
  4818. Text('歌手名:')
  4819. .fontSize(14)
  4820. .fontColor(Color.White)
  4821. .margin({ left: 22 })
  4822. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4823. .fontSize(14)
  4824. .fontColor(Color.White)
  4825. .margin({ left: 10 })
  4826. .layoutWeight(1)
  4827. }
  4828. .width('100%')
  4829. .margin({ top: 10, bottom: 10 })
  4830. .justifyContent(FlexAlign.Start)
  4831. Row() {
  4832. Text('专辑名:')
  4833. .fontSize(14)
  4834. .fontColor(Color.White)
  4835. .margin({ left: 22 })
  4836. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4837. .fontSize(14)
  4838. .margin({ left: 10 })
  4839. .fontColor(Color.White)
  4840. .layoutWeight(1)
  4841. }
  4842. .width('100%')
  4843. .margin({ top: 10, bottom: 10 })
  4844. .justifyContent(FlexAlign.Start)
  4845. Row() {
  4846. Text('时长:')
  4847. .fontSize(14)
  4848. .fontColor(Color.White)
  4849. .margin({ left: 22 })
  4850. Text(StrUtil.isEmpty(currentItem.duration)?
  4851. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4852. .fontSize(14)
  4853. .margin({ left: 10 })
  4854. .fontColor(Color.White)
  4855. .layoutWeight(1)
  4856. }
  4857. .width('100%')
  4858. .margin({ top: 10, bottom: 10 })
  4859. .justifyContent(FlexAlign.Start)
  4860. Row() {
  4861. Text('采样率:')
  4862. .fontSize(14)
  4863. .fontColor(Color.White)
  4864. .margin({ left: 22 })
  4865. Text(Utility.convertToKHz(currentItem.sampleRate))
  4866. .fontSize(14)
  4867. .margin({ left: 10 })
  4868. .fontColor(Color.White)
  4869. .layoutWeight(1)
  4870. }
  4871. .width('100%')
  4872. .margin({ top: 10, bottom: 10 })
  4873. .justifyContent(FlexAlign.Start)
  4874. Row() {
  4875. Text('比特率:')
  4876. .fontSize(14)
  4877. .fontColor(Color.White)
  4878. .margin({ left: 22 })
  4879. Text(currentItem.bit_rate)
  4880. .fontSize(14)
  4881. .margin({ left: 10 })
  4882. .fontColor(Color.White)
  4883. .layoutWeight(1)
  4884. }
  4885. .width('100%')
  4886. .margin({ top: 10, bottom: 10 })
  4887. .justifyContent(FlexAlign.Start)
  4888. Row() {
  4889. Text('风格:')
  4890. .fontSize(14)
  4891. .fontColor(Color.White)
  4892. .margin({ left: 22 })
  4893. Text(currentItem.genre)
  4894. .fontSize(14)
  4895. .margin({ left: 10 })
  4896. .fontColor(Color.White)
  4897. .layoutWeight(1)
  4898. }
  4899. .width('100%')
  4900. .margin({ top: 10, bottom: 10 })
  4901. .justifyContent(FlexAlign.Start)
  4902. Row() {
  4903. Text('发行时间:')
  4904. .fontSize(14)
  4905. .fontColor(Color.White)
  4906. .margin({ left: 22 })
  4907. Text(currentItem.year)
  4908. .fontSize(14)
  4909. .margin({ left: 10 })
  4910. .fontColor(Color.White)
  4911. .layoutWeight(1)
  4912. }
  4913. .width('100%')
  4914. .margin({ top: 10, bottom: 10 })
  4915. .justifyContent(FlexAlign.Start)
  4916. Row() {
  4917. Text('质量评分:')
  4918. .fontSize(14)
  4919. .fontColor(Color.White)
  4920. .margin({ left: 22 })
  4921. Text(currentItem.probe_score+"")
  4922. .fontSize(14)
  4923. .margin({ left: 10 })
  4924. .fontColor(Color.White)
  4925. .layoutWeight(1)
  4926. }
  4927. .width('100%')
  4928. .margin({ top: 10, bottom: 10 })
  4929. .justifyContent(FlexAlign.Start)
  4930. Row() {
  4931. Text('音轨号:')
  4932. .fontSize(14)
  4933. .fontColor(Color.White)
  4934. .margin({ left: 22 })
  4935. Text(currentItem.track)
  4936. .fontSize(14)
  4937. .margin({ left: 10 })
  4938. .fontColor(Color.White)
  4939. .layoutWeight(1)
  4940. }
  4941. .width('100%')
  4942. .margin({ top: 10, bottom: 10 })
  4943. .justifyContent(FlexAlign.Start)
  4944. Row() {
  4945. Text('格式:')
  4946. .fontSize(14)
  4947. .fontColor(Color.White)
  4948. .margin({ left: 22 })
  4949. Text(Utility.formatMimeType(currentItem.mimeType))
  4950. .fontSize(14)
  4951. .margin({ left: 10 })
  4952. .fontColor(Color.White)
  4953. .layoutWeight(1)
  4954. }
  4955. .width('100%')
  4956. .margin({ top: 10, bottom: 10 })
  4957. .justifyContent(FlexAlign.Start)
  4958. Row() {
  4959. Text('播放次数:')
  4960. .fontSize(14)
  4961. .fontColor(Color.White)
  4962. .margin({ left: 22 })
  4963. Text(currentItem.playCount?.toString())
  4964. .fontSize(14)
  4965. .margin({ left: 10 })
  4966. .fontColor(Color.White)
  4967. .layoutWeight(1)
  4968. }
  4969. .width('100%')
  4970. .margin({ top: 10, bottom: 10 })
  4971. .justifyContent(FlexAlign.Start)
  4972. Row() {
  4973. Text('流数量:')
  4974. .fontSize(14)
  4975. .fontColor(Color.White)
  4976. .margin({ left: 22 })
  4977. Text(currentItem.nb_streams?.toString())
  4978. .fontSize(14)
  4979. .margin({ left: 10 })
  4980. .fontColor(Color.White)
  4981. .layoutWeight(1)
  4982. }
  4983. .width('100%')
  4984. .margin({ top: 10, bottom: 10 })
  4985. .justifyContent(FlexAlign.Start)
  4986. Row() {
  4987. Text('文件大小:')
  4988. .fontSize(14)
  4989. .fontColor(Color.White)
  4990. .margin({ left: 22 })
  4991. Text(currentItem.size)
  4992. .fontSize(14)
  4993. .margin({ left: 10 })
  4994. .fontColor(Color.White)
  4995. .layoutWeight(1)
  4996. }
  4997. .width('100%')
  4998. .margin({ top: 10, bottom: 10 })
  4999. .justifyContent(FlexAlign.Start)
  5000. Row() {
  5001. Text('文件名:')
  5002. .fontSize(14)
  5003. .fontColor(Color.White)
  5004. .margin({ left: 22 })
  5005. Text(currentItem.fileName)
  5006. .fontSize(14)
  5007. .margin({ left: 10 })
  5008. .fontColor(Color.White)
  5009. .layoutWeight(1)
  5010. }
  5011. .width('100%')
  5012. .margin({ top: 10, bottom: 10 })
  5013. .justifyContent(FlexAlign.Start)
  5014. Row() {
  5015. Text('修改时间:')
  5016. .fontSize(14)
  5017. .fontColor(Color.White)
  5018. .margin({ left: 22 })
  5019. Text(currentItem.cTime)
  5020. .fontSize(14)
  5021. .margin({ left: 10 })
  5022. .fontColor(Color.White)
  5023. .layoutWeight(1)
  5024. }
  5025. .width('100%')
  5026. .margin({ top: 10, bottom: 10 })
  5027. .justifyContent(FlexAlign.Start)
  5028. Row() {
  5029. Text('存放目录:')
  5030. .fontSize(14)
  5031. .fontColor(Color.White)
  5032. .margin({ left: 22 })
  5033. Text(currentItem.filePath)
  5034. .fontSize(12)
  5035. .margin({ left: 10 })
  5036. .fontColor(Color.White)
  5037. .layoutWeight(1)
  5038. }
  5039. .margin({ top: 10, bottom: 10 })
  5040. .width('100%')
  5041. .justifyContent(FlexAlign.Start)
  5042. }
  5043. }
  5044. .margin({ bottom: 20 })
  5045. }
  5046. //定时关闭布局
  5047. @Builder
  5048. TimeCloseSheet() {
  5049. Scroll() {
  5050. Column() {
  5051. this.TimeClose()
  5052. }
  5053. }
  5054. .width('100%')
  5055. .height('100%')
  5056. }
  5057. //倒计时关闭音乐,退出App功能实现。
  5058. @State selectedMinutes: number = 0 // 0表示未开启
  5059. @State remainingSeconds: number = 0
  5060. // 预设时间选项
  5061. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  5062. private formatTime(seconds: number): string {
  5063. const mins = Math.floor(seconds / 60)
  5064. const secs = seconds % 60
  5065. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  5066. }
  5067. // 开始倒计时
  5068. private handleTimeSelect(minutes: number) {
  5069. if (minutes === this.selectedMinutes) {
  5070. this.stopCountdown();
  5071. this.selectedMinutes = 0;
  5072. return;
  5073. }
  5074. this.selectedMinutes = minutes;
  5075. this.remainingSeconds = minutes * 60;
  5076. this.startCountdown(); // 新增调用
  5077. }
  5078. @Builder
  5079. TimeClose() {
  5080. Column() {
  5081. // 倒计时显示区域
  5082. Text(this.selectedMinutes > 0 ?
  5083. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  5084. "定时关闭未开启")
  5085. .fontSize(17)
  5086. .fontColor($r('app.color.text_color'))
  5087. .margin({ top: 2, bottom: 8 });
  5088. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  5089. ForEach(this.presetTimes, (minutes: number, index: number) => {
  5090. // 单行时间选项容器
  5091. Row() {
  5092. // 文字描述区域
  5093. Text(this.getDisplayText(minutes))
  5094. .fontSize(15)
  5095. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  5096. $r('app.color.text_color'))// 选中态颜色变化
  5097. .textAlign(TextAlign.Start)
  5098. .layoutWeight(1); // 占据剩余空间
  5099. // 复选框样式的选择器
  5100. Row() {
  5101. if (minutes === this.selectedMinutes) {
  5102. // 选中状态 - 带勾号的圆形复选框
  5103. Row() {
  5104. // 使用系统内置的勾号图标
  5105. Image($r('sys.media.ohos_ic_public_ok'))
  5106. .width(14)
  5107. .height(14)
  5108. .fillColor(Color.White)
  5109. }
  5110. .width(24)
  5111. .height(24)
  5112. .borderRadius(12)
  5113. .backgroundColor(this.themeColor)
  5114. .justifyContent(FlexAlign.Center)
  5115. .alignItems(VerticalAlign.Center)
  5116. } else {
  5117. // 未选中状态的圆形边框
  5118. Row()
  5119. .width(24)
  5120. .height(24)
  5121. .borderRadius(12)
  5122. .border({
  5123. width: 2,
  5124. color: $r('app.color.text_color'),
  5125. style: BorderStyle.Solid
  5126. })
  5127. .backgroundColor(Color.Transparent)
  5128. }
  5129. }
  5130. .width(24)
  5131. .height(24)
  5132. .margin({ left: 20 })
  5133. .justifyContent(FlexAlign.Center)
  5134. .alignItems(VerticalAlign.Center)
  5135. }
  5136. .width('100%')
  5137. .padding({
  5138. top: 18,
  5139. bottom: 18,
  5140. left: 18,
  5141. right: 18
  5142. })
  5143. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  5144. $r('app.color.bottom_control_background')) // 选中背景高亮
  5145. .borderRadius(12)
  5146. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  5147. .margin({ bottom: 18 })
  5148. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  5149. });
  5150. }
  5151. .width('100%')
  5152. .padding(16)
  5153. }
  5154. }
  5155. // 获取显示文本
  5156. private getDisplayText(minutes: number): string {
  5157. if (minutes === -1) {
  5158. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  5159. }
  5160. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  5161. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  5162. }
  5163. // 处理选择事件
  5164. private handleSelect(minutes: number): void {
  5165. if (minutes === -1) { // 自定义
  5166. // 弹出自定义时间对话框
  5167. DialogHelper.showTextInputDialog({
  5168. title: '自定义时间',
  5169. maskColor: Color.Transparent,
  5170. inputType: InputType.Number,
  5171. text: '',
  5172. onChange: (text) => {
  5173. console.error("onChange: " + text);
  5174. },
  5175. onAction: (action, dialogId, content) => {
  5176. if (action == DialogAction.TWO) {
  5177. const customMinutes = Number(content);
  5178. if (customMinutes > 0) {
  5179. this.handleTimeSelect(customMinutes); // 设置自定义时间
  5180. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  5181. }
  5182. }
  5183. }
  5184. });
  5185. } else {
  5186. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  5187. }
  5188. }
  5189. // 添加定时器引用
  5190. private timerId: number = -1;
  5191. // 启动/重置倒计时
  5192. private startCountdown() {
  5193. // 清除旧定时器
  5194. if (this.timerId !== -1) {
  5195. clearInterval(this.timerId);
  5196. }
  5197. // 创建新定时器
  5198. if (this.selectedMinutes > 0) {
  5199. this.timerId = setInterval(() => {
  5200. if (this.remainingSeconds === 15) {
  5201. this.showConfirmationDialog();
  5202. }
  5203. if (this.remainingSeconds > 0) {
  5204. this.remainingSeconds -= 1;
  5205. } else {
  5206. this.stopCountdown();
  5207. this.handleTimeout();
  5208. }
  5209. }, 1000);
  5210. }
  5211. }
  5212. // 15倒计时后再次提示显示确认是否关闭App对话框
  5213. private showConfirmationDialog() {
  5214. DialogHelper.showAlertDialog({
  5215. backgroundColor: $r('app.color.btn_green'),
  5216. title: '确认关闭',
  5217. maskColor: Color.Transparent,
  5218. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  5219. borderStyle: BorderStyle.Dashed,
  5220. primaryButton: '暂不关闭',
  5221. secondaryButton: '确定',
  5222. onAction: (action) => {
  5223. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  5224. this.stopCountdown();
  5225. this.selectedMinutes = 0
  5226. } else if (action == DialogAction.TWO) {
  5227. }
  5228. }
  5229. })
  5230. }
  5231. // 停止倒计时
  5232. private stopCountdown() {
  5233. if (this.timerId !== -1) {
  5234. clearInterval(this.timerId);
  5235. this.timerId = -1;
  5236. }
  5237. }
  5238. // 超时处理
  5239. private handleTimeout() {
  5240. // 执行播放器关闭逻辑
  5241. this.selectedMinutes = 0;
  5242. ToastUtil.showToast(" 定时关闭已完成");
  5243. this.stop(); // 假设存在的播放器实例
  5244. //退出APP
  5245. const mContext = getContext(this) as common.UIAbilityContext
  5246. mContext.terminateSelf();
  5247. AvSessionController.getInstance(true).unregisterSessionListener()
  5248. }
  5249. //倒计时关闭音乐,退出App功能实现结束。
  5250. //播放列表的拖动List 重新排序
  5251. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  5252. //左滑操作 移动文件 重命名 删除等操作
  5253. @Builder
  5254. sonButton(item: VideoItem, index: number, filePath: string) {
  5255. Row() {
  5256. //加入下一首播放
  5257. Button() {
  5258. Image($r('app.media.next_to_play'))
  5259. .fillColor(Color.White)
  5260. .width(20)
  5261. }
  5262. .width(40)
  5263. .height(40)
  5264. .type(ButtonType.Circle)
  5265. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5266. .backgroundColor(this.themeColor)
  5267. .margin(5)
  5268. .onClick(() => {
  5269. this.addToNextPlay(item);
  5270. })
  5271. Button() {
  5272. Image($r('app.media.close'))
  5273. .fillColor(Color.White)
  5274. .width(20)
  5275. }
  5276. .width(40)
  5277. .height(40)
  5278. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5279. .type(ButtonType.Circle)
  5280. .backgroundColor(this.themeColor)
  5281. .margin(5)
  5282. .onClick(() => {
  5283. this.removeFromPlaylistViaService(Number(index));
  5284. })
  5285. Button() {
  5286. Image($r('app.media.share2'))
  5287. .fillColor(Color.White)
  5288. .width(20)
  5289. }
  5290. .width(40)
  5291. .height(40)
  5292. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5293. .type(ButtonType.Circle)
  5294. .backgroundColor(this.themeColor)
  5295. .margin(5)
  5296. .onClick(() => {
  5297. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5298. })
  5299. }
  5300. }
  5301. itemMoveSon(index: number, newIndex: number): void {
  5302. if (newIndex < 0 || newIndex >= this.songList.length) {
  5303. return;
  5304. }
  5305. try {
  5306. // 使用UnifiedPlayerService进行播放列表重排序
  5307. const removedSong = this.unifiedPlayerService.removeFromPlaylist(index);
  5308. if (removedSong) {
  5309. this.unifiedPlayerService.addToPlaylist(removedSong, newIndex);
  5310. }
  5311. // 更新本地播放列表
  5312. let tmp = this.songList.splice(index, 1);
  5313. this.songList.splice(newIndex, 0, tmp[0]);
  5314. this.sonDataSource.pushArrayData(this.songList);
  5315. // 更新当前索引
  5316. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl);
  5317. } catch (error) {
  5318. // 错误处理:回退到原有逻辑
  5319. let tmp = this.songList.splice(index, 1);
  5320. this.songList.splice(newIndex, 0, tmp[0]);
  5321. this.sonDataSource.pushArrayData(this.songList);
  5322. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl);
  5323. }
  5324. }
  5325. @Builder
  5326. PlayList() {
  5327. List({ scroller: this.playListScroller }) {
  5328. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  5329. ListItem() {
  5330. this.MusicItemSon(item, index)
  5331. }
  5332. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  5333. .animation({
  5334. duration: 666,
  5335. curve: 'ease-in-out' // 可选动画曲线
  5336. })
  5337. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  5338. TransitionEffect.scale({ x: 0, y: 0 })))
  5339. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  5340. //拖动List关键代码开始
  5341. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5342. .zIndex(this.dragItem === index ? 1 : 0)
  5343. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5344. .gesture(
  5345. GestureGroup(GestureMode.Sequence,
  5346. LongPressGesture({ repeat: true })
  5347. .onAction((event?: GestureEvent) => {
  5348. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5349. this.scaleItem = index
  5350. })
  5351. })
  5352. .onActionEnd(() => {
  5353. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5354. this.scaleItem = -1
  5355. })
  5356. }),
  5357. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5358. .onActionStart(() => {
  5359. this.dragItem = index // 记录当前拖动项索引
  5360. this.dragRefOffset = 0 // 重置偏移基准
  5361. })
  5362. .onActionUpdate((event: GestureEvent) => {
  5363. this.offsetY = event.offsetY - this.dragRefOffset;
  5364. this.neighborItem = -1;
  5365. let indexA = this.songList.indexOf(item);
  5366. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5367. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5368. let value: number = 0;
  5369. if (this.offsetY < 0) {
  5370. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5371. this.neighborItem = indexA - 1;
  5372. this.neighborScale = 1 - value / 20;
  5373. } else if (this.offsetY > 0) {
  5374. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5375. this.neighborItem = indexA + 1;
  5376. this.neighborScale = 1 - value / 20;
  5377. }
  5378. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  5379. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5380. this.offsetY -= this.ITEM_INTV;
  5381. this.dragRefOffset += this.ITEM_INTV;
  5382. this.itemMoveSon(indexA, indexA + 1);
  5383. });
  5384. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5385. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5386. this.offsetY += this.ITEM_INTV;
  5387. this.dragRefOffset -= this.ITEM_INTV;
  5388. this.itemMoveSon(indexA, indexA - 1);
  5389. });
  5390. }
  5391. })
  5392. .onActionEnd((event: GestureEvent) => {
  5393. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5394. this.dragItem = -1
  5395. this.neighborItem = -1
  5396. })
  5397. animateTo({
  5398. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5399. }, () => {
  5400. this.scaleItem = -1
  5401. })
  5402. })
  5403. )
  5404. .onCancel(() => {
  5405. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5406. this.dragItem = -1
  5407. this.neighborItem = -1
  5408. })
  5409. animateTo({
  5410. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5411. }, () => {
  5412. this.scaleItem = -1
  5413. })
  5414. })
  5415. ) //拖动List关键代码结束
  5416. .onClick(() => {
  5417. this.doPlay(item, index, true)
  5418. })
  5419. }, (item: VideoItem) => item.filePath)
  5420. }
  5421. .width('100%')
  5422. .height('100%')
  5423. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5424. // .animation({ duration: 500, curve: Curve.Ease }))
  5425. .cachedCount(10)
  5426. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5427. .gesture(PinchGesture({ fingers: 2 })
  5428. .onActionEnd((event: GestureEvent) => {
  5429. this.setlistTwoFingers()
  5430. })
  5431. .onActionUpdate(e => {
  5432. this.scaleValue = this.pinchValue * e.scale
  5433. })
  5434. .onActionStart(e => {
  5435. }))
  5436. .padding({
  5437. bottom: 0
  5438. })
  5439. }
  5440. @Builder
  5441. private MusicItemSon(item: VideoItem, index?: number) {
  5442. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5443. Row() {
  5444. Stack() {
  5445. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5446. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5447. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5448. .alt($r('app.media.music_red'))
  5449. .fillColor(this.themeColor)
  5450. .borderRadius('100%')
  5451. .clip(true)
  5452. .margin({ left: 20 })
  5453. }
  5454. .width('15%')
  5455. Column() {
  5456. Column() {
  5457. Text(item.name)
  5458. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5459. .fontColor(this.curIndex === index ? this.themeColor :
  5460. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5461. .maxLines(1)
  5462. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5463. Row() {
  5464. Column(){
  5465. Text(item.md5Str?.includes('Lossless')?
  5466. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5467. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5468. .padding({ top: 3,right:6,left:6,bottom:3 })
  5469. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5470. $r('app.color.text_color'))
  5471. .fontWeight(500)
  5472. .borderRadius(12)
  5473. .margin({ left: this.twoFingerType == 3 ? 12 : 10 })
  5474. .backgroundColor('#FFC107')
  5475. }
  5476. .padding({ top: 8 })
  5477. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5478. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5479. .padding({ top: 8 })
  5480. .fontColor(this.curIndex === index ? this.themeColor :
  5481. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5482. .margin({ left: this.twoFingerType == 3 ? 5 : 3 })
  5483. Blank()
  5484. Text(item.size)
  5485. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5486. .padding({ top: 8 })
  5487. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5488. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5489. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5490. .margin({ left: 10 })
  5491. }
  5492. }
  5493. .height('100%')
  5494. .width('100%')
  5495. .justifyContent(FlexAlign.Center)
  5496. .alignItems(HorizontalAlign.Start)
  5497. }
  5498. .height('100%')
  5499. .width('65%')
  5500. Column() {
  5501. ImageAnimator()
  5502. .images(this.imagesF)// 动画数组
  5503. .duration(1000)// 持续
  5504. .state(this.animationState)// 动画状态
  5505. .fillMode(FillMode.Forwards)
  5506. .width(18)
  5507. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5508. Visibility.None)
  5509. .height(18)
  5510. .iterations(-1) // 播放次数
  5511. }
  5512. .width('20%')
  5513. }
  5514. }
  5515. .backgroundColor(Color.Transparent)
  5516. .width('100%')
  5517. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5518. .shadow(this.scaleItem === index ? {
  5519. radius: 70,
  5520. color: '#15000000',
  5521. offsetX: 0,
  5522. offsetY: 0
  5523. } :
  5524. {
  5525. radius: 0,
  5526. color: '#15000000',
  5527. offsetX: 0,
  5528. offsetY: 0
  5529. })
  5530. .animation({ curve: Curve.Sharp, duration: 300 })
  5531. }
  5532. @Builder
  5533. MusicPlayBuilder() {
  5534. Column() {
  5535. this.MusicPlayerView()
  5536. }
  5537. .height('100%')
  5538. .width('100%')
  5539. .onDisAppear(() => {
  5540. this.translateY = 0;
  5541. })
  5542. .translate({ y: this.translateY })
  5543. .gesture(
  5544. PanGesture(this.panOption)
  5545. .onActionUpdate((event?: GestureEvent) => {
  5546. if (event) {
  5547. // 只允许向下滑动,向上滑动时限制为0
  5548. this.translateY = Math.max(0, event.offsetY);
  5549. }
  5550. })
  5551. .onActionEnd((event?: GestureEvent) => {
  5552. // 使用更低的阈值和滑动速度判断
  5553. const minDistance = 100; // 最小滑动距离 100vp
  5554. const minVelocity = 500; // 最小滑动速度
  5555. // 获取滑动速度(如果可用)
  5556. const velocity = event?.velocityY || 0;
  5557. // 判断是否应该关闭:距离足够 或者 速度足够快
  5558. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5559. if (shouldClose) {
  5560. // 添加关闭动画
  5561. this.getUIContext().animateTo({
  5562. duration: 300,
  5563. curve: Curve.Smooth
  5564. }, () => {
  5565. this.isShowPlay = false;
  5566. this.translateY = 0;
  5567. })
  5568. } else {
  5569. // 回弹动画
  5570. this.getUIContext().animateTo({
  5571. duration: 300,
  5572. curve: Curve.Smooth
  5573. }, () => {
  5574. this.translateY = 0;
  5575. })
  5576. }
  5577. })
  5578. )
  5579. }
  5580. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5581. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5582. HeightBreakpoint.HEIGHT_LG;
  5583. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5584. @State topBarHeight: number = 50
  5585. @State barOpacity: number = 1
  5586. @State barBottomOpacity: number = 1
  5587. private hideDone: boolean = false;
  5588. @State currentYOffset: number = 0;
  5589. @State bottomBarHeight: number = 60;
  5590. private isHiding: boolean = false;
  5591. //是否是Pura X外屏,或者小屏幕
  5592. isPuraWP() {
  5593. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5594. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5595. }
  5596. //是否是Pura X外屏,或者小屏幕,手机横屏
  5597. isCoverOpacity() {
  5598. if (this.isPuraWP()) {
  5599. return true
  5600. }
  5601. if (this.isPhoneLan()) {
  5602. return true
  5603. }
  5604. if (deviceInfo.marketName.includes('Pura X')
  5605. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5606. return true
  5607. }
  5608. return false
  5609. }
  5610. //是不是手机横屏
  5611. isPhoneLan() {
  5612. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5613. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5614. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5615. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5616. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  5617. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5618. if (this.isHiCar()) {
  5619. return false
  5620. }
  5621. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5622. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5623. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  5624. return true
  5625. }
  5626. return false
  5627. }
  5628. //是不是1920x720的hicar的屏幕分辨率
  5629. isHiCarKuanBianPing(){
  5630. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5631. { ratio: 1920 / 720, name: "1920x720" },
  5632. ];
  5633. const currentRatio: number = this.windowWidth / this.windowHeight;
  5634. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5635. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5636. for (const hiCarRatio of hiCarAspectRatios) {
  5637. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5638. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5639. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5640. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5641. return true&&this.isHiCar();
  5642. }
  5643. }
  5644. return false;
  5645. }
  5646. //是不是hicar的屏幕分辨率
  5647. isHiCarSmall() {
  5648. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5649. return false
  5650. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5651. { ratio: 800 / 480, name: "800x480" },
  5652. { ratio: 1280 / 720, name: "1280x720" },
  5653. { ratio: 1920 / 720, name: "1920x720" },
  5654. ];
  5655. const currentRatio: number = this.windowWidth / this.windowHeight;
  5656. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5657. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5658. for (const hiCarRatio of hiCarAspectRatios) {
  5659. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5660. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5661. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5662. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5663. return true&&this.isHiCarStatus;
  5664. }
  5665. }
  5666. return false;
  5667. }
  5668. isHiCar() {
  5669. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  5670. }
  5671. //是不是正常的手机竖屏
  5672. isPhonePortrait() {
  5673. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5674. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5675. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5676. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5677. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5678. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5679. return true
  5680. }
  5681. return false
  5682. }
  5683. @State showSpeedDialog: boolean = false
  5684. @State longPressSpeed: number = 3 //长按默认倍数
  5685. @Builder
  5686. SpeedDialog() {
  5687. Stack() {
  5688. Column() {
  5689. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5690. .fontColor(Color.White)
  5691. .visibility(Visibility.Hidden)
  5692. }
  5693. .backgroundColor(Color.Black)
  5694. .borderRadius(20)
  5695. .padding({
  5696. top: 10,
  5697. right: 20,
  5698. left: 15,
  5699. bottom: 20
  5700. })
  5701. .opacity(0.6)
  5702. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5703. .fontColor(Color.White)
  5704. }
  5705. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5706. .zIndex(5)
  5707. .margin({ top: 80 })
  5708. }
  5709. @Builder
  5710. MusicPlayerView() {
  5711. Column() {
  5712. Column() {
  5713. Column() {
  5714. //播放标题
  5715. Column() {
  5716. this.PlayTitle()
  5717. }
  5718. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5719. .width('100%')
  5720. .margin({ top: 0 })
  5721. .height(PlayConstants.HEIGHT)
  5722. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5723. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5724. if (this.showSpeedDialog) {
  5725. this.SpeedDialog()
  5726. }
  5727. Stack() {
  5728. //手势拖动快进
  5729. Column()
  5730. .width(CommonConstants.FULL_PERCENT)
  5731. .height('100%')
  5732. .gesture(
  5733. GestureGroup(GestureMode.Parallel,
  5734. // 长按屏幕倍数播放
  5735. LongPressGesture({ repeat: true })
  5736. .onAction(() => {
  5737. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5738. this.showSpeedDialog = true;
  5739. this.unifiedPlayerService.setPlaybackSpeed(this.longPressSpeed);
  5740. }
  5741. })
  5742. .onActionEnd(() => {
  5743. this.showSpeedDialog = false;
  5744. this.setPlaybackSpeedViaService(this.playSpeed);
  5745. }),
  5746. //双击屏幕暂停或者播放
  5747. TapGesture({ count: 2 })
  5748. .onAction((event: GestureEvent) => {
  5749. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5750. ToastUtil.showToast('已暂停')
  5751. }
  5752. this.playOrPause()
  5753. })
  5754. )
  5755. )
  5756. }
  5757. .height('65%')
  5758. Swiper() {
  5759. this.CoverInfo()
  5760. this.PlayerLyrics()
  5761. }
  5762. .onChange((index: number) => {
  5763. this.currentSwiperIndex = index
  5764. })
  5765. .indicator(false)
  5766. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5767. // new DotIndicator()
  5768. // .top(this.isCoverOpacity()?0:10)
  5769. //
  5770. // .selectedColor($r('app.color.select_swiper'))
  5771. // .color($r('app.color.slider_track')):false
  5772. // )
  5773. .displayCount(new BreakpointType({
  5774. sm: 1,
  5775. md: 2,
  5776. lg: 2,
  5777. xl: 2,
  5778. xxl: 2
  5779. }).getValue(this.currentBreakpoint))
  5780. .clip(false)
  5781. .loop(false)
  5782. .autoPlay(false)
  5783. // .interval(8000)
  5784. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5785. .height('100%')
  5786. .hitTestBehavior(HitTestMode.Transparent)
  5787. Image($r('app.media.icon_replay'))
  5788. .objectFit(ImageFit.Auto)
  5789. .width('120px')
  5790. .height('120px')
  5791. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5792. .border({ width: 0 })
  5793. .visibility(Visibility.None)
  5794. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5795. .onClick(() => {
  5796. this.startPlayOrResumePlay();
  5797. })
  5798. }
  5799. .width(CommonConstants.FULL_PERCENT)
  5800. .height(CommonConstants.FULL_PERCENT)
  5801. .justifyContent(FlexAlign.End)
  5802. }
  5803. .justifyContent(FlexAlign.End)
  5804. .margin({ bottom: 8 })
  5805. }
  5806. // .backgroundImage(this.imageLabelBg)
  5807. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5808. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5809. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5810. // .backgroundImagePosition(Alignment.Center)
  5811. .animation({
  5812. duration: 666,
  5813. curve: 'ease-in-out' // 可选动画曲线
  5814. })
  5815. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5816. BlurStyle.BACKGROUND_ULTRA_THICK)
  5817. .hitTestBehavior(HitTestMode.Transparent)
  5818. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5819. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5820. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5821. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5822. .onClick(() => {
  5823. // this.startAutoHide()
  5824. if(this.isHiCar())
  5825. return
  5826. if(this.is_auto_hide_progress){
  5827. this.is_auto_hide_progress = false
  5828. }
  5829. this.startAutoHide()
  5830. })
  5831. }
  5832. @State progressValue: number = 0;
  5833. @State currentTime: string = "00:00";
  5834. @State totalTime: string = "00:00";
  5835. @State loadingVisible: Visibility = Visibility.None;
  5836. @State replayVisible: Visibility = Visibility.None;
  5837. @State slideEnable: boolean = false;
  5838. @State aspRatio: number = 0.5;
  5839. @State mContext: object | undefined = undefined;
  5840. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  5841. @State mFirst: boolean = true;
  5842. @State mDestroyPage: boolean = false;
  5843. @State playSpeed: number = 1;
  5844. @State oldSeconds: number = 0;
  5845. @State isSeekTo: boolean = false;
  5846. @State isCurrentTime: boolean = false;
  5847. @State lastSongPath: string = ""; // 用于检测歌曲切换
  5848. @State justSwitched: boolean = false; // 标记歌曲刚刚切换
  5849. @State lastSwitchTime: number = 0; // 记录最后一次歌曲切换的时间戳
  5850. @State videoWidth: string = '100%';
  5851. @State videoHeight: string = '100%';
  5852. @State initAspectRatio: number = 1;
  5853. @State videoAspectRatio: number = this.initAspectRatio;
  5854. private videoUrl: string = '';
  5855. private last: number = 0;
  5856. @State videoParentAspectRatio: number = this.initAspectRatio;
  5857. // 使用UnifiedPlayerService替代ijkMediaPlayer
  5858. // private mIjkMediaPlayer = IjkMediaPlayer.getInstance(); // 已移除,使用UnifiedPlayerService
  5859. private unifiedPlayerService: IPlayerService = UnifiedPlayerService.getInstance();
  5860. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  5861. @State PROGRESS_MAX_VALUE: number = 100;
  5862. @State updateProgressTimer: number = 0;
  5863. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  5864. @State name: string = '';
  5865. // @State loop: boolean = false;
  5866. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  5867. @State multiple: string = '1.0X';
  5868. xcomponentController: XComponentController = new XComponentController()
  5869. private windowClass: window.Window = globalThis.windowClass
  5870. @State volume: number = 0.3;
  5871. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  5872. @State bright: number = PlayConstants.BRIGHT;
  5873. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  5874. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  5875. @State screenWidth: number = 0
  5876. @State screenHeight: number = 0
  5877. @State statusBarHeight: number = 0
  5878. @State isYesFull: boolean = false
  5879. private seekValue: number = 0
  5880. @State isVideoLock: boolean = false; // Whether the video playback is locked
  5881. eventHub = getContext().eventHub;
  5882. //投播组件
  5883. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  5884. private avSessionWidgetListener: AvSessionWidgetListener = AvSessionWidgetListener.getInstance();
  5885. private castController: avSession.AVCastController | undefined = undefined;
  5886. @State isCastPlaying: boolean = false;
  5887. @State isCasting: boolean = false; // 是否正在投播中
  5888. private currentCastDevice: avSession.DeviceInfo | undefined = undefined; // 当前投播设备
  5889. @State currentTime2: number = 0;
  5890. @State currentStringTime: string = '00:00';
  5891. @State duration: number = 0;
  5892. @State isReady: boolean = false;
  5893. @State durationTime: number = 0;
  5894. @State durationStringTime: string = '00:00';
  5895. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  5896. // @State isPlaying: boolean = false;
  5897. private castSeek: boolean = false;
  5898. private castItem: avSession.AVQueueItem | undefined = undefined;
  5899. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  5900. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  5901. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  5902. @State rotateAngle2: number = 0
  5903. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  5904. @State cover: string | undefined = '';
  5905. @State artist: string | undefined = ''
  5906. // 1.初始化controller
  5907. private lyricController: LyricController = new LyricController()
  5908. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  5909. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  5910. private parser = new LyricParser()
  5911. @State randomColor: string = 'rgb(0,0,0)'
  5912. @State randomShakenX: number = 0
  5913. @State randomShakenY: number = 0
  5914. @State lyricTextSize: number = 24
  5915. @State lyricContent: string = ''
  5916. @State isDebug: boolean = false
  5917. @State isHightLightCenter: boolean = true
  5918. /**
  5919. * 初始化歌词加载与展示逻辑
  5920. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  5921. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  5922. * @param isApi2 是否使用API2获取歌词(可选)
  5923. *
  5924. * 主要流程:
  5925. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  5926. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  5927. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  5928. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  5929. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  5930. * 6. 解析失败或读取失败时,清空歌词显示。
  5931. *
  5932. * 注意事项:
  5933. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  5934. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  5935. * - 歌词内容解析后通过lyricController驱动UI渲染。
  5936. */
  5937. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  5938. if (StrUtil.isEmpty(lyricPath)) {
  5939. return
  5940. }
  5941. this.initPipLyricSetting()
  5942. this.lyricControllerSingle
  5943. .setTextSize(15)
  5944. .setCacheSize(4)
  5945. .setTextColor("#FFFFFF")
  5946. .setHighlightColor("#FFFFFF")
  5947. .setHighlightScale(1.2)
  5948. .setEmptyHint("")
  5949. .setAlignMode('center')
  5950. .setAnimationDuration(500)
  5951. .setSingleLine(true)
  5952. this.lyricContent = ''
  5953. this.lyricController
  5954. .setTextSize(this.currentLyricSize)
  5955. .setCacheSize(4)
  5956. .setTextColor("#DDDDDD")
  5957. .setHighlightColor("#FFFFFF")
  5958. .setEmptyHint("")
  5959. .setAnimationDuration(1000)
  5960. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  5961. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  5962. this.setBlurDegree(this.blurDegree, false)
  5963. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  5964. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  5965. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  5966. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  5967. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  5968. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  5969. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  5970. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  5971. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  5972. this.lyricController.setTextWeight(this.lyricTextWeight)
  5973. this.showSingleLyric = false
  5974. this.timeOffset = 0
  5975. this.lyricController.setLyric(null)
  5976. this.lyricControllerSingle.setLyric(null)
  5977. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  5978. console.log("onecold lyricPath =" + lyricPath)
  5979. let neiqianLrc = ''
  5980. let lyContent = this.currentSong?.lyricContent
  5981. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  5982. neiqianLrc = lyContent
  5983. }
  5984. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  5985. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  5986. //赋值给this.lyricContent,播控中心才可以显示歌词
  5987. this.lyricContent = neiqianLrc
  5988. // 将文件内容按行分割成字符串数组
  5989. let lines = neiqianLrc.split('\n').map(line => line.trim());
  5990. // 3.解析歌词
  5991. let lyric = this.parser.parse(lines);
  5992. // 4.设置歌词
  5993. this.lyricController.setLyric(lyric);
  5994. this.lyricControllerXF.setLyric(lyric)
  5995. this.lyricControllerSingle.setLyric(lyric)
  5996. return
  5997. }
  5998. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  5999. && !Utility.isVideoByExtension(this.videoUrl))) {
  6000. if (this.currentSong !== undefined) {
  6001. // ToastUtil.showShort('正在为你搜索在线歌词!')
  6002. //判断是不是赞助会员,是会员的话才开启歌词功能
  6003. // if (!this.isDebug) {
  6004. // if (!Utility.isNoble()) {
  6005. // LogUtil.debug("onecold 不是赞助会员")
  6006. // return
  6007. // }
  6008. // if(!Utility.isPassInstallTime(33)){
  6009. // LogUtil.debug("onecold not pass time")
  6010. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  6011. // return
  6012. // }
  6013. // }
  6014. let artist = this.currentSong?.artist
  6015. if (artist === undefined) {
  6016. artist = ''
  6017. }
  6018. if (isApi2 === undefined) {
  6019. isApi2 = false
  6020. }
  6021. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  6022. // LogUtil.debug("onecold res =" + res)
  6023. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6024. if (StrUtil.isNotEmpty(res)) {
  6025. this.lyricContent = res
  6026. let lines = res.split('\n').map(line => line.trim());
  6027. // 3.解析歌词
  6028. let lyric = this.parser.parse(lines);
  6029. // 4.设置歌词
  6030. this.lyricController.setLyric(lyric);
  6031. this.lyricControllerXF.setLyric(lyric)
  6032. this.lyricControllerSingle.setLyric(lyric)
  6033. this.showSingleLyric = true
  6034. // 4.保存歌词文件lyric到本地
  6035. this.saveDataToFile(res, jiaMilyricPath, true)
  6036. } else {
  6037. this.lyricController.setLyric(null)
  6038. this.lyricControllerXF.setLyric(null)
  6039. this.lyricControllerSingle.setLyric(null)
  6040. if (isOnLineAndToast) {
  6041. ToastUtil.showShort('未获取到歌词!')
  6042. }
  6043. }
  6044. } else {
  6045. this.lyricController.setLyric(null)
  6046. this.lyricControllerXF.setLyric(null)
  6047. this.lyricControllerSingle.setLyric(null)
  6048. if (isOnLineAndToast) {
  6049. ToastUtil.showShort('未获取到歌词!')
  6050. }
  6051. }
  6052. })
  6053. } else {
  6054. this.lyricController.setLyric(null)
  6055. this.lyricControllerXF.setLyric(null)
  6056. this.lyricControllerSingle.setLyric(null)
  6057. if (isOnLineAndToast) {
  6058. ToastUtil.showShort('未获取到歌词!')
  6059. }
  6060. }
  6061. return
  6062. }
  6063. try {
  6064. let isJiaMi = false;
  6065. let realLyricPath = lyricPath
  6066. if (FileUtil.accessSync(jiaMilyricPath)) {
  6067. isJiaMi = true
  6068. realLyricPath = jiaMilyricPath
  6069. console.info("onecold 找到加密本地歌词 ");
  6070. } else {
  6071. isJiaMi = false
  6072. realLyricPath = lyricPath
  6073. console.info("onecold 找到本地歌词 ");
  6074. }
  6075. // 3.读取文件内容并指定编码为 UTF-8
  6076. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6077. const stat = await fileIo.stat(file.fd);
  6078. const arrayBuffer = new ArrayBuffer(stat.size);
  6079. fs.read(file.fd, arrayBuffer)
  6080. .then((readLen: number) => {
  6081. console.info("read file data succeed");
  6082. // let buf = buffer.from(arrayBuffer, 0, readLen);
  6083. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6084. // 检查 buf 是否为空
  6085. if (buf.length === 0) {
  6086. throw new Error("Buffer is empty after reading the file");
  6087. }
  6088. try {
  6089. // 检测文件编码
  6090. // let detectedEncoding = chardet.detect(buf);
  6091. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  6092. let detectedEncoding = this.detect(arrayBuffer)
  6093. console.info("onecoldT Detected encoding: " + detectedEncoding);
  6094. // 使用检测到的编码解码,解决中文乱码问题
  6095. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6096. console.info("onecoldT Detected textDecoder: " + textDecoder);
  6097. let fileContent = textDecoder.decode(buf);
  6098. console.info(`onecoldT The content of file1: ${fileContent}`);
  6099. //解密
  6100. if (isJiaMi) {
  6101. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  6102. }
  6103. console.info(`onecold The content of file2: ${fileContent}`);
  6104. this.lyricContent = fileContent
  6105. // 将文件内容按行分割成字符串数组
  6106. let lines = fileContent.split('\n').map(line => line.trim());
  6107. console.info(`onecold The content of file: ${fileContent}`);
  6108. // 3.解析歌词
  6109. let lyric = this.parser.parse(lines);
  6110. // 4.设置歌词
  6111. this.lyricController.setLyric(lyric);
  6112. this.lyricControllerXF.setLyric(lyric)
  6113. this.lyricControllerSingle.setLyric(lyric)
  6114. this.showSingleLyric = true
  6115. console.info(`The content of file: ${fileContent}`);
  6116. } catch (chardetError) {
  6117. console.error("chardet.detect failed with error: " + chardetError.message);
  6118. this.lyricController.setLyric(null);
  6119. this.lyricControllerXF.setLyric(null)
  6120. this.lyricControllerSingle.setLyric(null)
  6121. }
  6122. })
  6123. .catch((err: BusinessError) => {
  6124. this.lyricController.setLyric(null)
  6125. this.lyricControllerXF.setLyric(null)
  6126. this.lyricControllerSingle.setLyric(null)
  6127. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  6128. })
  6129. .catch((err: Error) => {
  6130. this.lyricController.setLyric(null)
  6131. this.lyricControllerXF.setLyric(null)
  6132. this.lyricControllerSingle.setLyric(null)
  6133. console.error("read file 2 data failed with error message: " + err.message);
  6134. })
  6135. .finally(() => {
  6136. fs.closeSync(file);
  6137. });
  6138. } catch (error) {
  6139. this.lyricController.setLyric(null)
  6140. this.lyricControllerSingle.setLyric(null)
  6141. this.lyricControllerXF.setLyric(null)
  6142. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  6143. }
  6144. }
  6145. detect(data: ArrayBuffer): string {
  6146. //创建检测对象
  6147. let detector: UniversalDetector = new UniversalDetector();
  6148. // 传入检测数据并实时判断编码格式
  6149. detector.handleData(data, 0, data.byteLength);
  6150. // 标记检测数据 读取结束
  6151. detector.dataEnd();
  6152. // 获取检测结果
  6153. let detected: string = detector.getDetectedCharset();
  6154. // 释放资源
  6155. detector.reset();
  6156. return detected;
  6157. }
  6158. //初始化悬浮歌词的自定义设置
  6159. initPipLyricSetting() {
  6160. this.lyricControllerXF
  6161. .setTextSize(this.currentLyricSize)
  6162. .setCacheSize(4)
  6163. .setTextColor("#DDDDDD")
  6164. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  6165. .setEmptyHint("")
  6166. .setAnimationDuration(1000)
  6167. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  6168. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  6169. this.setBlurDegree(this.blurDegreePip, true)
  6170. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  6171. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  6172. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  6173. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  6174. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  6175. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  6176. this.lyricControllerXF.setHightLightCenter(true)
  6177. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  6178. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  6179. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6180. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  6181. if (this.pipBgIndex === 0) {
  6182. if (this.cover) {
  6183. this.pipBg = this.cover
  6184. } else {
  6185. this.pipBg = this.imageColor
  6186. }
  6187. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6188. }
  6189. }
  6190. //根据item返回歌词内容
  6191. async getLyricContent(item: VideoItem): Promise<string> {
  6192. try {
  6193. let filePath = item.filePath;
  6194. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  6195. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  6196. let isJiaMi = false;
  6197. let realLyricPath = lyricPath;
  6198. if (FileUtil.accessSync(jiaMilyricPath)) {
  6199. isJiaMi = true;
  6200. realLyricPath = jiaMilyricPath;
  6201. console.info("onecold 找到加密本地歌词");
  6202. } else {
  6203. console.info("onecold 找到本地歌词");
  6204. }
  6205. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6206. const stat = await fileIo.stat(file.fd);
  6207. const arrayBuffer = new ArrayBuffer(stat.size);
  6208. const readLen = await fs.read(file.fd, arrayBuffer);
  6209. console.info("read file data succeed");
  6210. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6211. if (buf.length === 0) {
  6212. throw new Error("Buffer is empty after reading the file");
  6213. }
  6214. // let detectedEncoding = chardet.detect(buf);
  6215. let detectedEncoding = this.detect(arrayBuffer)
  6216. console.info("Detected encoding: " + detectedEncoding);
  6217. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6218. let fileContent = textDecoder.decode(buf);
  6219. console.info(`onecold The content of file1: ${fileContent}`);
  6220. if (isJiaMi) {
  6221. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  6222. }
  6223. console.info(`onecold The content of file2: ${fileContent}`);
  6224. fs.closeSync(file);
  6225. return fileContent;
  6226. } catch (error) {
  6227. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  6228. return '';
  6229. }
  6230. }
  6231. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  6232. if (StrUtil.isEmpty(filePath)) {
  6233. return
  6234. }
  6235. try {
  6236. //将content进行加密
  6237. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  6238. let lyricContent = ''
  6239. if (isJiaMi) {
  6240. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  6241. } else {
  6242. lyricContent = content
  6243. }
  6244. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  6245. // 清空文件内容
  6246. await fileIo.truncate(file.fd, 0);
  6247. await fileIo.write(file.fd, lyricContent);
  6248. await fileIo.close(file);
  6249. console.log('onecold lyric file Data saved successfully.');
  6250. } catch (error) {
  6251. console.error('onecold lyric file Failed to save data:', error);
  6252. }
  6253. }
  6254. /**
  6255. * Get largest proportion color of an image.
  6256. */
  6257. getImageColor() {
  6258. if (!this.context) {
  6259. return;
  6260. }
  6261. let bg = Utility.getMusisBg()
  6262. this.imageLabel = bg
  6263. ColorConversion.setSysBarLightBackground(true);
  6264. this.context.resourceManager.getMediaContent(bg)
  6265. .then((value: Uint8Array) => {
  6266. let buffer = value.buffer as ArrayBuffer;
  6267. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  6268. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  6269. if (error) {
  6270. Logger.error('Failed to create color picker.');
  6271. } else {
  6272. let color = colorPicker.getLargestProportionColor();
  6273. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  6274. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  6275. }
  6276. })
  6277. let headFilter = effectKit.createEffect(pixelMap);
  6278. if (headFilter !== null) {
  6279. headFilter.blur(15);
  6280. headFilter.getEffectPixelMap().then((value) => {
  6281. this.imageLabelBg = value;
  6282. })
  6283. }
  6284. })
  6285. .catch((error: BusinessError) => {
  6286. Logger.error(`${error.code} + ${error.message}`)
  6287. })
  6288. })
  6289. .catch((error: BusinessError) => {
  6290. Logger.error(`${error.code} + ${error.message}`)
  6291. })
  6292. }
  6293. setImageColor(cover: string) {
  6294. if (!this.context) {
  6295. return;
  6296. }
  6297. if (cover === undefined) {
  6298. return;
  6299. }
  6300. ImageUtils.imagePathToPixelMap(cover).then((value) => {
  6301. let headFilter = effectKit.createEffect(value);
  6302. if (headFilter !== null) {
  6303. headFilter.blur(15);
  6304. headFilter.getEffectPixelMap().then((value) => {
  6305. this.imageLabelBg = value;
  6306. })
  6307. }
  6308. }).catch((error: BusinessError) => {
  6309. Logger.error(`${error.code} + ${error.message}`)
  6310. })
  6311. }
  6312. setImageColor2(cover: string) {
  6313. if (!this.context) {
  6314. return;
  6315. }
  6316. if (cover === undefined) {
  6317. return;
  6318. }
  6319. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  6320. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  6321. this.imageColor = data.imageColor;
  6322. if (data.blurPixelMap) {
  6323. this.imageLabelBg = data.blurPixelMap;
  6324. }
  6325. })
  6326. }
  6327. // 定义开始旋转的方法
  6328. // 定时器用于一百毫秒执行一次旋转角度
  6329. @State timer: number = 0
  6330. @State rotateAngle: number = 0
  6331. //封面旋转动画
  6332. animationRoFun() {
  6333. if (this.isPlaying && !this.isCoverRectangle) {
  6334. this.timer = setInterval(() => {
  6335. this.rotateAngle += 1
  6336. }, 100)
  6337. this.startRotation()
  6338. } else {
  6339. clearInterval(this.timer)
  6340. this.stopRotation()
  6341. }
  6342. }
  6343. // 定义开始旋转的方法
  6344. startRotation() {
  6345. if (this.isPlaying) {
  6346. animateTo({
  6347. duration: 777,
  6348. iterations: 1,
  6349. curve: Curve.Linear
  6350. }, () => {
  6351. this.rotateAngle2 = 0
  6352. })
  6353. }
  6354. }
  6355. // 回调,暂停和播放按钮回调,下一首和上一首
  6356. playChange() {
  6357. // if(this.isCoverRectangle){
  6358. // return
  6359. // }
  6360. const isPlaying = this.CONTROL_PlayStatus === PlayStatus.PLAY;
  6361. // 同步所有播放状态
  6362. this.setIsPlaying(isPlaying);
  6363. this.animationState = isPlaying ? AnimationStatus.Running : AnimationStatus.Paused;
  6364. // 记录状态变化日志
  6365. LogUtils.getInstance().LOGI(`LocalMusic: playChange - CONTROL_PlayStatus: ${this.CONTROL_PlayStatus}, isPlaying: ${isPlaying}, globalIsPlaying: ${this.isPlaying}`);
  6366. // 强制触发UI刷新 - 这对于@State变量应该是自动的,但我们确保一下
  6367. setTimeout(() => {
  6368. LogUtils.getInstance().LOGI(`LocalMusic: UI refresh triggered - CONTROL_PlayStatus: ${this.CONTROL_PlayStatus}`);
  6369. }, 50);
  6370. }
  6371. // 手动同步状态的方法,用于调试
  6372. public forceSyncState(): void {
  6373. const currentState = this.unifiedPlayerService.getCurrentState();
  6374. LogUtils.getInstance().LOGI(`LocalMusic: Force sync - UnifiedPlayerService state: isPlaying=${currentState.isPlaying}, isPaused=${currentState.isPaused}`);
  6375. // 手动触发状态同步
  6376. if (currentState.isPlaying) {
  6377. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  6378. } else if (currentState.isPaused) {
  6379. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  6380. } else {
  6381. this.CONTROL_PlayStatus = PlayStatus.INIT;
  6382. }
  6383. this.setIsPlaying(currentState.isPlaying);
  6384. this.playChange();
  6385. LogUtils.getInstance().LOGI(`LocalMusic: Force sync completed - CONTROL_PlayStatus: ${this.CONTROL_PlayStatus}`);
  6386. }
  6387. // 定义停止旋转的方法
  6388. stopRotation() {
  6389. if (this.isCoverRectangle) {
  6390. this.rotateAngle = 0
  6391. } else {
  6392. //唱针以左上角为点选择逆时针40度
  6393. animateTo({
  6394. duration: 1000,
  6395. curve: Curve.Linear,
  6396. iterations: 1,
  6397. }, () => {
  6398. this.rotateAngle2 = -40;
  6399. });
  6400. }
  6401. }
  6402. @Builder
  6403. private LyricsTopItem() {
  6404. Row() {
  6405. Stack() {
  6406. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6407. .height(55)
  6408. .width(55)
  6409. .alt(this.imageLabel)
  6410. .borderRadius(8)
  6411. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6412. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6413. }
  6414. .width('18%')
  6415. Column() {
  6416. Column() {
  6417. Text(this.name)
  6418. .fontSize(16)
  6419. .maxLines(1)
  6420. .fontWeight(FontWeight.Bolder)
  6421. .fontColor(this.currentLyricColor)
  6422. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6423. Row() {
  6424. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6425. .fontSize(13)
  6426. .fontWeight(FontWeight.Bold)
  6427. .padding({ top: 8 })
  6428. .fontColor(this.currentLyricColor)
  6429. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6430. Blank()
  6431. }
  6432. }
  6433. .height('100%')
  6434. .width('100%')
  6435. .justifyContent(FlexAlign.Center)
  6436. .alignItems(HorizontalAlign.Start)
  6437. }
  6438. .height('100%')
  6439. .width('65%')
  6440. Column() {
  6441. Image($r('app.media.lyric'))
  6442. .width(28)
  6443. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6444. .margin({ right: 30 })
  6445. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6446. .onClick(() => {
  6447. this.isLyricSetting = !this.isLyricSetting;
  6448. })
  6449. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6450. height: this.isCoverOpacity() ? '95%' : '88%',
  6451. dragBar: true,
  6452. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6453. showClose: true,
  6454. blurStyle: BlurStyle.Thin,
  6455. backgroundColor: Color.Transparent,
  6456. // title: { title: $r('app.string.lyric_setting') }
  6457. })
  6458. }
  6459. .width('18%')
  6460. }
  6461. .width('82%')
  6462. .height(58)
  6463. .justifyContent(FlexAlign.SpaceBetween)
  6464. }
  6465. //歌词显示
  6466. @Builder
  6467. PlayerLyrics() {
  6468. Column() {
  6469. Column() {
  6470. this.LyricsTopItem()
  6471. }
  6472. .height(this.isPuraWP() ? 15 : 58)
  6473. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6474. Visibility.None : Visibility.Visible)
  6475. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6476. .width("100%")
  6477. Column() {
  6478. LyricView2({
  6479. controller: this.lyricController,
  6480. enableSeek: true,
  6481. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6482. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6483. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6484. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6485. if (!this.isPlaying) {
  6486. this.startPlayOrResumePlay()
  6487. } else {
  6488. this.isSeekTo = true;
  6489. this.mDestroyPage = false;
  6490. this.showLoadIng();
  6491. this.seekTo(position + "");
  6492. this.isSeekTo = false;
  6493. }
  6494. return true
  6495. }
  6496. })
  6497. .width("100%")
  6498. .layoutWeight(1)
  6499. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6500. if (this.isPhoneLan()) {
  6501. Column() {
  6502. this.playCenterView()
  6503. }
  6504. .margin({ bottom: 20, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6505. }
  6506. }
  6507. .position({
  6508. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6509. (this.isPuraWP() ? 58 : 99)
  6510. })
  6511. .justifyContent(FlexAlign.Center)
  6512. .height(this.isCoverOpacity() ? '95%' : '80%')
  6513. }
  6514. }
  6515. @Builder
  6516. SingleLyricView() {
  6517. Column() {
  6518. Column() {
  6519. LyricView2({
  6520. controller: this.lyricControllerSingle,
  6521. enableSeek: false,
  6522. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6523. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6524. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6525. })
  6526. }
  6527. .height(66)
  6528. .margin({ bottom: 20 })
  6529. }
  6530. }
  6531. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6532. @Builder
  6533. BottomControl() {
  6534. Column() {
  6535. //播放 暂停,下一首,上一首
  6536. this.playCenterView()
  6537. //播放进度条
  6538. this.playProgressView()
  6539. }
  6540. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 100) }) // 将 固定在底部
  6541. }
  6542. //播放控制上一首 下一首 暂停和播放
  6543. @Builder
  6544. playCenterView() {
  6545. Row() {
  6546. Row({ space: 20 }) {
  6547. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6548. //更多功能
  6549. Image($r('app.media.menu'))
  6550. .width(24)
  6551. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6552. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6553. height: this.isCoverOpacity() ? '95%' : '93%',
  6554. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6555. dragBar: true,
  6556. showClose: true,
  6557. blurStyle: BlurStyle.Thin,
  6558. backgroundColor: Color.Transparent,
  6559. })
  6560. }
  6561. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6562. .backgroundColor(Color.Transparent)
  6563. .onClick(() => {
  6564. this.isShowMoreView = !this.isShowMoreView;
  6565. })
  6566. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6567. Image($r('app.media.ic_previous'))
  6568. .width(33)
  6569. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6570. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6571. }
  6572. .onClick(async () => {
  6573. this.playPrevious()
  6574. })
  6575. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6576. .backgroundColor(Color.Transparent)
  6577. .margin({ left: 5 })
  6578. }
  6579. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6580. Column() {
  6581. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6582. (this.isCircleBtn ? $r('app.media.hm_pause') : $r('app.media.ic_public_play'))
  6583. : (this.isCircleBtn ? $r('app.media.hm_play2') : $r('app.media.ic_public_pause')))
  6584. .width(this.isPhoneLan() ? 48 : 60)
  6585. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6586. .fillColor(Color.White)
  6587. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6588. .onClick(async () => {
  6589. this.playOrPause()
  6590. })
  6591. }
  6592. }
  6593. .backgroundColor(Color.Transparent)
  6594. .layoutWeight(1)
  6595. .margin({ left: 38, right: 38 })
  6596. Row({ space: 20 }) {
  6597. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6598. Image($r('app.media.ic_next'))
  6599. .width(33)
  6600. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6601. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6602. .onClick(() => {
  6603. this.playNext();
  6604. })
  6605. }
  6606. .backgroundColor(Color.Transparent)
  6607. .margin({ right: 5 })
  6608. .width(33)
  6609. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6610. //添加或取消收藏
  6611. Image(Utility.getIsFav(this.favList, this.currentSong) ?
  6612. $r('app.media.add_fac_light') : $r('app.media.add_fac'))
  6613. .width(24)
  6614. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6615. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6616. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6617. .onClick(async () => {
  6618. if (this.currentSong) {
  6619. this.doFav(this.currentSong)
  6620. }
  6621. })
  6622. }
  6623. .backgroundColor(Color.Transparent)
  6624. .width(24)
  6625. }
  6626. // .margin({ left: 5 })
  6627. }
  6628. .width('100%')
  6629. .margin({ left: 10, right: 10, bottom: this.isCoverOpacity() ? 0 : 20 })
  6630. .justifyContent(FlexAlign.Center)
  6631. }
  6632. //播放进度条
  6633. @Builder
  6634. playProgressView() {
  6635. Row() {
  6636. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6637. Column() {
  6638. if (this.playType === 0) {
  6639. Image($r('app.media.loop'))
  6640. .width($r('app.float.control_image_width'))
  6641. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6642. } else if (this.playType === 1) {
  6643. Image($r('app.media.single'))
  6644. .width($r('app.float.control_image_width'))
  6645. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6646. } else if (this.playType === 2) {
  6647. Image($r('app.media.normal_play'))
  6648. .width($r('app.float.control_image_width'))
  6649. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6650. } else if (this.playType === 3) {
  6651. Image($r('app.media.random'))
  6652. .width($r('app.float.control_image_width'))
  6653. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6654. }
  6655. }
  6656. }
  6657. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6658. .animation({
  6659. duration: 666,
  6660. curve: 'ease-in-out' // 可选动画曲线
  6661. })
  6662. .backgroundColor(Color.Transparent)
  6663. .margin({ left: 20, right: 10 })
  6664. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6665. .onClick(async () => {
  6666. this.setLoopMode()
  6667. })
  6668. Text(this.currentTime)
  6669. .fontSize($r('app.float.slider_font_size'))
  6670. .fontColor(Color.White)
  6671. .margin(3)
  6672. Slider({
  6673. value: this.progressValue,
  6674. min: 0,
  6675. max: this.PROGRESS_MAX_VALUE,
  6676. step: 1,
  6677. style: SliderStyle.OutSet
  6678. })
  6679. .width('600px')
  6680. .blockColor('rgba(255,255,255,1)')
  6681. .trackColor('rgba(255,255,255,0.3)')
  6682. .selectedColor(Color.White)
  6683. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  6684. .layoutWeight(1)
  6685. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6686. .showSteps(false)
  6687. .showTips(true)
  6688. .enabled(this.slideEnable)
  6689. .onChange((value: number, mode: SliderChangeMode) => {
  6690. // if (mode == 2) {
  6691. this.isSeekTo = true;
  6692. this.mDestroyPage = false;
  6693. this.showLoadIng();
  6694. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6695. // 通过UnifiedPlayerService获取时长并计算拖动位置
  6696. const currentState = this.unifiedPlayerService.getCurrentState();
  6697. let seekValue = value * (currentState.duration / 100);
  6698. this.seekTo(seekValue + "");
  6699. // this.setProgress()
  6700. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6701. this.isSeekTo = false;
  6702. // }
  6703. })
  6704. Text(this.totalTime)
  6705. .fontSize($r('app.float.slider_font_size'))
  6706. .fontColor(Color.White)
  6707. .margin(3)
  6708. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6709. //播放列表
  6710. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6711. Image($r('app.media.hm_playlist'))
  6712. .width($r('app.float.control_image_width'))
  6713. .fillColor(Color.White)
  6714. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6715. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6716. height: '95%',
  6717. dragBar: true,
  6718. showClose: true,
  6719. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6720. blurStyle: BlurStyle.Thin,
  6721. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6722. title: {
  6723. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6724. + `(${this.songList.length}首)`
  6725. }
  6726. })
  6727. }
  6728. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6729. .animation({
  6730. duration: 666,
  6731. curve: 'ease-in-out' // 可选动画曲线
  6732. })
  6733. .backgroundColor(Color.Transparent)
  6734. .margin({ right: 20, left: 10 })
  6735. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6736. .onClick(() => {
  6737. this.isShowSheetView = !this.isShowSheetView;
  6738. if (this.isPlayListBgGrass) {
  6739. this.isFrontWhite = true
  6740. } else {
  6741. this.isFrontWhite = false
  6742. }
  6743. setTimeout(() => {
  6744. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  6745. }, 123)
  6746. })
  6747. }
  6748. //x5的竖屏模式需要99%
  6749. .width(this.isPhonePortrait() ? '93.4%'
  6750. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  6751. .height(this.isPhoneLan() ? 25 : 33)
  6752. .animation({
  6753. duration: 666,
  6754. curve: 'ease-in-out' // 可选动画曲线
  6755. })
  6756. }
  6757. isBigScreen() {
  6758. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  6759. return true
  6760. }
  6761. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6762. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6763. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  6764. return false
  6765. } else {
  6766. return true
  6767. }
  6768. return false
  6769. }
  6770. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  6771. @State isCoverRectangle: boolean = false
  6772. @State isCoverTop: boolean = true
  6773. // 添加控制缩放的状态变量
  6774. @State scaleValueImage: number = 1
  6775. @Builder
  6776. CoverInfo() {
  6777. Column() {
  6778. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  6779. if (this.isCoverRectangle) {
  6780. if (!this.isCoverTop) {
  6781. this.musicNameInfo(false)
  6782. }
  6783. } else {
  6784. this.musicNameInfo(false)
  6785. }
  6786. Stack() {
  6787. // 唱片旋转效果
  6788. Image($r('app.media.ic_music_disc'))
  6789. .width(245)
  6790. .height(245)
  6791. .margin({ right: 20, left: 20 })
  6792. .aspectRatio(1)
  6793. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6794. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6795. .borderRadius('100%')
  6796. .align(Alignment.Center)
  6797. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  6798. .rotate({
  6799. angle: this.rotateAngle,
  6800. centerX: "50%",
  6801. centerY: "50%",
  6802. })
  6803. .animation({
  6804. duration: 100,
  6805. curve: Curve.Linear
  6806. })
  6807. .shadow({
  6808. radius: 30,
  6809. color: this.randomColor
  6810. })
  6811. Column() {
  6812. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  6813. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  6814. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  6815. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6816. .alt(this.imageLabel)
  6817. .margin({ right: 8, left: 8, top: 8 })
  6818. .aspectRatio(1)
  6819. .opacity(this.opacityValueImage)
  6820. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6821. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  6822. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6823. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6824. .align(Alignment.Center)//
  6825. .clip(true)
  6826. .rotate({
  6827. x: 0,
  6828. y: 0,
  6829. z: 1,
  6830. angle: this.rotateAngle
  6831. })
  6832. .onClick(() => {
  6833. this.getImageColor()
  6834. })
  6835. this.musicNameInfo(false)
  6836. } else {
  6837. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6838. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:220):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  6839. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6840. .alt(this.imageLabel)
  6841. .margin({ right: 20, left: 20 })
  6842. .aspectRatio(1)
  6843. .opacity(this.opacityValueImage)
  6844. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6845. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6846. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6847. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  6848. .align(Alignment.Center)//
  6849. .clip(true)
  6850. .rotate({
  6851. x: 0,
  6852. y: 0,
  6853. z: 1,
  6854. angle: this.rotateAngle
  6855. })
  6856. .onClick(() => {
  6857. this.getImageColor()
  6858. })
  6859. if (this.isPhoneLan()) {
  6860. Text(this.name)
  6861. .fontSize(18)
  6862. .fontWeight(FontWeight.Bold)
  6863. .margin({ top: 13 })
  6864. .textOverflow({ overflow: TextOverflow.Ellipsis })
  6865. .maxLines(1)
  6866. .width('99%')
  6867. .textAlign(TextAlign.Center)
  6868. .fontColor(Color.White)
  6869. }
  6870. }
  6871. }
  6872. // 唱针以左上角为点选择逆时针40度
  6873. Image($r('app.media.ic_music_cover_hand'))
  6874. .height(130)
  6875. .margin({ bottom: 220, top: 0 })
  6876. .align(Alignment.Top)
  6877. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  6878. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6879. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6880. Column({ space: 8 }) {
  6881. Text(this.name)
  6882. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  6883. .fontWeight(FontWeight.Bold)
  6884. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6885. .maxLines(1)
  6886. .width('48%')
  6887. .textAlign(TextAlign.Center)
  6888. .fontColor(Color.White)
  6889. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6890. Text(this.artist)
  6891. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  6892. .fontColor(Color.White)
  6893. .fontWeight(FontWeight.Bold)
  6894. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6895. }
  6896. .justifyContent(FlexAlign.Start)
  6897. .zIndex(1)
  6898. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  6899. }
  6900. .margin({
  6901. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  6902. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  6903. top: this.isCoverOpacity() ? 0 : 20
  6904. })
  6905. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  6906. this.SingleLyricView()
  6907. }
  6908. if (this.isPhoneLan()) {
  6909. Column() {
  6910. this.playProgressView()
  6911. }
  6912. .position({ left: 40, bottom: 48 })
  6913. } else {
  6914. this.BottomControl()
  6915. }
  6916. }
  6917. .width(CommonConstants.FULL_PERCENT)
  6918. .clip(true)
  6919. }
  6920. @Builder
  6921. private musicNameInfo(isHidden: boolean) {
  6922. Column({ space: 8 }) {
  6923. Text(this.name)
  6924. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  6925. .fontWeight(FontWeight.Bold)
  6926. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6927. .maxLines(1)
  6928. .width('99%')
  6929. .textAlign(TextAlign.Center)
  6930. .fontColor(Color.White)
  6931. Text(this.artist + ' ' + this.currentSong?.album)
  6932. .fontSize(this.isCoverOpacity() ? 12 : 15)
  6933. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6934. .fontColor(Color.White)
  6935. .textAlign(TextAlign.Center)
  6936. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  6937. .width('99%')
  6938. .maxLines(1)
  6939. }
  6940. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  6941. .zIndex(1)
  6942. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6943. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  6944. }
  6945. @Builder
  6946. private PlayTitle() {
  6947. Row() {
  6948. Row() {
  6949. Image($r('app.media.ic_back_down'))
  6950. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  6951. .hitTestBehavior(HitTestMode.Transparent)
  6952. Text(this.name + ' ' + this.artist)
  6953. .fontColor(Color.White)
  6954. .fontSize($r('app.float.title_font_size'))
  6955. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6956. .maxLines(1)
  6957. .visibility(Visibility.None)
  6958. .margin({ left: 2, right: 30 })
  6959. }
  6960. .layoutWeight(1)
  6961. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6962. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  6963. .onClick(() => {
  6964. this.isShowPlay = false;
  6965. })
  6966. Column() {
  6967. AVCastPicker({
  6968. normalColor: Color.White,
  6969. onStateChange: this.onStateVastChange
  6970. })
  6971. .width(24)
  6972. .height(24)
  6973. }
  6974. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  6975. }
  6976. .width(PlayConstants.ROW_WIDTH)
  6977. }
  6978. @Builder
  6979. lyricSettingSheet(isPip: boolean) {
  6980. Scroll() {
  6981. this.lyricSetting(isPip)
  6982. }
  6983. .width('100%')
  6984. .height('100%')
  6985. }
  6986. @Builder
  6987. lyricSetting(isPip: boolean) {
  6988. Column() {
  6989. // 时间调节模块
  6990. if (!isPip) {
  6991. this.BuildTimeControls()
  6992. }
  6993. // 字号控制模块
  6994. this.BuildFontControls(isPip)
  6995. }
  6996. }
  6997. // 歌词时间偏移状态
  6998. @State timeOffset: number = 0.0
  6999. @State currentLyricColor: string = '#FFFFFF'
  7000. @State currentLyricColorPip: string = '#FFFFFF'
  7001. @State currentHighLightLyricColor: string = '#FF4081'
  7002. @State currentHighLightLyricColorPip: string = '#FF4081'
  7003. // 歌词字号状态
  7004. @State currentLyricSize: number = 20
  7005. @State currentLyricSizePip: number = 20
  7006. // 高亮歌词放大倍数
  7007. @State currentHightLyricSize: number = 1.2
  7008. @State currentHightLyricSizePip: number = 1.2
  7009. @State currentLyricLineSpace: number = 10
  7010. @State currentLyricLineSpacePip: number = 10
  7011. @State currentLyricAlignMode: number = 1
  7012. @State currentLyricAlignModePip: number = 1
  7013. @State blurDegree: number = 2
  7014. @State blurDegreePip: number = 2
  7015. @State isShowSelectColor: boolean = false
  7016. @State isShowHLSelectColor: boolean = false
  7017. @State isShowPipBgSelectColor: boolean = false
  7018. @State pipLyWidth: number = 330
  7019. @State pipLyHeight: number = 120
  7020. // 构建颜色选择器
  7021. @Builder
  7022. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  7023. Row({ space: 10 }) {
  7024. HSBColorPicker({
  7025. color: '#FFFFFF',
  7026. radius: 8,
  7027. layout: HSBColorPickerLayout.COLUMN,
  7028. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  7029. '#fa7105'],
  7030. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  7031. this.changeLyricColor(value, isPip, isBGPip)
  7032. })
  7033. .height(250)
  7034. .layoutWeight(1)
  7035. .padding(25)
  7036. }
  7037. .width('66%')
  7038. }
  7039. @State isOpenPip: boolean = false
  7040. @State pipBgIndex: number = 0
  7041. // 构建字号控制器
  7042. @Builder
  7043. BuildFontControls(isPip: boolean) {
  7044. Column() {
  7045. if (isPip) {
  7046. Column() {
  7047. Row() {
  7048. Text('悬浮歌词')
  7049. .margin({ left: 18 })
  7050. .fontSize(15)
  7051. .fontColor(Color.White)
  7052. .fontWeight(480)
  7053. .layoutWeight(1)
  7054. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  7055. .selectedColor(this.themeColor)
  7056. .switchPointColor(Color.White)
  7057. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7058. .margin({ right: 18 })
  7059. .onChange((checked: boolean) => {
  7060. this.isOpenPip = checked;
  7061. if (this.isOpenPip) {
  7062. this.startPip()
  7063. } else {
  7064. this.stopPip()
  7065. }
  7066. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  7067. })
  7068. .width(50)
  7069. .height(30);
  7070. }
  7071. .height(55)
  7072. }
  7073. .backgroundColor(Color.Transparent)
  7074. .borderRadius(15)
  7075. .margin({
  7076. left: 30,
  7077. right: 30,
  7078. top: 0,
  7079. bottom: 20
  7080. })
  7081. .padding(0)
  7082. .border({
  7083. color: Color.White,
  7084. width: 1.8
  7085. })
  7086. }
  7087. Row() {
  7088. Text(`歌词居中:`)
  7089. .fontSize(14)
  7090. .fontColor(Color.White)
  7091. .margin({ left: 2 })
  7092. Row() {
  7093. ForEach(['居中', '居左'], (size: string, index: number) => {
  7094. Button(size)
  7095. .width(60)
  7096. .height(28)
  7097. .fontSize(12)
  7098. .fontColor('#FFFFFF')
  7099. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  7100. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  7101. .border({
  7102. color: (!isPip && this.currentLyricAlignMode === index) ||
  7103. (isPip && this.currentLyricAlignModePip === index) ?
  7104. '#007DFF' : '#DDDDDD',
  7105. width: 1.8
  7106. })
  7107. .onClick(() => {
  7108. this.setLyricAlignMode(index, isPip)
  7109. })
  7110. .margin({ left: 10, right: 8 })
  7111. })
  7112. }
  7113. .width('76%')
  7114. Blank()
  7115. }
  7116. .margin({
  7117. top: 10,
  7118. bottom: 10,
  7119. right: 20,
  7120. left: 20
  7121. })
  7122. if (isPip) {
  7123. Row() {
  7124. Text(`悬浮背景:`)
  7125. .fontSize(14)
  7126. .fontColor(Color.White)
  7127. Select([
  7128. { value: CommonConstants.PIP_LYRIC_BG[0] },
  7129. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  7130. .font({ size: 13, weight: FontWeight.Medium })
  7131. .fontColor(Color.White)
  7132. .margin({ left: 10 })
  7133. .selected(this.pipBgIndex)
  7134. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  7135. .onSelect(async (_index: number, text?: string | undefined) => {
  7136. this.pipBgIndex = _index
  7137. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  7138. if (this.pipBgIndex === 0) {
  7139. if (this.cover) {
  7140. this.pipBg = this.cover
  7141. } else {
  7142. this.pipBg = this.imageColor
  7143. }
  7144. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7145. } else {
  7146. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7147. }
  7148. })
  7149. Column() {
  7150. }
  7151. .backgroundColor(this.pipBg)
  7152. .margin({ left: 10, right: 10 })
  7153. .borderRadius(20)
  7154. .height(28)
  7155. .width(28)
  7156. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7157. Row() {
  7158. SymbolGlyph($r('sys.symbol.paintbrush'))
  7159. .fontColor([Color.White])
  7160. .effectStrategy(1)
  7161. Text(`选择颜色`)
  7162. .fontSize(13)
  7163. .margin({ left: 10 })
  7164. .fontColor(Color.White)
  7165. }
  7166. }
  7167. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  7168. .backgroundColor(Color.Transparent)
  7169. .border({
  7170. color: '#FFFFFF',
  7171. radius: 20,
  7172. width: 1.8
  7173. })
  7174. .height(36)
  7175. .width(110)
  7176. .onClick(() => {
  7177. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  7178. })
  7179. .bindPopup(this.isShowPipBgSelectColor, {
  7180. builder: this.SelectColor(false, isPip, true),
  7181. placement: Placement.Top,
  7182. mask: { color: '#33000000' },
  7183. enableArrow: false, //是否显示箭头
  7184. showInSubWindow: false,
  7185. onStateChange: (e) => {
  7186. if (!e.isVisible) {
  7187. this.isShowPipBgSelectColor = false
  7188. }
  7189. }
  7190. })
  7191. }
  7192. .width('76%')
  7193. .margin({ bottom: 5, right: 45, left: 20 })
  7194. }
  7195. if (!isPip) {
  7196. Row() {
  7197. Text(`高亮居中:`)
  7198. .fontSize(14)
  7199. .fontColor(Color.White)
  7200. Column() {
  7201. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  7202. .selectedColor(this.themeColor)
  7203. .switchPointColor(Color.White)
  7204. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7205. .onChange((checked: boolean) => {
  7206. this.isHightLightCenter = checked;
  7207. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  7208. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7209. })
  7210. .width(50)
  7211. .height(30)
  7212. .alignSelf(ItemAlign.Start)
  7213. .margin({ left: 12 })
  7214. Blank()
  7215. }
  7216. .width('76%')
  7217. }
  7218. .margin({
  7219. left: 20,
  7220. right: 15,
  7221. top: 10,
  7222. bottom: 10
  7223. })
  7224. }
  7225. Row() {
  7226. Text(`歌词颜色:`)
  7227. .fontSize(14)
  7228. .fontColor(Color.White)
  7229. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7230. .fontSize(15)
  7231. .fontColor(Color.White)
  7232. .margin({ left: 12, right: 12 })
  7233. Column() {
  7234. }
  7235. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7236. .margin({ right: 12 })
  7237. .borderRadius(20)
  7238. .height(28)
  7239. .width(28)
  7240. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7241. Row() {
  7242. SymbolGlyph($r('sys.symbol.paintbrush'))
  7243. .fontColor([Color.White])
  7244. .effectStrategy(1)
  7245. Text(`选择颜色`)
  7246. .fontSize(13)
  7247. .margin({ left: 10 })
  7248. .fontColor(Color.White)
  7249. }
  7250. }
  7251. .backgroundColor(Color.Transparent)
  7252. .border({
  7253. color: '#FFFFFF',
  7254. radius: 20,
  7255. width: 1.8
  7256. })
  7257. .height(36)
  7258. .width(110)
  7259. .onClick(() => {
  7260. this.isShowSelectColor = !this.isShowSelectColor
  7261. })
  7262. .bindPopup(this.isShowSelectColor, {
  7263. builder: this.SelectColor(false, isPip),
  7264. placement: Placement.Top,
  7265. mask: { color: '#33000000' },
  7266. enableArrow: false, //是否显示箭头
  7267. showInSubWindow: false,
  7268. onStateChange: (e) => {
  7269. if (!e.isVisible) {
  7270. this.isShowSelectColor = false
  7271. }
  7272. }
  7273. })
  7274. }
  7275. .width('76%')
  7276. .margin({
  7277. top: 10,
  7278. bottom: 10,
  7279. right: 45,
  7280. left: 20
  7281. })
  7282. Row() {
  7283. Text(`高亮颜色:`)
  7284. .fontSize(14)
  7285. .fontColor(Color.White)
  7286. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7287. .fontSize(15)
  7288. .fontColor(Color.White)
  7289. .margin({ left: 12, right: 12 })
  7290. Column() {
  7291. }
  7292. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7293. .margin({ right: 12 })
  7294. .borderRadius(20)
  7295. .height(28)
  7296. .width(28)
  7297. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7298. Row() {
  7299. SymbolGlyph($r('sys.symbol.paintbrush'))
  7300. .fontColor([Color.White])
  7301. .effectStrategy(1)
  7302. Text(`选择颜色`)
  7303. .fontSize(13)
  7304. .margin({ left: 10 })
  7305. .fontColor(Color.White)
  7306. }
  7307. }
  7308. .backgroundColor(Color.Transparent)
  7309. .border({
  7310. color: '#FFFFFF',
  7311. radius: 20,
  7312. width: 1.8
  7313. })
  7314. .height(36)
  7315. .width(110)
  7316. .onClick(() => {
  7317. this.isShowHLSelectColor = !this.isShowHLSelectColor
  7318. })
  7319. .bindPopup(this.isShowHLSelectColor, {
  7320. builder: this.SelectColor(true, isPip),
  7321. placement: Placement.Top,
  7322. mask: { color: '#33000000' },
  7323. enableArrow: false, //是否显示箭头
  7324. showInSubWindow: false,
  7325. onStateChange: (e) => {
  7326. if (!e.isVisible) {
  7327. this.isShowHLSelectColor = false
  7328. }
  7329. }
  7330. })
  7331. }
  7332. .width('76%')
  7333. .margin({
  7334. top: 10,
  7335. bottom: 10,
  7336. right: 45,
  7337. left: 20
  7338. })
  7339. if (isPip) {
  7340. Row() {
  7341. Text(`显示宽度:`)
  7342. .fontSize(14)
  7343. .fontColor(Color.White)
  7344. Slider({
  7345. value: this.pipLyWidth,
  7346. min: 10,
  7347. max: 800,
  7348. step: 1,
  7349. style: SliderStyle.OutSet
  7350. })
  7351. .blockColor(this.themeColor)
  7352. .trackColor($r('app.color.speed_text_color'))
  7353. .selectedColor(Color.White)
  7354. .trackThickness(6)
  7355. .onChange((value: number) => {
  7356. this.pipLyWidth = value
  7357. if (this.pipController) {
  7358. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7359. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  7360. }
  7361. })
  7362. .width('76%')
  7363. }
  7364. .margin({
  7365. left: 20,
  7366. right: 15,
  7367. top: 5,
  7368. bottom: 5
  7369. })
  7370. Row() {
  7371. Text(`显示高度:`)
  7372. .fontSize(14)
  7373. .fontColor(Color.White)
  7374. Slider({
  7375. value: this.pipLyHeight,
  7376. min: 10,
  7377. max: 1000,
  7378. step: 1,
  7379. style: SliderStyle.OutSet
  7380. })
  7381. .blockColor(this.themeColor)
  7382. .trackColor($r('app.color.speed_text_color'))
  7383. .selectedColor(Color.White)
  7384. .trackThickness(6)
  7385. .onChange((value: number) => {
  7386. this.pipLyHeight = value
  7387. if (this.pipController) {
  7388. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7389. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7390. }
  7391. })
  7392. .width('76%')
  7393. }
  7394. .margin({
  7395. left: 20,
  7396. right: 15,
  7397. top: 5,
  7398. bottom: 5
  7399. })
  7400. }
  7401. Row() {
  7402. Text(`歌词字号:`)
  7403. .fontSize(14)
  7404. .fontColor(Color.White)
  7405. Slider({
  7406. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7407. min: 12,
  7408. max: 30,
  7409. step: 0.1,
  7410. style: SliderStyle.OutSet
  7411. })
  7412. .blockColor(this.themeColor)
  7413. .trackColor($r('app.color.speed_text_color'))
  7414. .selectedColor(Color.White)
  7415. .trackThickness(6)
  7416. .onChange((value: number) => {
  7417. this.setLyricTextSize(value, isPip)
  7418. })
  7419. .width('76%')
  7420. }
  7421. .margin({
  7422. left: 20,
  7423. right: 15,
  7424. top: 5,
  7425. bottom: 5
  7426. })
  7427. Row() {
  7428. Text(`高亮倍数:`)
  7429. .fontSize(14)
  7430. .fontColor(Color.White)
  7431. Slider({
  7432. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7433. min: 1,
  7434. max: 2,
  7435. step: 0.1,
  7436. style: SliderStyle.OutSet
  7437. })
  7438. .blockColor(this.themeColor)
  7439. .trackColor($r('app.color.speed_text_color'))
  7440. .selectedColor(Color.White)
  7441. .trackThickness(6)
  7442. .onChange((value: number) => {
  7443. this.setHighLyricTextSize(value, isPip)
  7444. })
  7445. .width('76%')
  7446. }
  7447. .margin({
  7448. left: 20,
  7449. right: 15,
  7450. top: 5,
  7451. bottom: 5
  7452. })
  7453. Row() {
  7454. Text(`歌词间隙:`)
  7455. .fontSize(14)
  7456. .fontColor(Color.White)
  7457. Slider({
  7458. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7459. min: 0,
  7460. max: 100,
  7461. step: 1,
  7462. style: SliderStyle.OutSet
  7463. })
  7464. .blockColor(this.themeColor)
  7465. .trackColor($r('app.color.speed_text_color'))
  7466. .selectedColor(Color.White)
  7467. .trackThickness(6)
  7468. .onChange((value: number) => {
  7469. this.setLyricLineSpace(value, isPip)
  7470. })
  7471. .width('76%')
  7472. }
  7473. .margin({
  7474. left: 20,
  7475. right: 15,
  7476. top: 5,
  7477. bottom: 5
  7478. })
  7479. //取值间隔为100,默认为400,取值越大,字体越粗
  7480. Row() {
  7481. Text(`歌词字重:`)
  7482. .fontSize(14)
  7483. .fontColor(Color.White)
  7484. Slider({
  7485. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7486. min: 100,
  7487. max: 900,
  7488. step: 100,
  7489. style: SliderStyle.OutSet
  7490. })
  7491. .blockColor(this.themeColor)
  7492. .trackColor($r('app.color.speed_text_color'))
  7493. .selectedColor(Color.White)
  7494. .trackThickness(6)
  7495. .onChange((value: number) => {
  7496. if (isPip) {
  7497. this.lyricTextWeightPip = value
  7498. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7499. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7500. } else {
  7501. this.lyricTextWeight = value
  7502. this.lyricController.setTextWeight(this.lyricTextWeight)
  7503. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7504. }
  7505. })
  7506. .width('76%')
  7507. }
  7508. .margin({
  7509. left: 20,
  7510. right: 15,
  7511. top: 5,
  7512. bottom: 5
  7513. })
  7514. if (!isPip) {
  7515. Row() {
  7516. Text(`歌词模糊:`)
  7517. .fontSize(14)
  7518. .fontColor(Color.White)
  7519. Slider({
  7520. value: isPip ? this.blurDegreePip : this.blurDegree,
  7521. min: 0,
  7522. max: 5,
  7523. step: 0.1,
  7524. style: SliderStyle.OutSet
  7525. })
  7526. .blockColor(this.themeColor)
  7527. .trackColor($r('app.color.speed_text_color'))
  7528. .selectedColor(Color.White)
  7529. .trackThickness(6)
  7530. .onChange((value: number) => {
  7531. this.setBlurDegree(value, isPip)
  7532. })
  7533. .width('76%')
  7534. }
  7535. .margin({
  7536. left: 20,
  7537. right: 15,
  7538. top: 5,
  7539. bottom: 15
  7540. })
  7541. }
  7542. Row() {
  7543. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7544. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7545. }
  7546. .justifyContent(FlexAlign.Center)
  7547. .margin({ top: 3, bottom: 10 })
  7548. }
  7549. }
  7550. private setBlurDegree(index: number, isPip: boolean) {
  7551. if (isPip) {
  7552. this.blurDegreePip = index
  7553. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7554. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7555. } else {
  7556. this.blurDegree = index
  7557. this.lyricController.setBlurDegree(this.blurDegree)
  7558. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7559. }
  7560. }
  7561. private setLyricAlignMode(index: number, isPip: boolean) {
  7562. if (isPip) {
  7563. this.currentLyricAlignModePip = index
  7564. if (this.currentLyricAlignModePip === 1) {
  7565. this.lyricControllerXF.setAlignMode("left")
  7566. } else {
  7567. this.lyricControllerXF.setAlignMode("center")
  7568. }
  7569. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7570. } else {
  7571. this.currentLyricAlignMode = index
  7572. if (this.currentLyricAlignMode === 1) {
  7573. this.lyricController.setAlignMode("left")
  7574. } else {
  7575. this.lyricController.setAlignMode("center")
  7576. }
  7577. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7578. }
  7579. }
  7580. private setLyricTextSize(index: number, isPip: boolean) {
  7581. if (isPip) {
  7582. this.currentLyricSizePip = index
  7583. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7584. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7585. } else {
  7586. this.currentLyricSize = index
  7587. this.lyricController.setTextSize(this.currentLyricSize)
  7588. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7589. }
  7590. }
  7591. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7592. if (isPip) {
  7593. this.currentHightLyricSizePip = scale
  7594. this.lyricControllerXF
  7595. .setHighlightScale(this.currentHightLyricSizePip)
  7596. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7597. } else {
  7598. this.currentHightLyricSize = scale
  7599. this.lyricController
  7600. .setHighlightScale(this.currentHightLyricSize)
  7601. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7602. }
  7603. }
  7604. private setLyricLineSpace(index: number, isPip: boolean) {
  7605. if (isPip) {
  7606. this.currentLyricLineSpacePip = index
  7607. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7608. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7609. } else {
  7610. this.currentLyricLineSpace = index
  7611. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7612. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7613. }
  7614. }
  7615. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7616. LogUtil.info('onecold isBG = ' + isBG)
  7617. if (isBG) { //如果是设置悬浮背景
  7618. this.pipBg = color
  7619. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7620. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7621. return
  7622. }
  7623. if (isPip) {
  7624. this.currentLyricColorPip = color
  7625. this.lyricControllerXF
  7626. .setTextColor(this.currentLyricColorPip)
  7627. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7628. } else {
  7629. this.currentLyricColor = color
  7630. this.lyricController
  7631. .setTextColor(this.currentLyricColor)
  7632. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7633. }
  7634. }
  7635. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7636. if (isPip) {
  7637. this.currentHighLightLyricColorPip = color
  7638. this.lyricControllerXF
  7639. .setHighlightColor(this.currentHighLightLyricColorPip)
  7640. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7641. } else {
  7642. this.currentHighLightLyricColor = color
  7643. this.lyricController
  7644. .setHighlightColor(this.currentHighLightLyricColor)
  7645. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7646. }
  7647. }
  7648. // 构建时间控制器
  7649. @Builder
  7650. BuildTimeControls() {
  7651. Column() {
  7652. // 时间显示
  7653. Text(this.getTimeText())
  7654. .fontSize(18)
  7655. .fontColor(Color.White)
  7656. .margin({ bottom: 10 })
  7657. Row() {
  7658. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  7659. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  7660. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  7661. }
  7662. .justifyContent(FlexAlign.Center)
  7663. }
  7664. .margin({ top: 12, bottom: 8 })
  7665. }
  7666. // 精度按钮组件
  7667. @Builder
  7668. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  7669. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7670. Column() {
  7671. Image(icon)
  7672. .width(28)
  7673. .margin({ bottom: 5 })
  7674. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  7675. Text(label)
  7676. .fontSize(12)
  7677. .fontColor('#FFFFFF')
  7678. }
  7679. }
  7680. .backgroundColor(Color.Transparent)
  7681. .enabled(!this.isButtonDisabled(step))
  7682. .onClick(() => this.handlePrecisionAdjust(step))
  7683. .padding(5)
  7684. .width(66)
  7685. .height(66)
  7686. .margin({ left: 18, right: 18 })
  7687. .border({
  7688. color: '#FFFFFF',
  7689. width: 1.8
  7690. })
  7691. }
  7692. private handlePrecisionAdjust(step: number) {
  7693. if (step === 0) {
  7694. this.timeOffset = 0
  7695. return
  7696. }
  7697. // 精度处理:保留1位小数
  7698. const newOffset = Number((this.timeOffset + step).toFixed(5))
  7699. // 边界保护(±15.0秒)
  7700. if (newOffset < -30.0 || newOffset > 30.0) {
  7701. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  7702. return
  7703. }
  7704. // 状态更新
  7705. this.timeOffset = newOffset
  7706. }
  7707. // 按钮禁用逻辑
  7708. private isButtonDisabled(step: number): boolean {
  7709. const futureOffset = this.timeOffset + step
  7710. return (futureOffset < -30.0) || (futureOffset > 30.0)
  7711. }
  7712. // 时间显示文本升级
  7713. private getTimeText(): string {
  7714. const absValue = Math.abs(this.timeOffset)
  7715. return this.timeOffset === 0
  7716. ? '歌词时间已重置'
  7717. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  7718. }
  7719. // 导入 本地歌词 搜索歌词
  7720. @Builder
  7721. pushLyricButton(icon: Resource, step: number, label: string) {
  7722. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7723. Row() {
  7724. Image(icon)
  7725. .width(14)
  7726. .margin({ left: 13 })
  7727. Text(label)
  7728. .fontSize(12)
  7729. .margin({ left: 6 })
  7730. .fontColor('#FFFFFF')
  7731. }
  7732. }
  7733. .onClick(() => {
  7734. switch (step) {
  7735. case 0:
  7736. this.callFilePickerSelectFileForLyric()
  7737. break;
  7738. case 1:
  7739. //判断是不是赞助会员
  7740. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  7741. this.isLyricSetting = false
  7742. this.showTipsDialog()
  7743. return
  7744. }
  7745. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7746. ToastUtil.showToast('正在获取')
  7747. this.isLyricSetting = false
  7748. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7749. this.initLyric(lyricPath, true);
  7750. }
  7751. break;
  7752. }
  7753. })
  7754. .padding(5)
  7755. .width(110)
  7756. .backgroundColor(Color.Transparent)
  7757. .height(40)
  7758. .margin({ left: 6, right: 6 })
  7759. .border({
  7760. color: '#FFFFFF',
  7761. radius: 20,
  7762. width: 1.8
  7763. })
  7764. }
  7765. showVipDialog() {
  7766. DialogHelper.showCustomContentDialog({
  7767. dialogId: 'vip',
  7768. title: "友情提示",
  7769. autoCancel: false, //点击遮障层时,不关闭弹窗
  7770. backCancel: true, //点击返回键,不关闭弹窗
  7771. contentBuilder: () => {
  7772. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  7773. },
  7774. buttons: [],
  7775. })
  7776. }
  7777. //去赞助的自定义内容
  7778. @Builder
  7779. customVipBuilder(content: string) {
  7780. Column() {
  7781. Text(content)
  7782. .fontColor(Color.Gray)
  7783. .fontSize(16)
  7784. .alignSelf(ItemAlign.Start)
  7785. .margin({ bottom: 15 })
  7786. .fontSize(16)
  7787. Row() {
  7788. Button('取消')
  7789. .fontColor(Color.White)
  7790. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7791. .height(50)
  7792. .layoutWeight(1)
  7793. .stateEffect(true)
  7794. .margin({ right: 6 })
  7795. .onClick(() => {
  7796. DialogHelper.closeDialog('vip'); //关闭弹框
  7797. })
  7798. Button('开通')
  7799. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7800. .layoutWeight(1)
  7801. .height(50)
  7802. .backgroundColor(this.themeColor)
  7803. .stateEffect(true)
  7804. .margin({ left: 6 })
  7805. .onClick(() => {
  7806. DialogHelper.closeDialog('vip'); //关闭弹框
  7807. this.isShowPlay = false
  7808. this.mType = 1 //跳转到用户中心
  7809. // router.pushUrl({
  7810. // url: 'pages/VipPage'
  7811. // }, router.RouterMode.Single);
  7812. })
  7813. }
  7814. }
  7815. .width("100%")
  7816. .padding(10)
  7817. }
  7818. showTipsDialog() {
  7819. DialogHelper.showCustomContentDialog({
  7820. dialogId: 'tips',
  7821. title: "友情提示",
  7822. autoCancel: false, //点击遮障层时,不关闭弹窗
  7823. backCancel: true, //点击返回键,不关闭弹窗
  7824. contentBuilder: () => {
  7825. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  7826. },
  7827. buttons: [],
  7828. })
  7829. }
  7830. @Builder
  7831. customTipsBuilder(content: string) {
  7832. Column() {
  7833. Text(content)
  7834. .fontColor(Color.Gray)
  7835. .fontSize(16)
  7836. .alignSelf(ItemAlign.Start)
  7837. .margin({ bottom: 15 })
  7838. .fontSize(16)
  7839. Row() {
  7840. Button('取消')
  7841. .fontColor(Color.White)
  7842. .backgroundColor(this.themeColor)
  7843. .height(50)
  7844. .layoutWeight(1)
  7845. .stateEffect(true)
  7846. .margin({ right: 6 })
  7847. .onClick(() => {
  7848. DialogHelper.closeDialog('tips'); //关闭弹框
  7849. })
  7850. Button('跳转')
  7851. .fontColor(Color.White)//
  7852. .layoutWeight(1)
  7853. .height(50)
  7854. .backgroundColor(this.themeColor)
  7855. .stateEffect(true)
  7856. .margin({ left: 6 })
  7857. .onClick(() => {
  7858. DialogHelper.closeDialog('tips'); //关闭弹框
  7859. this.isShowPlay = false
  7860. this.mType = 3
  7861. // router.pushUrl({
  7862. // url: 'pages/SettingPage'
  7863. // }, router.RouterMode.Single);
  7864. })
  7865. }
  7866. }
  7867. .width("100%")
  7868. .padding(10)
  7869. }
  7870. @Builder
  7871. PlayMoreSheet() {
  7872. Column() {
  7873. this.MoreList()
  7874. }
  7875. .width('100%')
  7876. .height('100%')
  7877. }
  7878. @Builder
  7879. MoreList() {
  7880. Scroll() {
  7881. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7882. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  7883. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7884. Row() {
  7885. if (more.id === 3&&this.currentSong) {
  7886. Image(more.image)
  7887. .width(24)
  7888. .height(24)
  7889. .margin({ left: 10, right: 10 })
  7890. Text(more.title)
  7891. .fontSize(16)
  7892. .fontColor(Color.White)
  7893. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  7894. height: this.isCoverOpacity() ? '95%' : '95%',
  7895. dragBar: true,
  7896. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7897. showClose: true,
  7898. blurStyle: BlurStyle.Thin,
  7899. backgroundColor: Color.Transparent,
  7900. title: { title: '歌曲信息' }
  7901. })
  7902. } else if (more.id === 15 && this.currentSong) { //编辑信息
  7903. Image(more.image)
  7904. .width(24)
  7905. .height(24)
  7906. .margin({ left: 10, right: 10 })
  7907. Text(more.title)
  7908. .fontSize(16)
  7909. .fontColor(Color.White)
  7910. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  7911. height: this.isCoverOpacity() ? '95%' : '93%',
  7912. dragBar: true,
  7913. showClose: true,
  7914. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7915. // blurStyle:BlurStyle.Thin,
  7916. // backgroundColor:Color.Transparent,
  7917. title: { title: '编辑信息' }
  7918. })
  7919. } else if (more.id === 5) { //定时关闭
  7920. Image(more.image)
  7921. .width(24)
  7922. .height(24)
  7923. .margin({ left: 10, right: 10 })
  7924. Text(more.title)
  7925. .fontSize(16)
  7926. .fontColor(Color.White)
  7927. .onClick(() => {
  7928. this.doMore(more.id)
  7929. })
  7930. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  7931. height: this.isCoverOpacity() ? '95%' : '95%',
  7932. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7933. dragBar: true,
  7934. showClose: true,
  7935. title: { title: $r('app.string.time_close') }
  7936. })
  7937. } else if (more.id === 2) { //歌词设置
  7938. Image(more.image)
  7939. .width(24)
  7940. .height(24)
  7941. .margin({ left: 10, right: 10 })
  7942. Text(more.title)
  7943. .fontSize(16)
  7944. .fontColor(Color.White)
  7945. } else if (more.id === 16) { //悬浮歌词设置
  7946. Image(more.image)
  7947. .width(24)
  7948. .height(24)
  7949. .margin({ left: 10, right: 10 })
  7950. Text(more.title)
  7951. .fontSize(16)
  7952. .fontColor(Color.White)
  7953. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  7954. height: this.isCoverOpacity() ? '95%' : '95%',
  7955. dragBar: true,
  7956. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7957. showClose: true,
  7958. blurStyle: BlurStyle.Thin,
  7959. backgroundColor: Color.Transparent,
  7960. title: { title: '悬浮歌词' }
  7961. })
  7962. } else if (more.id === 11) {
  7963. Image(more.image)
  7964. .width(24)
  7965. .height(24)
  7966. .margin({ left: 10, right: 10 })
  7967. Text(more.title)
  7968. .fontSize(16)
  7969. .fontColor(Color.White)
  7970. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  7971. height: this.isCoverOpacity() ? '95%' : '60%',
  7972. dragBar: true,
  7973. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7974. showClose: true,
  7975. blurStyle: BlurStyle.Thin,
  7976. backgroundColor: Color.Transparent,
  7977. title: { title: '跳过头尾' }
  7978. })
  7979. } else if (more.id === 12) { //投播
  7980. AVCastPicker({
  7981. customPicker: (): void => this.TPImageBuilder(more),
  7982. onStateChange: (state) => {
  7983. if (state == AVCastPickerState.STATE_APPEARING) {
  7984. console.log(' The picker starts showing.');
  7985. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  7986. console.log(' The picker finishes presenting.');
  7987. }
  7988. },
  7989. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  7990. sessionType: 'video'
  7991. })
  7992. .id('AVCastPicker')
  7993. } else {
  7994. Image(more.image)
  7995. .width(24)
  7996. .height(24)
  7997. .margin({ left: 10, right: 10 })
  7998. .onClick(() => {
  7999. this.doMore(more.id)
  8000. })
  8001. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  8002. .fontSize(16)
  8003. .fontColor(Color.White)
  8004. .onClick(() => {
  8005. this.doMore(more.id)
  8006. })
  8007. Select([//倍速
  8008. { value: '0.25x' },
  8009. { value: '0.5x' },
  8010. { value: '0.75x' },
  8011. { value: '1x' },
  8012. { value: '1.25x' },
  8013. { value: '1.5x' },
  8014. { value: '1.75x' },
  8015. { value: '2x' },
  8016. { value: '3x' }])
  8017. .font({ size: 16, weight: FontWeight.Medium })
  8018. .fontColor($r('sys.color.white'))
  8019. .margin({ left: 25 })
  8020. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  8021. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  8022. .value(Utility.optimizedFormat(this.playSpeed))
  8023. .onSelect(async (_index: number, text?: string | undefined) => {
  8024. let speed = parseFloat(text?.replace('x', '') || '1');
  8025. if (!CommonConstants.video_speed_list.includes(speed)) {
  8026. speed = 1;
  8027. }
  8028. // 使用UnifiedPlayerService设置播放速度
  8029. this.setPlaybackSpeedViaService(speed);
  8030. })
  8031. Slider({
  8032. value: this.volume,
  8033. min: 0,
  8034. max: 1,
  8035. step: 0.1,
  8036. style: SliderStyle.OutSet
  8037. })
  8038. .margin({ left: 18, right: 8 })
  8039. .blockColor(this.themeColor)
  8040. .trackColor($r('app.color.speed_text_color'))
  8041. .selectedColor(Color.White)
  8042. .trackThickness(9)
  8043. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  8044. .onChange((value: number) => {
  8045. // 使用UnifiedPlayerService设置音量
  8046. this.setVolumeViaService(value);
  8047. })
  8048. .layoutWeight(1)
  8049. Blank()
  8050. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  8051. .selectedColor(this.themeColor)
  8052. .switchPointColor(Color.White)
  8053. .margin({ right: 15 })
  8054. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8055. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  8056. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8057. if (more.id == 6) {
  8058. this.isMusicMemoryPlay = checked;
  8059. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  8060. if (this.isMusicMemoryPlay) {
  8061. ToastUtil.showToast('记忆播放已开启')
  8062. } else {
  8063. ToastUtil.showToast('记忆播放已关闭')
  8064. }
  8065. }
  8066. })
  8067. .width(48)
  8068. .height(24);
  8069. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  8070. .selectedColor(this.themeColor)
  8071. .switchPointColor(Color.White)
  8072. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8073. .margin({ right: 15 })
  8074. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  8075. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8076. if (more.id == 7) {
  8077. this.isMusicBGCover = checked;
  8078. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  8079. if (this.isMusicBGCover) {
  8080. ToastUtil.showToast('播放背景随音乐封面已开启')
  8081. } else {
  8082. ToastUtil.showToast('播放背景随音乐封面已关闭')
  8083. }
  8084. }
  8085. })
  8086. .width(48)
  8087. .height(24);
  8088. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  8089. .selectedColor(this.themeColor)
  8090. .switchPointColor(Color.White)
  8091. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8092. .margin({ right: 15 })
  8093. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  8094. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8095. if (more.id == 8) {
  8096. this.isSavePlayMode = checked;
  8097. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  8098. if (this.isSavePlayMode) {
  8099. ToastUtil.showToast('保存播放模式已开启')
  8100. } else {
  8101. ToastUtil.showToast('保存播放模式已关闭')
  8102. }
  8103. }
  8104. })
  8105. .width(48)
  8106. .height(24);
  8107. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  8108. .selectedColor(this.themeColor)
  8109. .switchPointColor(Color.White)
  8110. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8111. .margin({ right: 15 })
  8112. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  8113. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8114. if (more.id == 13) {
  8115. this.isCoverRectangle = checked;
  8116. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  8117. if (this.isCoverRectangle) {
  8118. ToastUtil.showToast('封面方形已开启')
  8119. this.animationRoFun()
  8120. } else {
  8121. ToastUtil.showToast('封面圆形已开启')
  8122. this.animationRoFun()
  8123. }
  8124. }
  8125. })
  8126. .width(48)
  8127. .height(24);
  8128. }
  8129. }
  8130. .width('100%')
  8131. .height(45)
  8132. .padding(15)
  8133. .backgroundColor(Color.Transparent)
  8134. .borderRadius(12)
  8135. .margin({ bottom: 6 })
  8136. }
  8137. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  8138. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8139. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  8140. .backgroundColor(Color.Transparent)
  8141. .onClick(() => {
  8142. this.doMore(more.id)
  8143. })
  8144. });
  8145. }
  8146. .width('100%')
  8147. .padding(16)
  8148. }.margin({ bottom: 18 })
  8149. }
  8150. @Builder
  8151. TPImageBuilder(more: MoreItem): void {
  8152. Row() {
  8153. Image($r('app.media.tuoping'))
  8154. .width(22)
  8155. .height(22)
  8156. .margin({ left: 10, right: 10 })
  8157. Text(more.title)
  8158. .fontSize(16)
  8159. .fontColor(Color.White)
  8160. }
  8161. .width('100%')
  8162. .layoutWeight(1)
  8163. .alignItems(VerticalAlign.Center)
  8164. .justifyContent(FlexAlign.Start)
  8165. }
  8166. private moreItems: MoreItem[] = [
  8167. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  8168. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  8169. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  8170. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  8171. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  8172. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  8173. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  8174. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  8175. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  8176. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  8177. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  8178. { id: 4, image: $r('app.media.share2'), title: '分享' },
  8179. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  8180. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  8181. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  8182. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  8183. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  8184. ];
  8185. @State isShowMoreView: boolean = false;
  8186. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  8187. @State isShowTimeCloseMore: boolean = false
  8188. @State isShowDetailMore: boolean = false
  8189. @State isMusicBGCover: boolean = true
  8190. @State isSavePlayMode: boolean = true
  8191. @State isLyricSetting: boolean = false
  8192. @State isJumpSetting: boolean = false
  8193. @State isShowEdit: boolean = false
  8194. @State showPipLyric: boolean = false
  8195. async setRingTone() {
  8196. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  8197. return
  8198. }
  8199. // 确定后的逻辑
  8200. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  8201. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  8202. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  8203. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  8204. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  8205. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  8206. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  8207. , this.videoUrl, this.name).then(res => {
  8208. LogUtil.info('onecold setFlag :' + res);
  8209. });
  8210. }
  8211. doMore(moreId: number) {
  8212. switch (moreId) {
  8213. case 2: //歌词
  8214. this.isLyricSetting = !this.isLyricSetting;
  8215. this.isShowMoreView = false
  8216. break;
  8217. case 3: //详情
  8218. this.isShowDetailMore = !this.isShowDetailMore;
  8219. break;
  8220. case 4: //分享
  8221. if (this.currentSong !== undefined) {
  8222. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  8223. }
  8224. this.isShowMoreView = false
  8225. break;
  8226. case 5: //定时关闭
  8227. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  8228. break;
  8229. case 10: //设为铃声
  8230. this.setRingTone()
  8231. this.isShowMoreView = false
  8232. break;
  8233. case 11: //跳过头尾
  8234. this.isJumpSetting = !this.isJumpSetting;
  8235. break;
  8236. case 13: //倍速
  8237. break;
  8238. case 14: //搜索封面
  8239. if (this.currentSong !== undefined) {
  8240. this.doSearchCover(this.currentSong)
  8241. }
  8242. this.isShowMoreView = false
  8243. break;
  8244. case 15: //编辑信息
  8245. this.isShowEdit = !this.isShowEdit;
  8246. break;
  8247. case 16: //悬浮歌词
  8248. this.showPipLyric = !this.showPipLyric;
  8249. break;
  8250. case 17: //横屏模式
  8251. if (this.isLandscape) {
  8252. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8253. } else {
  8254. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8255. }
  8256. this.isShowMoreView = false
  8257. break;
  8258. }
  8259. }
  8260. /**
  8261. * 切换横竖屏
  8262. *
  8263. */
  8264. setOrientation(orientation: number) {
  8265. if (this.windowClass) {
  8266. this.windowClass.setPreferredOrientation(orientation).then(() => {
  8267. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  8268. }).catch((err: BusinessError) => {
  8269. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  8270. });
  8271. }
  8272. }
  8273. /**
  8274. * 画中画功能(悬浮歌词功能)
  8275. *
  8276. */
  8277. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  8278. pipController?: PiPWindow.PiPController;
  8279. navigationId: string = '';
  8280. @State curState: string = '';
  8281. @State curError: ResourceStr = '';
  8282. @State pipBg: string = '#E8E8E8'
  8283. @State buttonAction: string = '';
  8284. //开启画中画功能
  8285. async startPip() {
  8286. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  8287. if (!this.pipController) {
  8288. await this.createPipController();
  8289. }
  8290. if (!this.pipController) {
  8291. Logger.info(`[${TAG}] pipController create error`);
  8292. return;
  8293. }
  8294. await this.pipController.startPiP();
  8295. }
  8296. async stopPip() {
  8297. if (!this.pipController) {
  8298. Logger.info(`[${TAG}] pipController is not exist`);
  8299. return;
  8300. }
  8301. this.isOpenPip = false
  8302. await this.pipController.stopPiP();
  8303. }
  8304. async createPipController() {
  8305. this.pipController = await PiPWindow.create({
  8306. context: getContext(this),
  8307. componentController: this.xcomponentController,
  8308. navigationId: this.navigationId,
  8309. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  8310. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  8311. customUIController: this.nodeController,
  8312. });
  8313. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  8314. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  8315. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8316. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  8317. this.onStateChange(state, reason);
  8318. });
  8319. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  8320. this.onActionEvent(event, status);
  8321. });
  8322. }
  8323. destroyPipController() {
  8324. if (!this.pipController) {
  8325. return;
  8326. }
  8327. this.pipController.off('stateChange');
  8328. this.pipController.off('controlPanelActionEvent');
  8329. this.pipController = undefined;
  8330. }
  8331. onStateChange(state: PiPWindow.PiPState, reason: string) {
  8332. switch (state) {
  8333. case PiPWindow.PiPState.ABOUT_TO_START:
  8334. this.curState = 'ABOUT_TO_START';
  8335. this.curError = $r('app.string.current_error_hint');
  8336. break;
  8337. case PiPWindow.PiPState.STARTED:
  8338. this.curState = 'STARTED';
  8339. this.curError = $r('app.string.current_error_hint');
  8340. break;
  8341. case PiPWindow.PiPState.ABOUT_TO_STOP:
  8342. this.curState = 'ABOUT_TO_STOP';
  8343. this.curError = $r('app.string.current_error_hint');
  8344. break;
  8345. case PiPWindow.PiPState.STOPPED:
  8346. this.curState = 'STOPPED';
  8347. this.curError = $r('app.string.current_error_hint');
  8348. this.stopPip()
  8349. this.destroyPipController()
  8350. break;
  8351. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  8352. this.curState = 'ABOUT_TO_RESTORE';
  8353. this.curError = $r('app.string.current_error_hint');
  8354. break;
  8355. case PiPWindow.PiPState.ERROR:
  8356. this.curState = 'ERROR';
  8357. this.curError = reason;
  8358. break;
  8359. default:
  8360. break;
  8361. }
  8362. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  8363. }
  8364. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  8365. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  8366. switch (event) {
  8367. case 'playbackStateChanged':
  8368. if (status === 0) {
  8369. this.pause();
  8370. } else {
  8371. this.startPlayOrResumePlay();
  8372. }
  8373. break;
  8374. case 'nextVideo':
  8375. // 切换到下一个视频
  8376. this.playNext()
  8377. break;
  8378. case 'previousVideo':
  8379. // 切换到上一个视频
  8380. this.playPrevious()
  8381. break;
  8382. case 'previousVideo':
  8383. // 切换到上一个视频
  8384. this.playPrevious()
  8385. break;
  8386. default:
  8387. }
  8388. this.buttonAction = event + `-status:${status}`;
  8389. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8390. }
  8391. /**
  8392. * 画中画功能(悬浮歌词功能)结束
  8393. *
  8394. */
  8395. doSearchCover(item: VideoItem) {
  8396. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8397. this.isShowMoreView = false
  8398. this.showTipsDialog()
  8399. return
  8400. }
  8401. if (item !== undefined) {
  8402. let artist = item?.artist
  8403. if (StrUtil.isEmpty(artist) || artist === undefined) {
  8404. artist = ''
  8405. }
  8406. this.searchCover(item, item.name, artist)
  8407. }
  8408. }
  8409. searchCover(item: VideoItem, title: string, artist: string) {
  8410. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8411. LogUtil.debug("onecold res =" + res)
  8412. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8413. if (item.filePath == this.currentSong?.filePath) {
  8414. this.cover = res
  8415. if (this.currentSong) {
  8416. this.currentSong.pixelMapPath = res
  8417. }
  8418. }
  8419. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8420. if (success) {
  8421. this.doUpdateData()
  8422. console.log(" onecold 更新音乐封面成功,数据库已同步");
  8423. } else {
  8424. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  8425. }
  8426. });
  8427. LogUtil.debug("onecold this.cover =" + this.cover)
  8428. }
  8429. })
  8430. }
  8431. @State jumpTopTime: number = 0
  8432. @State jumpEndTime: number = 0
  8433. @State isOpenJump: boolean = false
  8434. @Builder
  8435. JumpTopEndSheet() {
  8436. Scroll() {
  8437. Column() {
  8438. Column() {
  8439. Text('仅对本播放列表有效')
  8440. .fontSize(16)
  8441. .fontColor($r('app.color.text_color'))
  8442. // 跳过头尾
  8443. Column() {
  8444. Row() {
  8445. Text('跳过片头:')
  8446. .fontSize(16)
  8447. .fontColor($r('app.color.text_color'))
  8448. Text(this.jumpTopTime + 's')
  8449. .fontSize(16)
  8450. .fontColor($r('app.color.text_color'))
  8451. }
  8452. .margin({ bottom: 5 })
  8453. Row() {
  8454. Slider({
  8455. value: this.jumpTopTime,
  8456. min: 0,
  8457. max: 120,
  8458. step: 1,
  8459. style: SliderStyle.OutSet
  8460. })
  8461. .blockColor(this.themeColor)
  8462. .trackColor($r('app.color.speed_text_color'))
  8463. .selectedColor(Color.White)
  8464. .trackThickness(8)
  8465. .onChange((value: number) => {
  8466. this.jumpTopTime = value;
  8467. })
  8468. .width('85%')
  8469. }
  8470. .alignItems(VerticalAlign.Top)
  8471. }
  8472. .margin({ top: 10, bottom: 10 })
  8473. // 跳过头尾
  8474. Column() {
  8475. Row() {
  8476. Text('跳过片尾:')
  8477. .fontSize(16)
  8478. .fontColor($r('app.color.text_color'))
  8479. Text(this.jumpEndTime + 's')
  8480. .fontSize(16)
  8481. .fontColor($r('app.color.text_color'))
  8482. }
  8483. .margin({ bottom: 5 })
  8484. Row() {
  8485. Slider({
  8486. value: this.jumpEndTime,
  8487. min: 0,
  8488. max: 120,
  8489. step: 1,
  8490. style: SliderStyle.OutSet
  8491. })
  8492. .blockColor(this.themeColor)
  8493. .trackColor($r('app.color.speed_text_color'))
  8494. .selectedColor(Color.White)
  8495. .trackThickness(8)
  8496. .onChange((value: number) => {
  8497. this.jumpEndTime = value;
  8498. })
  8499. .width('85%')
  8500. }
  8501. .alignItems(VerticalAlign.Top)
  8502. }
  8503. .margin({ top: 10, bottom: 10 })
  8504. Row() {
  8505. Button('保存设置')
  8506. .fontColor(Color.White)
  8507. .layoutWeight(1)
  8508. .height(40)
  8509. .width(80)
  8510. .backgroundColor(this.themeColor)
  8511. .stateEffect(true)
  8512. .margin({ left: 0, bottom: 20 })
  8513. .onClick(async () => {
  8514. if (!Utility.isNoble()) {
  8515. this.isJumpSetting = false
  8516. this.isShowMoreView = false
  8517. this.showVipDialog()
  8518. return
  8519. }
  8520. if (this.currentSong === undefined) {
  8521. return
  8522. }
  8523. if (this.modeType === 0) {
  8524. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8525. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8526. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8527. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8528. } else if (this.modeType === 1) { //媒体库
  8529. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8530. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8531. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8532. } else if (this.modeType === 2) { //艺术家
  8533. if (this.currentSong?.artist) {
  8534. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8535. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8536. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8537. }
  8538. } else if (this.modeType === 3) { //专辑
  8539. if (this.currentSong?.album) {
  8540. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8541. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8542. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8543. }
  8544. }
  8545. ToastUtil.showShort("保存成功")
  8546. this.isJumpSetting = false
  8547. })
  8548. }
  8549. .margin({
  8550. left: 38,
  8551. right: 38,
  8552. top: 10,
  8553. bottom: 10
  8554. })
  8555. .width(120)
  8556. .height(50)
  8557. }
  8558. }
  8559. }
  8560. .width('100%')
  8561. .height('100%')
  8562. }
  8563. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8564. private onStateVastChange(state: AVCastPickerState) {
  8565. if (state == AVCastPickerState.STATE_APPEARING) {
  8566. LogUtils.getInstance().LOGI('投播选择器开始显示');
  8567. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8568. LogUtils.getInstance().LOGI('投播选择器结束显示');
  8569. }
  8570. }
  8571. // 检查是否存在投播设备
  8572. private async checkCastingDeviceAvailability(): Promise<boolean> {
  8573. try {
  8574. const session = this.avSessionController.getAvSession();
  8575. if (!session) {
  8576. return false;
  8577. }
  8578. const outputDevice = await session.getOutputDevice();
  8579. if (!outputDevice || !outputDevice.devices || outputDevice.devices.length === 0) {
  8580. return false;
  8581. }
  8582. // 检查是否有远程设备可用
  8583. const remoteDevices = outputDevice.devices.filter(device =>
  8584. device.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE
  8585. );
  8586. return remoteDevices.length > 0;
  8587. } catch (error) {
  8588. LogUtils.getInstance().LOGI(`检查投播设备可用性失败: ${error}`);
  8589. return false;
  8590. }
  8591. }
  8592. // 获取当前输出设备信息
  8593. private async getCurrentOutputDevice(): Promise<avSession.OutputDeviceInfo | undefined> {
  8594. try {
  8595. const session = this.avSessionController.getAvSession();
  8596. if (!session) {
  8597. return undefined;
  8598. }
  8599. return await session.getOutputDevice();
  8600. } catch (error) {
  8601. LogUtils.getInstance().LOGI(`获取当前输出设备失败: ${error}`);
  8602. return undefined;
  8603. }
  8604. }
  8605. // 检查当前是否正在投播
  8606. private async checkCurrentCastingStatus(): Promise<boolean> {
  8607. try {
  8608. const outputDevice = await this.getCurrentOutputDevice();
  8609. if (!outputDevice || !outputDevice.devices || outputDevice.devices.length === 0) {
  8610. return false;
  8611. }
  8612. // 检查当前设备是否为远程设备
  8613. const currentDevice = outputDevice.devices[0];
  8614. return currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE;
  8615. } catch (error) {
  8616. LogUtils.getInstance().LOGI(`检查当前投播状态失败: ${error}`);
  8617. return false;
  8618. }
  8619. }
  8620. // 投播状态下的播放下一首
  8621. private async handleCastingPlayNext(): Promise<void> {
  8622. try {
  8623. LogUtils.getInstance().LOGI('投播状态下切换下一首');
  8624. // 计算下一首的索引
  8625. let nextIndex = this.curIndex;
  8626. if (this.playType === 1) { // 单曲循环
  8627. // 保持当前索引不变
  8628. } else if (this.playType === 2) { // 列表循环
  8629. nextIndex = (this.curIndex + 1) % this.songList.length;
  8630. } else { // 顺序播放
  8631. if (this.curIndex < this.songList.length - 1) {
  8632. nextIndex = this.curIndex + 1;
  8633. } else {
  8634. LogUtils.getInstance().LOGI('已是最后一首,停止投播');
  8635. this.endCasting();
  8636. return;
  8637. }
  8638. }
  8639. // 更新当前歌曲信息
  8640. this.curIndex = nextIndex;
  8641. this.currentSong = this.songList[this.curIndex];
  8642. this.videoUrl = this.currentSong.filePath;
  8643. this.artist = this.currentSong.artist;
  8644. this.name = this.currentSong.name;
  8645. this.cover = this.currentSong.pixelMapPath;
  8646. // 切换投播资源
  8647. await this.changeCasting();
  8648. LogUtils.getInstance().LOGI(`投播下一首完成: ${this.currentSong.name}`);
  8649. } catch (error) {
  8650. LogUtils.getInstance().LOGI(`投播下一首失败: ${error}`);
  8651. ToastUtil.showToast(`投播切换失败: ${error}`);
  8652. }
  8653. }
  8654. // 投播状态下的播放上一首
  8655. private async handleCastingPlayPrevious(): Promise<void> {
  8656. try {
  8657. LogUtils.getInstance().LOGI('投播状态下切换上一首');
  8658. // 计算上一首的索引
  8659. let prevIndex = this.curIndex;
  8660. if (this.playType === 1) { // 单曲循环
  8661. // 保持当前索引不变
  8662. } else if (this.playType === 2) { // 列表循环
  8663. prevIndex = this.curIndex === 0 ? this.songList.length - 1 : this.curIndex - 1;
  8664. } else { // 顺序播放
  8665. if (this.curIndex > 0) {
  8666. prevIndex = this.curIndex - 1;
  8667. } else {
  8668. LogUtils.getInstance().LOGI('已是第一首,停止投播');
  8669. this.endCasting();
  8670. return;
  8671. }
  8672. }
  8673. // 更新当前歌曲信息
  8674. this.curIndex = prevIndex;
  8675. this.currentSong = this.songList[this.curIndex];
  8676. this.videoUrl = this.currentSong.filePath;
  8677. this.artist = this.currentSong.artist;
  8678. this.name = this.currentSong.name;
  8679. this.cover = this.currentSong.pixelMapPath;
  8680. // 切换投播资源
  8681. await this.changeCasting();
  8682. LogUtils.getInstance().LOGI(`投播上一首完成: ${this.currentSong.name}`);
  8683. } catch (error) {
  8684. LogUtils.getInstance().LOGI(`投播上一首失败: ${error}`);
  8685. ToastUtil.showToast(`投播切换失败: ${error}`);
  8686. }
  8687. }
  8688. // 投播状态下的播放/暂停控制
  8689. private async handleCastingPlayPause(): Promise<void> {
  8690. try {
  8691. if (this.isCastPlaying) {
  8692. await this.sendCastControlCommand('pause');
  8693. LogUtils.getInstance().LOGI('投播暂停');
  8694. } else {
  8695. await this.sendCastControlCommand('play');
  8696. LogUtils.getInstance().LOGI('投播播放');
  8697. }
  8698. } catch (error) {
  8699. LogUtils.getInstance().LOGI(`投播播放/暂停控制失败: ${error}`);
  8700. }
  8701. }
  8702. // 投播状态下的进度控制
  8703. private async handleCastingSeek(position: number): Promise<void> {
  8704. try {
  8705. await this.sendCastControlCommand('seek', position);
  8706. LogUtils.getInstance().LOGI(`投播进度调节: ${position}ms`);
  8707. } catch (error) {
  8708. LogUtils.getInstance().LOGI(`投播进度调节失败: ${error}`);
  8709. }
  8710. }
  8711. // 检查并恢复投播状态
  8712. private async checkAndRestoreCastingState(): Promise<void> {
  8713. try {
  8714. LogUtils.getInstance().LOGI('检查当前投播状态...');
  8715. const session = this.avSessionController.getAvSession();
  8716. if (!session) {
  8717. LogUtils.getInstance().LOGI('AVSession不可用,跳过投播状态检查');
  8718. return;
  8719. }
  8720. // 获取当前输出设备
  8721. const outputDevice = await session.getOutputDevice();
  8722. if (!outputDevice || !outputDevice.devices || outputDevice.devices.length === 0) {
  8723. LogUtils.getInstance().LOGI('没有输出设备,当前为本地播放');
  8724. return;
  8725. }
  8726. const currentDevice = outputDevice.devices[0];
  8727. LogUtils.getInstance().LOGI(`当前输出设备: ${currentDevice.castCategory}, 协议: ${currentDevice.supportedProtocols}`);
  8728. // 检查是否为远程设备(投播状态)
  8729. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE) {
  8730. LogUtils.getInstance().LOGI('检测到投播状态,恢复投播控制器');
  8731. // 恢复投播状态
  8732. this.currentCastDevice = currentDevice;
  8733. this.isCasting = true;
  8734. // 获取投播控制器
  8735. this.castController = await session.getAVCastController();
  8736. if (this.castController) {
  8737. // 设置投播监听器
  8738. this.setPlaybackStateChangeListener();
  8739. // 查询当前播放状态
  8740. const playbackState = await this.castController.getAVPlaybackState();
  8741. if (playbackState) {
  8742. this.playbackStateChangeListener(playbackState);
  8743. }
  8744. // 同步投播状态到AppStorage
  8745. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8746. refToIsCasting?.set(true);
  8747. LogUtils.getInstance().LOGI('投播状态恢复成功');
  8748. ToastUtil.showToast('已连接到投播设备');
  8749. } else {
  8750. LogUtils.getInstance().LOGI('获取投播控制器失败');
  8751. }
  8752. } else {
  8753. LogUtils.getInstance().LOGI('当前为本地播放状态');
  8754. }
  8755. } catch (error) {
  8756. LogUtils.getInstance().LOGI(`检查投播状态失败: ${error}`);
  8757. }
  8758. }
  8759. private showSelectLyric() {
  8760. DialogHelper.showActionSheetDialog({
  8761. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  8762. // sheets: ["本地歌词", "搜索歌词"],
  8763. sheets: [
  8764. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  8765. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  8766. ],
  8767. maskColor: Color.Transparent,
  8768. backgroundColor: $r('app.color.bg_card'),
  8769. transition: AnimationHelper.transitionInDown(666),
  8770. onAction: (index) => {
  8771. switch (index) {
  8772. case 0:
  8773. this.callFilePickerSelectFileForLyric()
  8774. break;
  8775. case 1:
  8776. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8777. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8778. this.initLyric(lyricPath);
  8779. }
  8780. break;
  8781. }
  8782. }
  8783. })
  8784. }
  8785. // 拉起picker选择文件管理器
  8786. async callFilePickerSelectFileForLyric(): Promise<void> {
  8787. try {
  8788. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  8789. DocumentSelectOptions.maxSelectNumber = 1
  8790. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  8791. let documentPicker = new picker.DocumentViewPicker();
  8792. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  8793. Logger.info(TAG,
  8794. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  8795. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  8796. this.saveVideoDatasLyric(DocumentSelectResult)
  8797. }
  8798. }).catch((err: BusinessError) => {
  8799. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  8800. });
  8801. } catch (err) {
  8802. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  8803. }
  8804. }
  8805. async saveVideoDatasLyric(uris: string[]) {
  8806. if (ArrayUtil.isEmpty(uris)) {
  8807. return
  8808. }
  8809. let newUris: string[] = [];
  8810. for (let i = 0; i < uris.length; i++) {
  8811. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  8812. Logger.info(TAG, 'filePath uri: ' + filePath);
  8813. newUris.push(filePath)
  8814. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  8815. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  8816. fileIo.copyFileSync(file.fd, file2.fd)
  8817. fileIo.closeSync(file);
  8818. fileIo.closeSync(file2);
  8819. this.initLyric(filePath)
  8820. }
  8821. }
  8822. private initDelayPlay(context: object) {
  8823. this.mContext = context;
  8824. }
  8825. startPipLyric() {
  8826. if (this.pipController) {
  8827. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  8828. PiPWindow.PiPControlStatus.PLAY);
  8829. }
  8830. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  8831. if (this.isOpenPip) {
  8832. this.startPip()
  8833. } else {
  8834. this.stopPip()
  8835. }
  8836. }
  8837. private async startPlayOrResumePlay() {
  8838. try {
  8839. this.startPipLyric()
  8840. this.mDestroyPage = false;
  8841. this.animationState = AnimationStatus.Running
  8842. // 智能同步播放列表到UnifiedPlayerService
  8843. if (ArrayUtil.isNotEmpty(this.songList)) {
  8844. // 检查UnifiedPlayerService是否已经有播放列表
  8845. const servicePlaylist = this.unifiedPlayerService.getPlaylist();
  8846. const serviceIndex = this.unifiedPlayerService.getCurrentIndex();
  8847. if (ArrayUtil.isEmpty(servicePlaylist)) {
  8848. // 如果服务没有播放列表,使用LocalMusic的播放列表
  8849. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  8850. } else {
  8851. // 如果服务已有播放列表,同步服务的状态到LocalMusic
  8852. const serviceSong = this.unifiedPlayerService.getCurrentSong();
  8853. if (serviceSong && serviceIndex >= 0 && serviceIndex < servicePlaylist.length) {
  8854. this.songList = servicePlaylist;
  8855. this.curIndex = serviceIndex;
  8856. this.currentSong = serviceSong;
  8857. this.sonDataSource.pushArrayData(this.songList);
  8858. // 更新UI显示
  8859. this.videoUrl = serviceSong.filePath;
  8860. this.name = serviceSong.name;
  8861. this.artist = serviceSong.artist;
  8862. this.cover = serviceSong.pixelMapPath;
  8863. }
  8864. }
  8865. }
  8866. // 使用UnifiedPlayerService开始播放
  8867. await this.unifiedPlayerService.startPlayOrResumePlay();
  8868. // 保持原有的UI更新逻辑
  8869. this.stopProgressTask();
  8870. this.startProgressTask();
  8871. this.watchStatus();
  8872. this.updateLastPlayTimeStr(this.videoUrl)
  8873. // 更新播放状态
  8874. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  8875. this.setIsPlaying(true);
  8876. // 注意:AVSession状态更新由UnifiedPlayerService统一处理,避免冲突
  8877. LogUtils.getInstance().LOGI("LocalMusic: startPlayOrResumePlay completed via UnifiedPlayerService");
  8878. } catch (error) {
  8879. LogUtils.getInstance().LOGI(`LocalMusic startPlayOrResumePlay error: ${error}`);
  8880. ToastUtil.showToast(`播放失败: ${error}`);
  8881. // 错误处理:回退到原有逻辑
  8882. this.handlePlaybackError();
  8883. }
  8884. }
  8885. // 播放错误处理
  8886. private handlePlaybackError() {
  8887. this.CONTROL_PlayStatus = PlayStatus.INIT;
  8888. this.setIsPlaying(false);
  8889. // 注意:AVSession状态更新由UnifiedPlayerService统一处理,避免冲突
  8890. this.mDestroyPage = true;
  8891. }
  8892. // 设置音量(通过UnifiedPlayerService)
  8893. private setVolumeViaService(volume: number) {
  8894. try {
  8895. this.unifiedPlayerService.setVolume(volume);
  8896. this.volume = volume;
  8897. PreferencesUtil.putSync('DefalutVolume', volume);
  8898. LogUtils.getInstance().LOGI(`LocalMusic: Volume set to ${volume} via UnifiedPlayerService`);
  8899. } catch (error) {
  8900. LogUtils.getInstance().LOGI(`LocalMusic setVolume error: ${error}`);
  8901. ToastUtil.showToast(`设置音量失败: ${error}`);
  8902. }
  8903. }
  8904. // 设置播放速度(通过UnifiedPlayerService)
  8905. private setPlaybackSpeedViaService(speed: number) {
  8906. try {
  8907. this.unifiedPlayerService.setPlaybackSpeed(speed);
  8908. this.playSpeed = speed;
  8909. LogUtils.getInstance().LOGI(`LocalMusic: Playback speed set to ${speed} via UnifiedPlayerService`);
  8910. } catch (error) {
  8911. LogUtils.getInstance().LOGI(`LocalMusic setPlaybackSpeed error: ${error}`);
  8912. ToastUtil.showToast(`设置播放速度失败: ${error}`);
  8913. }
  8914. }
  8915. // 设置播放模式(通过UnifiedPlayerService)
  8916. private setPlayModeViaService(mode: number) {
  8917. try {
  8918. this.unifiedPlayerService.setPlayMode(mode);
  8919. this.playType = mode;
  8920. PreferencesUtil.putSync('musicPlayType', mode);
  8921. LogUtils.getInstance().LOGI(`LocalMusic: Play mode set to ${mode} via UnifiedPlayerService`);
  8922. } catch (error) {
  8923. LogUtils.getInstance().LOGI(`LocalMusic setPlayMode error: ${error}`);
  8924. // 回退到原有逻辑
  8925. this.playType = mode;
  8926. PreferencesUtil.putSync('musicPlayType', mode);
  8927. }
  8928. }
  8929. // 播放指定索引的歌曲(通过UnifiedPlayerService)
  8930. private async playSongAtIndexViaService(index: number) {
  8931. try {
  8932. // 确保播放列表已同步到UnifiedPlayerService
  8933. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  8934. // 使用UnifiedPlayerService播放指定索引的歌曲
  8935. await this.unifiedPlayerService.playSongAtIndex(index);
  8936. // 更新本地状态以保持UI同步
  8937. const currentIndex = this.unifiedPlayerService.getCurrentIndex();
  8938. const currentSong = this.unifiedPlayerService.getCurrentSong();
  8939. if (currentSong) {
  8940. this.curIndex = currentIndex;
  8941. this.currentSong = currentSong;
  8942. this.videoUrl = currentSong.filePath;
  8943. this.name = currentSong.name;
  8944. this.artist = currentSong.artist;
  8945. this.cover = currentSong.pixelMapPath;
  8946. }
  8947. } catch (error) {
  8948. ToastUtil.showToast(`播放歌曲失败: ${error}`);
  8949. // 错误处理:回退到原有逻辑
  8950. this.playIndex(index);
  8951. }
  8952. }
  8953. // 同步播放列表到UnifiedPlayerService
  8954. private syncPlaylistToService() {
  8955. try {
  8956. if (ArrayUtil.isNotEmpty(this.songList)) {
  8957. // 记录调用栈信息以便调试
  8958. const stack = new Error().stack || 'No stack available';
  8959. const caller = stack.split('\n')[2] || 'Unknown caller';
  8960. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  8961. // 同步播放模式到UnifiedPlayerService
  8962. this.unifiedPlayerService.setPlayMode(this.playType);
  8963. LogUtils.getInstance().LOGI(`LocalMusic: Playlist and play mode synced to UnifiedPlayerService - ${this.songList.length} songs, mode: ${this.playType}, caller: ${caller.trim()}`);
  8964. // 如果同步的是小播放列表,记录更多信息
  8965. if (this.songList.length <= 20) {
  8966. LogUtils.getInstance().LOGI(`LocalMusic: Small playlist sync detected, current path: ${this.currentPath}, first few songs: ${this.songList.slice(0, 5).map(s => s.name).join(', ')}`);
  8967. }
  8968. } else {
  8969. LogUtils.getInstance().LOGI('LocalMusic: syncPlaylistToService - No songs to sync');
  8970. }
  8971. } catch (error) {
  8972. LogUtils.getInstance().LOGI(`LocalMusic syncPlaylistToService error: ${error}`);
  8973. }
  8974. }
  8975. // 从播放列表移除歌曲(通过UnifiedPlayerService)
  8976. private removeFromPlaylistViaService(index: number) {
  8977. try {
  8978. // 使用UnifiedPlayerService移除歌曲
  8979. const removedSong = this.unifiedPlayerService.removeFromPlaylist(index);
  8980. if (removedSong) {
  8981. // 更新本地播放列表
  8982. this.songList.splice(index, 1);
  8983. this.sonDataSource.pushArrayData(this.songList);
  8984. // 更新当前索引
  8985. this.curIndex = this.unifiedPlayerService.getCurrentIndex();
  8986. ToastUtil.showToast(`已移除 ${removedSong.name}`);
  8987. }
  8988. } catch (error) {
  8989. // 错误处理:回退到原有逻辑
  8990. if (index >= 0 && index < this.songList.length) {
  8991. const removedSong = this.songList.splice(index, 1)[0];
  8992. this.sonDataSource.pushArrayData(this.songList);
  8993. ToastUtil.showToast(`已移除 ${removedSong.name}`);
  8994. }
  8995. }
  8996. }
  8997. // 同步进度更新到UI(从UnifiedPlayerService)
  8998. private syncProgressFromService(progress: PlayProgress) {
  8999. try {
  9000. // 检测歌曲是否发生切换(额外保障机制)
  9001. const currentSongPath = this.currentSong?.filePath || "";
  9002. let isSongChanged = false;
  9003. if (this.lastSongPath !== currentSongPath && currentSongPath !== "") {
  9004. console.log(`Heanup 在进度更新中检测到歌曲切换: ${this.lastSongPath} -> ${currentSongPath}`);
  9005. console.log(`Heanup 歌曲切换前 oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`);
  9006. // 立即重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  9007. this.oldSeconds = 0;
  9008. this.currentTime = "00:00";
  9009. this.lastSongPath = currentSongPath;
  9010. this.justSwitched = true; // 标记歌曲刚刚切换
  9011. isSongChanged = true;
  9012. console.log(`Heanup 歌曲切换后 oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`);
  9013. // 歌曲切换时,强制将播放位置重置为0,忽略服务报告的位置
  9014. progress.currentPosition = 0;
  9015. console.log(`Heanup 歌曲切换,强制progress.currentPosition为0`);
  9016. // 立即返回,不更新进度,等待新歌曲开始播放
  9017. return;
  9018. }
  9019. // 直接使用ijkplayer获取播放进度,避免状态同步延迟
  9020. try {
  9021. const ijkPlayer = this.unifiedPlayerService.getIjkPlayer();
  9022. if (ijkPlayer && ijkPlayer.isPlaying()) {
  9023. const currentPosition = ijkPlayer.getCurrentPosition();
  9024. const duration = ijkPlayer.getDuration();
  9025. if (duration > 0 && currentPosition >= 0) {
  9026. // 更新进度条
  9027. this.slideEnable = true;
  9028. let curPercent = currentPosition / duration;
  9029. let pos = curPercent * 100;
  9030. if (pos > this.PROGRESS_MAX_VALUE) {
  9031. this.progressValue = this.PROGRESS_MAX_VALUE;
  9032. } else {
  9033. this.progressValue = pos;
  9034. }
  9035. // 更新时间显示
  9036. this.totalTime = this.stringForTime(duration);
  9037. console.log(`Heanup 当前时间 (直接从ijkplayer获取) - ${currentPosition} / ${duration}`)
  9038. console.log(`Heanup 更新前 - oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`)
  9039. this.isCurrentTime = true;
  9040. this.currentTime = this.stringForTime(currentPosition);
  9041. this.isCurrentTime = false;
  9042. console.log(`Heanup 更新后 - oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`)
  9043. // 继续执行后续的歌词更新等逻辑
  9044. }
  9045. }
  9046. } catch (error) {
  9047. console.error('LocalMusic: 获取ijkplayer播放进度失败', error);
  9048. // 如果直接获取失败,回退到使用服务状态
  9049. this.updateProgressFromServiceState(progress);
  9050. return;
  9051. }
  9052. // 如果直接获取ijkplayer失败或者不在播放状态,使用服务状态
  9053. this.updateProgressFromServiceState(progress);
  9054. // 更新歌词位置
  9055. const lyricPosition = progress.currentPosition + this.timeOffset * 1000;
  9056. if (this.lyricController) {
  9057. this.lyricController.updatePosition(lyricPosition);
  9058. }
  9059. if (this.lyricControllerXF) {
  9060. this.lyricControllerXF.updatePosition(lyricPosition);
  9061. }
  9062. if (this.lyricControllerSingle) {
  9063. this.lyricControllerSingle.updatePosition(lyricPosition);
  9064. }
  9065. // 更新随机颜色(如果正在播放)
  9066. const currentState = this.unifiedPlayerService.getCurrentState();
  9067. if (currentState.isPlaying) {
  9068. this.randomColor =
  9069. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`;
  9070. } else {
  9071. this.randomColor = 'rbg(0,0,0)';
  9072. }
  9073. // 检查是否需要跳到下一首(片尾跳过功能)
  9074. if (this.isOpenJump && progress.duration > this.jumpEndTime * 1000) {
  9075. if (progress.currentPosition >= progress.duration - this.jumpEndTime * 1000) {
  9076. this.playNext();
  9077. }
  9078. }
  9079. LogUtils.getInstance().LOGI(`LocalMusic: Progress synchronized from service - ${progress.currentPosition}/${progress.duration}ms`);
  9080. } catch (error) {
  9081. LogUtils.getInstance().LOGI(`LocalMusic syncProgressFromService error: ${error}`);
  9082. }
  9083. }
  9084. /**
  9085. * 从服务状态更新播放进度(回退方案)
  9086. */
  9087. private updateProgressFromServiceState(progress: PlayProgress) {
  9088. // 更新进度条
  9089. if (progress.duration > 0) {
  9090. this.slideEnable = true;
  9091. let curPercent = progress.currentPosition / progress.duration;
  9092. let pos = curPercent * 100;
  9093. if (pos > this.PROGRESS_MAX_VALUE) {
  9094. this.progressValue = this.PROGRESS_MAX_VALUE;
  9095. } else {
  9096. this.progressValue = pos;
  9097. }
  9098. }
  9099. // 更新时间显示
  9100. this.totalTime = this.stringForTime(progress.duration);
  9101. if (progress.currentPosition > progress.duration) {
  9102. progress.currentPosition = progress.duration;
  9103. }
  9104. console.log(`Heanup 当前时间 (从服务状态获取) - ${progress.currentPosition} / ${progress.duration}`)
  9105. console.log(`Heanup 更新前 - oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`)
  9106. this.isCurrentTime = true;
  9107. this.currentTime = this.stringForTime(progress.currentPosition);
  9108. this.isCurrentTime = false;
  9109. console.log(`Heanup 更新后 - oldSeconds: ${this.oldSeconds}, currentTime: ${this.currentTime}`)
  9110. }
  9111. updateLastPlayTimeStr(filePath: string) {
  9112. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  9113. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  9114. if (success) {
  9115. this.getHistoryList(false)
  9116. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  9117. } else {
  9118. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  9119. }
  9120. });
  9121. }
  9122. private completionNum(num: number): string | number {
  9123. if (num < 10) {
  9124. return '0' + num;
  9125. } else {
  9126. return num;
  9127. }
  9128. }
  9129. // 纯粹的时间格式化函数,不包含任何业务逻辑
  9130. private stringForTime(timeMs: number): string {
  9131. let totalSeconds: number = Math.floor(timeMs / 1000);
  9132. let seconds: number = totalSeconds % 60;
  9133. let minutes: number = Math.floor(totalSeconds / 60) % 60;
  9134. let hours: number = Math.floor(totalSeconds / 3600);
  9135. // 防抖逻辑:只在当前播放时间更新时生效
  9136. if (this.isCurrentTime) {
  9137. // 如果歌曲刚刚切换,强制重置并使用新时间
  9138. if (this.justSwitched) {
  9139. this.oldSeconds = seconds; // 直接使用新时间
  9140. this.justSwitched = false; // 重置标志
  9141. this.lastSwitchTime = Date.now(); // 记录切换时间
  9142. } else if (this.isSeekTo) {
  9143. // 如果是拖动进度条,直接使用新时间
  9144. this.oldSeconds = seconds;
  9145. } else {
  9146. // 正常播放时的防抖逻辑
  9147. // 检查是否在切换后的冷却期内(切换后5秒内允许更大的时间跳跃)
  9148. const timeSinceSwitch = this.lastSwitchTime ? Date.now() - this.lastSwitchTime : Number.MAX_VALUE;
  9149. const isInCooldown = timeSinceSwitch < 5000; // 5秒冷却期
  9150. // 如果时间差值过大,根据情况处理
  9151. const timeDiff = Math.abs(seconds - this.oldSeconds);
  9152. if (timeDiff > 10) {
  9153. // 如果在冷却期内,允许更大的时间跳跃(可能是新歌曲开始播放)
  9154. if (isInCooldown) {
  9155. this.oldSeconds = seconds;
  9156. } else {
  9157. // 不在冷却期内,可能是异常情况,记录但使用新时间
  9158. this.oldSeconds = seconds;
  9159. }
  9160. } else if (this.oldSeconds <= seconds || seconds === 0) {
  9161. // 正常时间递进或重置为0
  9162. this.oldSeconds = seconds;
  9163. } else {
  9164. // 时间倒退,使用防抖
  9165. seconds = this.oldSeconds;
  9166. }
  9167. }
  9168. }
  9169. const hoursStr = this.completionNum(hours);
  9170. const minutesStr = this.completionNum(minutes);
  9171. const secondsStr = this.completionNum(seconds);
  9172. if (hours > 0) {
  9173. return `${hoursStr}:${minutesStr}:${secondsStr}`;
  9174. } else {
  9175. return `${minutesStr}:${secondsStr}`;
  9176. }
  9177. }
  9178. private setProgress() {
  9179. let ijkPlayer=this.unifiedPlayerService.getIjkPlayer() as IjkMediaPlayer;
  9180. let position = ijkPlayer.getCurrentPosition();
  9181. let duration = ijkPlayer.getDuration();
  9182. let pos = 0;
  9183. if (duration > 0) {
  9184. this.slideEnable = true;
  9185. let curPercent = position / duration;
  9186. pos = curPercent * 100;
  9187. if (pos > this.PROGRESS_MAX_VALUE) {
  9188. this.progressValue = this.PROGRESS_MAX_VALUE
  9189. } else {
  9190. this.progressValue = pos;
  9191. }
  9192. }
  9193. // LogUtils.getInstance()
  9194. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9195. this.totalTime = this.stringForTime(duration);
  9196. if (position > duration) {
  9197. position = duration;
  9198. }
  9199. this.isCurrentTime = true;
  9200. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  9201. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  9202. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  9203. this.currentTime = this.stringForTime(position);
  9204. this.isCurrentTime = false
  9205. if (ijkPlayer.isPlaying()) {
  9206. this.randomColor =
  9207. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  9208. // 判断是否播放到结束时间
  9209. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  9210. if (position >= duration - this.jumpEndTime * 1000) {
  9211. this.playNext()
  9212. this.broadcastProgressIfNeeded();
  9213. }
  9214. }
  9215. } else {
  9216. this.randomColor = 'rbg(0,0,0)'
  9217. }
  9218. // try {
  9219. // // 优先从UnifiedPlayerService获取进度信息
  9220. // const currentState = this.unifiedPlayerService.getCurrentState();
  9221. // let position = currentState.currentPosition;
  9222. // let duration = currentState.duration;
  9223. //
  9224. // // 检测歌曲切换并重置播放位置
  9225. // const currentSongPath = this.currentSong?.filePath || "";
  9226. // if (this.lastSongPath !== currentSongPath && currentSongPath !== "") {
  9227. // console.log(`Heanup setProgress检测到歌曲切换,重置position: ${position} -> 0`);
  9228. // this.oldSeconds = 0;
  9229. // this.currentTime = "00:00";
  9230. // this.lastSongPath = currentSongPath;
  9231. // position = 0; // 强制重置播放位置
  9232. // }
  9233. //
  9234. // let pos = 0;
  9235. // if (duration > 0) {
  9236. // this.slideEnable = true;
  9237. // let curPercent = position / duration;
  9238. // pos = curPercent * 100;
  9239. // if (pos > this.PROGRESS_MAX_VALUE) {
  9240. // this.progressValue = this.PROGRESS_MAX_VALUE
  9241. // } else {
  9242. // this.progressValue = pos;
  9243. // }
  9244. // }
  9245. //
  9246. // this.totalTime = this.stringForTime(duration);
  9247. // if (position > duration) {
  9248. // position = duration;
  9249. // }
  9250. //
  9251. //
  9252. // // 更新歌词位置
  9253. // const lyricPosition = position + this.timeOffset * 1000;
  9254. // this.lyricController.updatePosition(lyricPosition);
  9255. // this.lyricControllerXF.updatePosition(lyricPosition);
  9256. // this.lyricControllerSingle.updatePosition(lyricPosition);
  9257. //
  9258. // this.isCurrentTime = true;
  9259. // this.currentTime = this.stringForTime(position);
  9260. // this.isCurrentTime = false;
  9261. //
  9262. // // 检查播放状态以更新随机颜色和跳过逻辑
  9263. // const isPlaying = currentState.isPlaying;
  9264. // if (isPlaying) {
  9265. // this.randomColor =
  9266. // `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  9267. //
  9268. // // 判断是否播放到结束时间
  9269. // if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  9270. // if (position >= duration - this.jumpEndTime * 1000) {
  9271. // this.playNext()
  9272. // }
  9273. // }
  9274. // } else {
  9275. // this.randomColor = 'rbg(0,0,0)'
  9276. // }
  9277. //
  9278. // // 节流广播进度更新到卡片
  9279. // this.broadcastProgressIfNeeded();
  9280. // } catch (error) {
  9281. // LogUtils.getInstance().LOGI(`LocalMusic setProgress error: ${error}`);
  9282. // }
  9283. }
  9284. private startProgressTask() {
  9285. let that = this;
  9286. this.updateProgressTimer = setInterval(() => {
  9287. //LogUtils.getInstance().LOGI("startProgressTask");
  9288. if (!that.mDestroyPage) {
  9289. that.setProgress();
  9290. }
  9291. }, 300);
  9292. }
  9293. private stopProgressTask() {
  9294. LogUtils.getInstance().LOGI("stopProgressTask");
  9295. clearInterval(this.updateProgressTimer);
  9296. }
  9297. private showLoadIng() {
  9298. this.loadingVisible = Visibility.Visible;
  9299. this.replayVisible = Visibility.None;
  9300. }
  9301. // 原来的 play 方法已移除,播放逻辑现在由 UnifiedPlayerService 统一处理
  9302. // private async play(url: string) { ... } 已移除
  9303. // 所有的播放器配置和监听器设置已移至 UnifiedPlayerService
  9304. //保存最后播放的那首歌和已经对应的播放列表
  9305. saveLastPlayList() {
  9306. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  9307. PreferencesUtil.putSync('LastMusicList', this.songList)
  9308. }
  9309. // 清空播放记录
  9310. clearVideoHistory() {
  9311. this.table.clearPlayHistory((success: boolean, error?: string) => {
  9312. if (success) {
  9313. this.historyList = [];
  9314. this.updateListData(this.historyList)
  9315. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  9316. ToastUtil.showToast('清空播放记录成功')
  9317. } else {
  9318. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  9319. }
  9320. });
  9321. }
  9322. setLoopMode() {
  9323. let itype = this.playType + 1
  9324. if (itype >= 4) {
  9325. this.setPlayModeViaService(0);
  9326. ToastUtil.showToast('连续播放')
  9327. } else if (itype === 1) {
  9328. this.setPlayModeViaService(1);
  9329. ToastUtil.showToast('单曲循环')
  9330. } else if (itype === 2) {
  9331. this.setPlayModeViaService(2);
  9332. ToastUtil.showToast('单曲播完')
  9333. } else if (itype === 3) {
  9334. this.setPlayModeViaService(3);
  9335. ToastUtil.showToast('随机播放')
  9336. } else if (itype === 0) {
  9337. this.setPlayModeViaService(0);
  9338. ToastUtil.showToast('连续播放')
  9339. }
  9340. this.setCurrentPlayMode()
  9341. }
  9342. public async setAvSessionListener() {
  9343. if (!this.avSessionController) {
  9344. console.log('heanup setAvSessionListener error: avSessionController is null');
  9345. return;
  9346. }
  9347. // 注意:基础播控监听器(play, pause, playNext, playPrevious, seek等)
  9348. // 已经在UnifiedPlayerService中设置,这里不再重复设置,避免冲突
  9349. // 只设置LocalMusic特有的监听器
  9350. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  9351. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  9352. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  9353. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  9354. // 设置投播设备变化监听器(这是投播功能的核心)
  9355. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange);
  9356. console.log('heanup setAvSessionListener 完成 - 已跳过基础播控监听器(由UnifiedPlayerService处理)');
  9357. // 检查当前是否已经在投播状态
  9358. await this.checkAndRestoreCastingState();
  9359. }
  9360. private sessionSetLoopModeCallback = (mode: number) => {
  9361. ToastUtil.showToast('当前播放模式:' + mode)
  9362. Logger.info('onecold 当前播放模式= ' + mode)
  9363. let hmPlayMode = mode + 1
  9364. if (hmPlayMode >= 4) {
  9365. hmPlayMode = 0
  9366. }
  9367. if (hmPlayMode === 1) {
  9368. this.setPlayModeViaService(1);
  9369. ToastUtil.showToast('单曲循环')
  9370. } else if (hmPlayMode === 0) {
  9371. this.setPlayModeViaService(2);
  9372. ToastUtil.showToast('单曲播完')
  9373. } else if (hmPlayMode === 3) {
  9374. this.setPlayModeViaService(3);
  9375. ToastUtil.showToast('随机播放')
  9376. } else if (hmPlayMode === 2) {
  9377. this.setPlayModeViaService(0);
  9378. ToastUtil.showToast('连续播放')
  9379. }
  9380. PreferencesUtil.putSync('musicPlayType', this.playType)
  9381. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  9382. let playBackState: avSession.AVPlaybackState = {
  9383. loopMode: hmPlayMode,
  9384. };
  9385. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  9386. console.info(`set setLoopMode AVPlaybackState successfully`);
  9387. }).catch((err: BusinessError) => {
  9388. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9389. });
  9390. }
  9391. setCurrentPlayMode() {
  9392. if (!this.avSessionController) {
  9393. return;
  9394. }
  9395. let mLoopMode = 0
  9396. switch (this.playType) {
  9397. case 0:
  9398. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  9399. break;
  9400. case 1:
  9401. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  9402. break;
  9403. case 2:
  9404. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  9405. break;
  9406. case 3:
  9407. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  9408. break;
  9409. }
  9410. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  9411. let playBState: avSession.AVPlaybackState = {
  9412. loopMode: mLoopMode,
  9413. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  9414. };
  9415. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  9416. console.info(`set setLoopMode AVPlaybackState successfully`);
  9417. }).catch((err: BusinessError) => {
  9418. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9419. });
  9420. }
  9421. private sessionToggleFavoriteCallback = (assetId: string) => {
  9422. if (this.currentSong) {
  9423. console.info(`on toggleFavorite - 播控中心收藏按钮被点击`);
  9424. // 应用收到收藏命令,进行收藏处理。
  9425. // 注意:这里不需要立即更新AVSession状态,因为doFav方法内部会处理状态更新
  9426. this.doFav(this.currentSong);
  9427. }
  9428. }
  9429. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  9430. device: avSession.OutputDeviceInfo) => {
  9431. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  9432. LogUtils.getInstance().LOGI(`投播设备状态变化: ${connectState}, 设备类型: ${currentDevice?.castCategory}, 协议: ${currentDevice?.supportedProtocols}`);
  9433. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9434. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  9435. // 设备连接成功,开始投播
  9436. this.currentCastDevice = currentDevice;
  9437. await this.startCasting();
  9438. // 检查设备支持的协议类型
  9439. if (currentDevice.supportedProtocols === avSession.ProtocolType.TYPE_CAST_PLUS_STREAM) {
  9440. LogUtils.getInstance().LOGI('设备支持Cast+投播协议');
  9441. } else if (currentDevice.supportedProtocols === avSession.ProtocolType.TYPE_DLNA) {
  9442. LogUtils.getInstance().LOGI('设备支持DLNA投播协议');
  9443. }
  9444. // 检查DRM支持能力
  9445. if (currentDevice.supportedDrmCapabilities?.includes('3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c')) {
  9446. LogUtils.getInstance().LOGI('设备支持chinaDRM');
  9447. // 监听许可证请求事件
  9448. this.castController?.on('keyRequest', this.keyRequestCallback);
  9449. }
  9450. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9451. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  9452. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  9453. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  9454. // 设备断开或切换回本地
  9455. if (device) {
  9456. this.endCasting();
  9457. this.currentCastDevice = undefined;
  9458. }
  9459. }
  9460. };
  9461. private async startCasting() {
  9462. try {
  9463. LogUtils.getInstance().LOGI('开始投播流程');
  9464. // 获取投播控制器
  9465. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9466. if (!this.castController) {
  9467. LogUtils.getInstance().LOGI('获取投播控制器失败');
  9468. ToastUtil.showToast('投播初始化失败');
  9469. return;
  9470. }
  9471. LogUtils.getInstance().LOGI('投播控制器获取成功');
  9472. // 设置投播状态监听
  9473. this.setPlaybackStateChangeListener();
  9474. // 暂停本地播放
  9475. this.pause();
  9476. // 初始化投播资源
  9477. this.initQueueItem();
  9478. // 准备并开始投播
  9479. await this.prepare();
  9480. // 更新投播状态
  9481. this.isCasting = true;
  9482. this.isCastPlaying = true;
  9483. this.castSeek = true;
  9484. // 同步到AppStorage
  9485. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9486. refToIsCasting?.set(true);
  9487. // 申请长时任务,避免投播时应用被冻结
  9488. this.startCastingBackgroundTask();
  9489. LogUtils.getInstance().LOGI('投播启动成功');
  9490. ToastUtil.showToast('投播已开始');
  9491. } catch (error) {
  9492. LogUtils.getInstance().LOGI(`投播启动失败: ${error}`);
  9493. ToastUtil.showToast(`投播启动失败: ${error}`);
  9494. this.endCasting();
  9495. }
  9496. }
  9497. async changeCasting() {
  9498. try {
  9499. LogUtils.getInstance().LOGI('投播资源切换开始');
  9500. // 确保投播控制器可用
  9501. if (!this.castController) {
  9502. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9503. }
  9504. if (!this.castController) {
  9505. LogUtils.getInstance().LOGI('投播控制器不可用,无法切换资源');
  9506. return;
  9507. }
  9508. // 初始化新的投播资源
  9509. this.initQueueItem();
  9510. // 准备并开始播放新资源
  9511. await this.prepare();
  9512. // 确保监听器已设置
  9513. this.setPlaybackStateChangeListener();
  9514. // 更新播放状态
  9515. this.isCastPlaying = true;
  9516. this.castSeek = true;
  9517. LogUtils.getInstance().LOGI(`投播资源切换成功: ${this.currentSong?.name}`);
  9518. } catch (error) {
  9519. LogUtils.getInstance().LOGI(`投播资源切换失败: ${error}`);
  9520. ToastUtil.showToast(`切换投播资源失败: ${error}`);
  9521. }
  9522. }
  9523. public endCasting() {
  9524. try {
  9525. LogUtils.getInstance().LOGI('结束投播流程');
  9526. // 停止投播
  9527. this.avSessionController.getAvSession()?.stopCasting();
  9528. // 清理投播控制器监听
  9529. this.stopCast();
  9530. // 更新投播状态
  9531. this.isCasting = false;
  9532. this.isCastPlaying = false;
  9533. this.castSeek = false;
  9534. // 同步到AppStorage
  9535. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9536. refToIsCasting?.set(false);
  9537. // 停止长时任务
  9538. this.stopCastingBackgroundTask();
  9539. // 恢复本地播放(可选)
  9540. // 建议保存投播断开时的进度,用于本地播放继续
  9541. const lastCastPosition = this.currentTime2 * 1000; // 投播的当前进度
  9542. // 暂停本地播放器,让用户手动选择是否继续播放
  9543. this.pause();
  9544. this.setIsPlaying(false);
  9545. // 如果需要自动恢复本地播放,可以取消注释以下代码
  9546. // if (lastCastPosition > 0) {
  9547. // this.seekTo(lastCastPosition.toString());
  9548. // setTimeout(() => {
  9549. // this.startPlayOrResumePlay();
  9550. // }, 500);
  9551. // }
  9552. LogUtils.getInstance().LOGI('投播结束成功');
  9553. ToastUtil.showToast('投播已结束');
  9554. } catch (error) {
  9555. LogUtils.getInstance().LOGI(`结束投播失败: ${error}`);
  9556. ToastUtil.showToast(`结束投播失败: ${error}`);
  9557. }
  9558. }
  9559. public setIsPlaying(isPlayer: boolean) {
  9560. this.isPlaying = isPlayer;
  9561. }
  9562. private setPlaybackStateChangeListener(): void {
  9563. if (!this.castController) {
  9564. LogUtils.getInstance().LOGI('投播控制器为空,无法设置监听器');
  9565. return;
  9566. }
  9567. try {
  9568. // 监听播放状态变化
  9569. this.castController.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  9570. // 监听播放完毕事件
  9571. this.castController.on('endOfStream', this.reloadCasting);
  9572. // 监听播控中心的上下一首切换
  9573. this.castController.on('playNext', this.playNextCallback);
  9574. this.castController.on('playPrevious', this.playPreviousCallback);
  9575. // 监听进度调节完成事件
  9576. this.castController.on('seekDone', this.seekDoneCallback);
  9577. // 监听错误事件
  9578. this.castController.on('error', this.castErrorCallback);
  9579. LogUtils.getInstance().LOGI('投播状态监听器设置完成');
  9580. } catch (error) {
  9581. LogUtils.getInstance().LOGI(`设置投播监听器失败: ${error}`);
  9582. }
  9583. }
  9584. private updateSessionPlayState(isPlay: boolean): void {
  9585. // if(!this.isBgPlayOpen)
  9586. // return
  9587. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  9588. try {
  9589. // 通过UnifiedPlayerService获取当前位置
  9590. const currentState = this.unifiedPlayerService.getCurrentState();
  9591. this.setAVSessionPlayState({
  9592. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  9593. position: {
  9594. elapsedTime: currentState.currentPosition,
  9595. updateTime: new Date().getTime()
  9596. }
  9597. });
  9598. } catch (error) {
  9599. LogUtils.getInstance().LOGI(`updateSessionPlayState error: ${error}`);
  9600. // 如果获取失败,使用默认值
  9601. this.setAVSessionPlayState({
  9602. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  9603. position: {
  9604. elapsedTime: 0,
  9605. updateTime: new Date().getTime()
  9606. }
  9607. });
  9608. }
  9609. }
  9610. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  9611. this.avSessionController.setAvSessionPlayState(playbackState)
  9612. }
  9613. private positionChange(position: number) {
  9614. this.currentTime2 = position / 1000;
  9615. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  9616. }
  9617. private playDurationChange(duration: number) {
  9618. this.duration = duration;
  9619. this.durationTime = Math.floor(this.duration / 1000);
  9620. this.durationStringTime = secondToTime((this.durationTime));
  9621. }
  9622. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  9623. try {
  9624. LogUtils.getInstance().LOGI(`投播状态变化: ${playbackState.state}, 进度: ${playbackState?.position?.elapsedTime}ms`);
  9625. // 处理播放时长变化
  9626. const duration = playbackState?.extras?.duration;
  9627. if (typeof duration === 'number') {
  9628. this.playDurationChange(duration as number);
  9629. }
  9630. // 处理播放进度变化
  9631. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  9632. this.positionChange(playbackState?.position?.elapsedTime);
  9633. }
  9634. // 处理播放状态变化
  9635. switch (playbackState.state) {
  9636. case avSession.PlaybackState.PLAYBACK_STATE_PLAY:
  9637. this.isCastPlaying = true;
  9638. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  9639. this.setIsPlaying(true);
  9640. break;
  9641. case avSession.PlaybackState.PLAYBACK_STATE_PAUSE:
  9642. this.isCastPlaying = false;
  9643. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9644. this.setIsPlaying(false);
  9645. break;
  9646. case avSession.PlaybackState.PLAYBACK_STATE_STOP:
  9647. case avSession.PlaybackState.PLAYBACK_STATE_PREPARE:
  9648. case avSession.PlaybackState.PLAYBACK_STATE_INITIAL:
  9649. this.isCastPlaying = false;
  9650. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9651. this.setIsPlaying(false);
  9652. break;
  9653. default:
  9654. LogUtils.getInstance().LOGI(`未处理的投播状态: ${playbackState.state}`);
  9655. break;
  9656. }
  9657. // 处理音量变化
  9658. if (playbackState?.volume !== undefined) {
  9659. LogUtils.getInstance().LOGI(`投播音量变化: ${playbackState.volume}`);
  9660. // 可以在这里同步音量到UI
  9661. }
  9662. // 更新UI显示
  9663. this.playChange();
  9664. } catch (error) {
  9665. LogUtils.getInstance().LOGI(`处理投播状态变化失败: ${error}`);
  9666. }
  9667. };
  9668. private reloadCasting = async () => {
  9669. try {
  9670. LogUtils.getInstance().LOGI('投播内容播放完毕,处理后续操作');
  9671. // 根据播放模式决定后续操作
  9672. switch (this.playType) {
  9673. case 0: // 顺序播放
  9674. if (this.curIndex < this.songList.length - 1) {
  9675. // 有下一首,自动切换
  9676. LogUtils.getInstance().LOGI('自动播放下一首');
  9677. this.playNext();
  9678. } else {
  9679. // 没有下一首,停止投播或循环播放第一首
  9680. LogUtils.getInstance().LOGI('播放列表结束,停止投播');
  9681. this.endCasting();
  9682. }
  9683. break;
  9684. case 1: // 单曲循环
  9685. LogUtils.getInstance().LOGI('单曲循环,重新播放当前歌曲');
  9686. this.initQueueItem();
  9687. await this.prepare();
  9688. this.isCastPlaying = true;
  9689. break;
  9690. case 2: // 列表循环
  9691. if (this.curIndex < this.songList.length - 1) {
  9692. // 播放下一首
  9693. this.playNext();
  9694. } else {
  9695. // 回到第一首
  9696. this.curIndex = 0;
  9697. this.currentSong = this.songList[0];
  9698. this.initQueueItem();
  9699. await this.prepare();
  9700. this.isCastPlaying = true;
  9701. }
  9702. break;
  9703. case 3: // 随机播放
  9704. LogUtils.getInstance().LOGI('随机播放下一首');
  9705. this.playNext();
  9706. break;
  9707. default:
  9708. LogUtils.getInstance().LOGI('未知播放模式,停止投播');
  9709. this.endCasting();
  9710. break;
  9711. }
  9712. } catch (error) {
  9713. LogUtils.getInstance().LOGI(`处理投播完毕事件失败: ${error}`);
  9714. ToastUtil.showToast(`投播切换失败: ${error}`);
  9715. }
  9716. };
  9717. public playNextCallback = (): void => {
  9718. LogUtils.getInstance().LOGI('投播设备请求播放下一首');
  9719. this.playNext();
  9720. };
  9721. public playPreviousCallback = (): void => {
  9722. LogUtils.getInstance().LOGI('投播设备请求播放上一首');
  9723. this.playPrevious();
  9724. };
  9725. // 进度调节完成回调
  9726. private seekDoneCallback = (position: number): void => {
  9727. LogUtils.getInstance().LOGI(`投播进度调节完成: ${position}ms`);
  9728. // 更新本地进度显示
  9729. this.positionChange(position);
  9730. };
  9731. // 投播错误回调
  9732. private castErrorCallback = (error: BusinessError): void => {
  9733. LogUtils.getInstance().LOGI(`投播错误: ${error.message || error}`);
  9734. ToastUtil.showToast(`投播错误: ${error.message || '未知错误'}`);
  9735. // 可以选择自动结束投播或重试
  9736. // this.endCasting();
  9737. };
  9738. // DRM许可证请求回调
  9739. private keyRequestCallback: avSession.KeyRequestCallback = async (assetId: string, requestData: Uint8Array) => {
  9740. try {
  9741. LogUtils.getInstance().LOGI(`DRM许可证请求: ${assetId}`);
  9742. // 根据assetId获取对应的DRM url(需要根据实际情况配置)
  9743. let drmUrl: string = 'http://license.xxx.xxx.com:8080/drmproxy/getLicense';
  9744. // 从服务器获取许可证
  9745. let licenseResponseData = await this.getLicense(drmUrl, requestData);
  9746. if (licenseResponseData) {
  9747. // 处理DRM许可证响应
  9748. await this.castController?.processMediaKeyResponse(assetId, licenseResponseData);
  9749. LogUtils.getInstance().LOGI('DRM许可证处理成功');
  9750. } else {
  9751. LogUtils.getInstance().LOGI('获取DRM许可证失败');
  9752. ToastUtil.showToast('DRM许可证获取失败');
  9753. }
  9754. } catch (error) {
  9755. LogUtils.getInstance().LOGI(`DRM许可证处理失败: ${error}`);
  9756. ToastUtil.showToast(`DRM许可证处理失败: ${error}`);
  9757. }
  9758. };
  9759. async prepare() {
  9760. try {
  9761. if (!this.castController || !this.castItem) {
  9762. LogUtils.getInstance().LOGI('投播控制器或资源项为空,无法准备播放');
  9763. return;
  9764. }
  9765. LogUtils.getInstance().LOGI('准备投播资源...');
  9766. // 准备播放,进行资源加载和缓冲,不会触发真正的播放
  9767. await this.castController.prepare(this.castItem);
  9768. LogUtils.getInstance().LOGI('投播资源准备完成');
  9769. // 启动播放,真正触发对端播放
  9770. await this.castController.start(this.castItem);
  9771. LogUtils.getInstance().LOGI('投播播放启动成功');
  9772. } catch (error) {
  9773. const errorMessage = error instanceof Error ? error.message : String(error);
  9774. LogUtils.getInstance().LOGI(`投播准备或启动失败: ${errorMessage}`);
  9775. ToastUtil.showToast(`投播播放失败: ${errorMessage}`);
  9776. throw new Error(errorMessage);
  9777. }
  9778. }
  9779. public initQueueItem() {
  9780. try {
  9781. let item = this.songList[this.curIndex];
  9782. if (!item) {
  9783. LogUtils.getInstance().LOGI('当前歌曲信息为空,无法初始化投播资源');
  9784. return;
  9785. }
  9786. LogUtils.getInstance().LOGI(`初始化投播资源: ${item.name}`);
  9787. let uri = fileUri.getUriFromPath(item.filePath);
  9788. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  9789. // 获取当前播放进度,用于投播时同步进度
  9790. const currentPosition = this.unifiedPlayerService.getCurrentPosition();
  9791. this.castItem = {
  9792. itemId: this.curIndex,
  9793. description: {
  9794. assetId: item.filePath,
  9795. title: item.name,
  9796. artist: item.artist || this.UNKONWN,
  9797. subtitle: item.album || '',
  9798. // 本地资源投播,使用文件描述符
  9799. fdSrc: {
  9800. fd: file.fd
  9801. },
  9802. // 音频资源类型
  9803. mediaType: 'AUDIO',
  9804. mediaSize: item.videoSize,
  9805. // 同步当前播放进度到远端
  9806. startPosition: currentPosition,
  9807. // 同步播放时长到远端显示
  9808. duration: this.duration,
  9809. // 专辑封面(如果有)
  9810. albumCoverUri: item.pixelMapPath,
  9811. albumTitle: item.album || '',
  9812. appName: this.appName,
  9813. // 如果是DRM资源,需要配置支持的DRM类型
  9814. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9815. }
  9816. };
  9817. LogUtils.getInstance().LOGI(`投播资源初始化完成 - 标题: ${item.name}, 进度: ${currentPosition}ms, 时长: ${this.duration}ms`);
  9818. } catch (error) {
  9819. LogUtils.getInstance().LOGI(`初始化投播资源失败: ${error}`);
  9820. ToastUtil.showToast(`初始化投播资源失败: ${error}`);
  9821. }
  9822. }
  9823. async stopCast() {
  9824. try {
  9825. LogUtils.getInstance().LOGI('清理投播监听器');
  9826. if (this.castController) {
  9827. // 移除所有投播监听器
  9828. this.castController.off('playbackStateChange');
  9829. this.castController.off('endOfStream');
  9830. this.castController.off('playNext');
  9831. this.castController.off('playPrevious');
  9832. this.castController.off('seekDone');
  9833. this.castController.off('error');
  9834. this.castController.off('keyRequest');
  9835. LogUtils.getInstance().LOGI('投播监听器清理完成');
  9836. }
  9837. // 清空投播控制器引用
  9838. this.castController = undefined;
  9839. this.castItem = undefined;
  9840. } catch (error) {
  9841. LogUtils.getInstance().LOGI(`清理投播监听器失败: ${error}`);
  9842. }
  9843. }
  9844. private async playOrPause() {
  9845. if (!this.debounce()) {
  9846. return;
  9847. }
  9848. // 如果正在投播,使用投播控制
  9849. if (this.isCurrentlyCasting()) {
  9850. await this.handleCastingPlayPause();
  9851. return;
  9852. }
  9853. // 本地播放控制
  9854. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9855. this.pause();
  9856. } else {
  9857. this.startPlayOrResumePlay();
  9858. this.playChange()
  9859. }
  9860. }
  9861. private sessionFastForwardCallback = (time?: number) => {
  9862. if (!time) {
  9863. return;
  9864. }
  9865. try {
  9866. // 通过UnifiedPlayerService获取当前位置
  9867. const currentState = this.unifiedPlayerService.getCurrentState();
  9868. const curPosition = currentState.currentPosition;
  9869. let seeTime = curPosition + time * 1000;
  9870. // 限制 seekValue 在合法范围内
  9871. if (seeTime < 0) {
  9872. seeTime = 0;
  9873. } else if (seeTime > currentState.duration) {
  9874. seeTime = currentState.duration;
  9875. }
  9876. Logger.info('onecold seeTime= ' + seeTime)
  9877. this.setSeekToActionProgress(seeTime)
  9878. this.seekTo(seeTime + "")
  9879. } catch (error) {
  9880. LogUtils.getInstance().LOGI(`sessionFastForwardCallback error: ${error}`);
  9881. }
  9882. };
  9883. /**
  9884. * Gesture method onActionUpdate.
  9885. *
  9886. * @param event Gesture event.手势拖动设置快进和后退
  9887. */
  9888. private setSeekToActionProgress(position: number) {
  9889. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  9890. let duration: number = this.unifiedPlayerService.getCurrentPosition();
  9891. let pos = 0;
  9892. if (duration > 0) {
  9893. this.slideEnable = true;
  9894. let curPercent = position / duration;
  9895. pos = curPercent * 100;
  9896. if (pos > this.PROGRESS_MAX_VALUE) {
  9897. this.progressValue = this.PROGRESS_MAX_VALUE
  9898. } else {
  9899. this.progressValue = pos;
  9900. }
  9901. }
  9902. // LogUtils.getInstance()
  9903. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9904. this.totalTime = this.stringForTime(duration);
  9905. if (position > duration) {
  9906. position = duration;
  9907. }
  9908. this.isCurrentTime = true;
  9909. this.currentTime = this.stringForTime(position);
  9910. this.isCurrentTime = false;
  9911. }
  9912. private sessionRewindCallback = (time?: number) => {
  9913. if (!time) {
  9914. return;
  9915. }
  9916. const curPosition: number = this.unifiedPlayerService.getCurrentPosition()
  9917. let seeTime = curPosition - time * 1000;
  9918. // 限制 seekValue 在合法范围内
  9919. if (seeTime < 0) {
  9920. seeTime = 0;
  9921. } else if (seeTime > this.duration) {
  9922. seeTime = this.duration;
  9923. }
  9924. Logger.info('onecold seeTime= ' + seeTime)
  9925. this.setSeekToActionProgress(seeTime)
  9926. this.seekTo(seeTime + "")
  9927. };
  9928. private sessionSeekCallback = (seekTime: number) => {
  9929. LogUtils.getInstance().LOGI(`播控中心请求进度调节: ${seekTime}ms`);
  9930. this.seekTo(seekTime + "");
  9931. };
  9932. // 注意:基础播控回调方法(play, pause, playNext, playPrevious, seek)
  9933. // 已经在UnifiedPlayerService中实现,这里不再重复定义,避免冲突
  9934. private async getFileSize(filePath: string): Promise<number> {
  9935. try {
  9936. const stat = await fs.stat(filePath);
  9937. return stat.size;
  9938. } catch (err) {
  9939. console.error('Failed to get file size: ' + err.message);
  9940. return 0;
  9941. }
  9942. }
  9943. // 启动投播长时任务
  9944. private startCastingBackgroundTask(): void {
  9945. try {
  9946. // 这里应该调用BackgroundTaskManager来申请长时任务
  9947. // 避免应用在投播时进入后台被系统冻结
  9948. LogUtils.getInstance().LOGI('申请投播长时任务');
  9949. // BackgroundTaskManager.startContinuousTask(this.context, backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK);
  9950. } catch (error) {
  9951. LogUtils.getInstance().LOGI(`申请投播长时任务失败: ${error}`);
  9952. }
  9953. }
  9954. // 停止投播长时任务
  9955. private stopCastingBackgroundTask(): void {
  9956. try {
  9957. LogUtils.getInstance().LOGI('停止投播长时任务');
  9958. // BackgroundTaskManager.stopContinuousTask(this.context);
  9959. } catch (error) {
  9960. LogUtils.getInstance().LOGI(`停止投播长时任务失败: ${error}`);
  9961. }
  9962. }
  9963. // 获取DRM许可证(示例实现,需要根据实际服务配置)
  9964. private async getLicense(drmUrl: string, requestData: Uint8Array): Promise<Uint8Array | undefined> {
  9965. try {
  9966. // 这里需要根据实际的DRM服务实现许可证获取逻辑
  9967. LogUtils.getInstance().LOGI(`请求DRM许可证: ${drmUrl}`);
  9968. // 示例:使用HTTP请求获取许可证
  9969. // const response = await fetch(drmUrl, {
  9970. // method: 'POST',
  9971. // headers: {
  9972. // 'Content-Type': 'application/octet-stream'
  9973. // },
  9974. // body: requestData
  9975. // });
  9976. //
  9977. // if (response.ok) {
  9978. // const licenseData = await response.arrayBuffer();
  9979. // return new Uint8Array(licenseData);
  9980. // }
  9981. LogUtils.getInstance().LOGI('DRM许可证获取功能需要根据实际服务配置');
  9982. return undefined;
  9983. } catch (error) {
  9984. LogUtils.getInstance().LOGI(`获取DRM许可证失败: ${error}`);
  9985. return undefined;
  9986. }
  9987. }
  9988. // 检查当前是否正在投播
  9989. public isCurrentlyCasting(): boolean {
  9990. return this.isCasting && this.castController !== undefined;
  9991. }
  9992. // 获取当前投播设备信息
  9993. public getCurrentCastDevice(): avSession.DeviceInfo | undefined {
  9994. return this.currentCastDevice;
  9995. }
  9996. // 投播控制命令
  9997. public async sendCastControlCommand(command: string, parameter?: number): Promise<void> {
  9998. if (!this.castController) {
  9999. LogUtils.getInstance().LOGI('投播控制器不可用');
  10000. return;
  10001. }
  10002. try {
  10003. let avCommand: avSession.AVCastControlCommand = {
  10004. command: command as avSession.AVCastControlCommandType
  10005. };
  10006. if (parameter !== undefined) {
  10007. avCommand.parameter = parameter;
  10008. }
  10009. await this.castController.sendControlCommand(avCommand);
  10010. LogUtils.getInstance().LOGI(`投播控制命令发送成功: ${command}`);
  10011. } catch (error) {
  10012. LogUtils.getInstance().LOGI(`发送投播控制命令失败: ${error}`);
  10013. ToastUtil.showToast(`投播控制失败: ${error}`);
  10014. }
  10015. }
  10016. private async pause() {
  10017. if (this.unifiedPlayerService.getIjkPlayer()?.isPlaying()){
  10018. this.savePlaybackPosition();
  10019. this.unifiedPlayerService.pause();
  10020. this.setProgress();
  10021. this.mDestroyPage = true;
  10022. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  10023. // 注意:AVSession状态更新由UnifiedPlayerService统一处理,避免冲突
  10024. this.playChange()
  10025. if (this.pipController) {
  10026. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10027. PiPWindow.PiPControlStatus.PAUSE);
  10028. }
  10029. }
  10030. // try {
  10031. // // 使用UnifiedPlayerService暂停播放
  10032. // await this.unifiedPlayerService.pause();
  10033. //
  10034. // // 保持原有的UI更新逻辑
  10035. // this.setProgress();
  10036. // this.mDestroyPage = true;
  10037. // this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  10038. // this.setIsPlaying(false);
  10039. // this.updateSessionPlayState(false);
  10040. // this.playChange()
  10041. //
  10042. // if (this.pipController) {
  10043. // this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10044. // PiPWindow.PiPControlStatus.PAUSE);
  10045. // }
  10046. //
  10047. // LogUtils.getInstance().LOGI("LocalMusic: pause completed via UnifiedPlayerService");
  10048. // } catch (error) {
  10049. // LogUtils.getInstance().LOGI(`LocalMusic pause error: ${error}`);
  10050. // ToastUtil.showToast(`暂停失败: ${error}`);
  10051. // }
  10052. }
  10053. private async stop() {
  10054. try {
  10055. // 使用UnifiedPlayerService停止播放
  10056. await this.unifiedPlayerService.stop();
  10057. // 保持原有的UI更新逻辑 - 重要:停止时清除所有播放状态
  10058. this.stopProgressTask();
  10059. this.CONTROL_PlayStatus = PlayStatus.INIT; // 初始状态,不是暂停
  10060. this.setIsPlaying(false);
  10061. // 强制更新UI状态
  10062. this.playChange()
  10063. this.watchStatus();
  10064. LogUtils.getInstance().LOGI("LocalMusic: stop completed - all states cleared to INIT");
  10065. } catch (error) {
  10066. LogUtils.getInstance().LOGI(`LocalMusic stop error: ${error}`);
  10067. ToastUtil.showToast(`停止播放失败: ${error}`);
  10068. }
  10069. }
  10070. //保持记忆播放功能
  10071. private savePlaybackPosition() {
  10072. try {
  10073. // 通过UnifiedPlayerService获取当前播放位置
  10074. const currentState = this.unifiedPlayerService.getCurrentState();
  10075. const position = currentState.currentPosition;
  10076. const duration = currentState.duration;
  10077. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  10078. // 如果播放位置接近视频末尾,则保存 position 为 0
  10079. const playbackPosition = (duration - position < threshold) ? 0 : position;
  10080. // 同时保存到PreferencesUtil和AppStorage,确保卡片也能访问
  10081. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  10082. AppStorage.setOrCreate(`playback_${this.videoUrl}`, playbackPosition);
  10083. LogUtils.getInstance().LOGI(`Saved playback position: ${playbackPosition}ms for ${this.name}`);
  10084. } catch (error) {
  10085. LogUtils.getInstance().LOGI(`savePlaybackPosition error: ${error}`);
  10086. }
  10087. }
  10088. //获取记忆播放功能
  10089. private restorePlaybackPosition() {
  10090. // 优先从AppStorage获取,如果没有则从PreferencesUtil获取
  10091. let position: number = AppStorage.get<number>(`playback_${this.videoUrl}`) || 0;
  10092. if (position === 0) {
  10093. position = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10094. }
  10095. // ToastUtil.showToast('position = ' + position)
  10096. if (position > 0) {
  10097. // ToastUtil.showToast('seekTo = ' + position)
  10098. this.seekTo(position + "");
  10099. LogUtils.getInstance().LOGI(`Restored playback position: ${position}ms for ${this.name}`);
  10100. }
  10101. }
  10102. private async seekTo(value: string) {
  10103. try {
  10104. const position = parseInt(value);
  10105. // 如果正在投播,使用投播进度控制
  10106. if (this.isCurrentlyCasting()) {
  10107. await this.handleCastingSeek(position);
  10108. return;
  10109. }
  10110. // 使用UnifiedPlayerService进行拖动
  10111. await this.unifiedPlayerService.seekTo(value);
  10112. // 保持原有的UI更新逻辑
  10113. this.setProgress()
  10114. LogUtils.getInstance().LOGI(`LocalMusic: seekTo ${value} completed via UnifiedPlayerService`);
  10115. } catch (error) {
  10116. LogUtils.getInstance().LOGI(`LocalMusic seekTo error: ${error}`);
  10117. // 如果是WMA格式错误,显示特定提示
  10118. if (error.toString().includes('WMA format')) {
  10119. ToastUtil.showToast('wma格式不支持拖动快进。');
  10120. return;
  10121. } else {
  10122. ToastUtil.showToast(`拖动失败: ${error}`);
  10123. }
  10124. }
  10125. }
  10126. // 添加到下一首播放
  10127. private addToNextPlay(song: VideoItem) {
  10128. if (!this.debounce()) {
  10129. return;
  10130. }
  10131. if (this.currentSong) {
  10132. if (this.currentSong === song) {
  10133. ToastUtil.showToast('当前已经在播放这首歌了!')
  10134. return
  10135. }
  10136. }
  10137. try {
  10138. // 如果未开始播放或队列为空
  10139. if (this.curIndex === -1 || this.songList.length === 0) {
  10140. this.songList = [song];
  10141. this.curIndex = 0;
  10142. this.doPlay(song)
  10143. return;
  10144. }
  10145. // 插入到当前索引+1的位置
  10146. const insertPos = this.curIndex + 1;
  10147. // 使用UnifiedPlayerService添加到播放列表
  10148. this.unifiedPlayerService.addToPlaylist(song, insertPos);
  10149. // 更新本地播放列表
  10150. this.songList.splice(insertPos, 0, song);
  10151. this.songList = [...this.songList]; // 触发状态更新
  10152. this.sonDataSource.pushArrayData(this.songList);
  10153. ToastUtil.showToast('已添加至下一首播放')
  10154. } catch (error) {
  10155. // 错误处理:回退到原有逻辑
  10156. const insertPos = this.curIndex + 1;
  10157. this.songList.splice(insertPos, 0, song);
  10158. this.songList = [...this.songList];
  10159. this.sonDataSource.pushArrayData(this.songList);
  10160. ToastUtil.showToast('已添加至下一首播放')
  10161. }
  10162. }
  10163. //下一个
  10164. private async playNext() {
  10165. if (!this.debounce()) {
  10166. return;
  10167. }
  10168. try {
  10169. // 移除了随机播放的特殊处理,统一使用UnifiedPlayerService
  10170. // 这样可以确保所有播放模式的状态都保持一致
  10171. if (ArrayUtil.isNotEmpty(this.songList)) {
  10172. // 如果正在投播,需要特殊处理
  10173. if (this.isCurrentlyCasting()) {
  10174. await this.handleCastingPlayNext();
  10175. return;
  10176. }
  10177. // 使用UnifiedPlayerService播放下一首,支持所有播放模式(包括随机播放)
  10178. await this.unifiedPlayerService.playNext();
  10179. // 智能同步播放列表到UnifiedPlayerService
  10180. const servicePlaylist = this.unifiedPlayerService.getPlaylist();
  10181. const serviceIndex = this.unifiedPlayerService.getCurrentIndex();
  10182. if (ArrayUtil.isEmpty(servicePlaylist)) {
  10183. // 如果服务没有播放列表,使用LocalMusic的播放列表
  10184. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  10185. } else {
  10186. // 如果服务已有播放列表,检查是否需要同步
  10187. const serviceSong = this.unifiedPlayerService.getCurrentSong();
  10188. if (serviceSong && serviceIndex >= 0 && serviceIndex < servicePlaylist.length) {
  10189. // 同步服务的状态到LocalMusic,确保状态一致
  10190. this.songList = servicePlaylist;
  10191. this.curIndex = serviceIndex;
  10192. this.currentSong = serviceSong;
  10193. this.sonDataSource.pushArrayData(this.songList);
  10194. }
  10195. }
  10196. // 更新本地状态以保持UI同步
  10197. const currentIndex = this.unifiedPlayerService.getCurrentIndex();
  10198. const currentSong = this.unifiedPlayerService.getCurrentSong();
  10199. if (currentSong) {
  10200. this.curIndex = currentIndex;
  10201. this.currentSong = currentSong;
  10202. this.videoUrl = currentSong.filePath;
  10203. this.artist = currentSong.artist;
  10204. this.name = currentSong.name;
  10205. this.cover = currentSong.pixelMapPath;
  10206. // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  10207. this.oldSeconds = 0;
  10208. this.currentTime = "00:00";
  10209. this.lastSongPath = currentSong.filePath;
  10210. this.justSwitched = true; // 标记歌曲刚刚切换
  10211. this.changeImageAnimation();
  10212. }
  10213. }
  10214. } catch (error) {
  10215. ToastUtil.showToast(`切换下一首失败: ${error}`);
  10216. // 错误处理:回退到原有逻辑
  10217. this.fallbackPlayNext();
  10218. }
  10219. // 同步播放列表到UnifiedPlayerService
  10220. this.syncPlaylistToService();
  10221. }
  10222. // 回退到原有的playNext逻辑
  10223. private fallbackPlayNext() {
  10224. if (ArrayUtil.isNotEmpty(this.songList)) {
  10225. if (this.curIndex == this.songList.length - 1) {
  10226. this.curIndex = 0;
  10227. } else {
  10228. this.curIndex++;
  10229. }
  10230. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10231. this.stop();
  10232. this.currentSong = this.songList[this.curIndex]
  10233. this.videoUrl = this.songList[this.curIndex].filePath;
  10234. this.artist = this.songList[this.curIndex].artist
  10235. this.name = this.songList[this.curIndex].name
  10236. this.changeImageAnimation()
  10237. }
  10238. }
  10239. changeImageAnimation() {
  10240. if(this.openSkipSongAnimate){
  10241. // 第一步:淡出动画
  10242. this.getUIContext()?.animateTo({
  10243. duration: 500,
  10244. curve: Curve.EaseOut,
  10245. }, () => {
  10246. this.opacityValueImage = 0.1;
  10247. if(this.isCoverRectangle){
  10248. this.scaleValueImage = 0.88
  10249. }
  10250. });
  10251. // 第二步:切换图片后淡入
  10252. setTimeout(() => {
  10253. this.cover = this.songList[this.curIndex].pixelMapPath
  10254. this.getUIContext()?.animateTo({
  10255. duration: 500,
  10256. curve: Curve.EaseIn,
  10257. }, () => {
  10258. this.opacityValueImage = 1;
  10259. this.scaleValueImage = 1 // 图标恢复到原始大小
  10260. // 注意:不再手动调用 startPlayOrResumePlay(),因为 UnifiedPlayerService 已经处理了播放逻辑
  10261. });
  10262. }, 500);
  10263. }else{
  10264. this.cover = this.songList[this.curIndex].pixelMapPath
  10265. // 注意:不再手动调用 startPlayOrResumePlay(),因为 UnifiedPlayerService 已经处理了播放逻辑
  10266. }
  10267. }
  10268. // 存储已播放的歌曲索引
  10269. private playedIndices: Set<number> = new Set();
  10270. //随机播放
  10271. private randomPlay() {
  10272. // if (!this.debounce()) {
  10273. // return;
  10274. // }
  10275. if (ArrayUtil.isNotEmpty(this.songList)) {
  10276. if (this.songList.length > 3) {
  10277. // 如果所有歌曲都播放过一次,清空已播放索引集合
  10278. if (this.playedIndices.size === this.songList.length) {
  10279. this.playedIndices.clear();
  10280. }
  10281. // 随机选择一个未播放的歌曲索引
  10282. let newIndex: number;
  10283. // 添加超时机制防止无限循环
  10284. let attempt = 0;
  10285. const maxAttempts = 100; // 根据需求调整
  10286. do {
  10287. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  10288. attempt++;
  10289. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  10290. if (attempt >= maxAttempts) {
  10291. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  10292. newIndex = Math.floor(Math.random() * this.songList.length);
  10293. }
  10294. this.curIndex = newIndex;
  10295. this.playedIndices.add(newIndex);
  10296. } else {
  10297. // 当歌曲数量小于或等于3时,直接播放下一首
  10298. if (this.curIndex == this.songList.length - 1) {
  10299. this.curIndex = 0;
  10300. } else {
  10301. this.curIndex++;
  10302. }
  10303. }
  10304. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10305. this.stop();
  10306. this.currentSong = this.songList[this.curIndex];
  10307. this.videoUrl = this.songList[this.curIndex].filePath;
  10308. this.name = this.songList[this.curIndex].name;
  10309. this.artist = this.songList[this.curIndex].artist
  10310. // this.cover = this.songList[this.curIndex].pixelMapPath
  10311. this.changeImageAnimation()
  10312. }
  10313. }
  10314. private async playIndex(index: number) {
  10315. if (!this.debounce()) {
  10316. return;
  10317. }
  10318. if (ArrayUtil.isNotEmpty(this.songList)) {
  10319. try {
  10320. // 使用UnifiedPlayerService播放指定索引的歌曲
  10321. await this.playSongAtIndexViaService(index);
  10322. this.changeImageAnimation();
  10323. } catch (error) {
  10324. // 错误处理:回退到原有逻辑
  10325. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10326. this.stop();
  10327. this.currentSong = this.songList[index]
  10328. this.videoUrl = this.songList[index].filePath;
  10329. this.name = this.songList[index].name
  10330. this.artist = this.songList[index].artist
  10331. this.curIndex = index;
  10332. this.changeImageAnimation()
  10333. }
  10334. }
  10335. }
  10336. //上一个
  10337. private async playPrevious() {
  10338. if (!this.debounce()) {
  10339. return;
  10340. }
  10341. try {
  10342. // 移除了随机播放的特殊处理,统一使用UnifiedPlayerService
  10343. // 这样可以确保所有播放模式的状态都保持一致
  10344. if (ArrayUtil.isNotEmpty(this.songList)) {
  10345. // 如果正在投播,需要特殊处理
  10346. if (this.isCurrentlyCasting()) {
  10347. await this.handleCastingPlayPrevious();
  10348. return;
  10349. }
  10350. // 使用UnifiedPlayerService播放上一首,支持所有播放模式(包括随机播放)
  10351. await this.unifiedPlayerService.playPrevious();
  10352. // 智能同步播放列表到UnifiedPlayerService
  10353. const servicePlaylist = this.unifiedPlayerService.getPlaylist();
  10354. const serviceIndex = this.unifiedPlayerService.getCurrentIndex();
  10355. // 更新本地状态以保持UI同步
  10356. const currentIndex = this.unifiedPlayerService.getCurrentIndex();
  10357. const currentSong = this.unifiedPlayerService.getCurrentSong();
  10358. if (currentSong) {
  10359. this.curIndex = currentIndex;
  10360. this.currentSong = currentSong;
  10361. this.videoUrl = currentSong.filePath;
  10362. this.name = currentSong.name;
  10363. this.artist = currentSong.artist;
  10364. this.cover = currentSong.pixelMapPath;
  10365. // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  10366. this.oldSeconds = 0;
  10367. this.currentTime = "00:00";
  10368. this.lastSongPath = currentSong.filePath;
  10369. this.justSwitched = true; // 标记歌曲刚刚切换
  10370. this.changeImageAnimation();
  10371. }
  10372. }
  10373. } catch (error) {
  10374. ToastUtil.showToast(`切换上一首失败: ${error}`);
  10375. // 错误处理:回退到原有逻辑
  10376. this.fallbackPlayPrevious();
  10377. }
  10378. // 同步播放列表到UnifiedPlayerService
  10379. this.syncPlaylistToService();
  10380. }
  10381. // 回退到原有的playPrevious逻辑
  10382. private fallbackPlayPrevious() {
  10383. if (this.curIndex == 0) {
  10384. this.curIndex = this.songList.length - 1;
  10385. } else {
  10386. this.curIndex--;
  10387. }
  10388. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10389. this.stop();
  10390. this.currentSong = this.songList[this.curIndex]
  10391. this.videoUrl = this.songList[this.curIndex].filePath;
  10392. this.name = this.songList[this.curIndex].name
  10393. this.artist = this.songList[this.curIndex].artist
  10394. this.startPlayOrResumePlay()
  10395. this.changeImageAnimation()
  10396. }
  10397. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  10398. private randomModePlayFromHistory() {
  10399. if (this.historyList.length >= 2) {
  10400. // 播放历史记录的第二首
  10401. const prevSong = this.historyList[1];
  10402. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  10403. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10404. this.stop();
  10405. this.currentSong = prevSong;
  10406. this.videoUrl = prevSong.filePath;
  10407. this.cover = prevSong.pixelMapPath
  10408. this.artist = prevSong.artist
  10409. this.name = prevSong.name;
  10410. this.startPlayOrResumePlay();
  10411. } else {
  10412. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  10413. if (this.curIndex === 0) {
  10414. this.curIndex = this.songList.length - 1;
  10415. } else {
  10416. this.curIndex--;
  10417. }
  10418. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10419. this.stop();
  10420. this.currentSong = this.songList[this.curIndex];
  10421. this.videoUrl = this.songList[this.curIndex].filePath;
  10422. this.artist = this.songList[this.curIndex].artist
  10423. this.name = this.songList[this.curIndex].name;
  10424. this.changeImageAnimation()
  10425. }
  10426. }
  10427. debounce() {
  10428. const delay = 600;
  10429. let cur = new Date().getTime();
  10430. if (cur - this.last > delay) {
  10431. this.last = cur;
  10432. return true;
  10433. }
  10434. return false;
  10435. }
  10436. /**
  10437. * Sets whether the screen is a constant based on the playback status.
  10438. */
  10439. watchStatus() {
  10440. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  10441. if (this.windowClass) {
  10442. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10443. this.windowClass.setWindowKeepScreenOn(true);
  10444. } else {
  10445. this.windowClass.setWindowKeepScreenOn(false);
  10446. }
  10447. }
  10448. }
  10449. /**
  10450. * Volume gesture method onActionStart.
  10451. *
  10452. * @param event Gesture event.
  10453. */
  10454. private customDialogComponentIdMM: number = 0
  10455. @Builder
  10456. customDialogComponentMM() {
  10457. Column() {
  10458. Row() {
  10459. Blank()
  10460. Text('验证密码')
  10461. .fontSize(22)
  10462. .fontColor($r('app.color.pri_bg'))
  10463. .margin({ top: 18 })
  10464. Blank()
  10465. Image($r('app.media.close'))
  10466. .fillColor(Color.White)
  10467. .margin({ top: 18, right: 18 })
  10468. .width(20)
  10469. .onClick(() => {
  10470. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10471. })
  10472. }
  10473. .width('100%') // 使Row占据整个宽度
  10474. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  10475. Verify({
  10476. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  10477. });
  10478. }.height('60%')
  10479. .backgroundColor($r('app.color.index_background'))
  10480. .justifyContent(FlexAlign.SpaceBetween)
  10481. }
  10482. private handleVerifyCompleted(isSuccess: boolean) {
  10483. if (isSuccess) {
  10484. console.log('验证成功');
  10485. // 在这里处理验证成功后的逻辑
  10486. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10487. this.currentPath = this.lockPath
  10488. this.getSortedFiles(this.currentPath)
  10489. } else {
  10490. // console.log('验证失败');
  10491. ToastUtil.showToast('验证失败')
  10492. }
  10493. }
  10494. private showVerifyDialog() {
  10495. promptAction.openCustomDialog({
  10496. transition: TransitionEffect.asymmetric(
  10497. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  10498. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10499. ,
  10500. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  10501. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10502. ),
  10503. builder: () => {
  10504. this.customDialogComponentMM()
  10505. },
  10506. isModal: true,
  10507. autoCancel: true,
  10508. maskColor: Color.Transparent,
  10509. alignment: DialogAlignment.Bottom,
  10510. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  10511. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  10512. console.log("dialog onWillDismiss")
  10513. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  10514. dismissDialogAction.dismiss()
  10515. }
  10516. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  10517. dismissDialogAction.dismiss()
  10518. }
  10519. }
  10520. }).then((dialogId: number) => {
  10521. this.customDialogComponentIdMM = dialogId
  10522. })
  10523. }
  10524. //左滑操作 移动文件 重命名 删除等操作
  10525. @Builder
  10526. DeleteButton(item: VideoItem, index: number, filePath: string) {
  10527. Row() {
  10528. //加入收藏
  10529. Button() {
  10530. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  10531. .fillColor(Color.White)
  10532. .width(20)
  10533. }
  10534. .width(40)
  10535. .height(40)
  10536. .type(ButtonType.Circle)
  10537. .backgroundColor(this.themeColor)
  10538. .margin(5)
  10539. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10540. .onClick(() => {
  10541. if (item) {
  10542. this.doFav(item)
  10543. }
  10544. })
  10545. //加入下一首播放
  10546. Button() {
  10547. Image($r('app.media.next_to_play'))
  10548. .fillColor(Color.White)
  10549. .width(20)
  10550. }
  10551. .width(40)
  10552. .height(40)
  10553. .type(ButtonType.Circle)
  10554. .backgroundColor(this.themeColor)
  10555. .margin(5)
  10556. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10557. .onClick(() => {
  10558. this.addToNextPlay(item);
  10559. })
  10560. //复制文件
  10561. Button() {
  10562. Image($r('app.media.copy'))
  10563. .fillColor(Color.White)
  10564. .width(20)
  10565. }
  10566. .width(40)
  10567. .height(40)
  10568. .type(ButtonType.Circle)
  10569. .backgroundColor(this.themeColor)
  10570. .margin(5)
  10571. .id(filePath + 'copy')
  10572. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10573. .onClick(() => {
  10574. this.showCopyDialog(false, item, index, filePath + 'copy');
  10575. })
  10576. //移动文件
  10577. Button() {
  10578. Image($r('app.media.cut'))
  10579. .fillColor(Color.White)
  10580. .width(20)
  10581. }
  10582. .width(40)
  10583. .height(40)
  10584. .type(ButtonType.Circle)
  10585. .backgroundColor(this.themeColor)
  10586. .margin(5)
  10587. .id(filePath)
  10588. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10589. .onClick(() => {
  10590. this.showCutDialog(false, item, index, filePath);
  10591. })
  10592. Button() {
  10593. Image($r('app.media.cut_current'))
  10594. .fillColor(Color.White)
  10595. .width(20)
  10596. }
  10597. .width(40)
  10598. .height(40)
  10599. .type(ButtonType.Circle)
  10600. .backgroundColor(this.themeColor)
  10601. .margin(5)
  10602. .id(filePath + 'current')
  10603. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  10604. (this.isHasDir ? Visibility.Visible : Visibility.None))
  10605. .onClick(() => {
  10606. this.showCutDialog(true, item, index, filePath + 'current');
  10607. })
  10608. //重命名
  10609. Button() {
  10610. Image($r('app.media.rename2'))
  10611. .fillColor(Color.White)
  10612. .width(20)
  10613. }
  10614. .width(40)
  10615. .height(40)
  10616. .type(ButtonType.Circle)
  10617. .backgroundColor(this.themeColor)
  10618. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10619. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10620. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10621. .margin(5)
  10622. .onClick(() => {
  10623. this.showReNameDialog(item, index + '', filePath)
  10624. })
  10625. Button() {
  10626. Image($r('app.media.delete2'))
  10627. .fillColor(Color.White)
  10628. .width(20)
  10629. }
  10630. .width(40)
  10631. .height(40)
  10632. .type(ButtonType.Circle)
  10633. .backgroundColor(this.themeColor)
  10634. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10635. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10636. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10637. .margin(5)
  10638. .onClick(() => {
  10639. this.showWarnIsDeleteFile(item, index + '', filePath)
  10640. })
  10641. Button() {
  10642. Image($r('app.media.share2'))
  10643. .fillColor(Color.White)
  10644. .width(20)
  10645. }
  10646. .width(40)
  10647. .height(40)
  10648. .type(ButtonType.Circle)
  10649. .backgroundColor(this.themeColor)
  10650. .margin(5)
  10651. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10652. .onClick(() => {
  10653. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10654. })
  10655. }
  10656. }
  10657. /**
  10658. * 穿山甲banner广告
  10659. */
  10660. // private declare bannerAd: CSJNativeExpressAd;
  10661. // @State private status: string = "未加载"
  10662. // @State private isShowAd: boolean = false
  10663. // private declare mAdSlot: AdSlot;
  10664. // private mBiddingAdm = '' //服务端bidding才需要设置
  10665. // private expressLoadAdListener: NativeExpressAdListener = {
  10666. // /**
  10667. // * 加载失败的回调
  10668. // *
  10669. // * @param code
  10670. // * @param message
  10671. // */
  10672. // onError: (code: number, message: string) => {
  10673. // console.error("加载广告失败,code=" + code + ",message=" + message);
  10674. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  10675. // },
  10676. //
  10677. // /**
  10678. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  10679. // *
  10680. // * @param ads 返回的广告列表
  10681. // */
  10682. //
  10683. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  10684. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  10685. // if (ads && ads.length > 0) {
  10686. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  10687. // ad.setExpressInteractionListener({
  10688. // /**
  10689. // *广告的点击回调
  10690. // * @param type 广告的交互类型
  10691. // */
  10692. // onAdClicked: (type: number) => {
  10693. // console.log("BannerExpressAdPage==onAdClicked......");
  10694. // },
  10695. //
  10696. // /**
  10697. // * 广告的展示回调 每个广告仅回调一次
  10698. // * @param type 广告的交互类型
  10699. // */
  10700. // onAdShow: (type: number) => {
  10701. // console.log("BannerExpressAdPage==onAdShow......");
  10702. // },
  10703. //
  10704. // /**
  10705. // * 模板渲染失败
  10706. // */
  10707. // onRenderFail: (code: number, msg: string) => {
  10708. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  10709. // },
  10710. //
  10711. // /**
  10712. // * 模板渲染成功
  10713. // * @param width 返回view的宽 单位 vp
  10714. // * @param height 返回view的高 单位 vp
  10715. // */
  10716. // onRenderSuccess: (width: number, height: number) => {
  10717. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  10718. // this.bannerAd = ad;
  10719. // this.status = "广告加载完成待展示";
  10720. //
  10721. // this.showBannerAd()
  10722. // }
  10723. // })
  10724. // //渲染广告
  10725. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  10726. // this.setDislikeCallback(ad); //设置dislike
  10727. // ad.render(this.getUIContext())
  10728. // this.status = "广告加载中...";
  10729. // });
  10730. // }
  10731. // }
  10732. // }
  10733. //
  10734. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  10735. // ad.setDislikeCallback({
  10736. // /**
  10737. // * dislike show
  10738. // */
  10739. // onShow: () => {
  10740. // console.log("BannerExpressAdPage==dislike......show");
  10741. // },
  10742. //
  10743. // /**
  10744. // * @param position 选择的位置
  10745. // * @param value 选择的内容
  10746. // * @param enforceRemove 是否强制关闭广告
  10747. // */
  10748. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  10749. // this.isShowAd = false;
  10750. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  10751. // ",enforce=" + enforceRemove);
  10752. // },
  10753. //
  10754. // /**
  10755. // * 点击取消
  10756. // */
  10757. // onCancel: () => {
  10758. // console.log("BannerExpressAdPage==dislike......onCancel");
  10759. // }
  10760. //
  10761. // })
  10762. // }
  10763. /**
  10764. * 加载Banner广告
  10765. */
  10766. loadBannerAd(rit: string) {
  10767. // if (Utility.isNoble()) {
  10768. // return
  10769. // }
  10770. // if (!Utility.isPassInstallTime(2)) {
  10771. // return
  10772. // }
  10773. // this.isShowAd = false;
  10774. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  10775. // this.mAdSlot = new AdSlotBuilder()
  10776. // .setCodeId(rit)
  10777. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  10778. // .setAdCount(1)
  10779. // .setBidAdm(this.mBiddingAdm)
  10780. // .build()
  10781. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  10782. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  10783. // this.status = "广告加载中..."
  10784. }
  10785. /**
  10786. * 节流广播进度更新
  10787. */
  10788. private broadcastProgressIfNeeded(): void {
  10789. const now = Date.now();
  10790. if (now - this.lastProgressBroadcastTime >= this.PROGRESS_BROADCAST_INTERVAL) {
  10791. this.lastProgressBroadcastTime = now;
  10792. this.broadcastPlayerProgress();
  10793. }
  10794. }
  10795. /**
  10796. * 广播播放进度到卡片
  10797. */
  10798. private broadcastPlayerProgress(): void {
  10799. try {
  10800. const currentPos: number = this.unifiedPlayerService.getCurrentPosition() || 0;
  10801. const progressData: PlayProgress = {
  10802. currentPosition: currentPos,
  10803. duration: this.duration || 0,
  10804. percentage: this.duration > 0 ? (currentPos / this.duration) * 100 : 0,
  10805. currentTimeText: this.currentTime || '00:00',
  10806. totalTimeText: this.totalTime || '00:00'
  10807. };
  10808. // 广播播放进度变化
  10809. const publishInfo: commonEventManager.CommonEventPublishData = {
  10810. data: JSON.stringify(progressData)
  10811. };
  10812. commonEventManager.publish(PLAYER_PROGRESS_CHANGED_EVENT, publishInfo, (err) => {
  10813. if (err) {
  10814. LogUtils.getInstance().error(`Failed to broadcast player progress: ${JSON.stringify(err)}`);
  10815. } else {
  10816. LogUtils.getInstance().LOGI(`Progress broadcasted: ${progressData.percentage.toFixed(1)}%`);
  10817. }
  10818. });
  10819. } catch (error) {
  10820. LogUtils.getInstance().error(`Failed to broadcast player progress: ${error}`);
  10821. }
  10822. }
  10823. }
  10824. //视频气泡窗口的布局
  10825. @Builder
  10826. function customPopupBuilder(dataBu: BubbleBean) {
  10827. List() {
  10828. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  10829. ListItem() {
  10830. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10831. Row() {
  10832. Column() {
  10833. Image(dataBu.imageRes[index])
  10834. .height(28)
  10835. .fillColor(dataBu.color)
  10836. .alignSelf(ItemAlign.Center)
  10837. }
  10838. .width(32)
  10839. Text(item)
  10840. .padding({
  10841. top: 10,
  10842. bottom: 10,
  10843. right: 10,
  10844. left: 10
  10845. })
  10846. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  10847. .textAlign(TextAlign.Start)
  10848. .width("100%")
  10849. }
  10850. }
  10851. .backgroundColor($r('app.color.settings_background_main'))
  10852. .margin({ top: 6, bottom: 6 })
  10853. }
  10854. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10855. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  10856. TransitionEffect.scale({ x: 0, y: 0 })))
  10857. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10858. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10859. .onClick(() => {
  10860. dataBu.onItemClick?.(index)
  10861. })
  10862. })
  10863. }
  10864. .width(120)
  10865. .divider({
  10866. strokeWidth: 1,
  10867. color: "#22FFFFFF"
  10868. })
  10869. }
  10870. // Function to calculate a hash for the file list
  10871. function simpleHash(fileList: string[]): string {
  10872. let hash = 0;
  10873. const str = fileList.join(',');
  10874. for (let i = 0; i < str.length; i++) {
  10875. const char = str.charCodeAt(i);
  10876. hash = (hash << 5) - hash + char;
  10877. hash |= 0; // Convert to 32bit integer
  10878. }
  10879. return hash.toString();
  10880. }
  10881. interface MoreItem {
  10882. id: number;
  10883. image: Resource;
  10884. title: string;
  10885. }
  10886. //视频气泡窗口的布局
  10887. @Builder
  10888. function cutPopupBuilder(dataBu: BubbleBean) {
  10889. Column() {
  10890. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  10891. .padding({
  10892. top: 10,
  10893. bottom: 10,
  10894. right: 10,
  10895. left: 10
  10896. })
  10897. .textAlign(TextAlign.Start)
  10898. .width(160)
  10899. .fontWeight(666)
  10900. .fontSize(16)
  10901. List() {
  10902. ForEach(dataBu.data, (item: string, index: number) => {
  10903. ListItem() {
  10904. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10905. Row() {
  10906. Column() {
  10907. Image($r('app.media.music_group'))
  10908. .height(28)
  10909. .fillColor(dataBu.color)
  10910. .alignSelf(ItemAlign.Center)
  10911. }
  10912. .width(32)
  10913. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  10914. .padding({
  10915. top: 10,
  10916. bottom: 10,
  10917. right: 10,
  10918. left: 10
  10919. })
  10920. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  10921. .fontSize(15)
  10922. }
  10923. }
  10924. .backgroundColor(Color.Transparent)
  10925. .margin({ top: 7, bottom: 7 })
  10926. }
  10927. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10928. .animation({ duration: 500 }),
  10929. TransitionEffect.scale({ x: 0, y: 0 })))
  10930. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10931. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10932. .onClick(() => {
  10933. dataBu.onItemClick?.(index)
  10934. })
  10935. })
  10936. }
  10937. .width(150)
  10938. .divider({
  10939. strokeWidth: 1,
  10940. color: "#22FFFFFF"
  10941. })
  10942. }
  10943. .height(300)
  10944. .padding({
  10945. bottom: 30
  10946. })
  10947. }
  10948. function getFileDirName(filePath: string,rootPath:string): string{
  10949. if(filePath===rootPath){
  10950. return '首页'
  10951. }
  10952. let result = FileUtil.getFileName(filePath)
  10953. if(StrUtil.isEmpty(result))
  10954. return ''
  10955. if(result.startsWith('.'))
  10956. result = result.replace(/\./g, '')
  10957. return result
  10958. }