LocalMusic.ets 430 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625
  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 { PlayerStateListener, PlayerState, PlayerError, PlayerErrorType } from '../common/service/PlayerStateModel';
  41. import {
  42. IjkMediaPlayer,
  43. // DeviceChangeReason,
  44. InterruptEvent,
  45. InterruptHintType,
  46. LogUtils
  47. } from '@ohos/ijkplayer';
  48. import { PlayStatus } from '../common/PlayStatus';
  49. import fs from '@ohos.file.fs';
  50. import { image } from '@kit.ImageKit';
  51. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  52. import { UniversalDetector } from '@ohos/juniversalchardet';
  53. import { SettingPage } from '../pages/SettingPage';
  54. import { secondToTime } from '../common/util/CommUtils';
  55. import { CommonConstants2 } from '../common/util/CommonConstants2';
  56. import { hilog } from '@kit.PerformanceAnalysisKit';
  57. import { LazyDataSource } from '../common/util/LazyDataSource';
  58. import MediaTable from '../common/util/MediaTable';
  59. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  60. import ImageUtils from '../common/util/ImageUtils';
  61. import { ringtone } from '@kit.RingtoneKit';
  62. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  63. import { resourceManager } from '@kit.LocalizationKit';
  64. import { deviceInfo } from '@kit.BasicServicesKit';
  65. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  66. import app from '@system.app';
  67. import { TextNodeController } from './PipLyricTextBuilder';
  68. import { IndexerView } from './IndexerView';
  69. import { KeyCode } from '@kit.InputKit';
  70. import { KnockController } from '../controller/KnockController';
  71. import { UnifiedPlayerService, IPlayerService } from '../common/service/UnifiedPlayerService';
  72. // import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  73. const TAG = 'LocalMusic';
  74. const DEFAULT_INDEX =
  75. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  76. 'X', 'Y', 'Z']
  77. //排序类型
  78. function getTypeOrder(type: number) {
  79. switch (type) {
  80. case CommonConstants.TYPE_IS_DIR:
  81. return 1; // First
  82. case CommonConstants.TYPE_IS_CSJAD:
  83. return 2; // Middle
  84. case CommonConstants.TYPE_LOCAL:
  85. return 3; // Last
  86. default:
  87. return 4; // Unknown types, if any, go last
  88. }
  89. }
  90. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  91. // 定义接口
  92. interface HiCarAspectRatio {
  93. ratio: number;
  94. name: string;
  95. }
  96. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  97. const ITEM_HEIGHT: number = 58; // 列表项中高度
  98. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  99. //功能强大的音乐播放器
  100. @Preview
  101. @Component
  102. export struct LocalMusic {
  103. @State opacityValueImage: number = 1;
  104. @State tipPopup:boolean = false
  105. @Consume mType: number;
  106. @StorageProp('themeColor') themeColor: string =
  107. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  108. themeMode: number = 0;
  109. @State titleName: string = '首页'
  110. @State textStr: string = ''
  111. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  112. // private download_path: string = '';
  113. @Consume rootPath: string //音频根目录
  114. @Consume currentPath: string
  115. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  116. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  117. @State lockPath: string = ''
  118. @State favPath: string = ''
  119. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  120. @State historyPath: string = ''
  121. @State historyList: Array<VideoItem> = []
  122. @Consume isHistory: boolean
  123. static readonly HISTORY_MUSIC: string = 'music_historyList';
  124. private table: MediaTable = new MediaTable(getContext(this))
  125. @State isZero: boolean = false
  126. @State fileList: Array<string> = []
  127. @State dirList: Array<VideoItem> = []
  128. @Consume videoLocalList: Array<VideoItem>
  129. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  130. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  131. @State artistList: Array<VideoItem> = []; //艺术家文件
  132. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  133. @State albumList: Array<VideoItem> = []; //专辑文件
  134. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  135. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  136. @State imageOpacities: number[] = [];
  137. @Consume isCanBack: boolean
  138. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  139. @State showSingleLyric: boolean = false
  140. @State sortType: number = 4 //默认排序方式
  141. @State isShowSimi: boolean = false //是否显示私密音频
  142. @State isShowFAV: boolean = true //是否显示我的收藏
  143. @State isShowTitleBar: boolean = true //是否显示分类导航条
  144. @State isShowAllBar: boolean = true //是否显示播放全部条
  145. @State isShowHistory: boolean = true //是否显示最近播放
  146. @State isCustomizeBg: boolean = false //自定义背景界面
  147. @State isGridMusic: boolean = false //是否网格布局
  148. @State isCircleBtn: boolean = false //是否圆形播放按钮
  149. @State twoFingerType: number = 3 //双支放大缩小的类型
  150. @State isScrollHide: boolean = false //是否滚动隐藏
  151. private widgetEventSubscriber: commonEventManager.CommonEventSubscriber | null = null; // 卡片事件订阅者
  152. private lastProgressBroadcastTime: number = 0; // 上次进度广播时间
  153. private readonly PROGRESS_BROADCAST_INTERVAL: number = 1000; // 进度广播间隔(1秒)
  154. private lastStateBroadcastTime: number = 0; // 上次状态广播时间
  155. private readonly STATE_BROADCAST_INTERVAL: number = 500; // 状态广播间隔(0.5秒)
  156. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  157. @State isStartAutoPlay: boolean = false //启动后自动播放
  158. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  159. @State isShowHeader: boolean = true
  160. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  161. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  162. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  163. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  164. @State isSwipe: boolean = false //listItem的左滑开关
  165. @State openSkipSongAnimate: boolean = true//切歌动画效果
  166. @State customizeBgPath: string | undefined = '';
  167. @State isDarkMode: boolean = false
  168. @State lyricTextWeight: number = 400
  169. @State lyricTextWeightPip: number = 400
  170. @State currentSwiperIndex: number = 0
  171. @State blurValue: number = 0 //背景模糊
  172. @State bgBrightness: number = 0 //背景亮度
  173. private listScroller: ListScroller = new ListScroller()
  174. private playListScroller: Scroller = new Scroller()
  175. @StorageProp('isLandscape') isLandscape: boolean = false;
  176. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  177. @StorageProp('windowWidth') windowWidth: number = 0;
  178. @StorageProp('windowHeight') windowHeight: number = 0;
  179. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  180. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  181. private UNKONWN:string = '';
  182. private listArea: Area = {
  183. width: 0,
  184. height: 0,
  185. position: {},
  186. globalPosition: {}
  187. }
  188. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  189. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  190. onColorModeChange() {
  191. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  192. if (this.isCustomizeBg) {
  193. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  194. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  195. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  196. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  197. } else {
  198. if (!this.isDarkMode) {
  199. this.titleBarModel.setTitleBarBackground(this.themeColor)
  200. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  201. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  202. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  203. } else {
  204. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  205. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  206. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  207. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  208. }
  209. }
  210. }
  211. onModeChange() {
  212. this.isFavMusic = false
  213. if (this.modeType === 2 || this.modeType === 3) {
  214. this.titleBarModel.setRightIcon(null)
  215. } else {
  216. this.titleBarModel.setRightIcon(($r('app.media.add')))
  217. }
  218. LogUtil.info('onecold onModeChange = ' + this.modeType)
  219. switch (this.modeType) {
  220. case 0:
  221. this.getSortedFiles(this.currentPath)
  222. break
  223. case 1:
  224. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  225. this.updateListData(this.mediaKuList)
  226. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  227. break
  228. case 2:
  229. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  230. this.updateListData(this.artistList)
  231. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  232. break
  233. case 3:
  234. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  235. this.updateListData(this.albumList)
  236. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  237. break
  238. }
  239. }
  240. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  241. // @StorageLink('isPlay') isPlay: boolean = false;
  242. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  243. @StorageLink('songList') songList: Array<VideoItem> = [];
  244. @State translateY: number = 0;
  245. @State isShowSheet: boolean = false;
  246. @State isShowSheetView: boolean = false;
  247. @State isShowTimeCloseView: boolean = false;
  248. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  249. @StorageLink('currIndex') curIndex: number = 0;
  250. @Consume isShowDrawer: boolean;
  251. @Consume offsetX: number;
  252. @State isFac: boolean = false;
  253. @State favList: Array<VideoItem> = []
  254. @Consume isFavMusic: boolean
  255. @State isClickedPLayAll: boolean = false;
  256. private knockController: KnockController | undefined = undefined;
  257. imagesF: ImageFrameInfo[] = [
  258. { src: $r("app.media.app_loading0") },
  259. { src: $r("app.media.app_loading1") },
  260. { src: $r("app.media.app_loading2") },
  261. { src: $r("app.media.app_loading3") },
  262. ]
  263. @State animationState: AnimationStatus = AnimationStatus.Initial
  264. // 缓存机制
  265. private cache: Map<string, Array<VideoItem>> = new Map();
  266. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  267. // 持久化缓存
  268. private async saveCacheToStorage() {
  269. const cacheArray = Array.from(this.cache.entries());
  270. const stringCacheArray = Array.from(this.stringCache.entries());
  271. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  272. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  273. }
  274. // 载入缓存
  275. private async loadCacheFromStorage() {
  276. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  277. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  278. if (cacheString) {
  279. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  280. this.cache = new Map(cacheArray);
  281. }
  282. if (stringCacheString) {
  283. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  284. this.stringCache = new Map(stringCacheArray);
  285. }
  286. }
  287. // 查找缓存
  288. private findCache(key: string): Array<VideoItem> | undefined {
  289. return this.cache.get(key);
  290. }
  291. // 查找字符串缓存
  292. private findStringCache(key: string): string | undefined {
  293. return this.stringCache.get(key);
  294. }
  295. // 添加缓存
  296. private addCache(key: string, value: Array<VideoItem>) {
  297. this.cache.set(key, value);
  298. }
  299. // 添加字符串缓存
  300. private addStringCache(key: string, value: string) {
  301. this.stringCache.set(key, value);
  302. }
  303. // 删除缓存
  304. private deleteCache(key: string) {
  305. this.cache.delete(key);
  306. this.saveCacheToStorage()
  307. }
  308. // 多选机制
  309. @State selectedFiles: Array<VideoItem> = [];
  310. @State isMultiSelect: boolean = false;
  311. @State isAllSelected: boolean = false;
  312. @State appName: string = ''
  313. @State isHasDir: boolean = false
  314. @State packName: string = ''
  315. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  316. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  317. .setTitleTextStyle(FontStyle.Normal)
  318. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  319. .setLeftIcon($r('app.media.menu'))
  320. .setLeftIconWidth(26)
  321. .setLeftIconHeight(26)
  322. .setTitleName('首页')
  323. .setTitleFontSize(18)
  324. .setTitleFontColor(Color.White)
  325. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  326. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  327. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  328. .setRightIcon($r('app.media.add'))
  329. .setOnRightClickListener(() => {
  330. this.showSheelDialog()
  331. })
  332. // .setOnTitleClickListener(() => {
  333. // this.showPupDialog()
  334. // })
  335. .setOnLeftClickListener(() => {
  336. this.doSwipBack()
  337. })
  338. doSwipBack() {
  339. if (this.modeType !== 0 && this.isCanBack) {
  340. this.onModeChange()
  341. this.isCanBack = false
  342. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  343. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  344. setTimeout(() => {
  345. if (this.modeType == 2) {
  346. if (this.isGridMusic) {
  347. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  348. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  349. } else {
  350. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  351. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  352. }
  353. } else if (this.modeType == 3) {
  354. if (this.isGridMusic) {
  355. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  356. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  357. } else {
  358. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  359. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  360. }
  361. }
  362. }, 200)
  363. return
  364. }
  365. if (this.isHistory || this.isFavMusic) {
  366. this.isHistory = false
  367. this.getSortedFiles(this.currentPath)
  368. return
  369. }
  370. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  371. animateTo({ duration: 555 }, () => {
  372. // 动画闭包内控制Image组件的出现和消失
  373. this.isShowDrawer = !this.isShowDrawer
  374. this.offsetX = 0
  375. })
  376. return
  377. }
  378. //返回上一级歌单的滚动位置
  379. setTimeout(() => {
  380. if (this.modeType == 0) {
  381. if (this.isGridMusic) {
  382. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  383. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  384. } else {
  385. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  386. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  387. }
  388. }
  389. }, 300)
  390. this.currentPath = Utility.getParentDirectory(this.currentPath)
  391. Logger.info('this.currentPath2 = ' + this.currentPath)
  392. this.getSortedFiles(this.currentPath)
  393. }
  394. // 初始化统一播放器服务
  395. private async initUnifiedPlayerService(): Promise<void> {
  396. try {
  397. await this.unifiedPlayerService.initialize(this.context);
  398. // 等待数据恢复完成后再获取播放列表
  399. LogUtils.getInstance().LOGI('LocalMusic: Waiting for UnifiedPlayerService data restoration...');
  400. await this.unifiedPlayerService.waitForDataRestoration(5000);
  401. // 从UnifiedPlayerService恢复播放列表和状态
  402. const restoredPlaylist = this.unifiedPlayerService.getPlaylist();
  403. const restoredIndex = this.unifiedPlayerService.getCurrentIndex();
  404. const restoredSong = this.unifiedPlayerService.getCurrentSong();
  405. if (ArrayUtil.isNotEmpty(restoredPlaylist)) {
  406. // 恢复播放列表到LocalMusic
  407. this.songList = restoredPlaylist;
  408. this.curIndex = restoredIndex;
  409. this.currentSong = restoredSong || undefined;
  410. // 更新UI数据源
  411. this.sonDataSource.pushArrayData(this.songList);
  412. // 如果有当前歌曲,更新UI显示
  413. if (this.currentSong) {
  414. this.videoUrl = this.currentSong.filePath;
  415. this.name = this.currentSong.name;
  416. this.artist = this.currentSong.artist;
  417. this.cover = this.currentSong.pixelMapPath;
  418. }
  419. LogUtils.getInstance().LOGI(`LocalMusic: Restored playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
  420. } else {
  421. LogUtils.getInstance().LOGI('LocalMusic: No playlist restored from UnifiedPlayerService, songList length = ' + this.songList.length);
  422. if (ArrayUtil.isNotEmpty(this.songList)) {
  423. // 如果LocalMusic有播放列表但UnifiedPlayerService没有,设置到服务中
  424. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  425. LogUtils.getInstance().LOGI(`LocalMusic: Set existing playlist to UnifiedPlayerService - ${this.songList.length} songs`);
  426. }
  427. }
  428. // 不设置LocalMusic自己的AVSession监听器,完全依赖UnifiedPlayerService
  429. // UnifiedPlayerService已经设置了AVSession监听器,状态变化会通过StateListener传播到LocalMusic
  430. LogUtils.getInstance().LOGI('LocalMusic: Relying on UnifiedPlayerService for AVSession handling');
  431. // 初始化完成后,立即同步当前状态到UI
  432. setTimeout(() => {
  433. try {
  434. const currentState = this.unifiedPlayerService.getCurrentState();
  435. const actuallyPlaying = this.unifiedPlayerService.getActualPlayingState();
  436. LogUtils.getInstance().LOGI(`LocalMusic: Syncing current state - StateModel: ${currentState.isPlaying}, ActualPlayer: ${actuallyPlaying}`);
  437. } catch (error) {
  438. LogUtils.getInstance().LOGI(`LocalMusic: Failed to sync current state: ${error}`);
  439. }
  440. }, 200); // 短延迟,确保组件完全初始化
  441. LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService initialized successfully');
  442. // 注册状态监听器,接收来自UnifiedPlayerService的状态变化通知
  443. const stateListener = new LocalMusicStateListener(this);
  444. this.unifiedPlayerService.addStateListener(stateListener);
  445. LogUtils.getInstance().LOGI('LocalMusic: State listener registered with UnifiedPlayerService');
  446. // 初始化完成后,开始加载本地文件
  447. this.loadLocalFilesAfterServiceInit();
  448. } catch (error) {
  449. LogUtils.getInstance().LOGI(`LocalMusic: Failed to initialize UnifiedPlayerService: ${error}`);
  450. ToastUtil.showToast('播放器服务初始化失败');
  451. // 即使服务初始化失败,也要加载本地文件
  452. this.loadLocalFilesAfterServiceInit();
  453. }
  454. }
  455. private loadLocalFilesAfterServiceInit() {
  456. // 加载本地文件,然后恢复播放列表
  457. this.getSortedFiles(this.rootPath).then(async () => {
  458. this.isFavMusic = false;
  459. // 数据恢复已在initUnifiedPlayerService中完成,直接获取播放列表
  460. LogUtils.getInstance().LOGI('LocalMusic: Getting playlist from UnifiedPlayerService after file loading');
  461. // 尝试从UnifiedPlayerService恢复播放列表
  462. const unifiedPlaylist = this.unifiedPlayerService.getPlaylist();
  463. const unifiedIndex = this.unifiedPlayerService.getCurrentIndex();
  464. const unifiedSong = this.unifiedPlayerService.getCurrentSong();
  465. if (ArrayUtil.isNotEmpty(unifiedPlaylist)) {
  466. // 使用UnifiedPlayerService的数据
  467. this.songList = unifiedPlaylist;
  468. this.curIndex = unifiedIndex;
  469. this.currentSong = unifiedSong || undefined;
  470. LogUtils.getInstance().LOGI(`LocalMusic: Using playlist from UnifiedPlayerService - ${this.songList.length} songs, index ${this.curIndex}, current song: ${this.currentSong?.name || 'null'}`);
  471. } else {
  472. // 回退到旧的存储方式
  473. LogUtils.getInstance().LOGI('LocalMusic: UnifiedPlayerService playlist empty, falling back to legacy storage');
  474. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  475. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  476. if (ArrayUtil.isEmpty(this.songList)) {
  477. const currentFileList = this.getCurFileList();
  478. LogUtils.getInstance().LOGI(`LocalMusic: No legacy playlist found, current directory has ${currentFileList.length} songs`);
  479. LogUtils.getInstance().LOGI(`LocalMusic: Current path: ${this.currentPath}, Root path: ${this.rootPath}`);
  480. this.songList = currentFileList;
  481. LogUtils.getInstance().LOGI(`LocalMusic: Using current file list as fallback - ${this.songList.length} songs`);
  482. } else {
  483. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  484. LogUtils.getInstance().LOGI(`LocalMusic: Using legacy playlist storage - ${this.songList.length} songs, index ${this.curIndex}`);
  485. }
  486. }
  487. if (ArrayUtil.isNotEmpty(this.songList)) {
  488. this.isFirstStartPlay = true
  489. this.sonDataSource.pushArrayData(this.songList)
  490. if (this.currentSong === undefined) {
  491. this.isFirstStartPlay = false
  492. this.currentSong = this.songList[0]
  493. }
  494. this.videoUrl = this.currentSong.filePath
  495. this.name = this.currentSong.name
  496. this.cover = this.currentSong.pixelMapPath
  497. this.artist = this.currentSong.artist
  498. }
  499. });
  500. }
  501. // ==================== PlayerStateListener 实现方法 ====================
  502. /**
  503. * 播放器状态变化监听器
  504. * 当UnifiedPlayerService的状态发生变化时被调用
  505. */
  506. public onPlayerStateChanged(state: PlayerState): void {
  507. try {
  508. LogUtils.getInstance().LOGI(`LocalMusic: Received state change from UnifiedPlayerService - isPlaying: ${state.isPlaying}, isPaused: ${state.isPaused}, currentIndex: ${state.currentIndex}`);
  509. // 同步播放状态到UI
  510. if (state.isPlaying !== undefined) {
  511. // 根据播放状态更新UI播放按钮状态
  512. if (state.isPlaying) {
  513. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  514. } else if (state.isPaused) {
  515. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  516. } else {
  517. this.CONTROL_PlayStatus = PlayStatus.INIT;
  518. }
  519. }
  520. // 同步进度信息
  521. if (state.currentPosition !== undefined && state.duration !== undefined) {
  522. this.setProgress();
  523. }
  524. // 同步播放列表状态
  525. if (state.currentIndex !== undefined && state.currentIndex !== this.curIndex) {
  526. this.curIndex = state.currentIndex;
  527. }
  528. // 同步收藏状态(每次状态变化时都检查,确保UI收藏状态是最新的)
  529. this.syncFavoriteStateFromService();
  530. LogUtils.getInstance().LOGI('LocalMusic: UI state synchronized with UnifiedPlayerService');
  531. } catch (error) {
  532. LogUtils.getInstance().LOGI(`LocalMusic: Error handling state change: ${error}`);
  533. }
  534. }
  535. /**
  536. * 歌曲变化监听器
  537. * 当UnifiedPlayerService的当前歌曲发生变化时被调用
  538. */
  539. public onPlayerSongChanged(song: VideoItem): void {
  540. try {
  541. LogUtils.getInstance().LOGI(`LocalMusic: Received song change from UnifiedPlayerService - ${song.name}`);
  542. // 同步当前歌曲信息到UI
  543. this.currentSong = song;
  544. this.videoUrl = song.filePath;
  545. this.name = song.name;
  546. this.artist = song.artist || this.UNKONWN;
  547. this.cover = song.pixelMapPath;
  548. // 同步收藏状态到UI
  549. this.syncFavoriteStateFromService();
  550. // 重置时间显示状态
  551. this.oldSeconds = 0;
  552. this.currentTime = "00:00";
  553. this.totalTime = "00:00";
  554. this.lastSongPath = song.filePath;
  555. this.justSwitched = true;
  556. // 触发封面动画
  557. this.changeImageAnimation();
  558. LogUtils.getInstance().LOGI('LocalMusic: UI song info synchronized with UnifiedPlayerService');
  559. } catch (error) {
  560. LogUtils.getInstance().LOGI(`LocalMusic: Error handling song change: ${error}`);
  561. }
  562. }
  563. /**
  564. * 播放器错误监听器
  565. * 当UnifiedPlayerService发生错误时被调用
  566. */
  567. public onPlayerError(error: PlayerError): void {
  568. try {
  569. LogUtils.getInstance().LOGI(`LocalMusic: Received error from UnifiedPlayerService - ${error.type}: ${error.message}`);
  570. // 根据错误类型显示不同的提示
  571. switch (error.type) {
  572. case PlayerErrorType.FILE_NOT_FOUND:
  573. ToastUtil.showToast('文件未找到,已跳过');
  574. break;
  575. case PlayerErrorType.NETWORK_ERROR:
  576. ToastUtil.showToast('网络错误,请检查网络连接');
  577. break;
  578. case PlayerErrorType.PLAYBACK_ERROR:
  579. ToastUtil.showToast('播放出错,正在重试');
  580. break;
  581. default:
  582. ToastUtil.showToast(`播放器错误: ${error.message}`);
  583. break;
  584. }
  585. LogUtils.getInstance().LOGI('LocalMusic: Error handled and user notified');
  586. } catch (error) {
  587. LogUtils.getInstance().LOGI(`LocalMusic: Error handling player error: ${error}`);
  588. }
  589. }
  590. /**
  591. * 从UnifiedPlayerService同步收藏状态到LocalMusic UI
  592. */
  593. private async syncFavoriteStateFromService(): Promise<void> {
  594. try {
  595. if (this.currentSong && this.unifiedPlayerService) {
  596. // 获取UnifiedPlayerService中的收藏状态
  597. const favList = this.unifiedPlayerService.getFav();
  598. const isFavorite = Utility.getIsFav(favList, this.currentSong);
  599. // 更新LocalMusic的收藏状态UI
  600. // 先更新收藏列表和其他UI
  601. this.deleteCache(this.currentPath)
  602. this.getFavList(false)
  603. if (this.modeType === 0 && !this.isFavMusic) {
  604. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  605. this.getSortedFiles(this.currentPath)
  606. }
  607. workerInstance.postMessage({ code: 2, data: this.context });
  608. workerInstance.postMessage({ code: 3, data: this.context });
  609. workerInstance.postMessage({ code: 4, data: this.context });
  610. // 刷新UnifiedPlayerService的收藏状态,这会自动更新AVSession
  611. // await this.unifiedPlayerService.refreshFavoriteStatus();
  612. LogUtils.getInstance().LOGI(`LocalMusic: 收藏状态已同步 - ${this.currentSong.name}: ${isFavorite ? '已收藏' : '未收藏'}`);
  613. }
  614. } catch (error) {
  615. LogUtils.getInstance().LOGI(`LocalMusic: 同步收藏状态失败: ${error}`);
  616. }
  617. }
  618. // ==================== 组件生命周期 ====================
  619. // 组件生命周期
  620. aboutToAppear() {
  621. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  622. this.tipPopup = !this.tipPopup
  623. PreferencesUtil.putSync('isFirstTiped',false)
  624. }
  625. this.initSetting()
  626. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  627. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  628. Utility.getAppName(getContext(this)).then((appName: string) => {
  629. this.appName = appName
  630. })
  631. this.packName = AppUtil.getBundleName()
  632. this.loadCacheFromStorage(); // 加载缓存
  633. // 初始化统一播放器服务,然后加载文件
  634. this.initUnifiedPlayerService().then(() => {
  635. this.mkDownLoadDir();
  636. });
  637. // 注意:getSortedFiles的调用已经移到initUnifiedPlayerService完成后
  638. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  639. // 监听广播事件(打开其他应用处理)
  640. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  641. this.saveVideoDatas([eventData.data?.message], true)
  642. });
  643. this.setAvSessionListener();
  644. //侧滑广播接收时间
  645. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  646. // 监听广播事件(打开其他应用处理)
  647. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  648. animateTo({ duration: 555 }, () => {
  649. this.doSwipBack()
  650. })
  651. });
  652. //ScanFilePage广播接收时间
  653. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  654. // 监听ScanFilePage广播事件(更新数据库)
  655. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  656. this.doUpdateData()
  657. });
  658. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  659. // 监听广播事件(通用设置配置更新)
  660. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  661. this.doChangeSetting()
  662. });
  663. let event: Callback<InterruptEvent> = (event) => {
  664. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  665. this.savePlaybackPosition()
  666. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  667. this.pause();
  668. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  669. this.startPlayOrResumePlay();
  670. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  671. // 对于STOP事件,使用pause而不是stop,保持播放状态以便恢复
  672. LogUtils.getInstance().LOGI('onecold 音频冲突STOP事件,使用pause保持播放状态');
  673. this.pause();
  674. }
  675. }
  676. // 直接在LocalMusic中处理音频中断,响应更快
  677. this.unifiedPlayerService.getIjkPlayer()?.on('audioInterrupt', event);
  678. // 音频设备断连回调处理
  679. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  680. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  681. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  682. // this.pause();
  683. // }
  684. // }
  685. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  686. this.makeWorker()
  687. //折叠屏的屏幕显示模式变化
  688. display.on('foldDisplayModeChange', (data) => {
  689. this.doChangeBarHeight()
  690. });
  691. display.on('foldStatusChange', (data) => {
  692. Logger.info('onecold foldStatusChange ')
  693. });
  694. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  695. // 读取 themeMode 并同步 currentColorMode
  696. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  697. this.applyThemeMode(this.themeMode)
  698. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  699. AppStorage.setOrCreate('themeColor', themeColor);
  700. this.themeColor = themeColor;
  701. this.doChangeSetting()
  702. // 安全地注册窗口大小变化监听器
  703. if (this.windowClass) {
  704. this.windowClass.on('windowSizeChange', (size) => {
  705. LogUtil.info('onecold windowSizeChange')
  706. this.doChangeBarHeight()
  707. let viewWidth = px2vp(size.width);
  708. let viewHeight = px2vp(size.height);
  709. if(this.isPhoneLan()){
  710. this.is_auto_hide_progress = false
  711. if(this.isHiCar()){
  712. return
  713. }
  714. setTimeout(() => {
  715. this.is_auto_hide_progress = true
  716. }, 6000)
  717. }else{
  718. this.startAutoHide()
  719. }
  720. });
  721. }
  722. this.eventHub.on('onStateChange', (fg: boolean) => {
  723. if (fg && this.curState === 'STARTED') {
  724. this.stopPip();
  725. }
  726. });
  727. }
  728. startAutoHide() {
  729. if(this.isHiCar()){
  730. return
  731. }
  732. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  733. console.info('onecold startAutoHide')
  734. this.is_auto_hide_progress = false
  735. setTimeout(() => {
  736. this.is_auto_hide_progress = true
  737. }, 6000)
  738. }
  739. }
  740. applyThemeMode(mode: number) {
  741. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  742. if (mode === 1) {
  743. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  744. } else if (mode === 2) {
  745. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  746. }
  747. AppStorage.setOrCreate('currentColorMode', colorMode)
  748. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  749. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  750. AppStorage.setOrCreate('themeMode', mode)
  751. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  752. // 只有强制浅色/深色时才主动设置
  753. const context = getContext(this) as common.UIAbilityContext
  754. context.getApplicationContext().setColorMode(colorMode)
  755. }
  756. initSetting() {
  757. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  758. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  759. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  760. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  761. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  762. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  763. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  764. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  765. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  766. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  767. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  768. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  769. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  770. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  771. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  772. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  773. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  774. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  775. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  776. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  777. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  778. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  779. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  780. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  781. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  782. //如果是hicar连接状态,这些都是false
  783. if(this.isHiCar()){
  784. this.isShowTitleBar = false//不显示导航栏
  785. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  786. {
  787. this.isShowHeader = false//二级菜单不显示头部
  788. this.isGridMusic= false//用list不用网格
  789. this.isCoverTopBig = false
  790. }
  791. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  792. }
  793. if (this.isSavePlayMode) {
  794. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  795. }
  796. if (this.isCustomizeBg) {
  797. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  798. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  799. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  800. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  801. } else {
  802. if (!this.isDarkMode) {
  803. this.titleBarModel.setTitleBarBackground(this.themeColor)
  804. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  805. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  806. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  807. } else {
  808. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  809. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  810. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  811. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  812. }
  813. }
  814. }
  815. doChangeSetting() {
  816. this.initSetting()
  817. this.deleteCache(this.currentPath)
  818. if (this.modeType === 0) {
  819. this.getSortedFiles(this.currentPath)
  820. }
  821. }
  822. doChangeBarHeight() {
  823. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  824. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  825. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  826. this.setBarHeightNormal()
  827. }
  828. }
  829. onPageShow() {
  830. this.knockController?.immersiveListening();
  831. app.setImageCacheCount(100);
  832. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  833. app.setImageRawDataCacheSize(104857600);
  834. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  835. // 修复音频中断后的状态同步问题
  836. this.syncPlaybackStateOnShow();
  837. }
  838. /**
  839. * 页面显示时同步播放状态,修复音频中断后的状态不一致问题
  840. */
  841. private syncPlaybackStateOnShow(): void {
  842. try {
  843. const currentState = this.unifiedPlayerService.getCurrentState();
  844. const actualPlaying = this.unifiedPlayerService.getActualPlayingState();
  845. LogUtils.getInstance().LOGI(`onPageShow state sync - StateModel: isPlaying=${currentState.isPlaying}, isPaused=${currentState.isPaused}, Actual: ${actualPlaying}`);
  846. // 如果状态不一致,强制同步
  847. if (currentState.isPlaying !== actualPlaying) {
  848. LogUtils.getInstance().LOGI(`State inconsistency detected, forcing sync`);
  849. this.setIsPlaying(actualPlaying);
  850. this.CONTROL_PlayStatus = actualPlaying ? PlayStatus.PLAY : PlayStatus.INIT;
  851. this.playChange();
  852. this.watchStatus();
  853. }
  854. } catch (error) {
  855. LogUtils.getInstance().LOGI(`syncPlaybackStateOnShow error: ${error}`);
  856. }
  857. }
  858. //开启线程查看各个数据库
  859. makeWorker() {
  860. setTimeout(() => {
  861. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  862. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  863. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  864. // workerInstance.postMessage({
  865. // code: 1,
  866. // data1: this.context,
  867. // data2: this.rootPath,
  868. // data3: this.lockPath,
  869. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  870. // });
  871. PreferencesUtil.putSync('isFirstApp', false)
  872. } else {
  873. workerInstance.postMessage({ code: 2, data: this.context });
  874. workerInstance.postMessage({ code: 3, data: this.context });
  875. workerInstance.postMessage({ code: 4, data: this.context });
  876. this.getHistoryList(false)
  877. }
  878. }, 1000)
  879. workerInstance.onmessage = (e: MessageEvents): void => {
  880. switch (e.data.code) {
  881. case 101: //第一次扫描文件夹入库
  882. ToastUtil.showToast('刷新同步数据库成功!')
  883. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  884. this.doUpdateData()
  885. break;
  886. case 102: //查询媒体库列表
  887. this.mediaKuList = e.data.data
  888. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  889. Utility.doSortListAscending(this.mediaKuList)
  890. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  891. if (this.modeType === 1) {
  892. this.updateListData(this.mediaKuList)
  893. }
  894. break;
  895. case 103: //收到查询艺术家列表
  896. this.artistMap = e.data.data1;
  897. this.artistList = e.data.data2;
  898. break;
  899. case 104: //收到查询专辑列表
  900. this.albumMap = e.data.data1;
  901. this.albumList = e.data.data2
  902. //查询完毕在启动是否自动播放
  903. if (this.isStartAutoPlay) {
  904. this.startPlayOrResumePlay()
  905. }
  906. break;
  907. }
  908. };
  909. // 在调用terminate后,执行onexit
  910. workerInstance.onexit = (code) => {
  911. console.log("main thread terminate");
  912. }
  913. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  914. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  915. workerInstance.onerror = (err: ErrorEvent) => {
  916. console.log("onerror" + err.message);
  917. }
  918. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  919. //碰一碰分享的监听
  920. this.knockController = KnockController.getInstance(this.context);
  921. this.knockController?.immersiveListening();
  922. }
  923. onPageHide(): void {
  924. this.knockController?.immersiveDisableListening();
  925. }
  926. @State isFirstStartPlay: boolean = false
  927. //获取download_path
  928. async mkDownLoadDir() {
  929. const documentViewPicker = new picker.DocumentViewPicker()
  930. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  931. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  932. // this.rootPath = this.download_path
  933. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  934. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  935. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  936. Logger.info('onecold rootPath = ' + this.rootPath)
  937. Logger.info('onecold lockPath = ' + this.lockPath)
  938. if (!FileUtil.accessSync(this.lockPath)) {
  939. FileUtil.mkdirSync(this.lockPath)
  940. }
  941. if (!FileUtil.accessSync(this.favPath)) {
  942. FileUtil.mkdirSync(this.favPath)
  943. }
  944. if (!FileUtil.accessSync(this.historyPath)) {
  945. FileUtil.mkdirSync(this.historyPath)
  946. }
  947. this.getSortedFiles(this.rootPath).then(() => {
  948. this.isFavMusic = false
  949. //穿山甲
  950. // this.loadBannerAd(CSJUtil.getBannerID())
  951. LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - Files loaded, skipping playlist restoration (already done in initUnifiedPlayerService)');
  952. // 播放列表恢复逻辑已经在 initUnifiedPlayerService 中完成,这里不需要重复
  953. // 只需要确保UI状态是最新的
  954. if (ArrayUtil.isNotEmpty(this.songList)) {
  955. this.isFirstStartPlay = true
  956. this.sonDataSource.pushArrayData(this.songList)
  957. // 不要强制设置为第一首歌曲,保持从UnifiedPlayerService恢复的状态
  958. // 只有在完全没有当前歌曲且没有有效索引时才设置默认值
  959. if (this.currentSong === undefined && this.curIndex < 0 && this.songList.length > 0) {
  960. this.isFirstStartPlay = false
  961. this.curIndex = 0
  962. this.currentSong = this.songList[0]
  963. LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - No current song found, setting to first song as fallback');
  964. } else if (this.currentSong === undefined && this.curIndex >= 0 && this.curIndex < this.songList.length) {
  965. // 如果有有效索引但没有当前歌曲,从索引恢复
  966. this.currentSong = this.songList[this.curIndex]
  967. LogUtils.getInstance().LOGI(`LocalMusic: mkDownLoadDir - Restored current song from index ${this.curIndex}: ${this.currentSong.name}`);
  968. }
  969. if (this.currentSong) {
  970. this.videoUrl = this.currentSong.filePath
  971. this.name = this.currentSong.name
  972. this.cover = this.currentSong.pixelMapPath
  973. AppStorage.setOrCreate('currentSong',this.currentSong);
  974. }
  975. LogUtils.getInstance().LOGI(`LocalMusic: mkDownLoadDir - UI updated with existing playlist: ${this.songList.length} songs, current index: ${this.curIndex}, current song: ${this.currentSong?.name || 'none'}`);
  976. } else {
  977. this.name = '空空如也'
  978. LogUtils.getInstance().LOGI('LocalMusic: mkDownLoadDir - No playlist available, showing empty state');
  979. }
  980. })
  981. this.getFavList(false)
  982. }
  983. getFavList(isFavRefresh: boolean) {
  984. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  985. this.favList = result
  986. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  987. this.videoLocalList = this.favList
  988. this.updateListData(this.videoLocalList)
  989. }
  990. })
  991. }
  992. getHistoryList(isRefresh: boolean) {
  993. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  994. this.historyList = result
  995. // for (let i = 0; i < this.historyList.length; i++) {
  996. //
  997. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  998. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  999. // }
  1000. if (isRefresh) {
  1001. this.videoLocalList = this.historyList
  1002. this.updateListData(this.videoLocalList, true)
  1003. }
  1004. })
  1005. }
  1006. // 组件消失生命周期
  1007. aboutToDisappear() {
  1008. console.info('LifeCycleComponent aboutToDisappear');
  1009. this.knockController?.immersiveDisableListening();
  1010. // 移除 this.curIndex = 0,避免重置当前播放索引
  1011. // 保持当前播放状态,让UnifiedPlayerService管理播放状态的持久化
  1012. emitter.off(2);
  1013. emitter.off(101);
  1014. emitter.off(888);
  1015. emitter.off(333);
  1016. this.mDestroyPage = true;
  1017. // UnifiedPlayerService会自动管理屏幕常亮状态
  1018. // this.mIjkMediaPlayer.setScreenOnWhilePlaying(false); // 已移除,使用UnifiedPlayerService
  1019. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1020. this.stop();
  1021. }
  1022. // 移除音频中断监听器
  1023. this.unifiedPlayerService.getIjkPlayer()?.off('audioInterrupt');
  1024. if (workerInstance) {
  1025. workerInstance.terminate();
  1026. }
  1027. this.stopPip();
  1028. this.destroyPipController();
  1029. this.syncPlaybackStateOnShow();
  1030. // 清理卡片事件监听器
  1031. if (this.widgetEventSubscriber) {
  1032. try {
  1033. commonEventManager.unsubscribe(this.widgetEventSubscriber, (err: BusinessError | undefined) => {
  1034. if (err) {
  1035. LogUtils.getInstance().error(`Failed to unsubscribe widget events: ${JSON.stringify(err)}`);
  1036. } else {
  1037. LogUtils.getInstance().LOGI('Widget event listener unsubscribed successfully');
  1038. }
  1039. });
  1040. } catch (error) {
  1041. LogUtils.getInstance().error(`Error during widget event cleanup: ${error}`);
  1042. }
  1043. }
  1044. this.avSessionController.unregisterSessionListener();
  1045. }
  1046. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  1047. this.isFavMusic = false
  1048. if (isWorkerPost) {
  1049. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  1050. }
  1051. if (this.modeType !== 0) {
  1052. return
  1053. }
  1054. this.isCanBack = false
  1055. this.currentPath = curPath
  1056. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  1057. if (curPath === this.rootPath) {
  1058. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1059. } else {
  1060. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1061. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1062. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  1063. }
  1064. }
  1065. // Get the current file list and calculate its hash
  1066. this.fileList = FileUtil.listFileSync(curPath);
  1067. const currentHash = simpleHash(this.fileList);
  1068. // Check cache
  1069. const cachedValue = this.findCache(curPath);
  1070. Logger.info('onecold cachedValue = ' + cachedValue)
  1071. const cachedHash = this.findStringCache(curPath + '_hash');
  1072. const cachedDirList = this.findCache(curPath + "_dirList");
  1073. if (cachedValue !== undefined) {
  1074. // this.videoLocalList = cachedValue;
  1075. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1076. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1077. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1078. }
  1079. this.updateListData(cachedValue)
  1080. }
  1081. if (cachedDirList !== undefined) {
  1082. this.dirList = cachedDirList
  1083. }
  1084. //通过当前hash值和缓存hash判断list有没有变化
  1085. if (cachedValue && cachedHash === currentHash) {
  1086. return;
  1087. }
  1088. this.fileList = FileUtil.listFileSync(curPath)
  1089. let directories: Array<VideoItem> = [];
  1090. let files: Array<VideoItem> = [];
  1091. for (let i = 0; i < this.fileList.length; i++) {
  1092. console.info(`The name of file: ${this.fileList[i]}`);
  1093. let path = curPath + '/' + this.fileList[i]
  1094. if (FileUtil.isDirectory(path)) {
  1095. let item: VideoItem =
  1096. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1097. '')
  1098. if (this.isShowDir(item.name)) {
  1099. directories.push(item);
  1100. }
  1101. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1102. // Utility.doSortListAscending(directories)
  1103. } else {
  1104. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1105. let item: VideoItem =
  1106. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1107. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1108. files.push(item);
  1109. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1110. // this.doSortListAscending(files)
  1111. }
  1112. }
  1113. }
  1114. }
  1115. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1116. if (this.currentPath !== this.lockPath) {
  1117. files = result;
  1118. }
  1119. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1120. Utility.doSortListAscending(files)
  1121. if (this.currentPath === this.rootPath) {
  1122. this.dirList = directories
  1123. this.addCache(curPath + "_dirList", this.dirList);
  1124. }
  1125. //插入广告先注释掉
  1126. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1127. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1128. // directories.push(adItem)
  1129. // }
  1130. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1131. this.videoLocalList = directories.concat(files);
  1132. this.updateListData(this.videoLocalList)
  1133. if (ArrayUtil.isNotEmpty(files)) {
  1134. if (this.currentPath != this.rootPath) {
  1135. if (files) {
  1136. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1137. }
  1138. }
  1139. // 缓存结果
  1140. this.addCache(curPath, this.videoLocalList);
  1141. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1142. this.addStringCache(curPath + '_hash', currentHash);
  1143. }
  1144. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1145. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1146. //
  1147. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1148. //
  1149. // }
  1150. // this.setButtonStatus()
  1151. if (isOpen) {
  1152. if (destPath === undefined) {
  1153. // 处理 destPath 为 undefined 的情况
  1154. return
  1155. }
  1156. if (destPath.endsWith('.lrc')) {
  1157. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1158. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1159. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1160. this.initLyric(lyricPath);
  1161. }
  1162. return
  1163. }
  1164. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  1165. this.doPlay(item2)
  1166. this.isShowPlay = true
  1167. }
  1168. });
  1169. }
  1170. //扫描文件夹入库
  1171. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1172. const files = FileUtil.listFileSync(curPath);
  1173. let mediaItems: VideoItem[] = [];
  1174. Logger.info('onecold scanDirectory start ')
  1175. for (const file of files) {
  1176. const fPath = `${curPath}/${file}`;
  1177. if (fPath === this.lockPath) {
  1178. Logger.info(`Skipping locked path: ${fPath}`);
  1179. continue;
  1180. }
  1181. if (FileUtil.isDirectory(fPath)) {
  1182. // Recursively scan subdirectories
  1183. const subDirItems = await this.scanDirectory(fPath);
  1184. mediaItems = mediaItems.concat(subDirItems);
  1185. } else {
  1186. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1187. // Process media files
  1188. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1189. let mediaItem: VideoItem =
  1190. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  1191. mediaItems.push(mediaItem);
  1192. this.table.insert(mediaItem, (id: number) => {
  1193. });
  1194. }
  1195. }
  1196. }
  1197. return mediaItems;
  1198. }
  1199. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1200. animateTo({ duration: 888 }, () => {
  1201. this.opacityItem = 0;
  1202. });
  1203. setTimeout(() => {
  1204. this.videoLocalList = mList;
  1205. if (!noSort) {
  1206. if (this.modeType === 0 || this.modeType === 1) {
  1207. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1208. this.doSortType(this.sortType)
  1209. }
  1210. }
  1211. this.dataSource.pushArrayData(this.videoLocalList)
  1212. // 如果当前有播放列表,检查是否需要更新播放列表到统一播放器服务
  1213. if (ArrayUtil.isNotEmpty(this.songList)) {
  1214. const globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  1215. // 只有在没有现有播放列表时,才使用当前目录的文件列表
  1216. // 避免在文件列表更新时破坏用户的播放列表
  1217. if (ArrayUtil.isEmpty(this.songList) && ArrayUtil.isNotEmpty(globalVideoList)) {
  1218. this.songList = globalVideoList;
  1219. this.sonDataSource.pushArrayData(this.songList);
  1220. // 同步到统一播放器服务进行持久化
  1221. this.syncPlaylistToService();
  1222. }
  1223. }
  1224. animateTo({ duration: 888 }, () => {
  1225. this.opacityItem = 1;
  1226. });
  1227. this.setButtonStatus()
  1228. }, 200);
  1229. }
  1230. //排序模式和多选模式
  1231. showPupDialog() {
  1232. if (this.modeType === 2 || this.modeType === 3) {
  1233. this.titleBarModel.setRightIcon(null)
  1234. } else {
  1235. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1236. }
  1237. let dataBean = new BubbleBean()
  1238. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1239. dataBean.color = this.themeColor
  1240. dataBean.modeType = this.modeType
  1241. dataBean.imageRes =
  1242. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1243. $r('app.media.refresh')]
  1244. let pup: XPopup;
  1245. if (this.isDarkMode) {
  1246. pup = XPopup.Builder()
  1247. .setPopupPosition(PopupPosition.BOTTOM)
  1248. .atView('pup_positon_music')
  1249. .setBackgroundColor(Color.Black)
  1250. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1251. .show()
  1252. } else {
  1253. pup = XPopup.Builder()
  1254. .setPopupPosition(PopupPosition.BOTTOM)
  1255. .atView('pup_positon_music')
  1256. .setBackgroundColor(Color.White)
  1257. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1258. .show()
  1259. }
  1260. dataBean.onItemClick = (i) => {
  1261. XPopup.dismissTop()
  1262. switch (i) {
  1263. case 0: //首页
  1264. this.modeType = 0
  1265. this.getSortedFiles(this.currentPath)
  1266. break
  1267. case 1:
  1268. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1269. this.modeType = 1
  1270. this.updateListData(this.mediaKuList)
  1271. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1272. break
  1273. case 2:
  1274. this.modeType = 2
  1275. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1276. this.updateListData(this.artistList)
  1277. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1278. break
  1279. case 3:
  1280. this.modeType = 3
  1281. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1282. this.updateListData(this.albumList)
  1283. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1284. break
  1285. case 4: //同步数据
  1286. this.asyncCurrentPathData()
  1287. break
  1288. }
  1289. }
  1290. }
  1291. getCurFileList(): Array<VideoItem> {
  1292. let files: Array<VideoItem> = [];
  1293. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1294. for (let i = 0; i < this.videoLocalList.length; i++) {
  1295. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1296. files.push(this.videoLocalList[i]);
  1297. }
  1298. }
  1299. }
  1300. return files
  1301. }
  1302. /**
  1303. * 刷新播放列表中歌曲的封面信息(从当前文件列表同步最新封面)
  1304. */
  1305. async refreshPlaylistCovers(): Promise<void> {
  1306. if (ArrayUtil.isEmpty(this.songList)) {
  1307. return;
  1308. }
  1309. try {
  1310. // 获取当前目录的最新文件列表(包含最新的封面信息)
  1311. const currentFileList = this.getCurFileList();
  1312. // 如果当前文件列表为空,直接返回
  1313. if (ArrayUtil.isEmpty(currentFileList)) {
  1314. return;
  1315. }
  1316. // 为播放列表中的每首歌曲更新封面信息
  1317. let hasUpdates = false;
  1318. this.songList.forEach((song, index) => {
  1319. // 在当前文件列表中查找对应的歌曲
  1320. const matchedSong = currentFileList.find(file => file.filePath === song.filePath);
  1321. if (matchedSong && StrUtil.isNotEmpty(matchedSong.pixelMapPath) &&
  1322. matchedSong.pixelMapPath !== song.pixelMapPath) {
  1323. // 更新播放列表中的封面信息
  1324. this.songList[index].pixelMapPath = matchedSong.pixelMapPath;
  1325. hasUpdates = true;
  1326. LogUtils.getInstance().LOGI(`LocalMusic: Updated cover for ${song.name}: ${matchedSong.pixelMapPath}`);
  1327. }
  1328. });
  1329. // 如果有更新,刷新UI数据源
  1330. if (hasUpdates) {
  1331. this.sonDataSource.pushArrayData(this.songList);
  1332. LogUtils.getInstance().LOGI(`LocalMusic: Refreshed covers for playlist with ${this.songList.length} songs`);
  1333. }
  1334. } catch (error) {
  1335. LogUtils.getInstance().LOGI(`LocalMusic: Error refreshing playlist covers: ${error.message}`);
  1336. }
  1337. }
  1338. setButtonStatus() {
  1339. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1340. this.isZero = false
  1341. } else {
  1342. this.isZero = true
  1343. }
  1344. if (this.currentPath !== this.rootPath &&
  1345. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1346. this.isHasDir = true //不为空,说明有子文件夹
  1347. } else {
  1348. this.isHasDir = false
  1349. }
  1350. }
  1351. showRankDialog() {
  1352. if (this.modeType === 2 || this.modeType === 3) {
  1353. //动作面板
  1354. DialogHelper.showBottomSheetDialog({
  1355. title: "请选择排序模式",
  1356. maskColor: Color.Transparent,
  1357. // sheets: ["按名称升序", "按名称降序"],
  1358. sheets: [
  1359. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1360. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1361. ],
  1362. backgroundColor: $r('app.color.bg_card'),
  1363. height: '30%',
  1364. transition: AnimationHelper.transitionInDown(555),
  1365. onAction: (index) => {
  1366. switch (index) {
  1367. case 0:
  1368. Utility.doSortListAscending(this.videoLocalList)
  1369. break;
  1370. case 1:
  1371. Utility.doSortListDescending(this.videoLocalList)
  1372. break;
  1373. }
  1374. this.updateListData(this.videoLocalList)
  1375. }
  1376. })
  1377. return
  1378. }
  1379. //动作面板
  1380. DialogHelper.showBottomSheetDialog({
  1381. title: "请选择排序模式",
  1382. maskColor: Color.Transparent,
  1383. height: '75%',
  1384. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1385. sheets: [
  1386. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1387. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1388. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1389. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1390. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1391. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1392. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1393. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1394. ],
  1395. backgroundColor: $r('app.color.bg_card'),
  1396. transition: AnimationHelper.transitionInDown(555),
  1397. onAction: (index) => {
  1398. this.doSortType(index)
  1399. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1400. this.updateListData(this.videoLocalList, true)
  1401. }
  1402. })
  1403. }
  1404. doSortType(index: number) {
  1405. switch (index) {
  1406. case 0:
  1407. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1408. // 类型排序优先级
  1409. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1410. if (typeOrder !== 0) {
  1411. return typeOrder;
  1412. }
  1413. // 处理艺术家可能为undefined的字符串比较
  1414. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1415. const artistB = b.artist?.trim() || '';
  1416. return artistA.localeCompare(artistB);
  1417. });
  1418. break;
  1419. case 1:
  1420. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1421. // 类型排序优先级
  1422. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1423. if (typeOrder !== 0) {
  1424. return typeOrder;
  1425. }
  1426. // 处理艺术家可能为undefined的字符串比较
  1427. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1428. const artistB = b.artist?.trim() || '';
  1429. return artistB.localeCompare(artistA);
  1430. });
  1431. break;
  1432. case 2:
  1433. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1434. // 类型排序优先级
  1435. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1436. if (typeOrder !== 0) {
  1437. return typeOrder;
  1438. }
  1439. // 处理专辑可能为undefined的字符串比较
  1440. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1441. const albumB = b.album?.trim() || '';
  1442. return albumA.localeCompare(albumB);
  1443. });
  1444. break;
  1445. case 3:
  1446. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1447. // 类型排序优先级
  1448. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1449. if (typeOrder !== 0) {
  1450. return typeOrder;
  1451. }
  1452. // 处理专辑可能为undefined的字符串比较
  1453. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1454. const albumB = b.album?.trim() || '';
  1455. return albumB.localeCompare(albumA);
  1456. });
  1457. break;
  1458. case 4:
  1459. Utility.doSortListAscending(this.videoLocalList)
  1460. break;
  1461. case 5:
  1462. Utility.doSortListDescending(this.videoLocalList)
  1463. break;
  1464. case 6:
  1465. this.videoLocalList.sort((a, b) => {
  1466. // First, sort by type
  1467. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1468. if (typeOrder !== 0) {
  1469. return typeOrder;
  1470. }
  1471. // If types are the same, sort by cTime in ascending order
  1472. return a.cTime.localeCompare(b.cTime);
  1473. });
  1474. break;
  1475. case 7:
  1476. this.videoLocalList.sort((a, b) => {
  1477. // First, sort by type
  1478. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1479. if (typeOrder !== 0) {
  1480. return typeOrder;
  1481. }
  1482. // If types are the same, sort by cTime in descending order
  1483. return b.cTime.localeCompare(a.cTime);
  1484. });
  1485. break;
  1486. }
  1487. }
  1488. showSheelDialog() {
  1489. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1490. // this.showTips()
  1491. // return
  1492. // }
  1493. this.showAddDialog()
  1494. }
  1495. showAddDialog() {
  1496. if (this.modeType === 2 || this.modeType === 3) {
  1497. return
  1498. }
  1499. DialogHelper.showActionSheetDialog({
  1500. title: "请选择添加方式(建议歌词文件一起导入)",
  1501. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1502. sheets: [
  1503. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1504. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1505. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1506. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1507. ],
  1508. maskColor: Color.Transparent,
  1509. backgroundColor: $r('app.color.bg_card'),
  1510. transition: AnimationHelper.transitionInDown(555),
  1511. onAction: (index) => {
  1512. switch (index) {
  1513. case 0:
  1514. if (this.modeType === 0) {
  1515. this.showMkDialog()
  1516. } else {
  1517. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1518. }
  1519. break;
  1520. case 1:
  1521. this.callFilePickerSelectFile()
  1522. break;
  1523. case 2:
  1524. this.showTips()
  1525. break;
  1526. case 3:
  1527. this.goSelectMusic()
  1528. break;
  1529. }
  1530. }
  1531. })
  1532. }
  1533. //拉起音频
  1534. goSelectMusic() {
  1535. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1536. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1537. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1538. ) {
  1539. ToastUtil.showToast('暂时不支持该设备')
  1540. return
  1541. }
  1542. try {
  1543. let documentSelectOptions = new picker.DocumentSelectOptions();
  1544. documentSelectOptions.authMode = true
  1545. documentSelectOptions.multiAuthMode = true
  1546. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1547. let documentPicker = new picker.DocumentViewPicker(this.context);
  1548. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1549. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1550. this.saveVideoDatas(documentSelectResult)
  1551. }
  1552. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1553. JSON.stringify(documentSelectResult));
  1554. }).catch((err: BusinessError) => {
  1555. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1556. });
  1557. } catch (error) {
  1558. let err: BusinessError = error as BusinessError;
  1559. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1560. }
  1561. }
  1562. async showTips() {
  1563. DialogHelper.showTipsDialog({
  1564. title: '使用提示:自动导入教程',
  1565. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1566. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1567. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1568. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1569. onAction: (action) => {
  1570. if (action == DialogAction.TWO) {
  1571. PreferencesUtil.putSync('isFirstMusic', false)
  1572. router.pushUrl({
  1573. url: 'pages/ScanFilePage'
  1574. });
  1575. }
  1576. }
  1577. })
  1578. }
  1579. showMkDialog() {
  1580. DialogHelper.showTextInputDialog({
  1581. title: '新建歌单',
  1582. maskColor: Color.Transparent,
  1583. text: '',
  1584. transition: AnimationHelper.transitionInDown(666),
  1585. onChange: (text) => {
  1586. console.error("onChange: " + text);
  1587. },
  1588. onAction: (action, dialogId, content) => {
  1589. // ToastUtil.showToast('content = ' +content)
  1590. if (action == DialogAction.TWO) {
  1591. const newName = content
  1592. const newPath = this.currentPath + '/' + newName
  1593. FileUtil.mkdir(newPath, true).then(() => {
  1594. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1595. this.getSortedFiles(this.currentPath)
  1596. }).catch((error: BusinessError) => {
  1597. console.error(error.message);
  1598. });
  1599. }
  1600. }
  1601. })
  1602. }
  1603. @State progress: number = 0;
  1604. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1605. if (ArrayUtil.isEmpty(uris)) {
  1606. return;
  1607. }
  1608. let newUris: string[] = [];
  1609. this.progress = 0
  1610. DialogHelper.showLoadingProgress({
  1611. progress: this.progress,
  1612. backCancel: false,
  1613. autoCancel: false,
  1614. loadColor: this.themeColor,
  1615. fontColor: this.themeColor
  1616. });
  1617. // 计算所有文件的总大小
  1618. let totalSize = 0;
  1619. for (let uri of uris) {
  1620. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1621. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1622. await fileIo.close(sourceFile.fd);
  1623. }
  1624. let totalRead = 0;
  1625. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1626. Logger.info(TAG, 'destPath uri: ' + destPath);
  1627. for (let i = 0; i < uris.length; i++) {
  1628. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1629. Logger.info(TAG, 'filePath uri: ' + filePath);
  1630. newUris.push(filePath);
  1631. try {
  1632. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1633. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1634. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1635. const buffer = new ArrayBuffer(buffSize);
  1636. let len = await fileIo.read(sourceFile.fd, buffer);
  1637. while (len > 0) {
  1638. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1639. totalRead += len;
  1640. // 计算总进度
  1641. this.progress = Math.floor((totalRead / totalSize) * 100);
  1642. DialogHelper.updateLoading('正在导入', this.progress);
  1643. len = await fileIo.read(sourceFile.fd, buffer);
  1644. }
  1645. await fileIo.close(sourceFile.fd);
  1646. await fileIo.close(destFile.fd);
  1647. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1648. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1649. let mediaItem: VideoItem =
  1650. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1651. this.table.insert(mediaItem, (id: number) => {
  1652. // 删除目标路径缓存
  1653. this.cache.delete(this.currentPath);
  1654. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1655. });
  1656. }
  1657. }
  1658. } catch (error) {
  1659. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1660. }
  1661. }
  1662. DialogHelper.closeLoading()
  1663. this.isZero = false
  1664. // setTimeout(() => {
  1665. // // 删除目标路径缓存
  1666. // this.cache.delete(this.currentPath);
  1667. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1668. // }, 500);
  1669. Logger.info(TAG, 'scan select video result:' + newUris)
  1670. }
  1671. //拉起音频
  1672. // goSelectMusic(){
  1673. //
  1674. // try {
  1675. // let audioSelectOptions = new picker.AudioSelectOptions();
  1676. // let audioPicker = new picker.AudioViewPicker(this.context);
  1677. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1678. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1679. // this.saveVideoDatas(audioSelectResult)
  1680. // }
  1681. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1682. // }).catch((err: BusinessError) => {
  1683. //
  1684. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1685. // });
  1686. // } catch (error) {
  1687. // let err: BusinessError = error as BusinessError;
  1688. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1689. // }
  1690. //
  1691. //
  1692. //
  1693. // }
  1694. goSelectImage(item: VideoItem) {
  1695. if (!item) {
  1696. return
  1697. }
  1698. let selectUris: Array<string> = [];
  1699. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1700. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1701. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1702. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1703. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1704. //用一个全局变量存储返回的uri
  1705. selectUris = photoSelectResult.photoUris;
  1706. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1707. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1708. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1709. console.info('file fd: ' + file.fd);
  1710. let name = await MD5.digestSync(this.videoUrl)
  1711. let imagePath = this.context.filesDir + FileUtil.separator + name
  1712. imagePath = fileUri.getUriFromPath(imagePath)
  1713. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1714. fileIo.copyFileSync(file.fd, file2.fd)
  1715. fileIo.closeSync(file);
  1716. fileIo.closeSync(file2);
  1717. if (item.filePath == this.currentSong?.filePath) {
  1718. this.cover = imagePath
  1719. }
  1720. if (item) {
  1721. item.pixelMapPath = imagePath
  1722. }
  1723. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1724. if (success) {
  1725. this.doUpdateData()
  1726. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1727. } else {
  1728. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1729. }
  1730. });
  1731. LogUtil.debug("onecold this.cover =" + this.cover)
  1732. }).catch((err: BusinessError) => {
  1733. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1734. })
  1735. }
  1736. // 拉起picker选择文件管理器
  1737. async callFilePickerSelectFile(): Promise<void> {
  1738. try {
  1739. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1740. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1741. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1742. } else {
  1743. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1744. }
  1745. let documentPicker = new picker.DocumentViewPicker();
  1746. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1747. Logger.info(TAG,
  1748. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1749. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1750. this.saveVideoDatas(DocumentSelectResult)
  1751. }
  1752. }).catch((err: BusinessError) => {
  1753. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1754. });
  1755. } catch (err) {
  1756. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1757. }
  1758. }
  1759. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1760. //操作确认类弹出框
  1761. DialogHelper.showAlertDialog({
  1762. maskColor: Color.Transparent,
  1763. content: "确定要删除这个文件吗?",
  1764. backgroundColor: Color.Grey,
  1765. transition: AnimationHelper.transitionInUp(555),
  1766. onAction: (action) => {
  1767. if (action == DialogAction.ONE) {
  1768. // ToastUtil.showToast(`您点击了取消按钮`);
  1769. } else if (action == DialogAction.TWO) {
  1770. // ToastUtil.showToast(`您点击了确认按钮`);
  1771. this.doDelete(item, index + '', filePath)
  1772. }
  1773. }
  1774. })
  1775. }
  1776. //删除单个索引index的视频
  1777. doDelete(item: VideoItem, index: string, filePath: string) {
  1778. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1779. Logger.info(TAG, 'delete filePath = ' + filePath);
  1780. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1781. //旧文件删除
  1782. this.table.deleteDataForParentPath(item.filePath, () => {
  1783. FileUtil.rmdir(filePath).then(() => {
  1784. this.videoLocalList.splice(Number(index), 1)
  1785. this.deleteCache(this.currentPath)
  1786. this.getSortedFiles(this.currentPath, true)
  1787. }).catch((error: BusinessError) => {
  1788. console.error(error.message);
  1789. });
  1790. });
  1791. } else {
  1792. this.table.deleteData(item, () => {
  1793. FileUtil.unlink(filePath)
  1794. .catch((error: BusinessError) => {
  1795. console.error(error.message);
  1796. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1797. })
  1798. .finally(() => {
  1799. this.videoLocalList.splice(Number(index), 1)
  1800. this.deleteCache(this.currentPath)
  1801. this.getSortedFiles(this.currentPath, true)
  1802. });
  1803. });
  1804. }
  1805. }
  1806. }
  1807. //重命名的对话框
  1808. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1809. DialogHelper.showTextInputDialog({
  1810. title: '重命名',
  1811. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1812. maskColor: Color.Transparent,
  1813. backgroundColor: Color.Grey,
  1814. transition: AnimationHelper.transitionInDown(666),
  1815. onChange: (text) => {
  1816. console.error("onChange: " + text);
  1817. },
  1818. onAction: (action, dialogId, content) => {
  1819. // ToastUtil.showToast('content = ' +content)
  1820. if (action == DialogAction.TWO) {
  1821. const newName = content
  1822. const newPath = this.currentPath + '/' + newName
  1823. console.log("onecold item = " + item.type);
  1824. this.doReName(index, newName, filePath, newPath, item)
  1825. }
  1826. }
  1827. })
  1828. }
  1829. //剪切 移动到另个文件夹的对话框
  1830. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1831. Logger.info('onecold showCutDialog')
  1832. let mList: Array<string> = []
  1833. let rPath = this.rootPath
  1834. if (isCurrent) {
  1835. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1836. rPath = this.currentPath
  1837. } else {
  1838. mList = Utility.getNameList(this.dirList);
  1839. rPath = this.rootPath
  1840. }
  1841. let dataBean = new BubbleBean()
  1842. dataBean.data = mList
  1843. dataBean.color = this.themeColor
  1844. dataBean.onItemClick = (i) => {
  1845. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1846. Logger.info('newPath = ' + newPath)
  1847. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1848. ToastUtil.showToast('移动成功')
  1849. this.table.deleteData(item, () => {
  1850. });
  1851. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1852. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1853. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1854. CommonConstants.TYPE_LOCAL, true);
  1855. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1856. this.table.insert(newItem, (id: number) => {
  1857. //加入数据库
  1858. });
  1859. }
  1860. this.cache.delete(this.currentPath); // 删除原路径缓存
  1861. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1862. this.getSortedFiles(this.currentPath, true)
  1863. }).catch((error: BusinessError) => {
  1864. console.error(error.message);
  1865. });
  1866. XPopup.dismissTop()
  1867. }
  1868. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1869. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1870. popupPosition = PopupPosition.TOP
  1871. }
  1872. if (index <= 3) {
  1873. popupPosition = PopupPosition.BOTTOM
  1874. }
  1875. let pup: XPopup
  1876. if (this.isDarkMode) {
  1877. pup = XPopup.Builder()
  1878. .setPopupPosition(popupPosition)
  1879. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1880. .setBackgroundColor(Color.Black)
  1881. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1882. .show()
  1883. } else {
  1884. pup = XPopup.Builder()
  1885. .setPopupPosition(popupPosition)
  1886. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1887. .setBackgroundColor(Color.White)
  1888. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1889. .show()
  1890. }
  1891. }
  1892. //复制 到另个文件夹的对话框
  1893. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1894. Logger.info('onecoldv showCopyDialog')
  1895. let mList: Array<string> = []
  1896. let rPath = this.rootPath
  1897. if (isCurrent) {
  1898. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1899. rPath = this.currentPath
  1900. } else {
  1901. mList = Utility.getNameList(this.dirList);
  1902. rPath = this.rootPath
  1903. }
  1904. let dataBean = new BubbleBean()
  1905. dataBean.data = mList
  1906. dataBean.isCopy = true
  1907. dataBean.color = this.themeColor
  1908. dataBean.onItemClick = (i) => {
  1909. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1910. Logger.info('newPath = ' + newPath)
  1911. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1912. ToastUtil.showToast('复制成功')
  1913. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1914. this.getSortedFiles(this.currentPath)
  1915. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1916. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1917. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1918. CommonConstants.TYPE_LOCAL, true);
  1919. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1920. this.table.insert(newItem, (id: number) => {
  1921. //加入数据库
  1922. });
  1923. }
  1924. }).catch((error: BusinessError) => {
  1925. console.error(error.message);
  1926. });
  1927. XPopup.dismissTop()
  1928. }
  1929. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1930. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1931. popupPosition = PopupPosition.TOP
  1932. }
  1933. if (index <= 3) {
  1934. popupPosition = PopupPosition.BOTTOM
  1935. }
  1936. let pup: XPopup
  1937. if (this.isDarkMode) {
  1938. pup = XPopup.Builder()
  1939. .setPopupPosition(popupPosition)
  1940. .atView(id)
  1941. .setMaxHeight('60%')
  1942. .setBackgroundColor(Color.Black)
  1943. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1944. .show();
  1945. } else {
  1946. pup = XPopup.Builder()
  1947. .setPopupPosition(popupPosition)
  1948. .atView(id)
  1949. .setMaxHeight('60%')
  1950. .setBackgroundColor(Color.White)
  1951. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1952. .show();
  1953. }
  1954. }
  1955. //重命名索引index的视频
  1956. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1957. FileUtil.rename(oldPath, newPath).then(async () => {
  1958. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1959. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1960. //如果是文件夹先删除源数据,再添加新数据
  1961. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1962. if (success) {
  1963. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1964. } else {
  1965. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1966. }
  1967. });
  1968. this.scanDirectory(newPath)
  1969. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1970. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1971. if (success) {
  1972. console.log(" onecold 重命名成功,数据库已同步");
  1973. } else {
  1974. console.error(" onecold 重命名数据库失败原因: " + error);
  1975. }
  1976. });
  1977. }
  1978. let mediaItem: VideoItem =
  1979. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1980. this.videoLocalList[index] = mediaItem;
  1981. }
  1982. this.cache.delete(this.currentPath)
  1983. this.getSortedFiles(this.currentPath, true)
  1984. }).catch((error: BusinessError) => {
  1985. console.error(error.message);
  1986. });
  1987. }
  1988. build() {
  1989. Scroll() {
  1990. Column() {
  1991. if (!this.isShowCoverHeader()) {
  1992. Column() {
  1993. Line().width('100%').height('100%')
  1994. }
  1995. .height(this.topRectHeight)
  1996. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1997. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1998. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1999. TitleBar({ model: $titleBarModel })
  2000. .id('pup_positon_music')
  2001. }
  2002. Stack() {
  2003. Column() {
  2004. XComponent({
  2005. id: 'xcomponentId',
  2006. type: 'surface',
  2007. libraryname: 'ijkplayer_napi',
  2008. controller: this.xcomponentController
  2009. })
  2010. .onLoad((event?: object) => {
  2011. if (!!event) {
  2012. this.initDelayPlay(event);
  2013. }
  2014. })
  2015. .onKeyEvent((event?: KeyEvent) => {
  2016. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2017. if (!event || event.type !== KeyType.Down) {
  2018. return;
  2019. }
  2020. //空格键 Space key controls pause/play
  2021. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  2022. this.playOrPause()
  2023. }
  2024. // Right-click to fast forward
  2025. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2026. this.sessionFastForwardCallback(15);
  2027. }
  2028. // Left-click to rewind
  2029. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2030. this.sessionRewindCallback(15);
  2031. }
  2032. })
  2033. .onDestroy(() => {
  2034. })
  2035. .width('100%')// .width(this.videoWidth)
  2036. .aspectRatio(this.videoAspectRatio)
  2037. }
  2038. .aspectRatio(this.videoAspectRatio)
  2039. .justifyContent(FlexAlign.Center)
  2040. .backgroundColor(Color.Transparent)
  2041. .visibility(Visibility.Hidden)
  2042. .height(CommonConstants.FULL_PERCENT)
  2043. .width(CommonConstants.FULL_PERCENT)
  2044. Stack() {
  2045. Row() {
  2046. Blank()
  2047. .layoutWeight(1)
  2048. IndexerView(
  2049. {
  2050. indexArray: DEFAULT_INDEX,
  2051. selectedIndex: this.selectedIndex,
  2052. textSize: 12,
  2053. selectedColor: "#ff419ee5",
  2054. normalColor: "#ffa0a0a0",
  2055. floatSelectedTextColor: "#ffffff",
  2056. floatSelectedViewColor: "#ff419ee5",
  2057. onIndexChanged: (index) => {
  2058. this.listScroller.scrollToIndex(index)
  2059. }
  2060. })
  2061. .width(24)
  2062. .height("50%")
  2063. }.visibility(Visibility.None)
  2064. Column() {
  2065. if (!this.isShowCoverHeader()) {
  2066. this.tabTitle()
  2067. }
  2068. if (this.isGridMusic) {
  2069. this.getGridView()
  2070. } else {
  2071. this.getListView()
  2072. }
  2073. if (this.modeType == 0) {
  2074. Column() {
  2075. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  2076. .width(130)
  2077. .height(50)
  2078. .margin({ top: 100, bottom: 40 })
  2079. .backgroundColor(this.themeColor)
  2080. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2081. .onClick(() => {
  2082. this.asyncCurrentPathData()
  2083. })
  2084. }
  2085. .height(100)
  2086. .position({ top: 260 })
  2087. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2088. .animation({ duration: 500 }),
  2089. TransitionEffect.scale({ x: 0, y: 0 })))
  2090. .justifyContent(FlexAlign.Center)
  2091. .opacity(this.isZero ? 1 : 0)
  2092. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2093. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  2094. .animation({
  2095. duration: 500,
  2096. curve: 'ease-in-out' // 可选动画曲线
  2097. })
  2098. .width('100%')
  2099. }
  2100. }
  2101. .layoutWeight(1)
  2102. .height('100%')
  2103. }
  2104. .layoutWeight(1)
  2105. .height('100%')
  2106. Row() {
  2107. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2108. .width('35%')
  2109. .height(60)
  2110. .margin({ top: 10, bottom: 10, right: 6 })
  2111. .backgroundColor(this.themeColor)
  2112. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2113. .onClick(() => {
  2114. if (this.isAllSelected) {
  2115. // 全不选
  2116. this.selectedFiles = [];
  2117. } else {
  2118. // 全选
  2119. this.selectedFiles = [...this.getCurFileList()];
  2120. }
  2121. this.isAllSelected = !this.isAllSelected;
  2122. })
  2123. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2124. .width('35%')
  2125. .height(60)
  2126. .id('music_cut')
  2127. .margin({ top: 10, bottom: 10, right: 6 })
  2128. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2129. .backgroundColor(this.themeColor)
  2130. .onClick(() => {
  2131. this.showCutDialogForMultipleFiles(false, 'music_cut')
  2132. })
  2133. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2134. .width('35%')
  2135. .height(60)
  2136. .id('music_cut_current')
  2137. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2138. .margin({ top: 10, bottom: 10, right: 6 })
  2139. .backgroundColor(this.themeColor)
  2140. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2141. .onClick(() => {
  2142. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2143. })
  2144. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2145. .width('35%')
  2146. .height(60)
  2147. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2148. .margin({ top: 10, bottom: 10, right: 6 })
  2149. .backgroundColor(this.themeColor)
  2150. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2151. .onClick(() => {
  2152. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2153. })
  2154. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2155. .width('35%')
  2156. .height(60)
  2157. .margin({ top: 10, bottom: 10, right: 6 })
  2158. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2159. .backgroundColor(this.themeColor)
  2160. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2161. .onClick(() => {
  2162. this.showWarnIsDelete()
  2163. })
  2164. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2165. .width('35%')
  2166. .height(60)
  2167. .margin({ top: 10, bottom: 10, right: 6 })
  2168. .backgroundColor(this.themeColor)
  2169. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2170. .onClick(() => {
  2171. this.selectedFiles = [];
  2172. this.isAllSelected = false
  2173. this.isMultiSelect = false
  2174. })
  2175. }
  2176. .width('100%')
  2177. .justifyContent(FlexAlign.Center)
  2178. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2179. .opacity(this.isMultiSelect ? 1 : 0)
  2180. .animation({
  2181. duration: 666,
  2182. curve: 'ease-in-out' // 可选动画曲线
  2183. })
  2184. .position(this.isShowCoverHeader() ? { bottom: 78 }
  2185. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  2186. }
  2187. .width('100%')
  2188. .height('100%')
  2189. .alignContent(Alignment.Top)
  2190. Column() {
  2191. this.PlayController()
  2192. }
  2193. .hitTestBehavior(HitTestMode.Transparent)
  2194. .position({ bottom: 0 }) // 将 Row 固定在底部
  2195. .opacity(this.barBottomOpacity)
  2196. }
  2197. .width('100%')
  2198. .height('100%')
  2199. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2200. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2201. .backgroundImagePosition(Alignment.Center)
  2202. .backdropBlur(this.blurValue)
  2203. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2204. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2205. }
  2206. }
  2207. asyncCurrentPathData() {
  2208. if (this.modeType == 0) {
  2209. workerInstance.postMessage({
  2210. code: 1,
  2211. data1: this.context,
  2212. data2: this.currentPath,
  2213. data3: this.lockPath,
  2214. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2215. });
  2216. }
  2217. }
  2218. // 处理文件选择的函数
  2219. handleFileSelection(item: VideoItem, checked: boolean) {
  2220. if (checked) {
  2221. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2222. this.selectedFiles.push(item);
  2223. }
  2224. } else {
  2225. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2226. if (index > -1) {
  2227. this.selectedFiles.splice(index, 1);
  2228. }
  2229. }
  2230. }
  2231. showWarnIsDelete() {
  2232. //操作确认类弹出框
  2233. DialogHelper.showAlertDialog({
  2234. content: "确定要删除这些文件吗?",
  2235. transition: AnimationHelper.transitionInUp(666),
  2236. maskColor: Color.Transparent,
  2237. backgroundColor: Color.Grey,
  2238. onAction: (action) => {
  2239. if (action == DialogAction.ONE) {
  2240. // ToastUtil.showToast(`您点击了取消按钮`);
  2241. } else if (action == DialogAction.TWO) {
  2242. // ToastUtil.showToast(`您点击了确认按钮`);
  2243. this.deleteMultipleFiles()
  2244. }
  2245. }
  2246. })
  2247. }
  2248. //多选删除文件
  2249. deleteMultipleFiles() {
  2250. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  2251. this.selectedFiles.forEach((item) => {
  2252. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  2253. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2254. this.table.deleteDataForParentPath(item.filePath, () => {
  2255. FileUtil.rmdir(item.filePath).then(() => {
  2256. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  2257. this.selectedFiles = [];
  2258. this.isMultiSelect = false
  2259. this.isAllSelected = false
  2260. this.cache.delete(this.currentPath);
  2261. this.getSortedFiles(this.currentPath, true);
  2262. }).catch((error: Error) => {
  2263. console.error(error.message);
  2264. });
  2265. });
  2266. } else {
  2267. this.table.deleteData(item, () => {
  2268. FileUtil.unlink(item.filePath).catch((error: Error) => {
  2269. console.error(error.message);
  2270. }).finally(() => {
  2271. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  2272. this.selectedFiles = [];
  2273. this.isMultiSelect = false
  2274. this.isAllSelected = false
  2275. this.cache.delete(this.currentPath);
  2276. this.getSortedFiles(this.currentPath, true);
  2277. });
  2278. });
  2279. }
  2280. });
  2281. }
  2282. }
  2283. //多选移动文件
  2284. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2285. Logger.info('onecold showCutDialogForMultipleFiles')
  2286. let mList: Array<string> = []
  2287. let rPath = this.rootPath
  2288. if (isCurrent) {
  2289. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2290. rPath = this.currentPath
  2291. } else {
  2292. mList = Utility.getNameList(this.dirList);
  2293. rPath = this.rootPath
  2294. }
  2295. let dataBean = new BubbleBean();
  2296. dataBean.data = mList;
  2297. dataBean.color = this.themeColor
  2298. dataBean.onItemClick = (i) => {
  2299. const newDirPath = rPath + '/' + mList[i];
  2300. // Logger.info('newDirPath = ' + newDirPath)
  2301. this.selectedFiles.forEach((item) => {
  2302. const newPath = newDirPath + '/' + item.fileName;
  2303. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2304. ToastUtil.showToast('移动成功');
  2305. this.table.deleteData(item, () => {
  2306. this.cache.delete(this.currentPath); // 删除原路径缓存
  2307. this.cache.delete(newDirPath); // 删除目标路径缓存
  2308. this.getSortedFiles(this.currentPath, true);
  2309. });
  2310. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2311. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2312. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2313. CommonConstants.TYPE_LOCAL, true);
  2314. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2315. this.table.insert(newItem, (id: number) => {
  2316. //加入数据库
  2317. });
  2318. }
  2319. }).catch((error: Error) => {
  2320. console.error(error.message);
  2321. });
  2322. });
  2323. this.isMultiSelect = false
  2324. this.selectedFiles = [];
  2325. this.isAllSelected = false
  2326. XPopup.dismissTop();
  2327. };
  2328. let pup: XPopup
  2329. if (this.isDarkMode) {
  2330. pup = XPopup.Builder()
  2331. .setPopupPosition(PopupPosition.TOP)
  2332. .atView(viewId)
  2333. .setBackgroundColor(Color.Black)
  2334. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2335. .show();
  2336. } else {
  2337. pup = XPopup.Builder()
  2338. .setPopupPosition(PopupPosition.TOP)
  2339. .atView(viewId)
  2340. .setBackgroundColor(Color.White)
  2341. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2342. .show();
  2343. }
  2344. }
  2345. doFav(item: VideoItem) {
  2346. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2347. let isFav = 0
  2348. if (Utility.getIsFav(this.favList, item)) {
  2349. isFav = 0
  2350. } else {
  2351. isFav = 1
  2352. }
  2353. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2354. if (result) {
  2355. if (isFav === 1) {
  2356. ToastUtil.showToast('收藏成功');
  2357. } else {
  2358. ToastUtil.showToast('取消收藏成功');
  2359. }
  2360. // 先更新收藏列表和其他UI
  2361. this.deleteCache(this.currentPath)
  2362. this.getFavList(false)
  2363. if (this.modeType === 0 && !this.isFavMusic) {
  2364. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2365. this.getSortedFiles(this.currentPath)
  2366. }
  2367. workerInstance.postMessage({ code: 2, data: this.context });
  2368. workerInstance.postMessage({ code: 3, data: this.context });
  2369. workerInstance.postMessage({ code: 4, data: this.context });
  2370. // 刷新UnifiedPlayerService的收藏状态,这会自动更新AVSession
  2371. await this.unifiedPlayerService.refreshFavoriteStatus();
  2372. }
  2373. })
  2374. }
  2375. //多选复制文件
  2376. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2377. console.log('onecold showCopyDialogForMultipleFiles');
  2378. let mList: Array<string> = []
  2379. let rPath = this.rootPath
  2380. if (isCurrent) {
  2381. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2382. rPath = this.currentPath
  2383. } else {
  2384. mList = Utility.getNameList(this.dirList);
  2385. rPath = this.rootPath
  2386. }
  2387. let dataBean = new BubbleBean();
  2388. dataBean.data = mList;
  2389. dataBean.isCopy = true
  2390. dataBean.color = this.themeColor
  2391. dataBean.onItemClick = (i) => {
  2392. const newDirPath = rPath + '/' + mList[i];
  2393. // Logger.info('newDirPath = ' + newDirPath)
  2394. this.selectedFiles.forEach((item) => {
  2395. const newPath = newDirPath + '/' + item.fileName;
  2396. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2397. ToastUtil.showToast('复制成功');
  2398. this.cache.delete(newDirPath); // 删除目标路径缓存
  2399. this.getSortedFiles(this.currentPath);
  2400. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2401. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2402. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2403. CommonConstants.TYPE_LOCAL, true);
  2404. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2405. this.table.insert(newItem, (id: number) => {
  2406. //加入数据库
  2407. });
  2408. }
  2409. }).catch((error: Error) => {
  2410. console.error(error.message);
  2411. });
  2412. });
  2413. this.isMultiSelect = false
  2414. this.selectedFiles = [];
  2415. this.isAllSelected = false
  2416. XPopup.dismissTop();
  2417. };
  2418. let pup: XPopup
  2419. if (this.isDarkMode) {
  2420. pup = XPopup.Builder()
  2421. .setPopupPosition(PopupPosition.TOP)
  2422. .atView(viewId)
  2423. .setBackgroundColor(Color.Black)
  2424. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2425. .show();
  2426. } else {
  2427. pup = XPopup.Builder()
  2428. .setPopupPosition(PopupPosition.TOP)
  2429. .atView(viewId)
  2430. .setBackgroundColor(Color.White)
  2431. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2432. .show();
  2433. }
  2434. }
  2435. @Builder
  2436. private DirItem(item: VideoItem, index?: number) {
  2437. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2438. Row() {
  2439. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2440. $r('app.media.music_group'))
  2441. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2442. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2443. .fillColor(this.themeColor)// .fontSize(33)
  2444. .alt($r('app.media.music_group'))
  2445. .borderRadius('100%')
  2446. .clip(true)
  2447. .margin({ left: 20, top: 8, bottom: 8 })
  2448. Column() {
  2449. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2450. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2451. .maxLines(1)// .width('88%')
  2452. .animation({
  2453. duration: 555,
  2454. curve: 'ease-in-out',
  2455. })
  2456. .transition({
  2457. type: TransitionType.Insert,
  2458. opacity: 0,
  2459. translate: { x: 160 }
  2460. })
  2461. .margin({ left: 10, right: 20 })
  2462. .fontColor($r('app.color.text_color'))
  2463. Row() {
  2464. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2465. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2466. .padding({ top: 8 })
  2467. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2468. .fontColor($r('app.color.text_color'))
  2469. .margin({ left: 10 })
  2470. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2471. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2472. .padding({ top: 8 })
  2473. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2474. .fontColor($r('app.color.text_color'))
  2475. .margin({ left: 10 })
  2476. Blank()
  2477. }
  2478. }
  2479. .height('100%')
  2480. .layoutWeight(1)
  2481. .justifyContent(FlexAlign.Center)
  2482. .alignItems(HorizontalAlign.Start)
  2483. Blank()
  2484. Image($r('app.media.arrow_right'))
  2485. .height(25)
  2486. .margin({ right: 10 })
  2487. .alignSelf(ItemAlign.Center)
  2488. .id(item.filePath)
  2489. }
  2490. }
  2491. .backgroundColor(Color.Transparent)
  2492. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2493. .width('100%')
  2494. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2495. .opacity(this.opacityItem) // 绑定透明度
  2496. }
  2497. isShowDir(dirName: string) {
  2498. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2499. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2500. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2501. if (dirName === undefined) {
  2502. return true
  2503. }
  2504. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2505. return this.isShowSimi
  2506. }
  2507. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2508. return this.isShowFAV
  2509. }
  2510. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2511. return this.isShowHistory
  2512. }
  2513. return true
  2514. }
  2515. @State opacityItem: number = 1; // 控制透明度的状态变量
  2516. @Builder
  2517. private MusicItem(item: VideoItem, index?: number) {
  2518. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2519. Row() {
  2520. Stack() {
  2521. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2522. .fillColor(this.themeColor)
  2523. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2524. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2525. .alt($r('app.media.music_red'))
  2526. .borderRadius('100%')
  2527. .clip(true)
  2528. .draggable(false)
  2529. .interpolation(ImageInterpolation.Medium)// 用于重采样后的抗锯齿
  2530. .autoResize(true) // 重采样,可减少内存占用
  2531. .opacity(this.opacityItem)// 绑定透明度
  2532. .margin({ left: 20 })
  2533. .gesture(LongPressGesture()
  2534. .onAction(async () => {
  2535. //如果是专辑和艺术家的首页,不能长按
  2536. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2537. return
  2538. //如果是我的收藏 最近播放等也不能长按
  2539. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2540. item.name === LocalMusic.STR_HISTORY_MUSIC
  2541. )
  2542. return
  2543. this.longItemFilePath = item.filePath
  2544. this.tempLyricContent = await this.getLyricContent(item)
  2545. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2546. })
  2547. .onActionEnd((event: GestureEvent) => {
  2548. }))
  2549. }
  2550. Column() {
  2551. Column() {
  2552. Text(item.name)
  2553. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2554. .maxLines(1)
  2555. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2556. .animation({
  2557. duration: 555,
  2558. curve: 'Linear',
  2559. })
  2560. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2561. $r('app.color.text_color'))
  2562. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2563. .bindPopup(this.longItemFilePath === item.filePath, {
  2564. builder: this.MenuBuilder(item,index,item.filePath),
  2565. placement: Placement.Top,
  2566. // autoCancel: true,
  2567. mask: {color:'#33000000'},
  2568. // popupColor: Color.Yellow,
  2569. enableArrow: false,//是否显示箭头
  2570. showInSubWindow: false,
  2571. onStateChange: (e) => {
  2572. if (!e.isVisible) {
  2573. this.longItemFilePath = ''
  2574. this.tempLyricContent = ''
  2575. }
  2576. }
  2577. })
  2578. .gesture(LongPressGesture()
  2579. .onAction(async () => {
  2580. //如果是专辑和艺术家的首页,不能长按
  2581. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2582. return
  2583. //如果是我的收藏 最近播放等也不能长按
  2584. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2585. item.name === LocalMusic.STR_HISTORY_MUSIC
  2586. )
  2587. return
  2588. this.longItemFilePath = item.filePath
  2589. this.tempLyricContent = await this.getLyricContent(item)
  2590. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2591. })
  2592. .onActionEnd((event: GestureEvent) => {
  2593. })
  2594. )
  2595. Row() {
  2596. Column(){
  2597. Text(item.md5Str?.includes('Lossless')?
  2598. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2599. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2600. .padding({ top: 3,right:6,left:6,bottom:3 })
  2601. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2602. $r('app.color.text_color'))
  2603. .fontWeight(500)
  2604. .borderRadius(12)
  2605. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2606. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2607. .backgroundColor('#FFC107')
  2608. }
  2609. .padding({ top: 8 })
  2610. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2611. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2612. .padding({ top: 8 })
  2613. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2614. $r('app.color.text_color'))
  2615. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2616. Blank()
  2617. Text(item.size)
  2618. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2619. .padding({ top: 8 })
  2620. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2621. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2622. $r('app.color.text_color'))
  2623. .margin({ left: 10 })
  2624. }
  2625. .gesture(LongPressGesture()
  2626. .onAction(async () => {
  2627. //如果是专辑和艺术家的首页,不能长按
  2628. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2629. return
  2630. //如果是我的收藏 最近播放等也不能长按
  2631. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2632. item.name === LocalMusic.STR_HISTORY_MUSIC
  2633. )
  2634. return
  2635. this.longItemFilePath = item.filePath
  2636. this.tempLyricContent = await this.getLyricContent(item)
  2637. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2638. })
  2639. .onActionEnd((event: GestureEvent) => {
  2640. })
  2641. )
  2642. }
  2643. .height('100%')
  2644. .width('100%')
  2645. .justifyContent(FlexAlign.Center)
  2646. .alignItems(HorizontalAlign.Start)
  2647. }
  2648. .height('100%')
  2649. .margin({ left: 5 })
  2650. .layoutWeight(1)
  2651. Column() {
  2652. Checkbox({ name: 'checkbox' + index })
  2653. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2654. .selectedColor(this.themeColor)
  2655. .shape(CheckBoxShape.CIRCLE)
  2656. .opacity(this.isMultiSelect ? 1 : 0)
  2657. .animation({
  2658. duration: 666,
  2659. curve: 'Smooth' // 可选动画曲线
  2660. })
  2661. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2662. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2663. .margin({ left: 20, top: 8, bottom: 8 })
  2664. .width(22)
  2665. .height(22)
  2666. ImageAnimator()
  2667. .images(this.imagesF)// 动画数组
  2668. .duration(1000)// 持续
  2669. .state(this.animationState)// 动画状态
  2670. .fillMode(FillMode.Forwards)
  2671. .width(18)
  2672. .margin({ right: 20, top: 8, bottom: 8 })
  2673. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2674. Visibility.None)
  2675. .height(18)
  2676. .iterations(-1) // 播放次数
  2677. }
  2678. }
  2679. }
  2680. .backgroundColor(Color.Transparent)
  2681. .width('100%')
  2682. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2683. }
  2684. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2685. @Builder
  2686. tabTitle() {
  2687. Column() {
  2688. // 使用 Stack 布局来实现绝对定位效果
  2689. Stack() {
  2690. // 背景动画容器
  2691. Row() {
  2692. ForEach(this.tabs, (i: string, index) => {
  2693. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2694. Flex()
  2695. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2696. .borderRadius(20)
  2697. .padding(10)
  2698. .margin(6)
  2699. .width('100%')
  2700. .height('100%')
  2701. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2702. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2703. .opacity(this.modeType === index ? 1 : 0)
  2704. .animation({
  2705. duration: 666,
  2706. playMode: PlayMode.Normal,
  2707. curve: 'ease-in-out'
  2708. });
  2709. }
  2710. .layoutWeight(1)
  2711. .margin({
  2712. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2713. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2714. });
  2715. });
  2716. }
  2717. .width('100%')
  2718. .height(50);
  2719. // 导航栏容器
  2720. Row() {
  2721. ForEach(this.tabs, (item: string, index) => {
  2722. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2723. Text(item)
  2724. .fontSize(16)
  2725. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2726. .padding(15)
  2727. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2728. .onClick(() => {
  2729. this.modeType = index;
  2730. this.onModeChange();
  2731. });
  2732. }
  2733. .layoutWeight(1)
  2734. .stateStyles({
  2735. pressed: { opacity: 0.6 } // 按压反馈
  2736. });
  2737. });
  2738. }
  2739. .width('100%')
  2740. .height(this.topBarHeight)
  2741. .opacity(this.barOpacity)
  2742. .backgroundColor(Color.Transparent);
  2743. }
  2744. .width('100%')
  2745. .height(this.topBarHeight)
  2746. .opacity(this.barOpacity)
  2747. Line()
  2748. .width('100%')
  2749. .height(1)
  2750. .backgroundColor($r('app.color.index_background'))
  2751. .opacity(this.barOpacity)
  2752. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2753. }
  2754. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2755. }
  2756. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2757. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2758. isShowCoverHeader() {
  2759. if (!this.isShowHeader) {
  2760. return false
  2761. }
  2762. if (this.modeType == 0) {
  2763. if (this.isHistory || this.isFavMusic) {
  2764. return true
  2765. }
  2766. if (this.currentPath != this.rootPath) {
  2767. return true
  2768. }
  2769. }
  2770. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2771. }
  2772. @Builder
  2773. coverHeader() {
  2774. if (this.isShowCoverHeader()) {
  2775. Column() {
  2776. Stack() {
  2777. // 居中标题
  2778. Text('')
  2779. .fontSize(18)
  2780. .fontColor(Color.White)
  2781. .align(Alignment.Center)
  2782. // 左右按钮
  2783. Row() {
  2784. Image($r('app.media.left_back_white'))
  2785. .width(28)
  2786. .height(28)
  2787. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2788. .margin({ left: 12, right: 8 })
  2789. .onClick(() => {
  2790. animateTo({ duration: 555 }, () => {
  2791. this.doSwipBack()
  2792. })
  2793. })
  2794. Blank().flexGrow(1)
  2795. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2796. Image($r('app.media.add'))
  2797. .width(25)
  2798. .height(25)
  2799. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2800. .margin({ left: 8, right: 15 })
  2801. .onClick(() => {
  2802. this.showAddDialog()
  2803. })
  2804. }
  2805. }
  2806. .height(48)
  2807. .width('100%')
  2808. .alignItems(VerticalAlign.Center)
  2809. }
  2810. .height(48)
  2811. .width('100%')
  2812. Row() {
  2813. Column() {
  2814. Image(this.currentTitleCover)
  2815. .height(100)
  2816. .width(100)
  2817. .alt(this.imageLabel)
  2818. .borderRadius(8)
  2819. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2820. }
  2821. .alignItems(HorizontalAlign.Start)
  2822. .margin({ left: 30, top: 3, bottom: 15 })
  2823. Column() {
  2824. Column() {
  2825. Text(this.currentTitleName)
  2826. .fontSize(16)
  2827. .maxLines(1)
  2828. .fontWeight(FontWeight.Bold)
  2829. .fontColor($r('app.color.text_color'))
  2830. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2831. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2832. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2833. .fontSize(14)
  2834. .padding({ top: 8 })
  2835. .maxLines(1)
  2836. .fontWeight(FontWeight.Bold)
  2837. .fontColor($r('app.color.text_color'))
  2838. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2839. if(this.videoLocalList[0].genre){
  2840. Text(`风格:${this.videoLocalList[0].genre}`)
  2841. .fontSize(14)
  2842. .padding({ top: 8 })
  2843. .maxLines(1)
  2844. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2845. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2846. ?Visibility.None:Visibility.Visible)
  2847. .fontWeight(FontWeight.Bold)
  2848. .fontColor($r('app.color.text_color'))
  2849. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2850. }
  2851. if(this.videoLocalList[0].year){
  2852. Text(`发行时间:${this.videoLocalList[0].year}`)
  2853. .fontSize(14)
  2854. .padding({ top: 8 })
  2855. .maxLines(1)
  2856. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2857. this.videoLocalList[0].year.includes(this.UNKONWN)
  2858. ?Visibility.None:Visibility.Visible)
  2859. .fontWeight(FontWeight.Bold)
  2860. .fontColor($r('app.color.text_color'))
  2861. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2862. }
  2863. }
  2864. if(this.modeType != 3){
  2865. Row() {
  2866. Text(`共${this.videoLocalList.length}首歌`)
  2867. .fontSize(13)
  2868. .fontWeight(FontWeight.Bold)
  2869. .padding({ top: 8 })
  2870. .fontColor($r('app.color.text_color'))
  2871. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2872. Blank()
  2873. }
  2874. }
  2875. }
  2876. .height('100%')
  2877. .width('100%')
  2878. .justifyContent(FlexAlign.Center)
  2879. .alignItems(HorizontalAlign.Start)
  2880. }
  2881. .height('100%')
  2882. .layoutWeight(1)
  2883. .margin({ left: 20 })
  2884. }
  2885. this.listViewTitle()
  2886. }
  2887. .backgroundImage(this.getCoverTitleBg())
  2888. .height(250)
  2889. .width('100%')
  2890. .backgroundImageSize({ height: '100%', width: '100%' })
  2891. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2892. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2893. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2894. .justifyContent(FlexAlign.SpaceBetween)
  2895. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2896. TransitionEffect.scale({ x: 0, y: 0 })))
  2897. } else {
  2898. this.listViewTitle()
  2899. }
  2900. }
  2901. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2902. if (this.isCustomizeBg) {
  2903. return ('rgba(255,255,255,0.2)')
  2904. }
  2905. if (this.isDarkMode) {
  2906. return $r('app.color.user_center_card_background')
  2907. }
  2908. return this.currentTitleCover
  2909. }
  2910. @Builder
  2911. listViewTitle() {
  2912. Column() {
  2913. Row({ space: 8 }) {
  2914. Row({ space: 8 }) {
  2915. Image($r("app.media.hm_playlist"))
  2916. .width(25)
  2917. .margin({ left: 8 })
  2918. .fillColor(this.themeColor)
  2919. Text(`共找到${this.artistList.length}位艺术家`)
  2920. .fontColor($r('app.color.text_color'))
  2921. .fontSize(14)
  2922. .opacity(this.opacityItem)
  2923. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2924. Text(`共找到${this.albumList.length}张专辑`)
  2925. .fontColor($r('app.color.text_color'))
  2926. .opacity(this.opacityItem)
  2927. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2928. .fontSize(14)
  2929. }
  2930. .layoutWeight(1)
  2931. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2932. Row() {
  2933. TextInput({
  2934. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2935. text: this.searchText
  2936. })
  2937. .height(35)
  2938. .onChange((value: string) => {
  2939. this.onSearchInput(value);
  2940. })
  2941. .layoutWeight(1)
  2942. Text(`取消`)
  2943. .margin({ left: 10, right: 10 })
  2944. .fontColor($r('app.color.text_color'))
  2945. .fontSize(16)
  2946. .onClick(() => {
  2947. this.isSearchMode = false
  2948. this.searchText = ''
  2949. if (this.modeType === 2) {
  2950. this.updateListData(this.artistList)
  2951. } else {
  2952. this.updateListData(this.albumList)
  2953. }
  2954. })
  2955. }
  2956. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2957. .animation({
  2958. duration: 666,
  2959. curve: 'ease-in-out' // 可选动画曲线
  2960. })
  2961. Blank()
  2962. Image($r("app.media.search"))
  2963. .width(25)
  2964. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2965. .animation({
  2966. duration: 666,
  2967. curve: 'ease-in-out' // 可选动画曲线
  2968. })// .opacity(this.opacityItem)
  2969. .fillColor(this.themeColor)
  2970. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2971. .onClick(() => {
  2972. this.isSearchMode = true
  2973. })
  2974. Image($r("app.media.top_rank"))
  2975. .width(25)// .opacity(this.opacityItem)
  2976. .fillColor(this.themeColor)
  2977. .animation({
  2978. duration: 666,
  2979. curve: 'ease-in-out' // 可选动画曲线
  2980. })
  2981. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2982. .onClick(() => {
  2983. this.showRankDialog()
  2984. })
  2985. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2986. .width(25)
  2987. .animation({
  2988. duration: 666,
  2989. curve: 'ease-in-out' // 可选动画曲线
  2990. })
  2991. .fillColor(this.themeColor)
  2992. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2993. .onClick(() => {
  2994. this.isGridMusic = !this.isGridMusic
  2995. })
  2996. }
  2997. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2998. Visibility.None)
  2999. .width('100%')
  3000. .padding(10)
  3001. .height(50)
  3002. .border({
  3003. width: { bottom: 1 },
  3004. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3005. })
  3006. Row({ space: 8 }) {
  3007. Row({ space: 8 }) {
  3008. Image($r("app.media.hm_play"))
  3009. .width(25)
  3010. .margin({ left: 8 })
  3011. .fillColor(this.themeColor)
  3012. Text(`播放全部`)
  3013. .fontColor($r('app.color.text_color'))
  3014. .fontSize(14)
  3015. .animation({
  3016. duration: 666,
  3017. curve: 'ease-in-out' // 可选动画曲线
  3018. })
  3019. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  3020. .fontColor($r('app.color.text_color'))
  3021. .fontSize(14)
  3022. .opacity(this.opacityItem)
  3023. .animation({
  3024. duration: 666,
  3025. curve: 'ease-in-out' // 可选动画曲线
  3026. })
  3027. }
  3028. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3029. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3030. .animation({
  3031. duration: 666,
  3032. curve: 'ease-in-out' // 可选动画曲线
  3033. })
  3034. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  3035. .onTouch((event: TouchEvent) => {
  3036. if (event.type === TouchType.Down) {
  3037. this.isClickedPLayAll = true;
  3038. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  3039. this.isClickedPLayAll = false;
  3040. }
  3041. })
  3042. .onClick(() => {
  3043. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  3044. if (this.modeType === 0) {
  3045. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  3046. this.doPlay(this.getCurFileList()[0])
  3047. }
  3048. } else {
  3049. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  3050. this.doPlay(this.mediaKuList[0])
  3051. }
  3052. }
  3053. })
  3054. Row() {
  3055. TextInput({ placeholder: '输入名称...', text: this.searchText })
  3056. .height(35)
  3057. .onChange((value: string) => {
  3058. this.onSearchInput(value);
  3059. })
  3060. .layoutWeight(1)
  3061. Text(`取消`)
  3062. .margin({ left: 10, right: 10 })
  3063. .fontColor($r('app.color.text_color'))
  3064. .fontSize(16)
  3065. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3066. .onClick(() => {
  3067. this.isSearchMode = false
  3068. this.searchText = ''
  3069. this.updateListData(this.mediaKuList)
  3070. })
  3071. }
  3072. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3073. .animation({
  3074. duration: 666,
  3075. curve: 'ease-in-out' // 可选动画曲线
  3076. })
  3077. Blank()
  3078. Image($r("app.media.search"))
  3079. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  3080. .animation({
  3081. duration: 666,
  3082. curve: 'ease-in-out' // 可选动画曲线
  3083. })// .opacity(this.opacityItem)
  3084. .fillColor(this.themeColor)
  3085. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3086. .onClick(() => {
  3087. this.isSearchMode = true
  3088. })
  3089. Image($r("app.media.refresh"))
  3090. .fillColor(this.themeColor)
  3091. .width(25)
  3092. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3093. .animation({
  3094. duration: 666,
  3095. curve: 'ease-in-out' // 可选动画曲线
  3096. })
  3097. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3098. .onClick(() => {
  3099. if (this.isFavMusic) {
  3100. this.getFavList(true)
  3101. } else {
  3102. if(this.modeType == 0){
  3103. this.asyncCurrentPathData()
  3104. }else if(this.modeType ==1){
  3105. workerInstance.postMessage({ code: 2, data: this.context });
  3106. }
  3107. }
  3108. })
  3109. Image($r("app.media.top_rank"))
  3110. .width(25)
  3111. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  3112. Visibility.Visible)// .opacity(this.opacityItem)
  3113. .animation({
  3114. duration: 666,
  3115. curve: 'ease-in-out' // 可选动画曲线
  3116. })
  3117. .fillColor(this.themeColor)
  3118. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3119. .onClick(() => {
  3120. this.showRankDialog()
  3121. })
  3122. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  3123. .width(24)
  3124. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3125. .animation({
  3126. duration: 666,
  3127. curve: 'ease-in-out' // 可选动画曲线
  3128. })
  3129. .fillColor(this.themeColor)
  3130. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3131. .onClick(() => {
  3132. this.isMultiSelect = !this.isMultiSelect
  3133. })
  3134. SymbolGlyph($r('sys.symbol.trash'))
  3135. .fontColor([this.themeColor])
  3136. .fontSize(25)
  3137. .effectStrategy(1)
  3138. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  3139. .animation({
  3140. duration: 666,
  3141. curve: 'ease-in-out' // 可选动画曲线
  3142. })
  3143. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3144. .onClick(() => {
  3145. this.clearVideoHistory() //清空播放记录
  3146. })
  3147. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3148. .width(24)
  3149. .animation({
  3150. duration: 666,
  3151. curve: 'ease-in-out' // 可选动画曲线
  3152. })
  3153. .fillColor(this.themeColor)
  3154. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3155. .bindPopup($$this.tipPopup, {
  3156. builder: this.popupBuilder,
  3157. placement: Placement.Bottom,
  3158. maskColor: 0x33000000,
  3159. enableArrow: true,
  3160. onStateChange: (e) => {
  3161. if (!e.isVisible) {
  3162. this.tipPopup = false;
  3163. }
  3164. }
  3165. })
  3166. .onClick(() => {
  3167. this.isGridMusic = !this.isGridMusic
  3168. })
  3169. }
  3170. .width('100%')
  3171. .padding(10)
  3172. .height(50)
  3173. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  3174. .border({
  3175. width: { bottom: 1 },
  3176. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3177. })
  3178. }
  3179. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3180. }
  3181. // 第二步:popup构造器定义弹框内容
  3182. @Builder popupBuilder() {
  3183. Column({ space: 2 }) {
  3184. Text('友情提示:双指缩放可以放大缩小列表')
  3185. .fontSize(12)
  3186. .fontWeight(FontWeight.Regular)
  3187. .fontColor($r('app.color.text_color'))
  3188. }
  3189. .justifyContent(FlexAlign.SpaceAround)
  3190. .width(220)
  3191. .height(55)
  3192. .padding(15)
  3193. }
  3194. //搜索功能的实现
  3195. @State searchText: string = ''; // 用户输入内容
  3196. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3197. @State isSearchMode: boolean = false
  3198. // 实时搜索逻辑(带防抖)
  3199. private onSearchInput(value: string) {
  3200. this.searchText = value.trim();
  3201. let mSearchList: Array<VideoItem> = []
  3202. switch (this.modeType) {
  3203. case 0:
  3204. mSearchList = this.videoLocalList
  3205. break;
  3206. case 1:
  3207. mSearchList = this.mediaKuList
  3208. break;
  3209. case 2:
  3210. mSearchList = this.artistList
  3211. break;
  3212. case 3:
  3213. mSearchList = this.albumList
  3214. break;
  3215. }
  3216. // 新增条件判断:空输入时显示所有数据
  3217. if (this.searchText === '') {
  3218. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3219. } else {
  3220. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3221. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  3222. });
  3223. }
  3224. this.updateListData(this.filteredList);
  3225. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3226. }
  3227. @State dragItem: number = -1
  3228. @State scaleItem: number = -1
  3229. @State neighborItem: number = -1
  3230. @State neighborScale: number = -1
  3231. @State offsetY: number = 0
  3232. private dragRefOffset: number = 0
  3233. private ITEM_INTV: number = 78
  3234. scaleSelect(item: number): number {
  3235. if (this.scaleItem === item) {
  3236. return 1.05
  3237. } else if (this.neighborItem === item) {
  3238. return this.neighborScale
  3239. } else {
  3240. return 1
  3241. }
  3242. }
  3243. itemMove(index: number, newIndex: number): void {
  3244. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3245. return;
  3246. }
  3247. let tmp = this.videoLocalList.splice(index, 1);
  3248. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3249. this.dataSource.pushArrayData(this.videoLocalList)
  3250. }
  3251. // Grid布局的开始
  3252. private dragRefOffSetX: number = 0;
  3253. private dragRefOffSetY: number = 0;
  3254. private FIX_VP_X: number = 180;
  3255. private FIX_VP_Y: number = 84;
  3256. isDraggable(index: number): boolean {
  3257. return index >= 0;
  3258. }
  3259. getRowEnd(item: number) {
  3260. if (item.toString() === '0') {
  3261. return 1;
  3262. } else {
  3263. return 0;
  3264. }
  3265. }
  3266. // [Start itemMove_start]
  3267. // itemMoveGrid(index: number, newIndex: number): void {
  3268. // if (!this.isDraggable(newIndex)) {
  3269. // return;
  3270. // }
  3271. // let tmp = this.videoLocalList.splice(index, 1);
  3272. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3273. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  3274. // }
  3275. isInLeft(index: number) {
  3276. return index % 2 == 0;
  3277. }
  3278. down(index: number): void {
  3279. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  3280. return;
  3281. }
  3282. this.offsetY -= this.FIX_VP_Y;
  3283. this.dragRefOffSetY += this.FIX_VP_Y;
  3284. this.itemMove(index, index + 1);
  3285. }
  3286. up(index: number): void {
  3287. if (!this.isDraggable(index - 2)) {
  3288. return;
  3289. }
  3290. this.offsetY += this.FIX_VP_Y;
  3291. this.dragRefOffSetY -= this.FIX_VP_Y;
  3292. this.itemMove(index, index - 1);
  3293. }
  3294. left(index: number): void {
  3295. if (this.isInLeft(index)) {
  3296. return;
  3297. }
  3298. if (!this.isDraggable(index - 1)) {
  3299. return;
  3300. }
  3301. this.offsetX += this.FIX_VP_X;
  3302. this.dragRefOffSetX -= this.FIX_VP_X;
  3303. this.itemMove(index, index - 1)
  3304. }
  3305. right(index: number): void {
  3306. if (!this.isInLeft(index)) {
  3307. return;
  3308. }
  3309. if (!this.isDraggable(index + 1)) {
  3310. return;
  3311. }
  3312. this.offsetX -= this.FIX_VP_X;
  3313. this.dragRefOffSetX += this.FIX_VP_X;
  3314. this.itemMove(index, index + 1)
  3315. }
  3316. private scroller: Scroller = new Scroller();
  3317. @State startIndex: number = 0
  3318. @State endIndex: number = 0
  3319. @State scaleValue: number = 1
  3320. @State pinchValue: number = 1
  3321. layoutOptionsForHeader: GridLayoutOptions = {
  3322. regularSize: [1, 1], // 只支持[1, 1]
  3323. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3324. };
  3325. @Builder
  3326. getGridView() {
  3327. Grid(this.scroller, this.layoutOptionsForHeader) {
  3328. GridItem() {
  3329. if (this.isShowCoverHeader()) {
  3330. this.coverHeader()
  3331. } else {
  3332. this.listViewTitle()
  3333. }
  3334. }
  3335. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3336. GridItem() {
  3337. Stack({ alignContent: Alignment.Center }) {
  3338. this.MusicItemGrid(item, index)
  3339. }
  3340. }
  3341. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3342. {
  3343. preview: MenuPreviewMode.IMAGE,
  3344. previewAnimationOptions: { scale: [0.8, 1.0] },
  3345. })
  3346. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3347. {
  3348. preview: MenuPreviewMode.IMAGE,
  3349. previewAnimationOptions: { scale: [0.8, 1.0] },
  3350. })
  3351. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3352. TransitionEffect.scale({ x: 0, y: 0 })))
  3353. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3354. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3355. .zIndex(this.dragItem === index ? 1 : 0)
  3356. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3357. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  3358. //长按拖动代码
  3359. // .gesture(
  3360. // GestureGroup(GestureMode.Sequence,
  3361. // LongPressGesture({ repeat: true })
  3362. // .onAction(() => {
  3363. // this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3364. // this.scaleItem = index;
  3365. // })
  3366. // })
  3367. // .onActionEnd(() => {
  3368. // this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3369. // this.scaleItem = -1;
  3370. // })
  3371. // }),
  3372. // PanGesture({ fingers: 1, direction: null, distance: 0 })
  3373. // .onActionStart(() => {
  3374. // this.dragItem = index;
  3375. // this.dragRefOffSetX = 0;
  3376. // this.dragRefOffSetY = 0;
  3377. // })
  3378. // .onActionUpdate((event: GestureEvent) => {
  3379. // this.offsetX = event.offsetX - this.dragRefOffSetX;
  3380. // this.offsetY = event.offsetY - this.dragRefOffSetY;
  3381. // this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3382. // let index = this.videoLocalList.indexOf(item);
  3383. // if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3384. // this.down(index);
  3385. // } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3386. // this.up(index);
  3387. // } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3388. // this.right(index);
  3389. // } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3390. // this.left(index);
  3391. // }
  3392. // })
  3393. //
  3394. //
  3395. // // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  3396. // // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  3397. // // }
  3398. //
  3399. //
  3400. // })
  3401. // .onActionEnd(() => {
  3402. // this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3403. // this.dragItem = -1;
  3404. // })
  3405. // this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3406. // this.scaleItem = -1;
  3407. // })
  3408. // })
  3409. // )
  3410. // .onCancel(() => {
  3411. // this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3412. // this.dragItem = -1;
  3413. // })
  3414. // this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3415. // this.scaleItem = -1;
  3416. // })
  3417. // })
  3418. // )
  3419. // [End gesture_start]
  3420. // [EndExclude GridItem_start]
  3421. }, (item: VideoItem) => item.filePath)
  3422. }
  3423. .width(this.isShowHeader ? '100%' : '94%')
  3424. .height('100%')
  3425. .editMode(true)
  3426. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3427. .animation({ duration: 500, curve: Curve.Ease }))
  3428. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3429. .margin({
  3430. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3431. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3432. })
  3433. .layoutWeight(1)
  3434. .scrollBar(BarState.Off)
  3435. .supportAnimation(true)
  3436. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3437. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3438. .columnsTemplate(
  3439. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3440. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3441. )
  3442. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3443. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3444. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3445. .gesture(PinchGesture({ fingers: 2 })
  3446. .onActionEnd((event: GestureEvent) => {
  3447. this.setGridTwoFingers()
  3448. })
  3449. .onActionUpdate(e => {
  3450. this.scaleValue = this.pinchValue * e.scale
  3451. })
  3452. .onActionStart(e => {
  3453. }))
  3454. .enableScrollInteraction(true)
  3455. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3456. .onScrollIndex((start: number, end: number) => {
  3457. this.startIndex = start
  3458. this.endIndex = end
  3459. })
  3460. .onScrollFrameBegin((offset: number) => {
  3461. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3462. // if (this.isPhoneLan()) {
  3463. // this.setBarHeightHide(offset)
  3464. // } else
  3465. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3466. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3467. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3468. if (this.isScrollHide) {
  3469. this.setBarHeightHide2(offset)
  3470. } else {
  3471. this.setBarHeightNormal()
  3472. }
  3473. } else {
  3474. this.setBarHeightHide(offset)
  3475. }
  3476. return { offsetRemain: offset };
  3477. })
  3478. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3479. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3480. .onDrop((event?: DragEvent) => {
  3481. try {
  3482. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3483. if (dragData !== undefined) {
  3484. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3485. if (records.length > 0) {
  3486. for (let i = 0; i < records.length; i++) {
  3487. let types = records[i].getTypes();
  3488. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3489. const fileUriUds =
  3490. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3491. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3492. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3493. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3494. this.targetFile = fileUriUds.oriUri;
  3495. this.saveVideoDatas([this.targetFile])
  3496. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3497. }
  3498. }
  3499. }
  3500. } else {
  3501. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3502. }
  3503. } else {
  3504. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3505. }
  3506. } catch (error) {
  3507. const err = error as BusinessError;
  3508. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3509. }
  3510. })
  3511. }
  3512. @State targetFile: string = '';
  3513. setGridTwoFingers() {
  3514. this.pinchValue = this.scaleValue;
  3515. Logger.info('this.pinchValue = ' + this.pinchValue);
  3516. if (this.pinchValue >= 1) {
  3517. this.twoFingerType++
  3518. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3519. if (this.twoFingerType > 3) {
  3520. this.twoFingerType = 3
  3521. }
  3522. } else {
  3523. this.twoFingerType--
  3524. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3525. if (this.twoFingerType < 1) {
  3526. this.twoFingerType = 3
  3527. this.isGridMusic = false
  3528. }
  3529. }
  3530. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3531. this.pinchValue = 1;
  3532. this.scaleValue = 1;
  3533. }
  3534. @State longItemFilePath: string = ''
  3535. @State tempLyricContent: string = ''
  3536. @Builder
  3537. private MusicItemGrid(item: VideoItem, index: number) {
  3538. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3539. Stack() {
  3540. Column() {
  3541. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3542. .height(this.getGridHeight())
  3543. .width(this.getGridWight())
  3544. .draggable(false)
  3545. .interpolation(ImageInterpolation.Medium)// 用于重采样后的抗锯齿
  3546. .autoResize(true) // 重采样,可减少内存占用
  3547. .alt($r('app.media.ic_avatar2'))
  3548. .clip(true)
  3549. .borderRadius({
  3550. topLeft: 12,
  3551. topRight: 12,
  3552. bottomLeft: 0,
  3553. bottomRight: 0
  3554. })
  3555. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3556. height: this.isCoverOpacity() ? '95%' : '88%',
  3557. dragBar: true,
  3558. onDisappear: () => {
  3559. this.longItemFilePath = '';
  3560. this.tempLyricContent = ''
  3561. },
  3562. showClose: true,
  3563. preferType: SheetType.CENTER ,
  3564. title: { title: '编辑信息' }
  3565. })
  3566. .draggable(false)
  3567. .opacity(this.opacityItem)// 绑定透明度
  3568. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3569. // .animation({ duration: 500, curve: Curve.Ease }))
  3570. .animation({
  3571. duration: 666,
  3572. curve: 'ease-in-out' // 可选动画曲线
  3573. })
  3574. .margin({
  3575. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3576. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3577. })
  3578. Column() {
  3579. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3580. .fontSize(this.twoFingerType == 1 ? 14 : this.twoFingerType == 2 ? 16 : 18)
  3581. .maxLines(1)
  3582. .fontWeight(FontWeight.Bold)
  3583. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3584. .animation({
  3585. duration: 555,
  3586. curve: 'Linear',
  3587. })
  3588. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3589. height: '95%',
  3590. dragBar: true,
  3591. showClose: true,
  3592. onDisappear: () => {
  3593. this.longItemFilePathDetail = '';
  3594. },
  3595. blurStyle:BlurStyle.Thin,
  3596. backgroundColor:Color.Transparent,
  3597. preferType: SheetType.CENTER ,
  3598. title: { title: '详情' }
  3599. })
  3600. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3601. $r('app.color.text_color'))
  3602. Column() {
  3603. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3604. .fontSize(11)
  3605. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3606. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3607. .fontColor($r('app.color.text_color'))
  3608. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3609. .fontSize(11)
  3610. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3611. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3612. .fontColor($r('app.color.text_color'))
  3613. Row(){
  3614. Column(){
  3615. Text(item.md5Str?.includes('Lossless')?
  3616. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3617. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3618. .padding({ top: 3,right:6,left:6,bottom:3 })
  3619. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3620. $r('app.color.text_color'))
  3621. .fontWeight(500)
  3622. .borderRadius(12)
  3623. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3624. .backgroundColor('#FFC107')
  3625. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  3626. }
  3627. .margin({ top: 2 ,right:6})
  3628. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3629. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3630. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3631. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3632. .maxLines(1)
  3633. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3634. .margin({ top: 2})
  3635. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3636. || item.type == CommonConstants.TYPE_IS_ALBUM
  3637. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3638. .fontWeight(FontWeight.Medium)
  3639. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3640. $r('app.color.text_color'))
  3641. }
  3642. }
  3643. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3644. }
  3645. // .bindPopup(this.longItemFilePath === item.filePath, {
  3646. // builder: this.MenuBuilder(item, index, item.filePath),
  3647. // placement: Placement.Top,
  3648. // // autoCancel: true,
  3649. // mask: { color: '#33000000' },
  3650. // // popupColor: Color.Yellow,
  3651. // enableArrow: false, //是否显示箭头
  3652. // showInSubWindow: false,
  3653. // onStateChange: (e) => {
  3654. // if (!e.isVisible) {
  3655. // this.longItemFilePath = ''
  3656. // this.tempLyricContent = ''
  3657. // }
  3658. // }
  3659. // })
  3660. //
  3661. // .gesture(LongPressGesture()
  3662. // .onAction(async () => {
  3663. // //如果是专辑和艺术家的首页,不能长按
  3664. // if ((this.modeType === 2 || this.modeType == 3) && !this.isCanBack) {
  3665. // return
  3666. // }
  3667. // //如果是我的收藏 最近播放等也不能长按
  3668. // if (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3669. // item.name === LocalMusic.STR_HISTORY_MUSIC
  3670. // ) {
  3671. // return
  3672. // }
  3673. // this.longItemFilePath = item.filePath
  3674. // this.tempLyricContent = await this.getLyricContent(item)
  3675. // LogUtil.info('长按this.tempLyricContent = ' + this.tempLyricContent)
  3676. // })
  3677. // .onActionEnd((event: GestureEvent) => {
  3678. //
  3679. // })
  3680. // )
  3681. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 55 : 42)
  3682. .width(this.getGridWight())
  3683. .justifyContent(FlexAlign.Center)
  3684. .margin({
  3685. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3686. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3687. })
  3688. }
  3689. .width(this.getGridWight())
  3690. .borderRadius(12)
  3691. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3692. .backgroundImageSize({ height: '100%', width: '100%' })
  3693. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3694. .animation({ curve: Curve.Sharp, duration: 300 })
  3695. Checkbox({ name: 'checkbox' + index })
  3696. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3697. .selectedColor(this.themeColor)
  3698. .shape(CheckBoxShape.CIRCLE)
  3699. .opacity(this.isMultiSelect ? 1 : 0)
  3700. .animation({
  3701. duration: 666,
  3702. curve: 'Smooth' // 可选动画曲线
  3703. })
  3704. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3705. Visibility.None)
  3706. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3707. .margin({ left: 20, top: 8, bottom: 8 })
  3708. .width(38)
  3709. .height(38)
  3710. }
  3711. }
  3712. .backgroundColor(Color.Transparent)
  3713. .width('100%')
  3714. .padding({ top: 15 })
  3715. .height(this.getGridAllHeight())
  3716. .onClick(() => {
  3717. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3718. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3719. this.handleFileSelection(item, !isChecked);
  3720. } else {
  3721. this.doPlay(item, index)
  3722. }
  3723. })
  3724. }
  3725. getGridAllHeight() {
  3726. let heightG = 222
  3727. switch (this.twoFingerType) {
  3728. case 1:
  3729. heightG = 118
  3730. break;
  3731. case 2:
  3732. heightG = 168
  3733. break;
  3734. case 3:
  3735. heightG = 222
  3736. break;
  3737. }
  3738. return heightG
  3739. }
  3740. getGridHeight() {
  3741. let heightG = 150
  3742. switch (this.twoFingerType) {
  3743. case 1:
  3744. heightG = 55
  3745. break;
  3746. case 2:
  3747. heightG = 100
  3748. break;
  3749. case 3:
  3750. heightG = 150
  3751. break;
  3752. }
  3753. return heightG
  3754. }
  3755. getGridWight() {
  3756. let wightG = 158
  3757. switch (this.twoFingerType) {
  3758. case 1:
  3759. wightG = 80
  3760. break;
  3761. case 2:
  3762. wightG = 110
  3763. break;
  3764. case 3:
  3765. wightG = 158
  3766. break;
  3767. }
  3768. return wightG
  3769. }
  3770. @State isShowDetail:boolean = false
  3771. // @State isShowDetailGrid:boolean = false
  3772. // @State isShowEditGrid:boolean = false
  3773. @State longItemFilePathDetail:string =''
  3774. @Builder
  3775. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3776. if(
  3777. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3778. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3779. item.name === LocalMusic.STR_HISTORY_MUSIC)
  3780. ){
  3781. //如果是专辑和艺术家的首页,不能长按
  3782. //如果是我的收藏 最近播放等也不能长按
  3783. }else{
  3784. Scroll() {
  3785. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3786. Menu() {
  3787. MenuItem({
  3788. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3789. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3790. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3791. })
  3792. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3793. .onClick(() => {
  3794. if (item) {
  3795. this.doFav(item)
  3796. }
  3797. this.longItemFilePath = ''
  3798. })
  3799. MenuItem({
  3800. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3801. content: '下一首播放'
  3802. })
  3803. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3804. .onClick(() => {
  3805. this.addToNextPlay(item);
  3806. this.longItemFilePath = ''
  3807. })
  3808. MenuItem({
  3809. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3810. content: '编辑信息'
  3811. })
  3812. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3813. height: this.isCoverOpacity() ? '95%' : '88%',
  3814. dragBar: true,
  3815. showClose: true,
  3816. preferType: SheetType.CENTER ,
  3817. title: { title: '编辑信息' }
  3818. })
  3819. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3820. .onClick(async() => {
  3821. this.tempLyricContent = await this.getLyricContent(item);
  3822. // console.info('onecold 长按this.tempLyricContent' +this.tempLyricContent)
  3823. if(this.isGridMusic){
  3824. this.longItemFilePath = item.filePath
  3825. }else{
  3826. this.isShowEdit = !this.isShowEdit;
  3827. }
  3828. })
  3829. MenuItem({
  3830. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  3831. content: $r('app.string.select_all')
  3832. })
  3833. .onClick(() => {
  3834. this.isMultiSelect = !this.isMultiSelect
  3835. this.longItemFilePath = ''
  3836. })
  3837. MenuItem({
  3838. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3839. content: $r('app.string.rename')
  3840. })
  3841. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3842. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3843. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3844. .onClick(() => {
  3845. this.showReNameDialog(item, index + '', filePath)
  3846. this.longItemFilePath = ''
  3847. })
  3848. MenuItem({
  3849. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3850. content: $r('app.string.delete')
  3851. })
  3852. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3853. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3854. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3855. .onClick(() => {
  3856. this.showWarnIsDeleteFile(item, index + '', filePath)
  3857. this.longItemFilePath = ''
  3858. })
  3859. MenuItem({
  3860. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3861. content: $r('app.string.detail')
  3862. })
  3863. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3864. height:'95%',
  3865. dragBar: true,
  3866. showClose: true,
  3867. blurStyle:BlurStyle.Thin,
  3868. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3869. backgroundColor:Color.Transparent,
  3870. title: { title: '详情信息' }
  3871. })
  3872. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3873. .onClick(() => {
  3874. if(this.isGridMusic){
  3875. this.longItemFilePathDetail = item.filePath
  3876. }else{
  3877. this.isShowDetail = !this.isShowDetail
  3878. }
  3879. })
  3880. MenuItem({
  3881. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3882. content: $r('app.string.share')
  3883. })
  3884. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3885. .onClick(() => {
  3886. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3887. this.longItemFilePath = ''
  3888. })
  3889. }
  3890. .font({ size: 15, weight: FontWeight.Normal })
  3891. }
  3892. .width(180)
  3893. }
  3894. .height('auto')
  3895. }
  3896. }
  3897. private listMaxScrollOffsetY: number = 0
  3898. @State selectedIndex: number = -1
  3899. setlistTwoFingers() {
  3900. this.pinchValue = this.scaleValue;
  3901. Logger.info('this.pinchValue = ' + this.pinchValue);
  3902. if (this.pinchValue >= 1) {
  3903. this.twoFingerType++
  3904. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3905. if (this.twoFingerType > 3) {
  3906. this.twoFingerType = 1
  3907. this.isGridMusic = true
  3908. }
  3909. } else {
  3910. this.twoFingerType--
  3911. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3912. if (this.twoFingerType < 1) {
  3913. this.twoFingerType = 1
  3914. }
  3915. }
  3916. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3917. this.pinchValue = 1;
  3918. this.scaleValue = 1;
  3919. }
  3920. @Builder
  3921. getListView() {
  3922. List({ scroller: this.listScroller }) {
  3923. ListItemGroup({ header: this.coverHeader() }) {
  3924. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3925. ListItem() {
  3926. Column() {
  3927. if (item.type === CommonConstants.TYPE_IS_DIR
  3928. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3929. this.DirItem(item, index)
  3930. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3931. } else {
  3932. this.MusicItem(item, index)
  3933. }
  3934. }
  3935. .shadow(this.scaleItem === index ? {
  3936. radius: 70,
  3937. color: '#15000000',
  3938. offsetX: 0,
  3939. offsetY: 0
  3940. } :
  3941. {
  3942. radius: 0,
  3943. color: '#15000000',
  3944. offsetX: 0,
  3945. offsetY: 0
  3946. })
  3947. .animation({ curve: Curve.Sharp, duration: 300 })
  3948. }
  3949. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3950. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3951. .animation({ duration: 500 }),
  3952. TransitionEffect.scale({ x: 0, y: 0 })))
  3953. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3954. .swipeAction((
  3955. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3956. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3957. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3958. .onClick(() => {
  3959. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3960. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3961. this.handleFileSelection(item, !isChecked);
  3962. } else {
  3963. this.doPlay(item, index)
  3964. }
  3965. })
  3966. //拖动List关键代码开始
  3967. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3968. .zIndex(this.dragItem === index ? 1 : 0)
  3969. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3970. .gesture(
  3971. GestureGroup(GestureMode.Sequence,
  3972. LongPressGesture({ repeat: true })
  3973. .onAction((event?: GestureEvent) => {
  3974. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3975. this.scaleItem = index
  3976. })
  3977. })
  3978. .onActionEnd(() => {
  3979. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3980. this.scaleItem = -1
  3981. })
  3982. }),
  3983. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3984. .onActionStart(() => {
  3985. this.dragItem = index // 记录当前拖动项索引
  3986. this.dragRefOffset = 0 // 重置偏移基准
  3987. })
  3988. .onActionUpdate((event: GestureEvent) => {
  3989. this.offsetY = event.offsetY - this.dragRefOffset;
  3990. this.neighborItem = -1;
  3991. let indexA = this.videoLocalList.indexOf(item);
  3992. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3993. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3994. let value: number = 0;
  3995. if (this.offsetY < 0) {
  3996. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3997. this.neighborItem = indexA - 1;
  3998. this.neighborScale = 1 - value / 20;
  3999. } else if (this.offsetY > 0) {
  4000. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4001. this.neighborItem = indexA + 1;
  4002. this.neighborScale = 1 - value / 20;
  4003. }
  4004. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  4005. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4006. this.offsetY -= this.ITEM_INTV;
  4007. this.dragRefOffset += this.ITEM_INTV;
  4008. this.itemMove(indexA, indexA + 1);
  4009. });
  4010. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4011. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4012. this.offsetY += this.ITEM_INTV;
  4013. this.dragRefOffset -= this.ITEM_INTV;
  4014. this.itemMove(indexA, indexA - 1);
  4015. });
  4016. }
  4017. let curListOffset = this.listScroller.currentOffset()
  4018. // 获取手指信息
  4019. let fingerInfo = event.fingerList[0]
  4020. let clickPercentY =
  4021. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  4022. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  4023. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  4024. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  4025. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  4026. }
  4027. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  4028. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  4029. if (curListOffset.yOffset > scrollVelocity + 5) {
  4030. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  4031. }
  4032. }
  4033. })
  4034. .onActionEnd((event: GestureEvent) => {
  4035. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4036. this.dragItem = -1
  4037. this.neighborItem = -1
  4038. })
  4039. animateTo({
  4040. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4041. }, () => {
  4042. this.scaleItem = -1
  4043. })
  4044. })
  4045. )
  4046. .onCancel(() => {
  4047. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4048. this.dragItem = -1
  4049. this.neighborItem = -1
  4050. })
  4051. animateTo({
  4052. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4053. }, () => {
  4054. this.scaleItem = -1
  4055. })
  4056. })
  4057. ) //拖动List关键代码结束
  4058. }, (item: VideoItem) => item.filePath)
  4059. }
  4060. }
  4061. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4062. .gesture(PinchGesture({ fingers: 2 })
  4063. .onActionEnd((event: GestureEvent) => {
  4064. this.setlistTwoFingers()
  4065. })
  4066. .onActionUpdate(e => {
  4067. this.scaleValue = this.pinchValue * e.scale
  4068. })
  4069. .onActionStart(e => {
  4070. }))
  4071. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  4072. .margin({
  4073. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  4074. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+125)
  4075. })
  4076. .cachedCount(6)
  4077. .borderRadius(20)
  4078. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  4079. TransitionEffect.scale({ x: 0, y: 0 })))
  4080. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4081. // .animation({ duration: 500, curve: Curve.Ease }))
  4082. .layoutWeight(1)
  4083. .onScrollIndex((start) => {
  4084. this.selectedIndex = start
  4085. })
  4086. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  4087. .lanes(
  4088. new BreakpointType<number>({
  4089. sm: 1,
  4090. md: 2,
  4091. lg: 2,
  4092. xl: 3,
  4093. xxl: 4
  4094. }).getValue(this.currentBreakpoint),
  4095. new BreakpointType<number>({
  4096. sm: 0,
  4097. md: 12,
  4098. lg: 12,
  4099. xl: 16,
  4100. xxl: 20
  4101. }).getValue(this.currentBreakpoint)
  4102. )
  4103. .onAreaChange((oldValue: Area, newValue: Area) => {
  4104. this.listArea = newValue
  4105. if (this.twoFingerType == 3) {
  4106. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  4107. } else if (this.twoFingerType == 2) {
  4108. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  4109. } else if (this.twoFingerType == 1) {
  4110. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  4111. }
  4112. })
  4113. .onScrollFrameBegin((offset: number) => {
  4114. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  4115. // if (this.isPhoneLan()) {
  4116. // this.setBarHeightHide(offset)
  4117. // } else
  4118. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4119. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4120. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4121. if (this.isScrollHide) {
  4122. this.setBarHeightHide2(offset)
  4123. } else {
  4124. this.setBarHeightNormal()
  4125. }
  4126. } else {
  4127. this.setBarHeightHide(offset)
  4128. }
  4129. return { offsetRemain: offset };
  4130. })
  4131. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  4132. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4133. .onDrop((event?: DragEvent) => {
  4134. try {
  4135. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4136. if (dragData !== undefined) {
  4137. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4138. if (records.length > 0) {
  4139. for (let i = 0; i < records.length; i++) {
  4140. let types = records[i].getTypes();
  4141. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4142. const fileUriUds =
  4143. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4144. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4145. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4146. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4147. this.targetFile = fileUriUds.oriUri;
  4148. this.saveVideoDatas([this.targetFile])
  4149. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4150. }
  4151. }
  4152. }
  4153. } else {
  4154. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4155. }
  4156. } else {
  4157. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4158. }
  4159. } catch (error) {
  4160. const err = error as BusinessError;
  4161. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4162. }
  4163. })
  4164. }
  4165. setBarHeightNormal() {
  4166. this.hideDone = false;
  4167. this.getUIContext().animateTo({
  4168. duration: 300
  4169. }, () => {
  4170. this.bottomBarHeight = 55 + 0;
  4171. this.topBarHeight = 50 + 0;
  4172. this.barOpacity = 1;
  4173. this.barBottomOpacity = 1
  4174. this.currentYOffset = 0;
  4175. this.isHiding = false;
  4176. });
  4177. }
  4178. setBarHeightHide(offset: number) {
  4179. if (offset > 0 && !this.hideDone) {
  4180. this.currentYOffset += offset;
  4181. if (this.currentYOffset <= 100) {
  4182. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  4183. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4184. this.barOpacity = 1 - this.currentYOffset / 100;
  4185. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  4186. } else {
  4187. this.topBarHeight = 0;
  4188. this.bottomBarHeight = 0;
  4189. this.barBottomOpacity = 0
  4190. this.barOpacity = 0;
  4191. this.hideDone = true;
  4192. }
  4193. this.isHiding = true;
  4194. }
  4195. if (offset < 0 && this.isHiding) {
  4196. this.hideDone = false;
  4197. this.getUIContext().animateTo({
  4198. duration: 300
  4199. }, () => {
  4200. this.bottomBarHeight = 55 + 0;
  4201. this.topBarHeight = 50 + 0;
  4202. this.barOpacity = 1;
  4203. this.barBottomOpacity = 1
  4204. this.currentYOffset = 0;
  4205. this.isHiding = false;
  4206. });
  4207. }
  4208. }
  4209. //这个方法没隐藏bottomBar,只隐藏topbar
  4210. setBarHeightHide2(offset: number) {
  4211. if (offset > 0 && !this.hideDone) {
  4212. this.currentYOffset += offset;
  4213. if (this.currentYOffset <= 100) {
  4214. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4215. this.barOpacity = 1 - this.currentYOffset / 100;
  4216. } else {
  4217. this.topBarHeight = 0;
  4218. this.barOpacity = 0;
  4219. this.hideDone = true;
  4220. }
  4221. this.isHiding = true;
  4222. }
  4223. if (offset < 0 && this.isHiding) {
  4224. this.hideDone = false;
  4225. this.getUIContext().animateTo({
  4226. duration: 300
  4227. }, () => {
  4228. this.topBarHeight = 50 + 0;
  4229. this.barOpacity = 1;
  4230. this.currentYOffset = 0;
  4231. this.isHiding = false;
  4232. });
  4233. }
  4234. }
  4235. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  4236. switch (item.type) {
  4237. case CommonConstants.TYPE_IS_DIR:
  4238. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  4239. let offsetB = 0
  4240. if (this.isGridMusic) {
  4241. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4242. let cur = this.scroller.currentOffset()
  4243. if (cur && typeof cur.yOffset === 'number') {
  4244. offsetB = cur.yOffset
  4245. }
  4246. }
  4247. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  4248. } else {
  4249. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4250. let cur = this.listScroller.currentOffset()
  4251. if (cur && typeof cur.yOffset === 'number') {
  4252. offsetB = cur.yOffset
  4253. }
  4254. }
  4255. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  4256. }
  4257. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  4258. this.showVerifyDialog()
  4259. this.currentTitleName = '私密音频'
  4260. this.currentTitleCover = $r('app.media.ic_avatar5')
  4261. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  4262. this.titleBarModel.setTitleName('最近播放')
  4263. this.currentTitleCover = $r('app.media.ic_avatar2')
  4264. this.currentTitleName = '最近播放'
  4265. //加载动画效果
  4266. this.updateListData(this.historyList, true)
  4267. // this.videoLocalList = this.historyList
  4268. if (ArrayUtil.isEmpty(this.historyList)) {
  4269. ToastUtil.showToast('最近播放记录空空如也')
  4270. } else {
  4271. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  4272. }
  4273. this.isHistory = true
  4274. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4275. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  4276. this.titleBarModel.setTitleName('我的收藏')
  4277. this.currentTitleName = '我的收藏'
  4278. this.currentTitleCover = $r('app.media.ic_avatar1')
  4279. //加载动画效果
  4280. this.updateListData(this.favList)
  4281. if (ArrayUtil.isEmpty(this.favList)) {
  4282. ToastUtil.showToast('无音乐收藏记录')
  4283. } else {
  4284. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  4285. }
  4286. this.isFavMusic = true
  4287. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4288. } else {
  4289. this.currentTitleName = item.name
  4290. this.currentPath = item.filePath
  4291. this.currentTitleCover = $r('app.media.ic_avatar5')
  4292. this.getSortedFiles(this.currentPath)
  4293. }
  4294. //进入歌单的时候的滚动位置在顶部
  4295. if (this.isGridMusic) {
  4296. this.scroller.scrollToIndex(0)
  4297. }
  4298. setTimeout(() => {
  4299. if (this.modeType == 0) {
  4300. if (!this.isGridMusic) {
  4301. this.listScroller.scrollToIndex(0)
  4302. }
  4303. }
  4304. }, 200)
  4305. break;
  4306. case CommonConstants.TYPE_IS_ARTIST:
  4307. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  4308. let offsetA = 0
  4309. if (this.isGridMusic) {
  4310. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4311. let cur = this.scroller.currentOffset()
  4312. if (cur && typeof cur.yOffset === 'number') {
  4313. offsetA = cur.yOffset
  4314. }
  4315. }
  4316. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  4317. } else {
  4318. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4319. let cur = this.listScroller.currentOffset()
  4320. if (cur && typeof cur.yOffset === 'number') {
  4321. offsetA = cur.yOffset
  4322. }
  4323. }
  4324. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  4325. }
  4326. let mList = this.artistMap.get(item.name)
  4327. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  4328. Utility.doSortListAscending(mList)
  4329. this.isCanBack = true
  4330. this.titleBarModel.setTitleName(item.name)
  4331. this.currentTitleName = '艺术家:' + item.name
  4332. if (item.pixelMapPath) {
  4333. this.currentTitleCover = item.pixelMapPath
  4334. }
  4335. this.updateListData(mList)
  4336. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4337. }
  4338. //进入歌单的时候的滚动位置在顶部
  4339. if (this.isGridMusic) {
  4340. this.scroller.scrollToIndex(0)
  4341. }
  4342. break;
  4343. case CommonConstants.TYPE_IS_ALBUM:
  4344. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  4345. let offset = 0
  4346. if (this.isGridMusic) {
  4347. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4348. let cur = this.scroller.currentOffset()
  4349. if (cur && typeof cur.yOffset === 'number') {
  4350. offset = cur.yOffset
  4351. }
  4352. }
  4353. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  4354. } else {
  4355. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4356. let cur = this.listScroller.currentOffset()
  4357. if (cur && typeof cur.yOffset === 'number') {
  4358. offset = cur.yOffset
  4359. }
  4360. }
  4361. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4362. }
  4363. let albumList = this.albumMap.get(item.name)
  4364. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4365. Utility.doSortListAscending(albumList)
  4366. this.isCanBack = true
  4367. this.titleBarModel.setTitleName(item.name)
  4368. this.currentTitleName = '专辑:' + item.name
  4369. if (item.pixelMapPath) {
  4370. this.currentTitleCover = item.pixelMapPath
  4371. }
  4372. this.updateListData(albumList)
  4373. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4374. this.mScrollMap.set(item.name, this.selectedIndex)
  4375. }
  4376. //进入歌单的时候的滚动位置在顶部
  4377. if (this.isGridMusic) {
  4378. this.scroller.scrollToIndex(0)
  4379. }
  4380. break;
  4381. case CommonConstants.TYPE_IS_CSJAD:
  4382. return
  4383. case CommonConstants.TYPE_LOCAL:
  4384. // 移除自动停止逻辑,让UnifiedPlayerService处理播放器状态管理
  4385. // if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4386. // this.stop();
  4387. // }
  4388. // 检查是否正在投播
  4389. if (this.isCurrentlyCasting()) {
  4390. // 更新当前歌曲信息
  4391. this.curIndex = index as number;
  4392. this.currentSong = item;
  4393. this.videoUrl = this.currentSong.filePath;
  4394. this.artist = this.currentSong.artist;
  4395. this.name = this.currentSong.name;
  4396. this.cover = this.currentSong.pixelMapPath;
  4397. this.changeCasting();
  4398. return;
  4399. }
  4400. if (isFromSonPlayList) { //点击来自右下角的播放列表
  4401. this.currentSong = item
  4402. if (index !== undefined) {
  4403. this.curIndex = index
  4404. }
  4405. } else {
  4406. // 点击文件列表中的歌曲,需要判断是否要创建新的播放列表
  4407. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4408. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4409. // 检查当前播放列表是否包含这首歌
  4410. const currentSongIndex = this.songList.findIndex(song => song.filePath === item.filePath);
  4411. if (currentSongIndex >= 0 && ArrayUtil.isNotEmpty(this.songList)) {
  4412. // 如果当前播放列表已经包含这首歌,使用现有播放列表
  4413. this.curIndex = currentSongIndex;
  4414. this.currentSong = this.songList[this.curIndex];
  4415. } else {
  4416. // 如果当前播放列表不包含这首歌,或者没有播放列表,则创建新的
  4417. this.songList = globalVideoList;
  4418. this.sonDataSource.pushArrayData(this.songList);
  4419. this.currentSong = globalVideoList[this.curIndex];
  4420. }
  4421. }
  4422. this.videoUrl = this.currentSong.filePath
  4423. this.name = this.currentSong.name
  4424. this.cover = this.currentSong.pixelMapPath
  4425. this.artist = this.currentSong.artist
  4426. // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  4427. this.oldSeconds = 0;
  4428. this.currentTime = "00:00";
  4429. this.currentTime = "00:00";
  4430. this.lastSongPath = this.currentSong.filePath;
  4431. this.justSwitched = true; // 标记歌曲刚刚切换
  4432. // 同步播放列表到UnifiedPlayerService
  4433. this.syncPlaylistToService();
  4434. this.startPlayOrResumePlay()
  4435. break;
  4436. }
  4437. }
  4438. @Builder
  4439. PlayController() {
  4440. Column() {
  4441. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4442. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4443. Row() {
  4444. Row() {
  4445. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  4446. Column() {
  4447. Text(this.currentSong?.name)
  4448. .fontSize(16)
  4449. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4450. .maxLines(1)
  4451. .fontColor($r('app.color.text_color'))
  4452. .fontWeight(500)
  4453. Row() {
  4454. Text(this.currentSong?.artist)
  4455. .margin({ top: 2 })
  4456. .fontSize(13)
  4457. .maxLines(1)
  4458. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4459. .fontColor($r('app.color.text_color'))
  4460. }
  4461. }
  4462. .alignItems(HorizontalAlign.Start)
  4463. .margin({ right: 22 })
  4464. }
  4465. .padding({ right: 18 })
  4466. .layoutWeight(1)
  4467. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4468. .onClick(() => {
  4469. if (ArrayUtil.isNotEmpty(this.songList)) {
  4470. this.isShowPlay = true;
  4471. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4472. this.initLyric(lyricPath);
  4473. this.startAutoHide()
  4474. } else {
  4475. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4476. }
  4477. })
  4478. Row() {
  4479. Image($r('app.media.hm_previous'))
  4480. .height(28)
  4481. .width(28)
  4482. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4483. .margin({ left: 8, right: 16 })
  4484. .fillColor(this.themeColor)
  4485. .displayPriority(2)
  4486. .onClick(() => {
  4487. if (ArrayUtil.isNotEmpty(this.songList)) {
  4488. this.playPrevious()
  4489. } else {
  4490. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4491. }
  4492. })
  4493. //播放进度条
  4494. Stack() {
  4495. Progress({
  4496. value: Math.floor(this.progressValue),
  4497. type: ProgressType.Ring,
  4498. })
  4499. .color(this.themeColor)// 进度条前景色为灰色
  4500. .backgroundColor($r('app.color.index_background'))
  4501. .height(40)
  4502. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4503. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4504. .height(38)
  4505. .width(38)
  4506. .displayPriority(3)
  4507. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4508. .fillColor(this.themeColor)
  4509. .onClick(() => {
  4510. if (ArrayUtil.isNotEmpty(this.songList)) {
  4511. this.playOrPause()
  4512. } else {
  4513. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4514. }
  4515. })
  4516. }
  4517. Image($r('app.media.hm_next'))
  4518. .height(28)
  4519. .width(28)
  4520. .margin({
  4521. right: 16,
  4522. left: 16
  4523. })
  4524. .fillColor(this.themeColor)
  4525. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4526. .displayPriority(2)
  4527. .onClick(() => {
  4528. if (ArrayUtil.isNotEmpty(this.songList)) {
  4529. this.playNext()
  4530. } else {
  4531. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4532. }
  4533. })
  4534. Image($r('app.media.hm_playlist'))
  4535. .height(28)
  4536. .width(28)
  4537. .displayPriority(1)
  4538. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4539. .fillColor(this.themeColor)
  4540. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4541. height: '95%',
  4542. dragBar: true,
  4543. showClose: true,
  4544. blurStyle: BlurStyle.Thin,
  4545. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4546. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4547. title: {
  4548. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4549. + `(${this.songList.length}首)`
  4550. }
  4551. })
  4552. .onClick(() => {
  4553. if (ArrayUtil.isNotEmpty(this.songList)) {
  4554. this.isShowSheet = !this.isShowSheet;
  4555. this.isFrontWhite = false
  4556. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4557. setTimeout(() => {
  4558. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  4559. }, 123)
  4560. } else {
  4561. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4562. }
  4563. })
  4564. }
  4565. }
  4566. .width('100%')
  4567. .height(this.bottomBarHeight)
  4568. .justifyContent(FlexAlign.Center)
  4569. .hitTestBehavior(HitTestMode.Transparent)
  4570. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4571. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4572. // modalTransition: ModalTransition.DEFAULT,
  4573. transition: AnimationHelper.transitionInDown(666),
  4574. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4575. })
  4576. .padding({
  4577. left: 16,
  4578. right: 16
  4579. })
  4580. Line()
  4581. .width('100%')
  4582. .height(25)
  4583. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4584. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4585. }
  4586. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4587. }
  4588. @State isFrontWhite: boolean = false
  4589. //播放列表布局
  4590. @Builder
  4591. PlayListSheet() {
  4592. Column() {
  4593. this.PlayList()
  4594. }
  4595. .width('100%')
  4596. .height('100%')
  4597. .onAppear(() => {
  4598. // 播放列表显示时刷新封面信息
  4599. this.refreshPlaylistCovers();
  4600. })
  4601. }
  4602. @State titleStr: string = ''
  4603. @State ablumStr: string = ''
  4604. @State artistStr: string = ''
  4605. @State lyricConStr: string = ''
  4606. @State currentEditItem: string = ''
  4607. doUpdateData() {
  4608. setTimeout(() => {
  4609. if (this.modeType === 0) {
  4610. this.deleteCache(this.currentPath)
  4611. this.getSortedFiles(this.currentPath)
  4612. }
  4613. workerInstance.postMessage({ code: 2, data: this.context });
  4614. workerInstance.postMessage({ code: 3, data: this.context });
  4615. workerInstance.postMessage({ code: 4, data: this.context });
  4616. }, 999)
  4617. }
  4618. //编辑信息
  4619. doEdit(item: VideoItem) {
  4620. if (!item) {
  4621. return
  4622. }
  4623. if (StrUtil.isEmpty(this.titleStr)) {
  4624. ToastUtil.showToast('标题不能为空')
  4625. return
  4626. }
  4627. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  4628. (success: boolean, error?: string) => {
  4629. // this.isShowEdit = false
  4630. if(this.isGridMusic){
  4631. this.longItemFilePath =''
  4632. }else{
  4633. this.isShowEdit = false
  4634. }
  4635. if (success) {
  4636. console.log(" onecold 编辑信息成功,数据库已同步");
  4637. ToastUtil.showToast('保存成功')
  4638. this.isShowMoreView = false
  4639. this.name = this.titleStr
  4640. if (item.filePath == this.currentSong?.filePath) {
  4641. this.currentSong.name = this.titleStr
  4642. this.artist = this.artistStr
  4643. this.currentSong.artist = this.artistStr
  4644. this.currentSong.album = this.ablumStr
  4645. }
  4646. this.doUpdateData()
  4647. } else {
  4648. ToastUtil.showToast('保存失败' + error?.toString())
  4649. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4650. }
  4651. });
  4652. let doChangeLyric = false
  4653. if (item.filePath == this.currentSong?.filePath) {
  4654. if (this.lyricConStr !== this.lyricContent) {
  4655. doChangeLyric = true
  4656. }
  4657. } else if (this.lyricConStr !== this.tempLyricContent) {
  4658. doChangeLyric = true
  4659. }
  4660. if (doChangeLyric) {
  4661. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4662. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4663. let isJiaMi = false;
  4664. let realLyricPath = lyricPath
  4665. if (FileUtil.accessSync(jiaMilyricPath)) {
  4666. isJiaMi = true
  4667. realLyricPath = jiaMilyricPath
  4668. console.info("onecold doEdit找到加密本地歌词 ");
  4669. } else {
  4670. isJiaMi = false
  4671. realLyricPath = lyricPath
  4672. console.info("onecold doEdit本地歌词 ");
  4673. }
  4674. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  4675. }
  4676. }
  4677. updateLyricToDB() {
  4678. }
  4679. @Builder
  4680. editSheet(item: VideoItem) {
  4681. Scroll() {
  4682. Column() {
  4683. this.editDetail(item)
  4684. }
  4685. }
  4686. .width('100%')
  4687. .height('100%')
  4688. }
  4689. @Builder
  4690. editDetail(item: VideoItem) {
  4691. Column() {
  4692. if (item) {
  4693. Row() {
  4694. Stack() {
  4695. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4696. item.pixelMapPath)
  4697. .fillColor(this.themeColor)
  4698. .height(33)
  4699. .width(33)
  4700. .borderRadius('100%')
  4701. .clip(true)
  4702. .opacity(this.opacityItem)// 绑定透明度
  4703. .margin({ left: 20 })
  4704. }
  4705. .width('15%')
  4706. Row() {
  4707. Column() {
  4708. Text(item.name)
  4709. .fontSize(14)
  4710. .maxLines(1)
  4711. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4712. .animation({
  4713. duration: 555,
  4714. curve: 'Linear',
  4715. })
  4716. .fontColor(this.themeColor)
  4717. .margin({ left: 10 })
  4718. Row() {
  4719. Text(item.artist)
  4720. .fontSize(11)
  4721. .maxLines(1)
  4722. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4723. .padding({ top: 8 })
  4724. .fontColor(this.themeColor)
  4725. .margin({ left: 10 })
  4726. }
  4727. }
  4728. .height('100%')
  4729. .width(100)
  4730. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4731. .justifyContent(FlexAlign.Center)
  4732. .alignItems(HorizontalAlign.Start)
  4733. Button('本地封面')
  4734. .fontColor(Color.White)
  4735. .fontSize(12)
  4736. .height(38)
  4737. .width(88)
  4738. .backgroundColor(this.themeColor)
  4739. .stateEffect(true)
  4740. .margin({ right: 5, left: 12 })
  4741. .onClick(async () => {
  4742. this.goSelectImage(item)
  4743. })
  4744. Button('获取封面')
  4745. .fontColor(Color.White)
  4746. .fontSize(12)
  4747. .height(38)
  4748. .width(88)
  4749. .backgroundColor(this.themeColor)
  4750. .stateEffect(true)
  4751. .margin({ right: 12, left: 5 })
  4752. .onClick(async () => {
  4753. this.doSearchCover(item)
  4754. })
  4755. }
  4756. .height('100%')
  4757. .justifyContent(FlexAlign.Start)
  4758. .layoutWeight(1)
  4759. }
  4760. .width('100%')
  4761. .height(58)
  4762. Row() {
  4763. Text('标题:')
  4764. .fontSize(14)
  4765. .fontColor($r('app.color.text_color'))
  4766. .margin({ left: 22 })
  4767. TextInput({ text: item.name })
  4768. .height(40)
  4769. .maxLines(1)
  4770. .fontSize(14)
  4771. .layoutWeight(1)
  4772. .fontColor($r('app.color.text_color'))
  4773. .margin({ right: 20, left: 10 })
  4774. .onChange((val: string) => {
  4775. this.titleStr = val
  4776. })
  4777. }
  4778. .width('100%')
  4779. .margin({ top: 10, bottom: 10 })
  4780. .justifyContent(FlexAlign.Start)
  4781. Row() {
  4782. Text('艺术家:')
  4783. .fontSize(14)
  4784. .fontColor($r('app.color.text_color'))
  4785. .margin({ left: 22 })
  4786. TextInput({ text: item.artist })
  4787. .height(40)
  4788. .maxLines(1)
  4789. .fontSize(14)
  4790. .layoutWeight(1)
  4791. .fontColor($r('app.color.text_color'))
  4792. .margin({ right: 20, left: 10 })
  4793. .onChange((val: string) => {
  4794. this.artistStr = val
  4795. })
  4796. }
  4797. .width('100%')
  4798. .margin({ top: 10, bottom: 10 })
  4799. .justifyContent(FlexAlign.Start)
  4800. Row() {
  4801. Text('专辑名:')
  4802. .fontSize(14)
  4803. .fontColor($r('app.color.text_color'))
  4804. .margin({ left: 22 })
  4805. TextInput({ text: item.album })
  4806. .height(40)
  4807. .maxLines(1)
  4808. .fontSize(14)
  4809. .layoutWeight(1)
  4810. .fontColor($r('app.color.text_color'))
  4811. .margin({ right: 20, left: 10 })
  4812. .onChange((val: string) => {
  4813. this.ablumStr = val
  4814. })
  4815. }
  4816. .width('100%')
  4817. .margin({ top: 10, bottom: 10 })
  4818. .justifyContent(FlexAlign.Start)
  4819. Row() {
  4820. Text('歌词:')
  4821. .fontSize(14)
  4822. .fontColor($r('app.color.text_color'))
  4823. .margin({ left: 22 })
  4824. TextArea({ text: item.filePath === this.currentSong?.filePath ? this.lyricContent : this.tempLyricContent })
  4825. .type(TextAreaType.NORMAL)
  4826. .height(275)
  4827. .fontSize(14)
  4828. .layoutWeight(1)
  4829. .fontColor($r('app.color.text_color'))
  4830. .margin({ right: 20, left: 10 })
  4831. .onChange((val: string) => {
  4832. this.lyricConStr = val
  4833. })
  4834. }
  4835. .width('100%')
  4836. .margin({ top: 10, bottom: 10 })
  4837. .justifyContent(FlexAlign.Start)
  4838. Row() {
  4839. Button('保存')
  4840. .fontColor(Color.White)
  4841. .layoutWeight(1)
  4842. .height(50)
  4843. .width(100)
  4844. .backgroundColor(this.themeColor)
  4845. .stateEffect(true)
  4846. .margin({ right: 20, bottom: 20 })
  4847. .onClick(async () => {
  4848. this.doEdit(item)
  4849. })
  4850. Button('取消')
  4851. .fontColor(Color.White)
  4852. .layoutWeight(1)
  4853. .height(50)
  4854. .width(100)
  4855. .backgroundColor(this.themeColor)
  4856. .stateEffect(true)
  4857. .margin({ left: 20, bottom: 20 })
  4858. .onClick(async () => {
  4859. if(this.isGridMusic){
  4860. this.longItemFilePath =''
  4861. }else{
  4862. this.isShowEdit = false
  4863. }
  4864. })
  4865. }
  4866. .margin({
  4867. left: 38,
  4868. right: 38,
  4869. top: 10,
  4870. bottom: 10
  4871. })
  4872. .width(250)
  4873. .height(60)
  4874. }
  4875. }
  4876. .margin({ bottom: 20 })
  4877. }
  4878. @Builder
  4879. detailSheet(item:VideoItem) {
  4880. Scroll() {
  4881. Column() {
  4882. this.songDetail(item)
  4883. }
  4884. }
  4885. .width('100%')
  4886. .height('100%')
  4887. }
  4888. @Builder
  4889. songDetail(currentItem:VideoItem) {
  4890. Column() {
  4891. if (currentItem) {
  4892. Row() {
  4893. Stack() {
  4894. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4895. currentItem.pixelMapPath)
  4896. .fillColor(this.themeColor)
  4897. .height(80)
  4898. .width(80)
  4899. .borderRadius(10)
  4900. .opacity(this.opacityItem)// 绑定透明度
  4901. .margin({ left: 22 })
  4902. }
  4903. Column() {
  4904. Column() {
  4905. Text(currentItem.name)
  4906. .fontSize(16)
  4907. .maxLines(1)
  4908. .animation({
  4909. duration: 555,
  4910. curve: 'Linear',
  4911. })
  4912. .fontColor($r('app.color.text_color'))
  4913. .margin({ left: 15 })
  4914. }
  4915. .height('100%')
  4916. .width('100%')
  4917. .justifyContent(FlexAlign.Center)
  4918. .alignItems(HorizontalAlign.Start)
  4919. }
  4920. .height('100%')
  4921. }
  4922. .width('100%')
  4923. .height(90)
  4924. .justifyContent(FlexAlign.SpaceBetween)
  4925. Row() {
  4926. Text('艺术家:')
  4927. .fontSize(14)
  4928. .fontColor($r('app.color.text_color'))
  4929. .margin({ left: 22 })
  4930. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4931. .fontSize(14)
  4932. .fontColor($r('app.color.text_color'))
  4933. .margin({ left: 10 })
  4934. .layoutWeight(1)
  4935. }
  4936. .width('100%')
  4937. .margin({ top: 10, bottom: 10 })
  4938. .justifyContent(FlexAlign.Start)
  4939. Row() {
  4940. Text('专辑名:')
  4941. .fontSize(14)
  4942. .fontColor($r('app.color.text_color'))
  4943. .margin({ left: 22 })
  4944. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4945. .fontSize(14)
  4946. .margin({ left: 10 })
  4947. .fontColor($r('app.color.text_color'))
  4948. .layoutWeight(1)
  4949. }
  4950. .width('100%')
  4951. .margin({ top: 10, bottom: 10 })
  4952. .justifyContent(FlexAlign.Start)
  4953. Row() {
  4954. Text('时长:')
  4955. .fontSize(14)
  4956. .fontColor($r('app.color.text_color'))
  4957. .margin({ left: 22 })
  4958. Text(StrUtil.isEmpty(currentItem.duration)?
  4959. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4960. .fontSize(14)
  4961. .margin({ left: 10 })
  4962. .fontColor($r('app.color.text_color'))
  4963. .layoutWeight(1)
  4964. }
  4965. .width('100%')
  4966. .margin({ top: 10, bottom: 10 })
  4967. .justifyContent(FlexAlign.Start)
  4968. Row() {
  4969. Text('采样率:')
  4970. .fontSize(14)
  4971. .fontColor($r('app.color.text_color'))
  4972. .margin({ left: 22 })
  4973. Text(Utility.convertToKHz(currentItem.sampleRate))
  4974. .fontSize(14)
  4975. .margin({ left: 10 })
  4976. .fontColor($r('app.color.text_color'))
  4977. .layoutWeight(1)
  4978. }
  4979. .width('100%')
  4980. .margin({ top: 10, bottom: 10 })
  4981. .justifyContent(FlexAlign.Start)
  4982. Row() {
  4983. Text('比特率:')
  4984. .fontSize(14)
  4985. .fontColor($r('app.color.text_color'))
  4986. .margin({ left: 22 })
  4987. Text(currentItem.bit_rate)
  4988. .fontSize(14)
  4989. .margin({ left: 10 })
  4990. .fontColor($r('app.color.text_color'))
  4991. .layoutWeight(1)
  4992. }
  4993. .width('100%')
  4994. .margin({ top: 10, bottom: 10 })
  4995. .justifyContent(FlexAlign.Start)
  4996. Row() {
  4997. Text('位深:')
  4998. .fontSize(14)
  4999. .fontColor($r('app.color.text_color'))
  5000. .margin({ left: 22 })
  5001. Text(`${currentItem.bits_per_raw_sample} bits`)
  5002. .fontSize(14)
  5003. .margin({ left: 10 })
  5004. .fontColor($r('app.color.text_color'))
  5005. .layoutWeight(1)
  5006. }
  5007. .width('100%')
  5008. .margin({ top: 10, bottom: 10 })
  5009. .justifyContent(FlexAlign.Start)
  5010. Row() {
  5011. Text('声道:')
  5012. .fontSize(14)
  5013. .fontColor($r('app.color.text_color'))
  5014. .margin({ left: 22 })
  5015. Text(`${currentItem.channels}`)
  5016. .fontSize(14)
  5017. .margin({ left: 10 })
  5018. .fontColor($r('app.color.text_color'))
  5019. .layoutWeight(1)
  5020. }
  5021. .width('100%')
  5022. .margin({ top: 10, bottom: 10 })
  5023. .justifyContent(FlexAlign.Start)
  5024. Row() {
  5025. Text('声道布局:')
  5026. .fontSize(14)
  5027. .fontColor($r('app.color.text_color'))
  5028. .margin({ left: 22 })
  5029. Text(`${currentItem.channel_layout}`)
  5030. .fontSize(14)
  5031. .margin({ left: 10 })
  5032. .fontColor($r('app.color.text_color'))
  5033. .layoutWeight(1)
  5034. }
  5035. .width('100%')
  5036. .margin({ top: 10, bottom: 10 })
  5037. .justifyContent(FlexAlign.Start)
  5038. Row() {
  5039. Text('起始播放点:')
  5040. .fontSize(14)
  5041. .fontColor($r('app.color.text_color'))
  5042. .margin({ left: 22 })
  5043. Text(`${currentItem.start_time}`)
  5044. .fontSize(14)
  5045. .margin({ left: 10 })
  5046. .fontColor($r('app.color.text_color'))
  5047. .layoutWeight(1)
  5048. }
  5049. .width('100%')
  5050. .margin({ top: 10, bottom: 10 })
  5051. .justifyContent(FlexAlign.Start)
  5052. Row() {
  5053. Text('风格:')
  5054. .fontSize(14)
  5055. .fontColor($r('app.color.text_color'))
  5056. .margin({ left: 22 })
  5057. Text(currentItem.genre)
  5058. .fontSize(14)
  5059. .margin({ left: 10 })
  5060. .fontColor($r('app.color.text_color'))
  5061. .layoutWeight(1)
  5062. }
  5063. .width('100%')
  5064. .margin({ top: 10, bottom: 10 })
  5065. .justifyContent(FlexAlign.Start)
  5066. Row() {
  5067. Text('发行时间:')
  5068. .fontSize(14)
  5069. .fontColor($r('app.color.text_color'))
  5070. .margin({ left: 22 })
  5071. Text(currentItem.year)
  5072. .fontSize(14)
  5073. .margin({ left: 10 })
  5074. .fontColor($r('app.color.text_color'))
  5075. .layoutWeight(1)
  5076. }
  5077. .width('100%')
  5078. .margin({ top: 10, bottom: 10 })
  5079. .justifyContent(FlexAlign.Start)
  5080. Row() {
  5081. Text('质量评分:')
  5082. .fontSize(14)
  5083. .fontColor($r('app.color.text_color'))
  5084. .margin({ left: 22 })
  5085. Text(currentItem.probe_score+"")
  5086. .fontSize(14)
  5087. .margin({ left: 10 })
  5088. .fontColor($r('app.color.text_color'))
  5089. .layoutWeight(1)
  5090. }
  5091. .width('100%')
  5092. .margin({ top: 10, bottom: 10 })
  5093. .justifyContent(FlexAlign.Start)
  5094. Row() {
  5095. Text('音轨号:')
  5096. .fontSize(14)
  5097. .fontColor($r('app.color.text_color'))
  5098. .margin({ left: 22 })
  5099. Text(currentItem.track)
  5100. .fontSize(14)
  5101. .margin({ left: 10 })
  5102. .fontColor($r('app.color.text_color'))
  5103. .layoutWeight(1)
  5104. }
  5105. .width('100%')
  5106. .margin({ top: 10, bottom: 10 })
  5107. .justifyContent(FlexAlign.Start)
  5108. Row() {
  5109. Text('格式:')
  5110. .fontSize(14)
  5111. .fontColor($r('app.color.text_color'))
  5112. .margin({ left: 22 })
  5113. Text(Utility.formatMimeType(currentItem.mimeType))
  5114. .fontSize(14)
  5115. .margin({ left: 10 })
  5116. .fontColor($r('app.color.text_color'))
  5117. .layoutWeight(1)
  5118. }
  5119. .width('100%')
  5120. .margin({ top: 10, bottom: 10 })
  5121. .justifyContent(FlexAlign.Start)
  5122. Row() {
  5123. Text('播放次数:')
  5124. .fontSize(14)
  5125. .fontColor($r('app.color.text_color'))
  5126. .margin({ left: 22 })
  5127. Text(currentItem.playCount?.toString())
  5128. .fontSize(14)
  5129. .margin({ left: 10 })
  5130. .fontColor($r('app.color.text_color'))
  5131. .layoutWeight(1)
  5132. }
  5133. .width('100%')
  5134. .margin({ top: 10, bottom: 10 })
  5135. .justifyContent(FlexAlign.Start)
  5136. Row() {
  5137. Text('流数量:')
  5138. .fontSize(14)
  5139. .fontColor($r('app.color.text_color'))
  5140. .margin({ left: 22 })
  5141. Text(currentItem.nb_streams?.toString())
  5142. .fontSize(14)
  5143. .margin({ left: 10 })
  5144. .fontColor($r('app.color.text_color'))
  5145. .layoutWeight(1)
  5146. }
  5147. .width('100%')
  5148. .margin({ top: 10, bottom: 10 })
  5149. .justifyContent(FlexAlign.Start)
  5150. Row() {
  5151. Text('文件大小:')
  5152. .fontSize(14)
  5153. .fontColor($r('app.color.text_color'))
  5154. .margin({ left: 22 })
  5155. Text(currentItem.size)
  5156. .fontSize(14)
  5157. .margin({ left: 10 })
  5158. .fontColor($r('app.color.text_color'))
  5159. .layoutWeight(1)
  5160. }
  5161. .width('100%')
  5162. .margin({ top: 10, bottom: 10 })
  5163. .justifyContent(FlexAlign.Start)
  5164. Row() {
  5165. Text('文件名:')
  5166. .fontSize(14)
  5167. .fontColor($r('app.color.text_color'))
  5168. .margin({ left: 22 })
  5169. Text(currentItem.fileName)
  5170. .fontSize(14)
  5171. .margin({ left: 10 })
  5172. .fontColor($r('app.color.text_color'))
  5173. .layoutWeight(1)
  5174. }
  5175. .width('100%')
  5176. .margin({ top: 10, bottom: 10 })
  5177. .justifyContent(FlexAlign.Start)
  5178. Row() {
  5179. Text('修改时间:')
  5180. .fontSize(14)
  5181. .fontColor($r('app.color.text_color'))
  5182. .margin({ left: 22 })
  5183. Text(currentItem.cTime)
  5184. .fontSize(14)
  5185. .margin({ left: 10 })
  5186. .fontColor($r('app.color.text_color'))
  5187. .layoutWeight(1)
  5188. }
  5189. .width('100%')
  5190. .margin({ top: 10, bottom: 10 })
  5191. .justifyContent(FlexAlign.Start)
  5192. Row() {
  5193. Text('存放目录:')
  5194. .fontSize(14)
  5195. .fontColor($r('app.color.text_color'))
  5196. .margin({ left: 22 })
  5197. Text(currentItem.filePath)
  5198. .fontSize(12)
  5199. .margin({ left: 10 })
  5200. .fontColor($r('app.color.text_color'))
  5201. .layoutWeight(1)
  5202. }
  5203. .margin({ top: 10, bottom: 10 })
  5204. .width('100%')
  5205. .justifyContent(FlexAlign.Start)
  5206. }
  5207. }
  5208. .margin({ bottom: 20 })
  5209. }
  5210. //定时关闭布局
  5211. @Builder
  5212. TimeCloseSheet() {
  5213. Scroll() {
  5214. Column() {
  5215. this.TimeClose()
  5216. }
  5217. }
  5218. .width('100%')
  5219. .height('100%')
  5220. }
  5221. //倒计时关闭音乐,退出App功能实现。
  5222. @State selectedMinutes: number = 0 // 0表示未开启
  5223. @State remainingSeconds: number = 0
  5224. // 预设时间选项
  5225. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  5226. private formatTime(seconds: number): string {
  5227. const mins = Math.floor(seconds / 60)
  5228. const secs = seconds % 60
  5229. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  5230. }
  5231. // 开始倒计时
  5232. private handleTimeSelect(minutes: number) {
  5233. if (minutes === this.selectedMinutes) {
  5234. this.stopCountdown();
  5235. this.selectedMinutes = 0;
  5236. return;
  5237. }
  5238. this.selectedMinutes = minutes;
  5239. this.remainingSeconds = minutes * 60;
  5240. this.startCountdown(); // 新增调用
  5241. }
  5242. @Builder
  5243. TimeClose() {
  5244. Column() {
  5245. // 倒计时显示区域
  5246. Text(this.selectedMinutes > 0 ?
  5247. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  5248. "定时关闭未开启")
  5249. .fontSize(17)
  5250. .fontColor($r('app.color.text_color'))
  5251. .margin({ top: 2, bottom: 8 });
  5252. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  5253. ForEach(this.presetTimes, (minutes: number, index: number) => {
  5254. // 单行时间选项容器
  5255. Row() {
  5256. // 文字描述区域
  5257. Text(this.getDisplayText(minutes))
  5258. .fontSize(15)
  5259. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  5260. $r('app.color.text_color'))// 选中态颜色变化
  5261. .textAlign(TextAlign.Start)
  5262. .layoutWeight(1); // 占据剩余空间
  5263. // 复选框样式的选择器
  5264. Row() {
  5265. if (minutes === this.selectedMinutes) {
  5266. // 选中状态 - 带勾号的圆形复选框
  5267. Row() {
  5268. // 使用系统内置的勾号图标
  5269. Image($r('sys.media.ohos_ic_public_ok'))
  5270. .width(14)
  5271. .height(14)
  5272. .fillColor(Color.White)
  5273. }
  5274. .width(24)
  5275. .height(24)
  5276. .borderRadius(12)
  5277. .backgroundColor(this.themeColor)
  5278. .justifyContent(FlexAlign.Center)
  5279. .alignItems(VerticalAlign.Center)
  5280. } else {
  5281. // 未选中状态的圆形边框
  5282. Row()
  5283. .width(24)
  5284. .height(24)
  5285. .borderRadius(12)
  5286. .border({
  5287. width: 2,
  5288. color: $r('app.color.text_color'),
  5289. style: BorderStyle.Solid
  5290. })
  5291. .backgroundColor(Color.Transparent)
  5292. }
  5293. }
  5294. .width(24)
  5295. .height(24)
  5296. .margin({ left: 20 })
  5297. .justifyContent(FlexAlign.Center)
  5298. .alignItems(VerticalAlign.Center)
  5299. }
  5300. .width('100%')
  5301. .padding({
  5302. top: 18,
  5303. bottom: 18,
  5304. left: 18,
  5305. right: 18
  5306. })
  5307. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  5308. $r('app.color.bottom_control_background')) // 选中背景高亮
  5309. .borderRadius(12)
  5310. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  5311. .margin({ bottom: 18 })
  5312. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  5313. });
  5314. }
  5315. .width('100%')
  5316. .padding(16)
  5317. }
  5318. }
  5319. // 获取显示文本
  5320. private getDisplayText(minutes: number): string {
  5321. if (minutes === -1) {
  5322. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  5323. }
  5324. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  5325. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  5326. }
  5327. // 处理选择事件
  5328. private handleSelect(minutes: number): void {
  5329. if (minutes === -1) { // 自定义
  5330. // 弹出自定义时间对话框
  5331. DialogHelper.showTextInputDialog({
  5332. title: '自定义时间',
  5333. maskColor: Color.Transparent,
  5334. inputType: InputType.Number,
  5335. text: '',
  5336. onChange: (text) => {
  5337. console.error("onChange: " + text);
  5338. },
  5339. onAction: (action, dialogId, content) => {
  5340. if (action == DialogAction.TWO) {
  5341. const customMinutes = Number(content);
  5342. if (customMinutes > 0) {
  5343. this.handleTimeSelect(customMinutes); // 设置自定义时间
  5344. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  5345. }
  5346. }
  5347. }
  5348. });
  5349. } else {
  5350. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  5351. }
  5352. }
  5353. // 添加定时器引用
  5354. private timerId: number = -1;
  5355. // 启动/重置倒计时
  5356. private startCountdown() {
  5357. // 清除旧定时器
  5358. if (this.timerId !== -1) {
  5359. clearInterval(this.timerId);
  5360. }
  5361. // 创建新定时器
  5362. if (this.selectedMinutes > 0) {
  5363. this.timerId = setInterval(() => {
  5364. if (this.remainingSeconds === 15) {
  5365. this.showConfirmationDialog();
  5366. }
  5367. if (this.remainingSeconds > 0) {
  5368. this.remainingSeconds -= 1;
  5369. } else {
  5370. this.stopCountdown();
  5371. this.handleTimeout();
  5372. }
  5373. }, 1000);
  5374. }
  5375. }
  5376. // 15倒计时后再次提示显示确认是否关闭App对话框
  5377. private showConfirmationDialog() {
  5378. DialogHelper.showAlertDialog({
  5379. backgroundColor: $r('app.color.btn_green'),
  5380. title: '确认关闭',
  5381. maskColor: Color.Transparent,
  5382. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  5383. borderStyle: BorderStyle.Dashed,
  5384. primaryButton: '暂不关闭',
  5385. secondaryButton: '确定',
  5386. onAction: (action) => {
  5387. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  5388. this.stopCountdown();
  5389. this.selectedMinutes = 0
  5390. } else if (action == DialogAction.TWO) {
  5391. }
  5392. }
  5393. })
  5394. }
  5395. // 停止倒计时
  5396. private stopCountdown() {
  5397. if (this.timerId !== -1) {
  5398. clearInterval(this.timerId);
  5399. this.timerId = -1;
  5400. }
  5401. }
  5402. // 超时处理
  5403. private handleTimeout() {
  5404. // 执行播放器关闭逻辑
  5405. this.selectedMinutes = 0;
  5406. ToastUtil.showToast(" 定时关闭已完成");
  5407. this.stop(); // 假设存在的播放器实例
  5408. //退出APP
  5409. const mContext = getContext(this) as common.UIAbilityContext
  5410. mContext.terminateSelf();
  5411. AvSessionController.getInstance(true).unregisterSessionListener()
  5412. }
  5413. //倒计时关闭音乐,退出App功能实现结束。
  5414. //播放列表的拖动List 重新排序
  5415. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  5416. //左滑操作 移动文件 重命名 删除等操作
  5417. @Builder
  5418. sonButton(item: VideoItem, index: number, filePath: string) {
  5419. Row() {
  5420. //加入下一首播放
  5421. Button() {
  5422. Image($r('app.media.next_to_play'))
  5423. .fillColor(Color.White)
  5424. .width(20)
  5425. }
  5426. .width(40)
  5427. .height(40)
  5428. .type(ButtonType.Circle)
  5429. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5430. .backgroundColor(this.themeColor)
  5431. .margin(5)
  5432. .onClick(() => {
  5433. this.addToNextPlay(item);
  5434. })
  5435. Button() {
  5436. Image($r('app.media.close'))
  5437. .fillColor(Color.White)
  5438. .width(20)
  5439. }
  5440. .width(40)
  5441. .height(40)
  5442. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5443. .type(ButtonType.Circle)
  5444. .backgroundColor(this.themeColor)
  5445. .margin(5)
  5446. .onClick(() => {
  5447. this.removeFromPlaylistViaService(Number(index));
  5448. })
  5449. Button() {
  5450. Image($r('app.media.share2'))
  5451. .fillColor(Color.White)
  5452. .width(20)
  5453. }
  5454. .width(40)
  5455. .height(40)
  5456. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5457. .type(ButtonType.Circle)
  5458. .backgroundColor(this.themeColor)
  5459. .margin(5)
  5460. .onClick(() => {
  5461. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5462. })
  5463. }
  5464. }
  5465. itemMoveSon(index: number, newIndex: number): void {
  5466. if (newIndex < 0 || newIndex >= this.songList.length) {
  5467. return;
  5468. }
  5469. try {
  5470. // 使用UnifiedPlayerService进行播放列表重排序
  5471. const removedSong = this.unifiedPlayerService.removeFromPlaylist(index);
  5472. if (removedSong) {
  5473. this.unifiedPlayerService.addToPlaylist(removedSong, newIndex);
  5474. }
  5475. // 更新本地播放列表
  5476. let tmp = this.songList.splice(index, 1);
  5477. this.songList.splice(newIndex, 0, tmp[0]);
  5478. this.sonDataSource.pushArrayData(this.songList);
  5479. // 更新当前索引
  5480. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl);
  5481. } catch (error) {
  5482. // 错误处理:回退到原有逻辑
  5483. let tmp = this.songList.splice(index, 1);
  5484. this.songList.splice(newIndex, 0, tmp[0]);
  5485. this.sonDataSource.pushArrayData(this.songList);
  5486. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl);
  5487. }
  5488. }
  5489. @Builder
  5490. PlayList() {
  5491. List({ scroller: this.playListScroller }) {
  5492. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  5493. ListItem() {
  5494. this.MusicItemSon(item, index)
  5495. }
  5496. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  5497. .animation({
  5498. duration: 666,
  5499. curve: 'ease-in-out' // 可选动画曲线
  5500. })
  5501. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  5502. TransitionEffect.scale({ x: 0, y: 0 })))
  5503. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  5504. //拖动List关键代码开始
  5505. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5506. .zIndex(this.dragItem === index ? 1 : 0)
  5507. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5508. .gesture(
  5509. GestureGroup(GestureMode.Sequence,
  5510. LongPressGesture({ repeat: true })
  5511. .onAction((event?: GestureEvent) => {
  5512. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5513. this.scaleItem = index
  5514. })
  5515. })
  5516. .onActionEnd(() => {
  5517. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5518. this.scaleItem = -1
  5519. })
  5520. }),
  5521. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5522. .onActionStart(() => {
  5523. this.dragItem = index // 记录当前拖动项索引
  5524. this.dragRefOffset = 0 // 重置偏移基准
  5525. })
  5526. .onActionUpdate((event: GestureEvent) => {
  5527. this.offsetY = event.offsetY - this.dragRefOffset;
  5528. this.neighborItem = -1;
  5529. let indexA = this.songList.indexOf(item);
  5530. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5531. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5532. let value: number = 0;
  5533. if (this.offsetY < 0) {
  5534. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5535. this.neighborItem = indexA - 1;
  5536. this.neighborScale = 1 - value / 20;
  5537. } else if (this.offsetY > 0) {
  5538. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5539. this.neighborItem = indexA + 1;
  5540. this.neighborScale = 1 - value / 20;
  5541. }
  5542. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  5543. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5544. this.offsetY -= this.ITEM_INTV;
  5545. this.dragRefOffset += this.ITEM_INTV;
  5546. this.itemMoveSon(indexA, indexA + 1);
  5547. });
  5548. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5549. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5550. this.offsetY += this.ITEM_INTV;
  5551. this.dragRefOffset -= this.ITEM_INTV;
  5552. this.itemMoveSon(indexA, indexA - 1);
  5553. });
  5554. }
  5555. })
  5556. .onActionEnd((event: GestureEvent) => {
  5557. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5558. this.dragItem = -1
  5559. this.neighborItem = -1
  5560. })
  5561. animateTo({
  5562. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5563. }, () => {
  5564. this.scaleItem = -1
  5565. })
  5566. })
  5567. )
  5568. .onCancel(() => {
  5569. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5570. this.dragItem = -1
  5571. this.neighborItem = -1
  5572. })
  5573. animateTo({
  5574. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5575. }, () => {
  5576. this.scaleItem = -1
  5577. })
  5578. })
  5579. ) //拖动List关键代码结束
  5580. .onClick(() => {
  5581. this.doPlay(item, index, true)
  5582. })
  5583. }, (item: VideoItem) => item.filePath)
  5584. }
  5585. .width('100%')
  5586. .height('100%')
  5587. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5588. // .animation({ duration: 500, curve: Curve.Ease }))
  5589. .cachedCount(10)
  5590. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5591. .gesture(PinchGesture({ fingers: 2 })
  5592. .onActionEnd((event: GestureEvent) => {
  5593. this.setlistTwoFingers()
  5594. })
  5595. .onActionUpdate(e => {
  5596. this.scaleValue = this.pinchValue * e.scale
  5597. })
  5598. .onActionStart(e => {
  5599. }))
  5600. .padding({
  5601. bottom: 0
  5602. })
  5603. }
  5604. @Builder
  5605. private MusicItemSon(item: VideoItem, index?: number) {
  5606. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5607. Row() {
  5608. Stack() {
  5609. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5610. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5611. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5612. .alt($r('app.media.music_red'))
  5613. .fillColor(this.themeColor)
  5614. .borderRadius('100%')
  5615. .clip(true)
  5616. .margin({ left: 20 })
  5617. }
  5618. .width('15%')
  5619. Column() {
  5620. Column() {
  5621. Text(item.name)
  5622. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5623. .fontColor(this.curIndex === index ? this.themeColor :
  5624. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5625. .maxLines(1)
  5626. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5627. Row() {
  5628. Column(){
  5629. Text(item.md5Str?.includes('Lossless')?
  5630. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5631. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5632. .padding({ top: 3,right:6,left:6,bottom:3 })
  5633. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5634. $r('app.color.text_color'))
  5635. .fontWeight(500)
  5636. .borderRadius(12)
  5637. .margin({ left: this.twoFingerType == 3 ? 12 : 10 })
  5638. .backgroundColor('#FFC107')
  5639. }
  5640. .padding({ top: 8 })
  5641. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5642. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5643. .padding({ top: 8 })
  5644. .fontColor(this.curIndex === index ? this.themeColor :
  5645. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5646. .margin({ left: this.twoFingerType == 3 ? 5 : 3 })
  5647. Blank()
  5648. Text(item.size)
  5649. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5650. .padding({ top: 8 })
  5651. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5652. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5653. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5654. .margin({ left: 10 })
  5655. }
  5656. }
  5657. .height('100%')
  5658. .width('100%')
  5659. .justifyContent(FlexAlign.Center)
  5660. .alignItems(HorizontalAlign.Start)
  5661. }
  5662. .height('100%')
  5663. .width('65%')
  5664. Column() {
  5665. ImageAnimator()
  5666. .images(this.imagesF)// 动画数组
  5667. .duration(1000)// 持续
  5668. .state(this.animationState)// 动画状态
  5669. .fillMode(FillMode.Forwards)
  5670. .width(18)
  5671. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5672. Visibility.None)
  5673. .height(18)
  5674. .iterations(-1) // 播放次数
  5675. }
  5676. .width('20%')
  5677. }
  5678. }
  5679. .backgroundColor(Color.Transparent)
  5680. .width('100%')
  5681. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5682. .shadow(this.scaleItem === index ? {
  5683. radius: 70,
  5684. color: '#15000000',
  5685. offsetX: 0,
  5686. offsetY: 0
  5687. } :
  5688. {
  5689. radius: 0,
  5690. color: '#15000000',
  5691. offsetX: 0,
  5692. offsetY: 0
  5693. })
  5694. .animation({ curve: Curve.Sharp, duration: 300 })
  5695. }
  5696. @Builder
  5697. MusicPlayBuilder() {
  5698. Column() {
  5699. this.MusicPlayerView()
  5700. }
  5701. .height('100%')
  5702. .width('100%')
  5703. .onDisAppear(() => {
  5704. this.translateY = 0;
  5705. })
  5706. .translate({ y: this.translateY })
  5707. .gesture(
  5708. PanGesture(this.panOption)
  5709. .onActionUpdate((event?: GestureEvent) => {
  5710. if (event) {
  5711. // 只允许向下滑动,向上滑动时限制为0
  5712. this.translateY = Math.max(0, event.offsetY);
  5713. }
  5714. })
  5715. .onActionEnd((event?: GestureEvent) => {
  5716. // 使用更低的阈值和滑动速度判断
  5717. const minDistance = 100; // 最小滑动距离 100vp
  5718. const minVelocity = 500; // 最小滑动速度
  5719. // 获取滑动速度(如果可用)
  5720. const velocity = event?.velocityY || 0;
  5721. // 判断是否应该关闭:距离足够 或者 速度足够快
  5722. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5723. if (shouldClose) {
  5724. // 添加关闭动画
  5725. this.getUIContext().animateTo({
  5726. duration: 300,
  5727. curve: Curve.Smooth
  5728. }, () => {
  5729. this.isShowPlay = false;
  5730. this.translateY = 0;
  5731. })
  5732. } else {
  5733. // 回弹动画
  5734. this.getUIContext().animateTo({
  5735. duration: 300,
  5736. curve: Curve.Smooth
  5737. }, () => {
  5738. this.translateY = 0;
  5739. })
  5740. }
  5741. })
  5742. )
  5743. }
  5744. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5745. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5746. HeightBreakpoint.HEIGHT_LG;
  5747. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5748. @State topBarHeight: number = 50
  5749. @State barOpacity: number = 1
  5750. @State barBottomOpacity: number = 1
  5751. private hideDone: boolean = false;
  5752. @State currentYOffset: number = 0;
  5753. @State bottomBarHeight: number = 60;
  5754. private isHiding: boolean = false;
  5755. //是否是Pura X外屏,或者小屏幕
  5756. isPuraWP() {
  5757. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5758. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5759. }
  5760. //是否是Pura X外屏,或者小屏幕,手机横屏
  5761. /**
  5762. * 是否是Pura X外屏,或者小屏幕,手机横屏
  5763. * @returns
  5764. */
  5765. isCoverOpacity() {
  5766. if (this.isPuraWP()) {
  5767. return true
  5768. }
  5769. if (this.isPhoneLan()) {
  5770. return true
  5771. }
  5772. if (deviceInfo.marketName.includes('Pura X')
  5773. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5774. return true
  5775. }
  5776. return false
  5777. }
  5778. //是不是手机横屏
  5779. isPhoneLan() {
  5780. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5781. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5782. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5783. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5784. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  5785. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5786. if (this.isHiCarKuanBianPing()) {
  5787. return true
  5788. }
  5789. if (this.isHiCar()) {
  5790. return false
  5791. }
  5792. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5793. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5794. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  5795. return true
  5796. }
  5797. return false
  5798. }
  5799. //是不是1920x720的hicar的屏幕分辨率
  5800. isHiCarKuanBianPing(){
  5801. if(!this.isHiCar()){
  5802. return false
  5803. }
  5804. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5805. { ratio: 1920 / 720, name: "1920x720" },
  5806. ];
  5807. const currentRatio: number = this.windowWidth / this.windowHeight;
  5808. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5809. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  5810. for (const hiCarRatio of hiCarAspectRatios) {
  5811. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  5812. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5813. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5814. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5815. return true;
  5816. }
  5817. }
  5818. return false;
  5819. }
  5820. //是不是hicar的屏幕分辨率
  5821. isHiCarSmall() {
  5822. if(!this.isHiCar()){
  5823. return false
  5824. }
  5825. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5826. return false
  5827. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5828. { ratio: 800 / 480, name: "800x480" },
  5829. { ratio: 1280 / 720, name: "1280x720" },
  5830. ];
  5831. const currentRatio: number = this.windowWidth / this.windowHeight;
  5832. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5833. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  5834. for (const hiCarRatio of hiCarAspectRatios) {
  5835. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  5836. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5837. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  5838. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5839. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5840. return true;
  5841. }
  5842. }
  5843. return false;
  5844. }
  5845. isHiCar() {
  5846. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  5847. }
  5848. //是不是正常的手机竖屏
  5849. isPhonePortrait() {
  5850. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5851. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5852. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5853. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5854. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5855. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5856. return true
  5857. }
  5858. return false
  5859. }
  5860. @State showSpeedDialog: boolean = false
  5861. @State longPressSpeed: number = 3 //长按默认倍数
  5862. @Builder
  5863. SpeedDialog() {
  5864. Stack() {
  5865. Column() {
  5866. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5867. .fontColor(Color.White)
  5868. .visibility(Visibility.Hidden)
  5869. }
  5870. .backgroundColor(Color.Black)
  5871. .borderRadius(20)
  5872. .padding({
  5873. top: 10,
  5874. right: 20,
  5875. left: 15,
  5876. bottom: 20
  5877. })
  5878. .opacity(0.6)
  5879. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5880. .fontColor(Color.White)
  5881. }
  5882. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5883. .zIndex(5)
  5884. .margin({ top: 80 })
  5885. }
  5886. @Builder
  5887. MusicPlayerView() {
  5888. Column() {
  5889. Column() {
  5890. Column() {
  5891. //播放标题
  5892. Column() {
  5893. this.PlayTitle()
  5894. }
  5895. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5896. .width('100%')
  5897. .margin({ top: 0 })
  5898. .height(PlayConstants.HEIGHT)
  5899. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5900. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5901. if (this.showSpeedDialog) {
  5902. this.SpeedDialog()
  5903. }
  5904. Stack() {
  5905. //手势拖动快进
  5906. Column()
  5907. .width(CommonConstants.FULL_PERCENT)
  5908. .height('100%')
  5909. .gesture(
  5910. GestureGroup(GestureMode.Parallel,
  5911. // 长按屏幕倍数播放
  5912. LongPressGesture({ repeat: true })
  5913. .onAction(() => {
  5914. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5915. this.showSpeedDialog = true;
  5916. this.unifiedPlayerService.setPlaybackSpeed(this.longPressSpeed);
  5917. }
  5918. })
  5919. .onActionEnd(() => {
  5920. this.showSpeedDialog = false;
  5921. this.setPlaybackSpeedViaService(this.playSpeed);
  5922. }),
  5923. //双击屏幕暂停或者播放
  5924. TapGesture({ count: 2 })
  5925. .onAction((event: GestureEvent) => {
  5926. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5927. ToastUtil.showToast('已暂停')
  5928. }
  5929. this.playOrPause()
  5930. })
  5931. )
  5932. )
  5933. }
  5934. .height('65%')
  5935. Swiper() {
  5936. this.CoverInfo()
  5937. this.PlayerLyrics()
  5938. }
  5939. .onChange((index: number) => {
  5940. this.currentSwiperIndex = index
  5941. })
  5942. .indicator(false)
  5943. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5944. // new DotIndicator()
  5945. // .top(this.isCoverOpacity()?0:10)
  5946. //
  5947. // .selectedColor($r('app.color.select_swiper'))
  5948. // .color($r('app.color.slider_track')):false
  5949. // )
  5950. .displayCount(new BreakpointType({
  5951. sm: 1,
  5952. md: 2,
  5953. lg: 2,
  5954. xl: 2,
  5955. xxl: 2
  5956. }).getValue(this.currentBreakpoint))
  5957. .clip(false)
  5958. .loop(false)
  5959. .autoPlay(false)
  5960. // .interval(8000)
  5961. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5962. .height('100%')
  5963. .hitTestBehavior(HitTestMode.Transparent)
  5964. Image($r('app.media.icon_replay'))
  5965. .objectFit(ImageFit.Auto)
  5966. .width('120px')
  5967. .height('120px')
  5968. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5969. .border({ width: 0 })
  5970. .visibility(Visibility.None)
  5971. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5972. .onClick(() => {
  5973. this.startPlayOrResumePlay();
  5974. })
  5975. }
  5976. .width(CommonConstants.FULL_PERCENT)
  5977. .height(CommonConstants.FULL_PERCENT)
  5978. .justifyContent(FlexAlign.End)
  5979. }
  5980. .justifyContent(FlexAlign.End)
  5981. .margin({ bottom: 8 })
  5982. }
  5983. // .backgroundImage(this.imageLabelBg)
  5984. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5985. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5986. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5987. // .backgroundImagePosition(Alignment.Center)
  5988. .animation({
  5989. duration: 666,
  5990. curve: 'ease-in-out' // 可选动画曲线
  5991. })
  5992. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5993. BlurStyle.BACKGROUND_ULTRA_THICK)
  5994. .hitTestBehavior(HitTestMode.Transparent)
  5995. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5996. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5997. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5998. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5999. .onClick(() => {
  6000. // this.startAutoHide()
  6001. if(this.isHiCar())
  6002. return
  6003. if(this.is_auto_hide_progress){
  6004. this.is_auto_hide_progress = false
  6005. }
  6006. this.startAutoHide()
  6007. })
  6008. }
  6009. @State progressValue: number = 0;
  6010. @State currentTime: string = "00:00";
  6011. @State totalTime: string = "00:00";
  6012. @State loadingVisible: Visibility = Visibility.None;
  6013. @State replayVisible: Visibility = Visibility.None;
  6014. @State slideEnable: boolean = false;
  6015. @State aspRatio: number = 0.5;
  6016. @State mContext: object | undefined = undefined;
  6017. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  6018. @State mFirst: boolean = true;
  6019. @State mDestroyPage: boolean = false;
  6020. @State playSpeed: number = 1;
  6021. @State oldSeconds: number = 0;
  6022. @State isSeekTo: boolean = false;
  6023. @State isCurrentTime: boolean = false;
  6024. @State lastSongPath: string = ""; // 用于检测歌曲切换
  6025. @State justSwitched: boolean = false; // 标记歌曲刚刚切换
  6026. @State lastSwitchTime: number = 0; // 记录最后一次歌曲切换的时间戳
  6027. @State videoWidth: string = '100%';
  6028. @State videoHeight: string = '100%';
  6029. @State initAspectRatio: number = 1;
  6030. @State videoAspectRatio: number = this.initAspectRatio;
  6031. private videoUrl: string = '';
  6032. private last: number = 0;
  6033. @State videoParentAspectRatio: number = this.initAspectRatio;
  6034. // 使用UnifiedPlayerService替代ijkMediaPlayer
  6035. // private mIjkMediaPlayer = IjkMediaPlayer.getInstance(); // 已移除,使用UnifiedPlayerService
  6036. private unifiedPlayerService: IPlayerService = UnifiedPlayerService.getInstance();
  6037. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  6038. @State PROGRESS_MAX_VALUE: number = 100;
  6039. @State updateProgressTimer: number = 0;
  6040. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  6041. @State name: string = '';
  6042. // @State loop: boolean = false;
  6043. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  6044. @State multiple: string = '1.0X';
  6045. xcomponentController: XComponentController = new XComponentController()
  6046. private windowClass: window.Window = globalThis.windowClass
  6047. @State volume: number = 0.3;
  6048. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  6049. @State bright: number = PlayConstants.BRIGHT;
  6050. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  6051. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  6052. @State screenWidth: number = 0
  6053. @State screenHeight: number = 0
  6054. @State statusBarHeight: number = 0
  6055. @State isYesFull: boolean = false
  6056. private seekValue: number = 0
  6057. @State isVideoLock: boolean = false; // Whether the video playback is locked
  6058. eventHub = getContext().eventHub;
  6059. //投播组件
  6060. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  6061. private castController: avSession.AVCastController | undefined = undefined;
  6062. @State isCastPlaying: boolean = false;
  6063. @State isCasting: boolean = false; // 是否正在投播中
  6064. private currentCastDevice: avSession.DeviceInfo | undefined = undefined; // 当前投播设备
  6065. @State currentTime2: number = 0;
  6066. @State currentStringTime: string = '00:00';
  6067. @State duration: number = 0;
  6068. @State isReady: boolean = false;
  6069. @State durationTime: number = 0;
  6070. @State durationStringTime: string = '00:00';
  6071. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  6072. // @State isPlaying: boolean = false;
  6073. private castSeek: boolean = false;
  6074. private castItem: avSession.AVQueueItem | undefined = undefined;
  6075. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  6076. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  6077. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  6078. @State rotateAngle2: number = 0
  6079. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  6080. @State cover: string | undefined = '';
  6081. @State artist: string | undefined = ''
  6082. // 1.初始化controller
  6083. private lyricController: LyricController = new LyricController()
  6084. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  6085. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  6086. private parser = new LyricParser()
  6087. @State randomColor: string = 'rgb(0,0,0)'
  6088. @State randomShakenX: number = 0
  6089. @State randomShakenY: number = 0
  6090. @State lyricTextSize: number = 24
  6091. @State lyricContent: string = ''
  6092. @State isDebug: boolean = false
  6093. @State isHightLightCenter: boolean = true
  6094. /**
  6095. * 初始化歌词加载与展示逻辑
  6096. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  6097. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  6098. * @param isApi2 是否使用API2获取歌词(可选)
  6099. *
  6100. * 主要流程:
  6101. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  6102. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  6103. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  6104. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  6105. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  6106. * 6. 解析失败或读取失败时,清空歌词显示。
  6107. *
  6108. * 注意事项:
  6109. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  6110. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  6111. * - 歌词内容解析后通过lyricController驱动UI渲染。
  6112. */
  6113. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  6114. if (StrUtil.isEmpty(lyricPath)) {
  6115. return
  6116. }
  6117. this.initPipLyricSetting()
  6118. this.lyricControllerSingle
  6119. .setTextSize(15)
  6120. .setCacheSize(4)
  6121. .setTextColor("#FFFFFF")
  6122. .setHighlightColor("#FFFFFF")
  6123. .setHighlightScale(1.2)
  6124. .setEmptyHint("")
  6125. .setAlignMode('center')
  6126. .setAnimationDuration(500)
  6127. .setSingleLine(true)
  6128. this.lyricContent = ''
  6129. this.lyricController
  6130. .setTextSize(this.currentLyricSize)
  6131. .setCacheSize(4)
  6132. .setTextColor("#DDDDDD")
  6133. .setHighlightColor("#FFFFFF")
  6134. .setEmptyHint("")
  6135. .setAnimationDuration(1000)
  6136. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  6137. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  6138. this.setBlurDegree(this.blurDegree, false)
  6139. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  6140. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  6141. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  6142. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  6143. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  6144. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  6145. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  6146. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6147. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  6148. this.lyricController.setTextWeight(this.lyricTextWeight)
  6149. this.showSingleLyric = false
  6150. this.timeOffset = 0
  6151. this.lyricController.setLyric(null)
  6152. this.lyricControllerSingle.setLyric(null)
  6153. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  6154. console.log("onecold lyricPath =" + lyricPath)
  6155. let neiqianLrc = ''
  6156. let lyContent = this.currentSong?.lyricContent
  6157. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  6158. neiqianLrc = lyContent
  6159. }
  6160. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  6161. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  6162. //赋值给this.lyricContent,播控中心才可以显示歌词
  6163. this.lyricContent = neiqianLrc
  6164. // 将文件内容按行分割成字符串数组
  6165. let lines = neiqianLrc.split('\n').map(line => line.trim());
  6166. // 3.解析歌词
  6167. let lyric = this.parser.parse(lines);
  6168. // 4.设置歌词
  6169. this.lyricController.setLyric(lyric);
  6170. this.lyricControllerXF.setLyric(lyric)
  6171. this.lyricControllerSingle.setLyric(lyric)
  6172. return
  6173. }
  6174. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  6175. && !Utility.isVideoByExtension(this.videoUrl))) {
  6176. if (this.currentSong !== undefined) {
  6177. // ToastUtil.showShort('正在为你搜索在线歌词!')
  6178. //判断是不是赞助会员,是会员的话才开启歌词功能
  6179. // if (!this.isDebug) {
  6180. // if (!Utility.isNoble()) {
  6181. // LogUtil.debug("onecold 不是赞助会员")
  6182. // return
  6183. // }
  6184. // if(!Utility.isPassInstallTime(33)){
  6185. // LogUtil.debug("onecold not pass time")
  6186. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  6187. // return
  6188. // }
  6189. // }
  6190. let artist = this.currentSong?.artist
  6191. if (artist === undefined) {
  6192. artist = ''
  6193. }
  6194. if (isApi2 === undefined) {
  6195. isApi2 = false
  6196. }
  6197. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  6198. // LogUtil.debug("onecold res =" + res)
  6199. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6200. if (StrUtil.isNotEmpty(res)) {
  6201. this.lyricContent = res
  6202. let lines = res.split('\n').map(line => line.trim());
  6203. // 3.解析歌词
  6204. let lyric = this.parser.parse(lines);
  6205. // 4.设置歌词
  6206. this.lyricController.setLyric(lyric);
  6207. this.lyricControllerXF.setLyric(lyric)
  6208. this.lyricControllerSingle.setLyric(lyric)
  6209. this.showSingleLyric = true
  6210. // 4.保存歌词文件lyric到本地
  6211. this.saveDataToFile(res, jiaMilyricPath, true)
  6212. } else {
  6213. this.lyricController.setLyric(null)
  6214. this.lyricControllerXF.setLyric(null)
  6215. this.lyricControllerSingle.setLyric(null)
  6216. if (isOnLineAndToast) {
  6217. ToastUtil.showShort('未获取到歌词!')
  6218. }
  6219. }
  6220. } else {
  6221. this.lyricController.setLyric(null)
  6222. this.lyricControllerXF.setLyric(null)
  6223. this.lyricControllerSingle.setLyric(null)
  6224. if (isOnLineAndToast) {
  6225. ToastUtil.showShort('未获取到歌词!')
  6226. }
  6227. }
  6228. })
  6229. } else {
  6230. this.lyricController.setLyric(null)
  6231. this.lyricControllerXF.setLyric(null)
  6232. this.lyricControllerSingle.setLyric(null)
  6233. if (isOnLineAndToast) {
  6234. ToastUtil.showShort('未获取到歌词!')
  6235. }
  6236. }
  6237. return
  6238. }
  6239. try {
  6240. let isJiaMi = false;
  6241. let realLyricPath = lyricPath
  6242. if (FileUtil.accessSync(jiaMilyricPath)) {
  6243. isJiaMi = true
  6244. realLyricPath = jiaMilyricPath
  6245. console.info("onecold 找到加密本地歌词 ");
  6246. } else {
  6247. isJiaMi = false
  6248. realLyricPath = lyricPath
  6249. console.info("onecold 找到本地歌词 ");
  6250. }
  6251. // 3.读取文件内容并指定编码为 UTF-8
  6252. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6253. const stat = await fileIo.stat(file.fd);
  6254. const arrayBuffer = new ArrayBuffer(stat.size);
  6255. fs.read(file.fd, arrayBuffer)
  6256. .then((readLen: number) => {
  6257. console.info("read file data succeed");
  6258. // let buf = buffer.from(arrayBuffer, 0, readLen);
  6259. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6260. // 检查 buf 是否为空
  6261. if (buf.length === 0) {
  6262. throw new Error("Buffer is empty after reading the file");
  6263. }
  6264. try {
  6265. // 检测文件编码
  6266. // let detectedEncoding = chardet.detect(buf);
  6267. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  6268. let detectedEncoding = this.detect(arrayBuffer)
  6269. console.info("onecoldT Detected encoding: " + detectedEncoding);
  6270. // 使用检测到的编码解码,解决中文乱码问题
  6271. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6272. console.info("onecoldT Detected textDecoder: " + textDecoder);
  6273. let fileContent = textDecoder.decode(buf);
  6274. console.info(`onecoldT The content of file1: ${fileContent}`);
  6275. //解密
  6276. if (isJiaMi) {
  6277. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  6278. }
  6279. console.info(`onecold The content of file2: ${fileContent}`);
  6280. this.lyricContent = fileContent
  6281. // 将文件内容按行分割成字符串数组
  6282. let lines = fileContent.split('\n').map(line => line.trim());
  6283. console.info(`onecold The content of file: ${fileContent}`);
  6284. // 3.解析歌词
  6285. let lyric = this.parser.parse(lines);
  6286. // 4.设置歌词
  6287. this.lyricController.setLyric(lyric);
  6288. this.lyricControllerXF.setLyric(lyric)
  6289. this.lyricControllerSingle.setLyric(lyric)
  6290. this.showSingleLyric = true
  6291. console.info(`The content of file: ${fileContent}`);
  6292. } catch (chardetError) {
  6293. console.error("chardet.detect failed with error: " + chardetError.message);
  6294. this.lyricController.setLyric(null);
  6295. this.lyricControllerXF.setLyric(null)
  6296. this.lyricControllerSingle.setLyric(null)
  6297. }
  6298. })
  6299. .catch((err: BusinessError) => {
  6300. this.lyricController.setLyric(null)
  6301. this.lyricControllerXF.setLyric(null)
  6302. this.lyricControllerSingle.setLyric(null)
  6303. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  6304. })
  6305. .catch((err: Error) => {
  6306. this.lyricController.setLyric(null)
  6307. this.lyricControllerXF.setLyric(null)
  6308. this.lyricControllerSingle.setLyric(null)
  6309. console.error("read file 2 data failed with error message: " + err.message);
  6310. })
  6311. .finally(() => {
  6312. fs.closeSync(file);
  6313. });
  6314. } catch (error) {
  6315. this.lyricController.setLyric(null)
  6316. this.lyricControllerSingle.setLyric(null)
  6317. this.lyricControllerXF.setLyric(null)
  6318. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  6319. }
  6320. }
  6321. detect(data: ArrayBuffer): string {
  6322. //创建检测对象
  6323. let detector: UniversalDetector = new UniversalDetector();
  6324. // 传入检测数据并实时判断编码格式
  6325. detector.handleData(data, 0, data.byteLength);
  6326. // 标记检测数据 读取结束
  6327. detector.dataEnd();
  6328. // 获取检测结果
  6329. let detected: string = detector.getDetectedCharset();
  6330. // 释放资源
  6331. detector.reset();
  6332. return detected;
  6333. }
  6334. //初始化悬浮歌词的自定义设置
  6335. initPipLyricSetting() {
  6336. this.lyricControllerXF
  6337. .setTextSize(this.currentLyricSize)
  6338. .setCacheSize(4)
  6339. .setTextColor("#DDDDDD")
  6340. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  6341. .setEmptyHint("")
  6342. .setAnimationDuration(1000)
  6343. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  6344. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  6345. this.setBlurDegree(this.blurDegreePip, true)
  6346. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  6347. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  6348. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  6349. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  6350. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  6351. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  6352. this.lyricControllerXF.setHightLightCenter(true)
  6353. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  6354. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  6355. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6356. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  6357. if (this.pipBgIndex === 0) {
  6358. if (this.cover) {
  6359. this.pipBg = this.cover
  6360. } else {
  6361. this.pipBg = this.imageColor
  6362. }
  6363. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6364. }
  6365. }
  6366. //根据item返回歌词内容
  6367. async getLyricContent(item: VideoItem): Promise<string> {
  6368. let neiqianLrc = ''
  6369. let lyContent = item?.lyricContent
  6370. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  6371. neiqianLrc = lyContent
  6372. return neiqianLrc
  6373. }
  6374. try {
  6375. let filePath = item.filePath;
  6376. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  6377. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  6378. let isJiaMi = false;
  6379. let realLyricPath = lyricPath;
  6380. if (FileUtil.accessSync(jiaMilyricPath)) {
  6381. isJiaMi = true;
  6382. realLyricPath = jiaMilyricPath;
  6383. console.info("onecold 找到加密本地歌词");
  6384. } else {
  6385. console.info("onecold 找到本地歌词");
  6386. }
  6387. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6388. const stat = await fileIo.stat(file.fd);
  6389. const arrayBuffer = new ArrayBuffer(stat.size);
  6390. const readLen = await fs.read(file.fd, arrayBuffer);
  6391. console.info("read file data succeed");
  6392. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6393. if (buf.length === 0) {
  6394. throw new Error("Buffer is empty after reading the file");
  6395. }
  6396. // let detectedEncoding = chardet.detect(buf);
  6397. let detectedEncoding = this.detect(arrayBuffer)
  6398. console.info("Detected encoding: " + detectedEncoding);
  6399. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6400. let fileContent = textDecoder.decode(buf);
  6401. console.info(`onecold The content of file1: ${fileContent}`);
  6402. if (isJiaMi) {
  6403. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  6404. }
  6405. console.info(`onecold The content of file2: ${fileContent}`);
  6406. fs.closeSync(file);
  6407. return fileContent;
  6408. } catch (error) {
  6409. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  6410. return '';
  6411. }
  6412. }
  6413. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  6414. if (StrUtil.isEmpty(filePath)) {
  6415. return
  6416. }
  6417. try {
  6418. //将content进行加密
  6419. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  6420. let lyricContent = ''
  6421. if (isJiaMi) {
  6422. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  6423. } else {
  6424. lyricContent = content
  6425. }
  6426. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  6427. // 清空文件内容
  6428. await fileIo.truncate(file.fd, 0);
  6429. await fileIo.write(file.fd, lyricContent);
  6430. await fileIo.close(file);
  6431. console.log('onecold lyric file Data saved successfully.');
  6432. } catch (error) {
  6433. console.error('onecold lyric file Failed to save data:', error);
  6434. }
  6435. }
  6436. /**
  6437. * Get largest proportion color of an image.
  6438. */
  6439. getImageColor() {
  6440. if (!this.context) {
  6441. return;
  6442. }
  6443. let bg = Utility.getMusisBg()
  6444. this.imageLabel = bg
  6445. ColorConversion.setSysBarLightBackground(true);
  6446. this.context.resourceManager.getMediaContent(bg)
  6447. .then((value: Uint8Array) => {
  6448. let buffer = value.buffer as ArrayBuffer;
  6449. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  6450. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  6451. if (error) {
  6452. Logger.error('Failed to create color picker.');
  6453. } else {
  6454. let color = colorPicker.getLargestProportionColor();
  6455. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  6456. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  6457. }
  6458. })
  6459. let headFilter = effectKit.createEffect(pixelMap);
  6460. if (headFilter !== null) {
  6461. headFilter.blur(15);
  6462. headFilter.getEffectPixelMap().then((value) => {
  6463. this.imageLabelBg = value;
  6464. })
  6465. }
  6466. })
  6467. .catch((error: BusinessError) => {
  6468. Logger.error(`${error.code} + ${error.message}`)
  6469. })
  6470. })
  6471. .catch((error: BusinessError) => {
  6472. Logger.error(`${error.code} + ${error.message}`)
  6473. })
  6474. }
  6475. setImageColor(cover: string) {
  6476. if (!this.context) {
  6477. return;
  6478. }
  6479. if (cover === undefined) {
  6480. return;
  6481. }
  6482. ImageUtils.imagePathToPixelMap(cover).then((value) => {
  6483. let headFilter = effectKit.createEffect(value);
  6484. if (headFilter !== null) {
  6485. headFilter.blur(15);
  6486. headFilter.getEffectPixelMap().then((value) => {
  6487. this.imageLabelBg = value;
  6488. })
  6489. }
  6490. }).catch((error: BusinessError) => {
  6491. Logger.error(`${error.code} + ${error.message}`)
  6492. })
  6493. }
  6494. setImageColor2(cover: string) {
  6495. if (!this.context) {
  6496. return;
  6497. }
  6498. if (cover === undefined) {
  6499. return;
  6500. }
  6501. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  6502. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  6503. this.imageColor = data.imageColor;
  6504. if (data.blurPixelMap) {
  6505. this.imageLabelBg = data.blurPixelMap;
  6506. }
  6507. })
  6508. }
  6509. // 定义开始旋转的方法
  6510. // 定时器用于一百毫秒执行一次旋转角度
  6511. @State timer: number = 0
  6512. @State rotateAngle: number = 0
  6513. //封面旋转动画
  6514. animationRoFun() {
  6515. if (this.isPlaying && !this.isCoverRectangle) {
  6516. this.timer = setInterval(() => {
  6517. this.rotateAngle += 1
  6518. }, 100)
  6519. this.startRotation()
  6520. } else {
  6521. clearInterval(this.timer)
  6522. this.stopRotation()
  6523. }
  6524. }
  6525. // 定义开始旋转的方法
  6526. startRotation() {
  6527. if (this.isPlaying) {
  6528. animateTo({
  6529. duration: 777,
  6530. iterations: 1,
  6531. curve: Curve.Linear
  6532. }, () => {
  6533. this.rotateAngle2 = 0
  6534. })
  6535. }
  6536. }
  6537. // 回调,暂停和播放按钮回调,下一首和上一首
  6538. playChange() {
  6539. // if(this.isCoverRectangle){
  6540. // return
  6541. // }
  6542. const isPlaying = this.CONTROL_PlayStatus === PlayStatus.PLAY;
  6543. // 同步所有播放状态
  6544. this.setIsPlaying(isPlaying);
  6545. this.animationState = isPlaying ? AnimationStatus.Running : AnimationStatus.Paused;
  6546. // 记录状态变化日志
  6547. LogUtils.getInstance().LOGI(`LocalMusic: playChange - CONTROL_PlayStatus: ${this.CONTROL_PlayStatus}, isPlaying: ${isPlaying}, globalIsPlaying: ${this.isPlaying}`);
  6548. // 强制触发UI刷新 - 这对于@State变量应该是自动的,但我们确保一下
  6549. setTimeout(() => {
  6550. LogUtils.getInstance().LOGI(`LocalMusic: UI refresh triggered - CONTROL_PlayStatus: ${this.CONTROL_PlayStatus}`);
  6551. }, 50);
  6552. }
  6553. // 手动同步状态的方法,用于调试
  6554. public forceSyncState(): void {
  6555. const currentState = this.unifiedPlayerService.getCurrentState();
  6556. LogUtils.getInstance().LOGI(`LocalMusic: Force sync - UnifiedPlayerService state: isPlaying=${currentState.isPlaying}, isPaused=${currentState.isPaused}`);
  6557. // 手动触发状态同步
  6558. if (currentState.isPlaying) {
  6559. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  6560. } else if (currentState.isPaused) {
  6561. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  6562. } else {
  6563. this.CONTROL_PlayStatus = PlayStatus.INIT;
  6564. }
  6565. this.setIsPlaying(currentState.isPlaying);
  6566. this.playChange();
  6567. LogUtils.getInstance().LOGI(`LocalMusic: Force sync completed - CONTROL_PlayStatus: ${this.CONTROL_PlayStatus}`);
  6568. }
  6569. // 定义停止旋转的方法
  6570. stopRotation() {
  6571. if (this.isCoverRectangle) {
  6572. this.rotateAngle = 0
  6573. } else {
  6574. //唱针以左上角为点选择逆时针40度
  6575. animateTo({
  6576. duration: 1000,
  6577. curve: Curve.Linear,
  6578. iterations: 1,
  6579. }, () => {
  6580. this.rotateAngle2 = -40;
  6581. });
  6582. }
  6583. }
  6584. @Builder
  6585. private LyricsTopItem() {
  6586. Row() {
  6587. Stack() {
  6588. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6589. .height(55)
  6590. .width(55)
  6591. .alt(this.imageLabel)
  6592. .borderRadius(8)
  6593. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6594. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6595. }
  6596. .width('18%')
  6597. Column() {
  6598. Column() {
  6599. Text(this.name)
  6600. .fontSize(16)
  6601. .maxLines(1)
  6602. .fontWeight(FontWeight.Bolder)
  6603. .fontColor(this.currentLyricColor)
  6604. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6605. Row() {
  6606. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6607. .fontSize(13)
  6608. .fontWeight(FontWeight.Bold)
  6609. .padding({ top: 8 })
  6610. .fontColor(this.currentLyricColor)
  6611. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6612. Blank()
  6613. }
  6614. }
  6615. .height('100%')
  6616. .width('100%')
  6617. .justifyContent(FlexAlign.Center)
  6618. .alignItems(HorizontalAlign.Start)
  6619. }
  6620. .height('100%')
  6621. .width('65%')
  6622. Column() {
  6623. Image($r('app.media.lyric'))
  6624. .width(28)
  6625. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6626. .margin({ right: 30 })
  6627. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6628. .onClick(() => {
  6629. this.isLyricSetting = !this.isLyricSetting;
  6630. })
  6631. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6632. height: this.isCoverOpacity() ? '95%' : '88%',
  6633. dragBar: true,
  6634. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6635. showClose: true,
  6636. blurStyle: BlurStyle.Thin,
  6637. backgroundColor: Color.Transparent,
  6638. // title: { title: $r('app.string.lyric_setting') }
  6639. })
  6640. }
  6641. .width('18%')
  6642. }
  6643. .width('82%')
  6644. .height(58)
  6645. .justifyContent(FlexAlign.SpaceBetween)
  6646. }
  6647. //歌词显示
  6648. @Builder
  6649. PlayerLyrics() {
  6650. Column() {
  6651. Column() {
  6652. this.LyricsTopItem()
  6653. }
  6654. .height(this.isPuraWP() ? 15 : 58)
  6655. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6656. Visibility.None : Visibility.Visible)
  6657. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6658. .width("100%")
  6659. Column() {
  6660. LyricView2({
  6661. controller: this.lyricController,
  6662. enableSeek: true,
  6663. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6664. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6665. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6666. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6667. if (!this.isPlaying) {
  6668. this.startPlayOrResumePlay()
  6669. } else {
  6670. this.isSeekTo = true;
  6671. this.mDestroyPage = false;
  6672. this.showLoadIng();
  6673. this.seekTo(position + "");
  6674. this.isSeekTo = false;
  6675. }
  6676. return true
  6677. }
  6678. })
  6679. .width("100%")
  6680. .layoutWeight(1)
  6681. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6682. if (this.isPhoneLan()) {
  6683. Column() {
  6684. this.playProgressView()
  6685. // this.playCenterView()
  6686. }
  6687. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6688. }
  6689. }
  6690. .position({
  6691. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6692. (this.isPuraWP() ? 58 : 99)
  6693. })
  6694. .justifyContent(FlexAlign.Center)
  6695. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  6696. }
  6697. }
  6698. @Builder
  6699. SingleLyricView() {
  6700. Column() {
  6701. Column() {
  6702. LyricView2({
  6703. controller: this.lyricControllerSingle,
  6704. enableSeek: false,
  6705. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6706. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6707. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6708. })
  6709. }
  6710. .height(66)
  6711. .margin({ bottom: 20 })
  6712. }
  6713. }
  6714. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6715. @Builder
  6716. BottomControl() {
  6717. Column() {
  6718. this.TopPlayProgressView()
  6719. //播放 暂停,下一首,上一首
  6720. this.playCenterView()
  6721. //播放进度条
  6722. this.BottomView()
  6723. }
  6724. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  6725. }
  6726. //播放控制上一首 下一首 暂停和播放
  6727. @Builder
  6728. playCenterView(){
  6729. Row() {
  6730. Row({ space: 20 }) {
  6731. Button({type:ButtonType.Circle,stateEffect:true}){
  6732. //更多功能
  6733. Image($r('app.media.menu'))
  6734. .width(24)
  6735. .clickEffect({level:ClickEffectLevel.MIDDLE})
  6736. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6737. height: this.isCoverOpacity() ? '95%' : '93%',
  6738. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6739. dragBar: true,
  6740. showClose: true,
  6741. blurStyle: BlurStyle.Thin,
  6742. backgroundColor: Color.Transparent,
  6743. })
  6744. }
  6745. .margin({ left: 5 })
  6746. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6747. .backgroundColor(Color.Transparent)
  6748. .onClick(() => {
  6749. this.isShowMoreView = !this.isShowMoreView;
  6750. })
  6751. Button({type:ButtonType.Circle,stateEffect:true}){
  6752. Image($r('app.media.ic_previous'))
  6753. .width(33)
  6754. .clickEffect({level:ClickEffectLevel.HEAVY})
  6755. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6756. }
  6757. .onClick(async () => {
  6758. this.playPrevious()
  6759. })
  6760. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6761. .backgroundColor(Color.Transparent)
  6762. .margin({ left: 5 })
  6763. }
  6764. Button({type:ButtonType.Circle,stateEffect:true}){
  6765. Column() {
  6766. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6767. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  6768. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  6769. .width(this.isPhoneLan()?45:55)
  6770. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6771. .fillColor(Color.White)
  6772. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6773. .onClick(async () => {
  6774. this.playOrPause()
  6775. })
  6776. }
  6777. }
  6778. .backgroundColor(Color.Transparent)
  6779. .layoutWeight(1)
  6780. // .margin({ left: 38, right: 38 })
  6781. Row({ space: 20 }) {
  6782. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6783. Image($r('app.media.ic_next'))
  6784. .width(33)
  6785. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6786. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6787. .onClick(() => {
  6788. this.playNext();
  6789. })
  6790. }
  6791. .backgroundColor(Color.Transparent)
  6792. .margin({ right: 5 })
  6793. .width(33)
  6794. Button({type:ButtonType.Circle,stateEffect:true}){
  6795. //添加或取消收藏
  6796. Image(Utility.getIsFav(this.favList,this.currentSong)?
  6797. $r('app.media.add_fac_light'):$r('app.media.add_fac'))
  6798. .width(24)
  6799. .clickEffect({level:ClickEffectLevel.MIDDLE})
  6800. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6801. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6802. .onClick(async () => {
  6803. if(this.currentSong){
  6804. this.doFav(this.currentSong)
  6805. }
  6806. })
  6807. }
  6808. .backgroundColor(Color.Transparent)
  6809. .width(24)
  6810. }
  6811. // .margin({ left: 5 })
  6812. }
  6813. .width('95%')
  6814. .margin({ bottom:this.isCoverOpacity()?0:20 })
  6815. .justifyContent(FlexAlign.SpaceEvenly)
  6816. }
  6817. //播放进度条
  6818. @Builder
  6819. TopPlayProgressView(){
  6820. Row() {
  6821. Column(){
  6822. Row(){
  6823. Slider({
  6824. value: this.progressValue,
  6825. min: 0,
  6826. max: this.PROGRESS_MAX_VALUE,
  6827. step: 1,
  6828. style: SliderStyle.InSet
  6829. })
  6830. .blockColor('rgba(255,255,255,1)')
  6831. .trackColor('rgba(255,255,255,0.3)')
  6832. .selectedColor(Color.White)
  6833. .trackThickness(4)
  6834. .layoutWeight(1)
  6835. .showSteps(false)
  6836. .showTips(true)
  6837. .enabled(this.slideEnable)
  6838. .onChange((value: number, mode: SliderChangeMode) => {
  6839. // if (mode == 2) {
  6840. this.isSeekTo = true;
  6841. this.mDestroyPage = false;
  6842. this.showLoadIng();
  6843. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6844. let seekValue = value * ((this.unifiedPlayerService.getIjkPlayer() as IjkMediaPlayer)?.getDuration() / 100);
  6845. this.seekTo(seekValue + "");
  6846. // this.setProgress()
  6847. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6848. this.isSeekTo = false;
  6849. // }
  6850. })
  6851. }
  6852. .padding({ right: 7,left:14 })
  6853. Row(){
  6854. Text(this.currentTime)
  6855. .fontSize(10)
  6856. .fontColor(Color.White)
  6857. Blank()
  6858. .layoutWeight(1)
  6859. Text(this.totalTime)
  6860. .fontSize(10)
  6861. .fontColor(Color.White)
  6862. }
  6863. .justifyContent(FlexAlign.Start)
  6864. .padding({ right: 18,left:36 })
  6865. }
  6866. }
  6867. //x5的竖屏模式需要99%
  6868. .width(this.isLandscape?'80%':'93%')
  6869. .justifyContent(FlexAlign.Center)
  6870. .margin({bottom:5})
  6871. .animation({
  6872. duration: 666,
  6873. curve: 'ease-in-out' // 可选动画曲线
  6874. })
  6875. }
  6876. //播放进度条
  6877. @Builder
  6878. BottomView(){
  6879. Row() {
  6880. Button({type:ButtonType.Circle,stateEffect:true}){
  6881. Column() {
  6882. if (this.playType === 0) {
  6883. Image($r('app.media.loop'))
  6884. .width(27)
  6885. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6886. } else if (this.playType === 1) {
  6887. Image($r('app.media.single'))
  6888. .width(27)
  6889. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6890. } else if (this.playType === 2) {
  6891. Image($r('app.media.normal_play'))
  6892. .width(27)
  6893. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6894. } else if (this.playType === 3) {
  6895. Image($r('app.media.random'))
  6896. .width(27)
  6897. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6898. }
  6899. }
  6900. }
  6901. .layoutWeight(1)
  6902. .margin({ left: 5 })
  6903. .backgroundColor(Color.Transparent)
  6904. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6905. .onClick(async () => {
  6906. this.setLoopMode()
  6907. })
  6908. Button({type:ButtonType.Circle,stateEffect:true}){
  6909. Column() {
  6910. Image($r('app.media.full_4'))
  6911. .width(25)
  6912. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6913. }
  6914. }
  6915. .layoutWeight(1)
  6916. .backgroundColor(Color.Transparent)
  6917. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6918. .onClick(async () => {
  6919. if (this.isLandscape) {
  6920. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  6921. } else {
  6922. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  6923. }
  6924. })
  6925. Button({type:ButtonType.Circle,stateEffect:true}){
  6926. Column() {
  6927. Image($r('app.media.lyric'))
  6928. .width(26)
  6929. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6930. }
  6931. }
  6932. .layoutWeight(1)
  6933. .backgroundColor(Color.Transparent)
  6934. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6935. .onClick(async () => {
  6936. this.isLyricSetting = !this.isLyricSetting;
  6937. })
  6938. //播放列表
  6939. Button({type:ButtonType.Circle,stateEffect:true}){
  6940. Image($r('app.media.hm_playlist'))
  6941. .width(24)
  6942. .fillColor(Color.White)
  6943. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6944. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6945. height: '95%',
  6946. dragBar: true,
  6947. showClose: true,
  6948. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6949. blurStyle: BlurStyle.Thin,
  6950. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  6951. title: {
  6952. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6953. + `(${this.songList.length}首)`
  6954. }
  6955. })
  6956. }
  6957. .layoutWeight(1)
  6958. .backgroundColor(Color.Transparent)
  6959. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6960. .onClick(() => {
  6961. this.isShowSheetView = !this.isShowSheetView;
  6962. if(this.isPlayListBgGrass){
  6963. this.isFrontWhite = true
  6964. }else{
  6965. this.isFrontWhite = false
  6966. }
  6967. setTimeout(() => {
  6968. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6969. }, 123)
  6970. })
  6971. }
  6972. .width(this.isLandscape?'88%':'95%')
  6973. .justifyContent(FlexAlign.SpaceAround)
  6974. .height(30)
  6975. .margin({top:3})
  6976. .animation({
  6977. duration: 666,
  6978. curve: 'ease-in-out' // 可选动画曲线
  6979. })
  6980. }
  6981. //旧版本播放进度条
  6982. @Builder
  6983. playProgressView() {
  6984. Row() {
  6985. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6986. Column() {
  6987. if (this.playType === 0) {
  6988. Image($r('app.media.loop'))
  6989. .width($r('app.float.control_image_width'))
  6990. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6991. } else if (this.playType === 1) {
  6992. Image($r('app.media.single'))
  6993. .width($r('app.float.control_image_width'))
  6994. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6995. } else if (this.playType === 2) {
  6996. Image($r('app.media.normal_play'))
  6997. .width($r('app.float.control_image_width'))
  6998. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6999. } else if (this.playType === 3) {
  7000. Image($r('app.media.random'))
  7001. .width($r('app.float.control_image_width'))
  7002. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7003. }
  7004. }
  7005. }
  7006. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  7007. .animation({
  7008. duration: 666,
  7009. curve: 'ease-in-out' // 可选动画曲线
  7010. })
  7011. .backgroundColor(Color.Transparent)
  7012. .margin({ right: 10 })
  7013. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7014. .onClick(async () => {
  7015. this.setLoopMode()
  7016. })
  7017. Text(this.currentTime)
  7018. .fontSize($r('app.float.slider_font_size'))
  7019. .fontColor(Color.White)
  7020. .margin(3)
  7021. Slider({
  7022. value: this.progressValue,
  7023. min: 0,
  7024. max: this.PROGRESS_MAX_VALUE,
  7025. step: 1,
  7026. style: SliderStyle.OutSet
  7027. })
  7028. .width('600px')
  7029. .blockColor('rgba(255,255,255,1)')
  7030. .trackColor('rgba(255,255,255,0.3)')
  7031. .selectedColor(Color.White)
  7032. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  7033. .layoutWeight(1)
  7034. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  7035. .showSteps(false)
  7036. .showTips(true)
  7037. .enabled(this.slideEnable)
  7038. .onChange((value: number, mode: SliderChangeMode) => {
  7039. // if (mode == 2) {
  7040. this.isSeekTo = true;
  7041. this.mDestroyPage = false;
  7042. this.showLoadIng();
  7043. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  7044. // 通过UnifiedPlayerService获取时长并计算拖动位置
  7045. const currentState = this.unifiedPlayerService.getCurrentState();
  7046. let seekValue = value * (currentState.duration / 100);
  7047. this.seekTo(seekValue + "");
  7048. // this.setProgress()
  7049. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  7050. this.isSeekTo = false;
  7051. // }
  7052. })
  7053. Text(this.totalTime)
  7054. .fontSize($r('app.float.slider_font_size'))
  7055. .fontColor(Color.White)
  7056. .margin(3)
  7057. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  7058. //播放列表
  7059. Button({ type: ButtonType.Circle, stateEffect: true }) {
  7060. Image($r('app.media.hm_playlist'))
  7061. .width($r('app.float.control_image_width'))
  7062. .fillColor(Color.White)
  7063. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7064. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  7065. height: '95%',
  7066. dragBar: true,
  7067. showClose: true,
  7068. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7069. blurStyle: BlurStyle.Thin,
  7070. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  7071. title: {
  7072. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  7073. + `(${this.songList.length}首)`
  7074. }
  7075. })
  7076. }
  7077. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  7078. .animation({
  7079. duration: 666,
  7080. curve: 'ease-in-out' // 可选动画曲线
  7081. })
  7082. .backgroundColor(Color.Transparent)
  7083. .margin({ right: 20, left: 10 })
  7084. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7085. .onClick(() => {
  7086. this.isShowSheetView = !this.isShowSheetView;
  7087. if (this.isPlayListBgGrass) {
  7088. this.isFrontWhite = true
  7089. } else {
  7090. this.isFrontWhite = false
  7091. }
  7092. setTimeout(() => {
  7093. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  7094. }, 123)
  7095. })
  7096. }
  7097. //x5的竖屏模式需要99%
  7098. .width(this.isPhonePortrait() ? '93.4%'
  7099. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  7100. .height(this.isPhoneLan() ? 25 : 33)
  7101. .animation({
  7102. duration: 666,
  7103. curve: 'ease-in-out' // 可选动画曲线
  7104. })
  7105. }
  7106. isBigScreen() {
  7107. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  7108. return true
  7109. }
  7110. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  7111. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  7112. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  7113. return false
  7114. } else {
  7115. return true
  7116. }
  7117. return false
  7118. }
  7119. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  7120. @State isCoverRectangle: boolean = false
  7121. @State isCoverTop: boolean = true
  7122. // 添加控制缩放的状态变量
  7123. @State scaleValueImage: number = 1
  7124. @Builder
  7125. CoverInfo() {
  7126. Column() {
  7127. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  7128. if (this.isCoverRectangle) {
  7129. if (!this.isCoverTop) {
  7130. this.musicNameInfo(false)
  7131. }
  7132. } else {
  7133. this.musicNameInfo(false)
  7134. }
  7135. Stack() {
  7136. // 唱片旋转效果
  7137. Image($r('app.media.ic_music_disc'))
  7138. .width(245)
  7139. .height(245)
  7140. .margin({ right: 20, left: 20 })
  7141. .aspectRatio(1)
  7142. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7143. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7144. .borderRadius('100%')
  7145. .align(Alignment.Center)
  7146. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  7147. .rotate({
  7148. angle: this.rotateAngle,
  7149. centerX: "50%",
  7150. centerY: "50%",
  7151. })
  7152. .animation({
  7153. duration: 100,
  7154. curve: Curve.Linear
  7155. })
  7156. .shadow({
  7157. radius: 30,
  7158. color: this.randomColor
  7159. })
  7160. Column() {
  7161. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  7162. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  7163. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  7164. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7165. .alt(this.imageLabel)
  7166. .margin({ right: 8, left: 8, top: 8 })
  7167. .aspectRatio(1)
  7168. .opacity(this.opacityValueImage)
  7169. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7170. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7171. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7172. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7173. .align(Alignment.Center)//
  7174. .clip(true)
  7175. .rotate({
  7176. x: 0,
  7177. y: 0,
  7178. z: 1,
  7179. angle: this.rotateAngle
  7180. })
  7181. .onClick(() => {
  7182. this.getImageColor()
  7183. })
  7184. this.musicNameInfo(false)
  7185. } else {
  7186. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7187. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  7188. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7189. .alt(this.imageLabel)
  7190. .margin({ right: 20, left: 20 })
  7191. .aspectRatio(1)
  7192. .opacity(this.opacityValueImage)
  7193. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7194. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7195. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7196. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7197. .align(Alignment.Center)//
  7198. .clip(true)
  7199. .rotate({
  7200. x: 0,
  7201. y: 0,
  7202. z: 1,
  7203. angle: this.rotateAngle
  7204. })
  7205. .onClick(() => {
  7206. this.getImageColor()
  7207. })
  7208. if (this.isPhoneLan()) {
  7209. Text(this.name)
  7210. .fontSize(18)
  7211. .fontWeight(FontWeight.Bold)
  7212. .margin({ top: 13 })
  7213. .textOverflow({ overflow: TextOverflow.Ellipsis })
  7214. .maxLines(1)
  7215. .width('99%')
  7216. .textAlign(TextAlign.Center)
  7217. .fontColor(Color.White)
  7218. }
  7219. }
  7220. }
  7221. // 唱针以左上角为点选择逆时针40度
  7222. Image($r('app.media.ic_music_cover_hand'))
  7223. .height(130)
  7224. .margin({ bottom: 220, top: 0 })
  7225. .align(Alignment.Top)
  7226. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  7227. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7228. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7229. Column({ space: 8 }) {
  7230. Text(this.name)
  7231. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  7232. .fontWeight(FontWeight.Bold)
  7233. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7234. .maxLines(1)
  7235. .width('48%')
  7236. .textAlign(TextAlign.Center)
  7237. .fontColor(Color.White)
  7238. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7239. Text(this.artist)
  7240. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  7241. .fontColor(Color.White)
  7242. .fontWeight(FontWeight.Bold)
  7243. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7244. }
  7245. .justifyContent(FlexAlign.Start)
  7246. .zIndex(1)
  7247. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  7248. }
  7249. .margin({
  7250. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  7251. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  7252. top: this.isCoverOpacity() ? 0 : 20
  7253. })
  7254. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  7255. this.SingleLyricView()
  7256. }
  7257. if (this.isPhoneLan()) {
  7258. Column() {
  7259. this.playCenterView()
  7260. // this.playProgressView()
  7261. }
  7262. .position({ left: 28, bottom: 38 })
  7263. } else {
  7264. this.BottomControl()
  7265. }
  7266. }
  7267. .width(CommonConstants.FULL_PERCENT)
  7268. .clip(true)
  7269. }
  7270. @Builder
  7271. private musicNameInfo(isHidden: boolean) {
  7272. Column({ space: 8 }) {
  7273. Text(this.name)
  7274. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  7275. .fontWeight(FontWeight.Bold)
  7276. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7277. .maxLines(1)
  7278. .width('99%')
  7279. .textAlign(TextAlign.Center)
  7280. .fontColor(Color.White)
  7281. Text(this.artist + ' ' + this.currentSong?.album)
  7282. .fontSize(this.isCoverOpacity() ? 12 : 15)
  7283. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7284. .fontColor(Color.White)
  7285. .textAlign(TextAlign.Center)
  7286. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  7287. .width('99%')
  7288. .maxLines(1)
  7289. }
  7290. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  7291. .zIndex(1)
  7292. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7293. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  7294. }
  7295. @Builder
  7296. private PlayTitle() {
  7297. Row() {
  7298. Row() {
  7299. Image($r('app.media.ic_back_down'))
  7300. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  7301. .hitTestBehavior(HitTestMode.Transparent)
  7302. Text(this.name + ' ' + this.artist)
  7303. .fontColor(Color.White)
  7304. .fontSize($r('app.float.title_font_size'))
  7305. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7306. .maxLines(1)
  7307. .visibility(Visibility.None)
  7308. .margin({ left: 2, right: 30 })
  7309. }
  7310. .layoutWeight(1)
  7311. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7312. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  7313. .onClick(() => {
  7314. this.isShowPlay = false;
  7315. })
  7316. Column() {
  7317. AVCastPicker({
  7318. normalColor: Color.White,
  7319. onStateChange: this.onStateVastChange
  7320. })
  7321. .width(24)
  7322. .height(24)
  7323. }
  7324. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  7325. }
  7326. .width(PlayConstants.ROW_WIDTH)
  7327. }
  7328. @Builder
  7329. lyricSettingSheet(isPip: boolean) {
  7330. Scroll() {
  7331. this.lyricSetting(isPip)
  7332. }
  7333. .width('100%')
  7334. .height('100%')
  7335. }
  7336. @Builder
  7337. lyricSetting(isPip: boolean) {
  7338. Column() {
  7339. // 时间调节模块
  7340. if (!isPip) {
  7341. this.BuildTimeControls()
  7342. }
  7343. // 字号控制模块
  7344. this.BuildFontControls(isPip)
  7345. }
  7346. }
  7347. // 歌词时间偏移状态
  7348. @State timeOffset: number = 0.0
  7349. @State currentLyricColor: string = '#FFFFFF'
  7350. @State currentLyricColorPip: string = '#FFFFFF'
  7351. @State currentHighLightLyricColor: string = '#FF4081'
  7352. @State currentHighLightLyricColorPip: string = '#FF4081'
  7353. // 歌词字号状态
  7354. @State currentLyricSize: number = 20
  7355. @State currentLyricSizePip: number = 20
  7356. // 高亮歌词放大倍数
  7357. @State currentHightLyricSize: number = 1.2
  7358. @State currentHightLyricSizePip: number = 1.2
  7359. @State currentLyricLineSpace: number = 10
  7360. @State currentLyricLineSpacePip: number = 10
  7361. @State currentLyricAlignMode: number = 1
  7362. @State currentLyricAlignModePip: number = 1
  7363. @State blurDegree: number = 2
  7364. @State blurDegreePip: number = 2
  7365. @State isShowSelectColor: boolean = false
  7366. @State isShowHLSelectColor: boolean = false
  7367. @State isShowPipBgSelectColor: boolean = false
  7368. @State pipLyWidth: number = 330
  7369. @State pipLyHeight: number = 120
  7370. // 构建颜色选择器
  7371. @Builder
  7372. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  7373. Row({ space: 10 }) {
  7374. HSBColorPicker({
  7375. color: '#FFFFFF',
  7376. radius: 8,
  7377. layout: HSBColorPickerLayout.COLUMN,
  7378. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  7379. '#fa7105'],
  7380. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  7381. this.changeLyricColor(value, isPip, isBGPip)
  7382. })
  7383. .height(250)
  7384. .layoutWeight(1)
  7385. .padding(25)
  7386. }
  7387. .width('66%')
  7388. }
  7389. @State isOpenPip: boolean = false
  7390. @State pipBgIndex: number = 0
  7391. // 构建字号控制器
  7392. @Builder
  7393. BuildFontControls(isPip: boolean) {
  7394. Column() {
  7395. if (isPip) {
  7396. Column() {
  7397. Row() {
  7398. Text('悬浮歌词')
  7399. .margin({ left: 18 })
  7400. .fontSize(15)
  7401. .fontColor(Color.White)
  7402. .fontWeight(480)
  7403. .layoutWeight(1)
  7404. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  7405. .selectedColor(this.themeColor)
  7406. .switchPointColor(Color.White)
  7407. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7408. .margin({ right: 18 })
  7409. .onChange((checked: boolean) => {
  7410. this.isOpenPip = checked;
  7411. if (this.isOpenPip) {
  7412. this.startPip()
  7413. } else {
  7414. this.stopPip()
  7415. }
  7416. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  7417. })
  7418. .width(50)
  7419. .height(30);
  7420. }
  7421. .height(55)
  7422. }
  7423. .backgroundColor(Color.Transparent)
  7424. .borderRadius(15)
  7425. .margin({
  7426. left: 30,
  7427. right: 30,
  7428. top: 0,
  7429. bottom: 20
  7430. })
  7431. .padding(0)
  7432. .border({
  7433. color: Color.White,
  7434. width: 1.8
  7435. })
  7436. }
  7437. Row() {
  7438. Text(`歌词居中:`)
  7439. .fontSize(14)
  7440. .fontColor(Color.White)
  7441. .margin({ left: 2 })
  7442. Row() {
  7443. ForEach(['居中', '居左'], (size: string, index: number) => {
  7444. Button(size)
  7445. .width(60)
  7446. .height(28)
  7447. .fontSize(12)
  7448. .fontColor('#FFFFFF')
  7449. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  7450. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  7451. .border({
  7452. color: (!isPip && this.currentLyricAlignMode === index) ||
  7453. (isPip && this.currentLyricAlignModePip === index) ?
  7454. '#007DFF' : '#DDDDDD',
  7455. width: 1.8
  7456. })
  7457. .onClick(() => {
  7458. this.setLyricAlignMode(index, isPip)
  7459. })
  7460. .margin({ left: 10, right: 8 })
  7461. })
  7462. }
  7463. .width('76%')
  7464. Blank()
  7465. }
  7466. .margin({
  7467. top: 10,
  7468. bottom: 10,
  7469. right: 20,
  7470. left: 20
  7471. })
  7472. if (isPip) {
  7473. Row() {
  7474. Text(`悬浮背景:`)
  7475. .fontSize(14)
  7476. .fontColor(Color.White)
  7477. Select([
  7478. { value: CommonConstants.PIP_LYRIC_BG[0] },
  7479. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  7480. .font({ size: 13, weight: FontWeight.Medium })
  7481. .fontColor(Color.White)
  7482. .margin({ left: 10 })
  7483. .selected(this.pipBgIndex)
  7484. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  7485. .onSelect(async (_index: number, text?: string | undefined) => {
  7486. this.pipBgIndex = _index
  7487. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  7488. if (this.pipBgIndex === 0) {
  7489. if (this.cover) {
  7490. this.pipBg = this.cover
  7491. } else {
  7492. this.pipBg = this.imageColor
  7493. }
  7494. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7495. } else {
  7496. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7497. }
  7498. })
  7499. Column() {
  7500. }
  7501. .backgroundColor(this.pipBg)
  7502. .margin({ left: 10, right: 10 })
  7503. .borderRadius(20)
  7504. .height(28)
  7505. .width(28)
  7506. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7507. Row() {
  7508. SymbolGlyph($r('sys.symbol.paintbrush'))
  7509. .fontColor([Color.White])
  7510. .effectStrategy(1)
  7511. Text(`选择颜色`)
  7512. .fontSize(13)
  7513. .margin({ left: 10 })
  7514. .fontColor(Color.White)
  7515. }
  7516. }
  7517. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  7518. .backgroundColor(Color.Transparent)
  7519. .border({
  7520. color: '#FFFFFF',
  7521. radius: 20,
  7522. width: 1.8
  7523. })
  7524. .height(36)
  7525. .width(110)
  7526. .onClick(() => {
  7527. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  7528. })
  7529. .bindPopup(this.isShowPipBgSelectColor, {
  7530. builder: this.SelectColor(false, isPip, true),
  7531. placement: Placement.Top,
  7532. mask: { color: '#33000000' },
  7533. enableArrow: false, //是否显示箭头
  7534. showInSubWindow: false,
  7535. onStateChange: (e) => {
  7536. if (!e.isVisible) {
  7537. this.isShowPipBgSelectColor = false
  7538. }
  7539. }
  7540. })
  7541. }
  7542. .width('76%')
  7543. .margin({ bottom: 5, right: 45, left: 20 })
  7544. }
  7545. if (!isPip) {
  7546. Row() {
  7547. Text(`高亮居中:`)
  7548. .fontSize(14)
  7549. .fontColor(Color.White)
  7550. Column() {
  7551. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  7552. .selectedColor(this.themeColor)
  7553. .switchPointColor(Color.White)
  7554. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7555. .onChange((checked: boolean) => {
  7556. this.isHightLightCenter = checked;
  7557. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  7558. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7559. })
  7560. .width(50)
  7561. .height(30)
  7562. .alignSelf(ItemAlign.Start)
  7563. .margin({ left: 12 })
  7564. Blank()
  7565. }
  7566. .width('76%')
  7567. }
  7568. .margin({
  7569. left: 20,
  7570. right: 15,
  7571. top: 10,
  7572. bottom: 10
  7573. })
  7574. }
  7575. Row() {
  7576. Text(`歌词颜色:`)
  7577. .fontSize(14)
  7578. .fontColor(Color.White)
  7579. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7580. .fontSize(15)
  7581. .fontColor(Color.White)
  7582. .margin({ left: 12, right: 12 })
  7583. Column() {
  7584. }
  7585. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7586. .margin({ right: 12 })
  7587. .borderRadius(20)
  7588. .height(28)
  7589. .width(28)
  7590. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7591. Row() {
  7592. SymbolGlyph($r('sys.symbol.paintbrush'))
  7593. .fontColor([Color.White])
  7594. .effectStrategy(1)
  7595. Text(`选择颜色`)
  7596. .fontSize(13)
  7597. .margin({ left: 10 })
  7598. .fontColor(Color.White)
  7599. }
  7600. }
  7601. .backgroundColor(Color.Transparent)
  7602. .border({
  7603. color: '#FFFFFF',
  7604. radius: 20,
  7605. width: 1.8
  7606. })
  7607. .height(36)
  7608. .width(110)
  7609. .onClick(() => {
  7610. this.isShowSelectColor = !this.isShowSelectColor
  7611. })
  7612. .bindPopup(this.isShowSelectColor, {
  7613. builder: this.SelectColor(false, isPip),
  7614. placement: Placement.Top,
  7615. mask: { color: '#33000000' },
  7616. enableArrow: false, //是否显示箭头
  7617. showInSubWindow: false,
  7618. onStateChange: (e) => {
  7619. if (!e.isVisible) {
  7620. this.isShowSelectColor = false
  7621. }
  7622. }
  7623. })
  7624. }
  7625. .width('76%')
  7626. .margin({
  7627. top: 10,
  7628. bottom: 10,
  7629. right: 45,
  7630. left: 20
  7631. })
  7632. Row() {
  7633. Text(`高亮颜色:`)
  7634. .fontSize(14)
  7635. .fontColor(Color.White)
  7636. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7637. .fontSize(15)
  7638. .fontColor(Color.White)
  7639. .margin({ left: 12, right: 12 })
  7640. Column() {
  7641. }
  7642. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7643. .margin({ right: 12 })
  7644. .borderRadius(20)
  7645. .height(28)
  7646. .width(28)
  7647. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7648. Row() {
  7649. SymbolGlyph($r('sys.symbol.paintbrush'))
  7650. .fontColor([Color.White])
  7651. .effectStrategy(1)
  7652. Text(`选择颜色`)
  7653. .fontSize(13)
  7654. .margin({ left: 10 })
  7655. .fontColor(Color.White)
  7656. }
  7657. }
  7658. .backgroundColor(Color.Transparent)
  7659. .border({
  7660. color: '#FFFFFF',
  7661. radius: 20,
  7662. width: 1.8
  7663. })
  7664. .height(36)
  7665. .width(110)
  7666. .onClick(() => {
  7667. this.isShowHLSelectColor = !this.isShowHLSelectColor
  7668. })
  7669. .bindPopup(this.isShowHLSelectColor, {
  7670. builder: this.SelectColor(true, isPip),
  7671. placement: Placement.Top,
  7672. mask: { color: '#33000000' },
  7673. enableArrow: false, //是否显示箭头
  7674. showInSubWindow: false,
  7675. onStateChange: (e) => {
  7676. if (!e.isVisible) {
  7677. this.isShowHLSelectColor = false
  7678. }
  7679. }
  7680. })
  7681. }
  7682. .width('76%')
  7683. .margin({
  7684. top: 10,
  7685. bottom: 10,
  7686. right: 45,
  7687. left: 20
  7688. })
  7689. if (isPip) {
  7690. Row() {
  7691. Text(`显示宽度:`)
  7692. .fontSize(14)
  7693. .fontColor(Color.White)
  7694. Slider({
  7695. value: this.pipLyWidth,
  7696. min: 10,
  7697. max: 800,
  7698. step: 1,
  7699. style: SliderStyle.OutSet
  7700. })
  7701. .blockColor(this.themeColor)
  7702. .trackColor($r('app.color.speed_text_color'))
  7703. .selectedColor(Color.White)
  7704. .trackThickness(6)
  7705. .onChange((value: number) => {
  7706. this.pipLyWidth = value
  7707. if (this.pipController) {
  7708. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7709. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  7710. }
  7711. })
  7712. .width('76%')
  7713. }
  7714. .margin({
  7715. left: 20,
  7716. right: 15,
  7717. top: 5,
  7718. bottom: 5
  7719. })
  7720. Row() {
  7721. Text(`显示高度:`)
  7722. .fontSize(14)
  7723. .fontColor(Color.White)
  7724. Slider({
  7725. value: this.pipLyHeight,
  7726. min: 10,
  7727. max: 1000,
  7728. step: 1,
  7729. style: SliderStyle.OutSet
  7730. })
  7731. .blockColor(this.themeColor)
  7732. .trackColor($r('app.color.speed_text_color'))
  7733. .selectedColor(Color.White)
  7734. .trackThickness(6)
  7735. .onChange((value: number) => {
  7736. this.pipLyHeight = value
  7737. if (this.pipController) {
  7738. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7739. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7740. }
  7741. })
  7742. .width('76%')
  7743. }
  7744. .margin({
  7745. left: 20,
  7746. right: 15,
  7747. top: 5,
  7748. bottom: 5
  7749. })
  7750. }
  7751. Row() {
  7752. Text(`歌词字号:`)
  7753. .fontSize(14)
  7754. .fontColor(Color.White)
  7755. Slider({
  7756. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7757. min: 12,
  7758. max: 30,
  7759. step: 0.1,
  7760. style: SliderStyle.OutSet
  7761. })
  7762. .blockColor(this.themeColor)
  7763. .trackColor($r('app.color.speed_text_color'))
  7764. .selectedColor(Color.White)
  7765. .trackThickness(6)
  7766. .onChange((value: number) => {
  7767. this.setLyricTextSize(value, isPip)
  7768. })
  7769. .width('76%')
  7770. }
  7771. .margin({
  7772. left: 20,
  7773. right: 15,
  7774. top: 5,
  7775. bottom: 5
  7776. })
  7777. Row() {
  7778. Text(`高亮倍数:`)
  7779. .fontSize(14)
  7780. .fontColor(Color.White)
  7781. Slider({
  7782. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7783. min: 1,
  7784. max: 2,
  7785. step: 0.1,
  7786. style: SliderStyle.OutSet
  7787. })
  7788. .blockColor(this.themeColor)
  7789. .trackColor($r('app.color.speed_text_color'))
  7790. .selectedColor(Color.White)
  7791. .trackThickness(6)
  7792. .onChange((value: number) => {
  7793. this.setHighLyricTextSize(value, isPip)
  7794. })
  7795. .width('76%')
  7796. }
  7797. .margin({
  7798. left: 20,
  7799. right: 15,
  7800. top: 5,
  7801. bottom: 5
  7802. })
  7803. Row() {
  7804. Text(`歌词间隙:`)
  7805. .fontSize(14)
  7806. .fontColor(Color.White)
  7807. Slider({
  7808. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7809. min: 0,
  7810. max: 100,
  7811. step: 1,
  7812. style: SliderStyle.OutSet
  7813. })
  7814. .blockColor(this.themeColor)
  7815. .trackColor($r('app.color.speed_text_color'))
  7816. .selectedColor(Color.White)
  7817. .trackThickness(6)
  7818. .onChange((value: number) => {
  7819. this.setLyricLineSpace(value, isPip)
  7820. })
  7821. .width('76%')
  7822. }
  7823. .margin({
  7824. left: 20,
  7825. right: 15,
  7826. top: 5,
  7827. bottom: 5
  7828. })
  7829. //取值间隔为100,默认为400,取值越大,字体越粗
  7830. Row() {
  7831. Text(`歌词字重:`)
  7832. .fontSize(14)
  7833. .fontColor(Color.White)
  7834. Slider({
  7835. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7836. min: 100,
  7837. max: 900,
  7838. step: 100,
  7839. style: SliderStyle.OutSet
  7840. })
  7841. .blockColor(this.themeColor)
  7842. .trackColor($r('app.color.speed_text_color'))
  7843. .selectedColor(Color.White)
  7844. .trackThickness(6)
  7845. .onChange((value: number) => {
  7846. if (isPip) {
  7847. this.lyricTextWeightPip = value
  7848. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7849. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7850. } else {
  7851. this.lyricTextWeight = value
  7852. this.lyricController.setTextWeight(this.lyricTextWeight)
  7853. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7854. }
  7855. })
  7856. .width('76%')
  7857. }
  7858. .margin({
  7859. left: 20,
  7860. right: 15,
  7861. top: 5,
  7862. bottom: 5
  7863. })
  7864. if (!isPip) {
  7865. Row() {
  7866. Text(`歌词模糊:`)
  7867. .fontSize(14)
  7868. .fontColor(Color.White)
  7869. Slider({
  7870. value: isPip ? this.blurDegreePip : this.blurDegree,
  7871. min: 0,
  7872. max: 5,
  7873. step: 0.1,
  7874. style: SliderStyle.OutSet
  7875. })
  7876. .blockColor(this.themeColor)
  7877. .trackColor($r('app.color.speed_text_color'))
  7878. .selectedColor(Color.White)
  7879. .trackThickness(6)
  7880. .onChange((value: number) => {
  7881. this.setBlurDegree(value, isPip)
  7882. })
  7883. .width('76%')
  7884. }
  7885. .margin({
  7886. left: 20,
  7887. right: 15,
  7888. top: 5,
  7889. bottom: 15
  7890. })
  7891. }
  7892. Row() {
  7893. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7894. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7895. }
  7896. .justifyContent(FlexAlign.Center)
  7897. .margin({ top: 3, bottom: 10 })
  7898. }
  7899. }
  7900. private setBlurDegree(index: number, isPip: boolean) {
  7901. if (isPip) {
  7902. this.blurDegreePip = index
  7903. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7904. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7905. } else {
  7906. this.blurDegree = index
  7907. this.lyricController.setBlurDegree(this.blurDegree)
  7908. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7909. }
  7910. }
  7911. private setLyricAlignMode(index: number, isPip: boolean) {
  7912. if (isPip) {
  7913. this.currentLyricAlignModePip = index
  7914. if (this.currentLyricAlignModePip === 1) {
  7915. this.lyricControllerXF.setAlignMode("left")
  7916. } else {
  7917. this.lyricControllerXF.setAlignMode("center")
  7918. }
  7919. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7920. } else {
  7921. this.currentLyricAlignMode = index
  7922. if (this.currentLyricAlignMode === 1) {
  7923. this.lyricController.setAlignMode("left")
  7924. } else {
  7925. this.lyricController.setAlignMode("center")
  7926. }
  7927. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7928. }
  7929. }
  7930. private setLyricTextSize(index: number, isPip: boolean) {
  7931. if (isPip) {
  7932. this.currentLyricSizePip = index
  7933. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7934. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7935. } else {
  7936. this.currentLyricSize = index
  7937. this.lyricController.setTextSize(this.currentLyricSize)
  7938. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7939. }
  7940. }
  7941. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7942. if (isPip) {
  7943. this.currentHightLyricSizePip = scale
  7944. this.lyricControllerXF
  7945. .setHighlightScale(this.currentHightLyricSizePip)
  7946. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7947. } else {
  7948. this.currentHightLyricSize = scale
  7949. this.lyricController
  7950. .setHighlightScale(this.currentHightLyricSize)
  7951. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7952. }
  7953. }
  7954. private setLyricLineSpace(index: number, isPip: boolean) {
  7955. if (isPip) {
  7956. this.currentLyricLineSpacePip = index
  7957. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7958. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7959. } else {
  7960. this.currentLyricLineSpace = index
  7961. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7962. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7963. }
  7964. }
  7965. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7966. LogUtil.info('onecold isBG = ' + isBG)
  7967. if (isBG) { //如果是设置悬浮背景
  7968. this.pipBg = color
  7969. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7970. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7971. return
  7972. }
  7973. if (isPip) {
  7974. this.currentLyricColorPip = color
  7975. this.lyricControllerXF
  7976. .setTextColor(this.currentLyricColorPip)
  7977. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7978. } else {
  7979. this.currentLyricColor = color
  7980. this.lyricController
  7981. .setTextColor(this.currentLyricColor)
  7982. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7983. }
  7984. }
  7985. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7986. if (isPip) {
  7987. this.currentHighLightLyricColorPip = color
  7988. this.lyricControllerXF
  7989. .setHighlightColor(this.currentHighLightLyricColorPip)
  7990. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7991. } else {
  7992. this.currentHighLightLyricColor = color
  7993. this.lyricController
  7994. .setHighlightColor(this.currentHighLightLyricColor)
  7995. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7996. }
  7997. }
  7998. // 构建时间控制器
  7999. @Builder
  8000. BuildTimeControls() {
  8001. Column() {
  8002. // 时间显示
  8003. Text(this.getTimeText())
  8004. .fontSize(18)
  8005. .fontColor(Color.White)
  8006. .margin({ bottom: 10 })
  8007. Row() {
  8008. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  8009. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  8010. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  8011. }
  8012. .justifyContent(FlexAlign.Center)
  8013. }
  8014. .margin({ top: 12, bottom: 8 })
  8015. }
  8016. // 精度按钮组件
  8017. @Builder
  8018. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  8019. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8020. Column() {
  8021. Image(icon)
  8022. .width(28)
  8023. .margin({ bottom: 5 })
  8024. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  8025. Text(label)
  8026. .fontSize(12)
  8027. .fontColor('#FFFFFF')
  8028. }
  8029. }
  8030. .backgroundColor(Color.Transparent)
  8031. .enabled(!this.isButtonDisabled(step))
  8032. .onClick(() => this.handlePrecisionAdjust(step))
  8033. .padding(5)
  8034. .width(66)
  8035. .height(66)
  8036. .margin({ left: 18, right: 18 })
  8037. .border({
  8038. color: '#FFFFFF',
  8039. width: 1.8
  8040. })
  8041. }
  8042. private handlePrecisionAdjust(step: number) {
  8043. if (step === 0) {
  8044. this.timeOffset = 0
  8045. return
  8046. }
  8047. // 精度处理:保留1位小数
  8048. const newOffset = Number((this.timeOffset + step).toFixed(5))
  8049. // 边界保护(±15.0秒)
  8050. if (newOffset < -30.0 || newOffset > 30.0) {
  8051. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  8052. return
  8053. }
  8054. // 状态更新
  8055. this.timeOffset = newOffset
  8056. }
  8057. // 按钮禁用逻辑
  8058. private isButtonDisabled(step: number): boolean {
  8059. const futureOffset = this.timeOffset + step
  8060. return (futureOffset < -30.0) || (futureOffset > 30.0)
  8061. }
  8062. // 时间显示文本升级
  8063. private getTimeText(): string {
  8064. const absValue = Math.abs(this.timeOffset)
  8065. return this.timeOffset === 0
  8066. ? '歌词时间已重置'
  8067. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  8068. }
  8069. // 导入 本地歌词 搜索歌词
  8070. @Builder
  8071. pushLyricButton(icon: Resource, step: number, label: string) {
  8072. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8073. Row() {
  8074. Image(icon)
  8075. .width(14)
  8076. .margin({ left: 13 })
  8077. Text(label)
  8078. .fontSize(12)
  8079. .margin({ left: 6 })
  8080. .fontColor('#FFFFFF')
  8081. }
  8082. }
  8083. .onClick(() => {
  8084. switch (step) {
  8085. case 0:
  8086. this.callFilePickerSelectFileForLyric()
  8087. break;
  8088. case 1:
  8089. //判断是不是赞助会员
  8090. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  8091. this.isLyricSetting = false
  8092. this.showTipsDialog()
  8093. return
  8094. }
  8095. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8096. ToastUtil.showToast('正在获取')
  8097. this.isLyricSetting = false
  8098. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8099. this.initLyric(lyricPath, true);
  8100. }
  8101. break;
  8102. }
  8103. })
  8104. .padding(5)
  8105. .width(110)
  8106. .backgroundColor(Color.Transparent)
  8107. .height(40)
  8108. .margin({ left: 6, right: 6 })
  8109. .border({
  8110. color: '#FFFFFF',
  8111. radius: 20,
  8112. width: 1.8
  8113. })
  8114. }
  8115. showVipDialog() {
  8116. DialogHelper.showCustomContentDialog({
  8117. dialogId: 'vip',
  8118. title: "友情提示",
  8119. autoCancel: false, //点击遮障层时,不关闭弹窗
  8120. backCancel: true, //点击返回键,不关闭弹窗
  8121. contentBuilder: () => {
  8122. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  8123. },
  8124. buttons: [],
  8125. })
  8126. }
  8127. //去赞助的自定义内容
  8128. @Builder
  8129. customVipBuilder(content: string) {
  8130. Column() {
  8131. Text(content)
  8132. .fontColor(Color.Gray)
  8133. .fontSize(16)
  8134. .alignSelf(ItemAlign.Start)
  8135. .margin({ bottom: 15 })
  8136. .fontSize(16)
  8137. Row() {
  8138. Button('取消')
  8139. .fontColor(Color.White)
  8140. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8141. .height(50)
  8142. .layoutWeight(1)
  8143. .stateEffect(true)
  8144. .margin({ right: 6 })
  8145. .onClick(() => {
  8146. DialogHelper.closeDialog('vip'); //关闭弹框
  8147. })
  8148. Button('开通')
  8149. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8150. .layoutWeight(1)
  8151. .height(50)
  8152. .backgroundColor(this.themeColor)
  8153. .stateEffect(true)
  8154. .margin({ left: 6 })
  8155. .onClick(() => {
  8156. DialogHelper.closeDialog('vip'); //关闭弹框
  8157. this.isShowPlay = false
  8158. this.mType = 1 //跳转到用户中心
  8159. // router.pushUrl({
  8160. // url: 'pages/VipPage'
  8161. // }, router.RouterMode.Single);
  8162. })
  8163. }
  8164. }
  8165. .width("100%")
  8166. .padding(10)
  8167. }
  8168. showTipsDialog() {
  8169. DialogHelper.showCustomContentDialog({
  8170. dialogId: 'tips',
  8171. title: "友情提示",
  8172. autoCancel: false, //点击遮障层时,不关闭弹窗
  8173. backCancel: true, //点击返回键,不关闭弹窗
  8174. contentBuilder: () => {
  8175. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  8176. },
  8177. buttons: [],
  8178. })
  8179. }
  8180. @Builder
  8181. customTipsBuilder(content: string) {
  8182. Column() {
  8183. Text(content)
  8184. .fontColor(Color.Gray)
  8185. .fontSize(16)
  8186. .alignSelf(ItemAlign.Start)
  8187. .margin({ bottom: 15 })
  8188. .fontSize(16)
  8189. Row() {
  8190. Button('取消')
  8191. .fontColor(Color.White)
  8192. .backgroundColor(this.themeColor)
  8193. .height(50)
  8194. .layoutWeight(1)
  8195. .stateEffect(true)
  8196. .margin({ right: 6 })
  8197. .onClick(() => {
  8198. DialogHelper.closeDialog('tips'); //关闭弹框
  8199. })
  8200. Button('跳转')
  8201. .fontColor(Color.White)//
  8202. .layoutWeight(1)
  8203. .height(50)
  8204. .backgroundColor(this.themeColor)
  8205. .stateEffect(true)
  8206. .margin({ left: 6 })
  8207. .onClick(() => {
  8208. DialogHelper.closeDialog('tips'); //关闭弹框
  8209. this.isShowPlay = false
  8210. this.mType = 3
  8211. // router.pushUrl({
  8212. // url: 'pages/SettingPage'
  8213. // }, router.RouterMode.Single);
  8214. })
  8215. }
  8216. }
  8217. .width("100%")
  8218. .padding(10)
  8219. }
  8220. @Builder
  8221. PlayMoreSheet() {
  8222. Column() {
  8223. this.MoreList()
  8224. }
  8225. .width('100%')
  8226. .height('100%')
  8227. }
  8228. @Builder
  8229. MoreList() {
  8230. Scroll() {
  8231. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  8232. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  8233. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8234. Row() {
  8235. if (more.id === 3&&this.currentSong) {
  8236. Image(more.image)
  8237. .width(24)
  8238. .height(24)
  8239. .margin({ left: 10, right: 10 })
  8240. Text(more.title)
  8241. .fontSize(16)
  8242. .fontColor(Color.White)
  8243. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  8244. height: this.isCoverOpacity() ? '95%' : '95%',
  8245. dragBar: true,
  8246. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8247. showClose: true,
  8248. blurStyle: BlurStyle.Thin,
  8249. backgroundColor: Color.Transparent,
  8250. title: { title: '歌曲信息' }
  8251. })
  8252. } else if (more.id === 15 && this.currentSong) { //编辑信息
  8253. Image(more.image)
  8254. .width(24)
  8255. .height(24)
  8256. .margin({ left: 10, right: 10 })
  8257. Text(more.title)
  8258. .fontSize(16)
  8259. .fontColor(Color.White)
  8260. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  8261. height: this.isCoverOpacity() ? '95%' : '93%',
  8262. dragBar: true,
  8263. showClose: true,
  8264. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8265. // blurStyle:BlurStyle.Thin,
  8266. // backgroundColor:Color.Transparent,
  8267. title: { title: '编辑信息' }
  8268. })
  8269. } else if (more.id === 5) { //定时关闭
  8270. Image(more.image)
  8271. .width(24)
  8272. .height(24)
  8273. .margin({ left: 10, right: 10 })
  8274. Text(more.title)
  8275. .fontSize(16)
  8276. .fontColor(Color.White)
  8277. .onClick(() => {
  8278. this.doMore(more.id)
  8279. })
  8280. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  8281. height: this.isCoverOpacity() ? '95%' : '95%',
  8282. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8283. dragBar: true,
  8284. showClose: true,
  8285. title: { title: $r('app.string.time_close') }
  8286. })
  8287. } else if (more.id === 2) { //歌词设置
  8288. Image(more.image)
  8289. .width(24)
  8290. .height(24)
  8291. .margin({ left: 10, right: 10 })
  8292. Text(more.title)
  8293. .fontSize(16)
  8294. .fontColor(Color.White)
  8295. } else if (more.id === 16) { //悬浮歌词设置
  8296. Image(more.image)
  8297. .width(24)
  8298. .height(24)
  8299. .margin({ left: 10, right: 10 })
  8300. Text(more.title)
  8301. .fontSize(16)
  8302. .fontColor(Color.White)
  8303. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  8304. height: this.isCoverOpacity() ? '95%' : '95%',
  8305. dragBar: true,
  8306. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8307. showClose: true,
  8308. blurStyle: BlurStyle.Thin,
  8309. backgroundColor: Color.Transparent,
  8310. title: { title: '悬浮歌词' }
  8311. })
  8312. } else if (more.id === 11) {
  8313. Image(more.image)
  8314. .width(24)
  8315. .height(24)
  8316. .margin({ left: 10, right: 10 })
  8317. Text(more.title)
  8318. .fontSize(16)
  8319. .fontColor(Color.White)
  8320. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  8321. height: this.isCoverOpacity() ? '95%' : '60%',
  8322. dragBar: true,
  8323. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8324. showClose: true,
  8325. blurStyle: BlurStyle.Thin,
  8326. backgroundColor: Color.Transparent,
  8327. title: { title: '跳过头尾' }
  8328. })
  8329. } else if (more.id === 12) { //投播
  8330. AVCastPicker({
  8331. customPicker: (): void => this.TPImageBuilder(more),
  8332. onStateChange: (state) => {
  8333. if (state == AVCastPickerState.STATE_APPEARING) {
  8334. console.log(' The picker starts showing.');
  8335. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8336. console.log(' The picker finishes presenting.');
  8337. }
  8338. },
  8339. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  8340. sessionType: 'video'
  8341. })
  8342. .id('AVCastPicker')
  8343. } else {
  8344. Image(more.image)
  8345. .width(24)
  8346. .height(24)
  8347. .margin({ left: 10, right: 10 })
  8348. .onClick(() => {
  8349. this.doMore(more.id)
  8350. })
  8351. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  8352. .fontSize(16)
  8353. .fontColor(Color.White)
  8354. .onClick(() => {
  8355. this.doMore(more.id)
  8356. })
  8357. Select([//倍速
  8358. { value: '0.25x' },
  8359. { value: '0.5x' },
  8360. { value: '0.75x' },
  8361. { value: '1x' },
  8362. { value: '1.25x' },
  8363. { value: '1.5x' },
  8364. { value: '1.75x' },
  8365. { value: '2x' },
  8366. { value: '3x' }])
  8367. .font({ size: 16, weight: FontWeight.Medium })
  8368. .fontColor($r('sys.color.white'))
  8369. .margin({ left: 25 })
  8370. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  8371. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  8372. .value(Utility.optimizedFormat(this.playSpeed))
  8373. .onSelect(async (_index: number, text?: string | undefined) => {
  8374. let speed = parseFloat(text?.replace('x', '') || '1');
  8375. if (!CommonConstants.video_speed_list.includes(speed)) {
  8376. speed = 1;
  8377. }
  8378. // 使用UnifiedPlayerService设置播放速度
  8379. this.setPlaybackSpeedViaService(speed);
  8380. })
  8381. Slider({
  8382. value: this.volume,
  8383. min: 0,
  8384. max: 1,
  8385. step: 0.1,
  8386. style: SliderStyle.OutSet
  8387. })
  8388. .margin({ left: 18, right: 8 })
  8389. .blockColor(this.themeColor)
  8390. .trackColor($r('app.color.speed_text_color'))
  8391. .selectedColor(Color.White)
  8392. .trackThickness(9)
  8393. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  8394. .onChange((value: number) => {
  8395. // 使用UnifiedPlayerService设置音量
  8396. this.setVolumeViaService(value);
  8397. })
  8398. .layoutWeight(1)
  8399. Blank()
  8400. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  8401. .selectedColor(this.themeColor)
  8402. .switchPointColor(Color.White)
  8403. .margin({ right: 15 })
  8404. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8405. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  8406. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8407. if (more.id == 6) {
  8408. this.isMusicMemoryPlay = checked;
  8409. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  8410. if (this.isMusicMemoryPlay) {
  8411. ToastUtil.showToast('记忆播放已开启')
  8412. } else {
  8413. ToastUtil.showToast('记忆播放已关闭')
  8414. }
  8415. }
  8416. })
  8417. .width(48)
  8418. .height(24);
  8419. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  8420. .selectedColor(this.themeColor)
  8421. .switchPointColor(Color.White)
  8422. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8423. .margin({ right: 15 })
  8424. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  8425. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8426. if (more.id == 7) {
  8427. this.isMusicBGCover = checked;
  8428. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  8429. if (this.isMusicBGCover) {
  8430. ToastUtil.showToast('播放背景随音乐封面已开启')
  8431. } else {
  8432. ToastUtil.showToast('播放背景随音乐封面已关闭')
  8433. }
  8434. }
  8435. })
  8436. .width(48)
  8437. .height(24);
  8438. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  8439. .selectedColor(this.themeColor)
  8440. .switchPointColor(Color.White)
  8441. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8442. .margin({ right: 15 })
  8443. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  8444. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8445. if (more.id == 8) {
  8446. this.isSavePlayMode = checked;
  8447. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  8448. if (this.isSavePlayMode) {
  8449. ToastUtil.showToast('保存播放模式已开启')
  8450. } else {
  8451. ToastUtil.showToast('保存播放模式已关闭')
  8452. }
  8453. }
  8454. })
  8455. .width(48)
  8456. .height(24);
  8457. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  8458. .selectedColor(this.themeColor)
  8459. .switchPointColor(Color.White)
  8460. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8461. .margin({ right: 15 })
  8462. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  8463. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8464. if (more.id == 13) {
  8465. this.isCoverRectangle = checked;
  8466. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  8467. if (this.isCoverRectangle) {
  8468. ToastUtil.showToast('封面方形已开启')
  8469. this.animationRoFun()
  8470. } else {
  8471. ToastUtil.showToast('封面圆形已开启')
  8472. this.animationRoFun()
  8473. }
  8474. }
  8475. })
  8476. .width(48)
  8477. .height(24);
  8478. }
  8479. }
  8480. .width('100%')
  8481. .height(45)
  8482. .padding(15)
  8483. .backgroundColor(Color.Transparent)
  8484. .borderRadius(12)
  8485. .margin({ bottom: 6 })
  8486. }
  8487. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  8488. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8489. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  8490. .backgroundColor(Color.Transparent)
  8491. .onClick(() => {
  8492. this.doMore(more.id)
  8493. })
  8494. });
  8495. }
  8496. .width('100%')
  8497. .padding(16)
  8498. }.margin({ bottom: 18 })
  8499. }
  8500. @Builder
  8501. TPImageBuilder(more: MoreItem): void {
  8502. Row() {
  8503. Image($r('app.media.tuoping'))
  8504. .width(22)
  8505. .height(22)
  8506. .margin({ left: 10, right: 10 })
  8507. Text(more.title)
  8508. .fontSize(16)
  8509. .fontColor(Color.White)
  8510. }
  8511. .width('100%')
  8512. .layoutWeight(1)
  8513. .alignItems(VerticalAlign.Center)
  8514. .justifyContent(FlexAlign.Start)
  8515. }
  8516. private moreItems: MoreItem[] = [
  8517. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  8518. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  8519. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  8520. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  8521. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  8522. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  8523. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  8524. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  8525. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  8526. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  8527. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  8528. { id: 4, image: $r('app.media.share2'), title: '分享' },
  8529. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  8530. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  8531. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  8532. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  8533. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  8534. ];
  8535. @State isShowMoreView: boolean = false;
  8536. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  8537. @State isShowTimeCloseMore: boolean = false
  8538. @State isShowDetailMore: boolean = false
  8539. @State isMusicBGCover: boolean = true
  8540. @State isSavePlayMode: boolean = true
  8541. @State isLyricSetting: boolean = false
  8542. @State isJumpSetting: boolean = false
  8543. @State isShowEdit: boolean = false
  8544. @State showPipLyric: boolean = false
  8545. async setRingTone() {
  8546. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  8547. return
  8548. }
  8549. // 确定后的逻辑
  8550. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  8551. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  8552. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  8553. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  8554. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  8555. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  8556. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  8557. , this.videoUrl, this.name).then(res => {
  8558. LogUtil.info('onecold setFlag :' + res);
  8559. });
  8560. }
  8561. doMore(moreId: number) {
  8562. switch (moreId) {
  8563. case 2: //歌词
  8564. this.isLyricSetting = !this.isLyricSetting;
  8565. this.isShowMoreView = false
  8566. break;
  8567. case 3: //详情
  8568. this.isShowDetailMore = !this.isShowDetailMore;
  8569. break;
  8570. case 4: //分享
  8571. if (this.currentSong !== undefined) {
  8572. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  8573. }
  8574. this.isShowMoreView = false
  8575. break;
  8576. case 5: //定时关闭
  8577. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  8578. break;
  8579. case 10: //设为铃声
  8580. this.setRingTone()
  8581. this.isShowMoreView = false
  8582. break;
  8583. case 11: //跳过头尾
  8584. this.isJumpSetting = !this.isJumpSetting;
  8585. break;
  8586. case 13: //倍速
  8587. break;
  8588. case 14: //搜索封面
  8589. if (this.currentSong !== undefined) {
  8590. this.doSearchCover(this.currentSong)
  8591. }
  8592. this.isShowMoreView = false
  8593. break;
  8594. case 15: //编辑信息
  8595. this.isShowEdit = !this.isShowEdit;
  8596. break;
  8597. case 16: //悬浮歌词
  8598. this.showPipLyric = !this.showPipLyric;
  8599. break;
  8600. case 17: //横屏模式
  8601. if (this.isLandscape) {
  8602. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8603. } else {
  8604. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8605. }
  8606. this.isShowMoreView = false
  8607. break;
  8608. }
  8609. }
  8610. /**
  8611. * 切换横竖屏
  8612. *
  8613. */
  8614. setOrientation(orientation: number) {
  8615. if (this.windowClass) {
  8616. this.windowClass.setPreferredOrientation(orientation).then(() => {
  8617. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  8618. }).catch((err: BusinessError) => {
  8619. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  8620. });
  8621. }
  8622. }
  8623. /**
  8624. * 画中画功能(悬浮歌词功能)
  8625. *
  8626. */
  8627. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  8628. pipController?: PiPWindow.PiPController;
  8629. navigationId: string = '';
  8630. @State curState: string = '';
  8631. @State curError: ResourceStr = '';
  8632. @State pipBg: string = '#E8E8E8'
  8633. @State buttonAction: string = '';
  8634. //开启画中画功能
  8635. async startPip() {
  8636. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  8637. if (!this.pipController) {
  8638. await this.createPipController();
  8639. }
  8640. if (!this.pipController) {
  8641. Logger.info(`[${TAG}] pipController create error`);
  8642. return;
  8643. }
  8644. await this.pipController.startPiP();
  8645. }
  8646. async stopPip() {
  8647. if (!this.pipController) {
  8648. Logger.info(`[${TAG}] pipController is not exist`);
  8649. return;
  8650. }
  8651. this.isOpenPip = false
  8652. await this.pipController.stopPiP();
  8653. }
  8654. async createPipController() {
  8655. this.pipController = await PiPWindow.create({
  8656. context: getContext(this),
  8657. componentController: this.xcomponentController,
  8658. navigationId: this.navigationId,
  8659. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  8660. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  8661. customUIController: this.nodeController,
  8662. });
  8663. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  8664. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  8665. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8666. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  8667. this.onStateChange(state, reason);
  8668. });
  8669. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  8670. this.onActionEvent(event, status);
  8671. });
  8672. }
  8673. destroyPipController() {
  8674. if (!this.pipController) {
  8675. return;
  8676. }
  8677. this.pipController.off('stateChange');
  8678. this.pipController.off('controlPanelActionEvent');
  8679. this.pipController = undefined;
  8680. }
  8681. onStateChange(state: PiPWindow.PiPState, reason: string) {
  8682. switch (state) {
  8683. case PiPWindow.PiPState.ABOUT_TO_START:
  8684. this.curState = 'ABOUT_TO_START';
  8685. this.curError = $r('app.string.current_error_hint');
  8686. break;
  8687. case PiPWindow.PiPState.STARTED:
  8688. this.curState = 'STARTED';
  8689. this.curError = $r('app.string.current_error_hint');
  8690. break;
  8691. case PiPWindow.PiPState.ABOUT_TO_STOP:
  8692. this.curState = 'ABOUT_TO_STOP';
  8693. this.curError = $r('app.string.current_error_hint');
  8694. break;
  8695. case PiPWindow.PiPState.STOPPED:
  8696. this.curState = 'STOPPED';
  8697. this.curError = $r('app.string.current_error_hint');
  8698. this.stopPip()
  8699. this.destroyPipController()
  8700. break;
  8701. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  8702. this.curState = 'ABOUT_TO_RESTORE';
  8703. this.curError = $r('app.string.current_error_hint');
  8704. break;
  8705. case PiPWindow.PiPState.ERROR:
  8706. this.curState = 'ERROR';
  8707. this.curError = reason;
  8708. break;
  8709. default:
  8710. break;
  8711. }
  8712. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  8713. }
  8714. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  8715. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  8716. switch (event) {
  8717. case 'playbackStateChanged':
  8718. if (status === 0) {
  8719. this.pause();
  8720. } else {
  8721. this.startPlayOrResumePlay();
  8722. }
  8723. break;
  8724. case 'nextVideo':
  8725. // 切换到下一个视频
  8726. this.playNext()
  8727. break;
  8728. case 'previousVideo':
  8729. // 切换到上一个视频
  8730. this.playPrevious()
  8731. break;
  8732. case 'previousVideo':
  8733. // 切换到上一个视频
  8734. this.playPrevious()
  8735. break;
  8736. default:
  8737. }
  8738. this.buttonAction = event + `-status:${status}`;
  8739. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8740. }
  8741. /**
  8742. * 画中画功能(悬浮歌词功能)结束
  8743. *
  8744. */
  8745. doSearchCover(item: VideoItem) {
  8746. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8747. this.isShowMoreView = false
  8748. this.showTipsDialog()
  8749. return
  8750. }
  8751. if (item !== undefined) {
  8752. let artist = item?.artist
  8753. if (StrUtil.isEmpty(artist) || artist === undefined) {
  8754. artist = ''
  8755. }
  8756. this.searchCover(item, item.name, artist)
  8757. }
  8758. }
  8759. searchCover(item: VideoItem, title: string, artist: string) {
  8760. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8761. LogUtil.debug("onecold res =" + res)
  8762. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8763. if (item.filePath == this.currentSong?.filePath) {
  8764. this.cover = res
  8765. if (this.currentSong) {
  8766. this.currentSong.pixelMapPath = res
  8767. }
  8768. }
  8769. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8770. if (success) {
  8771. this.doUpdateData()
  8772. console.log(" onecold 更新音乐封面成功,数据库已同步");
  8773. } else {
  8774. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  8775. }
  8776. });
  8777. LogUtil.debug("onecold this.cover =" + this.cover)
  8778. }
  8779. })
  8780. }
  8781. @State jumpTopTime: number = 0
  8782. @State jumpEndTime: number = 0
  8783. @State isOpenJump: boolean = false
  8784. @Builder
  8785. JumpTopEndSheet() {
  8786. Scroll() {
  8787. Column() {
  8788. Column() {
  8789. Text('仅对本播放列表有效')
  8790. .fontSize(16)
  8791. .fontColor($r('app.color.text_color'))
  8792. // 跳过头尾
  8793. Column() {
  8794. Row() {
  8795. Text('跳过片头:')
  8796. .fontSize(16)
  8797. .fontColor($r('app.color.text_color'))
  8798. Text(this.jumpTopTime + 's')
  8799. .fontSize(16)
  8800. .fontColor($r('app.color.text_color'))
  8801. }
  8802. .margin({ bottom: 5 })
  8803. Row() {
  8804. Slider({
  8805. value: this.jumpTopTime,
  8806. min: 0,
  8807. max: 120,
  8808. step: 1,
  8809. style: SliderStyle.OutSet
  8810. })
  8811. .blockColor(this.themeColor)
  8812. .trackColor($r('app.color.speed_text_color'))
  8813. .selectedColor(Color.White)
  8814. .trackThickness(8)
  8815. .onChange((value: number) => {
  8816. this.jumpTopTime = value;
  8817. })
  8818. .width('85%')
  8819. }
  8820. .alignItems(VerticalAlign.Top)
  8821. }
  8822. .margin({ top: 10, bottom: 10 })
  8823. // 跳过头尾
  8824. Column() {
  8825. Row() {
  8826. Text('跳过片尾:')
  8827. .fontSize(16)
  8828. .fontColor($r('app.color.text_color'))
  8829. Text(this.jumpEndTime + 's')
  8830. .fontSize(16)
  8831. .fontColor($r('app.color.text_color'))
  8832. }
  8833. .margin({ bottom: 5 })
  8834. Row() {
  8835. Slider({
  8836. value: this.jumpEndTime,
  8837. min: 0,
  8838. max: 120,
  8839. step: 1,
  8840. style: SliderStyle.OutSet
  8841. })
  8842. .blockColor(this.themeColor)
  8843. .trackColor($r('app.color.speed_text_color'))
  8844. .selectedColor(Color.White)
  8845. .trackThickness(8)
  8846. .onChange((value: number) => {
  8847. this.jumpEndTime = value;
  8848. })
  8849. .width('85%')
  8850. }
  8851. .alignItems(VerticalAlign.Top)
  8852. }
  8853. .margin({ top: 10, bottom: 10 })
  8854. Row() {
  8855. Button('保存设置')
  8856. .fontColor(Color.White)
  8857. .layoutWeight(1)
  8858. .height(40)
  8859. .width(80)
  8860. .backgroundColor(this.themeColor)
  8861. .stateEffect(true)
  8862. .margin({ left: 0, bottom: 20 })
  8863. .onClick(async () => {
  8864. if (!Utility.isNoble()) {
  8865. this.isJumpSetting = false
  8866. this.isShowMoreView = false
  8867. this.showVipDialog()
  8868. return
  8869. }
  8870. if (this.currentSong === undefined) {
  8871. return
  8872. }
  8873. if (this.modeType === 0) {
  8874. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8875. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8876. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8877. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8878. } else if (this.modeType === 1) { //媒体库
  8879. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8880. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8881. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8882. } else if (this.modeType === 2) { //艺术家
  8883. if (this.currentSong?.artist) {
  8884. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8885. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8886. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8887. }
  8888. } else if (this.modeType === 3) { //专辑
  8889. if (this.currentSong?.album) {
  8890. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8891. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8892. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8893. }
  8894. }
  8895. ToastUtil.showShort("保存成功")
  8896. this.isJumpSetting = false
  8897. })
  8898. }
  8899. .margin({
  8900. left: 38,
  8901. right: 38,
  8902. top: 10,
  8903. bottom: 10
  8904. })
  8905. .width(120)
  8906. .height(50)
  8907. }
  8908. }
  8909. }
  8910. .width('100%')
  8911. .height('100%')
  8912. }
  8913. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8914. private onStateVastChange(state: AVCastPickerState) {
  8915. if (state == AVCastPickerState.STATE_APPEARING) {
  8916. LogUtils.getInstance().LOGI('投播选择器开始显示');
  8917. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8918. LogUtils.getInstance().LOGI('投播选择器结束显示');
  8919. }
  8920. }
  8921. // 检查是否存在投播设备
  8922. private async checkCastingDeviceAvailability(): Promise<boolean> {
  8923. try {
  8924. const session = this.avSessionController.getAvSession();
  8925. if (!session) {
  8926. return false;
  8927. }
  8928. const outputDevice = await session.getOutputDevice();
  8929. if (!outputDevice || !outputDevice.devices || outputDevice.devices.length === 0) {
  8930. return false;
  8931. }
  8932. // 检查是否有远程设备可用
  8933. const remoteDevices = outputDevice.devices.filter(device =>
  8934. device.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE
  8935. );
  8936. return remoteDevices.length > 0;
  8937. } catch (error) {
  8938. LogUtils.getInstance().LOGI(`检查投播设备可用性失败: ${error}`);
  8939. return false;
  8940. }
  8941. }
  8942. // 获取当前输出设备信息
  8943. private async getCurrentOutputDevice(): Promise<avSession.OutputDeviceInfo | undefined> {
  8944. try {
  8945. const session = this.avSessionController.getAvSession();
  8946. if (!session) {
  8947. return undefined;
  8948. }
  8949. return await session.getOutputDevice();
  8950. } catch (error) {
  8951. LogUtils.getInstance().LOGI(`获取当前输出设备失败: ${error}`);
  8952. return undefined;
  8953. }
  8954. }
  8955. // 检查当前是否正在投播
  8956. private async checkCurrentCastingStatus(): Promise<boolean> {
  8957. try {
  8958. const outputDevice = await this.getCurrentOutputDevice();
  8959. if (!outputDevice || !outputDevice.devices || outputDevice.devices.length === 0) {
  8960. return false;
  8961. }
  8962. // 检查当前设备是否为远程设备
  8963. const currentDevice = outputDevice.devices[0];
  8964. return currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE;
  8965. } catch (error) {
  8966. LogUtils.getInstance().LOGI(`检查当前投播状态失败: ${error}`);
  8967. return false;
  8968. }
  8969. }
  8970. // 投播状态下的播放下一首
  8971. private async handleCastingPlayNext(): Promise<void> {
  8972. try {
  8973. LogUtils.getInstance().LOGI('投播状态下切换下一首');
  8974. // 计算下一首的索引
  8975. let nextIndex = this.curIndex;
  8976. if (this.playType === 1) { // 单曲循环
  8977. // 保持当前索引不变
  8978. } else if (this.playType === 2) { // 列表循环
  8979. nextIndex = (this.curIndex + 1) % this.songList.length;
  8980. } else { // 顺序播放
  8981. if (this.curIndex < this.songList.length - 1) {
  8982. nextIndex = this.curIndex + 1;
  8983. } else {
  8984. LogUtils.getInstance().LOGI('已是最后一首,停止投播');
  8985. this.endCasting();
  8986. return;
  8987. }
  8988. }
  8989. // 更新当前歌曲信息
  8990. this.curIndex = nextIndex;
  8991. this.currentSong = this.songList[this.curIndex];
  8992. this.videoUrl = this.currentSong.filePath;
  8993. this.artist = this.currentSong.artist;
  8994. this.name = this.currentSong.name;
  8995. this.cover = this.currentSong.pixelMapPath;
  8996. // 切换投播资源
  8997. await this.changeCasting();
  8998. LogUtils.getInstance().LOGI(`投播下一首完成: ${this.currentSong.name}`);
  8999. } catch (error) {
  9000. LogUtils.getInstance().LOGI(`投播下一首失败: ${error}`);
  9001. ToastUtil.showToast(`投播切换失败: ${error}`);
  9002. }
  9003. }
  9004. // 投播状态下的播放上一首
  9005. private async handleCastingPlayPrevious(): Promise<void> {
  9006. try {
  9007. LogUtils.getInstance().LOGI('投播状态下切换上一首');
  9008. // 计算上一首的索引
  9009. let prevIndex = this.curIndex;
  9010. if (this.playType === 1) { // 单曲循环
  9011. // 保持当前索引不变
  9012. } else if (this.playType === 2) { // 列表循环
  9013. prevIndex = this.curIndex === 0 ? this.songList.length - 1 : this.curIndex - 1;
  9014. } else { // 顺序播放
  9015. if (this.curIndex > 0) {
  9016. prevIndex = this.curIndex - 1;
  9017. } else {
  9018. LogUtils.getInstance().LOGI('已是第一首,停止投播');
  9019. this.endCasting();
  9020. return;
  9021. }
  9022. }
  9023. // 更新当前歌曲信息
  9024. this.curIndex = prevIndex;
  9025. this.currentSong = this.songList[this.curIndex];
  9026. this.videoUrl = this.currentSong.filePath;
  9027. this.artist = this.currentSong.artist;
  9028. this.name = this.currentSong.name;
  9029. this.cover = this.currentSong.pixelMapPath;
  9030. // 切换投播资源
  9031. await this.changeCasting();
  9032. LogUtils.getInstance().LOGI(`投播上一首完成: ${this.currentSong.name}`);
  9033. } catch (error) {
  9034. LogUtils.getInstance().LOGI(`投播上一首失败: ${error}`);
  9035. ToastUtil.showToast(`投播切换失败: ${error}`);
  9036. }
  9037. }
  9038. // 投播状态下的播放/暂停控制
  9039. private async handleCastingPlayPause(): Promise<void> {
  9040. try {
  9041. if (this.isCastPlaying) {
  9042. await this.sendCastControlCommand('pause');
  9043. LogUtils.getInstance().LOGI('投播暂停');
  9044. } else {
  9045. await this.sendCastControlCommand('play');
  9046. LogUtils.getInstance().LOGI('投播播放');
  9047. }
  9048. } catch (error) {
  9049. LogUtils.getInstance().LOGI(`投播播放/暂停控制失败: ${error}`);
  9050. }
  9051. }
  9052. // 投播状态下的进度控制
  9053. private async handleCastingSeek(position: number): Promise<void> {
  9054. try {
  9055. await this.sendCastControlCommand('seek', position);
  9056. LogUtils.getInstance().LOGI(`投播进度调节: ${position}ms`);
  9057. } catch (error) {
  9058. LogUtils.getInstance().LOGI(`投播进度调节失败: ${error}`);
  9059. }
  9060. }
  9061. // 检查并恢复投播状态
  9062. private async checkAndRestoreCastingState(): Promise<void> {
  9063. try {
  9064. LogUtils.getInstance().LOGI('检查当前投播状态...');
  9065. const session = this.avSessionController.getAvSession();
  9066. if (!session) {
  9067. LogUtils.getInstance().LOGI('AVSession不可用,跳过投播状态检查');
  9068. return;
  9069. }
  9070. // 获取当前输出设备
  9071. const outputDevice = await session.getOutputDevice();
  9072. if (!outputDevice || !outputDevice.devices || outputDevice.devices.length === 0) {
  9073. LogUtils.getInstance().LOGI('没有输出设备,当前为本地播放');
  9074. return;
  9075. }
  9076. const currentDevice = outputDevice.devices[0];
  9077. LogUtils.getInstance().LOGI(`当前输出设备: ${currentDevice.castCategory}, 协议: ${currentDevice.supportedProtocols}`);
  9078. // 检查是否为远程设备(投播状态)
  9079. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE) {
  9080. LogUtils.getInstance().LOGI('检测到投播状态,恢复投播控制器');
  9081. // 恢复投播状态
  9082. this.currentCastDevice = currentDevice;
  9083. this.isCasting = true;
  9084. // 获取投播控制器
  9085. this.castController = await session.getAVCastController();
  9086. if (this.castController) {
  9087. // 设置投播监听器
  9088. this.setPlaybackStateChangeListener();
  9089. // 查询当前播放状态
  9090. const playbackState = await this.castController.getAVPlaybackState();
  9091. if (playbackState) {
  9092. this.playbackStateChangeListener(playbackState);
  9093. }
  9094. // 同步投播状态到AppStorage
  9095. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9096. refToIsCasting?.set(true);
  9097. LogUtils.getInstance().LOGI('投播状态恢复成功');
  9098. ToastUtil.showToast('已连接到投播设备');
  9099. } else {
  9100. LogUtils.getInstance().LOGI('获取投播控制器失败');
  9101. }
  9102. } else {
  9103. LogUtils.getInstance().LOGI('当前为本地播放状态');
  9104. }
  9105. } catch (error) {
  9106. LogUtils.getInstance().LOGI(`检查投播状态失败: ${error}`);
  9107. }
  9108. }
  9109. private showSelectLyric() {
  9110. DialogHelper.showActionSheetDialog({
  9111. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  9112. // sheets: ["本地歌词", "搜索歌词"],
  9113. sheets: [
  9114. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  9115. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  9116. ],
  9117. maskColor: Color.Transparent,
  9118. backgroundColor: $r('app.color.bg_card'),
  9119. transition: AnimationHelper.transitionInDown(666),
  9120. onAction: (index) => {
  9121. switch (index) {
  9122. case 0:
  9123. this.callFilePickerSelectFileForLyric()
  9124. break;
  9125. case 1:
  9126. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9127. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9128. this.initLyric(lyricPath);
  9129. }
  9130. break;
  9131. }
  9132. }
  9133. })
  9134. }
  9135. // 拉起picker选择文件管理器
  9136. async callFilePickerSelectFileForLyric(): Promise<void> {
  9137. try {
  9138. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  9139. DocumentSelectOptions.maxSelectNumber = 1
  9140. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  9141. let documentPicker = new picker.DocumentViewPicker();
  9142. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  9143. Logger.info(TAG,
  9144. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  9145. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  9146. this.saveVideoDatasLyric(DocumentSelectResult)
  9147. }
  9148. }).catch((err: BusinessError) => {
  9149. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  9150. });
  9151. } catch (err) {
  9152. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  9153. }
  9154. }
  9155. async saveVideoDatasLyric(uris: string[]) {
  9156. if (ArrayUtil.isEmpty(uris)) {
  9157. return
  9158. }
  9159. let newUris: string[] = [];
  9160. for (let i = 0; i < uris.length; i++) {
  9161. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  9162. Logger.info(TAG, 'filePath uri: ' + filePath);
  9163. newUris.push(filePath)
  9164. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  9165. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  9166. fileIo.copyFileSync(file.fd, file2.fd)
  9167. fileIo.closeSync(file);
  9168. fileIo.closeSync(file2);
  9169. this.initLyric(filePath)
  9170. }
  9171. }
  9172. private initDelayPlay(context: object) {
  9173. this.mContext = context;
  9174. }
  9175. startPipLyric() {
  9176. if (this.pipController) {
  9177. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9178. PiPWindow.PiPControlStatus.PLAY);
  9179. }
  9180. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  9181. if (this.isOpenPip) {
  9182. this.startPip()
  9183. } else {
  9184. this.stopPip()
  9185. }
  9186. }
  9187. private async startPlayOrResumePlay() {
  9188. try {
  9189. this.startPipLyric()
  9190. this.mDestroyPage = false;
  9191. this.animationState = AnimationStatus.Running
  9192. // 智能同步播放列表到UnifiedPlayerService
  9193. if (ArrayUtil.isNotEmpty(this.songList)) {
  9194. // 检查UnifiedPlayerService是否已经有播放列表
  9195. const servicePlaylist = this.unifiedPlayerService.getPlaylist();
  9196. const serviceIndex = this.unifiedPlayerService.getCurrentIndex();
  9197. if (ArrayUtil.isEmpty(servicePlaylist)) {
  9198. // 如果服务没有播放列表,使用LocalMusic的播放列表
  9199. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  9200. } else {
  9201. // 如果服务已有播放列表,同步服务的状态到LocalMusic
  9202. const serviceSong = this.unifiedPlayerService.getCurrentSong();
  9203. if (serviceSong && serviceIndex >= 0 && serviceIndex < servicePlaylist.length) {
  9204. this.songList = servicePlaylist;
  9205. this.curIndex = serviceIndex;
  9206. this.currentSong = serviceSong;
  9207. this.sonDataSource.pushArrayData(this.songList);
  9208. // 更新UI显示
  9209. this.videoUrl = serviceSong.filePath;
  9210. this.name = serviceSong.name;
  9211. this.artist = serviceSong.artist;
  9212. this.cover = serviceSong.pixelMapPath;
  9213. }
  9214. }
  9215. }
  9216. // 使用UnifiedPlayerService开始播放
  9217. await this.unifiedPlayerService.startPlayOrResumePlay();
  9218. // 保持原有的UI更新逻辑
  9219. this.stopProgressTask();
  9220. this.startProgressTask();
  9221. this.watchStatus();
  9222. this.updateLastPlayTimeStr(this.videoUrl)
  9223. // 更新播放状态
  9224. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  9225. this.setIsPlaying(true);
  9226. // 注意:AVSession状态更新由UnifiedPlayerService统一处理,避免冲突
  9227. LogUtils.getInstance().LOGI("LocalMusic: startPlayOrResumePlay completed via UnifiedPlayerService");
  9228. } catch (error) {
  9229. LogUtils.getInstance().LOGI(`LocalMusic startPlayOrResumePlay error: ${error}`);
  9230. ToastUtil.showToast(`播放失败: ${error}`);
  9231. // 错误处理:回退到原有逻辑
  9232. this.handlePlaybackError();
  9233. }
  9234. }
  9235. // 播放错误处理
  9236. private handlePlaybackError() {
  9237. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9238. this.setIsPlaying(false);
  9239. // 注意:AVSession状态更新由UnifiedPlayerService统一处理,避免冲突
  9240. this.mDestroyPage = true;
  9241. }
  9242. // 设置音量(通过UnifiedPlayerService)
  9243. private setVolumeViaService(volume: number) {
  9244. try {
  9245. this.unifiedPlayerService.setVolume(volume);
  9246. this.volume = volume;
  9247. PreferencesUtil.putSync('DefalutVolume', volume);
  9248. LogUtils.getInstance().LOGI(`LocalMusic: Volume set to ${volume} via UnifiedPlayerService`);
  9249. } catch (error) {
  9250. LogUtils.getInstance().LOGI(`LocalMusic setVolume error: ${error}`);
  9251. ToastUtil.showToast(`设置音量失败: ${error}`);
  9252. }
  9253. }
  9254. // 设置播放速度(通过UnifiedPlayerService)
  9255. private setPlaybackSpeedViaService(speed: number) {
  9256. try {
  9257. this.unifiedPlayerService.setPlaybackSpeed(speed);
  9258. this.playSpeed = speed;
  9259. LogUtils.getInstance().LOGI(`LocalMusic: Playback speed set to ${speed} via UnifiedPlayerService`);
  9260. } catch (error) {
  9261. LogUtils.getInstance().LOGI(`LocalMusic setPlaybackSpeed error: ${error}`);
  9262. ToastUtil.showToast(`设置播放速度失败: ${error}`);
  9263. }
  9264. }
  9265. // 设置播放模式(通过UnifiedPlayerService)
  9266. private setPlayModeViaService(mode: number) {
  9267. try {
  9268. this.unifiedPlayerService.setPlayMode(mode);
  9269. this.playType = mode;
  9270. PreferencesUtil.putSync('musicPlayType', mode);
  9271. LogUtils.getInstance().LOGI(`LocalMusic: Play mode set to ${mode} via UnifiedPlayerService`);
  9272. } catch (error) {
  9273. LogUtils.getInstance().LOGI(`LocalMusic setPlayMode error: ${error}`);
  9274. // 回退到原有逻辑
  9275. this.playType = mode;
  9276. PreferencesUtil.putSync('musicPlayType', mode);
  9277. }
  9278. }
  9279. // 播放指定索引的歌曲(通过UnifiedPlayerService)
  9280. private async playSongAtIndexViaService(index: number) {
  9281. try {
  9282. // 确保播放列表已同步到UnifiedPlayerService
  9283. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  9284. // 使用UnifiedPlayerService播放指定索引的歌曲
  9285. await this.unifiedPlayerService.playSongAtIndex(index);
  9286. // 更新本地状态以保持UI同步
  9287. const currentIndex = this.unifiedPlayerService.getCurrentIndex();
  9288. const currentSong = this.unifiedPlayerService.getCurrentSong();
  9289. if (currentSong) {
  9290. this.curIndex = currentIndex;
  9291. this.currentSong = currentSong;
  9292. this.videoUrl = currentSong.filePath;
  9293. this.name = currentSong.name;
  9294. this.artist = currentSong.artist;
  9295. this.cover = currentSong.pixelMapPath;
  9296. }
  9297. } catch (error) {
  9298. ToastUtil.showToast(`播放歌曲失败: ${error}`);
  9299. // 错误处理:回退到原有逻辑
  9300. this.playIndex(index);
  9301. }
  9302. }
  9303. // 同步播放列表到UnifiedPlayerService
  9304. private syncPlaylistToService() {
  9305. try {
  9306. if (ArrayUtil.isNotEmpty(this.songList)) {
  9307. // 记录调用栈信息以便调试
  9308. const stack = new Error().stack || 'No stack available';
  9309. const caller = stack.split('\n')[2] || 'Unknown caller';
  9310. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  9311. // 同步播放模式到UnifiedPlayerService
  9312. this.unifiedPlayerService.setPlayMode(this.playType);
  9313. LogUtils.getInstance().LOGI(`LocalMusic: Playlist and play mode synced to UnifiedPlayerService - ${this.songList.length} songs, mode: ${this.playType}, caller: ${caller.trim()}`);
  9314. // 如果同步的是小播放列表,记录更多信息
  9315. if (this.songList.length <= 20) {
  9316. 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(', ')}`);
  9317. }
  9318. } else {
  9319. LogUtils.getInstance().LOGI('LocalMusic: syncPlaylistToService - No songs to sync');
  9320. }
  9321. } catch (error) {
  9322. LogUtils.getInstance().LOGI(`LocalMusic syncPlaylistToService error: ${error}`);
  9323. }
  9324. }
  9325. // 从播放列表移除歌曲(通过UnifiedPlayerService)
  9326. private removeFromPlaylistViaService(index: number) {
  9327. try {
  9328. // 使用UnifiedPlayerService移除歌曲
  9329. const removedSong = this.unifiedPlayerService.removeFromPlaylist(index);
  9330. if (removedSong) {
  9331. // 更新本地播放列表
  9332. this.songList.splice(index, 1);
  9333. this.sonDataSource.pushArrayData(this.songList);
  9334. // 更新当前索引
  9335. this.curIndex = this.unifiedPlayerService.getCurrentIndex();
  9336. ToastUtil.showToast(`已移除 ${removedSong.name}`);
  9337. }
  9338. } catch (error) {
  9339. // 错误处理:回退到原有逻辑
  9340. if (index >= 0 && index < this.songList.length) {
  9341. const removedSong = this.songList.splice(index, 1)[0];
  9342. this.sonDataSource.pushArrayData(this.songList);
  9343. ToastUtil.showToast(`已移除 ${removedSong.name}`);
  9344. }
  9345. }
  9346. }
  9347. updateLastPlayTimeStr(filePath: string) {
  9348. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  9349. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  9350. if (success) {
  9351. this.getHistoryList(false)
  9352. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  9353. } else {
  9354. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  9355. }
  9356. });
  9357. }
  9358. private completionNum(num: number): string | number {
  9359. if (num < 10) {
  9360. return '0' + num;
  9361. } else {
  9362. return num;
  9363. }
  9364. }
  9365. // 纯粹的时间格式化函数,不包含任何业务逻辑
  9366. private stringForTime(timeMs: number): string {
  9367. let totalSeconds: number = Math.floor(timeMs / 1000);
  9368. let seconds: number = totalSeconds % 60;
  9369. let minutes: number = Math.floor(totalSeconds / 60) % 60;
  9370. let hours: number = Math.floor(totalSeconds / 3600);
  9371. // 防抖逻辑:只在当前播放时间更新时生效
  9372. if (this.isCurrentTime) {
  9373. // 如果歌曲刚刚切换,强制重置并使用新时间
  9374. if (this.justSwitched) {
  9375. this.oldSeconds = seconds; // 直接使用新时间
  9376. this.justSwitched = false; // 重置标志
  9377. this.lastSwitchTime = Date.now(); // 记录切换时间
  9378. } else if (this.isSeekTo) {
  9379. // 如果是拖动进度条,直接使用新时间
  9380. this.oldSeconds = seconds;
  9381. } else {
  9382. // 正常播放时的防抖逻辑
  9383. // 检查是否在切换后的冷却期内(切换后5秒内允许更大的时间跳跃)
  9384. const timeSinceSwitch = this.lastSwitchTime ? Date.now() - this.lastSwitchTime : Number.MAX_VALUE;
  9385. const isInCooldown = timeSinceSwitch < 5000; // 5秒冷却期
  9386. // 如果时间差值过大,根据情况处理
  9387. const timeDiff = Math.abs(seconds - this.oldSeconds);
  9388. if (timeDiff > 10) {
  9389. // 如果在冷却期内,允许更大的时间跳跃(可能是新歌曲开始播放)
  9390. if (isInCooldown) {
  9391. this.oldSeconds = seconds;
  9392. } else {
  9393. // 不在冷却期内,可能是异常情况,记录但使用新时间
  9394. this.oldSeconds = seconds;
  9395. }
  9396. } else if (this.oldSeconds <= seconds || seconds === 0) {
  9397. // 正常时间递进或重置为0
  9398. this.oldSeconds = seconds;
  9399. } else {
  9400. // 时间倒退,使用防抖
  9401. seconds = this.oldSeconds;
  9402. }
  9403. }
  9404. }
  9405. const hoursStr = this.completionNum(hours);
  9406. const minutesStr = this.completionNum(minutes);
  9407. const secondsStr = this.completionNum(seconds);
  9408. if (hours > 0) {
  9409. return `${hoursStr}:${minutesStr}:${secondsStr}`;
  9410. } else {
  9411. return `${minutesStr}:${secondsStr}`;
  9412. }
  9413. }
  9414. private setProgress() {
  9415. let ijkPlayer=this.unifiedPlayerService.getIjkPlayer() as IjkMediaPlayer;
  9416. let position = ijkPlayer.getCurrentPosition();
  9417. let duration = ijkPlayer.getDuration();
  9418. let pos = 0;
  9419. if (duration > 0) {
  9420. this.slideEnable = true;
  9421. let curPercent = position / duration;
  9422. pos = curPercent * 100;
  9423. if (pos > this.PROGRESS_MAX_VALUE) {
  9424. this.progressValue = this.PROGRESS_MAX_VALUE
  9425. } else {
  9426. this.progressValue = pos;
  9427. }
  9428. }
  9429. // LogUtils.getInstance()
  9430. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9431. this.totalTime = this.stringForTime(duration);
  9432. if (position > duration) {
  9433. position = duration;
  9434. }
  9435. this.isCurrentTime = true;
  9436. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  9437. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  9438. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  9439. this.currentTime = this.stringForTime(position);
  9440. this.isCurrentTime = false
  9441. if (ijkPlayer.isPlaying()) {
  9442. this.randomColor =
  9443. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  9444. // 判断是否播放到结束时间
  9445. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  9446. if (position >= duration - this.jumpEndTime * 1000) {
  9447. this.playNext()
  9448. }
  9449. }
  9450. } else {
  9451. this.randomColor = 'rbg(0,0,0)'
  9452. }
  9453. // try {
  9454. // // 优先从UnifiedPlayerService获取进度信息
  9455. // const currentState = this.unifiedPlayerService.getCurrentState();
  9456. // let position = currentState.currentPosition;
  9457. // let duration = currentState.duration;
  9458. //
  9459. // // 检测歌曲切换并重置播放位置
  9460. // const currentSongPath = this.currentSong?.filePath || "";
  9461. // if (this.lastSongPath !== currentSongPath && currentSongPath !== "") {
  9462. // console.log(`Heanup setProgress检测到歌曲切换,重置position: ${position} -> 0`);
  9463. // this.oldSeconds = 0;
  9464. // this.currentTime = "00:00";
  9465. // this.lastSongPath = currentSongPath;
  9466. // position = 0; // 强制重置播放位置
  9467. // }
  9468. //
  9469. // let pos = 0;
  9470. // if (duration > 0) {
  9471. // this.slideEnable = true;
  9472. // let curPercent = position / duration;
  9473. // pos = curPercent * 100;
  9474. // if (pos > this.PROGRESS_MAX_VALUE) {
  9475. // this.progressValue = this.PROGRESS_MAX_VALUE
  9476. // } else {
  9477. // this.progressValue = pos;
  9478. // }
  9479. // }
  9480. //
  9481. // this.totalTime = this.stringForTime(duration);
  9482. // if (position > duration) {
  9483. // position = duration;
  9484. // }
  9485. //
  9486. //
  9487. // // 更新歌词位置
  9488. // const lyricPosition = position + this.timeOffset * 1000;
  9489. // this.lyricController.updatePosition(lyricPosition);
  9490. // this.lyricControllerXF.updatePosition(lyricPosition);
  9491. // this.lyricControllerSingle.updatePosition(lyricPosition);
  9492. //
  9493. // this.isCurrentTime = true;
  9494. // this.currentTime = this.stringForTime(position);
  9495. // this.isCurrentTime = false;
  9496. //
  9497. // // 检查播放状态以更新随机颜色和跳过逻辑
  9498. // const isPlaying = currentState.isPlaying;
  9499. // if (isPlaying) {
  9500. // this.randomColor =
  9501. // `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  9502. //
  9503. // // 判断是否播放到结束时间
  9504. // if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  9505. // if (position >= duration - this.jumpEndTime * 1000) {
  9506. // this.playNext()
  9507. // }
  9508. // }
  9509. // } else {
  9510. // this.randomColor = 'rbg(0,0,0)'
  9511. // }
  9512. //
  9513. // // 节流广播进度更新到卡片
  9514. // this.broadcastProgressIfNeeded();
  9515. // } catch (error) {
  9516. // LogUtils.getInstance().LOGI(`LocalMusic setProgress error: ${error}`);
  9517. // }
  9518. }
  9519. private startProgressTask() {
  9520. let that = this;
  9521. this.updateProgressTimer = setInterval(() => {
  9522. //LogUtils.getInstance().LOGI("startProgressTask");
  9523. if (!that.mDestroyPage) {
  9524. that.setProgress();
  9525. }
  9526. }, 300);
  9527. }
  9528. private stopProgressTask() {
  9529. LogUtils.getInstance().LOGI("stopProgressTask");
  9530. clearInterval(this.updateProgressTimer);
  9531. }
  9532. private showLoadIng() {
  9533. this.loadingVisible = Visibility.Visible;
  9534. this.replayVisible = Visibility.None;
  9535. }
  9536. // 原来的 play 方法已移除,播放逻辑现在由 UnifiedPlayerService 统一处理
  9537. // private async play(url: string) { ... } 已移除
  9538. // 所有的播放器配置和监听器设置已移至 UnifiedPlayerService
  9539. //保存最后播放的那首歌和已经对应的播放列表
  9540. saveLastPlayList() {
  9541. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  9542. PreferencesUtil.putSync('LastMusicList', this.songList)
  9543. }
  9544. // 清空播放记录
  9545. clearVideoHistory() {
  9546. this.table.clearPlayHistory((success: boolean, error?: string) => {
  9547. if (success) {
  9548. this.historyList = [];
  9549. this.updateListData(this.historyList)
  9550. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  9551. ToastUtil.showToast('清空播放记录成功')
  9552. } else {
  9553. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  9554. }
  9555. });
  9556. }
  9557. setLoopMode() {
  9558. let itype = this.playType + 1
  9559. if (itype >= 4) {
  9560. this.setPlayModeViaService(0);
  9561. ToastUtil.showToast('连续播放')
  9562. } else if (itype === 1) {
  9563. this.setPlayModeViaService(1);
  9564. ToastUtil.showToast('单曲循环')
  9565. } else if (itype === 2) {
  9566. this.setPlayModeViaService(2);
  9567. ToastUtil.showToast('单曲播完')
  9568. } else if (itype === 3) {
  9569. this.setPlayModeViaService(3);
  9570. ToastUtil.showToast('随机播放')
  9571. } else if (itype === 0) {
  9572. this.setPlayModeViaService(0);
  9573. ToastUtil.showToast('连续播放')
  9574. }
  9575. this.setCurrentPlayMode()
  9576. }
  9577. public async setAvSessionListener() {
  9578. if (!this.avSessionController) {
  9579. console.log('heanup setAvSessionListener error: avSessionController is null');
  9580. return;
  9581. }
  9582. // 注意:基础播控监听器(play, pause, playNext, playPrevious, seek等)
  9583. // 已经在UnifiedPlayerService中设置,这里不再重复设置,避免冲突
  9584. // 只设置LocalMusic特有的监听器
  9585. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  9586. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  9587. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  9588. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  9589. // 设置投播设备变化监听器(这是投播功能的核心)
  9590. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange);
  9591. console.log('heanup setAvSessionListener 完成 - 已跳过基础播控监听器(由UnifiedPlayerService处理)');
  9592. // 检查当前是否已经在投播状态
  9593. await this.checkAndRestoreCastingState();
  9594. }
  9595. private sessionSetLoopModeCallback = (mode: number) => {
  9596. ToastUtil.showToast('当前播放模式:' + mode)
  9597. Logger.info('onecold 当前播放模式= ' + mode)
  9598. let hmPlayMode = mode + 1
  9599. if (hmPlayMode >= 4) {
  9600. hmPlayMode = 0
  9601. }
  9602. if (hmPlayMode === 1) {
  9603. this.setPlayModeViaService(1);
  9604. ToastUtil.showToast('单曲循环')
  9605. } else if (hmPlayMode === 0) {
  9606. this.setPlayModeViaService(2);
  9607. ToastUtil.showToast('单曲播完')
  9608. } else if (hmPlayMode === 3) {
  9609. this.setPlayModeViaService(3);
  9610. ToastUtil.showToast('随机播放')
  9611. } else if (hmPlayMode === 2) {
  9612. this.setPlayModeViaService(0);
  9613. ToastUtil.showToast('连续播放')
  9614. }
  9615. PreferencesUtil.putSync('musicPlayType', this.playType)
  9616. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  9617. let playBackState: avSession.AVPlaybackState = {
  9618. loopMode: hmPlayMode,
  9619. };
  9620. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  9621. console.info(`set setLoopMode AVPlaybackState successfully`);
  9622. }).catch((err: BusinessError) => {
  9623. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9624. });
  9625. }
  9626. setCurrentPlayMode() {
  9627. if (!this.avSessionController) {
  9628. return;
  9629. }
  9630. let mLoopMode = 0
  9631. switch (this.playType) {
  9632. case 0:
  9633. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  9634. break;
  9635. case 1:
  9636. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  9637. break;
  9638. case 2:
  9639. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  9640. break;
  9641. case 3:
  9642. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  9643. break;
  9644. }
  9645. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  9646. let playBState: avSession.AVPlaybackState = {
  9647. loopMode: mLoopMode,
  9648. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  9649. };
  9650. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  9651. console.info(`set setLoopMode AVPlaybackState successfully`);
  9652. }).catch((err: BusinessError) => {
  9653. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9654. });
  9655. }
  9656. private sessionToggleFavoriteCallback = (assetId: string) => {
  9657. if (this.currentSong) {
  9658. console.info(`on toggleFavorite - 播控中心收藏按钮被点击`);
  9659. // 应用收到收藏命令,进行收藏处理。
  9660. // 注意:这里不需要立即更新AVSession状态,因为doFav方法内部会处理状态更新
  9661. this.doFav(this.currentSong);
  9662. }
  9663. }
  9664. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  9665. device: avSession.OutputDeviceInfo) => {
  9666. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  9667. LogUtils.getInstance().LOGI(`投播设备状态变化: ${connectState}, 设备类型: ${currentDevice?.castCategory}, 协议: ${currentDevice?.supportedProtocols}`);
  9668. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9669. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  9670. // 设备连接成功,开始投播
  9671. this.currentCastDevice = currentDevice;
  9672. await this.startCasting();
  9673. // 检查设备支持的协议类型
  9674. if (currentDevice.supportedProtocols === avSession.ProtocolType.TYPE_CAST_PLUS_STREAM) {
  9675. LogUtils.getInstance().LOGI('设备支持Cast+投播协议');
  9676. } else if (currentDevice.supportedProtocols === avSession.ProtocolType.TYPE_DLNA) {
  9677. LogUtils.getInstance().LOGI('设备支持DLNA投播协议');
  9678. }
  9679. // 检查DRM支持能力
  9680. if (currentDevice.supportedDrmCapabilities?.includes('3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c')) {
  9681. LogUtils.getInstance().LOGI('设备支持chinaDRM');
  9682. // 监听许可证请求事件
  9683. this.castController?.on('keyRequest', this.keyRequestCallback);
  9684. }
  9685. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9686. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  9687. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  9688. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  9689. // 设备断开或切换回本地
  9690. if (device) {
  9691. this.endCasting();
  9692. this.currentCastDevice = undefined;
  9693. }
  9694. }
  9695. };
  9696. private async startCasting() {
  9697. try {
  9698. LogUtils.getInstance().LOGI('开始投播流程');
  9699. // 获取投播控制器
  9700. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9701. if (!this.castController) {
  9702. LogUtils.getInstance().LOGI('获取投播控制器失败');
  9703. ToastUtil.showToast('投播初始化失败');
  9704. return;
  9705. }
  9706. LogUtils.getInstance().LOGI('投播控制器获取成功');
  9707. // 设置投播状态监听
  9708. this.setPlaybackStateChangeListener();
  9709. // 暂停本地播放
  9710. this.pause();
  9711. // 初始化投播资源
  9712. this.initQueueItem();
  9713. // 准备并开始投播
  9714. await this.prepare();
  9715. // 更新投播状态
  9716. this.isCasting = true;
  9717. this.isCastPlaying = true;
  9718. this.castSeek = true;
  9719. // 同步到AppStorage
  9720. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9721. refToIsCasting?.set(true);
  9722. // 申请长时任务,避免投播时应用被冻结
  9723. this.startCastingBackgroundTask();
  9724. LogUtils.getInstance().LOGI('投播启动成功');
  9725. ToastUtil.showToast('投播已开始');
  9726. } catch (error) {
  9727. LogUtils.getInstance().LOGI(`投播启动失败: ${error}`);
  9728. ToastUtil.showToast(`投播启动失败: ${error}`);
  9729. this.endCasting();
  9730. }
  9731. }
  9732. async changeCasting() {
  9733. try {
  9734. LogUtils.getInstance().LOGI('投播资源切换开始');
  9735. // 确保投播控制器可用
  9736. if (!this.castController) {
  9737. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9738. }
  9739. if (!this.castController) {
  9740. LogUtils.getInstance().LOGI('投播控制器不可用,无法切换资源');
  9741. return;
  9742. }
  9743. // 初始化新的投播资源
  9744. this.initQueueItem();
  9745. // 准备并开始播放新资源
  9746. await this.prepare();
  9747. // 确保监听器已设置
  9748. this.setPlaybackStateChangeListener();
  9749. // 更新播放状态
  9750. this.isCastPlaying = true;
  9751. this.castSeek = true;
  9752. LogUtils.getInstance().LOGI(`投播资源切换成功: ${this.currentSong?.name}`);
  9753. } catch (error) {
  9754. LogUtils.getInstance().LOGI(`投播资源切换失败: ${error}`);
  9755. ToastUtil.showToast(`切换投播资源失败: ${error}`);
  9756. }
  9757. }
  9758. public endCasting() {
  9759. try {
  9760. LogUtils.getInstance().LOGI('结束投播流程');
  9761. // 停止投播
  9762. this.avSessionController.getAvSession()?.stopCasting();
  9763. // 清理投播控制器监听
  9764. this.stopCast();
  9765. // 更新投播状态
  9766. this.isCasting = false;
  9767. this.isCastPlaying = false;
  9768. this.castSeek = false;
  9769. // 同步到AppStorage
  9770. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9771. refToIsCasting?.set(false);
  9772. // 停止长时任务
  9773. this.stopCastingBackgroundTask();
  9774. // 恢复本地播放(可选)
  9775. // 建议保存投播断开时的进度,用于本地播放继续
  9776. const lastCastPosition = this.currentTime2 * 1000; // 投播的当前进度
  9777. // 暂停本地播放器,让用户手动选择是否继续播放
  9778. this.pause();
  9779. this.setIsPlaying(false);
  9780. // 如果需要自动恢复本地播放,可以取消注释以下代码
  9781. // if (lastCastPosition > 0) {
  9782. // this.seekTo(lastCastPosition.toString());
  9783. // setTimeout(() => {
  9784. // this.startPlayOrResumePlay();
  9785. // }, 500);
  9786. // }
  9787. LogUtils.getInstance().LOGI('投播结束成功');
  9788. ToastUtil.showToast('投播已结束');
  9789. } catch (error) {
  9790. LogUtils.getInstance().LOGI(`结束投播失败: ${error}`);
  9791. ToastUtil.showToast(`结束投播失败: ${error}`);
  9792. }
  9793. }
  9794. public setIsPlaying(isPlayer: boolean) {
  9795. this.isPlaying = isPlayer;
  9796. }
  9797. private setPlaybackStateChangeListener(): void {
  9798. if (!this.castController) {
  9799. LogUtils.getInstance().LOGI('投播控制器为空,无法设置监听器');
  9800. return;
  9801. }
  9802. try {
  9803. // 监听播放状态变化
  9804. this.castController.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  9805. // 监听播放完毕事件
  9806. this.castController.on('endOfStream', this.reloadCasting);
  9807. // 监听播控中心的上下一首切换
  9808. this.castController.on('playNext', this.playNextCallback);
  9809. this.castController.on('playPrevious', this.playPreviousCallback);
  9810. // 监听进度调节完成事件
  9811. this.castController.on('seekDone', this.seekDoneCallback);
  9812. // 监听错误事件
  9813. this.castController.on('error', this.castErrorCallback);
  9814. LogUtils.getInstance().LOGI('投播状态监听器设置完成');
  9815. } catch (error) {
  9816. LogUtils.getInstance().LOGI(`设置投播监听器失败: ${error}`);
  9817. }
  9818. }
  9819. private updateSessionPlayState(isPlay: boolean): void {
  9820. // if(!this.isBgPlayOpen)
  9821. // return
  9822. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  9823. try {
  9824. // 通过UnifiedPlayerService获取当前位置
  9825. const currentState = this.unifiedPlayerService.getCurrentState();
  9826. this.setAVSessionPlayState({
  9827. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  9828. position: {
  9829. elapsedTime: currentState.currentPosition,
  9830. updateTime: new Date().getTime()
  9831. }
  9832. });
  9833. } catch (error) {
  9834. LogUtils.getInstance().LOGI(`updateSessionPlayState error: ${error}`);
  9835. // 如果获取失败,使用默认值
  9836. this.setAVSessionPlayState({
  9837. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  9838. position: {
  9839. elapsedTime: 0,
  9840. updateTime: new Date().getTime()
  9841. }
  9842. });
  9843. }
  9844. }
  9845. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  9846. this.avSessionController.setAvSessionPlayState(playbackState)
  9847. }
  9848. private positionChange(position: number) {
  9849. this.currentTime2 = position / 1000;
  9850. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  9851. }
  9852. private playDurationChange(duration: number) {
  9853. this.duration = duration;
  9854. this.durationTime = Math.floor(this.duration / 1000);
  9855. this.durationStringTime = secondToTime((this.durationTime));
  9856. }
  9857. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  9858. try {
  9859. LogUtils.getInstance().LOGI(`投播状态变化: ${playbackState.state}, 进度: ${playbackState?.position?.elapsedTime}ms`);
  9860. // 处理播放时长变化
  9861. const duration = playbackState?.extras?.duration;
  9862. if (typeof duration === 'number') {
  9863. this.playDurationChange(duration as number);
  9864. }
  9865. // 处理播放进度变化
  9866. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  9867. this.positionChange(playbackState?.position?.elapsedTime);
  9868. }
  9869. // 处理播放状态变化
  9870. switch (playbackState.state) {
  9871. case avSession.PlaybackState.PLAYBACK_STATE_PLAY:
  9872. this.isCastPlaying = true;
  9873. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  9874. this.setIsPlaying(true);
  9875. break;
  9876. case avSession.PlaybackState.PLAYBACK_STATE_PAUSE:
  9877. this.isCastPlaying = false;
  9878. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9879. this.setIsPlaying(false);
  9880. break;
  9881. case avSession.PlaybackState.PLAYBACK_STATE_STOP:
  9882. case avSession.PlaybackState.PLAYBACK_STATE_PREPARE:
  9883. case avSession.PlaybackState.PLAYBACK_STATE_INITIAL:
  9884. this.isCastPlaying = false;
  9885. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9886. this.setIsPlaying(false);
  9887. break;
  9888. default:
  9889. LogUtils.getInstance().LOGI(`未处理的投播状态: ${playbackState.state}`);
  9890. break;
  9891. }
  9892. // 处理音量变化
  9893. if (playbackState?.volume !== undefined) {
  9894. LogUtils.getInstance().LOGI(`投播音量变化: ${playbackState.volume}`);
  9895. // 可以在这里同步音量到UI
  9896. }
  9897. // 更新UI显示
  9898. this.playChange();
  9899. } catch (error) {
  9900. LogUtils.getInstance().LOGI(`处理投播状态变化失败: ${error}`);
  9901. }
  9902. };
  9903. private reloadCasting = async () => {
  9904. try {
  9905. LogUtils.getInstance().LOGI('投播内容播放完毕,处理后续操作');
  9906. // 根据播放模式决定后续操作
  9907. switch (this.playType) {
  9908. case 0: // 顺序播放
  9909. if (this.curIndex < this.songList.length - 1) {
  9910. // 有下一首,自动切换
  9911. LogUtils.getInstance().LOGI('自动播放下一首');
  9912. this.playNext();
  9913. } else {
  9914. // 没有下一首,停止投播或循环播放第一首
  9915. LogUtils.getInstance().LOGI('播放列表结束,停止投播');
  9916. this.endCasting();
  9917. }
  9918. break;
  9919. case 1: // 单曲循环
  9920. LogUtils.getInstance().LOGI('单曲循环,重新播放当前歌曲');
  9921. this.initQueueItem();
  9922. await this.prepare();
  9923. this.isCastPlaying = true;
  9924. break;
  9925. case 2: // 列表循环
  9926. if (this.curIndex < this.songList.length - 1) {
  9927. // 播放下一首
  9928. this.playNext();
  9929. } else {
  9930. // 回到第一首
  9931. this.curIndex = 0;
  9932. this.currentSong = this.songList[0];
  9933. this.initQueueItem();
  9934. await this.prepare();
  9935. this.isCastPlaying = true;
  9936. }
  9937. break;
  9938. case 3: // 随机播放
  9939. LogUtils.getInstance().LOGI('随机播放下一首');
  9940. this.playNext();
  9941. break;
  9942. default:
  9943. LogUtils.getInstance().LOGI('未知播放模式,停止投播');
  9944. this.endCasting();
  9945. break;
  9946. }
  9947. } catch (error) {
  9948. LogUtils.getInstance().LOGI(`处理投播完毕事件失败: ${error}`);
  9949. ToastUtil.showToast(`投播切换失败: ${error}`);
  9950. }
  9951. };
  9952. public playNextCallback = (): void => {
  9953. LogUtils.getInstance().LOGI('投播设备请求播放下一首');
  9954. this.playNext();
  9955. };
  9956. public playPreviousCallback = (): void => {
  9957. LogUtils.getInstance().LOGI('投播设备请求播放上一首');
  9958. this.playPrevious();
  9959. };
  9960. // 进度调节完成回调
  9961. private seekDoneCallback = (position: number): void => {
  9962. LogUtils.getInstance().LOGI(`投播进度调节完成: ${position}ms`);
  9963. // 更新本地进度显示
  9964. this.positionChange(position);
  9965. };
  9966. // 投播错误回调
  9967. private castErrorCallback = (error: BusinessError): void => {
  9968. LogUtils.getInstance().LOGI(`投播错误: ${error.message || error}`);
  9969. ToastUtil.showToast(`投播错误: ${error.message || '未知错误'}`);
  9970. // 可以选择自动结束投播或重试
  9971. // this.endCasting();
  9972. };
  9973. // DRM许可证请求回调
  9974. private keyRequestCallback: avSession.KeyRequestCallback = async (assetId: string, requestData: Uint8Array) => {
  9975. try {
  9976. LogUtils.getInstance().LOGI(`DRM许可证请求: ${assetId}`);
  9977. // 根据assetId获取对应的DRM url(需要根据实际情况配置)
  9978. let drmUrl: string = 'http://license.xxx.xxx.com:8080/drmproxy/getLicense';
  9979. // 从服务器获取许可证
  9980. let licenseResponseData = await this.getLicense(drmUrl, requestData);
  9981. if (licenseResponseData) {
  9982. // 处理DRM许可证响应
  9983. await this.castController?.processMediaKeyResponse(assetId, licenseResponseData);
  9984. LogUtils.getInstance().LOGI('DRM许可证处理成功');
  9985. } else {
  9986. LogUtils.getInstance().LOGI('获取DRM许可证失败');
  9987. ToastUtil.showToast('DRM许可证获取失败');
  9988. }
  9989. } catch (error) {
  9990. LogUtils.getInstance().LOGI(`DRM许可证处理失败: ${error}`);
  9991. ToastUtil.showToast(`DRM许可证处理失败: ${error}`);
  9992. }
  9993. };
  9994. async prepare() {
  9995. try {
  9996. if (!this.castController || !this.castItem) {
  9997. LogUtils.getInstance().LOGI('投播控制器或资源项为空,无法准备播放');
  9998. return;
  9999. }
  10000. LogUtils.getInstance().LOGI('准备投播资源...');
  10001. // 准备播放,进行资源加载和缓冲,不会触发真正的播放
  10002. await this.castController.prepare(this.castItem);
  10003. LogUtils.getInstance().LOGI('投播资源准备完成');
  10004. // 启动播放,真正触发对端播放
  10005. await this.castController.start(this.castItem);
  10006. LogUtils.getInstance().LOGI('投播播放启动成功');
  10007. } catch (error) {
  10008. const errorMessage = error instanceof Error ? error.message : String(error);
  10009. LogUtils.getInstance().LOGI(`投播准备或启动失败: ${errorMessage}`);
  10010. ToastUtil.showToast(`投播播放失败: ${errorMessage}`);
  10011. throw new Error(errorMessage);
  10012. }
  10013. }
  10014. public initQueueItem() {
  10015. try {
  10016. let item = this.songList[this.curIndex];
  10017. if (!item) {
  10018. LogUtils.getInstance().LOGI('当前歌曲信息为空,无法初始化投播资源');
  10019. return;
  10020. }
  10021. LogUtils.getInstance().LOGI(`初始化投播资源: ${item.name}`);
  10022. let uri = fileUri.getUriFromPath(item.filePath);
  10023. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  10024. // 获取当前播放进度,用于投播时同步进度
  10025. const currentPosition = this.unifiedPlayerService.getCurrentPosition();
  10026. this.castItem = {
  10027. itemId: this.curIndex,
  10028. description: {
  10029. assetId: item.filePath,
  10030. title: item.name,
  10031. artist: item.artist || this.UNKONWN,
  10032. subtitle: item.album || '',
  10033. // 本地资源投播,使用文件描述符
  10034. fdSrc: {
  10035. fd: file.fd
  10036. },
  10037. // 音频资源类型
  10038. mediaType: 'AUDIO',
  10039. mediaSize: item.videoSize,
  10040. // 同步当前播放进度到远端
  10041. startPosition: currentPosition,
  10042. // 同步播放时长到远端显示
  10043. duration: this.duration,
  10044. // 专辑封面(如果有)
  10045. albumCoverUri: item.pixelMapPath,
  10046. albumTitle: item.album || '',
  10047. appName: this.appName,
  10048. // 如果是DRM资源,需要配置支持的DRM类型
  10049. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  10050. }
  10051. };
  10052. LogUtils.getInstance().LOGI(`投播资源初始化完成 - 标题: ${item.name}, 进度: ${currentPosition}ms, 时长: ${this.duration}ms`);
  10053. } catch (error) {
  10054. LogUtils.getInstance().LOGI(`初始化投播资源失败: ${error}`);
  10055. ToastUtil.showToast(`初始化投播资源失败: ${error}`);
  10056. }
  10057. }
  10058. async stopCast() {
  10059. try {
  10060. LogUtils.getInstance().LOGI('清理投播监听器');
  10061. if (this.castController) {
  10062. // 移除所有投播监听器
  10063. this.castController.off('playbackStateChange');
  10064. this.castController.off('endOfStream');
  10065. this.castController.off('playNext');
  10066. this.castController.off('playPrevious');
  10067. this.castController.off('seekDone');
  10068. this.castController.off('error');
  10069. this.castController.off('keyRequest');
  10070. LogUtils.getInstance().LOGI('投播监听器清理完成');
  10071. }
  10072. // 清空投播控制器引用
  10073. this.castController = undefined;
  10074. this.castItem = undefined;
  10075. } catch (error) {
  10076. LogUtils.getInstance().LOGI(`清理投播监听器失败: ${error}`);
  10077. }
  10078. }
  10079. private async playOrPause() {
  10080. if (!this.debounce()) {
  10081. return;
  10082. }
  10083. // 如果正在投播,使用投播控制
  10084. if (this.isCurrentlyCasting()) {
  10085. await this.handleCastingPlayPause();
  10086. return;
  10087. }
  10088. // 本地播放控制
  10089. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10090. this.pause();
  10091. } else {
  10092. this.startPlayOrResumePlay();
  10093. this.playChange()
  10094. }
  10095. }
  10096. private sessionFastForwardCallback = (time?: number) => {
  10097. if (!time) {
  10098. return;
  10099. }
  10100. try {
  10101. // 通过UnifiedPlayerService获取当前位置
  10102. const currentState = this.unifiedPlayerService.getCurrentState();
  10103. const curPosition = currentState.currentPosition;
  10104. let seeTime = curPosition + time * 1000;
  10105. // 限制 seekValue 在合法范围内
  10106. if (seeTime < 0) {
  10107. seeTime = 0;
  10108. } else if (seeTime > currentState.duration) {
  10109. seeTime = currentState.duration;
  10110. }
  10111. Logger.info('onecold seeTime= ' + seeTime)
  10112. this.setSeekToActionProgress(seeTime)
  10113. this.seekTo(seeTime + "")
  10114. } catch (error) {
  10115. LogUtils.getInstance().LOGI(`sessionFastForwardCallback error: ${error}`);
  10116. }
  10117. };
  10118. /**
  10119. * Gesture method onActionUpdate.
  10120. *
  10121. * @param event Gesture event.手势拖动设置快进和后退
  10122. */
  10123. private setSeekToActionProgress(position: number) {
  10124. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  10125. let duration: number = this.unifiedPlayerService.getCurrentPosition();
  10126. let pos = 0;
  10127. if (duration > 0) {
  10128. this.slideEnable = true;
  10129. let curPercent = position / duration;
  10130. pos = curPercent * 100;
  10131. if (pos > this.PROGRESS_MAX_VALUE) {
  10132. this.progressValue = this.PROGRESS_MAX_VALUE
  10133. } else {
  10134. this.progressValue = pos;
  10135. }
  10136. }
  10137. // LogUtils.getInstance()
  10138. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10139. this.totalTime = this.stringForTime(duration);
  10140. if (position > duration) {
  10141. position = duration;
  10142. }
  10143. this.isCurrentTime = true;
  10144. this.currentTime = this.stringForTime(position);
  10145. this.isCurrentTime = false;
  10146. }
  10147. private sessionRewindCallback = (time?: number) => {
  10148. if (!time) {
  10149. return;
  10150. }
  10151. const curPosition: number = this.unifiedPlayerService.getCurrentPosition()
  10152. let seeTime = curPosition - time * 1000;
  10153. // 限制 seekValue 在合法范围内
  10154. if (seeTime < 0) {
  10155. seeTime = 0;
  10156. } else if (seeTime > this.duration) {
  10157. seeTime = this.duration;
  10158. }
  10159. Logger.info('onecold seeTime= ' + seeTime)
  10160. this.setSeekToActionProgress(seeTime)
  10161. this.seekTo(seeTime + "")
  10162. };
  10163. private sessionSeekCallback = (seekTime: number) => {
  10164. LogUtils.getInstance().LOGI(`播控中心请求进度调节: ${seekTime}ms`);
  10165. this.seekTo(seekTime + "");
  10166. };
  10167. // 注意:基础播控回调方法(play, pause, playNext, playPrevious, seek)
  10168. // 已经在UnifiedPlayerService中实现,这里不再重复定义,避免冲突
  10169. private async getFileSize(filePath: string): Promise<number> {
  10170. try {
  10171. const stat = await fs.stat(filePath);
  10172. return stat.size;
  10173. } catch (err) {
  10174. console.error('Failed to get file size: ' + err.message);
  10175. return 0;
  10176. }
  10177. }
  10178. // 启动投播长时任务
  10179. private startCastingBackgroundTask(): void {
  10180. try {
  10181. // 这里应该调用BackgroundTaskManager来申请长时任务
  10182. // 避免应用在投播时进入后台被系统冻结
  10183. LogUtils.getInstance().LOGI('申请投播长时任务');
  10184. // BackgroundTaskManager.startContinuousTask(this.context, backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK);
  10185. } catch (error) {
  10186. LogUtils.getInstance().LOGI(`申请投播长时任务失败: ${error}`);
  10187. }
  10188. }
  10189. // 停止投播长时任务
  10190. private stopCastingBackgroundTask(): void {
  10191. try {
  10192. LogUtils.getInstance().LOGI('停止投播长时任务');
  10193. // BackgroundTaskManager.stopContinuousTask(this.context);
  10194. } catch (error) {
  10195. LogUtils.getInstance().LOGI(`停止投播长时任务失败: ${error}`);
  10196. }
  10197. }
  10198. // 获取DRM许可证(示例实现,需要根据实际服务配置)
  10199. private async getLicense(drmUrl: string, requestData: Uint8Array): Promise<Uint8Array | undefined> {
  10200. try {
  10201. // 这里需要根据实际的DRM服务实现许可证获取逻辑
  10202. LogUtils.getInstance().LOGI(`请求DRM许可证: ${drmUrl}`);
  10203. // 示例:使用HTTP请求获取许可证
  10204. // const response = await fetch(drmUrl, {
  10205. // method: 'POST',
  10206. // headers: {
  10207. // 'Content-Type': 'application/octet-stream'
  10208. // },
  10209. // body: requestData
  10210. // });
  10211. //
  10212. // if (response.ok) {
  10213. // const licenseData = await response.arrayBuffer();
  10214. // return new Uint8Array(licenseData);
  10215. // }
  10216. LogUtils.getInstance().LOGI('DRM许可证获取功能需要根据实际服务配置');
  10217. return undefined;
  10218. } catch (error) {
  10219. LogUtils.getInstance().LOGI(`获取DRM许可证失败: ${error}`);
  10220. return undefined;
  10221. }
  10222. }
  10223. // 检查当前是否正在投播
  10224. public isCurrentlyCasting(): boolean {
  10225. return this.isCasting && this.castController !== undefined;
  10226. }
  10227. // 获取当前投播设备信息
  10228. public getCurrentCastDevice(): avSession.DeviceInfo | undefined {
  10229. return this.currentCastDevice;
  10230. }
  10231. // 投播控制命令
  10232. public async sendCastControlCommand(command: string, parameter?: number): Promise<void> {
  10233. if (!this.castController) {
  10234. LogUtils.getInstance().LOGI('投播控制器不可用');
  10235. return;
  10236. }
  10237. try {
  10238. let avCommand: avSession.AVCastControlCommand = {
  10239. command: command as avSession.AVCastControlCommandType
  10240. };
  10241. if (parameter !== undefined) {
  10242. avCommand.parameter = parameter;
  10243. }
  10244. await this.castController.sendControlCommand(avCommand);
  10245. LogUtils.getInstance().LOGI(`投播控制命令发送成功: ${command}`);
  10246. } catch (error) {
  10247. LogUtils.getInstance().LOGI(`发送投播控制命令失败: ${error}`);
  10248. ToastUtil.showToast(`投播控制失败: ${error}`);
  10249. }
  10250. }
  10251. private async pause() {
  10252. if (this.unifiedPlayerService.getIjkPlayer()?.isPlaying()){
  10253. this.savePlaybackPosition();
  10254. this.unifiedPlayerService.pause();
  10255. this.setProgress();
  10256. this.mDestroyPage = true;
  10257. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  10258. // 注意:AVSession状态更新由UnifiedPlayerService统一处理,避免冲突
  10259. this.playChange()
  10260. if (this.pipController) {
  10261. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10262. PiPWindow.PiPControlStatus.PAUSE);
  10263. }
  10264. }
  10265. // try {
  10266. // // 使用UnifiedPlayerService暂停播放
  10267. // await this.unifiedPlayerService.pause();
  10268. //
  10269. // // 保持原有的UI更新逻辑
  10270. // this.setProgress();
  10271. // this.mDestroyPage = true;
  10272. // this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  10273. // this.setIsPlaying(false);
  10274. // this.updateSessionPlayState(false);
  10275. // this.playChange()
  10276. //
  10277. // if (this.pipController) {
  10278. // this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10279. // PiPWindow.PiPControlStatus.PAUSE);
  10280. // }
  10281. //
  10282. // LogUtils.getInstance().LOGI("LocalMusic: pause completed via UnifiedPlayerService");
  10283. // } catch (error) {
  10284. // LogUtils.getInstance().LOGI(`LocalMusic pause error: ${error}`);
  10285. // ToastUtil.showToast(`暂停失败: ${error}`);
  10286. // }
  10287. }
  10288. private async stop() {
  10289. try {
  10290. // 使用UnifiedPlayerService停止播放
  10291. await this.unifiedPlayerService.stop();
  10292. // 保持原有的UI更新逻辑 - 重要:停止时清除所有播放状态
  10293. this.stopProgressTask();
  10294. this.CONTROL_PlayStatus = PlayStatus.INIT; // 初始状态,不是暂停
  10295. this.setIsPlaying(false);
  10296. // 强制更新UI状态
  10297. this.playChange()
  10298. this.watchStatus();
  10299. LogUtils.getInstance().LOGI("LocalMusic: stop completed - all states cleared to INIT");
  10300. } catch (error) {
  10301. LogUtils.getInstance().LOGI(`LocalMusic stop error: ${error}`);
  10302. ToastUtil.showToast(`停止播放失败: ${error}`);
  10303. }
  10304. }
  10305. //保持记忆播放功能
  10306. private savePlaybackPosition() {
  10307. try {
  10308. // 通过UnifiedPlayerService获取当前播放位置
  10309. const currentState = this.unifiedPlayerService.getCurrentState();
  10310. const position = currentState.currentPosition;
  10311. const duration = currentState.duration;
  10312. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  10313. // 如果播放位置接近视频末尾,则保存 position 为 0
  10314. const playbackPosition = (duration - position < threshold) ? 0 : position;
  10315. // 同时保存到PreferencesUtil和AppStorage,确保卡片也能访问
  10316. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  10317. AppStorage.setOrCreate(`playback_${this.videoUrl}`, playbackPosition);
  10318. LogUtils.getInstance().LOGI(`Saved playback position: ${playbackPosition}ms for ${this.name}`);
  10319. } catch (error) {
  10320. LogUtils.getInstance().LOGI(`savePlaybackPosition error: ${error}`);
  10321. }
  10322. }
  10323. //获取记忆播放功能
  10324. private restorePlaybackPosition() {
  10325. // 优先从AppStorage获取,如果没有则从PreferencesUtil获取
  10326. let position: number = AppStorage.get<number>(`playback_${this.videoUrl}`) || 0;
  10327. if (position === 0) {
  10328. position = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10329. }
  10330. // ToastUtil.showToast('position = ' + position)
  10331. if (position > 0) {
  10332. // ToastUtil.showToast('seekTo = ' + position)
  10333. this.seekTo(position + "");
  10334. LogUtils.getInstance().LOGI(`Restored playback position: ${position}ms for ${this.name}`);
  10335. }
  10336. }
  10337. private async seekTo(value: string) {
  10338. try {
  10339. const position = parseInt(value);
  10340. // 如果正在投播,使用投播进度控制
  10341. if (this.isCurrentlyCasting()) {
  10342. await this.handleCastingSeek(position);
  10343. return;
  10344. }
  10345. // 使用UnifiedPlayerService进行拖动
  10346. await this.unifiedPlayerService.seekTo(value);
  10347. // 保持原有的UI更新逻辑
  10348. this.setProgress()
  10349. LogUtils.getInstance().LOGI(`LocalMusic: seekTo ${value} completed via UnifiedPlayerService`);
  10350. } catch (error) {
  10351. LogUtils.getInstance().LOGI(`LocalMusic seekTo error: ${error}`);
  10352. // 如果是WMA格式错误,显示特定提示
  10353. if (error.toString().includes('WMA format')) {
  10354. ToastUtil.showToast('wma格式不支持拖动快进。');
  10355. return;
  10356. } else {
  10357. ToastUtil.showToast(`拖动失败: ${error}`);
  10358. }
  10359. }
  10360. }
  10361. // 添加到下一首播放
  10362. private addToNextPlay(song: VideoItem) {
  10363. if (!this.debounce()) {
  10364. return;
  10365. }
  10366. if (this.currentSong) {
  10367. if (this.currentSong === song) {
  10368. ToastUtil.showToast('当前已经在播放这首歌了!')
  10369. return
  10370. }
  10371. }
  10372. try {
  10373. // 如果未开始播放或队列为空
  10374. if (this.curIndex === -1 || this.songList.length === 0) {
  10375. this.songList = [song];
  10376. this.curIndex = 0;
  10377. this.doPlay(song)
  10378. return;
  10379. }
  10380. // 插入到当前索引+1的位置
  10381. const insertPos = this.curIndex + 1;
  10382. // 使用UnifiedPlayerService添加到播放列表
  10383. this.unifiedPlayerService.addToPlaylist(song, insertPos);
  10384. // 更新本地播放列表
  10385. this.songList.splice(insertPos, 0, song);
  10386. this.songList = [...this.songList]; // 触发状态更新
  10387. this.sonDataSource.pushArrayData(this.songList);
  10388. ToastUtil.showToast('已添加至下一首播放')
  10389. } catch (error) {
  10390. // 错误处理:回退到原有逻辑
  10391. const insertPos = this.curIndex + 1;
  10392. this.songList.splice(insertPos, 0, song);
  10393. this.songList = [...this.songList];
  10394. this.sonDataSource.pushArrayData(this.songList);
  10395. ToastUtil.showToast('已添加至下一首播放')
  10396. }
  10397. }
  10398. //下一个
  10399. private async playNext() {
  10400. if (!this.debounce()) {
  10401. return;
  10402. }
  10403. try {
  10404. // 移除了随机播放的特殊处理,统一使用UnifiedPlayerService
  10405. // 这样可以确保所有播放模式的状态都保持一致
  10406. if (ArrayUtil.isNotEmpty(this.songList)) {
  10407. // 如果正在投播,需要特殊处理
  10408. if (this.isCurrentlyCasting()) {
  10409. await this.handleCastingPlayNext();
  10410. return;
  10411. }
  10412. // 使用UnifiedPlayerService播放下一首,支持所有播放模式(包括随机播放)
  10413. await this.unifiedPlayerService.playNext();
  10414. // 智能同步播放列表到UnifiedPlayerService
  10415. const servicePlaylist = this.unifiedPlayerService.getPlaylist();
  10416. const serviceIndex = this.unifiedPlayerService.getCurrentIndex();
  10417. if (ArrayUtil.isEmpty(servicePlaylist)) {
  10418. // 如果服务没有播放列表,使用LocalMusic的播放列表
  10419. this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
  10420. } else {
  10421. // 如果服务已有播放列表,检查是否需要同步
  10422. const serviceSong = this.unifiedPlayerService.getCurrentSong();
  10423. if (serviceSong && serviceIndex >= 0 && serviceIndex < servicePlaylist.length) {
  10424. // 同步服务的状态到LocalMusic,确保状态一致
  10425. this.songList = servicePlaylist;
  10426. this.curIndex = serviceIndex;
  10427. this.currentSong = serviceSong;
  10428. this.sonDataSource.pushArrayData(this.songList);
  10429. }
  10430. }
  10431. // 更新本地状态以保持UI同步
  10432. const currentIndex = this.unifiedPlayerService.getCurrentIndex();
  10433. const currentSong = this.unifiedPlayerService.getCurrentSong();
  10434. if (currentSong) {
  10435. this.curIndex = currentIndex;
  10436. this.currentSong = currentSong;
  10437. this.videoUrl = currentSong.filePath;
  10438. this.artist = currentSong.artist;
  10439. this.name = currentSong.name;
  10440. this.cover = currentSong.pixelMapPath;
  10441. // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  10442. this.oldSeconds = 0;
  10443. this.currentTime = "00:00";
  10444. this.lastSongPath = currentSong.filePath;
  10445. this.justSwitched = true; // 标记歌曲刚刚切换
  10446. this.changeImageAnimation();
  10447. }
  10448. }
  10449. } catch (error) {
  10450. ToastUtil.showToast(`切换下一首失败: ${error}`);
  10451. // 错误处理:回退到原有逻辑
  10452. this.fallbackPlayNext();
  10453. }
  10454. // 同步播放列表到UnifiedPlayerService
  10455. this.syncPlaylistToService();
  10456. }
  10457. // 回退到原有的playNext逻辑
  10458. private fallbackPlayNext() {
  10459. if (ArrayUtil.isNotEmpty(this.songList)) {
  10460. if (this.curIndex == this.songList.length - 1) {
  10461. this.curIndex = 0;
  10462. } else {
  10463. this.curIndex++;
  10464. }
  10465. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10466. this.stop();
  10467. this.currentSong = this.songList[this.curIndex]
  10468. this.videoUrl = this.songList[this.curIndex].filePath;
  10469. this.artist = this.songList[this.curIndex].artist
  10470. this.name = this.songList[this.curIndex].name
  10471. this.changeImageAnimation()
  10472. }
  10473. }
  10474. changeImageAnimation() {
  10475. if(this.openSkipSongAnimate){
  10476. // 第一步:淡出动画
  10477. this.getUIContext()?.animateTo({
  10478. duration: 500,
  10479. curve: Curve.EaseOut,
  10480. }, () => {
  10481. this.opacityValueImage = 0.1;
  10482. if(this.isCoverRectangle){
  10483. this.scaleValueImage = 0.88
  10484. }
  10485. });
  10486. // 第二步:切换图片后淡入
  10487. setTimeout(() => {
  10488. this.cover = this.songList[this.curIndex].pixelMapPath
  10489. this.getUIContext()?.animateTo({
  10490. duration: 500,
  10491. curve: Curve.EaseIn,
  10492. }, () => {
  10493. this.opacityValueImage = 1;
  10494. this.scaleValueImage = 1 // 图标恢复到原始大小
  10495. // 注意:不再手动调用 startPlayOrResumePlay(),因为 UnifiedPlayerService 已经处理了播放逻辑
  10496. });
  10497. }, 500);
  10498. }else{
  10499. this.cover = this.songList[this.curIndex].pixelMapPath
  10500. // 注意:不再手动调用 startPlayOrResumePlay(),因为 UnifiedPlayerService 已经处理了播放逻辑
  10501. }
  10502. }
  10503. // 存储已播放的歌曲索引
  10504. private playedIndices: Set<number> = new Set();
  10505. //随机播放
  10506. private randomPlay() {
  10507. // if (!this.debounce()) {
  10508. // return;
  10509. // }
  10510. if (ArrayUtil.isNotEmpty(this.songList)) {
  10511. if (this.songList.length > 3) {
  10512. // 如果所有歌曲都播放过一次,清空已播放索引集合
  10513. if (this.playedIndices.size === this.songList.length) {
  10514. this.playedIndices.clear();
  10515. }
  10516. // 随机选择一个未播放的歌曲索引
  10517. let newIndex: number;
  10518. // 添加超时机制防止无限循环
  10519. let attempt = 0;
  10520. const maxAttempts = 100; // 根据需求调整
  10521. do {
  10522. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  10523. attempt++;
  10524. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  10525. if (attempt >= maxAttempts) {
  10526. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  10527. newIndex = Math.floor(Math.random() * this.songList.length);
  10528. }
  10529. this.curIndex = newIndex;
  10530. this.playedIndices.add(newIndex);
  10531. } else {
  10532. // 当歌曲数量小于或等于3时,直接播放下一首
  10533. if (this.curIndex == this.songList.length - 1) {
  10534. this.curIndex = 0;
  10535. } else {
  10536. this.curIndex++;
  10537. }
  10538. }
  10539. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10540. this.stop();
  10541. this.currentSong = this.songList[this.curIndex];
  10542. this.videoUrl = this.songList[this.curIndex].filePath;
  10543. this.name = this.songList[this.curIndex].name;
  10544. this.artist = this.songList[this.curIndex].artist
  10545. // this.cover = this.songList[this.curIndex].pixelMapPath
  10546. this.changeImageAnimation()
  10547. }
  10548. }
  10549. private async playIndex(index: number) {
  10550. if (!this.debounce()) {
  10551. return;
  10552. }
  10553. if (ArrayUtil.isNotEmpty(this.songList)) {
  10554. try {
  10555. // 使用UnifiedPlayerService播放指定索引的歌曲
  10556. await this.playSongAtIndexViaService(index);
  10557. this.changeImageAnimation();
  10558. } catch (error) {
  10559. // 错误处理:回退到原有逻辑
  10560. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10561. this.stop();
  10562. this.currentSong = this.songList[index]
  10563. this.videoUrl = this.songList[index].filePath;
  10564. this.name = this.songList[index].name
  10565. this.artist = this.songList[index].artist
  10566. this.curIndex = index;
  10567. this.changeImageAnimation()
  10568. }
  10569. }
  10570. }
  10571. //上一个
  10572. private async playPrevious() {
  10573. if (!this.debounce()) {
  10574. return;
  10575. }
  10576. try {
  10577. // 移除了随机播放的特殊处理,统一使用UnifiedPlayerService
  10578. // 这样可以确保所有播放模式的状态都保持一致
  10579. if (ArrayUtil.isNotEmpty(this.songList)) {
  10580. // 如果正在投播,需要特殊处理
  10581. if (this.isCurrentlyCasting()) {
  10582. await this.handleCastingPlayPrevious();
  10583. return;
  10584. }
  10585. // 使用UnifiedPlayerService播放上一首,支持所有播放模式(包括随机播放)
  10586. await this.unifiedPlayerService.playPrevious();
  10587. // 智能同步播放列表到UnifiedPlayerService
  10588. const servicePlaylist = this.unifiedPlayerService.getPlaylist();
  10589. const serviceIndex = this.unifiedPlayerService.getCurrentIndex();
  10590. // 更新本地状态以保持UI同步
  10591. const currentIndex = this.unifiedPlayerService.getCurrentIndex();
  10592. const currentSong = this.unifiedPlayerService.getCurrentSong();
  10593. if (currentSong) {
  10594. this.curIndex = currentIndex;
  10595. this.currentSong = currentSong;
  10596. this.videoUrl = currentSong.filePath;
  10597. this.name = currentSong.name;
  10598. this.artist = currentSong.artist;
  10599. this.cover = currentSong.pixelMapPath;
  10600. // 重置时间显示状态,防止新歌曲时间显示被上一首歌曲的时间"卡住"
  10601. this.oldSeconds = 0;
  10602. this.currentTime = "00:00";
  10603. this.lastSongPath = currentSong.filePath;
  10604. this.justSwitched = true; // 标记歌曲刚刚切换
  10605. this.changeImageAnimation();
  10606. }
  10607. }
  10608. } catch (error) {
  10609. ToastUtil.showToast(`切换上一首失败: ${error}`);
  10610. // 错误处理:回退到原有逻辑
  10611. this.fallbackPlayPrevious();
  10612. }
  10613. // 同步播放列表到UnifiedPlayerService
  10614. this.syncPlaylistToService();
  10615. }
  10616. // 回退到原有的playPrevious逻辑
  10617. private fallbackPlayPrevious() {
  10618. if (this.curIndex == 0) {
  10619. this.curIndex = this.songList.length - 1;
  10620. } else {
  10621. this.curIndex--;
  10622. }
  10623. this.CONTROL_PlayStatus = PlayStatus.INIT;
  10624. this.stop();
  10625. this.currentSong = this.songList[this.curIndex]
  10626. this.videoUrl = this.songList[this.curIndex].filePath;
  10627. this.name = this.songList[this.curIndex].name
  10628. this.artist = this.songList[this.curIndex].artist
  10629. this.startPlayOrResumePlay()
  10630. this.changeImageAnimation()
  10631. }
  10632. debounce() {
  10633. const delay = 600;
  10634. let cur = new Date().getTime();
  10635. if (cur - this.last > delay) {
  10636. this.last = cur;
  10637. return true;
  10638. }
  10639. return false;
  10640. }
  10641. /**
  10642. * Sets whether the screen is a constant based on the playback status.
  10643. */
  10644. watchStatus() {
  10645. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  10646. if (this.windowClass) {
  10647. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10648. this.windowClass.setWindowKeepScreenOn(true);
  10649. } else {
  10650. this.windowClass.setWindowKeepScreenOn(false);
  10651. }
  10652. }
  10653. }
  10654. /**
  10655. * Volume gesture method onActionStart.
  10656. *
  10657. * @param event Gesture event.
  10658. */
  10659. private customDialogComponentIdMM: number = 0
  10660. @Builder
  10661. customDialogComponentMM() {
  10662. Column() {
  10663. Row() {
  10664. Blank()
  10665. Text('验证密码')
  10666. .fontSize(22)
  10667. .fontColor($r('app.color.pri_bg'))
  10668. .margin({ top: 18 })
  10669. Blank()
  10670. Image($r('app.media.close'))
  10671. .fillColor(Color.White)
  10672. .margin({ top: 18, right: 18 })
  10673. .width(20)
  10674. .onClick(() => {
  10675. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10676. })
  10677. }
  10678. .width('100%') // 使Row占据整个宽度
  10679. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  10680. Verify({
  10681. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  10682. });
  10683. }.height('60%')
  10684. .backgroundColor($r('app.color.index_background'))
  10685. .justifyContent(FlexAlign.SpaceBetween)
  10686. }
  10687. private handleVerifyCompleted(isSuccess: boolean) {
  10688. if (isSuccess) {
  10689. console.log('验证成功');
  10690. // 在这里处理验证成功后的逻辑
  10691. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10692. this.currentPath = this.lockPath
  10693. this.getSortedFiles(this.currentPath)
  10694. } else {
  10695. // console.log('验证失败');
  10696. ToastUtil.showToast('验证失败')
  10697. }
  10698. }
  10699. private showVerifyDialog() {
  10700. promptAction.openCustomDialog({
  10701. transition: TransitionEffect.asymmetric(
  10702. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  10703. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10704. ,
  10705. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  10706. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10707. ),
  10708. builder: () => {
  10709. this.customDialogComponentMM()
  10710. },
  10711. isModal: true,
  10712. autoCancel: true,
  10713. maskColor: Color.Transparent,
  10714. alignment: DialogAlignment.Bottom,
  10715. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  10716. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  10717. console.log("dialog onWillDismiss")
  10718. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  10719. dismissDialogAction.dismiss()
  10720. }
  10721. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  10722. dismissDialogAction.dismiss()
  10723. }
  10724. }
  10725. }).then((dialogId: number) => {
  10726. this.customDialogComponentIdMM = dialogId
  10727. })
  10728. }
  10729. //左滑操作 移动文件 重命名 删除等操作
  10730. @Builder
  10731. DeleteButton(item: VideoItem, index: number, filePath: string) {
  10732. Row() {
  10733. //加入收藏
  10734. Button() {
  10735. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  10736. .fillColor(Color.White)
  10737. .width(20)
  10738. }
  10739. .width(40)
  10740. .height(40)
  10741. .type(ButtonType.Circle)
  10742. .backgroundColor(this.themeColor)
  10743. .margin(5)
  10744. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10745. .onClick(() => {
  10746. if (item) {
  10747. this.doFav(item)
  10748. }
  10749. })
  10750. //加入下一首播放
  10751. Button() {
  10752. Image($r('app.media.next_to_play'))
  10753. .fillColor(Color.White)
  10754. .width(20)
  10755. }
  10756. .width(40)
  10757. .height(40)
  10758. .type(ButtonType.Circle)
  10759. .backgroundColor(this.themeColor)
  10760. .margin(5)
  10761. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10762. .onClick(() => {
  10763. this.addToNextPlay(item);
  10764. })
  10765. //复制文件
  10766. Button() {
  10767. Image($r('app.media.copy'))
  10768. .fillColor(Color.White)
  10769. .width(20)
  10770. }
  10771. .width(40)
  10772. .height(40)
  10773. .type(ButtonType.Circle)
  10774. .backgroundColor(this.themeColor)
  10775. .margin(5)
  10776. .id(filePath + 'copy')
  10777. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10778. .onClick(() => {
  10779. this.showCopyDialog(false, item, index, filePath + 'copy');
  10780. })
  10781. //移动文件
  10782. Button() {
  10783. Image($r('app.media.cut'))
  10784. .fillColor(Color.White)
  10785. .width(20)
  10786. }
  10787. .width(40)
  10788. .height(40)
  10789. .type(ButtonType.Circle)
  10790. .backgroundColor(this.themeColor)
  10791. .margin(5)
  10792. .id(filePath)
  10793. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10794. .onClick(() => {
  10795. this.showCutDialog(false, item, index, filePath);
  10796. })
  10797. Button() {
  10798. Image($r('app.media.cut_current'))
  10799. .fillColor(Color.White)
  10800. .width(20)
  10801. }
  10802. .width(40)
  10803. .height(40)
  10804. .type(ButtonType.Circle)
  10805. .backgroundColor(this.themeColor)
  10806. .margin(5)
  10807. .id(filePath + 'current')
  10808. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  10809. (this.isHasDir ? Visibility.Visible : Visibility.None))
  10810. .onClick(() => {
  10811. this.showCutDialog(true, item, index, filePath + 'current');
  10812. })
  10813. //重命名
  10814. Button() {
  10815. Image($r('app.media.rename2'))
  10816. .fillColor(Color.White)
  10817. .width(20)
  10818. }
  10819. .width(40)
  10820. .height(40)
  10821. .type(ButtonType.Circle)
  10822. .backgroundColor(this.themeColor)
  10823. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10824. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10825. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10826. .margin(5)
  10827. .onClick(() => {
  10828. this.showReNameDialog(item, index + '', filePath)
  10829. })
  10830. Button() {
  10831. Image($r('app.media.delete2'))
  10832. .fillColor(Color.White)
  10833. .width(20)
  10834. }
  10835. .width(40)
  10836. .height(40)
  10837. .type(ButtonType.Circle)
  10838. .backgroundColor(this.themeColor)
  10839. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10840. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10841. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10842. .margin(5)
  10843. .onClick(() => {
  10844. this.showWarnIsDeleteFile(item, index + '', filePath)
  10845. })
  10846. Button() {
  10847. Image($r('app.media.share2'))
  10848. .fillColor(Color.White)
  10849. .width(20)
  10850. }
  10851. .width(40)
  10852. .height(40)
  10853. .type(ButtonType.Circle)
  10854. .backgroundColor(this.themeColor)
  10855. .margin(5)
  10856. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10857. .onClick(() => {
  10858. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10859. })
  10860. }
  10861. }
  10862. /**
  10863. * 穿山甲banner广告
  10864. */
  10865. // private declare bannerAd: CSJNativeExpressAd;
  10866. // @State private status: string = "未加载"
  10867. // @State private isShowAd: boolean = false
  10868. // private declare mAdSlot: AdSlot;
  10869. // private mBiddingAdm = '' //服务端bidding才需要设置
  10870. // private expressLoadAdListener: NativeExpressAdListener = {
  10871. // /**
  10872. // * 加载失败的回调
  10873. // *
  10874. // * @param code
  10875. // * @param message
  10876. // */
  10877. // onError: (code: number, message: string) => {
  10878. // console.error("加载广告失败,code=" + code + ",message=" + message);
  10879. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  10880. // },
  10881. //
  10882. // /**
  10883. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  10884. // *
  10885. // * @param ads 返回的广告列表
  10886. // */
  10887. //
  10888. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  10889. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  10890. // if (ads && ads.length > 0) {
  10891. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  10892. // ad.setExpressInteractionListener({
  10893. // /**
  10894. // *广告的点击回调
  10895. // * @param type 广告的交互类型
  10896. // */
  10897. // onAdClicked: (type: number) => {
  10898. // console.log("BannerExpressAdPage==onAdClicked......");
  10899. // },
  10900. //
  10901. // /**
  10902. // * 广告的展示回调 每个广告仅回调一次
  10903. // * @param type 广告的交互类型
  10904. // */
  10905. // onAdShow: (type: number) => {
  10906. // console.log("BannerExpressAdPage==onAdShow......");
  10907. // },
  10908. //
  10909. // /**
  10910. // * 模板渲染失败
  10911. // */
  10912. // onRenderFail: (code: number, msg: string) => {
  10913. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  10914. // },
  10915. //
  10916. // /**
  10917. // * 模板渲染成功
  10918. // * @param width 返回view的宽 单位 vp
  10919. // * @param height 返回view的高 单位 vp
  10920. // */
  10921. // onRenderSuccess: (width: number, height: number) => {
  10922. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  10923. // this.bannerAd = ad;
  10924. // this.status = "广告加载完成待展示";
  10925. //
  10926. // this.showBannerAd()
  10927. // }
  10928. // })
  10929. // //渲染广告
  10930. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  10931. // this.setDislikeCallback(ad); //设置dislike
  10932. // ad.render(this.getUIContext())
  10933. // this.status = "广告加载中...";
  10934. // });
  10935. // }
  10936. // }
  10937. // }
  10938. //
  10939. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  10940. // ad.setDislikeCallback({
  10941. // /**
  10942. // * dislike show
  10943. // */
  10944. // onShow: () => {
  10945. // console.log("BannerExpressAdPage==dislike......show");
  10946. // },
  10947. //
  10948. // /**
  10949. // * @param position 选择的位置
  10950. // * @param value 选择的内容
  10951. // * @param enforceRemove 是否强制关闭广告
  10952. // */
  10953. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  10954. // this.isShowAd = false;
  10955. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  10956. // ",enforce=" + enforceRemove);
  10957. // },
  10958. //
  10959. // /**
  10960. // * 点击取消
  10961. // */
  10962. // onCancel: () => {
  10963. // console.log("BannerExpressAdPage==dislike......onCancel");
  10964. // }
  10965. //
  10966. // })
  10967. // }
  10968. /**
  10969. * 加载Banner广告
  10970. */
  10971. loadBannerAd(rit: string) {
  10972. // if (Utility.isNoble()) {
  10973. // return
  10974. // }
  10975. // if (!Utility.isPassInstallTime(2)) {
  10976. // return
  10977. // }
  10978. // this.isShowAd = false;
  10979. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  10980. // this.mAdSlot = new AdSlotBuilder()
  10981. // .setCodeId(rit)
  10982. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  10983. // .setAdCount(1)
  10984. // .setBidAdm(this.mBiddingAdm)
  10985. // .build()
  10986. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  10987. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  10988. // this.status = "广告加载中..."
  10989. }
  10990. }
  10991. //视频气泡窗口的布局
  10992. @Builder
  10993. function customPopupBuilder(dataBu: BubbleBean) {
  10994. List() {
  10995. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  10996. ListItem() {
  10997. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10998. Row() {
  10999. Column() {
  11000. Image(dataBu.imageRes[index])
  11001. .height(28)
  11002. .fillColor(dataBu.color)
  11003. .alignSelf(ItemAlign.Center)
  11004. }
  11005. .width(32)
  11006. Text(item)
  11007. .padding({
  11008. top: 10,
  11009. bottom: 10,
  11010. right: 10,
  11011. left: 10
  11012. })
  11013. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  11014. .textAlign(TextAlign.Start)
  11015. .width("100%")
  11016. }
  11017. }
  11018. .backgroundColor($r('app.color.settings_background_main'))
  11019. .margin({ top: 6, bottom: 6 })
  11020. }
  11021. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  11022. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  11023. TransitionEffect.scale({ x: 0, y: 0 })))
  11024. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  11025. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  11026. .onClick(() => {
  11027. dataBu.onItemClick?.(index)
  11028. })
  11029. })
  11030. }
  11031. .width(120)
  11032. .divider({
  11033. strokeWidth: 1,
  11034. color: "#22FFFFFF"
  11035. })
  11036. }
  11037. // Function to calculate a hash for the file list
  11038. function simpleHash(fileList: string[]): string {
  11039. let hash = 0;
  11040. const str = fileList.join(',');
  11041. for (let i = 0; i < str.length; i++) {
  11042. const char = str.charCodeAt(i);
  11043. hash = (hash << 5) - hash + char;
  11044. hash |= 0; // Convert to 32bit integer
  11045. }
  11046. return hash.toString();
  11047. }
  11048. interface MoreItem {
  11049. id: number;
  11050. image: Resource;
  11051. title: string;
  11052. }
  11053. //视频气泡窗口的布局
  11054. @Builder
  11055. function cutPopupBuilder(dataBu: BubbleBean) {
  11056. Column() {
  11057. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  11058. .padding({
  11059. top: 10,
  11060. bottom: 10,
  11061. right: 10,
  11062. left: 10
  11063. })
  11064. .textAlign(TextAlign.Start)
  11065. .width(160)
  11066. .fontWeight(666)
  11067. .fontSize(16)
  11068. List() {
  11069. ForEach(dataBu.data, (item: string, index: number) => {
  11070. ListItem() {
  11071. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11072. Row() {
  11073. Column() {
  11074. Image($r('app.media.music_group'))
  11075. .height(28)
  11076. .fillColor(dataBu.color)
  11077. .alignSelf(ItemAlign.Center)
  11078. }
  11079. .width(32)
  11080. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  11081. .padding({
  11082. top: 10,
  11083. bottom: 10,
  11084. right: 10,
  11085. left: 10
  11086. })
  11087. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  11088. .fontSize(15)
  11089. }
  11090. }
  11091. .backgroundColor(Color.Transparent)
  11092. .margin({ top: 7, bottom: 7 })
  11093. }
  11094. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  11095. .animation({ duration: 500 }),
  11096. TransitionEffect.scale({ x: 0, y: 0 })))
  11097. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  11098. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  11099. .onClick(() => {
  11100. dataBu.onItemClick?.(index)
  11101. })
  11102. })
  11103. }
  11104. .width(150)
  11105. .divider({
  11106. strokeWidth: 1,
  11107. color: "#22FFFFFF"
  11108. })
  11109. }
  11110. .height(300)
  11111. .padding({
  11112. bottom: 30
  11113. })
  11114. }
  11115. function getFileDirName(filePath: string,rootPath:string): string{
  11116. if(filePath===rootPath){
  11117. return '首页'
  11118. }
  11119. let result = FileUtil.getFileName(filePath)
  11120. if(StrUtil.isEmpty(result))
  11121. return ''
  11122. if(result.startsWith('.'))
  11123. result = result.replace(/\./g, '')
  11124. return result
  11125. }
  11126. /**
  11127. * LocalMusic 状态监听器实现类
  11128. * 用于接收 UnifiedPlayerService 的状态变化通知
  11129. */
  11130. class LocalMusicStateListener implements PlayerStateListener {
  11131. private localMusic: LocalMusic;
  11132. constructor(localMusic: LocalMusic) {
  11133. this.localMusic = localMusic;
  11134. }
  11135. onStateChanged(state: PlayerState): void {
  11136. this.localMusic.onPlayerStateChanged(state);
  11137. }
  11138. onSongChanged(song: VideoItem): void {
  11139. this.localMusic.onPlayerSongChanged(song);
  11140. }
  11141. onError(error: PlayerError): void {
  11142. this.localMusic.onPlayerError(error);
  11143. }
  11144. }