LocalMusic.ets 658 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. getNavidromeVideoItems,
  8. getNavidromeCurrentPlayIndex,
  9. getUnplayedSongs,
  10. getUnplayedCount,
  11. markAsPlayed,
  12. clearPlayedHistory,
  13. getPlayedCount,
  14. getNavidromeTotalCount,
  15. setNavidromeTotalCount
  16. } from '../common/util/NavidromePlaylistStore';
  17. import { triggerLoadMoreSongs, hasMoreData } from '../common/util/NavidromeRandomLoader';
  18. import {
  19. ImplOnBufferingUpdateListener,
  20. ImplOnCompletionListener,
  21. ImplOnErrorListener,
  22. ImplOnInfoListener,
  23. ImplOnPreparedListener,
  24. ImplOnSeekCompleteListener,
  25. ImplOnTimedTextListener,
  26. ImplOnVideoSizeChangedListener
  27. } from '../common/IjkPlayerListenerImpls';
  28. import {
  29. ButtonFancyModifier,
  30. ImageFancyModifier,
  31. ShadowModifier,
  32. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  33. import {
  34. AppUtil,
  35. ArrayUtil,
  36. Base64Util,
  37. DateUtil,
  38. DeviceUtil,
  39. FileUtil,
  40. GlobalContext,
  41. LogUtil,
  42. MD5,
  43. PreferencesUtil,
  44. RandomUtil,
  45. StrUtil,
  46. ToastUtil
  47. } from '@pura/harmony-utils';
  48. import { imagePathToPixelMap } from '../common/util/CommUtils';
  49. import LyricUtil from '../common/util/LyricUtil';
  50. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  51. import { CommonConstants } from '../common/constants/CommonConstants';
  52. import { BaiduConstants } from '../common/constants/BaiduConstants';
  53. import { EventConstants } from '../common/constants/EventConstants';
  54. import Logger from '../common/util/Logger';
  55. import { http } from '@kit.NetworkKit';
  56. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  57. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  58. import { BubbleBean } from '../viewmodel/BubbleBean';
  59. import { PopupPosition, XPopup } from '@chinalike/popup';
  60. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  61. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  62. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  63. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  64. import { Verify } from './Verify';
  65. import { taskpool } from '@kit.ArkTS';
  66. import { RotatingCover } from './RotatingCover';
  67. import { SpectrumView } from './spectrum/SpectrumView';
  68. import { PointLightButton } from './PointLight/PointLightButton';
  69. import { PlayConstants } from '../common/constants/PlayConstants';
  70. import { effectKit } from '@kit.ArkGraphics2D';
  71. import { ColorConversion } from '../common/util/ColorConversion';
  72. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  73. import { AvSessionController } from '../controller/AvSessionController';
  74. import { EqualizerManager } from '../common/util/EqualizerManager';
  75. import { EqualizerViewWithCallback } from './EqualizerView';
  76. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  77. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  78. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  79. import { TagsContentCover } from '../view/TagsContentCover';
  80. import {
  81. DeviceChangeReason,
  82. IjkMediaPlayer,
  83. InterruptEvent,
  84. InterruptHintType,
  85. LogUtils,
  86. OnBufferingUpdateListener,
  87. OnCompletionListener,
  88. OnErrorListener,
  89. OnInfoListener,
  90. OnPreparedListener,
  91. OnSeekCompleteListener,
  92. OnTimedTextListener,
  93. OnVideoSizeChangedListener
  94. } from '@ohos/ijkplayer';
  95. import { PlayStatus } from '../common/PlayStatus';
  96. import fs from '@ohos.file.fs';
  97. import { image } from '@kit.ImageKit';
  98. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  99. import { media } from '@kit.MediaKit';
  100. import { UniversalDetector } from '@ohos/juniversalchardet';
  101. import { SettingPage } from '../pages/SettingPage';
  102. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  103. import { CommonConstants2 } from '../common/util/CommonConstants2';
  104. import { hilog } from '@kit.PerformanceAnalysisKit';
  105. import { LazyDataSource } from '../common/util/LazyDataSource';
  106. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  107. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  108. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  109. import { ringtone } from '@kit.RingtoneKit';
  110. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  111. import { resourceManager } from '@kit.LocalizationKit';
  112. import { deviceInfo } from '@kit.BasicServicesKit';
  113. import '../common/network/RemoteCacheRegistry';
  114. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  115. import { lyricService, SongData } from '../common/service/LyricService';
  116. import {
  117. cloneVideoItem,
  118. preloadNextSongIfNeeded,
  119. setVideoUrlForSong,
  120. getTypeOrder,
  121. isWebDavType,
  122. isSmbType,
  123. isNavidromeType,
  124. isFtpType,
  125. isBaiduType,
  126. isJellyfinType,
  127. isEmbyType,
  128. isAudioStationType,
  129. isPlexType,
  130. isRemoteCloudType,
  131. WorkerEditMusicResult,
  132. WebDavMetadataUpdatePayload,
  133. isDaoLiYuType
  134. } from '../common/util/RemotePlayerUtil';
  135. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  136. import app from '@system.app';
  137. import { TextNodeController } from './PipLyricTextBuilder';
  138. import { IndexerView } from './IndexerView';
  139. import { KeyCode } from '@kit.InputKit';
  140. import { KnockController } from '../controller/KnockController';
  141. import { DeleteComptent } from '../view/DeleteComptent';
  142. import { ABLoopComptent } from '../view/ABLoopComptent';
  143. import { FixMessyView } from '../view/FixMessyView';
  144. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  145. import { CueComptent } from '../view/CueComptent';
  146. import PlaylistTable from '../common/util/PlaylistTable';
  147. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  148. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  149. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  150. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  151. import { Song } from '../viewmodel/Song';
  152. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  153. import { SongType } from '../common/enums/SongType';
  154. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  155. buildHttpHeadersWithWebDav,
  156. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  157. import PermissionUtil from '../common/util/PermissionUtil'
  158. import { EditAudio, setRingTone } from './EditAudio';
  159. import { ExtractAccompaniment } from './ExtractAccompaniment';
  160. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  161. import { AudioFormatConverter } from './AudioFormatConverter';
  162. import { MergeAudio } from './MergeAudio';
  163. import { AIVoiceSeparation } from './AIVoiceSeparation';
  164. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  165. import { ChangeTone } from './ChangeTone';
  166. import {
  167. hdsEffect,
  168. HdsVisualComponent,
  169. HdsSceneController,
  170. HdsSceneType,
  171. HdsVisualComponentAttribute,
  172. } from '@kit.UIDesignKit';
  173. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  174. import { getFirstLetter } from '../Constants';
  175. import { audio } from '@kit.AudioKit';
  176. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  177. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  178. import { LyricCopySheet } from './LyricCopySheet';
  179. const TAG = 'LocalMusic';
  180. const HICAR_LOG_TAG = 'HiCarWindow';
  181. function logHiCarWindow(message: string): void {
  182. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  183. }
  184. export interface WorkerMetadataPayload {
  185. originFilePath: string;
  186. originId?: string;
  187. bit_rate?: string;
  188. duration?: string;
  189. sampleRate?: string;
  190. mimeType?: string;
  191. md5Str?: string;
  192. videoSize?: number;
  193. size?: string;
  194. pixelMapPath?: string;
  195. artist?: string;
  196. album?: string;
  197. name?: string;
  198. lyricContent?: string;
  199. bits_per_raw_sample?: string;
  200. channels?: string;
  201. channel_layout?: string;
  202. start_time?: string;
  203. genre?: string;
  204. year?: string;
  205. probe_score?: number;
  206. track?: string;
  207. disc?: string;
  208. ALBUMARTIST?: string;
  209. COMPOSER?: string;
  210. COMMENT?: string;
  211. LYRICIST?: string;
  212. nb_streams?: number;
  213. nb_programs?: number;
  214. error?: string;
  215. }
  216. interface WorkerMessageScanDone {
  217. code: 101;
  218. data: Record<string, never>;
  219. }
  220. interface WorkerMessageMediaList {
  221. code: 102;
  222. data: Array<VideoItem>;
  223. totalCount: number;
  224. }
  225. interface WorkerMessageArtistList {
  226. code: 103;
  227. data1: Map<string, Array<VideoItem>>;
  228. data2: Array<VideoItem>;
  229. totalCount: number;
  230. }
  231. interface WorkerMessageAlbumList {
  232. code: 104;
  233. data1: Map<string, Array<VideoItem>>;
  234. data2: Array<VideoItem>;
  235. totalCount: number;
  236. }
  237. interface WorkerMessageMetadata {
  238. code: 105;
  239. data: WorkerMetadataPayload;
  240. }
  241. interface WorkerMessageEditResult {
  242. code: 106;
  243. data: WorkerEditMusicResult;
  244. }
  245. interface AlphaTaskItem {
  246. type: number;
  247. name?: string;
  248. pyStr?: string;
  249. fileName?: string;
  250. artist?: string;
  251. album?: string;
  252. }
  253. type LocalMusicWorkerMessage =
  254. WorkerMessageScanDone
  255. | WorkerMessageMediaList
  256. | WorkerMessageArtistList
  257. | WorkerMessageAlbumList
  258. | WorkerMessageMetadata
  259. | WorkerMessageEditResult;
  260. /**
  261. * 歌单播放事件数据
  262. */
  263. interface PlaylistEventData {
  264. playlistId: string;
  265. playlistName: string;
  266. songCount: number;
  267. startIndex: number;
  268. songFilePaths: string[];
  269. isJump: boolean;
  270. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  271. }
  272. const DEFAULT_INDEX =
  273. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  274. 'X', 'Y', 'Z']
  275. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  276. // 元数据提取状态追踪
  277. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  278. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  279. // 定义接口
  280. interface HiCarAspectRatio {
  281. ratio: number;
  282. name: string;
  283. }
  284. interface GeneratedObjectLiteralInterface_1 {
  285. assetId: string;
  286. title: string;
  287. artist: string;
  288. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  289. mediaUri: string;
  290. // 该字段大写,音频'AUDIO',视频'VIDEO'
  291. mediaType: string;
  292. mediaSize: number;
  293. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  294. startPosition: number;
  295. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  296. duration: number;
  297. albumCoverUri: string;
  298. albumTitle: string;
  299. appName: string;
  300. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  301. drmScheme: string;
  302. }
  303. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  304. const ITEM_HEIGHT: number = 65; // 列表项中高度
  305. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  306. /**
  307. * 排序模式枚举
  308. * 定义各种排序方式的升序基准值
  309. */
  310. export enum SortMode {
  311. ByArtist = 0, // 按艺术家升序
  312. ByAlbum = 2, // 按专辑升序
  313. ByName = 4, // 按名称升序
  314. ByTime = 6, // 按时间升序
  315. ByAddTime = 7, // 按添加时间(只有降序)
  316. ByCount = 8, // 按数量升序
  317. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  318. }
  319. //功能强大的音乐播放器
  320. @Preview
  321. @Component
  322. export struct LocalMusic {
  323. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  324. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  325. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  326. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  327. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  328. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  329. @State showFindLocation: boolean = true
  330. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  331. @State showSimple: boolean = true//开启沉浸模式
  332. @State isPaging: boolean = true;//是否分页加载机制
  333. @State isCoverRectangle: boolean = true;
  334. @State showZMIndex: boolean = false //是否右侧显示字母索引
  335. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  336. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  337. // 字母表
  338. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  339. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  340. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  341. @State selectAlphaBetIndex: number = 0
  342. @State isShowAlphaBet: boolean = false
  343. @State isScrolling: boolean = false
  344. @State isTouchingAlphaBet: boolean = false
  345. @State alphabetHeight: number = 0
  346. public enableShowAlphabet: boolean = true // 是否显示字母表
  347. private alphaBetHideTimer: number = 0
  348. private alphaBetRebuildTimer: number = 0
  349. private alphaBetDirty: boolean = false
  350. private alphaBetCacheKey: string = ''
  351. private alphaBetBuildVersion: number = 0
  352. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  353. //背景两侧流光控制器
  354. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  355. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  356. new HdsSceneController()
  357. .setSceneParams({
  358. backgroundMaskColors: [Color.Green, Color.Red],
  359. firstEdgeFlowLight: {
  360. startPos: 0,
  361. endPos: 0.5,
  362. color: Color.Red
  363. },
  364. secondEdgeFlowLight: {
  365. startPos: 0,
  366. endPos: -0.5,
  367. color: Color.Green
  368. }
  369. }) : undefined;
  370. //背景流光控制器
  371. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  372. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  373. new hdsEffect.ShaderEffectController():undefined;
  374. @State showAddSheet:boolean = false
  375. private loadingDialogId: string = ''
  376. private loadingProgressDialogId: string = ''
  377. searchController: SearchController = new SearchController()
  378. @State rightTopImage:Resource = $r('sys.symbol.sort')
  379. @State isEditAudio:boolean = false
  380. @State isExtractAcc:boolean = false
  381. @State isConverter:boolean = false
  382. @State isAIVoiceSeparation:boolean = false
  383. @State isExtractAudio:boolean = false
  384. @State isMergeAudio:boolean = false
  385. @State isCopyFileToDownLoad: boolean = false
  386. @State isChangeTone:boolean = false
  387. @State offHeight: number = 75
  388. @State currentSongList: Array<VideoItem> = []//当前歌单
  389. @Consume currentSongListName:string //当前歌单名称
  390. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  391. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  392. @State isRefreshing: boolean = false;
  393. @State maxRefreshingHeight: number = 100.0;
  394. @State isPlayerLoading: boolean = false; // 播放器加载状态
  395. private contentNode?: ComponentContent<Object> = undefined;
  396. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  397. @State ratioL: number = 1;
  398. @State mediaKuCount: number = 0;
  399. @State albumCount: number = 0;
  400. @State artistCount: number = 0;
  401. @State fastForwardSeconds: string = '10'
  402. @State isShowBackFast: boolean = true//快进快退按钮
  403. @State isCanAuto:boolean = true
  404. @State opacityValueImage: number = 1;
  405. @State tipPopup:boolean = false
  406. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  407. @Consume mType: number;
  408. @StorageProp('themeColor') themeColor: string =
  409. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  410. themeMode: number = 0;
  411. @State titleName: string = '首页'
  412. @State textStr: string = ''
  413. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  414. // private download_path: string = '';
  415. @Consume rootPath: string //音频根目录
  416. @Consume currentPath: string
  417. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  418. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  419. @State lockPath: string = ''
  420. @State favPath: string = ''
  421. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  422. @State historyPath: string = ''
  423. @State historyList: Array<VideoItem> = []
  424. @Consume isHistory: boolean
  425. static readonly HISTORY_MUSIC: string = 'music_historyList';
  426. private table: MediaTable = new MediaTable(getContext(this))
  427. private playlistTable: PlaylistTable | null = null
  428. private deletionWatcher: FileDeletionWatcher | null = null
  429. @State allPlaylists: Playlist[] = []
  430. @State isZero: boolean = false
  431. @State fileList: Array<string> = []
  432. @State dirList: Array<VideoItem> = []
  433. @Consume videoLocalList:VideoItem[]
  434. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  435. @State listRefreshKey: number = 0
  436. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  437. @State artistList: Array<VideoItem> = []; //艺术家文件
  438. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  439. @State artistSongCountMap: Map<string, number> = new Map();
  440. @State albumList: Array<VideoItem> = []; //专辑文件
  441. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  442. @State albumSongCountMap: Map<string, number> = new Map();
  443. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  444. @State imageOpacities: number[] = [];
  445. @Consume isCanBack: boolean
  446. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  447. @State showSingleLyric: boolean = false
  448. @State sortType: number = 4 //默认排序方式
  449. @State isShowSimi: boolean = false //是否显示私密音频
  450. @State isShowFAV: boolean = true //是否显示我的收藏
  451. @State isShowTitleBar: boolean = true //是否显示分类导航条
  452. @State isShowAllBar: boolean = true //是否显示播放全部条
  453. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  454. @State isShowHistory: boolean = true //是否显示最近播放
  455. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  456. @State isGridMusic: boolean = false //是否网格布局
  457. @State isCircleBtn: boolean = false //是否圆形播放按钮
  458. @State twoFingerType: number = 3 //双支放大缩小的类型
  459. @State isScrollHide: boolean = false //是否滚动隐藏
  460. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  461. @State isStartAutoPlay: boolean = false //启动后自动播放
  462. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  463. @State isShowHeader: boolean = true
  464. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  465. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  466. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  467. @State isSwipe: boolean = false //listItem的左滑开关
  468. @State openSkipSongAnimate: boolean = true//切歌动画效果
  469. @State customizeBgPath: string | undefined = '';
  470. @State isDarkMode: boolean = false
  471. @State lyricTextWeight: number = 400
  472. @State lyricTextWeightPip: number = 400
  473. @State currentSwiperIndex: number = 0
  474. @State blurValue: number = 0 //背景模糊
  475. @State bgBrightness: number = 0 //背景亮度
  476. private listScroller: ListScroller = new ListScroller()
  477. private playListScroller: Scroller = new Scroller()
  478. @State isOneKeyTags:boolean = false
  479. @State isFixMessy:boolean = false
  480. // 分页相关状态
  481. @State private currentPage: number = 0 // 当前页码
  482. @State private pageSize: number = 53 // 每页数量
  483. @State private totalCount: number = 0 // 总记录数
  484. @State private hasMoreData: boolean = true // 是否还有更多数据
  485. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  486. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  487. private pageHasMoreCache: Map<number, boolean> = new Map()
  488. private pageTotalCountCache: Map<number, number> = new Map()
  489. private prefetchingPages: Set<number> = new Set()
  490. private preloadStartRatio: number = 0.18
  491. private appendStartRatio: number = 0.30
  492. private earlyAppendReserveCount: number = 28
  493. private lastScrollTriggerPage: number = -1
  494. private lastVisibleEndIndex: number = -1
  495. private isPagingTransition: boolean = false
  496. private pagingScheduleTimer: number = 0
  497. private listScrollAlphaCheckAt: number = 0
  498. private listScrollPagingCheckAt: number = 0
  499. private listScrollLastAlphaStart: number = -1
  500. private listScrollLastPagingEnd: number = -1
  501. private gridScrollPagingCheckAt: number = 0
  502. private gridScrollLastPagingEnd: number = -1
  503. private waterScrollPagingCheckAt: number = 0
  504. private waterScrollLastPagingEnd: number = -1
  505. private gridWaterScrollIdleTimer: number = 0
  506. private gridWaterLastActiveTs: number = 0
  507. private listUpdateTimer: number = 0
  508. private listUpdateVersion: number = 0
  509. private detailBackTransitioning: boolean = false
  510. private mediaLibraryEnterTs: number = 0
  511. private mediaLibraryWarmupPrefetchTimer: number = 0
  512. private listVisibleStart: number = -1
  513. private listVisibleEnd: number = -1
  514. private listThumbWarmupCheckAt: number = 0
  515. private listThumbWarmupStart: number = -1
  516. private listThumbWarmupEnd: number = -1
  517. private gridThumbWarmupCheckAt: number = 0
  518. private gridThumbWarmupStart: number = -1
  519. private gridThumbWarmupEnd: number = -1
  520. private waterThumbWarmupCheckAt: number = 0
  521. private waterThumbWarmupStart: number = -1
  522. private waterThumbWarmupEnd: number = -1
  523. private gridVisibleStart: number = -1
  524. private gridVisibleEnd: number = -1
  525. private waterVisibleStart: number = -1
  526. private waterVisibleEnd: number = -1
  527. private titleBarToggleMinDelta: number = 12
  528. private titleBarLastCheckTs: number = 0
  529. @State private coverThumbVersion: number = 0
  530. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  531. private coverThumbCacheReady: boolean = false
  532. private pendingCoverThumbRefresh: boolean = false
  533. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  534. private isHydratingPlayList: boolean = false
  535. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  536. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  537. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  538. @StorageProp('windowWidth') windowWidth: number = 0;
  539. @StorageProp('windowHeight') windowHeight: number = 0;
  540. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  541. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  542. private UNKONWN:string = '';
  543. private listArea: Area = {
  544. width: 0,
  545. height: 0,
  546. position: {},
  547. globalPosition: {}
  548. }
  549. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  550. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  551. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  552. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  553. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  554. private activePlaybackMemoryKey: string = '';
  555. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  556. private remoteRestoreSeekToken: number = 0;
  557. // 本次是否需要先seek到记忆点再开始播放
  558. private waitInitialSeekBeforeStart: boolean = false;
  559. // 本次播放记忆点(毫秒)
  560. private pendingMemorySeekPosition: number = 0;
  561. // 记忆播放seek兜底,避免一直转圈
  562. private initialSeekGuardTimer: number = 0;
  563. private readonly initialSeekGuardTimeoutMs: number = 2000;
  564. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  565. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  566. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  567. //瀑布流的列数横竖屏动态切换
  568. onIsLandscapeChange() {
  569. if(this.isLandscape){
  570. this.columns = 4
  571. }else{
  572. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  573. }
  574. }
  575. onColorModeChange() {
  576. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  577. }
  578. //点击某个歌单id发生变化的时候回调
  579. onIDChange(){
  580. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  581. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  582. if(this.modeType==4){
  583. this.titleName = this.currentSongListName
  584. this.rightTopImage = $r('sys.symbol.sort')
  585. //获取缓存
  586. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  587. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  588. if(StrUtil.isNotEmpty(cacheSongs)){
  589. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  590. this.updateListData(this.currentSongList, true)
  591. }
  592. this.doSongListTask()//获取歌单信息
  593. }
  594. }
  595. async doSongListTask() {
  596. // 初始化歌单数据库
  597. const playlistTable = new PlaylistTable(this.context);
  598. // 查询歌单中的所有歌曲
  599. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  600. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  601. if (ArrayUtil.isEmpty(playlistSongs)) {
  602. this.updateListData([], true)
  603. // 清空歌单路径列表
  604. this.currentPlaylistSongFilePaths = [];
  605. } else {
  606. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  607. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  608. this.updateListData(this.currentSongList, true)
  609. // 保存歌单的歌曲路径列表,用于随机播放
  610. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  611. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  612. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  613. // 只保存前100条记录到缓存中
  614. let canceList = this.currentSongList.slice(0, 100);
  615. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  616. JSON.stringify(canceList))
  617. } else {
  618. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  619. }
  620. }
  621. this.isRefreshing = false
  622. }
  623. async onModeChange(preserveList: boolean = false): Promise<void> {
  624. this.isFavMusic = false
  625. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  626. this.refreshDirVisibilitySettings()
  627. if (this.mediaLibraryWarmupPrefetchTimer) {
  628. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  629. this.mediaLibraryWarmupPrefetchTimer = 0
  630. }
  631. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  632. switch (this.modeType) {
  633. case 0:
  634. // 首页模式已在 resetAndLoadFirstPage 中处理
  635. // 切换模式时加载对应的排序类型
  636. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  637. this.sortType = this.loadSortTypeForCurrentMode()
  638. this.mediaLibraryEnterTs = 0
  639. break
  640. case 1:
  641. this.rightTopImage = $r('sys.symbol.sort')
  642. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  643. // 切换模式时加载对应的排序类型
  644. this.sortType = this.loadSortTypeForCurrentMode()
  645. this.mediaLibraryEnterTs = Date.now()
  646. break
  647. case 2:
  648. this.rightTopImage = $r('sys.symbol.sort')
  649. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  650. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  651. this.sortType = this.loadSortTypeForCurrentMode()
  652. this.mediaLibraryEnterTs = 0
  653. break
  654. case 3:
  655. this.rightTopImage = $r('sys.symbol.sort')
  656. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  657. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  658. this.sortType = this.loadSortTypeForCurrentMode()
  659. this.mediaLibraryEnterTs = 0
  660. break
  661. }
  662. // 模式切换时重置分页状态并加载第一页
  663. await this.resetAndLoadFirstPage(!preserveList);
  664. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  665. }
  666. // @Consume currentSong: VideoItem | undefined;
  667. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  668. // @StorageLink('isPlay') isPlay: boolean = false;
  669. @Consume isShowPlay: boolean ;
  670. @StorageLink('songList') songList: Array<VideoItem> = [];
  671. @State translateY: number = 0;
  672. @State isShowSheet: boolean = false;
  673. @State isShowSheetView: boolean = false;
  674. @State isShowLyricCopySheet: boolean = false;
  675. @State lyricCopyLines: string[] = [];
  676. @State lyricSelectedIndexes: number[] = [];
  677. @State isShowTimeCloseView: boolean = false;
  678. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  679. @StorageLink('currIndex') curIndex: number = 0;
  680. @Consume isShowDrawer: boolean;
  681. @Consume offsetX: number;
  682. @State isFac: boolean = false;
  683. @State favList: Array<VideoItem> = []
  684. @Consume isFavMusic: boolean
  685. @State isClickedPLayAll: boolean = false;
  686. private scrollerForlist: ListScroller = new ListScroller();
  687. private knockController: KnockController | undefined = undefined;
  688. // 修改为:
  689. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  690. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  691. // 缓存机制
  692. private cache: Map<string, Array<VideoItem>> = new Map();
  693. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  694. // 持久化缓存
  695. private async saveCacheToStorage() {
  696. const cacheArray = Array.from(this.cache.entries());
  697. const stringCacheArray = Array.from(this.stringCache.entries());
  698. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  699. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  700. }
  701. // 载入缓存
  702. private async loadCacheFromStorage() {
  703. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  704. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  705. if (cacheString) {
  706. const parsedCache: Object | null = JSON.parse(cacheString);
  707. if (parsedCache && Array.isArray(parsedCache)) {
  708. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  709. this.cache = new Map(cacheArray);
  710. }
  711. }
  712. if (stringCacheString) {
  713. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  714. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  715. const stringCacheArray: [string, string][] = parsedStringCache;
  716. this.stringCache = new Map(stringCacheArray);
  717. }
  718. }
  719. }
  720. // 查找缓存
  721. private findCache(key: string): Array<VideoItem> | undefined {
  722. return this.cache.get(key);
  723. }
  724. // 查找字符串缓存
  725. private findStringCache(key: string): string | undefined {
  726. return this.stringCache.get(key);
  727. }
  728. // 添加缓存
  729. private addCache(key: string, value: Array<VideoItem>) {
  730. this.cache.set(key, value);
  731. }
  732. // 添加字符串缓存
  733. private addStringCache(key: string, value: string) {
  734. this.stringCache.set(key, value);
  735. }
  736. // 删除缓存
  737. private deleteCache(key: string) {
  738. this.cache.delete(key);
  739. this.saveCacheToStorage()
  740. }
  741. // 删除字符串缓存
  742. private deleteStringCache(key: string) {
  743. this.stringCache.delete(key);
  744. }
  745. // 多选机制
  746. @State selectedFiles: Array<VideoItem> = [];
  747. @Consume isMultiSelect: boolean;
  748. @State isAllSelected: boolean = false;
  749. @State appName: string = ''
  750. @State isHasDir: boolean = false
  751. @State packName: string = ''
  752. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  753. doSwipBack() {
  754. if(this.isSearchMode){
  755. console.info('onecold doSwipBack = ' +this.isSearchMode)
  756. this.isSearchMode = false
  757. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  758. this.searchText = ''
  759. this.getSortedFiles(this.currentPath)
  760. return
  761. }
  762. this.onSearchInput('')
  763. return
  764. }
  765. this.isZero = false
  766. if (this.modeType !== 0 && this.isCanBack) {
  767. if (this.detailBackTransitioning) {
  768. return
  769. }
  770. this.detailBackTransitioning = true
  771. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  772. this.isCanBack = false
  773. this.rightTopImage = $r('sys.symbol.sort')
  774. if (this.modeType == 2) {
  775. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  776. if (ArrayUtil.isNotEmpty(this.artistList)) {
  777. this.updateListData(this.artistList, true, true)
  778. }
  779. } else if (this.modeType == 3) {
  780. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  781. if (ArrayUtil.isNotEmpty(this.albumList)) {
  782. this.updateListData(this.albumList, true, true)
  783. }
  784. }
  785. // 返回列表页时保留当前列表,避免先清空导致闪现
  786. void this.onModeChange(true).then(() => {
  787. if (this.modeType == 2) {
  788. if (this.isGridMusic||this.twoFingerType==4) {
  789. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  790. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  791. if(this.twoFingerType==4){
  792. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  793. }else{
  794. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  795. }
  796. } else {
  797. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  798. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  799. }
  800. } else if (this.modeType == 3) {
  801. if (this.isGridMusic||this.twoFingerType==4) {
  802. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  803. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  804. if(this.twoFingerType==4){
  805. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  806. }else{
  807. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  808. }
  809. } else {
  810. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  811. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  812. }
  813. }
  814. this.detailBackTransitioning = false
  815. }).catch((error: Error) => {
  816. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  817. this.detailBackTransitioning = false
  818. })
  819. return
  820. }
  821. this.mediaLibraryEnterTs = 0
  822. if (this.isHistory || this.isFavMusic) {
  823. this.isHistory = false
  824. this.getSortedFiles(this.currentPath)
  825. return
  826. }
  827. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  828. animateTo({ duration: 555 }, () => {
  829. // 动画闭包内控制Image组件的出现和消失
  830. this.isShowDrawer = !this.isShowDrawer
  831. this.offsetX = 0
  832. })
  833. return
  834. }
  835. //返回上一级歌单的滚动位置
  836. setTimeout(() => {
  837. if (this.modeType == 0) {
  838. if (this.isGridMusic||this.twoFingerType==4) {
  839. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  840. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  841. if(this.twoFingerType==4){
  842. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  843. }else{
  844. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  845. }
  846. } else {
  847. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  848. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  849. }
  850. }
  851. }, 100)
  852. this.currentPath = Utility.getParentDirectory(this.currentPath)
  853. Logger.info('this.currentPath2 = ' + this.currentPath)
  854. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  855. }
  856. private triggerSwipeBackWithAnimation(): void {
  857. animateTo({ duration: 555 }, () => {
  858. this.doSwipBack()
  859. })
  860. }
  861. // 组件生命周期
  862. aboutToAppear() {
  863. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  864. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  865. this.updateListData(this.videoLocalList)
  866. }
  867. // 初始化 PlaylistTable
  868. this.playlistTable = new PlaylistTable(getContext(this))
  869. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  870. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  871. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  872. this.tipPopup = !this.tipPopup
  873. PreferencesUtil.putSync('isFirstTiped',false)
  874. }
  875. this.initSetting()
  876. this.syncEqualizerUi();
  877. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  878. Utility.getAppName(getContext(this)).then((appName: string) => {
  879. this.appName = appName
  880. })
  881. this.packName = AppUtil.getBundleName()
  882. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  883. this.loadCacheFromStorage(); // 加载文件夹缓存
  884. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  885. this.initLoadCache()
  886. this.mkDownLoadDir()
  887. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  888. // 监听广播事件(打开其他应用处理)
  889. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  890. this.saveVideoDatas([eventData.data?.message], true)
  891. });
  892. //侧滑广播接收时间
  893. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  894. // 监听广播事件(手势返回处理)
  895. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  896. this.triggerSwipeBackWithAnimation()
  897. });
  898. //ScanFilePage广播接收时间
  899. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  900. // 监听ScanFilePage广播事件(更新数据库)
  901. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  902. this.doUpdateData()
  903. });
  904. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  905. emitter.on(eventEqualizerChanged, () => {
  906. this.syncEqualizerUi();
  907. if (this.mIjkMediaPlayer) {
  908. const equalizerManager = EqualizerManager.getInstance();
  909. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  910. this.markEqualizerApplied();
  911. }
  912. });
  913. // 监听歌单播放请求事件
  914. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  915. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  916. const data = eventData.data as Record<string, Object>
  917. if (!data) {
  918. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  919. return
  920. }
  921. // 检查歌单播放数据结构
  922. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  923. const playlistData: PlaylistEventData = {
  924. playlistId: data.playlistId as string,
  925. playlistName: data.playlistName as string,
  926. songCount: data.songCount as number,
  927. startIndex: data.startIndex as number,
  928. isJump: data.isJump as boolean,
  929. songFilePaths: data.songFilePaths as string[]
  930. }
  931. await this.handlePlaylistPlayRequest(
  932. playlistData.playlistId,
  933. playlistData.playlistName,
  934. playlistData.songFilePaths,
  935. playlistData.startIndex,
  936. playlistData.isJump,
  937. playlistData.songCount
  938. )
  939. return
  940. }
  941. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  942. });
  943. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  944. // 监听广播事件(通用设置配置更新)
  945. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  946. if(this.modeType ==4){
  947. this.doSongListTask()//获取歌单信息
  948. }
  949. });
  950. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  951. // 监听广播事件(通用设置配置更新)
  952. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  953. this.initSetting()
  954. });
  955. // 监听 WebDAV 元数据更新事件
  956. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  957. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  958. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  959. if (!payloads || payloads.length === 0) {
  960. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  961. return;
  962. }
  963. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  964. // 处理每个元数据更新
  965. for (let i = 0; i < payloads.length; i++) {
  966. const payload = payloads[i];
  967. if (!payload || !payload.filePath) {
  968. continue;
  969. }
  970. // 重要:只更新当前正在播放的歌曲
  971. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  972. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  973. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  974. if (payload.name && payload.name.length > 0) {
  975. this.name = payload.name;
  976. if (this.currentSong) {
  977. this.currentSong.name = payload.name;
  978. }
  979. }
  980. if (payload.artist && payload.artist.length > 0) {
  981. this.artist = payload.artist;
  982. if (this.currentSong) {
  983. this.currentSong.artist = payload.artist;
  984. }
  985. }
  986. if (payload.pixelMapPath && payload.pixelMapPath.length > 0) {
  987. this.cover = payload.pixelMapPath;
  988. if (this.currentSong) {
  989. this.currentSong.pixelMapPath = payload.pixelMapPath;
  990. }
  991. Logger.info(TAG, `LocalMusic: 封面已更新: ${payload.pixelMapPath}`);
  992. }
  993. // 同步更新 AppStorage
  994. AppStorage.setOrCreate('currentSong', this.currentSong);
  995. } else {
  996. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  997. }
  998. }
  999. });
  1000. // 监听广播事件(通用设置配置更新)
  1001. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1002. this.doChangeSetting()
  1003. });
  1004. let event: Callback<InterruptEvent> = (event) => {
  1005. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1006. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1007. this.savePlaybackPosition()
  1008. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1009. this.pause();
  1010. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1011. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1012. this.startPlayOrResumePlay();
  1013. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1014. console.info(`heanup onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1015. if(!this.isSameTimePlay){
  1016. this.stop();
  1017. }
  1018. }
  1019. }
  1020. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1021. // 音频设备断连回调处理比如蓝牙耳机断开
  1022. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1023. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1024. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1025. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1026. console.info('heanup onecold 音频设备断开连接, 暂停播放')
  1027. this.pause();
  1028. }
  1029. }
  1030. // 订阅音频设备断开和连接事件
  1031. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1032. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1033. // 监听广播事件(hicar断开暂停播放)
  1034. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1035. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1036. this.pause();
  1037. });
  1038. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1039. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1040. // 监听蓝牙音响断开音频设备状态变化。
  1041. audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1042. console.info(`onecold device change type : ${deviceChanged.type}`); // 设备连接状态变化,0为连接,1为断开连接。
  1043. console.info(`onecold device descriptor size : ${deviceChanged.deviceDescriptors.length}`);
  1044. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole}`); // 设备角色。
  1045. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType}`);
  1046. // 蓝牙设备类型为8
  1047. const isBluetooth = deviceChanged.deviceDescriptors[0].deviceType === 8;
  1048. if (isBluetooth) {
  1049. if (deviceChanged.type === 0) {
  1050. // 蓝牙连接
  1051. this.isBluetoothConnected = true;
  1052. console.info('onecold 蓝牙设备已连接');
  1053. } else if (deviceChanged.type === 1) {
  1054. // 蓝牙断开
  1055. this.isBluetoothConnected = false;
  1056. this.lastBluetoothLyricLine = '';
  1057. console.info('onecold 蓝牙设备已断开');
  1058. // 恢复原始元数据
  1059. if (this.currentSong) {
  1060. this.avSessionController.restoreOriginalMetadata(
  1061. this.currentSong.name || '',
  1062. this.currentSong.artist || ''
  1063. );
  1064. }
  1065. // 蓝牙断开暂停
  1066. if (this.bluetoothDisconnectPause && deviceChanged.deviceDescriptors[0].deviceRole === 2) {
  1067. console.info('heanup onecold 蓝牙音响断开, 暂停播放');
  1068. this.pause();
  1069. }
  1070. }
  1071. }
  1072. });
  1073. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1074. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1075. console.info('onecold device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1076. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1077. if(deviceChanged.type==1&&
  1078. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1079. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1080. console.info('heanup onecold 有线耳机断开, 暂停播放')
  1081. this.pause();
  1082. }
  1083. });
  1084. this.makeWorker()
  1085. //折叠屏的屏幕显示模式变化
  1086. display.on('foldDisplayModeChange', (data) => {
  1087. this.doChangeBarHeight()
  1088. });
  1089. display.on('foldStatusChange', (data) => {
  1090. Logger.info('onecold foldStatusChange ')
  1091. });
  1092. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1093. // 读取 themeMode 并同步 currentColorMode
  1094. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1095. this.applyThemeMode(this.themeMode)
  1096. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1097. AppStorage.setOrCreate('themeColor', themeColor);
  1098. this.themeColor = themeColor;
  1099. this.doChangeSetting()
  1100. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1101. LogUtil.info('onecold windowSizeChange')
  1102. this.doChangeBarHeight()
  1103. let viewWidth = px2vp(size.width);
  1104. let viewHeight = px2vp(size.height);
  1105. if(this.isPhoneLan()){
  1106. this.is_auto_hide_progress = false
  1107. if(this.isHiCar()){
  1108. return
  1109. }
  1110. setTimeout(() => {
  1111. this.is_auto_hide_progress = true
  1112. }, 6000)
  1113. }else{
  1114. this.startAutoHide()
  1115. }
  1116. });
  1117. this.eventHub.on('onStateChange', (fg: boolean) => {
  1118. if (fg && this.curState === 'STARTED') {
  1119. this.stopPip();
  1120. }
  1121. });
  1122. //NewIndex的博空调收到eventHub消息控制播放
  1123. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1124. if (ArrayUtil.isNotEmpty(this.songList)) {
  1125. this.playOrPause();
  1126. } else {
  1127. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1128. }
  1129. });
  1130. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1131. if (ArrayUtil.isNotEmpty(this.songList)) {
  1132. this.playPrevious();
  1133. } else {
  1134. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1135. }
  1136. });
  1137. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1138. if (ArrayUtil.isNotEmpty(this.songList)) {
  1139. this.playNext();
  1140. } else {
  1141. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1142. }
  1143. });
  1144. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1145. this.showPlayerView();
  1146. });
  1147. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1148. this.openPlayList();
  1149. });
  1150. }
  1151. //载入媒体库,艺术家,专辑等缓存
  1152. initLoadCache(){
  1153. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1154. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1155. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1156. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1157. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1158. if(ArrayUtil.isNotEmpty(cachedList)){
  1159. this.mediaKuList = cachedList
  1160. if(this.modeType==1){
  1161. this.updateListData(this.mediaKuList)
  1162. }
  1163. }
  1164. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1165. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1166. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1167. this.artistList = artistCachedList
  1168. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1169. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1170. this.artistMap = new Map(parsedArray);
  1171. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1172. if(this.modeType==2){
  1173. this.updateListData(this.artistList)
  1174. }
  1175. }
  1176. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1177. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1178. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1179. this.albumList = albumCachedList
  1180. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1181. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1182. this.albumMap = new Map(parsedArray);
  1183. if(this.modeType==3){
  1184. this.updateListData(this.albumList)
  1185. }
  1186. }
  1187. }
  1188. startAutoHide() {
  1189. if(this.isHiCar()){
  1190. return
  1191. }
  1192. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1193. console.info('onecold startAutoHide')
  1194. this.is_auto_hide_progress = false
  1195. setTimeout(() => {
  1196. this.is_auto_hide_progress = true
  1197. }, 6000)
  1198. }
  1199. }
  1200. applyThemeMode(mode: number) {
  1201. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1202. if (mode === 1) {
  1203. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1204. } else if (mode === 2) {
  1205. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1206. }
  1207. AppStorage.setOrCreate('currentColorMode', colorMode)
  1208. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1209. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1210. AppStorage.setOrCreate('themeMode', mode)
  1211. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1212. // 只有强制浅色/深色时才主动设置
  1213. const context = getContext(this) as common.UIAbilityContext
  1214. context.getApplicationContext().setColorMode(colorMode)
  1215. }
  1216. initSetting() {
  1217. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1218. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1219. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1220. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1221. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1222. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1223. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1224. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1225. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1226. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1227. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1228. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1229. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1230. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1231. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1232. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1233. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1234. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1235. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1236. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1237. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1238. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1239. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1240. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1241. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1242. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1243. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1244. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1245. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1246. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1247. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1248. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1249. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1250. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1251. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1252. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1253. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1254. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1255. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1256. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1257. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1258. this.refreshDirVisibilitySettings()
  1259. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1260. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1261. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1262. let audioManager = audio.getAudioManager();
  1263. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1264. if(this.isSameTimePlay){
  1265. //与其他应用同时播放,关键代码
  1266. let strategy: audio.AudioSessionStrategy = {
  1267. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1268. };
  1269. audioSessionManager.activateAudioSession(strategy).then(() => {
  1270. console.info('onecold Succeeded in doing activateAudioSession.');
  1271. }).catch((err: BusinessError) => {
  1272. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1273. });
  1274. }else{
  1275. let isActivated = audioSessionManager.isAudioSessionActivated();
  1276. if(isActivated){
  1277. audioSessionManager.deactivateAudioSession().then(() => {
  1278. console.info('Succeeded in doing deactivateAudioSession.');
  1279. }).catch((err: BusinessError) => {
  1280. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1281. });
  1282. }
  1283. }
  1284. //如果是hicar连接状态,这些都是false
  1285. if(this.isHiCar()){
  1286. this.autoHideTitle = false
  1287. this.isCoverRectangle= true
  1288. this.columns=4
  1289. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1290. {
  1291. this.isGridMusic= false//用list不用网格
  1292. this.isCoverTopBig = false
  1293. }
  1294. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1295. }
  1296. if (this.isSavePlayMode) {
  1297. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1298. }
  1299. }
  1300. doChangeSetting() {
  1301. this.initSetting()
  1302. this.deleteCache(this.currentPath)
  1303. if (this.modeType === 0) {
  1304. this.getSortedFiles(this.currentPath)
  1305. }
  1306. }
  1307. doChangeBarHeight() {
  1308. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1309. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1310. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1311. this.setBarHeightNormal()
  1312. }
  1313. }
  1314. onPageShow() {
  1315. this.knockController?.immersiveListening();
  1316. app.setImageCacheCount(100);
  1317. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1318. app.setImageRawDataCacheSize(104857600);
  1319. this.refreshDirVisibilitySettings();
  1320. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1321. }
  1322. //开启线程查看各个数据库
  1323. makeWorker() {
  1324. setTimeout(() => {
  1325. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1326. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1327. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1328. // workerInstance.postMessage({
  1329. // code: 1,
  1330. // data1: this.context,
  1331. // data2: this.rootPath,
  1332. // data3: this.lockPath,
  1333. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1334. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1335. // });
  1336. PreferencesUtil.putSync('isFirstApp', false)
  1337. } else {
  1338. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1339. workerInstance.postMessage({ code: 3, data: this.context });
  1340. workerInstance.postMessage({ code: 4, data: this.context });
  1341. this.getHistoryList(false)
  1342. }
  1343. }, 1000)
  1344. workerInstance.onmessage = (e: MessageEvents): void => {
  1345. const message = e.data as LocalMusicWorkerMessage;
  1346. switch (message.code) {
  1347. case 101: //第一次扫描文件夹入库
  1348. ToastUtil.showToast('刷新同步数据库成功!')
  1349. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1350. this.doAllUpdateData()
  1351. break;
  1352. case 102: //查询媒体库列表
  1353. this.isRefreshing = false
  1354. this.mediaKuList = message.data // 只包含前100条
  1355. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1356. this.mediaKuCount = mediaTotalCount;
  1357. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1358. Utility.doSortListAscending(this.mediaKuList)
  1359. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1360. // 媒体库模式下重新加载第一页(分页查询)
  1361. if (this.modeType === 1) {
  1362. this.resetAndLoadFirstPage();
  1363. }
  1364. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1365. // 只保存前100条记录到缓存中
  1366. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1367. break;
  1368. case 103: //收到查询艺术家列表
  1369. this.isRefreshing = false
  1370. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1371. this.artistList = message.data2; // 只包含前100个艺术家
  1372. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1373. this.artistCount = artistTotalCount;
  1374. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1375. this.artistMap.forEach((songs, artist) => {
  1376. nextArtistCountMap.set(artist, songs.length);
  1377. });
  1378. this.artistSongCountMap = nextArtistCountMap;
  1379. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1380. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1381. // 艺术家模式下重新加载第一页(分页查询)
  1382. if (this.modeType === 2) {
  1383. this.resetAndLoadFirstPage();
  1384. }
  1385. // 保存前100条艺术家列表
  1386. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1387. // 保存前60条艺术家的歌曲Map
  1388. const sortedEntries = Array.from(this.artistMap.entries());
  1389. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1390. break;
  1391. case 104: //收到查询专辑列表
  1392. this.isRefreshing = false
  1393. this.albumMap = message.data1;
  1394. this.albumList = message.data2
  1395. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1396. this.albumCount = albumTotalCount;
  1397. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1398. this.albumMap.forEach((songs, album) => {
  1399. nextAlbumCountMap.set(album, songs.length);
  1400. });
  1401. this.albumSongCountMap = nextAlbumCountMap;
  1402. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1403. // 专辑模式下重新加载第一页(分页查询)
  1404. if (this.modeType === 3) {
  1405. this.resetAndLoadFirstPage();
  1406. }
  1407. //查询完毕在启动是否自动播放
  1408. if (this.isStartAutoPlay&&this.isCanAuto) {
  1409. this.isCanAuto = false
  1410. console.info('onecold startPlayOrResumePlay 757')
  1411. this.startPlayOrResumePlay()
  1412. }
  1413. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1414. // 保存前100条专辑列表(Worker已经只发送了100条)
  1415. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1416. // 保存前60条专辑Map(Worker已经只发送了60条)
  1417. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1418. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1419. break;
  1420. case 105: // 缓存完成后返回的元数据
  1421. this.handleWorkerMetadataPayload(message.data);
  1422. break;
  1423. case 106: // 编辑音乐元数据和封面完成
  1424. this.handleEditMusicResult(message.data);
  1425. break;
  1426. }
  1427. };
  1428. // 在调用terminate后,执行onexit
  1429. workerInstance.onexit = (code) => {
  1430. metadataExtractionInFlight.clear();
  1431. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1432. }
  1433. workerInstance.onerror = (err: ErrorEvent) => {
  1434. metadataExtractionInFlight.clear();
  1435. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1436. }
  1437. }
  1438. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1439. if (!payload || !payload.originFilePath) {
  1440. return;
  1441. }
  1442. metadataExtractionInFlight.delete(payload.originFilePath);
  1443. if (payload.error) {
  1444. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1445. return;
  1446. }
  1447. this.applyMetadataToCollections(payload.originFilePath, payload);
  1448. }
  1449. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1450. const targets: Array<VideoItem> = [];
  1451. let mainListUpdated = false;
  1452. let playlistUpdated = false;
  1453. if (this.currentSong && this.currentSong.filePath === filePath) {
  1454. targets.push(this.currentSong);
  1455. }
  1456. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1457. if (!list || list.length === 0) {
  1458. return;
  1459. }
  1460. const found = Utility.getItemByFilePath(list, filePath);
  1461. if (found) {
  1462. markUpdated?.();
  1463. targets.push(found);
  1464. }
  1465. };
  1466. collectFromList(this.videoLocalList, () => {
  1467. mainListUpdated = true;
  1468. });
  1469. collectFromList(this.songList, () => {
  1470. playlistUpdated = true;
  1471. });
  1472. collectFromList(this.historyList);
  1473. collectFromList(this.favList);
  1474. const remoteManager = RemoteDriveManager.getInstance();
  1475. collectFromList(remoteManager.webDavSongs);
  1476. const updated = new Set<VideoItem>();
  1477. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1478. for (let i = 0; i < targets.length; i++) {
  1479. const target = targets[i];
  1480. if (!target || updated.has(target)) {
  1481. continue;
  1482. }
  1483. updated.add(target);
  1484. this.mergeVideoItemWithPayload(target, payload);
  1485. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1486. remoteMetadataUpdates.set(target.filePath, {
  1487. filePath: target.filePath,
  1488. pixelMapPath: target.pixelMapPath,
  1489. name: target.name,
  1490. artist: target.artist
  1491. });
  1492. }
  1493. }
  1494. if (this.currentSong && this.currentSong.filePath === filePath) {
  1495. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1496. if (payload.name) {
  1497. this.name = payload.name;
  1498. }
  1499. if (payload.artist) {
  1500. this.artist = payload.artist;
  1501. }
  1502. if (payload.pixelMapPath) {
  1503. this.cover = payload.pixelMapPath;
  1504. }
  1505. if (payload.lyricContent) {
  1506. this.applyInlineLyricContent(payload.lyricContent);
  1507. }
  1508. let avSessionDurationMs: number = this.duration;
  1509. if (payload.duration) {
  1510. const durationSeconds = Number(payload.duration);
  1511. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1512. avSessionDurationMs = durationSeconds * 1000;
  1513. this.duration = avSessionDurationMs;
  1514. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1515. this.durationStringTime = secondToTime(this.durationTime);
  1516. }
  1517. }
  1518. if (avSessionDurationMs > 0) {
  1519. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1520. }
  1521. this.currentSong = cloneVideoItem(this.currentSong);
  1522. AppStorage.setOrCreate('currentSong', this.currentSong);
  1523. }
  1524. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1525. if (primaryTarget) {
  1526. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1527. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1528. });
  1529. }
  1530. if (remoteMetadataUpdates.size > 0) {
  1531. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1532. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1533. }
  1534. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1535. }
  1536. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1537. // 关闭进度条
  1538. DialogHelper.closeDialog(this.loadingDialogId)
  1539. if (result.success) {
  1540. console.log("heanup 编辑信息成功,数据库已同步");
  1541. if (result.coverResult) {
  1542. ToastUtil.showToast('内嵌封面成功');
  1543. }
  1544. ToastUtil.showToast('内嵌音乐标签成功');
  1545. this.isShowMoreView = false;
  1546. this.name = this.titleStr;
  1547. // 同步当前播放的歌曲信息
  1548. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1549. this.currentSong.name = this.titleStr;
  1550. this.artist = this.artistStr;
  1551. this.currentSong.artist = this.artistStr;
  1552. this.currentSong.album = this.ablumStr;
  1553. this.currentSong.year = this.yearStr;
  1554. this.currentSong.genre = this.genreStr;
  1555. this.currentSong.track = this.trackStr;
  1556. this.currentSong.lyricContent = this.lyricConStr;
  1557. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1558. this.currentSong.COMPOSER = this.composerStr;
  1559. this.currentSong.LYRICIST = this.lyricistStr;
  1560. this.currentSong.COMMENT = this.commentStr;
  1561. }
  1562. // if (result.needRefreshList && this.modeType == 0) {
  1563. // this.deleteCache(this.currentPath);
  1564. // this.getSortedFiles(this.currentPath);
  1565. // }
  1566. // 同步编辑字段到本地列表
  1567. if (this.editingItem) {
  1568. this.syncEditedFields(this.editingItem);
  1569. this.syncListsAfterEdit(this.editingItem.filePath);
  1570. this.doUpateEditedFields(this.editingItem);
  1571. }
  1572. // 清理临时变量
  1573. this.longItemFilePath = '';
  1574. this.tempLyricContent = '';
  1575. this.isShowEdit = false;
  1576. this.imagePathStr = '';
  1577. } else {
  1578. console.error("heanup 编辑信息失败: " + result.error);
  1579. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1580. // 清理临时变量
  1581. this.longItemFilePath = '';
  1582. this.tempLyricContent = '';
  1583. this.isShowEdit = false;
  1584. this.imagePathStr = '';
  1585. }
  1586. }
  1587. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1588. if (value === undefined || value === null) {
  1589. return;
  1590. }
  1591. const text = value.toString();
  1592. if (!allowEmpty && text.trim().length === 0) {
  1593. return;
  1594. }
  1595. Reflect.set(target, key as string, value);
  1596. }
  1597. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1598. if (value === undefined || value === null || Number.isNaN(value)) {
  1599. return;
  1600. }
  1601. Reflect.set(target, key as string, value);
  1602. }
  1603. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1604. if (!target || !payload) {
  1605. return;
  1606. }
  1607. this.assignStringMetadata(target, 'name', payload.name);
  1608. this.assignStringMetadata(target, 'artist', payload.artist);
  1609. this.assignStringMetadata(target, 'album', payload.album);
  1610. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1611. this.assignStringMetadata(target, 'duration', payload.duration);
  1612. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1613. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1614. this.assignStringMetadata(target, 'size', payload.size);
  1615. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1616. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1617. this.assignStringMetadata(target, 'genre', payload.genre);
  1618. this.assignStringMetadata(target, 'track', payload.track);
  1619. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1620. this.assignStringMetadata(target, 'channels', payload.channels);
  1621. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1622. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1623. this.assignStringMetadata(target, 'year', payload.year);
  1624. this.assignStringMetadata(target, 'disc', payload.disc);
  1625. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1626. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1627. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1628. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1629. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1630. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1631. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1632. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1633. }
  1634. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1635. if (!target || !source) {
  1636. return;
  1637. }
  1638. this.assignStringMetadata(target, 'name', source.name);
  1639. this.assignStringMetadata(target, 'artist', source.artist);
  1640. this.assignStringMetadata(target, 'album', source.album);
  1641. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1642. this.assignStringMetadata(target, 'duration', source.duration);
  1643. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1644. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1645. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1646. this.assignStringMetadata(target, 'size', source.size);
  1647. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1648. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1649. this.assignStringMetadata(target, 'genre', source.genre);
  1650. this.assignStringMetadata(target, 'track', source.track);
  1651. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1652. this.assignStringMetadata(target, 'channels', source.channels);
  1653. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1654. this.assignStringMetadata(target, 'start_time', source.start_time);
  1655. this.assignStringMetadata(target, 'year', source.year);
  1656. this.assignStringMetadata(target, 'disc', source.disc);
  1657. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1658. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1659. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1660. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1661. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1662. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1663. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1664. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1665. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1666. target.remote_rel_path = source.remote_rel_path;
  1667. }
  1668. }
  1669. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1670. if (!item || !isRemoteCloudType(item.type)) {
  1671. return;
  1672. }
  1673. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1674. if (!storagePath) {
  1675. return;
  1676. }
  1677. try {
  1678. const cached = await this.table.queryVideoByFilePath(storagePath);
  1679. if (!cached) {
  1680. return;
  1681. }
  1682. this.mergeVideoItemFromSource(item, cached);
  1683. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1684. item.remote_rel_path = storagePath;
  1685. }
  1686. if (item === this.currentSong) {
  1687. if (StrUtil.isNotEmpty(item.name)) {
  1688. this.name = item.name;
  1689. }
  1690. if (StrUtil.isNotEmpty(item.artist)) {
  1691. this.artist = item.artist!;
  1692. }
  1693. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1694. this.cover = item.pixelMapPath!;
  1695. }
  1696. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1697. this.applyInlineLyricContent(item.lyricContent as string);
  1698. }
  1699. }
  1700. } catch (error) {
  1701. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1702. }
  1703. }
  1704. private applyInlineLyricContent(content: string): void {
  1705. if (StrUtil.isEmpty(content)) {
  1706. return;
  1707. }
  1708. this.lyricContent = content;
  1709. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1710. const lyric: Lyric = this.parser.parse(lines);
  1711. this.lyricController.setLyric(lyric);
  1712. this.lyricControllerXF.setLyric(lyric);
  1713. this.lyricControllerSingle.setLyric(lyric);
  1714. }
  1715. private extractParentPathFromStoragePath(path: string): string {
  1716. if (!path) {
  1717. return '';
  1718. }
  1719. const lastSlash = path.lastIndexOf('/');
  1720. if (lastSlash <= 0) {
  1721. return '';
  1722. }
  1723. return path.substring(0, lastSlash);
  1724. }
  1725. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1726. if (!target || !isRemoteCloudType(target.type)) {
  1727. return null;
  1728. }
  1729. if (isWebDavType(target.type)) {
  1730. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1731. if (storagePath) {
  1732. target.remote_rel_path = storagePath;
  1733. return storagePath;
  1734. }
  1735. return null;
  1736. }
  1737. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1738. return target.remote_rel_path;
  1739. }
  1740. return null;
  1741. }
  1742. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1743. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1744. return;
  1745. }
  1746. const storagePath = this.resolveRemoteStoragePath(target);
  1747. if (!storagePath) {
  1748. return;
  1749. }
  1750. const table = new MediaTable(this.context);
  1751. await new Promise<void>((resolve) => {
  1752. table.getRdbStore(this.context as Context, () => resolve());
  1753. });
  1754. const cloneItem = cloneVideoItem(target);
  1755. cloneItem.filePath = storagePath;
  1756. cloneItem.remote_rel_path = storagePath;
  1757. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1758. await table.saveOrUpdateWebDavItem(cloneItem);
  1759. }
  1760. onPageHide() {
  1761. this.knockController?.immersiveDisableListening();
  1762. }
  1763. @State isFirstStartPlay: boolean = false
  1764. private async startFileDeletionWatcher(): Promise<void> {
  1765. if (!this.rootPath) {
  1766. return;
  1767. }
  1768. if (!this.deletionWatcher) {
  1769. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1770. }
  1771. try {
  1772. await this.deletionWatcher.watchDirectories([
  1773. this.rootPath,
  1774. this.lockPath,
  1775. this.favPath,
  1776. this.historyPath
  1777. ]);
  1778. } catch (error) {
  1779. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1780. }
  1781. }
  1782. //获取download_path
  1783. async mkDownLoadDir() {
  1784. const documentViewPicker = new picker.DocumentViewPicker()
  1785. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1786. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1787. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1788. this.currentPath = this.rootPath
  1789. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1790. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1791. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1792. Logger.info('onecold rootPath = ' + this.rootPath)
  1793. if (!FileUtil.accessSync(this.favPath)) {
  1794. FileUtil.mkdirSync(this.favPath)
  1795. }
  1796. if (!FileUtil.accessSync(this.historyPath)) {
  1797. FileUtil.mkdirSync(this.historyPath)
  1798. }
  1799. // await this.startFileDeletionWatcher();
  1800. this.getSortedFiles(this.rootPath).then(async () => {
  1801. this.isFavMusic = false
  1802. //穿山甲
  1803. // this.loadBannerAd(CSJUtil.getBannerID())
  1804. this.restoreLastPlayContext();
  1805. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1806. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1807. if (ArrayUtil.isEmpty(this.songList)) {
  1808. this.songList = this.getCurFileList()
  1809. } else {
  1810. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1811. }
  1812. if (ArrayUtil.isNotEmpty(this.songList)) {
  1813. this.isFirstStartPlay = true
  1814. this.sonDataSource.pushArrayData(this.songList)
  1815. if (this.currentSong === undefined) {
  1816. this.isFirstStartPlay = false
  1817. this.currentSong = this.songList[0]
  1818. }
  1819. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1820. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1821. context: this.context,
  1822. autoParseMusicName: this.autoParseMusicName
  1823. });
  1824. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1825. this.name = this.currentSong.name
  1826. this.cover = this.currentSong.pixelMapPath
  1827. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1828. } else {
  1829. this.name = '空空如也'
  1830. }
  1831. })
  1832. this.getFavList(false)
  1833. }
  1834. getFavList(isFavRefresh: boolean) {
  1835. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1836. this.favList = result
  1837. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1838. this.videoLocalList = this.favList
  1839. this.updateListData(this.videoLocalList, true)
  1840. }
  1841. })
  1842. }
  1843. getHistoryList(isRefresh: boolean) {
  1844. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1845. this.historyList = result
  1846. // for (let i = 0; i < this.historyList.length; i++) {
  1847. //
  1848. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1849. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1850. // }
  1851. if (isRefresh) {
  1852. this.videoLocalList = this.historyList
  1853. this.updateListData(this.videoLocalList, true)
  1854. }
  1855. })
  1856. }
  1857. // 组件消失生命周期
  1858. aboutToDisappear() {
  1859. console.info('LifeCycleComponent aboutToDisappear');
  1860. if (this.alphaBetHideTimer) {
  1861. clearTimeout(this.alphaBetHideTimer);
  1862. this.alphaBetHideTimer = 0;
  1863. }
  1864. if (this.alphaBetRebuildTimer) {
  1865. clearTimeout(this.alphaBetRebuildTimer);
  1866. this.alphaBetRebuildTimer = 0;
  1867. }
  1868. if (this.pagingScheduleTimer) {
  1869. clearTimeout(this.pagingScheduleTimer);
  1870. this.pagingScheduleTimer = 0;
  1871. }
  1872. if (this.gridWaterScrollIdleTimer) {
  1873. clearTimeout(this.gridWaterScrollIdleTimer);
  1874. this.gridWaterScrollIdleTimer = 0;
  1875. }
  1876. if (this.listUpdateTimer) {
  1877. clearTimeout(this.listUpdateTimer);
  1878. this.listUpdateTimer = 0;
  1879. }
  1880. if (this.mediaLibraryWarmupPrefetchTimer) {
  1881. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  1882. this.mediaLibraryWarmupPrefetchTimer = 0;
  1883. }
  1884. this.clearInitialSeekGuardTimer();
  1885. this.alphaBetBuildVersion++;
  1886. this.gridWaterLastActiveTs = 0;
  1887. this.coverThumbCache.dispose();
  1888. this.coverThumbCacheReady = false;
  1889. this.pendingCoverThumbRefresh = false;
  1890. this.deletionWatcher?.stop();
  1891. this.knockController?.immersiveDisableListening();
  1892. this.curIndex = 0
  1893. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1894. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1895. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1896. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1897. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  1898. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  1899. this.mDestroyPage = true;
  1900. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1901. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1902. this.stop();
  1903. }
  1904. this.mIjkMediaPlayer.off('audioInterrupt');
  1905. this.mIjkMediaPlayer.off('deviceChange');
  1906. if (workerInstance) {
  1907. workerInstance.terminate();
  1908. }
  1909. this.stopPip();
  1910. this.destroyPipController()
  1911. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1912. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1913. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  1914. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  1915. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  1916. }
  1917. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  1918. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  1919. this.isFavMusic = false
  1920. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1921. if (isWorkerPost) {
  1922. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1923. }
  1924. if (this.modeType !== 0) {
  1925. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  1926. if (isOpen && destPath) {
  1927. this.openMusic(true, destPath, openItem)
  1928. }
  1929. return
  1930. }
  1931. console.info('onecold getSortedFiles 2')
  1932. this.isCanBack = false
  1933. this.currentPath = curPath
  1934. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1935. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1936. if (curPath === this.rootPath) {
  1937. this.rightTopImage = $r('sys.symbol.sort')
  1938. } else {
  1939. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1940. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1941. this.rightTopImage = $r('sys.symbol.chevron_left')
  1942. }
  1943. }
  1944. // Get the current file list and calculate its hash
  1945. this.fileList = FileUtil.listFileSync(curPath);
  1946. const currentHash = simpleHash(this.fileList);
  1947. // Check cache
  1948. const cachedValue = this.findCache(curPath);
  1949. Logger.info('onecold cachedValue = ' + cachedValue)
  1950. const cachedHash = this.findStringCache(curPath + '_hash');
  1951. const cachedDirList = this.findCache(curPath + "_dirList");
  1952. if (cachedValue !== undefined&&!this.isRefreshing) {
  1953. // this.videoLocalList = cachedValue;
  1954. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1955. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1956. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1957. }
  1958. this.isRefreshing = false
  1959. this.updateListData(cachedValue, undefined, immediateListUpdate)
  1960. if (scrollTopAfterUpdate) {
  1961. this.scrollToTopForCurrentLayout()
  1962. }
  1963. }
  1964. if (cachedDirList !== undefined) {
  1965. this.dirList = cachedDirList
  1966. }
  1967. //通过当前hash值和缓存hash判断list有没有变化
  1968. if (cachedValue && cachedHash === currentHash) {
  1969. return;
  1970. }
  1971. // this.fileList = FileUtil.listFileSync(curPath)
  1972. let directories: Array<VideoItem> = [];
  1973. let files: Array<VideoItem> = [];
  1974. for (let i = 0; i < this.fileList.length; i++) {
  1975. // console.info(`The name of file: ${this.fileList[i]}`);
  1976. let path = curPath + '/' + this.fileList[i]
  1977. if (FileUtil.isDirectory(path)) {
  1978. let item: VideoItem =
  1979. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1980. '')
  1981. if (this.isShowDir(item.name)) {
  1982. directories.push(item);
  1983. }
  1984. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1985. // Utility.doSortListAscending(directories)
  1986. } else {
  1987. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1988. let item: VideoItem =
  1989. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1990. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1991. files.push(item);
  1992. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1993. // this.doSortListAscending(files)
  1994. }
  1995. }
  1996. }
  1997. }
  1998. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1999. if (this.currentPath !== this.lockPath) {
  2000. files = result;
  2001. }
  2002. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2003. Utility.doSortListAscending(files)
  2004. if (this.currentPath === this.rootPath) {
  2005. this.dirList = directories
  2006. this.addCache(curPath + "_dirList", this.dirList);
  2007. }
  2008. //插入广告先注释掉
  2009. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2010. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2011. // directories.push(adItem)
  2012. // }
  2013. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2014. this.videoLocalList = directories.concat(files);
  2015. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2016. if (scrollTopAfterUpdate) {
  2017. this.scrollToTopForCurrentLayout()
  2018. }
  2019. if (ArrayUtil.isNotEmpty(files)) {
  2020. if (this.currentPath != this.rootPath) {
  2021. if (files) {
  2022. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2023. }
  2024. }
  2025. // 缓存结果
  2026. this.addCache(curPath, this.videoLocalList);
  2027. await this.saveCacheToStorage(); // 保存缓存至本地存储
  2028. this.addStringCache(curPath + '_hash', currentHash);
  2029. }
  2030. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2031. for (let i = 0; i < this.videoLocalList.length; i++) {
  2032. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2033. }
  2034. // this.setButtonStatus()
  2035. this.openMusic(isOpen, destPath,openItem)
  2036. this.isRefreshing = false
  2037. });
  2038. }
  2039. //第三方app打开天天静听导入音乐后播放
  2040. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2041. if (isOpen&&destPath) {
  2042. if (destPath === undefined) {
  2043. // 处理 destPath 为 undefined 的情况
  2044. return
  2045. }
  2046. if (destPath.endsWith('.lrc')) {
  2047. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2048. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2049. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2050. this.initLyric(lyricPath);
  2051. }
  2052. return
  2053. }
  2054. if(openItem){
  2055. this.doPlay(openItem,0,false,true)
  2056. // this.isShowPlay = true
  2057. this.setShowPlayTrue()
  2058. }
  2059. }
  2060. }
  2061. //扫描文件夹入库
  2062. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2063. const files = FileUtil.listFileSync(curPath);
  2064. let mediaItems: VideoItem[] = [];
  2065. Logger.info('onecold scanDirectory start ')
  2066. for (const file of files) {
  2067. const fPath = `${curPath}/${file}`;
  2068. if (fPath === this.lockPath) {
  2069. Logger.info(`Skipping locked path: ${fPath}`);
  2070. continue;
  2071. }
  2072. if (FileUtil.isDirectory(fPath)) {
  2073. // Recursively scan subdirectories
  2074. const subDirItems = await this.scanDirectory(fPath);
  2075. mediaItems = mediaItems.concat(subDirItems);
  2076. } else {
  2077. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2078. // Process media files
  2079. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2080. let mediaItem: VideoItem =
  2081. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2082. mediaItems.push(mediaItem);
  2083. this.table.insert(mediaItem, (id: number) => {
  2084. });
  2085. }
  2086. }
  2087. }
  2088. return mediaItems;
  2089. }
  2090. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2091. this.isShowTitleBar = true
  2092. const shouldAnimate = !immediate
  2093. if (this.listUpdateTimer) {
  2094. clearTimeout(this.listUpdateTimer)
  2095. this.listUpdateTimer = 0
  2096. }
  2097. const updateVersion = ++this.listUpdateVersion
  2098. if (shouldAnimate) {
  2099. this.getUIContext().animateTo({ duration: 666 }, () => {
  2100. this.opacityItem = 0.5;
  2101. });
  2102. }
  2103. const applyListData = () => {
  2104. if (updateVersion !== this.listUpdateVersion) {
  2105. return
  2106. }
  2107. this.videoLocalList = mList;
  2108. if (!noSort) {
  2109. if (this.modeType === 0 || this.modeType === 1) {
  2110. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2111. this.doSortType(this.sortType)
  2112. }
  2113. }
  2114. this.dataSource.pushArrayData(this.videoLocalList)
  2115. if (shouldAnimate) {
  2116. this.getUIContext().animateTo({ duration: 666 }, () => {
  2117. this.opacityItem = 1;
  2118. });
  2119. } else {
  2120. this.opacityItem = 1;
  2121. }
  2122. this.setButtonStatus()
  2123. //添加到字母索引表
  2124. this.markAlphaBetDirty()
  2125. };
  2126. if (immediate) {
  2127. applyListData();
  2128. return;
  2129. }
  2130. this.listUpdateTimer = setTimeout(() => {
  2131. this.listUpdateTimer = 0
  2132. applyListData();
  2133. }, 200);
  2134. }
  2135. getCurFileList(): Array<VideoItem> {
  2136. if(this.isSearchMode){
  2137. return this.filteredList
  2138. }
  2139. let files: Array<VideoItem> = [];
  2140. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2141. for (let i = 0; i < this.videoLocalList.length; i++) {
  2142. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  2143. files.push(this.videoLocalList[i]);
  2144. }
  2145. }
  2146. }
  2147. return files
  2148. }
  2149. setButtonStatus() {
  2150. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2151. this.isZero = false
  2152. } else {
  2153. this.isZero = true
  2154. }
  2155. if (this.currentPath !== this.rootPath &&
  2156. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2157. this.isHasDir = true //不为空,说明有子文件夹
  2158. } else {
  2159. this.isHasDir = false
  2160. }
  2161. }
  2162. private getPlayListDisplayCount(): number {
  2163. if (this.playQueueScope === 'history') {
  2164. return this.historyList.length;
  2165. }
  2166. if (this.playQueueScope === 'fav') {
  2167. return this.favList.length;
  2168. }
  2169. if (this.playQueueScope === 'playlist') {
  2170. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2171. // 如果是,优先返回服务端总数
  2172. const navidromeTotalCount = getNavidromeTotalCount();
  2173. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2174. if (navidromeTotalCount > 0 && this.currentSong && (
  2175. isNavidromeType(this.currentSong.type) ||
  2176. isJellyfinType(this.currentSong.type) ||
  2177. isEmbyType(this.currentSong.type) ||
  2178. isAudioStationType(this.currentSong.type) ||
  2179. isPlexType(this.currentSong.type) ||
  2180. isDaoLiYuType(this.currentSong.type)
  2181. )) {
  2182. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2183. return navidromeTotalCount;
  2184. }
  2185. Logger.info('heanup getPlayListDisplayCount', `返回 currentSongList.length: ${this.currentSongList.length}`);
  2186. return this.currentSongList.length;
  2187. }
  2188. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2189. return this.totalCount;
  2190. }
  2191. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2192. return this.songList.length;
  2193. }
  2194. private restoreLastPlayContext(): void {
  2195. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2196. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  2197. this.playQueueScope = scope;
  2198. } else {
  2199. this.playQueueScope = 'view';
  2200. }
  2201. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2202. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2203. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2204. this.totalCount = lastTotalCount;
  2205. }
  2206. }
  2207. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2208. if (this.isHydratingPlayList) {
  2209. return;
  2210. }
  2211. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2212. return;
  2213. }
  2214. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2215. return;
  2216. }
  2217. this.isHydratingPlayList = true;
  2218. try {
  2219. const fullList: VideoItem[] = [];
  2220. let pageIndex = 0;
  2221. let hasMore = true;
  2222. while (hasMore) {
  2223. const result = await this.table.queryMediaLibraryPaged({
  2224. pageIndex,
  2225. pageSize: this.pageSize,
  2226. sortType: this.sortType,
  2227. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2228. isShowFileName: this.isShowFileName
  2229. });
  2230. if (result.items.length === 0) {
  2231. break;
  2232. }
  2233. fullList.push(...result.items);
  2234. hasMore = result.hasMore;
  2235. pageIndex += 1;
  2236. if (fullList.length >= result.totalCount) {
  2237. hasMore = false;
  2238. }
  2239. }
  2240. if (fullList.length > 0) {
  2241. if(isSonList){
  2242. this.songList = fullList;
  2243. this.sonDataSource.pushArrayData(this.songList);
  2244. }else{
  2245. this.videoLocalList = fullList;
  2246. this.dataSource.pushArrayData(this.videoLocalList);
  2247. }
  2248. }
  2249. } finally {
  2250. this.isHydratingPlayList = false;
  2251. }
  2252. }
  2253. @Builder
  2254. SortMenuBuilder() {
  2255. Menu() {
  2256. MenuItem({
  2257. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2258. content: "按艺术家",
  2259. builder: this.SubSortBuilder(SortMode.ByArtist),
  2260. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2261. })
  2262. MenuItem({
  2263. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2264. content: "按专辑",
  2265. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2266. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2267. })
  2268. MenuItem({
  2269. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2270. content: "按名称",
  2271. builder: this.SubSortBuilder(SortMode.ByName),
  2272. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2273. })
  2274. MenuItem({
  2275. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2276. content: $r('app.string.sort_by_time'),
  2277. builder: this.SubSortBuilder(SortMode.ByTime),
  2278. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2279. })
  2280. MenuItem({
  2281. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2282. content: '按碟片音轨号',
  2283. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2284. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2285. })
  2286. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2287. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2288. }.attributeModifier(new MenuModifier())
  2289. }
  2290. @Builder
  2291. SortMenuForArtistAblumBuilder() {
  2292. Menu() {
  2293. MenuItem({
  2294. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2295. content: "按名称",
  2296. builder: this.SubSortBuilder(SortMode.ByName),
  2297. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2298. })
  2299. MenuItem({
  2300. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2301. content: '按数量',
  2302. builder: this.SubSortBuilder(SortMode.ByCount),
  2303. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2304. })
  2305. }.attributeModifier(new MenuModifier())
  2306. }
  2307. @Builder SubSortBuilder(sortType: number){
  2308. Menu(){
  2309. MenuItem({
  2310. content: "升序",
  2311. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2312. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2313. })
  2314. .onClick(async () => {
  2315. await this.doSortType(sortType)
  2316. })
  2317. MenuItem({
  2318. content: "降序",
  2319. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2320. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2321. })
  2322. .onClick(async () => {
  2323. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2324. })
  2325. }
  2326. }
  2327. async doSortType(index: number): Promise<void> {
  2328. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2329. this.sortType = index;
  2330. this.saveSortTypeForCurrentMode(index);
  2331. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2332. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2333. await this.reloadCurrentDetailSongs();
  2334. } else {
  2335. // 分页模式下,排序需要重新从数据库查询
  2336. await this.resetAndLoadFirstPage();
  2337. }
  2338. }
  2339. /**
  2340. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2341. * 用于详情页切换排序方式时重新查询并排序
  2342. */
  2343. private async reloadCurrentDetailSongs(): Promise<void> {
  2344. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2345. try {
  2346. if (this.modeType === 2) {
  2347. // 艺术家详情页: 重新查询该艺术家的歌曲
  2348. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2349. if (ArrayUtil.isNotEmpty(mList)) {
  2350. // 使用带排序类型的缓存键
  2351. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2352. this.artistMap.set(cacheKey, mList);
  2353. this.totalCount = mList.length;
  2354. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2355. this.updateListData(mList, true);
  2356. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2357. }
  2358. } else if (this.modeType === 3) {
  2359. // 专辑详情页: 重新查询该专辑的歌曲
  2360. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2361. if (ArrayUtil.isNotEmpty(albumList)) {
  2362. // 使用带排序类型的缓存键
  2363. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2364. this.albumMap.set(cacheKey, albumList);
  2365. this.totalCount = albumList.length;
  2366. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2367. this.updateListData(albumList, true);
  2368. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2369. }
  2370. }
  2371. } catch (err) {
  2372. const error = err as Error;
  2373. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2374. ToastUtil.showToast('重新加载数据失败');
  2375. }
  2376. }
  2377. /**
  2378. * 根据当前模式保存排序类型到不同的存储键
  2379. * 区分列表页和详情页的排序设置
  2380. */
  2381. private saveSortTypeForCurrentMode(sortType: number): void {
  2382. let storageKey = SettingPage.SORT_TYPE;
  2383. if (this.modeType === 2) {
  2384. // 艺术家模式
  2385. if (this.isCanBack) {
  2386. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2387. } else {
  2388. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2389. }
  2390. } else if (this.modeType === 3) {
  2391. // 专辑模式
  2392. if (this.isCanBack) {
  2393. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2394. } else {
  2395. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2396. }
  2397. } else {
  2398. storageKey = SettingPage.SORT_TYPE;
  2399. }
  2400. PreferencesUtil.putSync(storageKey, sortType);
  2401. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2402. }
  2403. /**
  2404. * 根据当前模式加载排序类型
  2405. * 区分列表页和详情页的排序设置
  2406. */
  2407. private loadSortTypeForCurrentMode(): number {
  2408. let storageKey = SettingPage.SORT_TYPE;
  2409. let defaultSortType = 4;
  2410. if (this.modeType === 2) {
  2411. // 艺术家模式
  2412. if (this.isCanBack) {
  2413. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2414. defaultSortType = 4; // 详情页默认按名称升序
  2415. } else {
  2416. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2417. defaultSortType = 9; // 列表页默认按数量降序
  2418. }
  2419. } else if (this.modeType === 3) {
  2420. // 专辑模式
  2421. if (this.isCanBack) {
  2422. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2423. defaultSortType = 4; // 详情页默认按名称升序
  2424. } else {
  2425. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2426. defaultSortType = 9; // 列表页默认按数量降序
  2427. }
  2428. }
  2429. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2430. }
  2431. /**
  2432. * 检查当前sortType是否在指定排序类型的范围内
  2433. * 用于判断是否显示打勾图标
  2434. * @param baseSortType 基础排序类型(升序的值)
  2435. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2436. */
  2437. private isSortTypeInRange(baseSortType: number): boolean {
  2438. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2439. }
  2440. showSheelDialog() {
  2441. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2442. // this.showTips()
  2443. // return
  2444. // }
  2445. this.showAddDialog()
  2446. }
  2447. showAddDialog() {
  2448. if (this.modeType === 2 || this.modeType === 3) {
  2449. return
  2450. }
  2451. DialogHelper.showActionSheetDialog({
  2452. title: "请选择添加方式(建议歌词文件一起导入)",
  2453. sheets: [
  2454. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2455. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2456. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2457. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2458. ],
  2459. maskColor: Color.Transparent,
  2460. backgroundColor: $r('app.color.bg_card'),
  2461. transition: AnimationHelper.transitionInDown(555),
  2462. onAction: (index) => {
  2463. switch (index) {
  2464. case 0:
  2465. if (this.modeType === 0) {
  2466. this.showMkDialog()
  2467. } else {
  2468. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2469. }
  2470. break;
  2471. case 1:
  2472. this.callFilePickerSelectFile()
  2473. break;
  2474. case 2:
  2475. this.showTips()
  2476. break;
  2477. case 3:
  2478. this.goSelectMusic()
  2479. break;
  2480. }
  2481. }
  2482. })
  2483. }
  2484. //拉起音频
  2485. goSelectMusic() {
  2486. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2487. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2488. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2489. ) {
  2490. ToastUtil.showToast('暂时不支持该设备')
  2491. return
  2492. }
  2493. try {
  2494. let documentSelectOptions = new picker.DocumentSelectOptions();
  2495. documentSelectOptions.authMode = true
  2496. documentSelectOptions.multiAuthMode = true
  2497. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2498. documentSelectOptions.maxSelectNumber = 20000
  2499. }
  2500. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2501. let documentPicker = new picker.DocumentViewPicker(this.context);
  2502. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2503. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2504. this.saveVideoDatas(documentSelectResult)
  2505. }
  2506. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2507. JSON.stringify(documentSelectResult));
  2508. }).catch((err: BusinessError) => {
  2509. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2510. });
  2511. } catch (error) {
  2512. let err: BusinessError = error as BusinessError;
  2513. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2514. }
  2515. }
  2516. async showTips() {
  2517. try {
  2518. this.getUIContext().getPromptAction().showDialog({
  2519. title: '导入指南',
  2520. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2521. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2522. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2523. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2524. buttons: [
  2525. {
  2526. text: '知道了',
  2527. color: '#000000'
  2528. },
  2529. ]
  2530. }, (err, data) => {
  2531. if (err) {
  2532. console.error('showDialog err: ' + err);
  2533. return;
  2534. }
  2535. console.info('showDialog success callback, click button: ' + data.index);
  2536. });
  2537. } catch (error) {
  2538. let message = (error as BusinessError).message;
  2539. let code = (error as BusinessError).code;
  2540. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2541. };
  2542. }
  2543. showMkDialog() {
  2544. DialogHelper.showTextInputDialog({
  2545. title: '新建歌单',
  2546. maskColor: Color.Transparent,
  2547. text: '',
  2548. transition: AnimationHelper.transitionInDown(666),
  2549. onChange: (text) => {
  2550. console.error("onChange: " + text);
  2551. },
  2552. onAction: (action, dialogId, content) => {
  2553. // ToastUtil.showToast('content = ' +content)
  2554. if (action == DialogAction.TWO) {
  2555. const newName = content
  2556. const newPath = this.currentPath + '/' + newName
  2557. FileUtil.mkdir(newPath, true).then(() => {
  2558. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2559. this.getSortedFiles(this.currentPath)
  2560. }).catch((error: BusinessError) => {
  2561. console.error(error.message);
  2562. });
  2563. }
  2564. }
  2565. })
  2566. }
  2567. @State progress: number = 0;
  2568. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2569. if (ArrayUtil.isEmpty(uris)) {
  2570. return;
  2571. }
  2572. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2573. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2574. this.saveVideoDatasToDownLoad(uris,isOpen)
  2575. return
  2576. }
  2577. // 初始化进度条
  2578. this.progress = 0;
  2579. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2580. progress: this.progress,
  2581. backCancel: false,
  2582. autoCancel: false,
  2583. loadColor: $r('app.color.title_bar_bg'),
  2584. fontColor: $r('app.color.title_bar_bg')
  2585. });
  2586. // 计算处理总数用于进度计算
  2587. const totalItems = uris.length;
  2588. let processedItems = 0;
  2589. for (let i = 0; i < uris.length; i++) {
  2590. let filePath = uris[i];
  2591. try {
  2592. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2593. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2594. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2595. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2596. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2597. if (!filePath.includes(this.rootPath)) {
  2598. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2599. mediaItem.parentPath = this.currentPath;
  2600. }
  2601. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2602. this.table.insert(mediaItem, (id: number) => {
  2603. // 插入完成回调
  2604. });
  2605. }
  2606. }
  2607. // 更新进度
  2608. processedItems++;
  2609. this.progress = Math.floor((processedItems / totalItems) * 100);
  2610. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2611. } catch (error) {
  2612. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2613. // 即使出错也更新进度
  2614. processedItems++;
  2615. this.progress = Math.floor((processedItems / totalItems) * 100);
  2616. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2617. }
  2618. }
  2619. // 关闭进度条
  2620. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2621. this.isZero = false
  2622. // 删除目标路径缓存
  2623. setTimeout(() => {
  2624. this.cache.delete(this.currentPath);
  2625. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2626. this.setButtonStatus()
  2627. }, 500);
  2628. }
  2629. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2630. if (ArrayUtil.isEmpty(uris)) {
  2631. return;
  2632. }
  2633. let newUris: string[] = [];
  2634. this.progress = 0
  2635. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2636. progress: this.progress,
  2637. backCancel: false,
  2638. autoCancel: false,
  2639. loadColor: this.themeColor,
  2640. fontColor: this.themeColor
  2641. });
  2642. // 计算所有文件的总大小
  2643. let totalSize = 0;
  2644. for (let uri of uris) {
  2645. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2646. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2647. await fileIo.close(sourceFile.fd);
  2648. }
  2649. let totalRead = 0;
  2650. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2651. Logger.info(TAG, 'destPath uri: ' + destPath);
  2652. for (let i = 0; i < uris.length; i++) {
  2653. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2654. Logger.info(TAG, 'filePath uri: ' + filePath);
  2655. newUris.push(filePath);
  2656. try {
  2657. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2658. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2659. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2660. const buffer = new ArrayBuffer(buffSize);
  2661. let len = await fileIo.read(sourceFile.fd, buffer);
  2662. while (len > 0) {
  2663. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2664. totalRead += len;
  2665. // 计算总进度
  2666. this.progress = Math.floor((totalRead / totalSize) * 100);
  2667. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2668. len = await fileIo.read(sourceFile.fd, buffer);
  2669. }
  2670. await fileIo.close(sourceFile.fd);
  2671. await fileIo.close(destFile.fd);
  2672. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2673. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2674. let mediaItem: VideoItem =
  2675. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2676. this.table.insert(mediaItem, (id: number) => {
  2677. // 删除目标路径缓存
  2678. this.cache.delete(this.currentPath);
  2679. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2680. });
  2681. }
  2682. }
  2683. } catch (error) {
  2684. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2685. }
  2686. }
  2687. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2688. this.isZero = false
  2689. Logger.info(TAG, 'scan select video result:' + newUris)
  2690. }
  2691. //拉起音频
  2692. // goSelectMusic(){
  2693. //
  2694. // try {
  2695. // let audioSelectOptions = new picker.AudioSelectOptions();
  2696. // let audioPicker = new picker.AudioViewPicker(this.context);
  2697. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2698. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2699. // this.saveVideoDatas(audioSelectResult)
  2700. // }
  2701. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2702. // }).catch((err: BusinessError) => {
  2703. //
  2704. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2705. // });
  2706. // } catch (error) {
  2707. // let err: BusinessError = error as BusinessError;
  2708. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2709. // }
  2710. //
  2711. //
  2712. //
  2713. // }
  2714. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2715. if (!item) {
  2716. return undefined;
  2717. }
  2718. try {
  2719. let selectUris: Array<string> = [];
  2720. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2721. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2722. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2723. photoSelectOptions.maxSelectNumber = 1;
  2724. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2725. selectUris = photoSelectResult.photoUris;
  2726. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2727. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2728. console.info('file fd: ' + file.fd);
  2729. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2730. let imagePath = this.context.filesDir + FileUtil.separator + name
  2731. imagePath = fileUri.getUriFromPath(imagePath)
  2732. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2733. fileIo.copyFileSync(file.fd, file2.fd)
  2734. fileIo.closeSync(file);
  2735. fileIo.closeSync(file2);
  2736. if (item.filePath == this.currentSong?.filePath) {
  2737. this.cover = imagePath
  2738. }
  2739. if (item) {
  2740. item.pixelMapPath = imagePath
  2741. }
  2742. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2743. if (success) {
  2744. this.doUpdateData()
  2745. console.log("onecold 更新音乐封面成功,数据库已同步");
  2746. } else {
  2747. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2748. }
  2749. });
  2750. LogUtil.debug("onecold this.cover =" + this.cover)
  2751. return FileUtil.getFilePath(imagePath); // Return the image path here
  2752. } catch (err) {
  2753. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2754. return undefined;
  2755. }
  2756. }
  2757. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  2758. try {
  2759. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  2760. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2761. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2762. photoSelectOptions.maxSelectNumber = 1;
  2763. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2764. const selectUris = photoSelectResult.photoUris;
  2765. if (!selectUris || selectUris.length === 0) {
  2766. return undefined;
  2767. }
  2768. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  2769. if (!FileUtil.accessSync(coverDir)) {
  2770. FileUtil.mkdirSync(coverDir);
  2771. }
  2772. const sourceUri = selectUris[0];
  2773. const sourceName = FileUtil.getFileName(sourceUri) || '';
  2774. let suffix = '.jpg';
  2775. const dotIndex = sourceName.lastIndexOf('.');
  2776. if (dotIndex >= 0) {
  2777. suffix = sourceName.substring(dotIndex);
  2778. }
  2779. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  2780. const targetPath = coverDir + FileUtil.separator + targetName;
  2781. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  2782. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  2783. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  2784. fileIo.closeSync(sourceFile.fd);
  2785. fileIo.closeSync(targetFile.fd);
  2786. return fileUri.getUriFromPath(targetPath);
  2787. } catch (error) {
  2788. const err = error as BusinessError;
  2789. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  2790. return undefined;
  2791. }
  2792. }
  2793. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  2794. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  2795. ToastUtil.showToast('当前歌曲无效');
  2796. return;
  2797. }
  2798. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  2799. ToastUtil.showToast('仅支持本地歌曲更换封面');
  2800. return;
  2801. }
  2802. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  2803. if (StrUtil.isEmpty(sandboxCoverUri)) {
  2804. return;
  2805. }
  2806. this.loadingDialogId = DialogHelper.showLoadingDialog();
  2807. try {
  2808. const task = new taskpool.Task(
  2809. replaceLocalMusicCoverTask,
  2810. this.context,
  2811. this.currentSong.filePath,
  2812. FileUtil.getFilePath(sandboxCoverUri!)
  2813. );
  2814. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  2815. if (!result) {
  2816. ToastUtil.showToast('更换封面失败');
  2817. return;
  2818. }
  2819. this.cover = sandboxCoverUri;
  2820. this.currentSong.pixelMapPath = sandboxCoverUri;
  2821. await this.doUpateEditedFields(this.currentSong);
  2822. ToastUtil.showToast('更换封面成功');
  2823. } catch (error) {
  2824. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  2825. ToastUtil.showToast('更换封面失败');
  2826. } finally {
  2827. DialogHelper.closeDialog(this.loadingDialogId);
  2828. }
  2829. }
  2830. // 拉起picker选择文件管理器
  2831. async callFilePickerSelectFile(): Promise<void> {
  2832. try {
  2833. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2834. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2835. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2836. } else {
  2837. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2838. }
  2839. let documentPicker = new picker.DocumentViewPicker();
  2840. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2841. Logger.info(TAG,
  2842. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2843. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2844. this.saveVideoDatas(DocumentSelectResult)
  2845. }
  2846. }).catch((err: BusinessError) => {
  2847. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2848. });
  2849. } catch (err) {
  2850. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2851. }
  2852. }
  2853. //重命名的对话框
  2854. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2855. if(!item.filePath.includes(this.packName)){
  2856. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2857. return
  2858. }
  2859. DialogHelper.showTextInputDialog({
  2860. title: '重命名',
  2861. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2862. maskColor: Color.Transparent,
  2863. backgroundColor: Color.Grey,
  2864. transition: AnimationHelper.transitionInDown(666),
  2865. onChange: (text) => {
  2866. console.error("onChange: " + text);
  2867. },
  2868. onAction: (action, dialogId, content) => {
  2869. // ToastUtil.showToast('content = ' +content)
  2870. if (action == DialogAction.TWO) {
  2871. const newName = content
  2872. const newPath = this.currentPath + '/' + newName
  2873. console.log("onecold item = " + item.type);
  2874. this.doReName(index, newName, filePath, newPath, item)
  2875. }
  2876. }
  2877. })
  2878. }
  2879. //剪切 移动到另个文件夹的对话框
  2880. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2881. Logger.info('onecold showCutDialog')
  2882. let mList: Array<string> = []
  2883. let rPath = this.rootPath
  2884. if (isCurrent) {
  2885. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2886. rPath = this.currentPath
  2887. } else {
  2888. mList = Utility.getNameList(this.dirList);
  2889. rPath = this.rootPath
  2890. }
  2891. let dataBean = new BubbleBean()
  2892. dataBean.data = mList
  2893. dataBean.color = this.themeColor
  2894. dataBean.onItemClick = (i) => {
  2895. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2896. Logger.info('newPath = ' + newPath)
  2897. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2898. ToastUtil.showToast('移动成功')
  2899. this.table.deleteData(item, () => {
  2900. });
  2901. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2902. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2903. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2904. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2905. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2906. this.table.insert(newItem, (id: number) => {
  2907. //加入数据库
  2908. });
  2909. }
  2910. this.cache.delete(this.currentPath); // 删除原路径缓存
  2911. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2912. this.getSortedFiles(this.currentPath, true)
  2913. }).catch((error: BusinessError) => {
  2914. console.error(error.message);
  2915. });
  2916. XPopup.dismissTop()
  2917. }
  2918. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2919. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2920. popupPosition = PopupPosition.TOP
  2921. }
  2922. if (index <= 3) {
  2923. popupPosition = PopupPosition.BOTTOM
  2924. }
  2925. let pup: XPopup
  2926. if (this.isDarkMode) {
  2927. pup = XPopup.Builder()
  2928. .setPopupPosition(popupPosition)
  2929. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2930. .setBackgroundColor(Color.Black)
  2931. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2932. .show()
  2933. } else {
  2934. pup = XPopup.Builder()
  2935. .setPopupPosition(popupPosition)
  2936. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2937. .setBackgroundColor(Color.White)
  2938. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2939. .show()
  2940. }
  2941. }
  2942. //复制 到另个文件夹的对话框
  2943. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2944. Logger.info('onecoldv showCopyDialog')
  2945. let mList: Array<string> = []
  2946. let rPath = this.rootPath
  2947. if (isCurrent) {
  2948. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2949. rPath = this.currentPath
  2950. } else {
  2951. mList = Utility.getNameList(this.dirList);
  2952. rPath = this.rootPath
  2953. }
  2954. let dataBean = new BubbleBean()
  2955. dataBean.data = mList
  2956. dataBean.isCopy = true
  2957. dataBean.color = this.themeColor
  2958. dataBean.onItemClick = (i) => {
  2959. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2960. Logger.info('newPath = ' + newPath)
  2961. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2962. ToastUtil.showToast('复制成功')
  2963. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2964. this.getSortedFiles(this.currentPath)
  2965. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2966. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2967. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2968. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2969. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2970. this.table.insert(newItem, (id: number) => {
  2971. //加入数据库
  2972. });
  2973. }
  2974. }).catch((error: BusinessError) => {
  2975. console.error(error.message);
  2976. });
  2977. XPopup.dismissTop()
  2978. }
  2979. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2980. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2981. popupPosition = PopupPosition.TOP
  2982. }
  2983. if (index <= 3) {
  2984. popupPosition = PopupPosition.BOTTOM
  2985. }
  2986. let pup: XPopup
  2987. if (this.isDarkMode) {
  2988. pup = XPopup.Builder()
  2989. .setPopupPosition(popupPosition)
  2990. .atView(id)
  2991. .setMaxHeight('60%')
  2992. .setBackgroundColor(Color.Black)
  2993. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2994. .show();
  2995. } else {
  2996. pup = XPopup.Builder()
  2997. .setPopupPosition(popupPosition)
  2998. .atView(id)
  2999. .setMaxHeight('60%')
  3000. .setBackgroundColor(Color.White)
  3001. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3002. .show();
  3003. }
  3004. }
  3005. //重命名索引index的视频
  3006. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3007. FileUtil.rename(oldPath, newPath).then(async () => {
  3008. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3009. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3010. //如果是文件夹先删除源数据,再添加新数据
  3011. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3012. if (success) {
  3013. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3014. } else {
  3015. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3016. }
  3017. });
  3018. this.scanDirectory(newPath)
  3019. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3020. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3021. if (success) {
  3022. console.log(" onecold 重命名成功,数据库已同步");
  3023. } else {
  3024. console.error(" onecold 重命名数据库失败原因: " + error);
  3025. }
  3026. });
  3027. }
  3028. let mediaItem: VideoItem =
  3029. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3030. this.videoLocalList[index] = mediaItem;
  3031. }
  3032. this.cache.delete(this.currentPath)
  3033. this.getSortedFiles(this.currentPath, true)
  3034. }).catch((error: BusinessError) => {
  3035. console.error(error.message);
  3036. });
  3037. }
  3038. build() {
  3039. Stack() {
  3040. this.ContentBuild()
  3041. Stack() {
  3042. Column()
  3043. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3044. height: '95%',
  3045. dragBar: true,
  3046. showClose: true,
  3047. blurStyle: BlurStyle.Thin,
  3048. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3049. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3050. title: {
  3051. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3052. + `(${this.getPlayListDisplayCount()}首)`
  3053. }
  3054. })
  3055. }
  3056. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3057. modalTransition:ModalTransition.DEFAULT,
  3058. onWillDisappear: () => {
  3059. this.setShowPlayFalse()
  3060. },
  3061. })
  3062. }
  3063. .alignContent(Alignment.Bottom)
  3064. .width('100%')
  3065. .height('100%')
  3066. }
  3067. @Builder
  3068. ContentBuild() {
  3069. Scroll() {
  3070. Column() {
  3071. Stack() {
  3072. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3073. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3074. controller: this.xcomponentController })
  3075. .onLoad(async (event?: object) => {
  3076. })
  3077. .focusable(true)
  3078. .height(0)
  3079. .focusOnTouch(true)
  3080. .defaultFocus(true) // 自动获取键盘焦点
  3081. .onKeyEvent((event?: KeyEvent) => {
  3082. console.info('onecold点击 onKeyEvent')
  3083. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3084. if (!event || event.type !== KeyType.Down) {
  3085. return;
  3086. }
  3087. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3088. //空格键 Space key controls pause/play
  3089. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3090. this.playOrPause()
  3091. }
  3092. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3093. this.playPrevious()
  3094. }
  3095. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3096. this.playNext()
  3097. }
  3098. // Right-click to fast forward
  3099. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3100. this.fastForward()
  3101. }
  3102. // Left-click to rewind
  3103. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3104. this.backForward()
  3105. }
  3106. })
  3107. Column() {
  3108. XComponent({
  3109. id: 'xcomponentId',
  3110. type: 'surface',
  3111. libraryname: 'ijkplayer_napi',
  3112. controller: this.xcomponentController
  3113. })
  3114. .onLoad((event?: object) => {
  3115. if (!!event) {
  3116. this.initDelayPlay(event);
  3117. }
  3118. })
  3119. .onDestroy(() => {
  3120. })
  3121. .width('100%')// .width(this.videoWidth)
  3122. .aspectRatio(this.videoAspectRatio)
  3123. }
  3124. .aspectRatio(this.videoAspectRatio)
  3125. .justifyContent(FlexAlign.Center)
  3126. .backgroundColor(Color.Transparent)
  3127. .visibility(Visibility.Hidden)
  3128. .height(CommonConstants.FULL_PERCENT)
  3129. .width(CommonConstants.FULL_PERCENT)
  3130. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3131. height:this.isLandscape?'80%': '43%',
  3132. dragBar: true,
  3133. showClose: true,
  3134. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3135. blurStyle:BlurStyle.Thin,
  3136. backgroundColor:Color.Transparent,
  3137. title: { title: 'AB循环' }
  3138. })
  3139. Stack() {
  3140. Column() {
  3141. if(this.twoFingerType==4){
  3142. this.getWaterView()
  3143. }else{
  3144. if(this.isGridMusic){
  3145. this.getGridView()
  3146. }else {
  3147. this.getListView()
  3148. }
  3149. }
  3150. if (this.modeType ==0||this.modeType==4) {
  3151. Column() {
  3152. emptyView(this.themeColor)
  3153. }
  3154. .padding({ right:6 })
  3155. .onClick(()=>{
  3156. this.asyncCurrentPathOnlyFile()
  3157. })
  3158. .alignItems(HorizontalAlign.Center)
  3159. .position({ top: 200 })
  3160. .justifyContent(FlexAlign.Center)
  3161. .opacity(this.isZero ? 1 : 0)
  3162. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3163. ? Visibility.Visible : Visibility.None)
  3164. .animation({
  3165. duration: 500,
  3166. curve: Curve.Friction // 可选动画曲线
  3167. })
  3168. .width('100%')
  3169. }
  3170. }
  3171. .layoutWeight(1)
  3172. .height('100%')
  3173. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3174. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3175. .onDrop((event?: DragEvent) => {
  3176. try {
  3177. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3178. if (dragData !== undefined) {
  3179. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3180. if (records.length > 0) {
  3181. for (let i = 0; i < records.length; i++) {
  3182. let types = records[i].getTypes();
  3183. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3184. const fileUriUds =
  3185. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3186. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3187. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3188. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3189. this.targetFile = fileUriUds.oriUri;
  3190. this.saveVideoDatas([this.targetFile])
  3191. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3192. }
  3193. }
  3194. }
  3195. } else {
  3196. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3197. }
  3198. } else {
  3199. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3200. }
  3201. } catch (error) {
  3202. const err = error as BusinessError;
  3203. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3204. }
  3205. })
  3206. // 右侧居中的字母表索引
  3207. this.indexBuilder()
  3208. this.topTitleBar()
  3209. }
  3210. .alignContent(Alignment.Top)
  3211. .layoutWeight(1)
  3212. .height('100%')
  3213. Row() {
  3214. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3215. .width(45)
  3216. .height(45)
  3217. .fontSize(10)
  3218. .margin({ top: 10, bottom: 10, right: 6 })
  3219. .backgroundColor(this.themeColor)
  3220. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3221. .onClick(() => {
  3222. if (this.isAllSelected) {
  3223. // 全不选
  3224. this.selectedFiles = [];
  3225. } else {
  3226. // 全选
  3227. this.selectedFiles = [...this.getCurFileList()];
  3228. }
  3229. this.isAllSelected = !this.isAllSelected;
  3230. })
  3231. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3232. .width(72)
  3233. .height(45)
  3234. .fontSize(10)
  3235. .margin({ top: 10, bottom: 10, right: 6 })
  3236. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3237. .backgroundColor(this.themeColor)
  3238. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3239. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3240. })
  3241. .onClick(() => {
  3242. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3243. this.isOneKeyTags = !this.isOneKeyTags
  3244. // }else{
  3245. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  3246. // }
  3247. })
  3248. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3249. .width(45)
  3250. .height(45)
  3251. .fontSize(10)
  3252. .margin({ top: 10, bottom: 10, right: 6 })
  3253. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3254. .backgroundColor(this.themeColor)
  3255. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3256. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3257. })
  3258. .onClick(() => {
  3259. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3260. this.isMergeAudio = !this.isMergeAudio
  3261. }else{
  3262. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3263. }
  3264. })
  3265. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3266. .width(45)
  3267. .height(45)
  3268. .fontSize(10)
  3269. .margin({ top: 10, bottom: 10, right: 6 })
  3270. .backgroundColor(this.themeColor)
  3271. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3272. .onClick(async () => {
  3273. this.longItemFilePath = ''
  3274. await this.openAddToPlaylistDialog(this.selectedFiles)
  3275. })
  3276. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3277. // .width(45)
  3278. // .height(45)
  3279. // .fontSize(10)
  3280. // .margin({ top: 10, bottom: 10, right: 6 })
  3281. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3282. // .backgroundColor(this.themeColor)
  3283. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3284. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3285. // })
  3286. // .onClick(() => {
  3287. // this.isFixMessy = !this.isFixMessy
  3288. // })
  3289. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3290. // .width('35%')
  3291. // .height(60)
  3292. // .id('music_cut')
  3293. // .margin({ top: 10, bottom: 10, right: 6 })
  3294. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3295. // .backgroundColor(this.themeColor)
  3296. // .onClick(() => {
  3297. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3298. // })
  3299. //
  3300. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3301. // .width('35%')
  3302. // .height(60)
  3303. // .id('music_cut_current')
  3304. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3305. // .margin({ top: 10, bottom: 10, right: 6 })
  3306. // .backgroundColor(this.themeColor)
  3307. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3308. // .onClick(() => {
  3309. //
  3310. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3311. // })
  3312. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3313. // .width('35%')
  3314. // .height(60)
  3315. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3316. // .margin({ top: 10, bottom: 10, right: 6 })
  3317. // .backgroundColor(this.themeColor)
  3318. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3319. // .onClick(() => {
  3320. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3321. // })
  3322. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3323. .width(45)
  3324. .height(45)
  3325. .fontSize(10)
  3326. .margin({ top: 10, bottom: 10, right: 6 })
  3327. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3328. .backgroundColor(this.themeColor)
  3329. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3330. .onClick(() => {
  3331. this.showWarnIsDelete()
  3332. })
  3333. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3334. .width(45)
  3335. .height(45)
  3336. .fontSize(10)
  3337. .margin({ top: 10, bottom: 10, right: 6 })
  3338. .backgroundColor(this.themeColor)
  3339. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3340. .onClick(() => {
  3341. this.selectedFiles = [];
  3342. this.isAllSelected = false
  3343. this.isMultiSelect = false
  3344. })
  3345. }
  3346. .width('100%')
  3347. .justifyContent(FlexAlign.Center)
  3348. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3349. .opacity(this.isMultiSelect ? 1 : 0)
  3350. .animation({
  3351. duration: 666,
  3352. curve: 'ease-in-out' // 可选动画曲线
  3353. })
  3354. .position({ bottom: 20 }) // 将 Row 固定在底部
  3355. }
  3356. .width('100%')
  3357. .height('100%')
  3358. .alignContent(Alignment.Top)
  3359. }
  3360. .width('100%')
  3361. .height('100%')
  3362. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3363. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3364. .backgroundImagePosition(Alignment.Center)
  3365. .backdropBlur(this.blurValue)
  3366. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3367. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3368. }
  3369. }
  3370. //字母表索引
  3371. @Builder
  3372. indexBuilder(){
  3373. Column({space: 5}){
  3374. if(this.showZMIndex&&this.enableShowAlphabet){
  3375. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3376. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3377. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3378. .attributeModifier(this.alphaBetStyle)
  3379. .usingPopup(this.isTouchingAlphaBet)
  3380. .onAreaChange((old_value,new_value)=>{
  3381. this.alphabetHeight = new_value.height as number
  3382. })
  3383. .popupPosition({
  3384. x: 40,
  3385. y: this.alphabetHeight / 2
  3386. })
  3387. .onSelect((index: number) => {
  3388. void this.onSelectIndexItem(this.alphaBet[index])
  3389. })
  3390. .onTouch((event: TouchEvent) =>{
  3391. this.showAlphabetIndex()
  3392. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3393. this.isTouchingAlphaBet = false
  3394. this.hideAlphabetIndexAfterDelay(1500)
  3395. }else{
  3396. this.isTouchingAlphaBet = true
  3397. }
  3398. })
  3399. .transition(
  3400. TransitionEffect.translate({x: 10})
  3401. .combine(TransitionEffect.opacity(0.1))
  3402. .animation({
  3403. duration: 150,
  3404. curve: Curve.EaseInOut,
  3405. })
  3406. )
  3407. }
  3408. }
  3409. if(this.showFindLocation){
  3410. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3411. Blank()
  3412. .layoutWeight(1)
  3413. }
  3414. PointLightDefaultButton({
  3415. isSysBol:true,
  3416. pointColor:Color.Gray,
  3417. imageResource:$r('sys.symbol.local_fill'),
  3418. isPx: false,
  3419. builderHeight: 30,
  3420. builderWidth: 30,
  3421. })
  3422. .onClick(() =>{
  3423. void this.locateCurrentSong();
  3424. })
  3425. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3426. .margin({
  3427. bottom: this.bottomSafeHeight+100,right:10
  3428. })
  3429. }
  3430. }
  3431. .padding({
  3432. bottom: 0
  3433. })
  3434. .margin({right:5})
  3435. .position({x:'92%'})
  3436. .height('100%')
  3437. .justifyContent(FlexAlign.Center)
  3438. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3439. height: '100%',
  3440. dragBar: true,
  3441. showClose: true,
  3442. preferType: SheetType.CENTER ,
  3443. blurStyle: BlurStyle.Thin,
  3444. title: { title: '均衡器' },
  3445. onDisappear: () => {
  3446. this.isEqualizerSheet = false
  3447. }
  3448. })
  3449. }
  3450. async onSelectIndexItem(letter: string) {
  3451. await this.ensureFullListForAlphabetIndex();
  3452. const findTargetIndex = (): number => {
  3453. const songs = this.videoLocalList;
  3454. for (let i = 0; i < songs.length; i++) {
  3455. const song = songs[i];
  3456. let text = this.isShowFileName ? song.fileName :
  3457. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3458. if (this.sortType === 0 || this.sortType == 1) {
  3459. text = song.artist;
  3460. } else if (this.sortType === 2 || this.sortType == 3) {
  3461. text = song.album;
  3462. }
  3463. if (text) {
  3464. const firstPinyin = getFirstLetter(text);
  3465. if (firstPinyin && firstPinyin === letter) {
  3466. return i;
  3467. }
  3468. }
  3469. }
  3470. return -1;
  3471. };
  3472. const targetIndex = findTargetIndex();
  3473. if (targetIndex !== -1) {
  3474. if (this.isGridMusic || this.twoFingerType == 4) {
  3475. this.scroller.scrollToIndex(targetIndex, false);
  3476. } else {
  3477. this.listScroller.scrollToIndex(targetIndex);
  3478. }
  3479. }
  3480. }
  3481. private showAlphabetIndex(): void {
  3482. this.isShowAlphaBet = true;
  3483. if (this.alphaBetHideTimer) {
  3484. clearTimeout(this.alphaBetHideTimer);
  3485. this.alphaBetHideTimer = 0;
  3486. }
  3487. }
  3488. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3489. if (this.alphaBetHideTimer) {
  3490. clearTimeout(this.alphaBetHideTimer);
  3491. }
  3492. this.alphaBetHideTimer = setTimeout(() => {
  3493. if (!this.isTouchingAlphaBet) {
  3494. this.isShowAlphaBet = false;
  3495. }
  3496. this.alphaBetHideTimer = 0;
  3497. }, delayMs) as number;
  3498. }
  3499. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  3500. if (!this.showZMIndex) {
  3501. return;
  3502. }
  3503. if (this.alphaBetRebuildTimer) {
  3504. clearTimeout(this.alphaBetRebuildTimer);
  3505. }
  3506. this.alphaBetRebuildTimer = setTimeout(() => {
  3507. this.alphaBetRebuildTimer = 0;
  3508. if (this.isScrolling) {
  3509. this.alphaBetDirty = true;
  3510. return;
  3511. }
  3512. this.alphaBetDirty = false;
  3513. void this.setAlphaBet();
  3514. }, delayMs) as number;
  3515. }
  3516. private markAlphaBetDirty(): void {
  3517. if (!this.showZMIndex) {
  3518. return;
  3519. }
  3520. if (this.isMediaLibraryWarmupWindow()) {
  3521. this.alphaBetDirty = true;
  3522. this.scheduleAlphaBetRebuild(900);
  3523. return;
  3524. }
  3525. this.alphaBetDirty = true;
  3526. if (!this.isScrolling) {
  3527. this.scheduleAlphaBetRebuild(80);
  3528. }
  3529. }
  3530. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3531. if (this.isLoadingPage) {
  3532. return;
  3533. }
  3534. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3535. return;
  3536. }
  3537. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3538. return;
  3539. }
  3540. if (this.modeType !== 0 && this.modeType !== 1) {
  3541. return;
  3542. }
  3543. this.isLoadingPage = true;
  3544. try {
  3545. const options: PageQueryOptions = {
  3546. pageIndex: 0,
  3547. pageSize: this.totalCount,
  3548. sortType: this.sortType,
  3549. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3550. isShowFileName: this.isShowFileName
  3551. };
  3552. if (this.modeType === 0) {
  3553. options.parentPath = this.currentPath;
  3554. }
  3555. let result: PageQueryResult;
  3556. if (this.modeType === 0) {
  3557. result = await this.table.queryByParentPathPaged(options);
  3558. if (!this.isSearchMode) {
  3559. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3560. result.items = [...directories, ...result.items];
  3561. result.totalCount += directories.length;
  3562. }
  3563. } else {
  3564. result = await this.table.queryMediaLibraryPaged(options);
  3565. }
  3566. this.videoLocalList = result.items;
  3567. this.dataSource.pushArrayData(this.videoLocalList);
  3568. this.pageCache.clear();
  3569. this.pageHasMoreCache.clear();
  3570. this.pageTotalCountCache.clear();
  3571. this.prefetchingPages.clear();
  3572. this.currentPage = 0;
  3573. this.totalCount = result.totalCount;
  3574. this.hasMoreData = false;
  3575. this.lastScrollTriggerPage = -1;
  3576. this.lastVisibleEndIndex = -1;
  3577. this.isPagingTransition = false;
  3578. if (this.pagingScheduleTimer) {
  3579. clearTimeout(this.pagingScheduleTimer);
  3580. this.pagingScheduleTimer = 0;
  3581. }
  3582. if (this.modeType === 1) {
  3583. this.mediaKuCount = result.totalCount;
  3584. }
  3585. this.setButtonStatus();
  3586. this.markAlphaBetDirty();
  3587. } catch (err) {
  3588. const error = err as Error;
  3589. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3590. } finally {
  3591. this.isLoadingPage = false;
  3592. }
  3593. }
  3594. // 找到对应字母表的索引
  3595. findAlphaBetIndex(song: VideoItem):number{
  3596. let text = this.isShowFileName?song.fileName:
  3597. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3598. if(this.sortType === 0||this.sortType==1){
  3599. text = song.artist
  3600. }else if(this.sortType === 2||this.sortType==3){
  3601. text = song.album
  3602. }
  3603. if(text){
  3604. let firstLetter = getFirstLetter(text)
  3605. for(let i=0;i<this.alphaBet.length;i++){
  3606. if(this.alphaBet[i] === firstLetter){
  3607. return i
  3608. }
  3609. }
  3610. }
  3611. return 0
  3612. }
  3613. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  3614. const items: Array<AlphaTaskItem> = []
  3615. for (const song of songs) {
  3616. items.push({
  3617. type: song.type,
  3618. name: song.name,
  3619. pyStr: song.pyStr,
  3620. fileName: song.fileName,
  3621. artist: song.artist,
  3622. album: song.album
  3623. })
  3624. }
  3625. return items
  3626. }
  3627. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  3628. const taskItems = this.buildAlphaTaskItems(songs)
  3629. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  3630. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  3631. if (version !== this.alphaBetBuildVersion) {
  3632. return
  3633. }
  3634. this.alphaBet = result
  3635. if (this.videoLocalList.length > 0) {
  3636. this.selectAlphaBetIndex = 0
  3637. }
  3638. }
  3639. async setAlphaBet(){
  3640. if(!this.showZMIndex){
  3641. return
  3642. }
  3643. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  3644. await this.refreshAlphaBetFromMediaLibrary()
  3645. return
  3646. }
  3647. try {
  3648. const songs = this.videoLocalList
  3649. if (songs.length > 40000) {
  3650. this.alphaBet = []
  3651. return
  3652. }
  3653. const version = ++this.alphaBetBuildVersion
  3654. await this.buildAlphaBetByTask(songs, version)
  3655. } catch (e) {
  3656. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3657. }
  3658. }
  3659. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  3660. if (this.totalCount <= 0) {
  3661. return
  3662. }
  3663. if (this.totalCount > 40000) {
  3664. this.alphaBet = []
  3665. return
  3666. }
  3667. const keyword = this.isSearchMode ? this.searchText : ''
  3668. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  3669. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  3670. return
  3671. }
  3672. const result = await this.table.queryMediaLibraryPaged({
  3673. pageIndex: 0,
  3674. pageSize: this.totalCount,
  3675. sortType: this.sortType,
  3676. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3677. isShowFileName: this.isShowFileName
  3678. })
  3679. const version = ++this.alphaBetBuildVersion
  3680. await this.buildAlphaBetByTask(result.items, version)
  3681. this.alphaBetCacheKey = cacheKey
  3682. }
  3683. @Builder
  3684. topTitleBar(){
  3685. Column() {
  3686. Row({ space: 15 }) {
  3687. if (!this.isSearchMode ) {
  3688. //左侧滑动按钮
  3689. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3690. SymbolGlyph(this.rightTopImage)
  3691. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3692. }
  3693. .attributeModifier(new ButtonFancyModifier(40, 40))
  3694. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3695. .animation({ duration: 300, curve: Curve.Ease })
  3696. .onClick(() => {
  3697. this.triggerSwipeBackWithAnimation()
  3698. })
  3699. .attributeModifier(new ShadowModifier())
  3700. .zIndex(0)
  3701. }else{
  3702. //左侧搜索返回按钮
  3703. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3704. SymbolGlyph($r('sys.symbol.chevron_left'))
  3705. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3706. }
  3707. .attributeModifier(new ButtonFancyModifier(40, 40))
  3708. .margin({bottom:5})
  3709. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3710. .animation({ duration: 300, curve: Curve.Ease })
  3711. .onClick(() => {
  3712. this.isSearchMode = false
  3713. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3714. this.searchText = ''
  3715. this.getSortedFiles(this.currentPath)
  3716. return
  3717. }
  3718. this.onSearchInput('')
  3719. })
  3720. .attributeModifier(new ShadowModifier())
  3721. .zIndex(0)
  3722. }
  3723. if (!this.isSearchMode) {
  3724. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3725. .margin({left:3,right:10})
  3726. .fontColor($r('app.color.text_color'))
  3727. .fontSize(this.twoFingerType==3?17:16)
  3728. .maxLines(1)
  3729. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3730. .layoutWeight(1)
  3731. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3732. }
  3733. //搜索框
  3734. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3735. .searchButton('搜索',{fontColor:this.themeColor})
  3736. .searchIcon({
  3737. src: $r('sys.media.ohos_ic_public_search_filled')
  3738. })
  3739. .cancelButton({
  3740. style: CancelButtonStyle.CONSTANT,
  3741. icon: {
  3742. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3743. }
  3744. })
  3745. .layoutWeight(1)
  3746. .height(40)
  3747. .maxLength(20)
  3748. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3749. .placeholderColor(Color.Grey)
  3750. .placeholderFont({ size: 14, weight: 400 })
  3751. .textFont({ size: 14, weight: 400 })
  3752. .onSubmit((value: string) => {
  3753. console.log('onecold onSubmit ='+value)
  3754. this.searchController.stopEditing()
  3755. if(this.modeType==0){
  3756. this.modeType =1//如果是首页 切换到媒体库搜索
  3757. }
  3758. this.onSearchInput(this.searchText);
  3759. })
  3760. .onChange((value: string) => {
  3761. console.log('onecold onChange ='+value)
  3762. if(this.modeType==0){
  3763. this.modeType =1//如果是首页 切换到媒体库搜索
  3764. }
  3765. this.onSearchInput(value);
  3766. })
  3767. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3768. .animation({ duration: 300, curve: Curve.Ease })
  3769. //搜索按钮
  3770. if (!this.isSearchMode) {
  3771. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3772. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3773. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3774. }
  3775. .attributeModifier(new ButtonFancyModifier(40, 40))
  3776. .animation({ duration: 300, curve: Curve.Ease })
  3777. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3778. .attributeModifier(new ShadowModifier())
  3779. .zIndex(0)
  3780. .onClick(()=>{
  3781. this.isSearchMode = true
  3782. })
  3783. //排序按钮
  3784. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3785. SymbolGlyph($r('sys.symbol.list_number'))
  3786. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3787. }
  3788. .attributeModifier(new ButtonFancyModifier(40, 40))
  3789. .animation({ duration: 300, curve: Curve.Ease })
  3790. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3791. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3792. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3793. .attributeModifier(new ShadowModifier())
  3794. .zIndex(0)
  3795. //添加按钮
  3796. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3797. SymbolGlyph($r('sys.symbol.plus'))
  3798. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3799. }
  3800. .attributeModifier(new ButtonFancyModifier(40, 40))
  3801. .animation({ duration: 300, curve: Curve.Ease })
  3802. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3803. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3804. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3805. height: SheetSize.FIT_CONTENT,
  3806. dragBar: true,
  3807. showClose: true,
  3808. preferType: SheetType.CENTER ,
  3809. title: {
  3810. title: '导入音乐'
  3811. }
  3812. })
  3813. .onClick(() => {
  3814. this.showAddSheet = !this.showAddSheet;
  3815. })
  3816. .attributeModifier(new ShadowModifier())
  3817. .zIndex(0)
  3818. }
  3819. }
  3820. }
  3821. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3822. .width('100%')
  3823. .translate({
  3824. x: 0,
  3825. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  3826. })
  3827. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  3828. .animation({
  3829. duration: 240,
  3830. curve: Curve.EaseInOut
  3831. })
  3832. }
  3833. @Builder
  3834. addSheet() {
  3835. Scroll() {
  3836. Column() {
  3837. Column() {
  3838. Row() {
  3839. SymbolGlyph($r('sys.symbol.info_circle'))
  3840. .fontSize(22)
  3841. .fontColor([this.themeColor])
  3842. .alignSelf(ItemAlign.Center)
  3843. .margin({ left: 8 })
  3844. Text('导入音乐复制到DownLoad目录')
  3845. .margin({ left: 8 })
  3846. .fontSize(14)
  3847. .fontColor($r('app.color.text_color'))
  3848. .fontWeight(480)
  3849. .layoutWeight(1)
  3850. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3851. .selectedColor(this.themeColor)
  3852. .switchPointColor(Color.White)
  3853. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3854. .margin({ right: 2 })
  3855. .onChange((checked: boolean) => {
  3856. this.isCopyFileToDownLoad = checked;
  3857. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3858. })
  3859. .width(50)
  3860. .height(30);
  3861. }
  3862. .height(72)
  3863. .padding({ left:8,right:8 })
  3864. }
  3865. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3866. .backgroundColor($r('app.color.start_window_background'))
  3867. .borderRadius(15)
  3868. .width('85%')
  3869. .margin({
  3870. top: 10,
  3871. bottom: 10
  3872. })
  3873. .padding(0)
  3874. .border({
  3875. color: Color.White,
  3876. width: 1.8
  3877. })
  3878. Menu() {
  3879. MenuItem({
  3880. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3881. content: "新建文件夹"
  3882. })
  3883. .backgroundColor($r('app.color.silvery'))
  3884. .border({
  3885. width: { bottom: 1 },
  3886. color: '#12ec5c87'
  3887. })
  3888. .margin(10)
  3889. .height(60)
  3890. .padding({left:15,right:15})
  3891. .onClick(async () => {
  3892. this.showMkDialog()
  3893. this.showAddSheet = !this.showAddSheet
  3894. })
  3895. MenuItem({
  3896. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3897. content: $r('app.string.import_from_files')
  3898. })
  3899. .padding({left:15,right:15})
  3900. .backgroundColor($r('app.color.silvery'))
  3901. .border({
  3902. width: { bottom: 1 },
  3903. color: '#12ec5c87'
  3904. })
  3905. .margin(10)
  3906. .height(60)
  3907. .onClick(async () => {
  3908. this.callFilePickerSelectFile()
  3909. this.showAddSheet = !this.showAddSheet
  3910. })
  3911. MenuItem({
  3912. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3913. content: '全选导入'
  3914. // content: '从下载文件夹导入(路径:Download/' +
  3915. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3916. })
  3917. .padding({left:15,right:15})
  3918. .backgroundColor($r('app.color.silvery'))
  3919. .border({
  3920. width: { bottom: 1 },
  3921. color: '#12ec5c87'
  3922. })
  3923. .margin(10)
  3924. .height(60)
  3925. .onClick(async () => {
  3926. this.goSelectMusic()
  3927. this.showAddSheet = !this.showAddSheet
  3928. })
  3929. MenuItem({
  3930. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3931. content: '自动导入教程'
  3932. })
  3933. .padding({left:15,right:15})
  3934. .backgroundColor($r('app.color.silvery'))
  3935. .border({
  3936. width: { bottom: 1 },
  3937. color: '#12ec5c87'
  3938. })
  3939. .margin(10)
  3940. .height(60)
  3941. .onClick(async () => {
  3942. this.showTips()
  3943. this.showAddSheet = !this.showAddSheet
  3944. })
  3945. MenuItem({
  3946. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  3947. content: '导入疑问'
  3948. })
  3949. .height(60)
  3950. .padding({left:15,right:15})
  3951. .backgroundColor($r('app.color.silvery'))
  3952. .border({
  3953. width: { bottom: 1 },
  3954. color: '#12ec5c87'
  3955. })
  3956. .margin(10)
  3957. .onClick(async () => {
  3958. this.showProblomTips()
  3959. this.showAddSheet = !this.showAddSheet
  3960. })
  3961. }.attributeModifier(new MenuModifier())
  3962. .margin({bottom:30})
  3963. .width('90%')
  3964. .borderRadius(15)
  3965. }
  3966. .layoutWeight(1)
  3967. }
  3968. }
  3969. async showProblomTips() {
  3970. try {
  3971. this.getUIContext().getPromptAction().showDialog({
  3972. title: '导入疑问',
  3973. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  3974. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  3975. buttons: [
  3976. {
  3977. text: '知道了',
  3978. color: '#000000'
  3979. },
  3980. ]
  3981. }, (err, data) => {
  3982. if (err) {
  3983. console.error('showDialog err: ' + err);
  3984. return;
  3985. }
  3986. console.info('showDialog success callback, click button: ' + data.index);
  3987. });
  3988. } catch (error) {
  3989. let message = (error as BusinessError).message;
  3990. let code = (error as BusinessError).code;
  3991. console.error(`showDialog args error code is ${code}, message is ${message}`);
  3992. };
  3993. }
  3994. @Builder
  3995. TagsContentCoverBuilder() {
  3996. Scroll() {
  3997. Column() {
  3998. TagsContentCover(
  3999. {
  4000. selectedFiles:this.selectedFiles,
  4001. isOneKeyTags:this.isOneKeyTags,
  4002. onSeePath:(path:string)=>{
  4003. this.modeType = 0
  4004. this.deleteCache(path)
  4005. this.getSortedFiles(path)
  4006. },
  4007. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4008. this.isMultiSelect = false
  4009. if(result){//如果嵌入成功,更新数据
  4010. this.listRefreshKey++
  4011. setTimeout(()=>{
  4012. this.doUpdateData()
  4013. },500)
  4014. }
  4015. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4016. if(deleteCache_path){
  4017. this.deleteCache(deleteCache_path)
  4018. }
  4019. }
  4020. }
  4021. )
  4022. }
  4023. }
  4024. .width('100%')
  4025. .height('100%')
  4026. }
  4027. @Builder
  4028. FixMessyViewBuilder() {
  4029. Scroll() {
  4030. Column() {
  4031. FixMessyView(
  4032. {
  4033. selectedFiles:this.selectedFiles,
  4034. isFixMessy:this.isFixMessy,
  4035. onFixResult:(result: boolean)=>{
  4036. this.isMultiSelect = false
  4037. if(result){//如果嵌入成功,更新数据
  4038. this.deleteCache(this.currentPath)
  4039. this.doUpdateData()
  4040. }
  4041. }
  4042. }
  4043. )
  4044. }
  4045. }
  4046. .width('100%')
  4047. .height('100%')
  4048. }
  4049. //剪辑音频
  4050. @Builder
  4051. EditAudioBuilder(item:VideoItem) {
  4052. Scroll() {
  4053. Column() {
  4054. EditAudio(
  4055. {
  4056. mVideoItem:item,
  4057. currentPath:this.currentPath,
  4058. videoUrl:this.videoUrl,
  4059. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4060. currentTime:this.currentTime,
  4061. progressValue:this.progressValue,
  4062. onBack:()=>{
  4063. this.isEditAudio = !this.isEditAudio
  4064. },
  4065. onSeeOutputPath:(outPutPath:string)=>{
  4066. this.isEditAudio = !this.isEditAudio
  4067. this.longItemFilePath = ''
  4068. this.modeType = 0
  4069. this.isShowFileName = true
  4070. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4071. },
  4072. onPlayOrPause:()=>{
  4073. if(this.videoUrl==item.filePath){
  4074. this.playOrPause()
  4075. }else{//如果不是当前播放的,则播放该文件
  4076. this.videoUrl==item.filePath
  4077. this.doPlay(item,0,false,true)
  4078. }
  4079. },
  4080. onSliderChange:(value:number)=>{
  4081. if(this.videoUrl!=item.filePath){
  4082. this.videoUrl==item.filePath
  4083. return
  4084. }
  4085. this.isSeekTo = true;
  4086. this.mDestroyPage = false;
  4087. this.showLoadIng();
  4088. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4089. let seekValue = value * (this.getActiveDuration() / 100);
  4090. this.seekTo(seekValue + "");
  4091. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4092. this.isSeekTo = false;
  4093. },
  4094. onResult:(result: boolean,outPath:string)=>{
  4095. if(result){//如果剪辑成功,更新数据
  4096. this.doUpdateData()
  4097. }else{
  4098. ToastUtil.showToast('剪辑失败')
  4099. }
  4100. }
  4101. }
  4102. )
  4103. }
  4104. }
  4105. .width('100%')
  4106. .height('100%')
  4107. }
  4108. //提取伴奏
  4109. @Builder
  4110. ConverterBuilder(item:VideoItem) {
  4111. Scroll() {
  4112. Column() {
  4113. AudioFormatConverter(
  4114. {
  4115. mVideoItem:item,
  4116. videoUrl:this.videoUrl,
  4117. currentPath:this.currentPath,
  4118. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4119. currentTime:this.currentTime,
  4120. progressValue:this.progressValue,
  4121. onBack:()=>{
  4122. this.isConverter = !this.isConverter
  4123. this.longItemFilePath = ''
  4124. },
  4125. onPlayOrPause:()=>{
  4126. if(this.videoUrl==item.filePath){
  4127. this.playOrPause()
  4128. }else{//如果不是当前播放的,则播放该文件
  4129. this.videoUrl==item.filePath
  4130. this.doPlay(item,0,false,true)
  4131. }
  4132. },
  4133. onSeeOutputPath:(outPutPath:string)=>{
  4134. this.isConverter = !this.isConverter
  4135. this.longItemFilePath = ''
  4136. this.modeType = 0
  4137. this.isShowFileName = true
  4138. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4139. },
  4140. onSliderChange:(value:number)=>{
  4141. if(this.videoUrl!=item.filePath){
  4142. this.videoUrl==item.filePath
  4143. return
  4144. }
  4145. this.isSeekTo = true;
  4146. this.mDestroyPage = false;
  4147. this.showLoadIng();
  4148. let seekValue = value * (this.getActiveDuration() / 100);
  4149. this.seekTo(seekValue + "");
  4150. this.isSeekTo = false;
  4151. },
  4152. onResult:(result: boolean,outPath:string)=>{
  4153. if(result){//如果成功,更新数据
  4154. this.doUpdateData()
  4155. }else{
  4156. ToastUtil.showToast('格式转化失败')
  4157. }
  4158. }
  4159. }
  4160. )
  4161. }
  4162. }
  4163. .width('100%')
  4164. .height('100%')
  4165. }
  4166. //提取伴奏
  4167. @Builder
  4168. ExtractAccBuilder(item:VideoItem) {
  4169. Scroll() {
  4170. Column() {
  4171. ExtractAccompaniment(
  4172. {
  4173. mVideoItem:item,
  4174. currentPath:this.currentPath,
  4175. videoUrl:this.videoUrl,
  4176. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4177. currentTime:this.currentTime,
  4178. progressValue:this.progressValue,
  4179. onBack:()=>{
  4180. this.isExtractAcc = !this.isExtractAcc
  4181. this.longItemFilePath = ''
  4182. },
  4183. onPlayOrPause:()=>{
  4184. if(this.videoUrl==item.filePath){
  4185. this.playOrPause()
  4186. }else{//如果不是当前播放的,则播放该文件
  4187. this.videoUrl==item.filePath
  4188. this.doPlay(item,0,false,true)
  4189. }
  4190. },
  4191. onSeeOutputPath:(outPutPath:string)=>{
  4192. this.isExtractAcc = !this.isExtractAcc
  4193. this.longItemFilePath = ''
  4194. this.modeType = 0
  4195. this.isShowFileName = true
  4196. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4197. },
  4198. onSliderChange:(value:number)=>{
  4199. if(this.videoUrl!=item.filePath){
  4200. this.videoUrl==item.filePath
  4201. return
  4202. }
  4203. this.isSeekTo = true;
  4204. this.mDestroyPage = false;
  4205. this.showLoadIng();
  4206. let seekValue = value * (this.getActiveDuration() / 100);
  4207. this.seekTo(seekValue + "");
  4208. this.isSeekTo = false;
  4209. },
  4210. onResult:(result: boolean,outPath:string)=>{
  4211. if(result){//如果成功,更新数据
  4212. this.doUpdateData()
  4213. }else{
  4214. ToastUtil.showToast('提取伴奏失败')
  4215. }
  4216. }
  4217. }
  4218. )
  4219. }
  4220. }
  4221. .width('100%')
  4222. .height('100%')
  4223. }
  4224. //AI人声分离
  4225. @Builder
  4226. AiBuilder(item:VideoItem) {
  4227. Scroll() {
  4228. Column() {
  4229. AIVoiceSeparation(
  4230. {
  4231. mVideoItem:item,
  4232. videoUrl:this.videoUrl,
  4233. currentPath:this.currentPath,
  4234. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4235. currentTime:this.currentTime,
  4236. progressValue:this.progressValue,
  4237. onBack:()=>{
  4238. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4239. this.longItemFilePath = ''
  4240. },
  4241. onPlayOrPause:()=>{
  4242. if(this.videoUrl==item.filePath||this.isPlaying){
  4243. this.playOrPause()
  4244. }else{//如果不是当前播放的,则播放该文件
  4245. this.videoUrl==item.filePath
  4246. this.doPlay(item,0,false,true)
  4247. }
  4248. },
  4249. onPlayPath:(path:string)=>{
  4250. this.videoUrl==path
  4251. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4252. if(itemP)
  4253. this.doPlay(itemP,0,false,true)
  4254. },
  4255. onSeeOutputPath:(outPutPath:string)=>{
  4256. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4257. this.longItemFilePath = ''
  4258. this.modeType = 0
  4259. this.isShowFileName = true
  4260. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4261. },
  4262. onSliderChange:(value:number)=>{
  4263. if(this.videoUrl!=item.filePath){
  4264. this.videoUrl==item.filePath
  4265. return
  4266. }
  4267. this.isSeekTo = true;
  4268. this.mDestroyPage = false;
  4269. this.showLoadIng();
  4270. let seekValue = value * (this.getActiveDuration() / 100);
  4271. this.seekTo(seekValue + "");
  4272. this.isSeekTo = false;
  4273. },
  4274. onResult:(result: boolean,outPath:string)=>{
  4275. if(result){//如果成功,更新数据
  4276. this.doUpdateData()
  4277. }else{
  4278. ToastUtil.showToast('Ai人声分离失败')
  4279. }
  4280. }
  4281. }
  4282. )
  4283. }
  4284. }
  4285. .width('100%')
  4286. .height('100%')
  4287. }
  4288. //变速变调
  4289. @Builder
  4290. ChangeToneBuilder(item:VideoItem) {
  4291. Scroll() {
  4292. Column() {
  4293. ChangeTone(
  4294. {
  4295. mVideoItem:item,
  4296. currentPath:this.currentPath,
  4297. videoUrl:this.videoUrl,
  4298. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4299. currentTime:this.currentTime,
  4300. progressValue:this.progressValue,
  4301. onBack:()=>{
  4302. this.isChangeTone = !this.isChangeTone
  4303. this.longItemFilePath = ''
  4304. },
  4305. onPlayOrPause:()=>{
  4306. if(this.videoUrl==item.filePath){
  4307. this.playOrPause()
  4308. }else{//如果不是当前播放的,则播放该文件
  4309. this.videoUrl==item.filePath
  4310. this.doPlay(item,0,false,true)
  4311. }
  4312. },
  4313. onSeeOutputPath:(outPutPath:string)=>{
  4314. this.isChangeTone = !this.isChangeTone
  4315. this.longItemFilePath = ''
  4316. this.modeType = 0
  4317. this.isShowFileName = true
  4318. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4319. },
  4320. onSliderChange:(value:number)=>{
  4321. if(this.videoUrl!=item.filePath){
  4322. this.videoUrl==item.filePath
  4323. return
  4324. }
  4325. this.isSeekTo = true;
  4326. this.mDestroyPage = false;
  4327. this.showLoadIng();
  4328. let seekValue = value * (this.getActiveDuration() / 100);
  4329. this.seekTo(seekValue + "");
  4330. this.isSeekTo = false;
  4331. },
  4332. onResult:(result: boolean,outPath:string)=>{
  4333. if(result){//如果成功,更新数据
  4334. this.doUpdateData()
  4335. }else{
  4336. ToastUtil.showToast('变速变调失败')
  4337. }
  4338. }
  4339. }
  4340. )
  4341. }
  4342. }
  4343. .width('100%')
  4344. .height('100%')
  4345. }
  4346. //提取视频中的音频
  4347. @Builder
  4348. extractAudioFromVideoBuilder(item:VideoItem) {
  4349. Scroll() {
  4350. Column() {
  4351. ExtractAudioFromVideo(
  4352. {
  4353. mVideoItem:item,
  4354. currentPath:this.currentPath,
  4355. videoUrl:this.videoUrl,
  4356. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4357. currentTime:this.currentTime,
  4358. progressValue:this.progressValue,
  4359. onBack:()=>{
  4360. this.isExtractAudio = !this.isExtractAudio
  4361. this.longItemFilePath = ''
  4362. },
  4363. onPlayOrPause:()=>{
  4364. if(this.videoUrl==item.filePath){
  4365. this.playOrPause()
  4366. }else{//如果不是当前播放的,则播放该文件
  4367. this.videoUrl==item.filePath
  4368. this.doPlay(item,0,false,true)
  4369. }
  4370. },
  4371. onSeeOutputPath:(outPutPath:string)=>{
  4372. this.isExtractAudio = !this.isExtractAudio
  4373. this.longItemFilePath = ''
  4374. this.modeType = 0
  4375. this.isShowFileName = true
  4376. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4377. },
  4378. onSliderChange:(value:number)=>{
  4379. if(this.videoUrl!=item.filePath){
  4380. this.videoUrl==item.filePath
  4381. return
  4382. }
  4383. this.isSeekTo = true;
  4384. this.mDestroyPage = false;
  4385. this.showLoadIng();
  4386. let seekValue = value * (this.getActiveDuration() / 100);
  4387. this.seekTo(seekValue + "");
  4388. this.isSeekTo = false;
  4389. },
  4390. onResult:(result: boolean,outPath:string)=>{
  4391. if(result){//如果成功,更新数据
  4392. this.doUpdateData()
  4393. }else{
  4394. ToastUtil.showToast('提取音频失败')
  4395. }
  4396. }
  4397. }
  4398. )
  4399. }
  4400. }
  4401. .width('100%')
  4402. .height('100%')
  4403. }
  4404. //合并音频
  4405. @Builder
  4406. MergeAudioBuilder() {
  4407. Scroll() {
  4408. Column() {
  4409. MergeAudio(
  4410. {
  4411. videoUrl:this.videoUrl,
  4412. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4413. currentPath:this.currentPath,
  4414. selectedFiles:this.selectedFiles,
  4415. currentTime:this.currentTime,
  4416. progressValue:this.progressValue,
  4417. onBack:()=>{
  4418. this.isMergeAudio = !this.isMergeAudio
  4419. this.longItemFilePath = ''
  4420. },
  4421. // onPlayPath:(path:string)=>{
  4422. // if(this.videoUrl==item.filePath){
  4423. // this.playOrPause()
  4424. // }else{//如果不是当前播放的,则播放该文件
  4425. // this.videoUrl==item.filePath
  4426. // this.doPlay(item,0,false,true)
  4427. // }
  4428. //
  4429. // },
  4430. onSeeOutputPath:(outPutPath:string)=>{
  4431. this.isMergeAudio = !this.isMergeAudio
  4432. this.longItemFilePath = ''
  4433. this.modeType = 0
  4434. this.isShowFileName = true
  4435. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4436. },
  4437. onResult:(result: boolean,outPath:string)=>{
  4438. if(result){//如果成功,更新数据
  4439. this.doUpdateData()
  4440. }else{
  4441. if(this.selectedFiles.length>=3){
  4442. ToastUtil.showToast('合并数量太多导致失败')
  4443. }else{
  4444. ToastUtil.showToast('合并失败')
  4445. }
  4446. }
  4447. }
  4448. }
  4449. )
  4450. }
  4451. }
  4452. .width('100%')
  4453. .height('100%')
  4454. }
  4455. asyncCurrentPathData() {
  4456. if (this.modeType == 0) {
  4457. workerInstance.postMessage({
  4458. code: 1,
  4459. data1: this.context,
  4460. data2: this.currentPath,
  4461. data3: this.lockPath,
  4462. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4463. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4464. });
  4465. }
  4466. }
  4467. // 处理文件选择的函数
  4468. handleFileSelection(item: VideoItem, checked: boolean) {
  4469. if (checked) {
  4470. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4471. this.selectedFiles.push(item);
  4472. }
  4473. } else {
  4474. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4475. if (index > -1) {
  4476. this.selectedFiles.splice(index, 1);
  4477. }
  4478. }
  4479. }
  4480. private deleteComponentId: number = 0
  4481. //多选删除文件
  4482. showWarnIsDelete(){
  4483. this.getUIContext().getPromptAction().openCustomDialog({
  4484. builder: () => {
  4485. this.deleteComptentBuilder()
  4486. },
  4487. isModal:true,
  4488. showInSubWindow:false,
  4489. maskColor: Color.Transparent,
  4490. dialogTransition: // 设置弹窗内容显示的过渡效果
  4491. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4492. .animation({ duration: 600, curve: Curve.Smooth }),
  4493. maskTransition: // 设置蒙层显示的过渡效果
  4494. TransitionEffect.opacity(0)
  4495. .animation({ duration: 600, curve: Curve.Smooth })
  4496. }).then((dialogId: number) => {
  4497. this.deleteComponentId = dialogId
  4498. })
  4499. .catch((error: BusinessError) => {
  4500. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4501. })
  4502. }
  4503. @Builder
  4504. deleteComptentBuilder(){
  4505. DeleteComptent({
  4506. selectedFiles:this.selectedFiles,
  4507. onCancel:()=>{
  4508. this.isMultiSelect = false
  4509. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4510. },
  4511. onDeleteResult:(result: boolean)=>{
  4512. this.isMultiSelect = false
  4513. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4514. if(result){//如果删除成功,更新数据
  4515. this.selectedFiles = [];
  4516. this.isAllSelected = false
  4517. this.cache.delete(this.currentPath);
  4518. this.getSortedFiles(this.currentPath, true);
  4519. }
  4520. }
  4521. })
  4522. }
  4523. //多选移动文件
  4524. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4525. Logger.info('onecold showCutDialogForMultipleFiles')
  4526. let mList: Array<string> = []
  4527. let rPath = this.rootPath
  4528. if (isCurrent) {
  4529. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4530. rPath = this.currentPath
  4531. } else {
  4532. mList = Utility.getNameList(this.dirList);
  4533. rPath = this.rootPath
  4534. }
  4535. let dataBean = new BubbleBean();
  4536. dataBean.data = mList;
  4537. dataBean.color = this.themeColor
  4538. dataBean.onItemClick = (i) => {
  4539. const newDirPath = rPath + '/' + mList[i];
  4540. // Logger.info('newDirPath = ' + newDirPath)
  4541. this.selectedFiles.forEach((item) => {
  4542. const newPath = newDirPath + '/' + item.fileName;
  4543. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4544. ToastUtil.showToast('移动成功');
  4545. this.table.deleteData(item, () => {
  4546. this.cache.delete(this.currentPath); // 删除原路径缓存
  4547. this.cache.delete(newDirPath); // 删除目标路径缓存
  4548. this.getSortedFiles(this.currentPath, true);
  4549. });
  4550. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4551. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4552. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4553. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4554. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4555. this.table.insert(newItem, (id: number) => {
  4556. //加入数据库
  4557. });
  4558. }
  4559. }).catch((error: Error) => {
  4560. console.error(error.message);
  4561. });
  4562. });
  4563. this.isMultiSelect = false
  4564. this.selectedFiles = [];
  4565. this.isAllSelected = false
  4566. XPopup.dismissTop();
  4567. };
  4568. let pup: XPopup
  4569. if (this.isDarkMode) {
  4570. pup = XPopup.Builder()
  4571. .setPopupPosition(PopupPosition.TOP)
  4572. .atView(viewId)
  4573. .setBackgroundColor(Color.Black)
  4574. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4575. .show();
  4576. } else {
  4577. pup = XPopup.Builder()
  4578. .setPopupPosition(PopupPosition.TOP)
  4579. .atView(viewId)
  4580. .setBackgroundColor(Color.White)
  4581. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4582. .show();
  4583. }
  4584. }
  4585. /**
  4586. * 加载所有歌单
  4587. */
  4588. async loadAllPlaylists() {
  4589. try {
  4590. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4591. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4592. } catch (error) {
  4593. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4594. }
  4595. }
  4596. /**
  4597. * 显示添加到歌单对话框
  4598. */
  4599. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4600. const songs = Array.isArray(items) ? items : [items]
  4601. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4602. if (musicItems.length === 0) {
  4603. ToastUtil.showToast('请选择要添加的歌曲')
  4604. return
  4605. }
  4606. // 加载最新的歌单列表
  4607. await this.loadAllPlaylists()
  4608. showAddToPlaylistDialog(
  4609. musicItems,
  4610. this.allPlaylists,
  4611. async (playlistId: string) => {
  4612. // 添加歌曲到歌单
  4613. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4614. musicItems.map(song => song.filePath))
  4615. if (success) {
  4616. const count = musicItems.length
  4617. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4618. // 重新加载歌单列表
  4619. await this.loadAllPlaylists()
  4620. } else {
  4621. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4622. }
  4623. this.longItemFilePath = ''
  4624. if (this.isMultiSelect) {
  4625. this.isMultiSelect = false
  4626. this.isAllSelected = false
  4627. this.selectedFiles = []
  4628. }
  4629. },
  4630. () => {
  4631. LogUtil.info('取消添加到歌单')
  4632. },
  4633. () => {
  4634. // 创建新歌单
  4635. showCreatePlaylistDialog(
  4636. async (name: string, description: string, coverPath?: string) => {
  4637. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4638. if (success) {
  4639. ToastUtil.showToast('歌单创建成功')
  4640. // 重新加载歌单列表并打开添加对话框
  4641. await this.loadAllPlaylists()
  4642. await this.openAddToPlaylistDialog(musicItems)
  4643. } else {
  4644. ToastUtil.showToast('歌单创建失败')
  4645. }
  4646. },
  4647. () => {
  4648. // 取消创建歌单
  4649. }
  4650. )
  4651. }
  4652. )
  4653. }
  4654. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  4655. const nextFavList = [...this.favList];
  4656. const favIndex = nextFavList.findIndex((favItem: VideoItem) => favItem.filePath === item.filePath);
  4657. if (isFav === 1) {
  4658. if (favIndex >= 0) {
  4659. nextFavList[favIndex].isFav = 1;
  4660. } else {
  4661. const favItem = cloneVideoItem(item);
  4662. favItem.isFav = 1;
  4663. nextFavList.push(favItem);
  4664. }
  4665. } else if (favIndex >= 0) {
  4666. nextFavList.splice(favIndex, 1);
  4667. }
  4668. this.favList = nextFavList;
  4669. item.isFav = isFav;
  4670. if (this.currentSong && this.currentSong.filePath === item.filePath) {
  4671. this.currentSong.isFav = isFav;
  4672. this.isFac = isFav === 1;
  4673. }
  4674. }
  4675. doFav(item: VideoItem) {
  4676. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4677. let isFav = 0
  4678. if (Utility.getIsFav(this.favList, item)) {
  4679. isFav = 0
  4680. } else {
  4681. isFav = 1
  4682. }
  4683. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4684. if (result) {
  4685. this.syncFavStateLocal(item, isFav);
  4686. if (isFav === 1) {
  4687. ToastUtil.showToast('收藏成功');
  4688. } else {
  4689. ToastUtil.showToast('取消收藏成功');
  4690. }
  4691. this.deleteCache(this.currentPath)
  4692. this.getFavList(false)
  4693. if (this.modeType === 0 && !this.isFavMusic) {
  4694. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4695. this.getSortedFiles(this.currentPath)
  4696. }
  4697. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4698. workerInstance.postMessage({ code: 3, data: this.context });
  4699. workerInstance.postMessage({ code: 4, data: this.context });
  4700. }
  4701. })
  4702. }
  4703. //多选复制文件
  4704. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4705. console.log('onecold showCopyDialogForMultipleFiles');
  4706. let mList: Array<string> = []
  4707. let rPath = this.rootPath
  4708. if (isCurrent) {
  4709. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4710. rPath = this.currentPath
  4711. } else {
  4712. mList = Utility.getNameList(this.dirList);
  4713. rPath = this.rootPath
  4714. }
  4715. let dataBean = new BubbleBean();
  4716. dataBean.data = mList;
  4717. dataBean.isCopy = true
  4718. dataBean.color = this.themeColor
  4719. dataBean.onItemClick = (i) => {
  4720. const newDirPath = rPath + '/' + mList[i];
  4721. // Logger.info('newDirPath = ' + newDirPath)
  4722. this.selectedFiles.forEach((item) => {
  4723. const newPath = newDirPath + '/' + item.fileName;
  4724. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4725. ToastUtil.showToast('复制成功');
  4726. this.cache.delete(newDirPath); // 删除目标路径缓存
  4727. this.getSortedFiles(this.currentPath);
  4728. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4729. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4730. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4731. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4732. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4733. this.table.insert(newItem, (id: number) => {
  4734. //加入数据库
  4735. });
  4736. }
  4737. }).catch((error: Error) => {
  4738. console.error(error.message);
  4739. });
  4740. });
  4741. this.isMultiSelect = false
  4742. this.selectedFiles = [];
  4743. this.isAllSelected = false
  4744. XPopup.dismissTop();
  4745. };
  4746. let pup: XPopup
  4747. if (this.isDarkMode) {
  4748. pup = XPopup.Builder()
  4749. .setPopupPosition(PopupPosition.TOP)
  4750. .atView(viewId)
  4751. .setBackgroundColor(Color.Black)
  4752. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4753. .show();
  4754. } else {
  4755. pup = XPopup.Builder()
  4756. .setPopupPosition(PopupPosition.TOP)
  4757. .atView(viewId)
  4758. .setBackgroundColor(Color.White)
  4759. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4760. .show();
  4761. }
  4762. }
  4763. @Builder
  4764. private DirItem(item: VideoItem, index?: number) {
  4765. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4766. Row() {
  4767. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ?
  4768. this.getListImageSource(item, index ?? -1, this.coverThumbVersion) :
  4769. $r('app.media.music_group'))
  4770. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4771. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4772. .fillColor(this.themeColor)// .fontSize(33)
  4773. .alt($r('app.media.music_group'))
  4774. .borderRadius(this.isCoverRectangle?9:'100%')
  4775. .clip(true)
  4776. .shadow({
  4777. radius: 2,
  4778. type: ShadowType.BLUR,
  4779. color: 'on_primary'
  4780. })
  4781. .sourceSize({width:38, height:38})
  4782. .margin({ left: 20, top: 8, bottom: 8 })
  4783. Column() {
  4784. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4785. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4786. .maxLines(1)// .width('88%')
  4787. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  4788. .margin({ left: 10, right: 20 })
  4789. .fontColor($r('app.color.text_color'))
  4790. Row() {
  4791. Text(`${this.getArtistSongCount(item.name)}首`)
  4792. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4793. .padding({ top: 8 })
  4794. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4795. .fontColor($r('app.color.text_color'))
  4796. .margin({ left: 10 })
  4797. Text(`${this.getAlbumSongCount(item.name)}首`)
  4798. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4799. .padding({ top: 8 })
  4800. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4801. .fontColor($r('app.color.text_color'))
  4802. .margin({ left: 10 })
  4803. Blank()
  4804. }
  4805. }
  4806. .height('100%')
  4807. .layoutWeight(1)
  4808. .justifyContent(FlexAlign.Center)
  4809. .alignItems(HorizontalAlign.Start)
  4810. Blank()
  4811. Image($r('app.media.arrow_right'))
  4812. .height(25)
  4813. .alignSelf(ItemAlign.Center)
  4814. .id(item.filePath)
  4815. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4816. }
  4817. }
  4818. .backgroundColor(Color.Transparent)
  4819. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4820. .width('98%')
  4821. .reuseId('dir_item')
  4822. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4823. .opacity(this.opacityItem) // 绑定透明度
  4824. }
  4825. private refreshDirVisibilitySettings(): void {
  4826. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4827. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4828. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4829. }
  4830. isShowDir(dirName: string) {
  4831. if (dirName === undefined) {
  4832. return true
  4833. }
  4834. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4835. return this.isShowSimi
  4836. }
  4837. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4838. return this.isShowFAV
  4839. }
  4840. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4841. return this.isShowHistory
  4842. }
  4843. return true
  4844. }
  4845. @State opacityItem: number = 1; // 控制透明度的状态变量
  4846. @Builder
  4847. private MusicItem(item: VideoItem, index?: number) {
  4848. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4849. Row() {
  4850. Stack() {
  4851. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  4852. .fillColor(this.themeColor)
  4853. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4854. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4855. .alt($r('app.media.alt'))
  4856. .borderRadius(this.isCoverRectangle?9:'100%')
  4857. .clip(true)
  4858. .draggable(false)
  4859. .sourceSize({width:38, height:38})
  4860. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4861. // .autoResize(true) // 重采样,可减少内存占用
  4862. .opacity(this.opacityItem)// 绑定透明度
  4863. .margin({ left: 20 })
  4864. .shadow({
  4865. radius: this.isScrolling ? 0 : 10,
  4866. type: ShadowType.BLUR,
  4867. color: 'on_primary'
  4868. })
  4869. .onClick(()=>{
  4870. if (this.isMultiSelect) {
  4871. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4872. this.handleFileSelection(item, !isChecked);
  4873. } else {
  4874. this.doPlay(item,index)
  4875. this.setShowPlayTrue()
  4876. }
  4877. })
  4878. }
  4879. Column() {
  4880. Column() {
  4881. Text(this.isShowFileName?item.fileName :item.name)
  4882. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4883. .maxLines(1)
  4884. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4885. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4886. $r('app.color.text_color'))
  4887. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4888. .padding({right:25})
  4889. .bindPopup(this.longItemFilePath === item.filePath, {
  4890. builder: this.MenuBuilder(item,index,item.filePath),
  4891. placement: Placement.Top,
  4892. // autoCancel: true,
  4893. mask: {color:'#33000000'},
  4894. // popupColor: Color.Yellow,
  4895. enableArrow: false,//是否显示箭头
  4896. showInSubWindow: false,
  4897. onStateChange: (e) => {
  4898. if (!e.isVisible) {
  4899. this.longItemFilePath = ''
  4900. this.tempLyricContent = ''
  4901. }
  4902. }
  4903. })
  4904. Row() {
  4905. Column(){
  4906. Text(item.md5Str?.includes('Lossless')?
  4907. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4908. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4909. .padding({ top: 3,right:6,left:6,bottom:3 })
  4910. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4911. $r('app.color.text_color'))
  4912. .fontWeight(500)
  4913. .borderRadius(12)
  4914. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4915. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4916. .backgroundColor('#FFC107')
  4917. }
  4918. .padding({ top: 8 })
  4919. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4920. :this.twoFingerType==2? item.artist +' ' + item.duration
  4921. : item.artist + ' ' + item?.duration)
  4922. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4923. .padding({ top: 8 ,right:25})
  4924. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4925. .maxLines(1)
  4926. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  4927. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4928. Color.Gray)
  4929. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4930. Blank()
  4931. Text(this.isShowFileName?item.duration:item.size)
  4932. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4933. .padding({ top: 8 })
  4934. .maxLines(1)
  4935. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4936. ? Visibility.Visible : Visibility.None)
  4937. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4938. Color.Gray)
  4939. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4940. }
  4941. }
  4942. .height('100%')
  4943. .width('100%')
  4944. .margin({ right: 10 })
  4945. .justifyContent(FlexAlign.Center)
  4946. .alignItems(HorizontalAlign.Start)
  4947. }
  4948. .height('100%')
  4949. .margin({ left: 5 })
  4950. .layoutWeight(1)
  4951. Column() {
  4952. Checkbox({ name: 'checkbox' + index })
  4953. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4954. .selectedColor(this.themeColor)
  4955. .shape(CheckBoxShape.CIRCLE)
  4956. .opacity(this.isMultiSelect ? 1 : 0)
  4957. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4958. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4959. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4960. .width(22)
  4961. .height(22)
  4962. ImageAnimator()
  4963. .images(this.imagesF)// 动画数组
  4964. .duration(1000)// 持续
  4965. .state(this.animationState)// 动画状态
  4966. .fillMode(FillMode.Forwards)
  4967. .width(18)
  4968. .margin({ right: 20, top: 8, bottom: 8 })
  4969. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4970. Visibility.None)
  4971. .height(18)
  4972. .iterations(-1) // 播放次数
  4973. }
  4974. }
  4975. }
  4976. .gesture(LongPressGesture()
  4977. .onAction(async () => {
  4978. //如果是专辑和艺术家的首页,不能长按
  4979. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4980. return
  4981. //如果是我的收藏 最近播放等也不能长按
  4982. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4983. item.name === LocalMusic.STR_HISTORY_MUSIC
  4984. )
  4985. return
  4986. this.longItemFilePath = item.filePath
  4987. this.tempLyricContent = await this.getLyricContent(item)
  4988. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4989. })
  4990. .onActionEnd((event: GestureEvent) => {
  4991. }))
  4992. .backgroundColor(Color.Transparent)
  4993. .width('100%')
  4994. .reuseId('file_item')
  4995. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4996. }
  4997. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4998. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4999. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5000. direction: Direction.Ltr,
  5001. buttonPadding:{top:12,bottom:12},
  5002. backgroundColor: Color.Transparent,
  5003. fontSize:14,
  5004. selectedFontSize:15,
  5005. selectedFontColor:Color.White,
  5006. selectedBackgroundColor: this.themeColor,
  5007. localizedTextPadding: {
  5008. end: LengthMetrics.vp(20),
  5009. start: LengthMetrics.vp(20)
  5010. }
  5011. })
  5012. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5013. //当胶囊按钮的选择发生变化时调用此函数
  5014. capsuleSelectedIndexesChanged() {
  5015. this.modeType = this.tabSelectedIndexes[0]
  5016. }
  5017. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5018. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5019. isShowCoverHeader() {
  5020. if (!this.isShowHeader) {
  5021. return false
  5022. }
  5023. if (this.modeType == 0) {
  5024. if (this.isHistory || this.isFavMusic) {
  5025. return true
  5026. }
  5027. if (this.currentPath != this.rootPath) {
  5028. return true
  5029. }
  5030. }
  5031. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5032. }
  5033. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5034. if (this.isCustomizeBg) {
  5035. return ('rgba(255,255,255,0.2)')
  5036. }
  5037. if (this.isDarkMode) {
  5038. return $r('app.color.user_center_card_background')
  5039. }
  5040. return this.currentTitleCover
  5041. }
  5042. // 第二步:popup构造器定义弹框内容
  5043. @Builder popupBuilder() {
  5044. Column({ space: 2 }) {
  5045. Text('友情提示:双指缩放可以放大缩小列表')
  5046. .fontSize(12)
  5047. .fontWeight(FontWeight.Regular)
  5048. .fontColor($r('app.color.text_color'))
  5049. }
  5050. .justifyContent(FlexAlign.SpaceAround)
  5051. .width(220)
  5052. .height(55)
  5053. .padding(15)
  5054. }
  5055. //搜索功能的实现
  5056. @State searchText: string = ''; // 用户输入内容
  5057. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5058. @State isSearchMode: boolean = false
  5059. // 实时搜索逻辑(带防抖)
  5060. private async onSearchInput(value: string): Promise<void> {
  5061. this.searchText = value.trim();
  5062. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5063. // 新增条件判断:空输入时退出搜索模式
  5064. if (this.searchText === '') {
  5065. this.isSearchMode = false;
  5066. // 重新加载第一页(不带搜索条件)
  5067. await this.resetAndLoadFirstPage();
  5068. return;
  5069. }
  5070. // 进入搜索模式
  5071. if (!this.isSearchMode) {
  5072. this.isSearchMode = true;
  5073. }
  5074. // 使用数据库分页查询(带搜索条件)
  5075. await this.resetAndLoadFirstPage();
  5076. }
  5077. @State dragItem: number = -1
  5078. @State scaleItem: number = -1
  5079. @State neighborItem: number = -1
  5080. @State neighborScale: number = -1
  5081. @State offsetY: number = 0
  5082. private dragRefOffset: number = 0
  5083. private ITEM_INTV: number = 78
  5084. scaleSelect(item: number): number {
  5085. if (this.scaleItem === item) {
  5086. return 1.05
  5087. } else if (this.neighborItem === item) {
  5088. return this.neighborScale
  5089. } else {
  5090. return 1
  5091. }
  5092. }
  5093. itemMove(index: number, newIndex: number): void {
  5094. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5095. return;
  5096. }
  5097. let tmp = this.videoLocalList.splice(index, 1);
  5098. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5099. this.dataSource.pushArrayData(this.videoLocalList)
  5100. if(this.modeType==4&&this.playlistTable){
  5101. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5102. }
  5103. }
  5104. //瀑布流布局 支持双指缩放
  5105. @State columns: number = 2;
  5106. @State waterFlowScale: number = 1;
  5107. @State imageScale: number = 1;
  5108. @State waterFlowOpacity: number = 1;
  5109. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5110. private columnChanged: boolean = false;
  5111. private oldColumn: number = this.columns;
  5112. private pinchTime: number = 0;
  5113. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5114. changeColumns(scale: number): void {
  5115. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5116. this.columns--;
  5117. this.columnChanged = true;
  5118. } else if (scale < 1 && this.columns < 4) {
  5119. this.columns++;
  5120. this.columnChanged = true;
  5121. }
  5122. }
  5123. @Builder
  5124. getWaterView(){
  5125. Scroll(this.scroller) {
  5126. Column() {
  5127. Blank().height(this.topSafeHeight + 55)
  5128. WaterFlow({
  5129. scroller:this.waterScroller,
  5130. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5131. }) {
  5132. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5133. FlowItem() {
  5134. this.MusicWaterCardItem(item,index)
  5135. }
  5136. .width('100%')
  5137. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5138. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5139. {
  5140. preview: MenuPreviewMode.IMAGE
  5141. })
  5142. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5143. {
  5144. preview: MenuPreviewMode.IMAGE
  5145. })
  5146. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5147. }
  5148. // .columnsTemplate('repeat(auto-fit, 160)')
  5149. .id('waterflow') // 设置id用于截图
  5150. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5151. .columnsGap(12) // 列间距
  5152. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5153. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5154. .padding({bottom:this.bottomBarHeight+10})
  5155. .scrollBar(BarState.Off)
  5156. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5157. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5158. .edgeEffect(EdgeEffect.None)
  5159. .width('90%')
  5160. .height('100%')
  5161. .opacity(this.waterFlowOpacity)
  5162. .scale({
  5163. x: this.waterFlowScale,
  5164. y: this.waterFlowScale,
  5165. centerX: 0,
  5166. centerY: 0
  5167. })
  5168. .onReachEnd(() => {
  5169. if(this.modeType === 4 )
  5170. return;
  5171. // 触底加载下一页
  5172. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5173. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5174. return;
  5175. }
  5176. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5177. this.scheduleLoadNextPage();
  5178. }
  5179. })
  5180. .onAppear(() => {
  5181. this.scroller.scrollEdge(Edge.Top)
  5182. })
  5183. .nestedScroll({
  5184. scrollForward: NestedScrollMode.PARENT_FIRST,
  5185. scrollBackward: NestedScrollMode.SELF_FIRST
  5186. })
  5187. .priorityGesture(
  5188. PinchGesture()
  5189. .onActionStart((event: GestureEvent) => {
  5190. // 双指捏合手势识别成功时截图
  5191. this.pinchTime = event.timestamp;
  5192. this.columnChanged = false;
  5193. this.oldColumn = this.columns;
  5194. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5195. if (error) {
  5196. console.info('error:' + JSON.stringify(error));
  5197. return;
  5198. }
  5199. this.waterFlowSnapshot = pixmap;
  5200. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5201. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5202. if (this.oldColumn ===4) {
  5203. this.twoFingerType =3
  5204. this.isGridMusic = true
  5205. }else if (this.oldColumn ===1) {
  5206. this.twoFingerType =1
  5207. this.isGridMusic = false
  5208. }
  5209. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5210. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5211. return;
  5212. }
  5213. })
  5214. })
  5215. .onActionUpdate((event: GestureEvent) => {
  5216. // 手势更新:处理缩放逻辑和视觉效果
  5217. // 边界限制:防止超出列数范围时继续缩放
  5218. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5219. return;
  5220. }
  5221. // 节流处理:避免过于频繁的更新,提升性能
  5222. if (event.timestamp - this.pinchTime < 10000000) {
  5223. return;
  5224. }
  5225. this.pinchTime = event.timestamp;
  5226. this.waterFlowScale = event.scale;
  5227. this.imageScale = event.scale;
  5228. // 根据缩放比例设置WaterFlow透明度
  5229. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5230. this.waterFlowOpacity *= 3;
  5231. if (!this.columnChanged) {
  5232. this.changeColumns(event.scale);
  5233. }
  5234. // 列数改变后的缩放比例调整:避免出现空白区域
  5235. if (this.columnChanged) {
  5236. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5237. // 限制缩放范围,确保视觉效果自然
  5238. if (event.scale < 1) {
  5239. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5240. } else {
  5241. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5242. }
  5243. }
  5244. })
  5245. .onActionEnd((event: GestureEvent) => {
  5246. // 手势结束:执行归位动画并保存状态
  5247. // 执行归位动画:平滑过渡到正常状态
  5248. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5249. this.waterFlowScale = 1;
  5250. this.waterFlowOpacity = 1;
  5251. })
  5252. // 持久化保存当前列数:下次启动时恢复
  5253. PreferencesUtil.putSync('lastColumns', this.columns);
  5254. })
  5255. )
  5256. .onScrollFrameBegin((offset: number) => {
  5257. this.markGridWaterScrollingActive()
  5258. // 获取当前滚动偏移量
  5259. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5260. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  5261. this.updateTitleBarByScrollOffset(currentOffsetY)
  5262. return { offsetRemain: offset };
  5263. })
  5264. }
  5265. }
  5266. .scrollBar(BarState.Off)
  5267. }
  5268. //瀑布流卡片布局
  5269. @Builder
  5270. private MusicWaterCardItem(item: VideoItem, index: number) {
  5271. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5272. Stack() {
  5273. Column() {
  5274. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  5275. .backgroundImageSize(ImageSize.Auto)
  5276. .borderRadius({
  5277. topLeft: 12,
  5278. topRight : 12,
  5279. bottomLeft: 0,
  5280. bottomRight: 0
  5281. })
  5282. .draggable(false)// 禁止长按手势拖动
  5283. .autoResize(true) // 重采样,可减少内存占用
  5284. .sourceSize({
  5285. width: this.getCoverThumbTargetSize(true),
  5286. height: this.getCoverThumbTargetSize(true)
  5287. })
  5288. .width('100%')
  5289. .height('auto')
  5290. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5291. .objectFit(ImageFit.Cover)
  5292. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5293. height: '99%' ,
  5294. dragBar: true,
  5295. onDisappear: () => {
  5296. this.longItemFilePath = '';
  5297. this.tempLyricContent = ''
  5298. },
  5299. showClose: true,
  5300. preferType: SheetType.CENTER ,
  5301. title: { title: '编辑标签' }
  5302. })
  5303. .draggable(false)
  5304. .opacity(this.opacityItem)// 绑定透明度
  5305. .margin({
  5306. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5307. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5308. })
  5309. Column() {
  5310. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5311. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5312. .maxLines(1)
  5313. .fontWeight(FontWeight.Bold)
  5314. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5315. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5316. height: '95%',
  5317. dragBar: true,
  5318. showClose: true,
  5319. onDisappear: () => {
  5320. this.longItemFilePathDetail = '';
  5321. },
  5322. blurStyle:BlurStyle.Thin,
  5323. backgroundColor:Color.Transparent,
  5324. preferType: SheetType.CENTER ,
  5325. title: { title: '详情' }
  5326. })
  5327. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5328. $r('app.color.text_color'))
  5329. Column() {
  5330. Text(`${this.getArtistSongCount(item.name)}首`)
  5331. .fontSize(11)
  5332. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5333. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5334. .fontColor($r('app.color.text_color'))
  5335. Text(`${this.getAlbumSongCount(item.name)}首`)
  5336. .fontSize(11)
  5337. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5338. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5339. .fontColor($r('app.color.text_color'))
  5340. Row(){
  5341. Column(){
  5342. Text(item.md5Str?.includes('Lossless')?
  5343. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5344. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5345. .padding({ top: 3,right:6,left:6,bottom:3 })
  5346. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5347. $r('app.color.text_color'))
  5348. .fontWeight(500)
  5349. .borderRadius(12)
  5350. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5351. .backgroundColor('#FFC107')
  5352. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5353. }
  5354. .margin({ top: 2 ,right:6})
  5355. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5356. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5357. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5358. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5359. .maxLines(1)
  5360. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  5361. .margin({ top: 2})
  5362. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5363. || item.type == CommonConstants.TYPE_IS_ALBUM
  5364. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5365. .fontWeight(FontWeight.Medium)
  5366. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5367. $r('app.color.text_color'))
  5368. }
  5369. }
  5370. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5371. }
  5372. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5373. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5374. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5375. .width('100%')
  5376. .justifyContent(FlexAlign.Center)
  5377. .margin({
  5378. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5379. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5380. })
  5381. }
  5382. .width('100%')
  5383. .borderRadius(12)
  5384. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  5385. Checkbox({ name: 'checkbox' + index })
  5386. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5387. .selectedColor(this.themeColor)
  5388. .shape(CheckBoxShape.CIRCLE)
  5389. .opacity(this.isMultiSelect ? 1 : 0)
  5390. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5391. Visibility.None)
  5392. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5393. .margin({ left: 20, top: 8, bottom: 8 })
  5394. .width(38)
  5395. .height(38)
  5396. }
  5397. }
  5398. .backgroundColor(Color.Transparent)
  5399. .width('100%')
  5400. .height('auto')
  5401. .padding({top:2})
  5402. .shadow({
  5403. radius: this.isScrolling ? 0 : 8,
  5404. type: ShadowType.BLUR,
  5405. color: 'on_primary'
  5406. })
  5407. .reuseId('card_item')
  5408. .onClick(() => {
  5409. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5410. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5411. this.handleFileSelection(item, !isChecked);
  5412. } else {
  5413. this.doPlay(item, index)
  5414. }
  5415. })
  5416. }
  5417. // Grid布局的开始
  5418. private dragRefOffSetX: number = 0;
  5419. private dragRefOffSetY: number = 0;
  5420. private FIX_VP_X: number = 180;
  5421. private FIX_VP_Y: number = 84;
  5422. isDraggable(index: number): boolean {
  5423. return index >= 0;
  5424. }
  5425. getRowEnd(item: number) {
  5426. if (item.toString() === '0') {
  5427. return 1;
  5428. } else {
  5429. return 0;
  5430. }
  5431. }
  5432. isInLeft(index: number) {
  5433. return index % 2 == 0;
  5434. }
  5435. down(index: number): void {
  5436. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5437. return;
  5438. }
  5439. this.offsetY -= this.FIX_VP_Y;
  5440. this.dragRefOffSetY += this.FIX_VP_Y;
  5441. this.itemMove(index, index + 1);
  5442. }
  5443. up(index: number): void {
  5444. if (!this.isDraggable(index - 2)) {
  5445. return;
  5446. }
  5447. this.offsetY += this.FIX_VP_Y;
  5448. this.dragRefOffSetY -= this.FIX_VP_Y;
  5449. this.itemMove(index, index - 1);
  5450. }
  5451. left(index: number): void {
  5452. if (this.isInLeft(index)) {
  5453. return;
  5454. }
  5455. if (!this.isDraggable(index - 1)) {
  5456. return;
  5457. }
  5458. this.offsetX += this.FIX_VP_X;
  5459. this.dragRefOffSetX -= this.FIX_VP_X;
  5460. this.itemMove(index, index - 1)
  5461. }
  5462. right(index: number): void {
  5463. if (!this.isInLeft(index)) {
  5464. return;
  5465. }
  5466. if (!this.isDraggable(index + 1)) {
  5467. return;
  5468. }
  5469. this.offsetX -= this.FIX_VP_X;
  5470. this.dragRefOffSetX += this.FIX_VP_X;
  5471. this.itemMove(index, index + 1)
  5472. }
  5473. private scroller: Scroller = new Scroller();
  5474. private waterScroller: Scroller = new Scroller();
  5475. private startIndex: number = 0
  5476. private endIndex: number = 0
  5477. @State scaleValue: number = 1
  5478. @State pinchValue: number = 1
  5479. layoutOptionsForHeader: GridLayoutOptions = {
  5480. regularSize: [1, 1], // 只支持[1, 1]
  5481. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5482. };
  5483. @Builder
  5484. getGridView() {
  5485. Grid(this.scroller, this.layoutOptionsForHeader) {
  5486. GridItem() {
  5487. Column(){
  5488. Blank().height(this.topSafeHeight + 45)
  5489. }
  5490. }
  5491. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5492. GridItem() {
  5493. Stack({ alignContent: Alignment.Center }) {
  5494. this.MusicItemGrid(item, index)
  5495. }
  5496. }
  5497. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5498. {
  5499. preview: MenuPreviewMode.IMAGE
  5500. })
  5501. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5502. {
  5503. preview: MenuPreviewMode.IMAGE
  5504. })
  5505. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  5506. // TransitionEffect.scale({ x: 0, y: 0 })))
  5507. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5508. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5509. .zIndex(this.dragItem === index ? 1 : 0)
  5510. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5511. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5512. }
  5513. .width('94%')
  5514. .height('100%')
  5515. .editMode(true)
  5516. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5517. .reuseId('grid_item')
  5518. .layoutWeight(1)
  5519. .scrollBar(BarState.Off)
  5520. .supportAnimation(false)
  5521. .onReachEnd(() => {
  5522. if(this.modeType === 4 )
  5523. return;
  5524. // 触底加载下一页
  5525. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5526. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5527. return;
  5528. }
  5529. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5530. this.scheduleLoadNextPage();
  5531. }
  5532. })
  5533. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  5534. .columnsTemplate(
  5535. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5536. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5537. )
  5538. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5539. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5540. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5541. .gesture(PinchGesture({ fingers: 2 })
  5542. .onActionEnd((event: GestureEvent) => {
  5543. this.setGridTwoFingers()
  5544. })
  5545. .onActionUpdate(e => {
  5546. this.scaleValue = this.pinchValue * e.scale
  5547. })
  5548. .onActionStart(e => {
  5549. }))
  5550. .enableScrollInteraction(true)
  5551. .onScrollIndex((start: number, end: number) => {
  5552. this.startIndex = start
  5553. this.endIndex = end
  5554. this.gridVisibleStart = start
  5555. this.gridVisibleEnd = end
  5556. this.lastVisibleEndIndex = end
  5557. this.warmupGridWaterVisibleThumbs(start, end, false)
  5558. const now = Date.now()
  5559. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  5560. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  5561. this.gridScrollPagingCheckAt = now
  5562. this.gridScrollLastPagingEnd = end
  5563. this.tryTriggerLoadNextPageByScroll(end)
  5564. }
  5565. })
  5566. .onScrollFrameBegin((offset: number) => {
  5567. this.markGridWaterScrollingActive()
  5568. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5569. this.updateTitleBarByScrollOffset(currentOffsetY)
  5570. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5571. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5572. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5573. if (this.isScrollHide) {
  5574. this.setBarHeightHide2(offset)
  5575. } else {
  5576. this.setBarHeightNormal()
  5577. }
  5578. } else {
  5579. this.setBarHeightHide(offset)
  5580. }
  5581. return { offsetRemain: offset };
  5582. })
  5583. }
  5584. @State targetFile: string = '';
  5585. setGridTwoFingers() {
  5586. this.pinchValue = this.scaleValue;
  5587. Logger.info('this.pinchValue = ' + this.pinchValue);
  5588. if (this.pinchValue >= 1) {
  5589. this.twoFingerType++
  5590. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5591. if(this.twoFingerType >= 4){
  5592. this.twoFingerType = 4//切换成瀑布流
  5593. this.columns = 4
  5594. }
  5595. } else {
  5596. this.twoFingerType--
  5597. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5598. if (this.twoFingerType < 1) {
  5599. this.twoFingerType = 3
  5600. this.isGridMusic = false
  5601. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5602. }
  5603. }
  5604. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5605. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5606. this.pinchValue = 1;
  5607. this.scaleValue = 1;
  5608. }
  5609. @State longItemFilePath: string = ''
  5610. @State tempLyricContent: string = ''
  5611. @State editingItem: VideoItem | null = null
  5612. @Builder
  5613. private MusicItemGrid(item: VideoItem, index: number) {
  5614. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5615. Stack() {
  5616. Column() {
  5617. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  5618. .height(this.getGridHeight())
  5619. .width(this.getGridWight())
  5620. .draggable(false)
  5621. .autoResize(true) // 重采样,可减少内存占用
  5622. .sourceSize({
  5623. width: this.getCoverThumbTargetSize(false),
  5624. height: this.getCoverThumbTargetSize(false)
  5625. })
  5626. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5627. .clip(true)
  5628. .borderRadius({
  5629. topLeft: 12,
  5630. topRight: 12,
  5631. bottomLeft: 0,
  5632. bottomRight: 0
  5633. })
  5634. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5635. height: '99%' ,
  5636. dragBar: true,
  5637. onDisappear: () => {
  5638. this.longItemFilePath = '';
  5639. this.tempLyricContent = ''
  5640. },
  5641. showClose: true,
  5642. preferType: SheetType.CENTER ,
  5643. title: { title: '编辑标签' }
  5644. })
  5645. .draggable(false)
  5646. .opacity(this.opacityItem)// 绑定透明度
  5647. .margin({
  5648. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5649. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5650. })
  5651. Column() {
  5652. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  5653. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5654. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5655. .maxLines(1)
  5656. .fontWeight(FontWeight.Bold)
  5657. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5658. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5659. height: '100%',
  5660. dragBar: true,
  5661. showClose: true,
  5662. onDisappear: () => {
  5663. this.longItemFilePathDetail = '';
  5664. },
  5665. blurStyle:BlurStyle.Thin,
  5666. backgroundColor:Color.Transparent,
  5667. preferType: SheetType.CENTER ,
  5668. title: { title: '详情' }
  5669. })
  5670. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5671. $r('app.color.text_color'))
  5672. Column() {
  5673. Text(`${this.getArtistSongCount(item.name)}首`)
  5674. .fontSize(11)
  5675. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5676. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5677. .fontColor($r('app.color.text_color'))
  5678. Text(`${this.getAlbumSongCount(item.name)}首`)
  5679. .fontSize(11)
  5680. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5681. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5682. .fontColor($r('app.color.text_color'))
  5683. Row(){
  5684. Column(){
  5685. Text(item.md5Str?.includes('Lossless')?
  5686. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5687. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5688. .padding({ top: 3,right:6,left:6,bottom:3 })
  5689. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5690. $r('app.color.text_color'))
  5691. .fontWeight(500)
  5692. .borderRadius(12)
  5693. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5694. .backgroundColor('#FFC107')
  5695. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5696. }
  5697. .margin({ top: 2 ,right:6})
  5698. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5699. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5700. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5701. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5702. .maxLines(1)
  5703. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  5704. .margin({ top: 2})
  5705. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5706. || item.type == CommonConstants.TYPE_IS_ALBUM
  5707. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5708. .fontWeight(FontWeight.Medium)
  5709. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5710. $r('app.color.text_color'))
  5711. }
  5712. }
  5713. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5714. }
  5715. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5716. .width(this.getGridWight())
  5717. .justifyContent(FlexAlign.Center)
  5718. .margin({
  5719. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5720. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5721. })
  5722. }
  5723. .width(this.getGridWight())
  5724. .borderRadius(12)
  5725. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  5726. Checkbox({ name: 'checkbox' + index })
  5727. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5728. .selectedColor(this.themeColor)
  5729. .shape(CheckBoxShape.CIRCLE)
  5730. .opacity(this.isMultiSelect ? 1 : 0)
  5731. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5732. Visibility.None)
  5733. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5734. .margin({ left: 20, top: 8, bottom: 8 })
  5735. .width(38)
  5736. .height(38)
  5737. }
  5738. }
  5739. .backgroundColor(Color.Transparent)
  5740. .width('100%')
  5741. .padding({ top: 15 })
  5742. .height(this.getGridAllHeight())
  5743. .onClick(() => {
  5744. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5745. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5746. this.handleFileSelection(item, !isChecked);
  5747. } else {
  5748. this.doPlay(item, index)
  5749. }
  5750. })
  5751. }
  5752. getGridAllHeight() {
  5753. let heightG = 222
  5754. switch (this.twoFingerType) {
  5755. case 1:
  5756. heightG = 143
  5757. break;
  5758. case 2:
  5759. heightG = 178
  5760. break;
  5761. case 3:
  5762. heightG = 222
  5763. break;
  5764. }
  5765. return heightG
  5766. }
  5767. getGridHeight() {
  5768. let heightG = 150
  5769. switch (this.twoFingerType) {
  5770. case 1:
  5771. heightG = 80
  5772. break;
  5773. case 2:
  5774. heightG = 110
  5775. break;
  5776. case 3:
  5777. heightG = 150
  5778. break;
  5779. }
  5780. return heightG
  5781. }
  5782. getGridWight() {
  5783. let wightG = 158
  5784. switch (this.twoFingerType) {
  5785. case 1:
  5786. wightG = 80
  5787. break;
  5788. case 2:
  5789. wightG = 110
  5790. break;
  5791. case 3:
  5792. wightG = 158
  5793. break;
  5794. }
  5795. return wightG
  5796. }
  5797. @State isShowDetail:boolean = false
  5798. @State longItemFilePathDetail:string =''
  5799. @Builder
  5800. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5801. if(
  5802. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5803. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5804. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5805. ){
  5806. //如果是专辑和艺术家的首页,不能长按
  5807. //如果是我的收藏 最近播放等也不能长按
  5808. }else{
  5809. Scroll() {
  5810. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5811. Menu() {
  5812. MenuItem({
  5813. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5814. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5815. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5816. })
  5817. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5818. .onClick(() => {
  5819. if (item) {
  5820. this.doFav(item)
  5821. }
  5822. this.longItemFilePath = ''
  5823. })
  5824. MenuItem({
  5825. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5826. content: '下一首播放'
  5827. })
  5828. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5829. .onClick(() => {
  5830. this.addToNextPlay(item);
  5831. this.longItemFilePath = ''
  5832. })
  5833. MenuItem({
  5834. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5835. content: '添加到歌单'
  5836. })
  5837. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5838. .onClick(async () => {
  5839. this.longItemFilePath = ''
  5840. await this.openAddToPlaylistDialog(item)
  5841. })
  5842. MenuItem({
  5843. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5844. content: '编辑标签'
  5845. })
  5846. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5847. height: '99%',
  5848. dragBar: true,
  5849. showClose: true,
  5850. preferType: SheetType.CENTER ,
  5851. title: { title: '编辑标签' }
  5852. })
  5853. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5854. .onClick(async() => {
  5855. this.initEditFields(item)
  5856. this.tempLyricContent = await this.getLyricContent(item);
  5857. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5858. this.lyricConStr = this.tempLyricContent
  5859. }
  5860. if(this.isGridMusic||this.twoFingerType==4){
  5861. this.longItemFilePath = item.filePath
  5862. }else{
  5863. this.isShowEdit = !this.isShowEdit;
  5864. }
  5865. })
  5866. MenuItem({
  5867. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5868. content: $r('app.string.select_all')
  5869. })
  5870. .onClick(() => {
  5871. this.isMultiSelect = !this.isMultiSelect
  5872. this.longItemFilePath = ''
  5873. this.selectedFiles.push(item)
  5874. })
  5875. MenuItem({
  5876. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5877. content: $r('app.string.edit_audio')
  5878. })
  5879. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5880. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5881. })
  5882. .onClick(() => {
  5883. this.isEditAudio = !this.isEditAudio
  5884. })
  5885. MenuItem({
  5886. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5887. content: $r('app.string.extract_accompaniment')
  5888. })
  5889. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5890. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5891. })
  5892. .onClick(() => {
  5893. if (!Utility.isNoble()) {
  5894. this.showVipDialog()
  5895. return
  5896. }
  5897. this.isExtractAcc = !this.isExtractAcc
  5898. })
  5899. MenuItem({
  5900. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5901. content: $r('app.string.converter_audio')
  5902. })
  5903. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5904. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5905. })
  5906. .onClick(() => {
  5907. if (!Utility.isNoble()) {
  5908. this.showVipDialog()
  5909. return
  5910. }
  5911. this.isConverter = !this.isConverter
  5912. })
  5913. // MenuItem({
  5914. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5915. // content: $r('app.string.vocal_separation')
  5916. // })
  5917. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5918. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5919. // })
  5920. // .onClick(() => {
  5921. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5922. // })
  5923. MenuItem({
  5924. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5925. content: $r('app.string.change_tone')
  5926. })
  5927. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5928. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5929. })
  5930. .onClick(() => {
  5931. this.isChangeTone = !this.isChangeTone
  5932. })
  5933. if(Utility.isVideoByExtension(item.filePath)){
  5934. MenuItem({
  5935. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5936. content: $r('app.string.extract_audio')
  5937. })
  5938. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5939. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5940. })
  5941. .onClick(() => {
  5942. this.isExtractAudio = !this.isExtractAudio
  5943. })
  5944. }
  5945. MenuItem({
  5946. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5947. content: $r('app.string.set_ring')
  5948. })
  5949. .onClick(async () => {
  5950. await PermissionUtil.activatePermission(item.filePath)
  5951. // if(item.filePath.includes(this.packName)){
  5952. setRingTone(this.context, item.filePath,item.name)
  5953. // }else{
  5954. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5955. // }
  5956. this.longItemFilePath = ''
  5957. })
  5958. MenuItem({
  5959. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5960. content: $r('app.string.rename')
  5961. })
  5962. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5963. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5964. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5965. .onClick(() => {
  5966. this.showReNameDialog(item, index + '', filePath)
  5967. this.longItemFilePath = ''
  5968. })
  5969. MenuItem({
  5970. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5971. content: $r('app.string.delete')
  5972. })
  5973. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5974. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5975. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5976. .onClick(() => {
  5977. this.selectedFiles.push(item)
  5978. this.showWarnIsDelete()
  5979. this.longItemFilePath = ''
  5980. })
  5981. MenuItem({
  5982. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5983. content: $r('app.string.detail')
  5984. })
  5985. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5986. height:'100%',
  5987. dragBar: true,
  5988. showClose: true,
  5989. blurStyle:BlurStyle.Thin,
  5990. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5991. backgroundColor:Color.Transparent,
  5992. title: { title: '详情信息' }
  5993. })
  5994. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5995. .onClick(() => {
  5996. if(this.isGridMusic||this.twoFingerType==4){
  5997. this.longItemFilePathDetail = item.filePath
  5998. }else{
  5999. this.isShowDetail = !this.isShowDetail
  6000. }
  6001. })
  6002. MenuItem({
  6003. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6004. content: $r('app.string.share')
  6005. })
  6006. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6007. .onClick(() => {
  6008. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6009. this.longItemFilePath = ''
  6010. })
  6011. }
  6012. .font({ size: 14, weight: FontWeight.Normal })
  6013. }
  6014. .width(180)
  6015. }
  6016. .height('auto')
  6017. .enableScrollInteraction(true)
  6018. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6019. }
  6020. }
  6021. private listMaxScrollOffsetY: number = 0
  6022. private selectedIndex: number = -1
  6023. setlistTwoFingers() {
  6024. this.pinchValue = this.scaleValue;
  6025. Logger.info('this.pinchValue = ' + this.pinchValue);
  6026. if (this.pinchValue >= 1) {
  6027. this.twoFingerType++
  6028. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6029. if (this.twoFingerType > 3) {
  6030. this.twoFingerType = 1
  6031. this.isGridMusic = true
  6032. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6033. }
  6034. } else {
  6035. this.twoFingerType--
  6036. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6037. if (this.twoFingerType < 1) {
  6038. this.twoFingerType = 4
  6039. this.columns = 1
  6040. }
  6041. }
  6042. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6043. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6044. this.pinchValue = 1;
  6045. this.scaleValue = 1;
  6046. }
  6047. @Builder
  6048. getList(){
  6049. Stack() {
  6050. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6051. this.getListView()
  6052. }
  6053. .pullDownRatio(this.ratioL)
  6054. .pullToRefresh(true)
  6055. .refreshOffset(0)
  6056. .onOffsetChange((offset: number) => {
  6057. // 越接近最大距离,下拉跟手系数越小。
  6058. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6059. })
  6060. .onStateChange((refreshStatus: RefreshStatus) => {
  6061. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6062. })
  6063. .onRefreshing(async () => {
  6064. if(this.modeType==0){
  6065. this.getHistoryList(false)
  6066. this.asyncCurrentPathOnlyFile()
  6067. }else if(this.modeType == 1){
  6068. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6069. }else if(this.modeType == 2){
  6070. workerInstance.postMessage({ code: 3, data: this.context });
  6071. }else if(this.modeType == 3){
  6072. workerInstance.postMessage({ code: 4, data: this.context });
  6073. }else if(this.modeType == 4){
  6074. this.doSongListTask()
  6075. }
  6076. console.log('onRefreshing test');
  6077. })
  6078. if (this.isLoadingPage) {
  6079. Row() {
  6080. LoadingProgress()
  6081. .width(24)
  6082. .height(24)
  6083. .color(this.themeColor)
  6084. Text('加载中...')
  6085. .margin({ left: 8 })
  6086. .fontSize(13)
  6087. .fontColor($r('app.color.text_color'))
  6088. }
  6089. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6090. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6091. .borderRadius(16)
  6092. .align(Alignment.Bottom)
  6093. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6094. }
  6095. }
  6096. }
  6097. // 扫描当前目录下的文件,不扫描子目录
  6098. asyncCurrentPathOnlyFile(){
  6099. if(this.modeType==0){
  6100. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6101. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6102. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6103. if(this.modeType==0){
  6104. setTimeout(()=>{
  6105. this.isRefreshing =false
  6106. this.deleteCache(this.currentPath)
  6107. this.getSortedFiles(this.currentPath)
  6108. },500)
  6109. }
  6110. }).catch((e:object)=>{
  6111. this.isRefreshing =false
  6112. console.info("onecold task1 catch e: " + e);
  6113. })
  6114. }
  6115. }
  6116. @Builder
  6117. getListView() {
  6118. List({ scroller: this.listScroller }) {
  6119. // ListItemGroup({ header: this.coverHeader() }) {
  6120. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6121. ListItem() {
  6122. Column() {
  6123. if (item.type === CommonConstants.TYPE_IS_DIR
  6124. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6125. this.DirItem(item, index)
  6126. } else {
  6127. this.MusicItem(item, index)
  6128. }
  6129. }
  6130. }
  6131. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6132. .swipeAction((
  6133. ((this.isSwipe && !this.isScrolling) &&
  6134. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6135. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6136. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6137. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6138. .onClick(() => {
  6139. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  6140. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  6141. this.handleFileSelection(item, !isChecked);
  6142. } else {
  6143. this.doPlay(item, index)
  6144. }
  6145. })
  6146. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6147. }
  6148. .onScrollStart(() => {
  6149. this.isScrolling = true
  6150. this.listVisibleStart = -1
  6151. this.listVisibleEnd = -1
  6152. this.listScrollAlphaCheckAt = 0
  6153. this.listScrollPagingCheckAt = 0
  6154. this.listScrollLastAlphaStart = -1
  6155. this.listScrollLastPagingEnd = -1
  6156. if (this.alphaBetRebuildTimer) {
  6157. clearTimeout(this.alphaBetRebuildTimer)
  6158. this.alphaBetRebuildTimer = 0
  6159. }
  6160. this.showAlphabetIndex()
  6161. })
  6162. .onScrollIndex((start: number,center:number,end:number) => {
  6163. this.selectedIndex = start
  6164. this.listVisibleStart = start
  6165. this.listVisibleEnd = end
  6166. this.lastVisibleEndIndex = end
  6167. if (!this.isMediaLibraryWarmupWindow()) {
  6168. this.warmupListVisibleThumbs(start, end)
  6169. }
  6170. const now = Date.now()
  6171. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  6172. if (!this.isMediaLibraryWarmupWindow() &&
  6173. start >= 0 && start < this.videoLocalList.length &&
  6174. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  6175. this.listScrollAlphaCheckAt = now
  6176. this.listScrollLastAlphaStart = start
  6177. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6178. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  6179. this.selectAlphaBetIndex = nextAlphaIndex
  6180. }
  6181. }
  6182. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  6183. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  6184. this.listScrollPagingCheckAt = now
  6185. this.listScrollLastPagingEnd = end
  6186. this.tryTriggerLoadNextPageByScroll(end)
  6187. }
  6188. })
  6189. .onScrollStop(() => {
  6190. if(this.isScrolling){
  6191. this.isScrolling = false
  6192. }
  6193. this.flushPendingCoverThumbRefresh()
  6194. if (this.alphaBetDirty) {
  6195. this.scheduleAlphaBetRebuild(0)
  6196. }
  6197. this.hideAlphabetIndexAfterDelay(1500)
  6198. })
  6199. .onReachEnd(() => {
  6200. if(this.modeType === 4 )//歌单不能加载下一页
  6201. return;
  6202. // 触底加载下一页
  6203. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6204. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6205. return;
  6206. }
  6207. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6208. this.scheduleLoadNextPage();
  6209. }
  6210. })
  6211. .scrollBar(BarState.Off)
  6212. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6213. .gesture(PinchGesture({ fingers: 2 })
  6214. .onActionEnd((event: GestureEvent) => {
  6215. this.setlistTwoFingers()
  6216. })
  6217. .onActionUpdate(e => {
  6218. this.scaleValue = this.pinchValue * e.scale
  6219. })
  6220. .onActionStart(e => {
  6221. }))
  6222. .contentStartOffset(this.topSafeHeight + 55)
  6223. .scrollBar(BarState.Off)
  6224. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6225. .cachedCount(this.modeType == 1 ? 4 : 8)
  6226. // .reuseId('list_item')
  6227. .borderRadius(20)
  6228. .layoutWeight(1)
  6229. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6230. .lanes(
  6231. new BreakpointType<number>({
  6232. sm: 1,
  6233. md: 2,
  6234. lg: 2,
  6235. xl: 3,
  6236. xxl: 4
  6237. }).getValue(this.currentBreakpoint),
  6238. new BreakpointType<number>({
  6239. sm: 0,
  6240. md: 12,
  6241. lg: 12,
  6242. xl: 16,
  6243. xxl: 20
  6244. }).getValue(this.currentBreakpoint)
  6245. )
  6246. .onAreaChange((oldValue: Area, newValue: Area) => {
  6247. this.listArea = newValue
  6248. if (this.twoFingerType == 3) {
  6249. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6250. } else if (this.twoFingerType == 2) {
  6251. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6252. } else if (this.twoFingerType == 1) {
  6253. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6254. }
  6255. })
  6256. .onScrollFrameBegin((offset: number) => {
  6257. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6258. this.updateTitleBarByScrollOffset(currentOffsetY)
  6259. return { offsetRemain: offset };
  6260. })
  6261. }
  6262. setBarHeightNormal() {
  6263. this.hideDone = false;
  6264. this.getUIContext().animateTo({
  6265. duration: 300
  6266. }, () => {
  6267. this.bottomBarHeight = 68 + 0;
  6268. this.topBarHeight = 50 + 0;
  6269. this.barOpacity = 1;
  6270. this.barBottomOpacity = 1
  6271. this.currentYOffset = 0;
  6272. this.isHiding = false;
  6273. });
  6274. }
  6275. setBarHeightHide(offset: number) {
  6276. if (offset > 0 && !this.hideDone) {
  6277. this.currentYOffset += offset;
  6278. if (this.currentYOffset <= 100) {
  6279. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6280. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6281. this.barOpacity = 1 - this.currentYOffset / 100;
  6282. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6283. } else {
  6284. this.topBarHeight = 0;
  6285. this.bottomBarHeight = 0;
  6286. this.barBottomOpacity = 0
  6287. this.barOpacity = 0;
  6288. this.hideDone = true;
  6289. }
  6290. this.isHiding = true;
  6291. }
  6292. if (offset < 0 && this.isHiding) {
  6293. this.hideDone = false;
  6294. this.getUIContext().animateTo({
  6295. duration: 300
  6296. }, () => {
  6297. this.bottomBarHeight = 68 + 0;
  6298. this.topBarHeight = 50 + 0;
  6299. this.barOpacity = 1;
  6300. this.barBottomOpacity = 1
  6301. this.currentYOffset = 0;
  6302. this.isHiding = false;
  6303. });
  6304. }
  6305. }
  6306. //这个方法没隐藏bottomBar,只隐藏topbar
  6307. setBarHeightHide2(offset: number) {
  6308. if (offset > 0 && !this.hideDone) {
  6309. this.currentYOffset += offset;
  6310. if (this.currentYOffset <= 100) {
  6311. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6312. this.barOpacity = 1 - this.currentYOffset / 100;
  6313. } else {
  6314. this.topBarHeight = 0;
  6315. this.barOpacity = 0;
  6316. this.hideDone = true;
  6317. }
  6318. this.isHiding = true;
  6319. }
  6320. if (offset < 0 && this.isHiding) {
  6321. this.hideDone = false;
  6322. this.getUIContext().animateTo({
  6323. duration: 300
  6324. }, () => {
  6325. this.topBarHeight = 50 + 0;
  6326. this.barOpacity = 1;
  6327. this.currentYOffset = 0;
  6328. this.isHiding = false;
  6329. });
  6330. }
  6331. }
  6332. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6333. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6334. switch (item.type) {
  6335. case CommonConstants.TYPE_IS_DIR:
  6336. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6337. let shouldScrollTopNow = true
  6338. let offsetB = 0
  6339. if(this.twoFingerType==4){
  6340. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6341. let cur = this.waterScroller.currentOffset()
  6342. if (cur && typeof cur.yOffset === 'number') {
  6343. offsetB = cur.yOffset
  6344. }
  6345. }
  6346. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6347. }else
  6348. if (this.isGridMusic) {
  6349. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6350. let cur = this.scroller.currentOffset()
  6351. if (cur && typeof cur.yOffset === 'number') {
  6352. offsetB = cur.yOffset
  6353. }
  6354. }
  6355. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6356. } else {
  6357. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6358. let cur = this.listScroller.currentOffset()
  6359. if (cur && typeof cur.yOffset === 'number') {
  6360. offsetB = cur.yOffset
  6361. }
  6362. }
  6363. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6364. }
  6365. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6366. this.showVerifyDialog()
  6367. this.currentTitleName = '私密音频'
  6368. this.currentTitleCover = $r('app.media.alt')
  6369. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6370. this.titleName = '最近播放'
  6371. this.currentTitleCover = $r('app.media.alt')
  6372. this.currentTitleName = '最近播放'
  6373. //加载动画效果
  6374. this.updateListData(this.historyList, true)
  6375. // this.videoLocalList = this.historyList
  6376. if (ArrayUtil.isEmpty(this.historyList)) {
  6377. ToastUtil.showToast('最近播放记录空空如也')
  6378. } else {
  6379. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6380. }
  6381. this.isHistory = true
  6382. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6383. this.titleName = '我的收藏'
  6384. this.currentTitleName = '我的收藏'
  6385. this.currentTitleCover = $r('app.media.alt')
  6386. //加载动画效果
  6387. this.updateListData(this.favList, true)
  6388. if (ArrayUtil.isEmpty(this.favList)) {
  6389. ToastUtil.showToast('无音乐收藏记录')
  6390. } else {
  6391. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6392. }
  6393. this.isFavMusic = true
  6394. } else {
  6395. this.currentTitleName = item.name
  6396. this.currentPath = item.filePath
  6397. this.currentTitleCover = $r('app.media.alt')
  6398. shouldScrollTopNow = false
  6399. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  6400. }
  6401. //进入歌单的时候的滚动位置在顶部
  6402. if (shouldScrollTopNow) {
  6403. if(this.twoFingerType==4){
  6404. setTimeout(() => {
  6405. this.waterScroller.scrollEdge(Edge.Top)
  6406. this.scroller.scrollEdge(Edge.Top)
  6407. }, 200)
  6408. }else{
  6409. if (this.isGridMusic) {
  6410. this.scroller.scrollToIndex(0,false)
  6411. }else{
  6412. this.listScroller.scrollToIndex(0,false)
  6413. }
  6414. }
  6415. }
  6416. this.rightTopImage = $r('sys.symbol.chevron_left')
  6417. break;
  6418. case CommonConstants.TYPE_IS_ARTIST:
  6419. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6420. let offsetA = 0
  6421. if(this.twoFingerType==4){
  6422. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6423. let cur = this.waterScroller.currentOffset()
  6424. if (cur && typeof cur.yOffset === 'number') {
  6425. offsetA = cur.yOffset
  6426. }
  6427. }
  6428. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6429. }else
  6430. if (this.isGridMusic) {
  6431. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6432. let cur = this.scroller.currentOffset()
  6433. if (cur && typeof cur.yOffset === 'number') {
  6434. offsetA = cur.yOffset
  6435. }
  6436. }
  6437. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6438. } else {
  6439. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6440. let cur = this.listScroller.currentOffset()
  6441. if (cur && typeof cur.yOffset === 'number') {
  6442. offsetA = cur.yOffset
  6443. }
  6444. }
  6445. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6446. }
  6447. // 进入艺术家详情页前,先加载详情页的排序类型
  6448. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6449. const artistOriginalIsCanBack = this.isCanBack;
  6450. this.isCanBack = true;
  6451. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  6452. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  6453. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  6454. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6455. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  6456. let mList = this.artistMap.get(artistCacheKey)
  6457. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  6458. // 使用详情页的排序类型查询
  6459. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  6460. if (ArrayUtil.isNotEmpty(mList)) {
  6461. this.artistMap.set(artistCacheKey, mList);
  6462. }
  6463. }
  6464. // 设置当前排序类型为详情页排序
  6465. this.sortType = artistDetailSortType;
  6466. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6467. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  6468. const nextArtistCountMap = new Map(this.artistSongCountMap);
  6469. nextArtistCountMap.set(item.name, mList.length);
  6470. this.artistSongCountMap = nextArtistCountMap;
  6471. this.isCanBack = true
  6472. this.hasMoreData = false
  6473. this.isLoadingPage = false
  6474. this.pageCache.clear()
  6475. this.pageHasMoreCache.clear()
  6476. this.pageTotalCountCache.clear()
  6477. this.prefetchingPages.clear()
  6478. this.lastScrollTriggerPage = -1
  6479. this.lastVisibleEndIndex = -1
  6480. this.isPagingTransition = false
  6481. if (this.pagingScheduleTimer) {
  6482. clearTimeout(this.pagingScheduleTimer)
  6483. this.pagingScheduleTimer = 0
  6484. }
  6485. this.totalCount = mList.length
  6486. this.titleName = item.name
  6487. this.currentTitleName = '艺术家:' + item.name
  6488. if (item.pixelMapPath) {
  6489. this.currentTitleCover = item.pixelMapPath
  6490. }
  6491. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  6492. } else {
  6493. ToastUtil.showToast('未找到该艺术家的歌曲');
  6494. return;
  6495. }
  6496. this.rightTopImage = $r('sys.symbol.chevron_left')
  6497. //进入歌单的时候的滚动位置在顶部
  6498. if(this.twoFingerType==4){
  6499. setTimeout(() => {
  6500. this.waterScroller.scrollEdge(Edge.Top)
  6501. this.scroller.scrollEdge(Edge.Top)
  6502. }, 380)
  6503. }else{
  6504. if (this.isGridMusic) {
  6505. this.scroller.scrollEdge(Edge.Top)
  6506. }else{
  6507. this.listScroller.scrollEdge(Edge.Top)
  6508. }
  6509. }
  6510. break;
  6511. case CommonConstants.TYPE_IS_ALBUM:
  6512. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6513. let offset = 0
  6514. if(this.twoFingerType==4){
  6515. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6516. let cur = this.waterScroller.currentOffset()
  6517. if (cur && typeof cur.yOffset === 'number') {
  6518. offset = cur.yOffset
  6519. }
  6520. }
  6521. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6522. }else
  6523. if (this.isGridMusic) {
  6524. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6525. let cur = this.scroller.currentOffset()
  6526. if (cur && typeof cur.yOffset === 'number') {
  6527. offset = cur.yOffset
  6528. }
  6529. }
  6530. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6531. } else {
  6532. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6533. let cur = this.listScroller.currentOffset()
  6534. if (cur && typeof cur.yOffset === 'number') {
  6535. offset = cur.yOffset
  6536. }
  6537. }
  6538. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6539. }
  6540. // 进入专辑详情页前,先加载详情页的排序类型
  6541. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6542. const albumOriginalIsCanBack = this.isCanBack;
  6543. this.isCanBack = true;
  6544. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  6545. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  6546. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  6547. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6548. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  6549. let albumList = this.albumMap.get(albumCacheKey)
  6550. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  6551. // 使用详情页的排序类型查询
  6552. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  6553. if (ArrayUtil.isNotEmpty(albumList)) {
  6554. this.albumMap.set(albumCacheKey, albumList);
  6555. }
  6556. }
  6557. // 设置当前排序类型为详情页排序
  6558. this.sortType = albumDetailSortType;
  6559. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6560. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  6561. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  6562. nextAlbumCountMap.set(item.name, albumList.length);
  6563. this.albumSongCountMap = nextAlbumCountMap;
  6564. this.isCanBack = true
  6565. this.hasMoreData = false
  6566. this.isLoadingPage = false
  6567. this.pageCache.clear()
  6568. this.pageHasMoreCache.clear()
  6569. this.pageTotalCountCache.clear()
  6570. this.prefetchingPages.clear()
  6571. this.lastScrollTriggerPage = -1
  6572. this.lastVisibleEndIndex = -1
  6573. this.isPagingTransition = false
  6574. if (this.pagingScheduleTimer) {
  6575. clearTimeout(this.pagingScheduleTimer)
  6576. this.pagingScheduleTimer = 0
  6577. }
  6578. this.totalCount = albumList.length
  6579. this.titleName = item.name
  6580. this.currentTitleName = '专辑:' + item.name
  6581. if (item.pixelMapPath) {
  6582. this.currentTitleCover = item.pixelMapPath
  6583. }
  6584. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  6585. this.mScrollMap.set(item.name, this.selectedIndex)
  6586. this.rightTopImage = $r('sys.symbol.chevron_left')
  6587. } else {
  6588. ToastUtil.showToast('未找到该专辑的歌曲');
  6589. return;
  6590. }
  6591. //进入歌单的时候的滚动位置在顶部
  6592. if(this.twoFingerType==4){
  6593. setTimeout(() => {
  6594. this.waterScroller.scrollEdge(Edge.Top)
  6595. this.scroller.scrollEdge(Edge.Top)
  6596. }, 380)
  6597. }else{
  6598. if (this.isGridMusic) {
  6599. this.scroller.scrollEdge(Edge.Top)
  6600. }else{
  6601. this.listScroller.scrollEdge(Edge.Top)
  6602. }
  6603. }
  6604. break;
  6605. case CommonConstants.TYPE_IS_CSJAD:
  6606. return
  6607. break;
  6608. case CommonConstants.TYPE_LOCAL:
  6609. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6610. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6611. const cueTracks:CueTrack[] = cueinfo.tracks
  6612. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6613. if(ArrayUtil.isNotEmpty(cueTracks)){
  6614. this.showCueDialog(cueTracks,cueinfo)
  6615. }
  6616. // this.showCueSheet = !this.showCueSheet
  6617. return
  6618. }
  6619. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6620. this.stop();
  6621. }
  6622. if (isOpen) {
  6623. this.currentSong = item
  6624. if (index !== undefined) {
  6625. this.curIndex = index
  6626. }
  6627. this.songList = []
  6628. this.songList.push(item)
  6629. this.sonDataSource.pushArrayData(this.songList)
  6630. this.playQueueScope = 'single'
  6631. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6632. this.currentSong = item
  6633. if (index !== undefined) {
  6634. this.curIndex = index
  6635. }
  6636. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6637. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6638. this.playQueueScope = 'playlist'
  6639. // 确保歌单路径列表已设置(从songList重新构建,以防被清空)
  6640. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  6641. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  6642. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6643. }
  6644. }else {
  6645. const globalVideoList = this.buildPlayQueueFromView();
  6646. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6647. if (this.curIndex < 0) {
  6648. globalVideoList.push(item);
  6649. this.curIndex = globalVideoList.length - 1;
  6650. }
  6651. this.songList = globalVideoList
  6652. this.sonDataSource.pushArrayData(this.songList)
  6653. this.currentSong = this.songList[this.curIndex]
  6654. // 只在非歌单模式下清空歌单路径列表
  6655. if (this.modeType !== 4) {
  6656. this.currentPlaylistSongFilePaths = [];
  6657. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  6658. } else {
  6659. // 歌单模式:确保歌单路径列表已设置
  6660. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  6661. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  6662. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6663. } else {
  6664. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6665. }
  6666. }
  6667. }
  6668. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6669. this.videoUrl = this.currentSong.filePath
  6670. this.name = this.currentSong.name
  6671. this.cover = this.currentSong.pixelMapPath
  6672. this.artist = this.currentSong.artist
  6673. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6674. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6675. this.startPlayOrResumePlay()
  6676. break;
  6677. case CommonConstants.TYPE_WEBDAV:
  6678. case CommonConstants.TYPE_SMB:
  6679. case CommonConstants.TYPE_NAVIDROME:
  6680. case CommonConstants.TYPE_FTP:
  6681. case CommonConstants.TYPE_BAIDU:
  6682. case CommonConstants.TYPE_JELLYFIN:
  6683. case CommonConstants.TYPE_EMBY:
  6684. case CommonConstants.TYPE_AUDIOSTATION:
  6685. case CommonConstants.TYPE_PLEX:
  6686. case CommonConstants.TYPE_DAOLIYU:
  6687. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  6688. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6689. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6690. this.stop();
  6691. }
  6692. if (isOpen) {
  6693. this.currentSong = item
  6694. if (index !== undefined) {
  6695. this.curIndex = index
  6696. }
  6697. this.songList = []
  6698. this.songList.push(item)
  6699. this.sonDataSource.pushArrayData(this.songList)
  6700. } else if (isFromSonPlayList) {
  6701. // 点击来自右下角的播放列表
  6702. this.currentSong = item
  6703. if (index !== undefined) {
  6704. this.curIndex = index
  6705. }
  6706. // 设置播放队列作用域为歌单
  6707. this.playQueueScope = 'playlist'
  6708. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6709. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  6710. } else {
  6711. // 从全局网络音频列表中查找
  6712. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6713. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6714. if (this.curIndex === -1 && index !== undefined) {
  6715. this.curIndex = index;
  6716. }
  6717. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6718. this.currentSong = this.songList[this.curIndex];
  6719. this.sonDataSource.pushArrayData(this.songList)
  6720. }
  6721. await this.hydrateRemoteSongFromDb(this.currentSong);
  6722. await this.hydrateRemoteSongFromDb(this.currentSong);
  6723. AppStorage.setOrCreate('currentSong', this.currentSong);
  6724. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6725. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6726. context: this.context,
  6727. autoParseMusicName: this.autoParseMusicName
  6728. });
  6729. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6730. this.name = this.currentSong.name
  6731. this.cover = this.currentSong.pixelMapPath
  6732. this.artist = this.currentSong.artist
  6733. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6734. this.startPlayOrResumePlay()
  6735. break;
  6736. }
  6737. }
  6738. private cueComponentId: number = 0
  6739. //显示cue分轨列表对话框
  6740. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6741. this.getUIContext().getPromptAction().openCustomDialog({
  6742. builder: () => {
  6743. this.cueComptentBuilder(cueTracks,cueinfo)
  6744. },
  6745. isModal:true,
  6746. showInSubWindow:false,
  6747. maskColor: Color.Transparent,
  6748. dialogTransition: // 设置弹窗内容显示的过渡效果
  6749. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6750. .animation({ duration: 600, curve: Curve.Smooth }),
  6751. maskTransition: // 设置蒙层显示的过渡效果
  6752. TransitionEffect.opacity(0.5)
  6753. .animation({ duration: 600, curve: Curve.Smooth })
  6754. }).then((dialogId: number) => {
  6755. this.cueComponentId = dialogId
  6756. })
  6757. .catch((error: BusinessError) => {
  6758. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6759. })
  6760. }
  6761. @Builder
  6762. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6763. CueComptent({
  6764. title:cueinfo.title,
  6765. cueTracks:cueTracks,
  6766. isLongNameRoLL:this.isLongNameRoLL,
  6767. onCancel:()=>{
  6768. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6769. },
  6770. onDoItemClick: async (item: CueTrack, index: number)=>{
  6771. //获取cueinfo对应的filePath
  6772. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6773. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6774. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6775. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6776. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6777. if (this.currentSong){
  6778. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6779. this.stop();//播放之前先停止之前播放。
  6780. }
  6781. this.songList = globalVideoList
  6782. this.sonDataSource.pushArrayData(this.songList)
  6783. if (this.currentSong) {
  6784. try {
  6785. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6786. context: this.context,
  6787. autoParseMusicName: this.autoParseMusicName
  6788. });
  6789. } catch (error) {
  6790. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6791. this.videoUrl = this.currentSong.filePath;
  6792. }
  6793. }
  6794. this.name = item.title||this.currentSong.name
  6795. this.cover = this.currentSong.pixelMapPath
  6796. this.artist = item.performer||this.currentSong.artist
  6797. this.currentSong.name = this.name
  6798. this.currentSong.artist = this.artist
  6799. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6800. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6801. }
  6802. }
  6803. })
  6804. }
  6805. @State isFrontWhite: boolean = false
  6806. setShowPlayTrue(){
  6807. this.getUIContext()?.animateTo({
  6808. duration: 500,
  6809. curve: Curve.Friction
  6810. }, () => {
  6811. this.isShowPlay = true;
  6812. });
  6813. }
  6814. setShowPlayFalse(){
  6815. this.getUIContext()?.animateTo({
  6816. duration: 500,
  6817. curve: Curve.Friction
  6818. }, () => {
  6819. this.isShowPlay = false;
  6820. });
  6821. }
  6822. //打开播放页
  6823. showPlayerView() {
  6824. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6825. if (ArrayUtil.isNotEmpty(this.songList)) {
  6826. // this.setShowPlayTrue()
  6827. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6828. this.initLyric(lyricPath);
  6829. this.startAutoHide();
  6830. } else {
  6831. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6832. }
  6833. }
  6834. //打开播放列表
  6835. openPlayList(){
  6836. if (ArrayUtil.isNotEmpty(this.songList)) {
  6837. this.isShowSheet = !this.isShowSheet;
  6838. this.isFrontWhite = false
  6839. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6840. this.scrollIndex()
  6841. // 只有在播放本地音乐时才自动加载完整列表
  6842. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  6843. void this.hydrateFullMediaPlayListIfNeeded();
  6844. }
  6845. } else {
  6846. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6847. }
  6848. }
  6849. scrollIndex(){
  6850. try {
  6851. setTimeout(() => {
  6852. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6853. if(this.curIndex>60){
  6854. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6855. }else{
  6856. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6857. }
  6858. })
  6859. }, 123)
  6860. }catch (error) {
  6861. console.error(`onecold scrollIndex出错: ${error}`);
  6862. }
  6863. }
  6864. scrollIndexMain(dialogId?:string){
  6865. try {
  6866. setTimeout(() => {
  6867. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6868. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  6869. if(dialogId)
  6870. DialogHelper.closeDialog(dialogId)
  6871. let isAni:boolean = false
  6872. if(this.curIndex<50){
  6873. isAni = true
  6874. }
  6875. if(this.twoFingerType==4){
  6876. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6877. }else{
  6878. if(this.isGridMusic){
  6879. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6880. }else{
  6881. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6882. }
  6883. }
  6884. })
  6885. }, 123)
  6886. }catch (error) {
  6887. console.error(`onecold scrollIndexMain出错: ${error}`);
  6888. }
  6889. }
  6890. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  6891. async locateCurrentSong(): Promise<void> {
  6892. if (!this.currentSong) {
  6893. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  6894. return;
  6895. }
  6896. // 检查当前播放歌曲是否在已加载的列表中
  6897. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6898. if (targetIndex > 0) {
  6899. // 歌曲在当前列表中,直接滚动
  6900. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  6901. this.curIndex = targetIndex;
  6902. this.scrollIndexMain();
  6903. } else {
  6904. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  6905. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  6906. const dialogID = DialogHelper.showLoadingDialog()
  6907. await this.hydrateFullMediaPlayListIfNeeded(false);
  6908. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6909. this.scrollIndexMain(dialogID);
  6910. }
  6911. }
  6912. //播放列表布局
  6913. @Builder
  6914. PlayListSheet() {
  6915. Column() {
  6916. this.PlayList()
  6917. }
  6918. .width('100%')
  6919. .height('100%')
  6920. }
  6921. @State titleStr: string = ''
  6922. @State ablumStr: string = ''
  6923. @State artistStr: string = ''
  6924. @State lyricConStr: string = ''
  6925. @State currentEditItem: string = ''
  6926. @State yearStr: string = ''
  6927. @State trackStr: string = ''
  6928. @State genreStr: string = ''
  6929. @State imagePathStr: string = ''
  6930. @State albumArtistStr: string = ''
  6931. @State composerStr: string = ''
  6932. @State lyricistStr: string = ''
  6933. @State commentStr: string = ''
  6934. @State discStr: string = ''
  6935. doUpdateData() {
  6936. setTimeout(async () => {
  6937. if (this.modeType === 0) {
  6938. this.deleteCache(this.currentPath)
  6939. await this.resetAndLoadFirstPage();
  6940. }else if (this.modeType === 1){
  6941. await this.resetAndLoadFirstPage();
  6942. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6943. }
  6944. }, 500)
  6945. }
  6946. doAllUpdateData() {
  6947. setTimeout(async () => {
  6948. if (this.modeType === 0) {
  6949. this.deleteCache(this.currentPath)
  6950. await this.resetAndLoadFirstPage();
  6951. }else{
  6952. await this.resetAndLoadFirstPage();
  6953. }
  6954. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6955. workerInstance.postMessage({ code: 3, data: this.context });
  6956. workerInstance.postMessage({ code: 4, data: this.context });
  6957. }, 999)
  6958. }
  6959. private delayMs(ms: number): Promise<void> {
  6960. return new Promise(resolve => {
  6961. setTimeout(() => resolve(), ms);
  6962. });
  6963. }
  6964. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  6965. if (!items || items.length === 0) {
  6966. return;
  6967. }
  6968. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  6969. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  6970. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  6971. if (!this.isScrolling || items.length <= directAppendThreshold) {
  6972. this.videoLocalList.push(...items);
  6973. this.dataSource.appendArrayData(items);
  6974. return;
  6975. }
  6976. const chunkSize = isHeavyGridWaterMode
  6977. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  6978. : (isMediaLibraryListMode
  6979. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  6980. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  6981. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  6982. for (let index = 0; index < items.length; index += chunkSize) {
  6983. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  6984. this.videoLocalList.push(...chunk);
  6985. this.dataSource.appendArrayData(chunk);
  6986. if (index + chunkSize < items.length) {
  6987. await this.delayMs(chunkDelay);
  6988. }
  6989. }
  6990. }
  6991. /**
  6992. * 加载指定页的数据
  6993. */
  6994. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  6995. try {
  6996. // 1. 检查缓存
  6997. if (this.pageCache.has(pageIndex)) {
  6998. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  6999. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  7000. const cachedData = this.pageCache.get(pageIndex)!;
  7001. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  7002. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  7003. if (cachedHasMore !== undefined) {
  7004. this.hasMoreData = cachedHasMore;
  7005. }
  7006. if (cachedTotal !== undefined) {
  7007. this.totalCount = cachedTotal;
  7008. if (this.modeType === 1) {
  7009. this.mediaKuCount = cachedTotal;
  7010. }
  7011. }
  7012. if (append) {
  7013. this.prefetchListThumbsFromItems(cachedData, 26);
  7014. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  7015. await this.appendItemsSmoothly(cachedData);
  7016. } else {
  7017. this.videoLocalList = cachedData;
  7018. this.dataSource.pushArrayData(this.videoLocalList);
  7019. if (inMediaLibraryWarmup) {
  7020. this.prefetchListThumbsFromItems(cachedData, 8);
  7021. } else {
  7022. this.prefetchListThumbsFromItems(cachedData, 30);
  7023. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  7024. }
  7025. }
  7026. this.setButtonStatus();
  7027. if (inMediaLibraryWarmup) {
  7028. this.scheduleAlphaBetRebuild(900);
  7029. } else {
  7030. this.markAlphaBetDirty();
  7031. }
  7032. if (this.hasMoreData) {
  7033. if (inMediaLibraryWarmup) {
  7034. if (this.mediaLibraryWarmupPrefetchTimer) {
  7035. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  7036. }
  7037. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  7038. this.mediaLibraryWarmupPrefetchTimer = 0;
  7039. if (this.modeType === 1 && !this.isCanBack) {
  7040. this.prefetchFollowingPages(pageIndex + 1);
  7041. }
  7042. }, 900) as number;
  7043. } else {
  7044. this.prefetchFollowingPages(pageIndex + 1);
  7045. }
  7046. }
  7047. return;
  7048. }
  7049. this.isLoadingPage = true;
  7050. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  7051. // 2. 构造查询参数
  7052. const options: PageQueryOptions = {
  7053. pageIndex: pageIndex,
  7054. pageSize: this.pageSize,
  7055. sortType: this.sortType,
  7056. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  7057. isShowFileName: this.isShowFileName
  7058. };
  7059. // 根据 modeType 补充查询条件
  7060. if (this.modeType === 0) {
  7061. options.parentPath = this.currentPath;
  7062. }
  7063. // 3. 执行查询
  7064. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  7065. switch (this.modeType) {
  7066. case 0:
  7067. result = await this.table.queryByParentPathPaged(options);
  7068. // modeType=0时,第一页需要添加文件夹列表
  7069. if (pageIndex === 0 && !this.isSearchMode) {
  7070. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  7071. result.items = [...directories, ...result.items];
  7072. result.totalCount += directories.length;
  7073. }
  7074. break;
  7075. case 1:
  7076. result = await this.table.queryMediaLibraryPaged(options);
  7077. break;
  7078. case 2:
  7079. result = await this.table.queryArtistsPaged(options);
  7080. break;
  7081. case 3:
  7082. result = await this.table.queryAlbumsPaged(options);
  7083. break;
  7084. default:
  7085. result = await this.table.queryMediaLibraryPaged(options);
  7086. break;
  7087. }
  7088. if (!result || result.items.length === 0) {
  7089. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  7090. this.isLoadingPage = false;
  7091. this.hasMoreData = false;
  7092. // 仅首页为空时清空,后续页为空只终止继续分页
  7093. if (pageIndex === 0) {
  7094. this.totalCount = 0;
  7095. this.videoLocalList = [];
  7096. this.dataSource.pushArrayData(this.videoLocalList);
  7097. this.setButtonStatus();
  7098. this.markAlphaBetDirty();
  7099. }
  7100. return;
  7101. }
  7102. // 4. 更新状态和缓存
  7103. this.totalCount = result.totalCount;
  7104. this.hasMoreData = result.hasMore;
  7105. if (this.modeType === 1) {
  7106. this.mediaKuCount = result.totalCount;
  7107. }
  7108. if (this.modeType === 2 && result.countMap) {
  7109. this.mergeArtistCountMap(result.countMap);
  7110. } else if (this.modeType === 3 && result.countMap) {
  7111. this.mergeAlbumCountMap(result.countMap);
  7112. }
  7113. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  7114. // 缓存管理 - 只保留最近3页
  7115. this.pageCache.set(pageIndex, result.items);
  7116. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  7117. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  7118. this.cleanOldCache(pageIndex);
  7119. // 5. 更新显示列表
  7120. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  7121. if (append) {
  7122. this.prefetchListThumbsFromItems(result.items, 26);
  7123. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  7124. await this.appendItemsSmoothly(result.items);
  7125. } else {
  7126. this.videoLocalList = result.items;
  7127. this.dataSource.pushArrayData(this.videoLocalList);
  7128. if (inMediaLibraryWarmup) {
  7129. this.prefetchListThumbsFromItems(result.items, 8);
  7130. } else {
  7131. this.prefetchListThumbsFromItems(result.items, 30);
  7132. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  7133. }
  7134. }
  7135. this.setButtonStatus();
  7136. if (inMediaLibraryWarmup) {
  7137. this.scheduleAlphaBetRebuild(900);
  7138. } else {
  7139. this.markAlphaBetDirty();
  7140. }
  7141. if (inMediaLibraryWarmup) {
  7142. if (this.mediaLibraryWarmupPrefetchTimer) {
  7143. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  7144. }
  7145. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  7146. this.mediaLibraryWarmupPrefetchTimer = 0;
  7147. if (this.modeType === 1 && !this.isCanBack) {
  7148. this.prefetchFollowingPages(pageIndex + 1);
  7149. }
  7150. }, 900) as number;
  7151. } else {
  7152. this.prefetchFollowingPages(pageIndex + 1);
  7153. }
  7154. this.isLoadingPage = false;
  7155. } catch (err) {
  7156. const error = err as Error;
  7157. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  7158. ToastUtil.showToast('加载数据失败');
  7159. this.isLoadingPage = false;
  7160. this.hasMoreData = false;
  7161. }
  7162. }
  7163. /**
  7164. * 清理旧缓存 - 只保留当前页前后各1页
  7165. */
  7166. private cleanOldCache(currentPage: number): void {
  7167. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  7168. const keysToDelete: number[] = [];
  7169. this.pageCache.forEach((_, page) => {
  7170. if (!pagesToKeep.has(page)) {
  7171. keysToDelete.push(page);
  7172. }
  7173. });
  7174. keysToDelete.forEach(page => {
  7175. this.pageCache.delete(page);
  7176. this.pageHasMoreCache.delete(page);
  7177. this.pageTotalCountCache.delete(page);
  7178. });
  7179. if (keysToDelete.length > 0) {
  7180. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  7181. }
  7182. }
  7183. private async prefetchNextPage(nextPage: number): Promise<void> {
  7184. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  7185. return;
  7186. }
  7187. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  7188. return;
  7189. }
  7190. const expectedModeType = this.modeType;
  7191. const expectedSortType = this.sortType;
  7192. const expectedIsShowFileName = this.isShowFileName;
  7193. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  7194. const expectedParentPath = this.currentPath;
  7195. this.prefetchingPages.add(nextPage);
  7196. try {
  7197. const options: PageQueryOptions = {
  7198. pageIndex: nextPage,
  7199. pageSize: this.pageSize,
  7200. sortType: this.sortType,
  7201. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  7202. isShowFileName: this.isShowFileName
  7203. };
  7204. if (this.modeType === 0) {
  7205. options.parentPath = this.currentPath;
  7206. }
  7207. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  7208. switch (this.modeType) {
  7209. case 0:
  7210. result = await this.table.queryByParentPathPaged(options);
  7211. break;
  7212. case 1:
  7213. result = await this.table.queryMediaLibraryPaged(options);
  7214. break;
  7215. case 2:
  7216. result = await this.table.queryArtistsPaged(options);
  7217. if (result.countMap) {
  7218. this.mergeArtistCountMap(result.countMap);
  7219. }
  7220. break;
  7221. case 3:
  7222. result = await this.table.queryAlbumsPaged(options);
  7223. if (result.countMap) {
  7224. this.mergeAlbumCountMap(result.countMap);
  7225. }
  7226. break;
  7227. default:
  7228. result = await this.table.queryMediaLibraryPaged(options);
  7229. break;
  7230. }
  7231. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  7232. if (expectedModeType !== this.modeType ||
  7233. expectedSortType !== this.sortType ||
  7234. expectedIsShowFileName !== this.isShowFileName ||
  7235. expectedSearchKeyword !== currentSearchKeyword ||
  7236. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  7237. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  7238. return;
  7239. }
  7240. this.pageHasMoreCache.set(nextPage, result.hasMore);
  7241. this.pageTotalCountCache.set(nextPage, result.totalCount);
  7242. if (result.items.length > 0) {
  7243. this.pageCache.set(nextPage, result.items);
  7244. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  7245. this.cleanOldCache(nextPage);
  7246. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  7247. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  7248. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  7249. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  7250. Logger.info('heanup LocalMusic',
  7251. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  7252. this.scheduleLoadNextPage(8);
  7253. }
  7254. }
  7255. }
  7256. } catch (err) {
  7257. const error = err as Error;
  7258. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  7259. } finally {
  7260. this.prefetchingPages.delete(nextPage);
  7261. }
  7262. }
  7263. private mergeArtistCountMap(countMap: Map<string, number>): void {
  7264. const nextMap = new Map(this.artistSongCountMap);
  7265. countMap.forEach((count, artist) => {
  7266. nextMap.set(artist, count);
  7267. });
  7268. this.artistSongCountMap = nextMap;
  7269. }
  7270. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  7271. const nextMap = new Map(this.albumSongCountMap);
  7272. countMap.forEach((count, album) => {
  7273. nextMap.set(album, count);
  7274. });
  7275. this.albumSongCountMap = nextMap;
  7276. }
  7277. private getArtistSongCount(artist: string): number {
  7278. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  7279. }
  7280. private getAlbumSongCount(album: string): number {
  7281. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  7282. }
  7283. /**
  7284. * 加载文件夹列表(仅用于modeType=0的首页模式)
  7285. */
  7286. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  7287. try {
  7288. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  7289. // 检查缓存
  7290. const cacheKey = curPath + "_dirList";
  7291. const cachedDirList = this.findCache(cacheKey);
  7292. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  7293. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  7294. return cachedDirList as VideoItem[];
  7295. }
  7296. // 从文件系统读取
  7297. const fileList = FileUtil.listFileSync(curPath);
  7298. const directories: VideoItem[] = [];
  7299. for (let i = 0; i < fileList.length; i++) {
  7300. const path = curPath + '/' + fileList[i];
  7301. if (FileUtil.isDirectory(path)) {
  7302. const item: VideoItem = new VideoItem(
  7303. fileList[i].toString(),
  7304. fileList[i].toString(),
  7305. path,
  7306. CommonConstants.TYPE_IS_DIR,
  7307. 0,
  7308. ''
  7309. );
  7310. if (this.isShowDir(item.name)) {
  7311. directories.push(item);
  7312. }
  7313. }
  7314. }
  7315. // 排序
  7316. Utility.doSortListAscending(directories);
  7317. // 缓存文件夹列表
  7318. if (curPath === this.rootPath) {
  7319. this.dirList = directories;
  7320. this.addCache(cacheKey, directories);
  7321. }
  7322. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  7323. return directories;
  7324. } catch (err) {
  7325. const error = err as Error;
  7326. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  7327. return [];
  7328. }
  7329. }
  7330. /**
  7331. * 构建播放队列(避免一次性加载全量)
  7332. */
  7333. private buildPlayQueueFromView(): Array<VideoItem> {
  7334. if (this.modeType === 4) {
  7335. this.playQueueScope = 'playlist';
  7336. return this.currentSongList;
  7337. }
  7338. if (this.isHistory) {
  7339. this.playQueueScope = 'history';
  7340. return this.historyList;
  7341. }
  7342. if (this.isFavMusic) {
  7343. this.playQueueScope = 'fav';
  7344. return this.favList;
  7345. }
  7346. this.playQueueScope = 'view';
  7347. return this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  7348. }
  7349. private async tryLoadNextPageForPlayback(): Promise<void> {
  7350. if (this.playQueueScope !== 'view') {
  7351. return;
  7352. }
  7353. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  7354. return;
  7355. }
  7356. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7357. return;
  7358. }
  7359. await this.loadNextPage();
  7360. const nextList = this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  7361. if (nextList.length > this.songList.length) {
  7362. this.songList = nextList;
  7363. this.sonDataSource.pushArrayData(this.songList);
  7364. }
  7365. }
  7366. /**
  7367. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  7368. * 当播放列表弹窗滚动到底部时调用
  7369. */
  7370. private async loadMoreNavidromeSongs(): Promise<void> {
  7371. const beforeCount = this.songList.length;
  7372. const hasMore = hasMoreData();
  7373. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  7374. if (!hasMore) {
  7375. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  7376. return;
  7377. }
  7378. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  7379. const success = await triggerLoadMoreSongs(1);
  7380. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  7381. if (success) {
  7382. // 获取更新后的完整列表
  7383. const updatedList = getNavidromeVideoItems();
  7384. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  7385. if (updatedList.length > beforeCount) {
  7386. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  7387. this.songList = updatedList;
  7388. this.sonDataSource.pushArrayData(this.songList);
  7389. } else {
  7390. Logger.info('heanup', '列表长度未增加');
  7391. }
  7392. } else {
  7393. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  7394. }
  7395. }
  7396. /**
  7397. * 重置分页状态并加载首页
  7398. */
  7399. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  7400. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  7401. this.currentPage = 0;
  7402. if (clearExistingList) {
  7403. this.videoLocalList = [];
  7404. }
  7405. this.pageCache.clear();
  7406. this.pageHasMoreCache.clear();
  7407. this.pageTotalCountCache.clear();
  7408. this.prefetchingPages.clear();
  7409. this.hasMoreData = true;
  7410. this.totalCount = 0;
  7411. this.lastScrollTriggerPage = -1;
  7412. this.lastVisibleEndIndex = -1;
  7413. this.listScrollAlphaCheckAt = 0;
  7414. this.listScrollPagingCheckAt = 0;
  7415. this.listScrollLastAlphaStart = -1;
  7416. this.listScrollLastPagingEnd = -1;
  7417. this.gridScrollPagingCheckAt = 0;
  7418. this.gridScrollLastPagingEnd = -1;
  7419. this.waterScrollPagingCheckAt = 0;
  7420. this.waterScrollLastPagingEnd = -1;
  7421. this.listVisibleStart = -1;
  7422. this.listVisibleEnd = -1;
  7423. this.listThumbWarmupCheckAt = 0;
  7424. this.listThumbWarmupStart = -1;
  7425. this.listThumbWarmupEnd = -1;
  7426. this.gridThumbWarmupCheckAt = 0;
  7427. this.gridThumbWarmupStart = -1;
  7428. this.gridThumbWarmupEnd = -1;
  7429. this.waterThumbWarmupCheckAt = 0;
  7430. this.waterThumbWarmupStart = -1;
  7431. this.waterThumbWarmupEnd = -1;
  7432. this.gridVisibleStart = -1;
  7433. this.gridVisibleEnd = -1;
  7434. this.waterVisibleStart = -1;
  7435. this.waterVisibleEnd = -1;
  7436. this.gridWaterLastActiveTs = 0;
  7437. this.isPagingTransition = false;
  7438. if (this.pagingScheduleTimer) {
  7439. clearTimeout(this.pagingScheduleTimer);
  7440. this.pagingScheduleTimer = 0;
  7441. }
  7442. if (this.gridWaterScrollIdleTimer) {
  7443. clearTimeout(this.gridWaterScrollIdleTimer);
  7444. this.gridWaterScrollIdleTimer = 0;
  7445. }
  7446. this.coverThumbCache.clearPending();
  7447. this.pendingCoverThumbRefresh = false;
  7448. if (this.modeType === 2) {
  7449. this.artistSongCountMap = new Map();
  7450. } else if (this.modeType === 3) {
  7451. this.albumSongCountMap = new Map();
  7452. }
  7453. await this.loadPage(0, false);
  7454. }
  7455. private markGridWaterScrollingActive(): void {
  7456. if (!this.isScrolling) {
  7457. this.isScrolling = true;
  7458. }
  7459. const now = Date.now();
  7460. if (now - this.gridWaterLastActiveTs < 80) {
  7461. return;
  7462. }
  7463. this.gridWaterLastActiveTs = now;
  7464. if (this.gridWaterScrollIdleTimer) {
  7465. clearTimeout(this.gridWaterScrollIdleTimer);
  7466. }
  7467. this.gridWaterScrollIdleTimer = setTimeout(() => {
  7468. this.gridWaterScrollIdleTimer = 0;
  7469. if (this.isScrolling) {
  7470. this.isScrolling = false;
  7471. }
  7472. this.flushPendingCoverThumbRefresh();
  7473. }, 120);
  7474. }
  7475. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  7476. if (!this.autoHideTitle) {
  7477. return;
  7478. }
  7479. const now = Date.now();
  7480. if (now - this.titleBarLastCheckTs < 36) {
  7481. return;
  7482. }
  7483. this.titleBarLastCheckTs = now;
  7484. const delta = currentOffsetY - this.prevOffsetY;
  7485. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  7486. return;
  7487. }
  7488. if (delta > 0) {
  7489. if (this.isShowTitleBar) {
  7490. this.isShowTitleBar = false;
  7491. }
  7492. } else {
  7493. if (!this.isShowTitleBar) {
  7494. this.isShowTitleBar = true;
  7495. }
  7496. }
  7497. this.prevOffsetY = currentOffsetY;
  7498. }
  7499. private shouldPrefetchSecondPage(): boolean {
  7500. if (this.isMediaLibraryListMode()) {
  7501. return this.pageSize <= 120;
  7502. }
  7503. if (this.pageSize > 60) {
  7504. return false;
  7505. }
  7506. return this.isGridMusic || this.twoFingerType == 4;
  7507. }
  7508. private isMediaLibraryListMode(): boolean {
  7509. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  7510. }
  7511. private isMediaLibraryWarmupWindow(): boolean {
  7512. if (this.modeType !== 1 || this.isCanBack) {
  7513. return false;
  7514. }
  7515. if (this.mediaLibraryEnterTs <= 0) {
  7516. return false;
  7517. }
  7518. return Date.now() - this.mediaLibraryEnterTs < 1800;
  7519. }
  7520. private getDynamicPreloadStartRatio(): number {
  7521. if (this.twoFingerType == 4) {
  7522. return 0.10;
  7523. }
  7524. if (this.isGridMusic) {
  7525. return 0.14;
  7526. }
  7527. if (this.isMediaLibraryListMode()) {
  7528. return 0.12;
  7529. }
  7530. return this.preloadStartRatio;
  7531. }
  7532. private getDynamicAppendStartRatio(): number {
  7533. if (this.twoFingerType == 4) {
  7534. return 0.18;
  7535. }
  7536. if (this.isGridMusic) {
  7537. return 0.22;
  7538. }
  7539. if (this.isMediaLibraryListMode()) {
  7540. return 0.22;
  7541. }
  7542. return this.appendStartRatio;
  7543. }
  7544. private getDynamicEarlyAppendReserveCount(): number {
  7545. if (this.twoFingerType == 4) {
  7546. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  7547. }
  7548. if (this.isGridMusic) {
  7549. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  7550. }
  7551. if (this.isMediaLibraryListMode()) {
  7552. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  7553. }
  7554. return this.earlyAppendReserveCount;
  7555. }
  7556. private prefetchFollowingPages(nextPage: number): void {
  7557. void this.prefetchNextPage(nextPage);
  7558. if (this.shouldPrefetchSecondPage()) {
  7559. void this.prefetchNextPage(nextPage + 1);
  7560. }
  7561. }
  7562. private scrollToTopForCurrentLayout(): void {
  7563. if (this.twoFingerType == 4) {
  7564. this.waterScroller.scrollEdge(Edge.Top);
  7565. this.scroller.scrollEdge(Edge.Top);
  7566. return;
  7567. }
  7568. if (this.isGridMusic) {
  7569. this.scroller.scrollEdge(Edge.Top);
  7570. return;
  7571. }
  7572. this.listScroller.scrollEdge(Edge.Top);
  7573. }
  7574. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  7575. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  7576. if (coverVersion < -1) {
  7577. return fallback;
  7578. }
  7579. if (StrUtil.isEmpty(item.pixelMapPath)) {
  7580. return fallback;
  7581. }
  7582. const sourceUri = item.pixelMapPath as string;
  7583. this.initCoverThumbCacheIfNeeded();
  7584. const targetSize = this.getListThumbTargetSize();
  7585. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  7586. if (cachedThumb) {
  7587. return cachedThumb;
  7588. }
  7589. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7590. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  7591. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  7592. const isNearVisible = !hasRange ||
  7593. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  7594. if (isNearVisible) {
  7595. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7596. }
  7597. }
  7598. return sourceUri;
  7599. }
  7600. private getListThumbTargetSize(): number {
  7601. if (this.twoFingerType == 1) {
  7602. return 96;
  7603. }
  7604. if (this.twoFingerType == 2) {
  7605. return 112;
  7606. }
  7607. return 128;
  7608. }
  7609. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  7610. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  7611. return;
  7612. }
  7613. this.initCoverThumbCacheIfNeeded();
  7614. const targetSize = this.getListThumbTargetSize();
  7615. const maxCount = Math.min(limit, items.length);
  7616. for (let i = 0; i < maxCount; i++) {
  7617. const item = items[i];
  7618. if (StrUtil.isEmpty(item.pixelMapPath)) {
  7619. continue;
  7620. }
  7621. const sourceUri = item.pixelMapPath as string;
  7622. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7623. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7624. }
  7625. }
  7626. }
  7627. private warmupListVisibleThumbs(start: number, end: number): void {
  7628. if (!this.isMediaLibraryListMode()) {
  7629. return;
  7630. }
  7631. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  7632. return;
  7633. }
  7634. const now = Date.now();
  7635. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  7636. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  7637. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  7638. return;
  7639. }
  7640. this.listThumbWarmupCheckAt = now;
  7641. this.listThumbWarmupStart = start;
  7642. this.listThumbWarmupEnd = end;
  7643. this.initCoverThumbCacheIfNeeded();
  7644. const targetSize = this.getListThumbTargetSize();
  7645. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  7646. const begin = Math.max(0, start - 4);
  7647. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  7648. for (let index = begin; index <= last; index++) {
  7649. const item = this.videoLocalList[index];
  7650. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  7651. continue;
  7652. }
  7653. const sourceUri = item.pixelMapPath as string;
  7654. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7655. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7656. }
  7657. }
  7658. }
  7659. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  7660. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  7661. return;
  7662. }
  7663. this.initCoverThumbCacheIfNeeded();
  7664. const isWater = this.twoFingerType == 4;
  7665. const targetSize = this.getCoverThumbTargetSize(isWater);
  7666. const maxCount = Math.min(limit, items.length);
  7667. for (let i = 0; i < maxCount; i++) {
  7668. const item = items[i];
  7669. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  7670. continue;
  7671. }
  7672. const sourceUri = item.pixelMapPath as string;
  7673. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7674. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7675. }
  7676. }
  7677. }
  7678. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  7679. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  7680. return;
  7681. }
  7682. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  7683. return;
  7684. }
  7685. const now = Date.now();
  7686. let lastStart = -1;
  7687. let lastEnd = -1;
  7688. let lastCheckAt = 0;
  7689. if (isWater) {
  7690. lastStart = this.waterThumbWarmupStart;
  7691. lastEnd = this.waterThumbWarmupEnd;
  7692. lastCheckAt = this.waterThumbWarmupCheckAt;
  7693. } else {
  7694. lastStart = this.gridThumbWarmupStart;
  7695. lastEnd = this.gridThumbWarmupEnd;
  7696. lastCheckAt = this.gridThumbWarmupCheckAt;
  7697. }
  7698. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  7699. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  7700. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  7701. return;
  7702. }
  7703. if (isWater) {
  7704. this.waterThumbWarmupCheckAt = now;
  7705. this.waterThumbWarmupStart = start;
  7706. this.waterThumbWarmupEnd = end;
  7707. } else {
  7708. this.gridThumbWarmupCheckAt = now;
  7709. this.gridThumbWarmupStart = start;
  7710. this.gridThumbWarmupEnd = end;
  7711. }
  7712. this.initCoverThumbCacheIfNeeded();
  7713. const columns = isWater ? Math.max(this.columns, 1) :
  7714. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  7715. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  7716. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  7717. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  7718. const targetSize = this.getCoverThumbTargetSize(isWater);
  7719. for (let index = begin; index <= last; index++) {
  7720. const item = this.videoLocalList[index];
  7721. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  7722. continue;
  7723. }
  7724. const sourceUri = item.pixelMapPath as string;
  7725. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7726. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7727. }
  7728. }
  7729. }
  7730. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  7731. coverVersion: number = 0): ResourceStr {
  7732. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  7733. if (coverVersion < -1) {
  7734. return fallback;
  7735. }
  7736. if (StrUtil.isEmpty(item.pixelMapPath)) {
  7737. return fallback;
  7738. }
  7739. const sourceUri = item.pixelMapPath as string;
  7740. this.initCoverThumbCacheIfNeeded();
  7741. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  7742. const targetSize = this.getCoverThumbTargetSize(isWater);
  7743. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  7744. if (cachedThumb) {
  7745. return cachedThumb;
  7746. }
  7747. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  7748. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  7749. const columns = isWater ? Math.max(this.columns, 1) :
  7750. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  7751. const preloadBuffer = Math.max(columns * 2, 8);
  7752. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  7753. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  7754. if (!isRemoteCover && isNearVisible) {
  7755. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7756. }
  7757. if (!this.isScrolling) {
  7758. return sourceUri;
  7759. }
  7760. if (isNearVisible) {
  7761. return sourceUri;
  7762. }
  7763. return fallback;
  7764. }
  7765. private flushPendingCoverThumbRefresh(): void {
  7766. if (!this.pendingCoverThumbRefresh) {
  7767. return;
  7768. }
  7769. this.pendingCoverThumbRefresh = false;
  7770. this.coverThumbVersion++;
  7771. }
  7772. private initCoverThumbCacheIfNeeded(): void {
  7773. if (this.coverThumbCacheReady) {
  7774. return;
  7775. }
  7776. this.coverThumbCache.setContext(this.context);
  7777. this.coverThumbCache.setOnThumbReady(() => {
  7778. if (this.isScrolling) {
  7779. this.pendingCoverThumbRefresh = true;
  7780. return;
  7781. }
  7782. this.coverThumbVersion++;
  7783. });
  7784. this.coverThumbCacheReady = true;
  7785. }
  7786. private getCoverThumbTargetSize(isWater: boolean): number {
  7787. if (isWater) {
  7788. if (this.columns >= 4) {
  7789. return 160;
  7790. }
  7791. if (this.columns == 3) {
  7792. return 200;
  7793. }
  7794. return 260;
  7795. }
  7796. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  7797. if (this.twoFingerType == 1) {
  7798. return baseSize;
  7799. }
  7800. if (this.twoFingerType == 2) {
  7801. return Math.floor(baseSize * 1.1);
  7802. }
  7803. return Math.floor(baseSize * 1.15);
  7804. }
  7805. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  7806. if (this.videoLocalList.length <= 0) {
  7807. return;
  7808. }
  7809. const columns = Math.max(this.columns, 1);
  7810. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  7811. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  7812. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  7813. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  7814. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  7815. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  7816. this.waterVisibleStart = startIndex;
  7817. this.waterVisibleEnd = estimatedEnd;
  7818. this.lastVisibleEndIndex = estimatedEnd;
  7819. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  7820. const now = Date.now();
  7821. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  7822. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  7823. this.waterScrollPagingCheckAt = now;
  7824. this.waterScrollLastPagingEnd = estimatedEnd;
  7825. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  7826. }
  7827. }
  7828. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  7829. if (this.modeType === 4) {
  7830. return;
  7831. }
  7832. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  7833. return;
  7834. }
  7835. if (this.isHistory || this.isFavMusic) {
  7836. return;
  7837. }
  7838. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7839. return;
  7840. }
  7841. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  7842. return;
  7843. }
  7844. const nextPage = this.currentPage + 1;
  7845. const next2Page = this.currentPage + 2;
  7846. const totalLoaded = this.videoLocalList.length;
  7847. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  7848. const remainCount = this.videoLocalList.length - endIndex - 1;
  7849. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  7850. const appendStartRatio = this.getDynamicAppendStartRatio();
  7851. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  7852. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  7853. if (seenRatio >= preloadStartRatio) {
  7854. if (!this.pageCache.has(nextPage)) {
  7855. void this.prefetchNextPage(nextPage);
  7856. }
  7857. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  7858. void this.prefetchNextPage(next2Page);
  7859. }
  7860. }
  7861. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  7862. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  7863. const shouldGapAppend = this.pageCache.has(nextPage) &&
  7864. seenRatio >= (appendStartRatio - 0.08) &&
  7865. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  7866. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  7867. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  7868. return;
  7869. }
  7870. if (this.lastScrollTriggerPage === this.currentPage) {
  7871. return;
  7872. }
  7873. this.lastScrollTriggerPage = this.currentPage;
  7874. Logger.info('heanup LocalMusic',
  7875. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  7876. this.scheduleLoadNextPage(8);
  7877. }
  7878. private scheduleLoadNextPage(delayMs: number = 0): void {
  7879. if (this.pagingScheduleTimer) {
  7880. return;
  7881. }
  7882. this.pagingScheduleTimer = setTimeout(() => {
  7883. this.pagingScheduleTimer = 0;
  7884. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7885. return;
  7886. }
  7887. void this.loadNextPage();
  7888. }, delayMs);
  7889. }
  7890. /**
  7891. * 加载下一页
  7892. */
  7893. private async loadNextPage(): Promise<void> {
  7894. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7895. return;
  7896. }
  7897. this.isPagingTransition = true;
  7898. this.currentPage++;
  7899. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  7900. try {
  7901. await this.loadPage(this.currentPage, true);
  7902. } finally {
  7903. this.isPagingTransition = false;
  7904. }
  7905. }
  7906. //编辑信息
  7907. async doEdit(item: VideoItem) {
  7908. if (!item) {
  7909. return
  7910. }
  7911. if (StrUtil.isEmpty(this.titleStr)) {
  7912. ToastUtil.showToast('标题不能为空')
  7913. return
  7914. }
  7915. //内嵌音乐标签不能开启监听
  7916. // this.deletionWatcher?.stop();
  7917. this.loadingDialogId = DialogHelper.showLoadingDialog()
  7918. await PermissionUtil.activatePermission(item.filePath)
  7919. let tempOutPath = ''
  7920. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  7921. if(!item.filePath.toLowerCase().includes(this.packName)){
  7922. tempOutPath = this.currentPath + '/' + item.fileName
  7923. }
  7924. console.info('onecold tempOutPath ='+tempOutPath)
  7925. //用户更改了封面,那就内嵌下封面
  7926. if(StrUtil.isNotEmpty(this.imagePathStr)){
  7927. const resultCover:boolean = await changeMusicCover(this.context,
  7928. item.filePath,this.imagePathStr,true,tempOutPath);
  7929. this.imagePathStr = ''
  7930. if(resultCover){
  7931. ToastUtil.showToast('内嵌封面成功')
  7932. }
  7933. }
  7934. const metadata:FFMpegTags = {
  7935. title: this.titleStr,
  7936. artist: this.artistStr,
  7937. album: this.ablumStr,
  7938. TYER:this.yearStr,
  7939. genre:this.genreStr,
  7940. track:this.trackStr,
  7941. album_artist:this.albumArtistStr,
  7942. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  7943. COMPOSER:this.composerStr,
  7944. lyricist:this.lyricistStr,
  7945. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  7946. comment:this.commentStr,
  7947. disc:this.discStr,
  7948. };
  7949. let newInput = item.filePath
  7950. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  7951. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  7952. newInput = tempOutPath
  7953. tempOutPath = ''
  7954. }
  7955. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  7956. ||newInput.toLowerCase().endsWith('.ape')
  7957. ||newInput.toLowerCase().endsWith('.dsf')
  7958. ||newInput.toLowerCase().endsWith('.dff');
  7959. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  7960. const result:boolean = await repairAudioMetadata(
  7961. newInput,
  7962. this.lyricConStr,
  7963. metadata,
  7964. true,
  7965. tempOutPath
  7966. );
  7967. if (result||isWav) {
  7968. if(!item.filePath.includes(this.packName)){
  7969. //内嵌成功的歌路径如果不是包含包名,则要入库
  7970. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  7971. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  7972. this.table.insert(newItem, (id: number) => {
  7973. //加入数据库
  7974. if(this.modeType==0){
  7975. this.deleteCache(this.currentPath)
  7976. this.getSortedFiles(this.currentPath)
  7977. }
  7978. });
  7979. }
  7980. const task = new taskpool.Task(
  7981. updateInfoDb,
  7982. this.context,
  7983. item.filePath,
  7984. this.titleStr,
  7985. this.artistStr,
  7986. this.ablumStr,
  7987. this.lyricConStr,
  7988. this.yearStr,this.genreStr,
  7989. this.trackStr,this.albumArtistStr,
  7990. this.composerStr, this.lyricistStr,
  7991. this.commentStr,this.discStr
  7992. );
  7993. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  7994. if (result) {
  7995. console.log(" onecold 编辑信息成功,数据库已同步");
  7996. if(isWav){
  7997. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  7998. }else{
  7999. ToastUtil.showToast('内嵌音乐标签成功')
  8000. }
  8001. this.isShowMoreView = false
  8002. this.name = this.titleStr
  8003. this.syncEditedFields(item)
  8004. if (item.filePath == this.currentSong?.filePath) {
  8005. this.currentSong.name = this.titleStr
  8006. this.artist = this.artistStr
  8007. this.currentSong.artist = this.artistStr
  8008. this.currentSong.album = this.ablumStr
  8009. this.currentSong.year = this.yearStr
  8010. this.currentSong.genre = this.genreStr
  8011. this.currentSong.track = this.trackStr
  8012. this.currentSong.lyricContent = this.lyricConStr
  8013. this.currentSong.ALBUMARTIST = this.albumArtistStr
  8014. this.currentSong.COMPOSER = this.composerStr
  8015. this.currentSong.LYRICIST = this.lyricistStr
  8016. this.currentSong.COMMENT = this.commentStr
  8017. }
  8018. this.syncListsAfterEdit(item.filePath)
  8019. this.doUpateEditedFields(item)
  8020. //this.doUpdateData()
  8021. } else {
  8022. // ToastUtil.showToast('保存失败' + error?.toString())
  8023. console.error(" onecold 编辑信息数据库失败 ");
  8024. }
  8025. // 关闭进度条
  8026. DialogHelper.closeDialog(this.loadingDialogId)
  8027. }).catch((error: Error) => {
  8028. // 关闭进度条
  8029. DialogHelper.closeDialog(this.loadingDialogId)
  8030. console.error('onecold Subtitle sync failed:', error);
  8031. });
  8032. console.log(' onecold 元数据标签更新成功,');
  8033. } else {
  8034. // 关闭进度条
  8035. DialogHelper.closeDialog(this.loadingDialogId)
  8036. ToastUtil.showToast('内嵌音乐标签失败')
  8037. console.log('onecold 内嵌音乐标签失败');
  8038. }
  8039. this.longItemFilePath = ''
  8040. this.tempLyricContent = ''
  8041. this.isShowEdit = false
  8042. }
  8043. // 内嵌标签更新当前内嵌的Item
  8044. async doUpateEditedFields(item: VideoItem) {
  8045. // 找到当前项在 videoLocalList 中的索引
  8046. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  8047. if (index !== -1) {
  8048. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  8049. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  8050. // 只有当查询结果不为 null 时才更新列表
  8051. if (updatedItem !== null) {
  8052. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  8053. this.videoLocalList = [
  8054. ...this.videoLocalList.slice(0, index),
  8055. updatedItem,
  8056. ...this.videoLocalList.slice(index + 1)
  8057. ];
  8058. // 同步更新 LazyDataSource
  8059. this.dataSource.pushArrayData(this.videoLocalList)
  8060. } else {
  8061. ToastUtil.showToast('未找到更新的数据');
  8062. }
  8063. }
  8064. DialogHelper.closeDialog(this.loadingDialogId)
  8065. }
  8066. @Builder
  8067. editSheet(item: VideoItem) {
  8068. Scroll() {
  8069. Column() {
  8070. this.editDetail(item)
  8071. }
  8072. }
  8073. .width('100%')
  8074. .height('100%')
  8075. }
  8076. @Builder
  8077. editDetail(item: VideoItem) {
  8078. Column() {
  8079. if (item) {
  8080. Row() {
  8081. Stack() {
  8082. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  8083. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  8084. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  8085. item.pixelMapPath)
  8086. .fillColor(this.themeColor)
  8087. .height(88)
  8088. .width(88)
  8089. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  8090. .borderRadius(12)
  8091. .clip(true)
  8092. .opacity(this.opacityItem)// 绑定透明度
  8093. .margin({ left: 25 })
  8094. }
  8095. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  8096. .onClick(async () => {
  8097. const imagePath:string | undefined = await this.goSelectImage(item);
  8098. if (imagePath) {
  8099. //用户更改过图片
  8100. this.imagePathStr = imagePath
  8101. }
  8102. })
  8103. .width('28%')
  8104. Row() {
  8105. Column() {
  8106. Text(item.name)
  8107. .fontSize(17)
  8108. .maxLines(1)
  8109. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8110. .animation({
  8111. duration: 555,
  8112. curve: 'Linear',
  8113. })
  8114. .fontColor(this.themeColor)
  8115. .margin({ left: 8 })
  8116. Row() {
  8117. Text(item.artist)
  8118. .fontSize(14)
  8119. .maxLines(1)
  8120. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8121. .padding({ top: 8 })
  8122. .fontColor(this.themeColor)
  8123. .margin({ left: 8 })
  8124. }
  8125. }
  8126. .height('100%')
  8127. .width(100)
  8128. .layoutWeight(1)
  8129. .justifyContent(FlexAlign.Center)
  8130. .alignItems(HorizontalAlign.Start)
  8131. Column() {
  8132. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8133. Row(){
  8134. SymbolGlyph($r('sys.symbol.picture'))
  8135. .fontSize(18)
  8136. .fontColor([Color.White])
  8137. Text('获取封面')
  8138. .margin({ left: 4 })
  8139. .fontSize(11)
  8140. .fontColor(Color.White)
  8141. .fontWeight(480)
  8142. .textAlign(TextAlign.Center)
  8143. }
  8144. .justifyContent(FlexAlign.Center)
  8145. }
  8146. .height(38)
  8147. .width(100)
  8148. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8149. .backgroundColor(this.themeColor)
  8150. .stateEffect(true)
  8151. .margin({ right: 35 })
  8152. .onClick(async () => {
  8153. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8154. this.showTipsDialog();
  8155. return; // Return empty string when no API is configured
  8156. }
  8157. const imagePath:string | undefined = await this.doSearchCover(item,
  8158. this.titleStr,this.artistStr);
  8159. console.info('onecold imagePath = '+imagePath)
  8160. if (StrUtil.isNotEmpty(imagePath)) {
  8161. //用户更改过图片
  8162. this.imagePathStr = imagePath
  8163. ToastUtil.showToast('获取封面成功')
  8164. }else{
  8165. ToastUtil.showToast('获取封面失败,请重试')
  8166. }
  8167. })
  8168. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8169. Row(){
  8170. SymbolGlyph($r('sys.symbol.input_mode'))
  8171. .fontSize(18)
  8172. .fontColor([Color.White])
  8173. Text('获取歌词')
  8174. .margin({ left: 4 })
  8175. .fontSize(11)
  8176. .fontColor(Color.White)
  8177. .fontWeight(480)
  8178. .textAlign(TextAlign.Center)
  8179. }
  8180. .justifyContent(FlexAlign.Center)
  8181. }
  8182. .height(38)
  8183. .width(100)
  8184. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8185. .backgroundColor(this.themeColor)
  8186. .stateEffect(true)
  8187. .margin({ top: 9, right: 35 })
  8188. .onClick(async () => {
  8189. //判断有没有设置api
  8190. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  8191. if (StrUtil.isEmpty(apiUrl)) {
  8192. this.isLyricSetting = false
  8193. this.showTipsDialog()
  8194. return
  8195. }
  8196. let res: string | undefined = await getApiLyric(apiUrl,
  8197. this.titleStr, this.artistStr, false);
  8198. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8199. this.lyricConStr = res;
  8200. ToastUtil.showToast('获取歌词成功')
  8201. }else{
  8202. ToastUtil.showToast('获取歌词失败,请重试')
  8203. }
  8204. })
  8205. }
  8206. .justifyContent(FlexAlign.Start)
  8207. }
  8208. .height('100%')
  8209. .justifyContent(FlexAlign.Start)
  8210. .layoutWeight(1)
  8211. }
  8212. .width('100%')
  8213. .height(98)
  8214. Row() {
  8215. Text('标题:')
  8216. .fontSize(14)
  8217. .fontColor($r('app.color.text_color'))
  8218. .margin({ left: 22 })
  8219. TextInput({ text: this.titleStr })
  8220. .height(40)
  8221. .maxLines(1)
  8222. .fontSize(14)
  8223. .layoutWeight(1)
  8224. .fontColor($r('app.color.text_color'))
  8225. .margin({ right: 15, left: 10 })
  8226. .onChange((val: string) => {
  8227. this.titleStr = val
  8228. })
  8229. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  8230. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8231. .backgroundColor(this.themeColor)
  8232. .fontSize(10)
  8233. .margin({ right: 20})
  8234. .onClick(async () => {
  8235. let hwTags = await extractHwMediaMetadata(item.filePath)
  8236. let artist = hwTags?.artist|| '';
  8237. let title = hwTags?.title|| '';
  8238. let album = hwTags?.album|| '';
  8239. console.info('onecold 乱码修正 artist='+artist);
  8240. console.info('onecold 乱码修正 title='+title);
  8241. console.info('onecold 乱码修正 album='+album);
  8242. this.titleStr = title;
  8243. this.artistStr = artist;
  8244. this.ablumStr = album;
  8245. })
  8246. }
  8247. .width('100%')
  8248. .margin({ top: 10, bottom: 10 })
  8249. .justifyContent(FlexAlign.Start)
  8250. Row() {
  8251. Text('艺术家:')
  8252. .fontSize(14)
  8253. .fontColor($r('app.color.text_color'))
  8254. .margin({ left: 22 })
  8255. TextInput({ text: this.artistStr })
  8256. .height(40)
  8257. .maxLines(1)
  8258. .fontSize(14)
  8259. .layoutWeight(1)
  8260. .fontColor($r('app.color.text_color'))
  8261. .margin({ right: 20, left: 10 })
  8262. .onChange((val: string) => {
  8263. this.artistStr = val
  8264. })
  8265. }
  8266. .width('100%')
  8267. .margin({ top: 10, bottom: 10 })
  8268. .justifyContent(FlexAlign.Start)
  8269. Row() {
  8270. Text('专辑名:')
  8271. .fontSize(14)
  8272. .fontColor($r('app.color.text_color'))
  8273. .margin({ left: 22 })
  8274. TextInput({ text: this.ablumStr})
  8275. .height(40)
  8276. .maxLines(1)
  8277. .fontSize(14)
  8278. .layoutWeight(1)
  8279. .fontColor($r('app.color.text_color'))
  8280. .margin({ right: 20, left: 10 })
  8281. .onChange((val: string) => {
  8282. this.ablumStr = val
  8283. })
  8284. }
  8285. .width('100%')
  8286. .margin({ top: 10, bottom: 10 })
  8287. .justifyContent(FlexAlign.Start)
  8288. Row() {
  8289. Column(){
  8290. Column(){
  8291. Text('歌词:')
  8292. .fontSize(14)
  8293. .fontColor($r('app.color.text_color'))
  8294. .margin({ top:9,left: 22 })
  8295. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8296. SymbolGlyph($r('sys.symbol.trash_fill'))
  8297. .fontSize(25)
  8298. .alignSelf(ItemAlign.Center)
  8299. .margin({ left: 22,top:25})
  8300. }
  8301. .backgroundColor(Color.Transparent)
  8302. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  8303. Visibility.None:Visibility.Visible)
  8304. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8305. .onClick(()=>{
  8306. this.lyricConStr = ''
  8307. this.lyricContent = ''
  8308. this.tempLyricContent = ''
  8309. })
  8310. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8311. SymbolGlyph($r('sys.symbol.plus'))
  8312. .fontSize(25)
  8313. .alignSelf(ItemAlign.Center)
  8314. .margin({ left: 22,top:25})
  8315. }
  8316. .backgroundColor(Color.Transparent)
  8317. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8318. .onClick( ()=>{
  8319. this.callFilePickerSelectFileForLyric()
  8320. })
  8321. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8322. SymbolGlyph($r('sys.symbol.traditional_square'))
  8323. .fontSize(25)
  8324. .alignSelf(ItemAlign.Center)
  8325. .margin({ left: 22,top:25})
  8326. }
  8327. .backgroundColor(Color.Transparent)
  8328. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  8329. Visibility.None:Visibility.Visible)
  8330. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8331. .onClick( ()=>{
  8332. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  8333. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  8334. })
  8335. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8336. Image($r('app.media.jianti'))
  8337. .height(25)
  8338. .fillColor($r('app.color.text_color'))
  8339. .alignSelf(ItemAlign.Center)
  8340. .margin({ left: 22,top:25})
  8341. }
  8342. .backgroundColor(Color.Transparent)
  8343. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  8344. Visibility.None:Visibility.Visible)
  8345. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8346. .onClick( ()=>{
  8347. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  8348. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  8349. })
  8350. }
  8351. .layoutWeight(1)
  8352. }
  8353. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  8354. this.tempLyricContent })
  8355. .type(TextAreaType.NORMAL)
  8356. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  8357. .fontSize(14)
  8358. .layoutWeight(1)
  8359. .fontColor($r('app.color.text_color'))
  8360. .margin({ right: 20, left: 10 })
  8361. .onChange((val: string) => {
  8362. this.lyricConStr = val
  8363. })
  8364. }
  8365. .width('100%')
  8366. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  8367. .margin({ top: 10, bottom: 10 })
  8368. .justifyContent(FlexAlign.Start)
  8369. Row() {
  8370. Text('年份:')
  8371. .fontSize(14)
  8372. .fontColor($r('app.color.text_color'))
  8373. .margin({ left: 22 })
  8374. TextInput({ text: item.year })
  8375. .height(40)
  8376. .maxLines(1)
  8377. .fontSize(14)
  8378. .type(InputType.Number)
  8379. .layoutWeight(1)
  8380. .fontColor($r('app.color.text_color'))
  8381. .margin({ right: 20, left: 10 })
  8382. .onChange((val: string) => {
  8383. this.yearStr = val
  8384. })
  8385. }
  8386. .width('100%')
  8387. .margin({ top: 10, bottom: 10 })
  8388. .justifyContent(FlexAlign.Start)
  8389. Row() {
  8390. Text('音轨号:')
  8391. .fontSize(14)
  8392. .fontColor($r('app.color.text_color'))
  8393. .margin({ left: 22 })
  8394. TextInput({ text:item.track=='未知'?'': item.track })
  8395. .height(40)
  8396. .maxLines(1)
  8397. .fontSize(14)
  8398. .type(InputType.Number)
  8399. .layoutWeight(1)
  8400. .fontColor($r('app.color.text_color'))
  8401. .margin({ right: 20, left: 10 })
  8402. .onChange((val: string) => {
  8403. this.trackStr = val
  8404. })
  8405. }
  8406. .width('100%')
  8407. .margin({ top: 10, bottom: 10 })
  8408. .justifyContent(FlexAlign.Start)
  8409. Row() {
  8410. Text('碟号:')
  8411. .fontSize(14)
  8412. .fontColor($r('app.color.text_color'))
  8413. .margin({ left: 22 })
  8414. TextInput({ text:item.disc })
  8415. .height(40)
  8416. .maxLines(1)
  8417. .fontSize(14)
  8418. .type(InputType.Number)
  8419. .layoutWeight(1)
  8420. .fontColor($r('app.color.text_color'))
  8421. .margin({ right: 20, left: 10 })
  8422. .onChange((val: string) => {
  8423. this.discStr = val
  8424. })
  8425. }
  8426. .width('100%')
  8427. .margin({ top: 10, bottom: 10 })
  8428. .justifyContent(FlexAlign.Start)
  8429. Row() {
  8430. Text('风格:')
  8431. .fontSize(14)
  8432. .fontColor($r('app.color.text_color'))
  8433. .margin({ left: 22 })
  8434. TextInput({ text: item.genre })
  8435. .height(40)
  8436. .maxLines(1)
  8437. .fontSize(14)
  8438. .layoutWeight(1)
  8439. .fontColor($r('app.color.text_color'))
  8440. .margin({ right: 20, left: 10 })
  8441. .onChange((val: string) => {
  8442. this.genreStr = val
  8443. })
  8444. }
  8445. .width('100%')
  8446. .margin({ top: 10, bottom: 10 })
  8447. .justifyContent(FlexAlign.Start)
  8448. Row() {
  8449. Text('专辑艺术家:')
  8450. .fontSize(14)
  8451. .fontColor($r('app.color.text_color'))
  8452. .margin({ left: 22 })
  8453. TextInput({ text: item.ALBUMARTIST })
  8454. .height(40)
  8455. .maxLines(1)
  8456. .fontSize(14)
  8457. .layoutWeight(1)
  8458. .fontColor($r('app.color.text_color'))
  8459. .margin({ right: 20, left: 10 })
  8460. .onChange((val: string) => {
  8461. this.albumArtistStr = val
  8462. })
  8463. }
  8464. .width('100%')
  8465. .margin({ top: 10, bottom: 10 })
  8466. .justifyContent(FlexAlign.Start)
  8467. Row() {
  8468. Text('作曲:')
  8469. .fontSize(14)
  8470. .fontColor($r('app.color.text_color'))
  8471. .margin({ left: 22 })
  8472. TextInput({ text: item.COMPOSER })
  8473. .height(40)
  8474. .maxLines(1)
  8475. .fontSize(14)
  8476. .layoutWeight(1)
  8477. .fontColor($r('app.color.text_color'))
  8478. .margin({ right: 20, left: 10 })
  8479. .onChange((val: string) => {
  8480. this.composerStr = val
  8481. })
  8482. }
  8483. .width('100%')
  8484. .margin({ top: 10, bottom: 10 })
  8485. .justifyContent(FlexAlign.Start)
  8486. Row() {
  8487. Text('作词:')
  8488. .fontSize(14)
  8489. .fontColor($r('app.color.text_color'))
  8490. .margin({ left: 22 })
  8491. TextInput({ text: item.LYRICIST })
  8492. .height(40)
  8493. .maxLines(1)
  8494. .fontSize(14)
  8495. .layoutWeight(1)
  8496. .fontColor($r('app.color.text_color'))
  8497. .margin({ right: 20, left: 10 })
  8498. .onChange((val: string) => {
  8499. this.lyricistStr = val
  8500. })
  8501. }
  8502. .width('100%')
  8503. .margin({ top: 10, bottom: 10 })
  8504. .justifyContent(FlexAlign.Start)
  8505. Row() {
  8506. Text('注释:')
  8507. .fontSize(14)
  8508. .fontColor($r('app.color.text_color'))
  8509. .margin({ left: 22 })
  8510. TextInput({ text: item.COMMENT })
  8511. .height(40)
  8512. .maxLines(1)
  8513. .fontSize(14)
  8514. .layoutWeight(1)
  8515. .fontColor($r('app.color.text_color'))
  8516. .margin({ right: 20, left: 10 })
  8517. .onChange((val: string) => {
  8518. this.commentStr = val
  8519. })
  8520. }
  8521. .width('100%')
  8522. .margin({ top: 10, bottom: 10 })
  8523. .justifyContent(FlexAlign.Start)
  8524. Row() {
  8525. Button('保存')
  8526. .fontColor(Color.White)
  8527. .layoutWeight(1)
  8528. .height(50)
  8529. .width(100)
  8530. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8531. .backgroundColor(this.themeColor)
  8532. .stateEffect(true)
  8533. .margin({ right: 20, bottom: 20 })
  8534. .onClick(async () => {
  8535. this.doEdit(item)
  8536. })
  8537. Button('取消')
  8538. .fontColor(Color.White)
  8539. .layoutWeight(1)
  8540. .height(50)
  8541. .width(100)
  8542. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8543. .backgroundColor(this.themeColor)
  8544. .stateEffect(true)
  8545. .margin({ left: 20, bottom: 20 })
  8546. .onClick(async () => {
  8547. if(this.isGridMusic){
  8548. this.longItemFilePath =''
  8549. }else{
  8550. this.isShowEdit = false
  8551. }
  8552. this.setEditStrEmpty()
  8553. if(this.isShowPlay){
  8554. this.isShowEdit = false
  8555. }
  8556. })
  8557. }
  8558. .margin({
  8559. left: 38,
  8560. right: 38,
  8561. top: 10,
  8562. bottom: 10
  8563. })
  8564. .width(250)
  8565. .height(60)
  8566. }
  8567. }
  8568. .margin({ bottom: 20 })
  8569. }
  8570. setEditStrEmpty(){
  8571. this.imagePathStr = ''
  8572. this.lyricConStr = ''
  8573. this.artistStr = ''
  8574. this.titleStr = ''
  8575. this.ablumStr = ''
  8576. this.genreStr = ''
  8577. this.yearStr = ''
  8578. this.trackStr = ''
  8579. this.albumArtistStr = ''
  8580. this.composerStr = ''
  8581. this.lyricistStr = ''
  8582. this.commentStr = ''
  8583. this.discStr = ''
  8584. }
  8585. initEditFields(item?: VideoItem) {
  8586. if (!item) {
  8587. this.setEditStrEmpty()
  8588. return
  8589. }
  8590. this.imagePathStr = ''
  8591. this.titleStr = item.name ?? ''
  8592. this.artistStr = item.artist ?? ''
  8593. this.ablumStr = item.album ?? ''
  8594. this.genreStr = item.genre ?? ''
  8595. this.yearStr = item.year ?? ''
  8596. this.trackStr = item.track ?? ''
  8597. this.albumArtistStr = item.ALBUMARTIST ?? ''
  8598. this.composerStr = item.COMPOSER ?? ''
  8599. this.lyricistStr = item.LYRICIST ?? ''
  8600. this.commentStr = item.COMMENT ?? ''
  8601. this.discStr = item.disc ?? ''
  8602. this.lyricConStr = item.lyricContent ?? ''
  8603. }
  8604. private syncEditedFields(target?: VideoItem) {
  8605. if (!target) {
  8606. return
  8607. }
  8608. target.name = this.titleStr
  8609. target.artist = this.artistStr
  8610. target.album = this.ablumStr
  8611. target.lyricContent = this.lyricConStr
  8612. target.year = this.yearStr
  8613. target.genre = this.genreStr
  8614. target.track = this.trackStr
  8615. target.ALBUMARTIST = this.albumArtistStr
  8616. target.COMPOSER = this.composerStr
  8617. target.LYRICIST = this.lyricistStr
  8618. target.COMMENT = this.commentStr
  8619. target.disc = this.discStr
  8620. }
  8621. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  8622. apply?: (next: Array<VideoItem>) => void) {
  8623. if (!list || ArrayUtil.isEmpty(list)) {
  8624. return
  8625. }
  8626. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  8627. if (index < 0) {
  8628. return
  8629. }
  8630. const nextList = [...list]
  8631. this.syncEditedFields(nextList[index])
  8632. apply?.(nextList)
  8633. }
  8634. private syncListsAfterEdit(filePath: string) {
  8635. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  8636. this.videoLocalList = next
  8637. this.dataSource.pushArrayData(next)
  8638. })
  8639. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  8640. this.songList = next
  8641. this.sonDataSource.pushArrayData(next)
  8642. })
  8643. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  8644. this.favList = next
  8645. })
  8646. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  8647. this.historyList = next
  8648. })
  8649. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  8650. this.currentSongList = next
  8651. })
  8652. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  8653. this.mediaKuList = next
  8654. })
  8655. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  8656. this.filteredList = next
  8657. })
  8658. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  8659. this.artistList = next
  8660. })
  8661. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  8662. this.albumList = next
  8663. })
  8664. this.listRefreshKey++
  8665. }
  8666. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  8667. if (!mainListUpdated && !playlistUpdated) {
  8668. return;
  8669. }
  8670. this.listRefreshKey++;
  8671. if (mainListUpdated) {
  8672. this.dataSource.notifyDataReload();
  8673. }
  8674. if (playlistUpdated) {
  8675. this.sonDataSource.notifyDataReload();
  8676. }
  8677. }
  8678. @Builder
  8679. detailSheet(item:VideoItem) {
  8680. Scroll() {
  8681. Column() {
  8682. this.songDetail(item)
  8683. }
  8684. }
  8685. .width('100%')
  8686. .height('100%')
  8687. }
  8688. @Builder
  8689. songDetail(currentItem:VideoItem) {
  8690. Column() {
  8691. if (currentItem) {
  8692. Row() {
  8693. Stack() {
  8694. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  8695. currentItem.pixelMapPath)
  8696. .fillColor(this.themeColor)
  8697. .height(80)
  8698. .width(80)
  8699. .borderRadius(10)
  8700. .opacity(this.opacityItem)// 绑定透明度
  8701. .margin({ left: 22 })
  8702. }
  8703. Column() {
  8704. Column() {
  8705. Text(currentItem.name)
  8706. .fontSize(16)
  8707. .maxLines(1)
  8708. .animation({
  8709. duration: 555,
  8710. curve: 'Linear',
  8711. })
  8712. .fontColor($r('app.color.text_color'))
  8713. .margin({ left: 15 })
  8714. }
  8715. .height('100%')
  8716. .width('100%')
  8717. .justifyContent(FlexAlign.Center)
  8718. .alignItems(HorizontalAlign.Start)
  8719. }
  8720. .height('100%')
  8721. }
  8722. .width('100%')
  8723. .height(90)
  8724. .justifyContent(FlexAlign.SpaceBetween)
  8725. Row() {
  8726. Text('艺术家:')
  8727. .fontSize(14)
  8728. .fontColor($r('app.color.text_color'))
  8729. .margin({ left: 22 })
  8730. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  8731. .fontSize(14)
  8732. .fontColor($r('app.color.text_color'))
  8733. .margin({ left: 10 })
  8734. .layoutWeight(1)
  8735. }
  8736. .width('100%')
  8737. .margin({ top: 10, bottom: 10 })
  8738. .justifyContent(FlexAlign.Start)
  8739. Row() {
  8740. Text('专辑名:')
  8741. .fontSize(14)
  8742. .fontColor($r('app.color.text_color'))
  8743. .margin({ left: 22 })
  8744. Text(currentItem?.album ?currentItem.album : '未知专辑')
  8745. .fontSize(14)
  8746. .margin({ left: 10 })
  8747. .fontColor($r('app.color.text_color'))
  8748. .layoutWeight(1)
  8749. }
  8750. .width('100%')
  8751. .margin({ top: 10, bottom: 10 })
  8752. .justifyContent(FlexAlign.Start)
  8753. Row() {
  8754. Text('时长:')
  8755. .fontSize(14)
  8756. .fontColor($r('app.color.text_color'))
  8757. .margin({ left: 22 })
  8758. Text(StrUtil.isEmpty(currentItem.duration)?
  8759. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  8760. .fontSize(14)
  8761. .margin({ left: 10 })
  8762. .fontColor($r('app.color.text_color'))
  8763. .layoutWeight(1)
  8764. }
  8765. .width('100%')
  8766. .margin({ top: 10, bottom: 10 })
  8767. .justifyContent(FlexAlign.Start)
  8768. Row() {
  8769. Text('采样率:')
  8770. .fontSize(14)
  8771. .fontColor($r('app.color.text_color'))
  8772. .margin({ left: 22 })
  8773. Text(Utility.convertToKHz(currentItem.sampleRate))
  8774. .fontSize(14)
  8775. .margin({ left: 10 })
  8776. .fontColor($r('app.color.text_color'))
  8777. .layoutWeight(1)
  8778. }
  8779. .width('100%')
  8780. .margin({ top: 10, bottom: 10 })
  8781. .justifyContent(FlexAlign.Start)
  8782. Row() {
  8783. Text('比特率:')
  8784. .fontSize(14)
  8785. .fontColor($r('app.color.text_color'))
  8786. .margin({ left: 22 })
  8787. Text(currentItem.bit_rate)
  8788. .fontSize(14)
  8789. .margin({ left: 10 })
  8790. .fontColor($r('app.color.text_color'))
  8791. .layoutWeight(1)
  8792. }
  8793. .width('100%')
  8794. .margin({ top: 10, bottom: 10 })
  8795. .justifyContent(FlexAlign.Start)
  8796. Row() {
  8797. Text('位深:')
  8798. .fontSize(14)
  8799. .fontColor($r('app.color.text_color'))
  8800. .margin({ left: 22 })
  8801. Text(`${currentItem.bits_per_raw_sample} bits`)
  8802. .fontSize(14)
  8803. .margin({ left: 10 })
  8804. .fontColor($r('app.color.text_color'))
  8805. .layoutWeight(1)
  8806. }
  8807. .width('100%')
  8808. .margin({ top: 10, bottom: 10 })
  8809. .justifyContent(FlexAlign.Start)
  8810. Row() {
  8811. Text('声道:')
  8812. .fontSize(14)
  8813. .fontColor($r('app.color.text_color'))
  8814. .margin({ left: 22 })
  8815. Text(`${currentItem.channels}`)
  8816. .fontSize(14)
  8817. .margin({ left: 10 })
  8818. .fontColor($r('app.color.text_color'))
  8819. .layoutWeight(1)
  8820. }
  8821. .width('100%')
  8822. .margin({ top: 10, bottom: 10 })
  8823. .justifyContent(FlexAlign.Start)
  8824. Row() {
  8825. Text('声道布局:')
  8826. .fontSize(14)
  8827. .fontColor($r('app.color.text_color'))
  8828. .margin({ left: 22 })
  8829. Text(`${currentItem.channel_layout}`)
  8830. .fontSize(14)
  8831. .margin({ left: 10 })
  8832. .fontColor($r('app.color.text_color'))
  8833. .layoutWeight(1)
  8834. }
  8835. .width('100%')
  8836. .margin({ top: 10, bottom: 10 })
  8837. .justifyContent(FlexAlign.Start)
  8838. Row() {
  8839. Text('起始播放点:')
  8840. .fontSize(14)
  8841. .fontColor($r('app.color.text_color'))
  8842. .margin({ left: 22 })
  8843. Text(`${currentItem.start_time}`)
  8844. .fontSize(14)
  8845. .margin({ left: 10 })
  8846. .fontColor($r('app.color.text_color'))
  8847. .layoutWeight(1)
  8848. }
  8849. .width('100%')
  8850. .margin({ top: 10, bottom: 10 })
  8851. .justifyContent(FlexAlign.Start)
  8852. Row() {
  8853. Text('风格:')
  8854. .fontSize(14)
  8855. .fontColor($r('app.color.text_color'))
  8856. .margin({ left: 22 })
  8857. Text(currentItem.genre)
  8858. .fontSize(14)
  8859. .margin({ left: 10 })
  8860. .fontColor($r('app.color.text_color'))
  8861. .layoutWeight(1)
  8862. }
  8863. .width('100%')
  8864. .margin({ top: 10, bottom: 10 })
  8865. .justifyContent(FlexAlign.Start)
  8866. Row() {
  8867. Text('发行时间:')
  8868. .fontSize(14)
  8869. .fontColor($r('app.color.text_color'))
  8870. .margin({ left: 22 })
  8871. Text(currentItem.year)
  8872. .fontSize(14)
  8873. .margin({ left: 10 })
  8874. .fontColor($r('app.color.text_color'))
  8875. .layoutWeight(1)
  8876. }
  8877. .width('100%')
  8878. .margin({ top: 10, bottom: 10 })
  8879. .justifyContent(FlexAlign.Start)
  8880. Row() {
  8881. Text('质量评分:')
  8882. .fontSize(14)
  8883. .fontColor($r('app.color.text_color'))
  8884. .margin({ left: 22 })
  8885. Text(currentItem.probe_score+"")
  8886. .fontSize(14)
  8887. .margin({ left: 10 })
  8888. .fontColor($r('app.color.text_color'))
  8889. .layoutWeight(1)
  8890. }
  8891. .width('100%')
  8892. .margin({ top: 10, bottom: 10 })
  8893. .justifyContent(FlexAlign.Start)
  8894. Row() {
  8895. Text('音轨号:')
  8896. .fontSize(14)
  8897. .fontColor($r('app.color.text_color'))
  8898. .margin({ left: 22 })
  8899. Text(currentItem.track)
  8900. .fontSize(14)
  8901. .margin({ left: 10 })
  8902. .fontColor($r('app.color.text_color'))
  8903. .layoutWeight(1)
  8904. }
  8905. .width('100%')
  8906. .margin({ top: 10, bottom: 10 })
  8907. .justifyContent(FlexAlign.Start)
  8908. Row() {
  8909. Text('碟号:')
  8910. .fontSize(14)
  8911. .fontColor($r('app.color.text_color'))
  8912. .margin({ left: 22 })
  8913. Text(currentItem.disc)
  8914. .fontSize(14)
  8915. .margin({ left: 10 })
  8916. .fontColor($r('app.color.text_color'))
  8917. .layoutWeight(1)
  8918. }
  8919. .width('100%')
  8920. .margin({ top: 10, bottom: 10 })
  8921. .justifyContent(FlexAlign.Start)
  8922. Row() {
  8923. Text('专辑艺术家:')
  8924. .fontSize(14)
  8925. .fontColor($r('app.color.text_color'))
  8926. .margin({ left: 22 })
  8927. Text(currentItem.ALBUMARTIST)
  8928. .fontSize(14)
  8929. .margin({ left: 10 })
  8930. .fontColor($r('app.color.text_color'))
  8931. .layoutWeight(1)
  8932. }
  8933. .width('100%')
  8934. .margin({ top: 10, bottom: 10 })
  8935. .justifyContent(FlexAlign.Start)
  8936. Row() {
  8937. Text('作曲家:')
  8938. .fontSize(14)
  8939. .fontColor($r('app.color.text_color'))
  8940. .margin({ left: 22 })
  8941. Text(currentItem.COMPOSER)
  8942. .fontSize(14)
  8943. .margin({ left: 10 })
  8944. .fontColor($r('app.color.text_color'))
  8945. .layoutWeight(1)
  8946. }
  8947. .width('100%')
  8948. .margin({ top: 10, bottom: 10 })
  8949. .justifyContent(FlexAlign.Start)
  8950. Row() {
  8951. Text('作词家:')
  8952. .fontSize(14)
  8953. .fontColor($r('app.color.text_color'))
  8954. .margin({ left: 22 })
  8955. Text(currentItem.LYRICIST)
  8956. .fontSize(14)
  8957. .margin({ left: 10 })
  8958. .fontColor($r('app.color.text_color'))
  8959. .layoutWeight(1)
  8960. }
  8961. .width('100%')
  8962. .margin({ top: 10, bottom: 10 })
  8963. .justifyContent(FlexAlign.Start)
  8964. Row() {
  8965. Text('注释:')
  8966. .fontSize(14)
  8967. .fontColor($r('app.color.text_color'))
  8968. .margin({ left: 22 })
  8969. Text(currentItem.COMMENT)
  8970. .fontSize(14)
  8971. .margin({ left: 10 })
  8972. .fontColor($r('app.color.text_color'))
  8973. .layoutWeight(1)
  8974. }
  8975. .width('100%')
  8976. .margin({ top: 10, bottom: 10 })
  8977. .justifyContent(FlexAlign.Start)
  8978. Row() {
  8979. Text('格式:')
  8980. .fontSize(14)
  8981. .fontColor($r('app.color.text_color'))
  8982. .margin({ left: 22 })
  8983. Text(Utility.formatMimeType(currentItem.mimeType))
  8984. .fontSize(14)
  8985. .margin({ left: 10 })
  8986. .fontColor($r('app.color.text_color'))
  8987. .layoutWeight(1)
  8988. }
  8989. .width('100%')
  8990. .margin({ top: 10, bottom: 10 })
  8991. .justifyContent(FlexAlign.Start)
  8992. Row() {
  8993. Text('播放次数:')
  8994. .fontSize(14)
  8995. .fontColor($r('app.color.text_color'))
  8996. .margin({ left: 22 })
  8997. Text(currentItem.playCount?.toString())
  8998. .fontSize(14)
  8999. .margin({ left: 10 })
  9000. .fontColor($r('app.color.text_color'))
  9001. .layoutWeight(1)
  9002. }
  9003. .width('100%')
  9004. .margin({ top: 10, bottom: 10 })
  9005. .justifyContent(FlexAlign.Start)
  9006. Row() {
  9007. Text('流数量:')
  9008. .fontSize(14)
  9009. .fontColor($r('app.color.text_color'))
  9010. .margin({ left: 22 })
  9011. Text(currentItem.nb_streams?.toString())
  9012. .fontSize(14)
  9013. .margin({ left: 10 })
  9014. .fontColor($r('app.color.text_color'))
  9015. .layoutWeight(1)
  9016. }
  9017. .width('100%')
  9018. .margin({ top: 10, bottom: 10 })
  9019. .justifyContent(FlexAlign.Start)
  9020. Row() {
  9021. Text('文件大小:')
  9022. .fontSize(14)
  9023. .fontColor($r('app.color.text_color'))
  9024. .margin({ left: 22 })
  9025. Text(currentItem.size)
  9026. .fontSize(14)
  9027. .margin({ left: 10 })
  9028. .fontColor($r('app.color.text_color'))
  9029. .layoutWeight(1)
  9030. }
  9031. .width('100%')
  9032. .margin({ top: 10, bottom: 10 })
  9033. .justifyContent(FlexAlign.Start)
  9034. Row() {
  9035. Text('文件名:')
  9036. .fontSize(14)
  9037. .fontColor($r('app.color.text_color'))
  9038. .margin({ left: 22 })
  9039. Text(currentItem.fileName)
  9040. .fontSize(14)
  9041. .margin({ left: 10 })
  9042. .fontColor($r('app.color.text_color'))
  9043. .layoutWeight(1)
  9044. }
  9045. .width('100%')
  9046. .margin({ top: 10, bottom: 10 })
  9047. .justifyContent(FlexAlign.Start)
  9048. Row() {
  9049. Text('修改时间:')
  9050. .fontSize(14)
  9051. .fontColor($r('app.color.text_color'))
  9052. .margin({ left: 22 })
  9053. Text(currentItem.cTime)
  9054. .fontSize(14)
  9055. .margin({ left: 10 })
  9056. .fontColor($r('app.color.text_color'))
  9057. .layoutWeight(1)
  9058. }
  9059. .width('100%')
  9060. .margin({ top: 10, bottom: 10 })
  9061. .justifyContent(FlexAlign.Start)
  9062. Row() {
  9063. Text('存放目录:')
  9064. .fontSize(14)
  9065. .fontColor($r('app.color.text_color'))
  9066. .margin({ left: 22 })
  9067. Text(currentItem.filePath)
  9068. .fontSize(12)
  9069. .margin({ left: 10 })
  9070. .fontColor($r('app.color.text_color'))
  9071. .layoutWeight(1)
  9072. }
  9073. .margin({ top: 10, bottom: 10 })
  9074. .width('100%')
  9075. .justifyContent(FlexAlign.Start)
  9076. Row() {
  9077. Text('内嵌歌词:')
  9078. .fontSize(14)
  9079. .fontColor($r('app.color.text_color'))
  9080. .margin({ left: 22 })
  9081. Text(currentItem.lyricContent)
  9082. .fontSize(12)
  9083. .copyOption(CopyOptions.InApp)
  9084. .margin({ left: 10 })
  9085. .fontColor($r('app.color.text_color'))
  9086. .layoutWeight(1)
  9087. }
  9088. .margin({ top: 10, bottom: 10 })
  9089. .width('100%')
  9090. .justifyContent(FlexAlign.Start)
  9091. }
  9092. }
  9093. .margin({ bottom: 20 })
  9094. }
  9095. //定时关闭布局
  9096. @Builder
  9097. TimeCloseSheet() {
  9098. Scroll() {
  9099. Column() {
  9100. this.TimeClose()
  9101. }
  9102. }
  9103. .width('100%')
  9104. .height('100%')
  9105. }
  9106. //倒计时关闭音乐,退出App功能实现。
  9107. @State selectedMinutes: number = 0 // 0表示未开启
  9108. @State remainingSeconds: number = 0
  9109. // 预设时间选项
  9110. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  9111. private formatTime(seconds: number): string {
  9112. const mins = Math.floor(seconds / 60)
  9113. const secs = seconds % 60
  9114. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  9115. }
  9116. // 开始倒计时
  9117. private handleTimeSelect(minutes: number) {
  9118. if (minutes === this.selectedMinutes) {
  9119. this.stopCountdown();
  9120. this.selectedMinutes = 0;
  9121. return;
  9122. }
  9123. this.selectedMinutes = minutes;
  9124. this.remainingSeconds = minutes * 60;
  9125. this.startCountdown(); // 新增调用
  9126. }
  9127. @Builder
  9128. TimeClose() {
  9129. Column() {
  9130. // 倒计时显示区域
  9131. Text(this.selectedMinutes > 0 ?
  9132. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  9133. "定时关闭未开启")
  9134. .fontSize(17)
  9135. .fontColor($r('app.color.text_color'))
  9136. .margin({ top: 2, bottom: 8 });
  9137. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9138. ForEach(this.presetTimes, (minutes: number, index: number) => {
  9139. // 单行时间选项容器
  9140. Row() {
  9141. // 文字描述区域
  9142. Text(this.getDisplayText(minutes))
  9143. .fontSize(15)
  9144. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  9145. $r('app.color.text_color'))// 选中态颜色变化
  9146. .textAlign(TextAlign.Start)
  9147. .layoutWeight(1); // 占据剩余空间
  9148. // 复选框样式的选择器
  9149. Row() {
  9150. if (minutes === this.selectedMinutes) {
  9151. // 选中状态 - 带勾号的圆形复选框
  9152. Row() {
  9153. // 使用系统内置的勾号图标
  9154. Image($r('sys.media.ohos_ic_public_ok'))
  9155. .width(14)
  9156. .height(14)
  9157. .fillColor(Color.White)
  9158. }
  9159. .width(24)
  9160. .height(24)
  9161. .borderRadius(12)
  9162. .backgroundColor(this.themeColor)
  9163. .justifyContent(FlexAlign.Center)
  9164. .alignItems(VerticalAlign.Center)
  9165. } else {
  9166. // 未选中状态的圆形边框
  9167. Row()
  9168. .width(24)
  9169. .height(24)
  9170. .borderRadius(12)
  9171. .border({
  9172. width: 2,
  9173. color: $r('app.color.text_color'),
  9174. style: BorderStyle.Solid
  9175. })
  9176. .backgroundColor(Color.Transparent)
  9177. }
  9178. }
  9179. .width(24)
  9180. .height(24)
  9181. .margin({ left: 20 })
  9182. .justifyContent(FlexAlign.Center)
  9183. .alignItems(VerticalAlign.Center)
  9184. }
  9185. .width('100%')
  9186. .padding({
  9187. top: 18,
  9188. bottom: 18,
  9189. left: 18,
  9190. right: 18
  9191. })
  9192. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  9193. $r('app.color.bottom_control_background')) // 选中背景高亮
  9194. .borderRadius(12)
  9195. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9196. .margin({ bottom: 18 })
  9197. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  9198. });
  9199. }
  9200. .width('100%')
  9201. .padding(16)
  9202. }
  9203. }
  9204. // 获取显示文本
  9205. private getDisplayText(minutes: number): string {
  9206. if (minutes === -1) {
  9207. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  9208. }
  9209. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  9210. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  9211. }
  9212. // 处理选择事件
  9213. private handleSelect(minutes: number): void {
  9214. if (minutes === -1) { // 自定义
  9215. // 弹出自定义时间对话框
  9216. DialogHelper.showTextInputDialog({
  9217. title: '自定义时间',
  9218. maskColor: Color.Transparent,
  9219. inputType: InputType.Number,
  9220. text: '',
  9221. onChange: (text) => {
  9222. console.error("onChange: " + text);
  9223. },
  9224. onAction: (action, dialogId, content) => {
  9225. if (action == DialogAction.TWO) {
  9226. const customMinutes = Number(content);
  9227. if (customMinutes > 0) {
  9228. this.handleTimeSelect(customMinutes); // 设置自定义时间
  9229. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  9230. }
  9231. }
  9232. }
  9233. });
  9234. } else {
  9235. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  9236. }
  9237. }
  9238. // 添加定时器引用
  9239. private timerId: number = -1;
  9240. // 启动/重置倒计时
  9241. private startCountdown() {
  9242. // 清除旧定时器
  9243. if (this.timerId !== -1) {
  9244. clearInterval(this.timerId);
  9245. }
  9246. // 创建新定时器
  9247. if (this.selectedMinutes > 0) {
  9248. this.timerId = setInterval(() => {
  9249. if (this.remainingSeconds === 15) {
  9250. this.showConfirmationDialog();
  9251. }
  9252. if (this.remainingSeconds > 0) {
  9253. this.remainingSeconds -= 1;
  9254. } else {
  9255. this.stopCountdown();
  9256. this.handleTimeout();
  9257. }
  9258. }, 1000);
  9259. }
  9260. }
  9261. // 15倒计时后再次提示显示确认是否关闭App对话框
  9262. private showConfirmationDialog() {
  9263. DialogHelper.showAlertDialog({
  9264. backgroundColor: $r('app.color.btn_green'),
  9265. title: '确认关闭',
  9266. maskColor: Color.Transparent,
  9267. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  9268. borderStyle: BorderStyle.Dashed,
  9269. primaryButton: '暂不关闭',
  9270. secondaryButton: '确定',
  9271. onAction: (action) => {
  9272. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  9273. this.stopCountdown();
  9274. this.selectedMinutes = 0
  9275. } else if (action == DialogAction.TWO) {
  9276. }
  9277. }
  9278. })
  9279. }
  9280. // 停止倒计时
  9281. private stopCountdown() {
  9282. if (this.timerId !== -1) {
  9283. clearInterval(this.timerId);
  9284. this.timerId = -1;
  9285. }
  9286. }
  9287. // 超时处理
  9288. private handleTimeout() {
  9289. // 执行播放器关闭逻辑
  9290. this.selectedMinutes = 0;
  9291. ToastUtil.showToast(" 定时关闭已完成");
  9292. this.stop(); // 假设存在的播放器实例
  9293. //退出APP
  9294. const mContext = getContext(this) as common.UIAbilityContext
  9295. mContext.terminateSelf();
  9296. AvSessionController.getInstance(true).unregisterSessionListener()
  9297. }
  9298. //倒计时关闭音乐,退出App功能实现结束。
  9299. //播放列表的拖动List 重新排序
  9300. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  9301. //左滑操作 移动文件 重命名 删除等操作
  9302. @Builder
  9303. sonButton(item: VideoItem, index: number, filePath: string) {
  9304. Row() {
  9305. //加入下一首播放
  9306. Button() {
  9307. Image($r('app.media.next_to_play'))
  9308. .fillColor(Color.White)
  9309. .width(20)
  9310. }
  9311. .width(40)
  9312. .height(40)
  9313. .type(ButtonType.Circle)
  9314. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  9315. .backgroundColor(this.themeColor)
  9316. .margin(5)
  9317. .onClick(() => {
  9318. this.addToNextPlay(item);
  9319. })
  9320. Button() {
  9321. Image($r('app.media.close'))
  9322. .fillColor(Color.White)
  9323. .width(20)
  9324. }
  9325. .width(40)
  9326. .height(40)
  9327. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  9328. .type(ButtonType.Circle)
  9329. .backgroundColor(this.themeColor)
  9330. .margin(5)
  9331. .onClick(() => {
  9332. this.songList.splice(Number(index), 1)
  9333. this.sonDataSource.pushArrayData(this.songList)
  9334. })
  9335. Button() {
  9336. Image($r('app.media.share2'))
  9337. .fillColor(Color.White)
  9338. .width(20)
  9339. }
  9340. .width(40)
  9341. .height(40)
  9342. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  9343. .type(ButtonType.Circle)
  9344. .backgroundColor(this.themeColor)
  9345. .margin(5)
  9346. .onClick(() => {
  9347. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  9348. })
  9349. }
  9350. }
  9351. itemMoveSon(index: number, newIndex: number): void {
  9352. if (newIndex < 0 || newIndex >= this.songList.length) {
  9353. return;
  9354. }
  9355. let tmp = this.songList.splice(index, 1);
  9356. this.songList.splice(newIndex, 0, tmp[0]);
  9357. this.sonDataSource.pushArrayData(this.songList)
  9358. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  9359. if(this.modeType==4&&this.playlistTable){
  9360. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  9361. }
  9362. }
  9363. @Builder
  9364. PlayList() {
  9365. List({ scroller: this.playListScroller }) {
  9366. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  9367. ListItem() {
  9368. this.MusicItemSon(item, index)
  9369. }
  9370. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  9371. .animation({
  9372. duration: 666,
  9373. curve: 'ease-in-out' // 可选动画曲线
  9374. })
  9375. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  9376. TransitionEffect.scale({ x: 0, y: 0 })))
  9377. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  9378. //拖动List关键代码开始
  9379. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  9380. .zIndex(this.dragItem === index ? 1 : 0)
  9381. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  9382. .gesture(
  9383. GestureGroup(GestureMode.Sequence,
  9384. LongPressGesture({ repeat: true })
  9385. .onAction((event?: GestureEvent) => {
  9386. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  9387. this.scaleItem = index
  9388. })
  9389. })
  9390. .onActionEnd(() => {
  9391. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  9392. this.scaleItem = -1
  9393. })
  9394. }),
  9395. PanGesture({ fingers: 1, direction: null, distance: 0 })
  9396. .onActionStart(() => {
  9397. this.dragItem = index // 记录当前拖动项索引
  9398. this.dragRefOffset = 0 // 重置偏移基准
  9399. })
  9400. .onActionUpdate((event: GestureEvent) => {
  9401. this.offsetY = event.offsetY - this.dragRefOffset;
  9402. this.neighborItem = -1;
  9403. let indexA = this.songList.indexOf(item);
  9404. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  9405. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  9406. let value: number = 0;
  9407. if (this.offsetY < 0) {
  9408. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  9409. this.neighborItem = indexA - 1;
  9410. this.neighborScale = 1 - value / 20;
  9411. } else if (this.offsetY > 0) {
  9412. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  9413. this.neighborItem = indexA + 1;
  9414. this.neighborScale = 1 - value / 20;
  9415. }
  9416. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  9417. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9418. this.offsetY -= this.ITEM_INTV;
  9419. this.dragRefOffset += this.ITEM_INTV;
  9420. this.itemMoveSon(indexA, indexA + 1);
  9421. });
  9422. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  9423. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9424. this.offsetY += this.ITEM_INTV;
  9425. this.dragRefOffset -= this.ITEM_INTV;
  9426. this.itemMoveSon(indexA, indexA - 1);
  9427. });
  9428. }
  9429. })
  9430. .onActionEnd((event: GestureEvent) => {
  9431. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9432. this.dragItem = -1
  9433. this.neighborItem = -1
  9434. })
  9435. animateTo({
  9436. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  9437. }, () => {
  9438. this.scaleItem = -1
  9439. })
  9440. })
  9441. )
  9442. .onCancel(() => {
  9443. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9444. this.dragItem = -1
  9445. this.neighborItem = -1
  9446. })
  9447. animateTo({
  9448. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  9449. }, () => {
  9450. this.scaleItem = -1
  9451. })
  9452. })
  9453. ) //拖动List关键代码结束
  9454. .onClick(() => {
  9455. this.doPlay(item, index, true)
  9456. })
  9457. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  9458. }
  9459. .width('100%')
  9460. .height('100%')
  9461. .onReachEnd(() => {
  9462. if(this.modeType === 4 )
  9463. return;
  9464. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  9465. const isStreamingSong = this.currentSong && (
  9466. isNavidromeType(this.currentSong.type) ||
  9467. isJellyfinType(this.currentSong.type) ||
  9468. isEmbyType(this.currentSong.type) ||
  9469. isAudioStationType(this.currentSong.type) ||
  9470. isPlexType(this.currentSong.type)
  9471. );
  9472. if (isStreamingSong && hasMoreData()) {
  9473. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  9474. void this.loadMoreNavidromeSongs();
  9475. } else {
  9476. void this.tryLoadNextPageForPlayback();
  9477. }
  9478. })
  9479. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  9480. // .animation({ duration: 500, curve: Curve.Ease }))
  9481. .cachedCount(10)
  9482. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  9483. .gesture(PinchGesture({ fingers: 2 })
  9484. .onActionEnd((event: GestureEvent) => {
  9485. this.setSonListTwoFingers()
  9486. })
  9487. .onActionUpdate(e => {
  9488. this.scaleValue = this.pinchValue * e.scale
  9489. })
  9490. .onActionStart(e => {
  9491. }))
  9492. .padding({
  9493. bottom: 0
  9494. })
  9495. }
  9496. setSonListTwoFingers() {
  9497. this.pinchValue = this.scaleValue;
  9498. Logger.info('this.pinchValue = ' + this.pinchValue);
  9499. if (this.pinchValue >= 1) {
  9500. this.sonTwoFingerType++
  9501. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  9502. if (this.sonTwoFingerType > 3) {
  9503. this.sonTwoFingerType = 1
  9504. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  9505. }
  9506. } else {
  9507. this.sonTwoFingerType--
  9508. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  9509. if (this.sonTwoFingerType < 1) {
  9510. this.sonTwoFingerType = 1
  9511. }
  9512. }
  9513. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  9514. this.pinchValue = 1;
  9515. this.scaleValue = 1;
  9516. }
  9517. @State sonTwoFingerType:number = 3
  9518. @Builder
  9519. private MusicItemSon(item: VideoItem, index?: number) {
  9520. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9521. Row() {
  9522. Stack() {
  9523. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  9524. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  9525. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  9526. .alt($r('app.media.alt'))
  9527. .fillColor(this.themeColor)
  9528. .borderRadius(this.isCoverRectangle?11:'100%')
  9529. .clip(true)
  9530. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  9531. .draggable(false)// 禁止长按手势拖动
  9532. .autoResize(true) // 重采样,可减少内存占用
  9533. .margin({ left: 20 })
  9534. }
  9535. .width('15%')
  9536. Column() {
  9537. Column() {
  9538. Text(this.isShowFileName?item.fileName :item.name)
  9539. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  9540. .fontColor(this.curIndex === index ? this.themeColor :
  9541. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  9542. .maxLines(1)
  9543. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  9544. Row() {
  9545. Column(){
  9546. Text(item.md5Str?.includes('Lossless')?
  9547. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  9548. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  9549. .padding({ top: 3,right:6,left:6,bottom:3 })
  9550. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  9551. $r('app.color.text_color'))
  9552. .fontWeight(500)
  9553. .borderRadius(12)
  9554. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  9555. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  9556. .backgroundColor('#FFC107')
  9557. }
  9558. .padding({ top: 8 })
  9559. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  9560. item.artist + ' ' + item?.duration)
  9561. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  9562. .padding({ top: 8 })
  9563. .maxLines(1)
  9564. .fontColor(this.curIndex === index ? this.themeColor :
  9565. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  9566. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  9567. Blank()
  9568. Text(item.size)
  9569. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  9570. .padding({ top: 8 })
  9571. .maxLines(1)
  9572. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  9573. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  9574. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  9575. .margin({ left: 10 })
  9576. }
  9577. }
  9578. .height('100%')
  9579. .width('100%')
  9580. .justifyContent(FlexAlign.Center)
  9581. .alignItems(HorizontalAlign.Start)
  9582. }
  9583. .height('100%')
  9584. .width('65%')
  9585. Column() {
  9586. ImageAnimator()
  9587. .images(this.imagesF)// 动画数组
  9588. .duration(1000)// 持续
  9589. .state(this.animationState)// 动画状态
  9590. .fillMode(FillMode.Forwards)
  9591. .width(18)
  9592. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  9593. Visibility.None)
  9594. .height(18)
  9595. .iterations(-1) // 播放次数
  9596. }
  9597. .width('20%')
  9598. }
  9599. }
  9600. .backgroundColor(Color.Transparent)
  9601. .width('100%')
  9602. .reuseId('son_item')
  9603. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  9604. .shadow(this.scaleItem === index ? {
  9605. radius: 70,
  9606. color: '#15000000',
  9607. offsetX: 0,
  9608. offsetY: 0
  9609. } :
  9610. {
  9611. radius: 0,
  9612. color: '#15000000',
  9613. offsetX: 0,
  9614. offsetY: 0
  9615. })
  9616. .animation({ curve: Curve.Sharp, duration: 300 })
  9617. }
  9618. @Builder
  9619. MusicPlayBuilder() {
  9620. Column() {
  9621. this.IjkMusicPlayerView()
  9622. }
  9623. .transition(TransitionEffect.asymmetric(
  9624. TransitionEffect.opacity(1),
  9625. TransitionEffect.OPACITY
  9626. ))
  9627. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  9628. new hdsEffect.HdsEffectBuilder()
  9629. .shaderEffect({
  9630. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  9631. animation: {
  9632. duration: 10000,
  9633. iterations: -1,
  9634. autoPlay: true,
  9635. onFinish: ()=> {
  9636. console.info('Succeeded in finishing');
  9637. }
  9638. },
  9639. controller: this.bgController,
  9640. })
  9641. .buildEffect():null)
  9642. .height('100%')
  9643. .width('100%')
  9644. .onDisAppear(() => {
  9645. this.translateY = 0;
  9646. })
  9647. .translate({ y: this.translateY })
  9648. .gesture(
  9649. PanGesture(this.panOption)
  9650. .onActionUpdate((event?: GestureEvent) => {
  9651. if (event) {
  9652. // 判断滑动方向
  9653. const offsetY = event.offsetY ?? 0;
  9654. const isSwipeUp = offsetY < 0;
  9655. if (isSwipeUp) {
  9656. // 向上滑动:不应用位移动画,保持 translateY = 0
  9657. this.translateY = 0;
  9658. } else {
  9659. if(this.isGeKongPlayNext){
  9660. return
  9661. }
  9662. // 向下滑动:应用位移动画
  9663. this.translateY = offsetY;
  9664. // 向下滑动时的缩放效果
  9665. this.getUIContext().animateTo({
  9666. duration: 500,
  9667. curve: Curve.Sharp
  9668. }, () => {
  9669. this.scaleValueImage = Math.min(1, Math.max(0.38, 1 - this.translateY / 500));
  9670. console.info('onecold scaleValueImage:', this.scaleValueImage)
  9671. this.scaleValueText = Math.min(1, Math.max(0.6, 1 - this.translateY / 700));
  9672. })
  9673. }
  9674. }
  9675. })
  9676. .onActionEnd((event?: GestureEvent) => {
  9677. // 判断滑动方向
  9678. const offsetY = event?.offsetY ?? 0;
  9679. const isSwipeUp = offsetY < 0;
  9680. const minDistance = 300; // 最小滑动距离
  9681. const minVelocity = 500; // 最小滑动速度
  9682. const velocity = event?.velocityY ?? 0;
  9683. if (isSwipeUp) {
  9684. // 向上滑动:切换下一首
  9685. const shouldSwitch = Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity;
  9686. if (shouldSwitch) {
  9687. // 直接切换下一首,无需动画(因为界面没有移动)
  9688. this.playNext().catch(() => {
  9689. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  9690. });
  9691. }
  9692. } else {
  9693. //这里加个变量,是否开启隔空手势播放下一首
  9694. if(this.isGeKongPlayNext){
  9695. this.playNext()
  9696. return
  9697. }
  9698. // 向下滑动:关闭播放页
  9699. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  9700. if (shouldClose) {
  9701. // 添加关闭动画
  9702. this.getUIContext().animateTo({
  9703. duration: 600,
  9704. curve: Curve.Friction
  9705. }, () => {
  9706. this.isShowPlay = false;
  9707. this.scaleValueImage = 1
  9708. this.scaleValueText = 1
  9709. this.translateY = 0;
  9710. })
  9711. } else {
  9712. // 回弹动画
  9713. this.getUIContext().animateTo({
  9714. duration: 600,
  9715. curve: Curve.Friction
  9716. }, () => {
  9717. this.scaleValueImage = 1
  9718. this.scaleValueText = 1
  9719. this.translateY = 0;
  9720. })
  9721. }
  9722. }
  9723. })
  9724. )
  9725. }
  9726. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  9727. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  9728. HeightBreakpoint.HEIGHT_LG;
  9729. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  9730. @State topBarHeight: number = 50
  9731. @State barOpacity: number = 1
  9732. @State barBottomOpacity: number = 1
  9733. private hideDone: boolean = false;
  9734. @State currentYOffset: number = 0;
  9735. @State bottomBarHeight: number = 68;
  9736. private isHiding: boolean = false;
  9737. //是否是Pura X外屏,或者小屏幕
  9738. isPuraWP() {
  9739. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9740. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  9741. }
  9742. //是否是Pura X外屏,或者小屏幕,手机横屏
  9743. /**
  9744. * 是否是Pura X外屏,或者小屏幕,手机横屏
  9745. * @returns
  9746. */
  9747. isCoverOpacity() {
  9748. if (this.isPuraWP()) {
  9749. return true
  9750. }
  9751. if (this.isPhoneLan()) {
  9752. return true
  9753. }
  9754. if (deviceInfo.marketName.includes('Pura X')
  9755. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  9756. return true
  9757. }
  9758. return false
  9759. }
  9760. //是不是手机横屏
  9761. isPhoneLan() {
  9762. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  9763. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  9764. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  9765. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  9766. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  9767. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  9768. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  9769. if (this.isHiCarKuanBianPing()) {
  9770. return true
  9771. }
  9772. if (this.isHiCar()) {
  9773. return false
  9774. }
  9775. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9776. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  9777. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  9778. return true
  9779. }
  9780. return false
  9781. }
  9782. //是不是1920x720的hicar的屏幕分辨率
  9783. isHiCarKuanBianPing(){
  9784. // if(!this.isHiCar()){
  9785. // return false
  9786. // }
  9787. const hiCarAspectRatios: HiCarAspectRatio[] = [
  9788. { ratio: 1920 / 720, name: "1920x720" },
  9789. ];
  9790. const currentRatio: number = this.windowWidth / this.windowHeight;
  9791. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  9792. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  9793. for (const hiCarRatio of hiCarAspectRatios) {
  9794. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  9795. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  9796. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  9797. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  9798. //宽扁平的尺寸设置列表展示
  9799. this.twoFingerType ==3
  9800. this.isGridMusic = false
  9801. return true;
  9802. }
  9803. }
  9804. return false;
  9805. }
  9806. //是不是hicar的屏幕分辨率
  9807. isHiCarSmall() {
  9808. if(!this.isHiCar()){
  9809. return false
  9810. }
  9811. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  9812. {
  9813. this.columns = 6
  9814. return false
  9815. }
  9816. const hiCarAspectRatios: HiCarAspectRatio[] = [
  9817. { ratio: 800 / 480, name: "800x480" },
  9818. { ratio: 1280 / 720, name: "1280x720" },
  9819. { ratio: 1920 / 1080, name: "1920x1080" },
  9820. ];
  9821. const currentRatio: number = this.windowWidth / this.windowHeight;
  9822. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  9823. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  9824. for (const hiCarRatio of hiCarAspectRatios) {
  9825. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  9826. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  9827. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  9828. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  9829. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  9830. //宽扁平的尺寸设置列表展示
  9831. return true;
  9832. }
  9833. }
  9834. return false;
  9835. }
  9836. isHiCar() {
  9837. return this.curDisplayIsHiCar;
  9838. }
  9839. //是不是正常的手机竖屏
  9840. isPhonePortrait() {
  9841. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  9842. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  9843. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  9844. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9845. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  9846. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  9847. return true
  9848. }
  9849. return false
  9850. }
  9851. @State showSpeedDialog: boolean = false
  9852. @State longPressSpeed: number = 3 //长按默认倍数
  9853. @Builder
  9854. SpeedDialog() {
  9855. Stack() {
  9856. Column() {
  9857. Text('已切换至' + this.longPressSpeed + '倍速播放')
  9858. .fontColor(Color.White)
  9859. .visibility(Visibility.Hidden)
  9860. }
  9861. .backgroundColor(Color.Black)
  9862. .borderRadius(20)
  9863. .padding({
  9864. top: 10,
  9865. right: 20,
  9866. left: 15,
  9867. bottom: 20
  9868. })
  9869. .opacity(0.6)
  9870. Text('已切换至' + this.longPressSpeed + '倍速播放')
  9871. .fontColor(Color.White)
  9872. }
  9873. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  9874. .zIndex(5)
  9875. .margin({ top: 80 })
  9876. }
  9877. @Builder
  9878. IjkMusicPlayerView() {
  9879. Stack() {
  9880. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  9881. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  9882. HdsVisualComponent()
  9883. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  9884. console.info('Succeeded in finishing');
  9885. })
  9886. .width('100%')
  9887. .height('100%')
  9888. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  9889. }
  9890. Column() {
  9891. Column() {
  9892. //播放标题
  9893. Column() {
  9894. this.PlayTitle()
  9895. }
  9896. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  9897. .width('100%')
  9898. .margin({ top: 0 })
  9899. .height(PlayConstants.HEIGHT)
  9900. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  9901. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  9902. if (this.showSpeedDialog) {
  9903. this.SpeedDialog()
  9904. }
  9905. Stack() {
  9906. //手势拖动快进
  9907. Column()
  9908. .width(CommonConstants.FULL_PERCENT)
  9909. .height('100%')
  9910. .gesture(
  9911. GestureGroup(GestureMode.Parallel,
  9912. // 长按屏幕倍数播放
  9913. LongPressGesture({ repeat: true })
  9914. .onAction(() => {
  9915. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9916. this.showSpeedDialog = true;
  9917. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  9918. }
  9919. })
  9920. .onActionEnd(() => {
  9921. this.showSpeedDialog = false;
  9922. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9923. }),
  9924. //双击屏幕暂停或者播放
  9925. TapGesture({ count: 2 })
  9926. .onAction((event: GestureEvent) => {
  9927. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9928. ToastUtil.showToast('已暂停')
  9929. }
  9930. console.info('onecold playOrPause 6693')
  9931. this.playOrPause()
  9932. })
  9933. )
  9934. )
  9935. }
  9936. .height('65%')
  9937. Swiper() {
  9938. this.CoverInfo()
  9939. this.PlayerLyrics()
  9940. }
  9941. .onChange((index: number) => {
  9942. this.currentSwiperIndex = index
  9943. })
  9944. .indicator(false)
  9945. .displayCount(new BreakpointType({
  9946. sm: 1,
  9947. md: 2,
  9948. lg: 2,
  9949. xl: 2,
  9950. xxl: 2
  9951. }).getValue(this.currentBreakpoint))
  9952. .clip(false)
  9953. .loop(false)
  9954. .autoPlay(false)
  9955. // .interval(8000)
  9956. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  9957. .height('100%')
  9958. .hitTestBehavior(HitTestMode.Transparent)
  9959. Image($r('app.media.icon_replay'))
  9960. .objectFit(ImageFit.Auto)
  9961. .width('120px')
  9962. .height('120px')
  9963. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  9964. .border({ width: 0 })
  9965. .visibility(Visibility.None)
  9966. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  9967. .onClick(() => {
  9968. console.info('onecold startPlayOrResumePlay 6744')
  9969. this.startPlayOrResumePlay();
  9970. })
  9971. }
  9972. .width(CommonConstants.FULL_PERCENT)
  9973. .height(CommonConstants.FULL_PERCENT)
  9974. .justifyContent(FlexAlign.End)
  9975. }
  9976. .justifyContent(FlexAlign.End)
  9977. .margin({ bottom: 8 })
  9978. }
  9979. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  9980. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  9981. .animation({
  9982. duration: 666,
  9983. curve: 'ease-in-out' // 可选动画曲线
  9984. })
  9985. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  9986. ? BlurStyle.NONE :
  9987. BlurStyle.BACKGROUND_ULTRA_THICK)
  9988. .hitTestBehavior(HitTestMode.Transparent)
  9989. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  9990. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  9991. .onClick(() => {
  9992. if(this.isHiCar())
  9993. return
  9994. if(this.is_auto_hide_progress){
  9995. this.is_auto_hide_progress = false
  9996. }
  9997. this.startAutoHide()
  9998. })
  9999. }
  10000. @Consume progressValue: number ;
  10001. @State currentTime: string = "00:00";
  10002. @State totalTime: string = "00:00";
  10003. @State loadingVisible: Visibility = Visibility.None;
  10004. @State replayVisible: Visibility = Visibility.None;
  10005. @State slideEnable: boolean = false;
  10006. @State aspRatio: number = 0.5;
  10007. @State mContext: object | undefined = undefined;
  10008. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  10009. @State mFirst: boolean = true;
  10010. @State mDestroyPage: boolean = false;
  10011. @State playSpeed: number = 1;
  10012. @State oldSeconds: number = 0;
  10013. @State isSeekTo: boolean = false;
  10014. @State isCurrentTime: boolean = false;
  10015. @State videoWidth: string = '100%';
  10016. @State videoHeight: string = '100%';
  10017. @State initAspectRatio: number = 1;
  10018. @State videoAspectRatio: number = this.initAspectRatio;
  10019. @State videoUrl: string = '';
  10020. private last: number = 0;
  10021. @State videoParentAspectRatio: number = this.initAspectRatio;
  10022. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  10023. @Consume CONTROL_PlayStatus: number ;
  10024. @State PROGRESS_MAX_VALUE: number = 100;
  10025. @State updateProgressTimer: number = 0;
  10026. private readonly progressUpdateIntervalMs: number = 120;
  10027. private readonly lyricUpdateMinDeltaMs: number = 24;
  10028. private lastLyricRenderPosition: number = Number.NaN;
  10029. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  10030. @State name: string = '';
  10031. // @State loop: boolean = false;
  10032. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  10033. @State multiple: string = '1.0X';
  10034. xcomponentController: XComponentController = new XComponentController()
  10035. private panOptionBright: PanGestureOptions =
  10036. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  10037. private panOptionVolume: PanGestureOptions =
  10038. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  10039. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  10040. //手势的音量控制和亮度控制
  10041. private positionX: number = PlayConstants.POSITION_X;
  10042. private positionY: number = PlayConstants.POSITION_Y;
  10043. private windowClass: window.Window = globalThis.windowClass
  10044. @State volume: number = 0.8;
  10045. @State volumeSmall: boolean = false
  10046. @State autoParseMusicName: boolean = true
  10047. @State isShowFileName: boolean = false
  10048. @State isLongNameRoLL: boolean = true//长歌名滚动
  10049. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  10050. @State bright: number = PlayConstants.BRIGHT;
  10051. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  10052. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  10053. @State screenWidth: number = 0
  10054. @State screenHeight: number = 0
  10055. @State statusBarHeight: number = 0
  10056. @State isYesFull: boolean = false
  10057. private seekValue: number = 0
  10058. @State isVideoLock: boolean = false; // Whether the video playback is locked
  10059. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  10060. eventHub = getContext().eventHub;
  10061. //投播组件
  10062. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  10063. // 新的投播控制器(封装了官方示例的逻辑)
  10064. private castControllerWrapper: CastController | undefined = undefined;
  10065. // 保留原始的 avCastController 引用(用于兼容旧代码)
  10066. private castController: avSession.AVCastController | undefined = undefined;
  10067. @State isCastPlaying: boolean = false;
  10068. @State currentTime2: number = 0;
  10069. @State currentStringTime: string = '00:00';
  10070. @State duration: number = 0;
  10071. @State isReady: boolean = false;
  10072. @State durationTime: number = 0;
  10073. @State durationStringTime: string = '00:00';
  10074. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  10075. // @State isPlaying: boolean = false;
  10076. private castSeek: boolean = false;
  10077. private castItem: avSession.AVQueueItem | undefined = undefined;
  10078. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  10079. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  10080. @State rotateAngle2: number = -9
  10081. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  10082. @Consume cover: string | undefined ;
  10083. @State artist: string | undefined = ''
  10084. // 1.初始化controller
  10085. private lyricController: LyricController = new LyricController()
  10086. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  10087. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  10088. private parser = new LyricParser()
  10089. @State randomShakenX: number = 0
  10090. @State randomShakenY: number = 0
  10091. @State lyricTextSize: number = 24
  10092. @State lyricContent: string = ''
  10093. @State isDebug: boolean = false
  10094. @State isHightLightCenter: boolean = true
  10095. /**
  10096. * 初始化歌词加载与展示逻辑
  10097. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  10098. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  10099. * @param isApi2 是否使用API2获取歌词(可选)
  10100. *
  10101. * 主要流程:
  10102. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  10103. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  10104. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  10105. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  10106. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  10107. * 6. 解析失败或读取失败时,清空歌词显示。
  10108. *
  10109. * 注意事项:
  10110. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  10111. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  10112. * - 歌词内容解析后通过lyricController驱动UI渲染。
  10113. */
  10114. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  10115. if (StrUtil.isEmpty(lyricPath)) {
  10116. return
  10117. }
  10118. this.initPipLyricSetting()
  10119. this.lyricControllerSingle
  10120. .setTextSize(15)
  10121. .setCacheSize(4)
  10122. .setTextColor("#FFFFFF")
  10123. .setHighlightColor(this.currentHighLightLyricColor)
  10124. .setHighlightScale(1.2)
  10125. .setEmptyHint("")
  10126. .setLineSpace(1)
  10127. .setAlignMode('center')
  10128. .setAnimationDuration(500)
  10129. .setSingleLine(true)
  10130. this.lyricContent = ''
  10131. this.lyricController
  10132. .setTextSize(this.currentLyricSize)
  10133. .setCacheSize(4)
  10134. .setTextColor("#DDDDDD")
  10135. .setHighlightColor("#FFFFFF")
  10136. .setEmptyHint("")
  10137. .setAnimationDuration(1000)
  10138. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  10139. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  10140. this.setBlurDegree(this.blurDegree, false)
  10141. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  10142. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  10143. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  10144. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  10145. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  10146. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  10147. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  10148. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10149. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  10150. this.lyricController.setTextWeight(this.lyricTextWeight)
  10151. this.showSingleLyric = false
  10152. // 加载已保存的歌词时间偏移
  10153. this.loadLyricTimeOffset()
  10154. this.lyricController.setLyric(null)
  10155. this.lyricControllerSingle.setLyric(null)
  10156. console.log("onecold lyricPath =" + lyricPath)
  10157. // 1. 检查内嵌歌词
  10158. let neiqianLrc = ''
  10159. let lyContent = this.currentSong?.lyricContent
  10160. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  10161. neiqianLrc = lyContent
  10162. }
  10163. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  10164. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  10165. // Navidrome JSON歌词转换
  10166. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  10167. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  10168. if (convertedLyric) {
  10169. neiqianLrc = convertedLyric;
  10170. console.log("onecold Navidrome歌词转换成功");
  10171. }
  10172. }
  10173. this.setLyricToControllers(neiqianLrc);
  10174. return
  10175. }
  10176. // 2. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  10177. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  10178. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  10179. || isPlexType(this.currentSong.type))) {
  10180. const manager = RemoteDriveManager.getInstance();
  10181. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  10182. // 将currentSong转换为SongData接口
  10183. const songData: SongData = {
  10184. webdav_account_id: this.currentSong.webdav_account_id,
  10185. artist: this.currentSong.artist,
  10186. name: this.currentSong.name,
  10187. webdav_id: this.currentSong.webdav_id,
  10188. lyricIndex: this.currentSong.lyricIndex,
  10189. type: this.currentSong.type
  10190. };
  10191. let serverLyric = '';
  10192. if (!serverLyric && isNavidromeType(songData.type)) {
  10193. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  10194. }
  10195. if (!serverLyric && isJellyfinType(songData.type)) {
  10196. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  10197. }
  10198. if (!serverLyric && isEmbyType(songData.type)) {
  10199. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  10200. }
  10201. if (!serverLyric && isAudioStationType(songData.type)) {
  10202. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  10203. }
  10204. if (!serverLyric && isPlexType(songData.type)) {
  10205. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  10206. }
  10207. if (serverLyric) {
  10208. this.setLyricToControllers(serverLyric, lyricPath);
  10209. return;
  10210. }
  10211. }
  10212. // 3. 尝试在线歌词API
  10213. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  10214. && !Utility.isVideoByExtension(this.videoUrl))) {
  10215. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  10216. return;
  10217. }
  10218. // 4. 从本地文件读取歌词
  10219. await this.loadLyricFromFile(lyricPath, isLocal || false);
  10220. }
  10221. /**
  10222. * 从本地文件加载歌词
  10223. */
  10224. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  10225. try {
  10226. let realLyricPath = lyricPath;
  10227. // 读取文件内容
  10228. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  10229. const stat = await fileIo.stat(file.fd);
  10230. const arrayBuffer = new ArrayBuffer(stat.size);
  10231. fs.read(file.fd, arrayBuffer)
  10232. .then((readLen: number) => {
  10233. console.info("read file data succeed");
  10234. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  10235. if (buf.length === 0) {
  10236. throw new Error("Buffer is empty after reading the file");
  10237. }
  10238. try {
  10239. // 检测文件编码
  10240. let detectedEncoding = this.detect(arrayBuffer);
  10241. console.info("onecoldT Detected encoding: " + detectedEncoding);
  10242. // 使用检测到的编码解码,解决中文乱码问题
  10243. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  10244. console.info("onecoldT Detected textDecoder: " + textDecoder);
  10245. let fileContent = textDecoder.decode(buf);
  10246. console.info(`onecoldT The content of file1: ${fileContent}`);
  10247. console.info(`onecold The content of file2: ${fileContent}`);
  10248. this.lyricContent = fileContent;
  10249. if(isLocal){
  10250. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  10251. this.lyricConStr = fileContent;
  10252. }
  10253. this.setLyricToControllers(fileContent);
  10254. console.info(`The content of file: ${fileContent}`);
  10255. } catch (chardetError) {
  10256. console.error("chardet.detect failed with error: " + chardetError.message);
  10257. this.clearLyricControllers();
  10258. }
  10259. })
  10260. .catch((err: BusinessError) => {
  10261. this.clearLyricControllers();
  10262. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  10263. })
  10264. .catch((err: Error) => {
  10265. this.clearLyricControllers();
  10266. console.error("read file 2 data failed with error message: " + err.message);
  10267. })
  10268. .finally(() => {
  10269. fs.closeSync(file);
  10270. });
  10271. } catch (error) {
  10272. this.clearLyricControllers();
  10273. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  10274. }
  10275. }
  10276. detect(data: ArrayBuffer): string {
  10277. //创建检测对象
  10278. let detector: UniversalDetector = new UniversalDetector();
  10279. // 限制检测数据大小,避免内存溢出
  10280. // 通常只需要检测文件前16KB就足够判断编码格式
  10281. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  10282. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  10283. // 传入检测数据并实时判断编码格式
  10284. detector.handleData(data, 0, detectSize);
  10285. // 标记检测数据 读取结束
  10286. detector.dataEnd();
  10287. // 获取检测结果
  10288. let detected: string = detector.getDetectedCharset();
  10289. // 释放资源
  10290. detector.reset();
  10291. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  10292. return detected;
  10293. }
  10294. /**
  10295. * 设置歌词到所有控制器
  10296. * @param lyricText 歌词文本
  10297. * @param savePath 可选,如果提供则保存到本地文件
  10298. */
  10299. private setLyricToControllers(lyricText: string, savePath?: string): void {
  10300. if (StrUtil.isEmpty(lyricText)) {
  10301. this.clearLyricControllers();
  10302. return;
  10303. }
  10304. this.lyricContent = lyricText;
  10305. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  10306. const lyric: Lyric = this.parser.parse(lines);
  10307. this.lyricController.setLyric(lyric);
  10308. this.lyricControllerXF.setLyric(lyric);
  10309. this.lyricControllerSingle.setLyric(lyric);
  10310. this.showSingleLyric = true;
  10311. // 如果提供了保存路径,保存歌词到本地
  10312. if (savePath) {
  10313. this.saveDataToFile(lyricText, savePath);
  10314. }
  10315. }
  10316. /**
  10317. * 清空所有歌词控制器
  10318. */
  10319. private clearLyricControllers(): void {
  10320. this.lyricController.setLyric(null);
  10321. this.lyricControllerXF.setLyric(null);
  10322. this.lyricControllerSingle.setLyric(null);
  10323. }
  10324. private extractLyricCopyLines(lyricText: string): string[] {
  10325. if (StrUtil.isEmpty(lyricText)) {
  10326. return [];
  10327. }
  10328. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  10329. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  10330. const lines = source.split('\n');
  10331. const result: string[] = [];
  10332. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  10333. for (let i = 0; i < lines.length; i++) {
  10334. const line = lines[i].trim();
  10335. if (!line || metaTagPattern.test(line)) {
  10336. continue;
  10337. }
  10338. const pureLine = line
  10339. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  10340. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  10341. .trim();
  10342. if (pureLine.length > 0) {
  10343. result.push(pureLine);
  10344. }
  10345. }
  10346. return result;
  10347. }
  10348. private openLyricCopySheet(): void {
  10349. const lines = this.extractLyricCopyLines(this.lyricContent);
  10350. if (ArrayUtil.isEmpty(lines)) {
  10351. ToastUtil.showToast('暂无可复制歌词');
  10352. return;
  10353. }
  10354. this.lyricCopyLines = lines;
  10355. this.lyricSelectedIndexes = [];
  10356. this.isShowLyricCopySheet = true;
  10357. }
  10358. private toggleLyricLineSelection(index: number): void {
  10359. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  10360. if (selectedIndex >= 0) {
  10361. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  10362. nextSelectedIndexes.splice(selectedIndex, 1);
  10363. this.lyricSelectedIndexes = nextSelectedIndexes;
  10364. return;
  10365. }
  10366. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  10367. }
  10368. private toggleLyricSelectAll(): void {
  10369. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  10370. this.lyricSelectedIndexes = [];
  10371. return;
  10372. }
  10373. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  10374. }
  10375. private copySelectedLyricLines(): void {
  10376. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  10377. ToastUtil.showToast('请先选择歌词');
  10378. return;
  10379. }
  10380. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  10381. const selectedLines: string[] = [];
  10382. for (let i = 0; i < selectedIndexes.length; i++) {
  10383. const index = selectedIndexes[i];
  10384. if (index >= 0 && index < this.lyricCopyLines.length) {
  10385. selectedLines.push(this.lyricCopyLines[index]);
  10386. }
  10387. }
  10388. if (ArrayUtil.isEmpty(selectedLines)) {
  10389. ToastUtil.showToast('暂无可复制歌词');
  10390. return;
  10391. }
  10392. Utility.copyText(selectedLines.join('\n'));
  10393. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  10394. }
  10395. /**
  10396. * 从在线API获取歌词
  10397. */
  10398. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  10399. if (!this.currentSong) {
  10400. this.clearLyricControllers();
  10401. if (isOnLineAndToast) {
  10402. ToastUtil.showShort('未获取到歌词!');
  10403. }
  10404. return;
  10405. }
  10406. let artist = this.currentSong.artist || '';
  10407. if (isApi2 === undefined) {
  10408. isApi2 = false;
  10409. }
  10410. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  10411. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10412. this.setLyricToControllers(res, lyricPath);
  10413. } else {
  10414. this.clearLyricControllers();
  10415. if (isOnLineAndToast) {
  10416. ToastUtil.showShort('未获取到歌词!');
  10417. }
  10418. }
  10419. });
  10420. }
  10421. //初始化悬浮歌词的自定义设置
  10422. initPipLyricSetting() {
  10423. this.lyricControllerXF
  10424. .setTextSize(this.currentLyricSize)
  10425. .setCacheSize(4)
  10426. .setTextColor("#DDDDDD")
  10427. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  10428. .setEmptyHint("")
  10429. .setAnimationDuration(1000)
  10430. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  10431. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  10432. this.setBlurDegree(this.blurDegreePip, true)
  10433. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  10434. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  10435. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  10436. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  10437. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  10438. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  10439. this.lyricControllerXF.setHightLightCenter(true)
  10440. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  10441. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10442. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10443. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  10444. if (this.pipBgIndex === 0) {
  10445. if (this.cover) {
  10446. this.pipBg = this.cover
  10447. } else {
  10448. this.pipBg = this.imageColor
  10449. }
  10450. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10451. }
  10452. }
  10453. //根据item返回歌词内容
  10454. async getLyricContent(item: VideoItem): Promise<string> {
  10455. let neiqianLrc = ''
  10456. let lyContent = item?.lyricContent
  10457. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  10458. neiqianLrc = lyContent
  10459. return neiqianLrc
  10460. }
  10461. try {
  10462. //取数据库里面的歌词lyContent
  10463. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  10464. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  10465. console.log("onecold Lyrics:", lyricContent);
  10466. neiqianLrc = lyricContent
  10467. return neiqianLrc
  10468. }
  10469. } catch (error) {
  10470. console.error("Error fetching lyrics:", error);
  10471. }
  10472. try {
  10473. let filePath = item.filePath;
  10474. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  10475. let realLyricPath = lyricPath;
  10476. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  10477. const stat = await fileIo.stat(file.fd);
  10478. const arrayBuffer = new ArrayBuffer(stat.size);
  10479. const readLen = await fs.read(file.fd, arrayBuffer);
  10480. console.info("read file data succeed");
  10481. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  10482. if (buf.length === 0) {
  10483. throw new Error("Buffer is empty after reading the file");
  10484. }
  10485. // let detectedEncoding = chardet.detect(buf);
  10486. let detectedEncoding = this.detect(arrayBuffer)
  10487. console.info("Detected encoding: " + detectedEncoding);
  10488. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  10489. let fileContent = textDecoder.decode(buf);
  10490. console.info(`onecold The content of file1: ${fileContent}`);
  10491. fs.closeSync(file);
  10492. return fileContent;
  10493. } catch (error) {
  10494. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  10495. return '';
  10496. }
  10497. }
  10498. async saveDataToFile(content: string, filePath: string) {
  10499. if (StrUtil.isEmpty(filePath)) {
  10500. return
  10501. }
  10502. try {
  10503. let lyricContent = ''
  10504. lyricContent = content
  10505. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  10506. // 清空文件内容
  10507. await fileIo.truncate(file.fd, 0);
  10508. await fileIo.write(file.fd, lyricContent);
  10509. await fileIo.close(file);
  10510. console.log('onecold lyric file Data saved successfully.');
  10511. } catch (error) {
  10512. console.error('onecold lyric file Failed to save data:', error);
  10513. }
  10514. }
  10515. // 定义开始旋转的方法
  10516. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  10517. @State timer: number = 0
  10518. @State rotateAngle: number = 0
  10519. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  10520. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  10521. // 页面可见性变化回调
  10522. onPageVisibilityChange() {
  10523. // 当页面可见性改变时,重新启动/停止旋转动画
  10524. this.animationRoFun()
  10525. }
  10526. //封面旋转动画
  10527. animationRoFun() {
  10528. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  10529. // 启动旋转动画
  10530. if (!this.isRotationRunning) {
  10531. this.isRotationRunning = true
  10532. this.startContinuousRotation()
  10533. }
  10534. this.startRotation()
  10535. } else {
  10536. // 停止旋转动画
  10537. this.isRotationRunning = false
  10538. clearInterval(this.timer)
  10539. this.stopRotation()
  10540. }
  10541. }
  10542. // 使用持续的动画进行旋转,避免频繁状态更新
  10543. private startContinuousRotation() {
  10544. clearInterval(this.timer)
  10545. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  10546. // 不使用 % 360 取模,让角度持续累加,避免反转
  10547. this.timer = setInterval(() => {
  10548. if (this.isRotationRunning) {
  10549. this.rotateAngle = this.rotateAngle + 36
  10550. }
  10551. }, 1000)
  10552. }
  10553. // 定义开始旋转的方法
  10554. startRotation() {
  10555. if (this.isPlaying) {
  10556. animateTo({
  10557. duration: 777,
  10558. iterations: 1,
  10559. curve: Curve.Linear
  10560. }, () => {
  10561. this.rotateAngle2 = -9
  10562. })
  10563. }
  10564. }
  10565. // 回调,暂停和播放按钮回调,下一首和上一首
  10566. playChange() {
  10567. // if(this.isCoverRectangle){
  10568. // return
  10569. // }
  10570. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10571. this.setIsPlaying(true)
  10572. this.animationState = AnimationStatus.Running
  10573. } else {
  10574. this.setIsPlaying(false)
  10575. this.animationState = AnimationStatus.Paused
  10576. }
  10577. AppStorage.setOrCreate('animationState', this.animationState);
  10578. }
  10579. // 定义停止旋转的方法
  10580. stopRotation() {
  10581. if (this.isCoverRectangle) {
  10582. this.rotateAngle = 0
  10583. } else {
  10584. //唱针以左上角为点选择逆时针40度
  10585. animateTo({
  10586. duration: 1000,
  10587. curve: Curve.Linear,
  10588. iterations: 1,
  10589. }, () => {
  10590. this.rotateAngle2 = -45;
  10591. });
  10592. }
  10593. }
  10594. @Builder
  10595. private LyricsTopItem() {
  10596. Row() {
  10597. Stack() {
  10598. Image( StrUtil.isNotEmpty(this.cover)?
  10599. this.cover:$r('app.media.alt'))
  10600. .height(58)
  10601. .width(58)
  10602. .clip(true)
  10603. .sourceSize({width:38, height:38})
  10604. .alt($r('app.media.alt'))
  10605. .borderRadius(8)
  10606. .clickEffect({ level: ClickEffectLevel.HEAVY })
  10607. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  10608. .shadow({
  10609. radius: 22,
  10610. type: ShadowType.BLUR,
  10611. color: 'on_primary'
  10612. })
  10613. }
  10614. .width('18%')
  10615. Column() {
  10616. Column() {
  10617. Text(this.name)
  10618. .fontSize(16)
  10619. .maxLines(1)
  10620. .fontWeight(FontWeight.Bolder)
  10621. .fontColor(Color.White)
  10622. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  10623. Row() {
  10624. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  10625. .fontSize(13)
  10626. .fontWeight(FontWeight.Bolder)
  10627. .padding({ top: 8 })
  10628. .fontColor(Color.White)
  10629. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  10630. Blank()
  10631. }
  10632. }
  10633. .height('100%')
  10634. .width('100%')
  10635. .justifyContent(FlexAlign.Center)
  10636. .alignItems(HorizontalAlign.Start)
  10637. }
  10638. .height('100%')
  10639. .width('65%')
  10640. Column() {
  10641. PointLightDefaultButton({
  10642. isSysBol:false,
  10643. pointColor:Color.White,
  10644. imageResource:$r('app.media.lyric'),
  10645. isPx: false,
  10646. builderHeight: 27,
  10647. builderWidth: 27,
  10648. })
  10649. .onClick(() => {
  10650. this.isLyricSetting = !this.isLyricSetting;
  10651. })
  10652. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  10653. height: '99%',
  10654. dragBar: true,
  10655. preferType: SheetType.CENTER,
  10656. showClose: true,
  10657. blurStyle: BlurStyle.Thin,
  10658. backgroundColor: Color.Transparent,
  10659. title: { title: $r('app.string.lyric_setting') }
  10660. })
  10661. }
  10662. .width('18%')
  10663. }
  10664. .width('82%')
  10665. .height(58)
  10666. .justifyContent(FlexAlign.SpaceBetween)
  10667. }
  10668. //歌词显示
  10669. @Builder
  10670. PlayerLyrics() {
  10671. Column() {
  10672. Column() {
  10673. this.LyricsTopItem()
  10674. }
  10675. .height(this.isPuraWP() ? 15 : 58)
  10676. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  10677. Visibility.None : Visibility.Visible)
  10678. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  10679. .width("100%")
  10680. Column() {
  10681. LyricView2({
  10682. controller: this.lyricController,
  10683. enableSeek: true,
  10684. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  10685. seekLineColor: "#80ffffff", // 滑动定位线颜色
  10686. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  10687. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  10688. if (!this.isPlaying) {
  10689. console.info('onecold startPlayOrResumePlay 7527')
  10690. this.startPlayOrResumePlay()
  10691. }
  10692. else {
  10693. this.isSeekTo = true;
  10694. this.mDestroyPage = false;
  10695. // 只有播放网盘歌曲时才显示转圈圈
  10696. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  10697. this.showLoadIng();
  10698. }
  10699. this.seekTo(position + "");
  10700. }
  10701. return true
  10702. }
  10703. })
  10704. .width("100%")
  10705. .layoutWeight(1)
  10706. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  10707. .gesture(LongPressGesture()
  10708. .onAction(() => {
  10709. this.openLyricCopySheet();
  10710. }))
  10711. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  10712. height: '99%',
  10713. dragBar: true,
  10714. showClose: true,
  10715. preferType: SheetType.CENTER,
  10716. blurStyle: BlurStyle.Thin,
  10717. title: { title: '歌词' }
  10718. })
  10719. if (this.isPhoneLan()) {
  10720. Column() {
  10721. if (this.isShowSpectrum) {
  10722. this.InlineSpectrumView()
  10723. }
  10724. this.playProgressView()
  10725. }
  10726. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  10727. }
  10728. }
  10729. .position({
  10730. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  10731. (this.isPuraWP() ? 58 : 99)
  10732. })
  10733. .justifyContent(FlexAlign.Center)
  10734. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  10735. }
  10736. }
  10737. @Builder
  10738. LyricCopySheetBuilder() {
  10739. LyricCopySheet({
  10740. lyricCopyLines: this.lyricCopyLines,
  10741. lyricSelectedIndexes: this.lyricSelectedIndexes,
  10742. isDarkMode: this.isDarkMode,
  10743. themeColor: this.themeColor,
  10744. bottomSafeHeight: this.bottomSafeHeight,
  10745. onToggleLyricLine: (index: number) => {
  10746. this.toggleLyricLineSelection(index);
  10747. },
  10748. onToggleSelectAll: () => {
  10749. this.toggleLyricSelectAll();
  10750. },
  10751. onCopySelectedLines: () => {
  10752. this.copySelectedLyricLines();
  10753. }
  10754. })
  10755. }
  10756. @Builder
  10757. SingleLyricView() {
  10758. Column() {
  10759. Column() {
  10760. LyricView2({
  10761. controller: this.lyricControllerSingle,
  10762. enableSeek: false,
  10763. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  10764. seekLineColor: "#80ffffff", // 滑动定位线颜色
  10765. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  10766. })
  10767. .gesture(LongPressGesture()
  10768. .onAction(() => {
  10769. this.openLyricCopySheet();
  10770. }))
  10771. }
  10772. .height(82)
  10773. .margin({ bottom: 20 })
  10774. }
  10775. }
  10776. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  10777. @Builder
  10778. BottomControl() {
  10779. Column() {
  10780. if (this.isShowSpectrum) {
  10781. this.InlineSpectrumView()
  10782. }
  10783. this.TopPlayProgressView()
  10784. //播放 暂停,下一首,上一首
  10785. this.playCenterView()
  10786. if(!this.curDisplayIsHiCar){
  10787. //播放进度条
  10788. this.BottomView()
  10789. }
  10790. }
  10791. .justifyContent(FlexAlign.Center)
  10792. .alignItems(HorizontalAlign.Center)
  10793. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  10794. }
  10795. @Builder
  10796. playMenuBuilder(){
  10797. Image($r('app.media.menu'))
  10798. .width(24)
  10799. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10800. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  10801. height: '99%',
  10802. preferType:SheetType.CENTER,
  10803. dragBar: true,
  10804. showClose: true,
  10805. blurStyle: BlurStyle.Thin,
  10806. title: { title: $r('app.string.more') },
  10807. backgroundColor: Color.Transparent,
  10808. })
  10809. }
  10810. //播放控制上一首 下一首 暂停和播放
  10811. @Builder
  10812. playCenterView(){
  10813. Row() {
  10814. PointLightButton({
  10815. builder: () => {
  10816. this.playMenuBuilder()
  10817. },
  10818. isPx: false,
  10819. builderHeight: 32,
  10820. builderWidth: 32,
  10821. })
  10822. .onClick(async () =>{
  10823. this.isShowMoreView = !this.isShowMoreView;
  10824. })
  10825. PointLightButton({
  10826. builder: () => {
  10827. this.playPreviousBuilder()
  10828. },
  10829. isPx: false,
  10830. builderHeight: 32,
  10831. builderWidth: 32,
  10832. })
  10833. .onClick(async () =>{
  10834. await this.playPrevious()
  10835. })
  10836. PointLightButton({
  10837. builder: () => {
  10838. this.PlayOrPauseButton()
  10839. },
  10840. isPx: false,
  10841. builderHeight: this.isPhoneLan()?42:55,
  10842. builderWidth: this.isPhoneLan()?42:55,
  10843. })
  10844. .onClick(() =>{
  10845. this.playOrPause()
  10846. })
  10847. PointLightButton({
  10848. builder: () => {
  10849. this.playNextBuilder()
  10850. },
  10851. isPx: false,
  10852. builderHeight: 32,
  10853. builderWidth: 32,
  10854. })
  10855. .onClick(async () =>{
  10856. await this.playNext()
  10857. })
  10858. this.playModeButton()
  10859. }
  10860. .width('95%')
  10861. .margin({ bottom:this.isCoverOpacity()?0:15 })
  10862. .justifyContent(FlexAlign.SpaceEvenly)
  10863. }
  10864. @Builder
  10865. playPreviousBuilder(){
  10866. Image($r('app.media.ic_previous'))
  10867. .width(32)
  10868. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10869. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10870. }
  10871. @Builder
  10872. playNextBuilder(){
  10873. Image($r('app.media.ic_next'))
  10874. .width(32)
  10875. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10876. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10877. }
  10878. @Builder
  10879. PlayOrPauseButton(){
  10880. Stack() {
  10881. Column() {
  10882. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  10883. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  10884. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  10885. .width(this.isPhoneLan()?43:53)
  10886. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10887. .fillColor(Color.White)
  10888. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10889. }
  10890. // 加载进度圈
  10891. if (this.isPlayerLoading) {
  10892. Progress({value:0,total:100,type:ProgressType.Ring })
  10893. .width(this.isPhoneLan()?46:55)
  10894. .height(this.isPhoneLan()?46:55)
  10895. .color(Color.White)
  10896. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  10897. }
  10898. }
  10899. .width(this.isPhoneLan()?43:53)
  10900. .height(this.isPhoneLan()?43:53)
  10901. }
  10902. @Builder
  10903. TopPlayProgressView(){
  10904. Column() {
  10905. Row(){
  10906. Stack(){
  10907. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  10908. .fontColor([Color.White])
  10909. .fontSize(21)
  10910. .effectStrategy(1)
  10911. Text(this.fastForwardSeconds)
  10912. .fontColor(Color.White)
  10913. .fontSize(10)
  10914. .fontWeight(FontWeight.Bold)
  10915. }
  10916. .padding({left:12,bottom:6})
  10917. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  10918. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10919. .onClick(()=>{
  10920. this.backForward()
  10921. })
  10922. Slider({
  10923. value: this.progressValue,
  10924. min: 0,
  10925. max: this.PROGRESS_MAX_VALUE,
  10926. step: 1,
  10927. style: SliderStyle.InSet
  10928. })
  10929. .height(20)
  10930. .blockColor('rgba(255,255,255,1)')
  10931. .trackColor('rgba(255,255,255,0.3)')
  10932. .selectedColor(Color.White)
  10933. .trackThickness(4)
  10934. .showSteps(false)
  10935. .showTips(true)
  10936. .layoutWeight(1)
  10937. .enabled(this.slideEnable)
  10938. .onChange((value: number, mode: SliderChangeMode) => {
  10939. if (mode !== 2) {
  10940. return
  10941. }
  10942. if(this.isSeekTo)
  10943. return
  10944. this.isSeekTo = true;
  10945. this.mDestroyPage = false;
  10946. // 只有播放网盘歌曲时才显示转圈圈
  10947. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  10948. this.showLoadIng();
  10949. }
  10950. let seekValue = value * (this.getActiveDuration() / 100);
  10951. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  10952. this.seekTo(seekValue + "");
  10953. })
  10954. Stack(){
  10955. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  10956. .fontColor([Color.White])
  10957. .fontSize(21)
  10958. .effectStrategy(1)
  10959. Text(this.fastForwardSeconds)
  10960. .fontColor(Color.White)
  10961. .fontSize(10)
  10962. .fontWeight(FontWeight.Bold)
  10963. }
  10964. .padding({right:10,bottom:6})
  10965. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  10966. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10967. .onClick(()=>{
  10968. this.fastForward()
  10969. })
  10970. }
  10971. .justifyContent(FlexAlign.Center)
  10972. .padding({left:20,right:20})
  10973. .width(this.isLandscape?'88%':'95%')
  10974. Row() {
  10975. Text(this.currentTime)
  10976. .fontSize(10)
  10977. .fontColor(Color.White)
  10978. .margin({left:25})
  10979. Blank()
  10980. Text(this.totalTime)
  10981. .fontSize(10)
  10982. .fontColor(Color.White)
  10983. .margin({right:25})
  10984. }
  10985. .width(this.isLandscape?'85%':'90%')
  10986. .height(10)
  10987. }
  10988. .width('100%')
  10989. .alignItems(HorizontalAlign.Center)
  10990. }
  10991. @Builder
  10992. playModeButton(){
  10993. PointLightButton({
  10994. builder: () => {
  10995. this.playModeBuilder()
  10996. },
  10997. isPx: false,
  10998. builderHeight: 32,
  10999. builderWidth: 32,
  11000. })
  11001. .onClick(async () =>{
  11002. this.setLoopMode()
  11003. })
  11004. }
  11005. @Builder
  11006. playModeBuilder(){
  11007. Column() {
  11008. if (this.playType === 0) {
  11009. Image($r('app.media.loop'))
  11010. .width(26)
  11011. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11012. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11013. } else if (this.playType === 1) {
  11014. Image($r('app.media.single'))
  11015. .width(26)
  11016. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11017. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11018. } else if (this.playType === 2) {
  11019. Image($r('app.media.normal_play'))
  11020. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11021. .width(26)
  11022. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11023. } else if (this.playType === 3) {
  11024. Image($r('app.media.random'))
  11025. .width(26)
  11026. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11027. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11028. } else if (this.playType === 4) {
  11029. Image($r('app.media.noloop'))
  11030. .width(26)
  11031. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11032. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11033. }
  11034. }
  11035. }
  11036. //播放进度条
  11037. @Builder
  11038. BottomView(){
  11039. Row() {
  11040. PointLightDefaultButton({
  11041. isSysBol:true,
  11042. pointColor:Color.White,
  11043. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  11044. isPx: false,
  11045. builderHeight: 26,
  11046. builderWidth: 26,
  11047. })
  11048. .onClick(async () =>{
  11049. if (this.isLandscape) {
  11050. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11051. } else {
  11052. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11053. }
  11054. })
  11055. if(this.currentSong){
  11056. PointLightDefaultButton({
  11057. isSysBol:true,
  11058. pointColor:Color.White,
  11059. imageResource:$r('sys.symbol.rename'),
  11060. isPx: false,
  11061. builderHeight: 26,
  11062. builderWidth: 26,
  11063. })
  11064. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  11065. height: '99%',
  11066. dragBar: true,
  11067. showClose: true,
  11068. preferType: SheetType.BOTTOM,
  11069. title: { title: '编辑标签' }
  11070. })
  11071. .onClick(async () => {
  11072. this.initEditFields(this.currentSong)
  11073. this.tempLyricContent = this.lyricContent
  11074. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11075. this.lyricConStr = this.tempLyricContent
  11076. }
  11077. this.isShowEdit = !this.isShowEdit;
  11078. })
  11079. }
  11080. PointLightDefaultButton({
  11081. isSysBol:true,
  11082. pointColor:Color.White,
  11083. imageResource:$r('sys.symbol.slider_vertical_3'),
  11084. isPx: false,
  11085. builderHeight: 26,
  11086. builderWidth: 26,
  11087. })
  11088. .onClick(async () => {
  11089. this.isEqualizerSheet = !this.isEqualizerSheet;
  11090. })
  11091. PointLightDefaultButton({
  11092. isSysBol:true,
  11093. pointColor:Color.White,
  11094. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  11095. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  11096. isPx: false,
  11097. builderHeight: 26,
  11098. builderWidth: 26,
  11099. })
  11100. .onClick(async () => {
  11101. if(this.currentSong){
  11102. this.doFav(this.currentSong)
  11103. }
  11104. })
  11105. this.playListBuilder()
  11106. }
  11107. .width(this.isLandscape?'88%':'95%')
  11108. .justifyContent(FlexAlign.SpaceAround)
  11109. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  11110. .height(30)
  11111. .animation({
  11112. duration: 666,
  11113. curve: 'ease-in-out' // 可选动画曲线
  11114. })
  11115. }
  11116. @Builder
  11117. fullButton(){
  11118. Column() {
  11119. Image($r('app.media.full_4'))
  11120. .width(25)
  11121. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11122. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11123. }
  11124. }
  11125. @Builder
  11126. playListBuilder(){
  11127. PointLightDefaultButton({
  11128. isSysBol:true,
  11129. pointColor:Color.White,
  11130. imageResource:$r('sys.symbol.music_note_list'),
  11131. isPx: false,
  11132. builderHeight: 26,
  11133. builderWidth: 26,
  11134. })
  11135. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  11136. height: '95%',
  11137. dragBar: true,
  11138. showClose: true,
  11139. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11140. blurStyle: BlurStyle.Thin,
  11141. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  11142. title: {
  11143. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  11144. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  11145. + `(${this.getPlayListDisplayCount()}首)`
  11146. }
  11147. })
  11148. .onClick(() => {
  11149. this.isShowSheetView = !this.isShowSheetView;
  11150. if(this.isPlayListBgGrass){
  11151. this.isFrontWhite = true
  11152. }else{
  11153. this.isFrontWhite = false
  11154. }
  11155. this.scrollIndex()
  11156. // 只有在播放本地音乐时才自动加载完整列表
  11157. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  11158. void this.hydrateFullMediaPlayListIfNeeded();
  11159. }
  11160. })
  11161. }
  11162. //旧版本播放进度条(现在是手机横屏的播放条)
  11163. @Builder
  11164. playProgressView() {
  11165. Row() {
  11166. Column(){
  11167. PointLightDefaultButton({
  11168. isSysBol:true,
  11169. pointColor:Color.White,
  11170. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  11171. isPx: false,
  11172. builderHeight: 26,
  11173. builderWidth: 26,
  11174. })
  11175. .onClick(async () =>{
  11176. if (this.isLandscape) {
  11177. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11178. } else {
  11179. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11180. }
  11181. })
  11182. }
  11183. .margin({ right: 10,bottom:6})
  11184. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  11185. .animation({
  11186. duration: 666,
  11187. curve: 'ease-in-out' // 可选动画曲线
  11188. })
  11189. Text(this.currentTime)
  11190. .fontSize($r('app.float.slider_font_size'))
  11191. .fontColor(Color.White)
  11192. .margin(3)
  11193. Slider({
  11194. value: this.progressValue,
  11195. min: 0,
  11196. max: this.PROGRESS_MAX_VALUE,
  11197. step: 1,
  11198. style: SliderStyle.InSet
  11199. })
  11200. .width('600px')
  11201. .blockColor('rgba(255,255,255,1)')
  11202. .trackColor('rgba(255,255,255,0.3)')
  11203. .selectedColor(Color.White)
  11204. .trackThickness(5)
  11205. .layoutWeight(1)
  11206. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  11207. .showSteps(false)
  11208. .showTips(true)
  11209. .enabled(this.slideEnable)
  11210. .onChange((value: number, mode: SliderChangeMode) => {
  11211. if (mode !== 2) {
  11212. return
  11213. }
  11214. this.isSeekTo = true;
  11215. this.mDestroyPage = false;
  11216. // 只有播放网盘歌曲时才显示转圈圈
  11217. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  11218. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11219. console.info("onecold 开始转圈圈")
  11220. this.showLoadIng();
  11221. }
  11222. let seekValue = value * (this.getActiveDuration() / 100);
  11223. this.seekTo(seekValue + "");
  11224. })
  11225. Text(this.totalTime)
  11226. .fontSize($r('app.float.slider_font_size'))
  11227. .fontColor(Color.White)
  11228. .margin(3)
  11229. //播放列表
  11230. Column(){
  11231. this.playListBuilder()
  11232. }
  11233. .margin({ left: 10,bottom:6})
  11234. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  11235. .animation({
  11236. duration: 666,
  11237. curve: 'ease-in-out' // 可选动画曲线
  11238. })
  11239. }
  11240. //x5的竖屏模式需要99%
  11241. .width(this.isPhonePortrait() ? '93.4%'
  11242. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  11243. .height(this.isPhoneLan() ? 25 : 33)
  11244. .alignItems(VerticalAlign.Bottom)
  11245. .animation({
  11246. duration: 666,
  11247. curve: 'ease-in-out' // 可选动画曲线
  11248. })
  11249. }
  11250. isBigScreen() {
  11251. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  11252. return true
  11253. }
  11254. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11255. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  11256. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  11257. return false
  11258. } else {
  11259. return true
  11260. }
  11261. return false
  11262. }
  11263. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  11264. // 添加控制缩放的状态变量
  11265. @State scaleValueImage: number = 1
  11266. @State scaleValueText: number = 1
  11267. @Builder
  11268. CoverInfo() {
  11269. Column() {
  11270. Stack() {
  11271. Column() {
  11272. //方形封面布局
  11273. if (this.isCoverRectangle) {
  11274. this.RectangleCoverView()
  11275. } else {
  11276. //圆形封面布局
  11277. this.CicleCoverView()
  11278. }
  11279. this.musicNameInfo(false)
  11280. if (this.isPhoneLan()) {
  11281. Text(this.name)
  11282. .fontSize(18)
  11283. .fontWeight(FontWeight.Bold)
  11284. .margin({ top: 13 })
  11285. .textOverflow({ overflow: TextOverflow.Ellipsis })
  11286. .maxLines(1)
  11287. .width('99%')
  11288. .textAlign(TextAlign.Center)
  11289. .fontColor(Color.White)
  11290. }
  11291. }
  11292. .width('100%')
  11293. Column({ space: 8 }) {
  11294. Text(this.name)
  11295. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  11296. .fontWeight(FontWeight.Bold)
  11297. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  11298. .maxLines(1)
  11299. .width('85%')
  11300. .textAlign(TextAlign.Center)
  11301. .fontColor(Color.White)
  11302. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  11303. Text(this.artist)
  11304. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  11305. .fontColor(Color.White)
  11306. .fontWeight(FontWeight.Bold)
  11307. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  11308. }
  11309. .justifyContent(FlexAlign.Start)
  11310. .zIndex(1)
  11311. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  11312. }
  11313. .margin({
  11314. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  11315. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  11316. top: this.isCoverOpacity() ? 0 : 20
  11317. })
  11318. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  11319. this.SingleLyricView()
  11320. }
  11321. if (this.isPhoneLan()) {
  11322. Column() {
  11323. this.playCenterView()
  11324. }
  11325. .position({ left: 28, bottom: 38 })
  11326. } else {
  11327. this.BottomControl()
  11328. }
  11329. }
  11330. .width(CommonConstants.FULL_PERCENT)
  11331. .clip(true)
  11332. }
  11333. //方形封面布局
  11334. @Builder
  11335. RectangleCoverView(){
  11336. Stack({alignContent:Alignment.Center}){
  11337. Image( StrUtil.isNotEmpty(this.cover)?
  11338. this.cover:$r('app.media.alt'))
  11339. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  11340. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  11341. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  11342. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  11343. .alt($r('app.media.alt'))
  11344. .margin({ right: 8, left: 8, top: 8 })
  11345. .aspectRatio(1)
  11346. .geometryTransition('cover') // 绑定标识符
  11347. .opacity(this.opacityValueImage)
  11348. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  11349. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  11350. {
  11351. preview: MenuPreviewMode.IMAGE,
  11352. previewAnimationOptions: { scale: [0.8, 1.0] },
  11353. })
  11354. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  11355. {
  11356. preview: MenuPreviewMode.IMAGE,
  11357. previewAnimationOptions: { scale: [0.8, 1.0] },
  11358. })
  11359. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  11360. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  11361. .clip(true)
  11362. .rotate({
  11363. x: 0,
  11364. y: 0,
  11365. z: 1,
  11366. angle: this.rotateAngle
  11367. })
  11368. .animation({
  11369. duration: 1000, // 与 setInterval 同步
  11370. curve: Curve.Linear,
  11371. iterations: 1
  11372. })
  11373. .shadow({
  11374. radius: 22,
  11375. type: ShadowType.BLUR,
  11376. color: 'on_primary'
  11377. })
  11378. .onClick(() => {
  11379. this.isMusicBGCover = !this.isMusicBGCover
  11380. })
  11381. }
  11382. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  11383. // 设置左下角为缩放中心点
  11384. centerX: '0%',
  11385. centerY: '100%' })
  11386. }
  11387. @Builder
  11388. CicleCoverView() {
  11389. //圆形封面布局
  11390. Stack({alignContent:Alignment.Center}) {
  11391. Image($r('app.media.ic_music_disc'))
  11392. .width(245)
  11393. .height(245)
  11394. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:50 })
  11395. .aspectRatio(1)
  11396. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  11397. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  11398. .borderRadius('100%')
  11399. .align(Alignment.Center)
  11400. .clip(true)
  11401. .rotate({
  11402. angle: this.rotateAngle,
  11403. centerX: "50%",
  11404. centerY: "50%",
  11405. })
  11406. .animation({
  11407. duration: 1000, // 改为 1000ms 与 setInterval 同步
  11408. curve: Curve.Linear,
  11409. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  11410. })
  11411. .shadow({
  11412. radius: 22,
  11413. type: ShadowType.BLUR,
  11414. color: 'on_primary'
  11415. })
  11416. Image( StrUtil.isNotEmpty(this.cover)?
  11417. this.cover:$r('app.media.alt'))
  11418. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  11419. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  11420. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  11421. .alt($r('app.media.alt'))
  11422. .margin({ right: 20, left: 20,
  11423. top:this.isCoverRectangle||this.isLandscape?0:50})
  11424. .aspectRatio(1)
  11425. .opacity(this.opacityValueImage)
  11426. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  11427. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  11428. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  11429. .align(Alignment.Center)//
  11430. .clip(true)
  11431. .shadow({
  11432. radius: 22,
  11433. type: ShadowType.BLUR,
  11434. color: 'on_primary'
  11435. })
  11436. .rotate({
  11437. x: 0,
  11438. y: 0,
  11439. z: 1,
  11440. angle: this.rotateAngle
  11441. })
  11442. .animation({
  11443. duration: 1000, // 与 setInterval 同步
  11444. curve: Curve.Linear,
  11445. iterations: 1
  11446. })
  11447. .onClick(() => {
  11448. this.isMusicBGCover = !this.isMusicBGCover
  11449. })
  11450. // 唱针以左上角为点选择逆时针40度
  11451. Image($r('app.media.ic_music_cover_hand'))
  11452. .height(130)
  11453. .margin({ bottom: 200, top: 0 })
  11454. // .position({ x: this.windowWidth/2, y: 0 })
  11455. .align(Alignment.Top)
  11456. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  11457. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  11458. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  11459. }
  11460. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  11461. // 设置左下角为缩放中心点
  11462. centerX: '0%',
  11463. centerY: '100%' })
  11464. }
  11465. @Builder
  11466. MenuImageBuilder(cover: string|undefined) {
  11467. Menu(){
  11468. MenuItem({
  11469. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  11470. content: '设为壁纸'
  11471. })
  11472. .onClick(async() => {
  11473. if (StrUtil.isEmpty(cover)) {
  11474. ToastUtil.showToast('当前没有可用封面')
  11475. return;
  11476. }
  11477. this.getUIContext().getRouter().pushUrl({
  11478. url: 'pages/WallpaperPreviewPage',
  11479. params: {
  11480. imageUri: cover
  11481. }
  11482. })
  11483. })
  11484. MenuItem({
  11485. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  11486. content: '更换封面'
  11487. })
  11488. .onClick(async() => {
  11489. await this.replaceCurrentSongCoverByAlbum();
  11490. })
  11491. }
  11492. }
  11493. @Builder
  11494. private musicNameInfo(isHidden: boolean) {
  11495. Row(){
  11496. Column({ space: 8 }) {
  11497. Text(this.name)
  11498. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  11499. .fontWeight(FontWeight.Bold)
  11500. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  11501. .maxLines(1)
  11502. .width('99%')
  11503. .textAlign(TextAlign.Start)
  11504. .fontColor(Color.White)
  11505. Text(this.artist + ' ' + this.currentSong?.album)
  11506. .fontSize(this.isCoverOpacity() ? 12 : 15)
  11507. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  11508. .fontColor(Color.White)
  11509. .textAlign(TextAlign.Start)
  11510. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  11511. .width('99%')
  11512. .maxLines(1)
  11513. }
  11514. .zIndex(1)
  11515. .layoutWeight(1)
  11516. .margin({ left: 15 })
  11517. Blank()
  11518. Row(){
  11519. PointLightDefaultButton({
  11520. isSysBol:true,
  11521. pointColor:Color.White,
  11522. imageResource:this.showSimple?
  11523. $r('sys.symbol.sun_max'):$r('sys.symbol.sun_max_fill'),
  11524. isPx: false,
  11525. builderHeight: 26,
  11526. builderWidth: 26,
  11527. })
  11528. .onClick(async () => {
  11529. this.showSimple = !this.showSimple
  11530. PreferencesUtil.put('showSimple', this.showSimple)
  11531. })
  11532. }
  11533. .margin({ left: 8,right:8 })
  11534. }
  11535. .width(this.isLandscape?'83%':'90%')
  11536. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  11537. .margin({ top:this.isCoverRectangle?10: 0 })
  11538. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  11539. }
  11540. @Builder
  11541. private PlayTitle() {
  11542. Row() {
  11543. Row() {
  11544. Image($r('app.media.ic_back_down'))
  11545. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  11546. .hitTestBehavior(HitTestMode.Transparent)
  11547. }
  11548. .layoutWeight(1)
  11549. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11550. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  11551. .onClick(() => {
  11552. this.setShowPlayFalse()
  11553. })
  11554. Column() {
  11555. AVCastPicker({
  11556. normalColor: Color.White,
  11557. onStateChange: this.onStateVastChange
  11558. })
  11559. .width(24)
  11560. .height(24)
  11561. }
  11562. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  11563. }
  11564. .width(PlayConstants.ROW_WIDTH)
  11565. }
  11566. @Builder
  11567. lyricSettingSheet(isPip: boolean) {
  11568. Scroll() {
  11569. this.lyricSetting(isPip)
  11570. }
  11571. .width('100%')
  11572. .height('100%')
  11573. }
  11574. @Builder
  11575. lyricSetting(isPip: boolean) {
  11576. Column() {
  11577. // 时间调节模块
  11578. if (!isPip) {
  11579. this.BuildTimeControls()
  11580. }
  11581. // 字号控制模块
  11582. this.BuildFontControls(isPip)
  11583. }
  11584. }
  11585. // 歌词时间偏移状态
  11586. @State timeOffset: number = 0.0
  11587. @State currentLyricColor: string = '#FFFFFF'
  11588. @State currentLyricColorPip: string = '#FFFFFF'
  11589. @State currentHighLightLyricColor: string = '#FF4081'
  11590. @State currentHighLightLyricColorPip: string = '#FF4081'
  11591. // 歌词字号状态
  11592. @State currentLyricSize: number = 20
  11593. @State currentLyricSizePip: number = 20
  11594. // 高亮歌词放大倍数
  11595. @State currentHightLyricSize: number = 1.2
  11596. @State currentHightLyricSizePip: number = 1.2
  11597. @State currentLyricLineSpace: number = 10
  11598. @State currentLyricLineSpacePip: number = 10
  11599. @State currentLyricAlignMode: number = 1
  11600. @State currentLyricAlignModePip: number = 1
  11601. @State blurDegree: number = 2
  11602. @State blurDegreePip: number = 2
  11603. @State isShowSelectColor: boolean = false
  11604. @State isShowHLSelectColor: boolean = false
  11605. @State isShowPipBgSelectColor: boolean = false
  11606. @State pipLyWidth: number = 330
  11607. @State pipLyHeight: number = 120
  11608. // 构建颜色选择器
  11609. @Builder
  11610. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  11611. Row({ space: 10 }) {
  11612. HSBColorPicker({
  11613. color: '#FFFFFF',
  11614. radius: 8,
  11615. layout: HSBColorPickerLayout.COLUMN,
  11616. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  11617. '#fa7105'],
  11618. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  11619. this.changeLyricColor(value, isPip, isBGPip)
  11620. })
  11621. .height(250)
  11622. .layoutWeight(1)
  11623. .padding(25)
  11624. }
  11625. .width('66%')
  11626. }
  11627. @State isOpenPip: boolean = false
  11628. @State pipBgIndex: number = 0
  11629. // 构建字号控制器
  11630. @Builder
  11631. BuildFontControls(isPip: boolean) {
  11632. Column() {
  11633. if (isPip) {
  11634. Column() {
  11635. Row() {
  11636. Text('悬浮歌词')
  11637. .margin({ left: 18 })
  11638. .fontSize(15)
  11639. .fontColor(Color.White)
  11640. .fontWeight(480)
  11641. .layoutWeight(1)
  11642. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  11643. .selectedColor(this.themeColor)
  11644. .switchPointColor(Color.White)
  11645. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11646. .margin({ right: 18 })
  11647. .onChange((checked: boolean) => {
  11648. this.isOpenPip = checked;
  11649. if (this.isOpenPip) {
  11650. this.startPip()
  11651. } else {
  11652. this.stopPip()
  11653. }
  11654. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  11655. })
  11656. .width(50)
  11657. .height(30);
  11658. }
  11659. .height(55)
  11660. }
  11661. .backgroundColor(Color.Transparent)
  11662. .borderRadius(15)
  11663. .margin({
  11664. left: 30,
  11665. right: 30,
  11666. top: 0,
  11667. bottom: 20
  11668. })
  11669. .padding(0)
  11670. .border({
  11671. color: Color.White,
  11672. width: 1.8
  11673. })
  11674. }else{
  11675. Column() {
  11676. Row() {
  11677. Text('显示迷你歌词')
  11678. .margin({ left: 18 })
  11679. .fontSize(15)
  11680. .fontColor(Color.White)
  11681. .fontWeight(480)
  11682. .layoutWeight(1)
  11683. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  11684. .selectedColor(this.themeColor)
  11685. .switchPointColor(Color.White)
  11686. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11687. .margin({ right: 18 })
  11688. .onChange((checked: boolean) => {
  11689. this.isShowSingleLineLyric = checked;
  11690. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  11691. })
  11692. .width(50)
  11693. .height(30);
  11694. }
  11695. .height(55)
  11696. }
  11697. .backgroundColor(Color.Transparent)
  11698. .borderRadius(15)
  11699. .margin({
  11700. left: 30,
  11701. right: 30,
  11702. top: 10,
  11703. bottom: 10
  11704. })
  11705. .padding(0)
  11706. .border({
  11707. color: Color.White,
  11708. width: 1.8
  11709. })
  11710. }
  11711. Row() {
  11712. Text(`歌词居中:`)
  11713. .fontSize(14)
  11714. .fontColor(Color.White)
  11715. .margin({ left: 2 })
  11716. Row() {
  11717. ForEach(['居中', '居左'], (size: string, index: number) => {
  11718. Button(size)
  11719. .width(60)
  11720. .height(28)
  11721. .fontSize(12)
  11722. .fontColor('#FFFFFF')
  11723. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  11724. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  11725. .border({
  11726. color: (!isPip && this.currentLyricAlignMode === index) ||
  11727. (isPip && this.currentLyricAlignModePip === index) ?
  11728. '#007DFF' : '#DDDDDD',
  11729. width: 1.8
  11730. })
  11731. .onClick(() => {
  11732. this.setLyricAlignMode(index, isPip)
  11733. })
  11734. .margin({ left: 10, right: 8 })
  11735. })
  11736. }
  11737. .width('76%')
  11738. Blank()
  11739. }
  11740. .margin({
  11741. top: 10,
  11742. bottom: 10,
  11743. right: 20,
  11744. left: 20
  11745. })
  11746. if (isPip) {
  11747. Row() {
  11748. Text(`悬浮背景:`)
  11749. .fontSize(14)
  11750. .fontColor(Color.White)
  11751. Select([
  11752. { value: CommonConstants.PIP_LYRIC_BG[0] },
  11753. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  11754. .font({ size: 13, weight: FontWeight.Medium })
  11755. .fontColor(Color.White)
  11756. .margin({ left: 10 })
  11757. .selected(this.pipBgIndex)
  11758. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  11759. .onSelect(async (_index: number, text?: string | undefined) => {
  11760. this.pipBgIndex = _index
  11761. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  11762. if (this.pipBgIndex === 0) {
  11763. if (this.cover) {
  11764. this.pipBg = this.cover
  11765. } else {
  11766. this.pipBg = this.imageColor
  11767. }
  11768. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  11769. } else {
  11770. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  11771. }
  11772. })
  11773. Column() {
  11774. }
  11775. .backgroundColor(this.pipBg)
  11776. .margin({ left: 10, right: 10 })
  11777. .borderRadius(20)
  11778. .height(28)
  11779. .width(28)
  11780. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11781. Row() {
  11782. SymbolGlyph($r('sys.symbol.paintbrush'))
  11783. .fontColor([Color.White])
  11784. .effectStrategy(1)
  11785. Text(`选择颜色`)
  11786. .fontSize(13)
  11787. .margin({ left: 10 })
  11788. .fontColor(Color.White)
  11789. }
  11790. }
  11791. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  11792. .backgroundColor(Color.Transparent)
  11793. .border({
  11794. color: '#FFFFFF',
  11795. radius: 20,
  11796. width: 1.8
  11797. })
  11798. .height(36)
  11799. .width(110)
  11800. .onClick(() => {
  11801. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  11802. })
  11803. .bindPopup(this.isShowPipBgSelectColor, {
  11804. builder: this.SelectColor(false, isPip, true),
  11805. placement: Placement.Top,
  11806. mask: { color: '#33000000' },
  11807. enableArrow: false, //是否显示箭头
  11808. showInSubWindow: false,
  11809. onStateChange: (e) => {
  11810. if (!e.isVisible) {
  11811. this.isShowPipBgSelectColor = false
  11812. }
  11813. }
  11814. })
  11815. }
  11816. .width('76%')
  11817. .margin({ bottom: 5, right: 45, left: 20 })
  11818. }
  11819. if (!isPip) {
  11820. Row() {
  11821. Text(`高亮居中:`)
  11822. .fontSize(14)
  11823. .fontColor(Color.White)
  11824. Column() {
  11825. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  11826. .selectedColor(this.themeColor)
  11827. .switchPointColor(Color.White)
  11828. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11829. .onChange((checked: boolean) => {
  11830. this.isHightLightCenter = checked;
  11831. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  11832. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  11833. })
  11834. .width(50)
  11835. .height(30)
  11836. .alignSelf(ItemAlign.Start)
  11837. .margin({ left: 12 })
  11838. Blank()
  11839. }
  11840. .width('76%')
  11841. }
  11842. .margin({
  11843. left: 20,
  11844. right: 15,
  11845. top: 10,
  11846. bottom: 10
  11847. })
  11848. }
  11849. Row() {
  11850. Text(`歌词颜色:`)
  11851. .fontSize(14)
  11852. .fontColor(Color.White)
  11853. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  11854. .fontSize(15)
  11855. .fontColor(Color.White)
  11856. .margin({ left: 12, right: 12 })
  11857. Column() {
  11858. }
  11859. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  11860. .margin({ right: 12 })
  11861. .borderRadius(20)
  11862. .height(28)
  11863. .width(28)
  11864. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11865. Row() {
  11866. SymbolGlyph($r('sys.symbol.paintbrush'))
  11867. .fontColor([Color.White])
  11868. .effectStrategy(1)
  11869. Text(`选择颜色`)
  11870. .fontSize(13)
  11871. .margin({ left: 10 })
  11872. .fontColor(Color.White)
  11873. }
  11874. }
  11875. .backgroundColor(Color.Transparent)
  11876. .border({
  11877. color: '#FFFFFF',
  11878. radius: 20,
  11879. width: 1.8
  11880. })
  11881. .height(36)
  11882. .width(110)
  11883. .onClick(() => {
  11884. this.isShowSelectColor = !this.isShowSelectColor
  11885. })
  11886. .bindPopup(this.isShowSelectColor, {
  11887. builder: this.SelectColor(false, isPip),
  11888. placement: Placement.Top,
  11889. mask: { color: '#33000000' },
  11890. enableArrow: false, //是否显示箭头
  11891. showInSubWindow: false,
  11892. onStateChange: (e) => {
  11893. if (!e.isVisible) {
  11894. this.isShowSelectColor = false
  11895. }
  11896. }
  11897. })
  11898. }
  11899. .width('76%')
  11900. .margin({
  11901. top: 10,
  11902. bottom: 10,
  11903. right: 45,
  11904. left: 20
  11905. })
  11906. Row() {
  11907. Text(`高亮颜色:`)
  11908. .fontSize(14)
  11909. .fontColor(Color.White)
  11910. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  11911. .fontSize(15)
  11912. .fontColor(Color.White)
  11913. .margin({ left: 12, right: 12 })
  11914. Column() {
  11915. }
  11916. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  11917. .margin({ right: 12 })
  11918. .borderRadius(20)
  11919. .height(28)
  11920. .width(28)
  11921. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11922. Row() {
  11923. SymbolGlyph($r('sys.symbol.paintbrush'))
  11924. .fontColor([Color.White])
  11925. .effectStrategy(1)
  11926. Text(`选择颜色`)
  11927. .fontSize(13)
  11928. .margin({ left: 10 })
  11929. .fontColor(Color.White)
  11930. }
  11931. }
  11932. .backgroundColor(Color.Transparent)
  11933. .border({
  11934. color: '#FFFFFF',
  11935. radius: 20,
  11936. width: 1.8
  11937. })
  11938. .height(36)
  11939. .width(110)
  11940. .onClick(() => {
  11941. this.isShowHLSelectColor = !this.isShowHLSelectColor
  11942. })
  11943. .bindPopup(this.isShowHLSelectColor, {
  11944. builder: this.SelectColor(true, isPip),
  11945. placement: Placement.Top,
  11946. mask: { color: '#33000000' },
  11947. enableArrow: false, //是否显示箭头
  11948. showInSubWindow: false,
  11949. onStateChange: (e) => {
  11950. if (!e.isVisible) {
  11951. this.isShowHLSelectColor = false
  11952. }
  11953. }
  11954. })
  11955. }
  11956. .width('76%')
  11957. .margin({
  11958. top: 10,
  11959. bottom: 10,
  11960. right: 45,
  11961. left: 20
  11962. })
  11963. if (isPip) {
  11964. Row() {
  11965. Text(`显示宽度:`)
  11966. .fontSize(14)
  11967. .fontColor(Color.White)
  11968. Slider({
  11969. value: this.pipLyWidth,
  11970. min: 10,
  11971. max: 800,
  11972. step: 1,
  11973. style: SliderStyle.OutSet
  11974. })
  11975. .blockColor(this.themeColor)
  11976. .trackColor($r('app.color.speed_text_color'))
  11977. .selectedColor(Color.White)
  11978. .trackThickness(6)
  11979. .onChange((value: number) => {
  11980. this.pipLyWidth = value
  11981. if (this.pipController) {
  11982. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11983. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  11984. }
  11985. })
  11986. .width('76%')
  11987. }
  11988. .margin({
  11989. left: 20,
  11990. right: 15,
  11991. top: 5,
  11992. bottom: 5
  11993. })
  11994. Row() {
  11995. Text(`显示高度:`)
  11996. .fontSize(14)
  11997. .fontColor(Color.White)
  11998. Slider({
  11999. value: this.pipLyHeight,
  12000. min: 10,
  12001. max: 1000,
  12002. step: 1,
  12003. style: SliderStyle.OutSet
  12004. })
  12005. .blockColor(this.themeColor)
  12006. .trackColor($r('app.color.speed_text_color'))
  12007. .selectedColor(Color.White)
  12008. .trackThickness(6)
  12009. .onChange((value: number) => {
  12010. this.pipLyHeight = value
  12011. if (this.pipController) {
  12012. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  12013. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  12014. }
  12015. })
  12016. .width('76%')
  12017. }
  12018. .margin({
  12019. left: 20,
  12020. right: 15,
  12021. top: 5,
  12022. bottom: 5
  12023. })
  12024. }
  12025. Row() {
  12026. Text(`歌词字号:`)
  12027. .fontSize(14)
  12028. .fontColor(Color.White)
  12029. Slider({
  12030. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  12031. min: 12,
  12032. max: 30,
  12033. step: 0.1,
  12034. style: SliderStyle.OutSet
  12035. })
  12036. .blockColor(this.themeColor)
  12037. .trackColor($r('app.color.speed_text_color'))
  12038. .selectedColor(Color.White)
  12039. .trackThickness(6)
  12040. .onChange((value: number) => {
  12041. this.setLyricTextSize(value, isPip)
  12042. })
  12043. .width('76%')
  12044. }
  12045. .margin({
  12046. left: 20,
  12047. right: 15,
  12048. top: 5,
  12049. bottom: 5
  12050. })
  12051. Row() {
  12052. Text(`高亮倍数:`)
  12053. .fontSize(14)
  12054. .fontColor(Color.White)
  12055. Slider({
  12056. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  12057. min: 1,
  12058. max: 2,
  12059. step: 0.1,
  12060. style: SliderStyle.OutSet
  12061. })
  12062. .blockColor(this.themeColor)
  12063. .trackColor($r('app.color.speed_text_color'))
  12064. .selectedColor(Color.White)
  12065. .trackThickness(6)
  12066. .onChange((value: number) => {
  12067. this.setHighLyricTextSize(value, isPip)
  12068. })
  12069. .width('76%')
  12070. }
  12071. .margin({
  12072. left: 20,
  12073. right: 15,
  12074. top: 5,
  12075. bottom: 5
  12076. })
  12077. Row() {
  12078. Text(`歌词间隙:`)
  12079. .fontSize(14)
  12080. .fontColor(Color.White)
  12081. Slider({
  12082. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  12083. min: 0,
  12084. max: 100,
  12085. step: 1,
  12086. style: SliderStyle.OutSet
  12087. })
  12088. .blockColor(this.themeColor)
  12089. .trackColor($r('app.color.speed_text_color'))
  12090. .selectedColor(Color.White)
  12091. .trackThickness(6)
  12092. .onChange((value: number) => {
  12093. this.setLyricLineSpace(value, isPip)
  12094. })
  12095. .width('76%')
  12096. }
  12097. .margin({
  12098. left: 20,
  12099. right: 15,
  12100. top: 5,
  12101. bottom: 5
  12102. })
  12103. //取值间隔为100,默认为400,取值越大,字体越粗
  12104. Row() {
  12105. Text(`歌词字重:`)
  12106. .fontSize(14)
  12107. .fontColor(Color.White)
  12108. Slider({
  12109. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  12110. min: 100,
  12111. max: 900,
  12112. step: 100,
  12113. style: SliderStyle.OutSet
  12114. })
  12115. .blockColor(this.themeColor)
  12116. .trackColor($r('app.color.speed_text_color'))
  12117. .selectedColor(Color.White)
  12118. .trackThickness(6)
  12119. .onChange((value: number) => {
  12120. if (isPip) {
  12121. this.lyricTextWeightPip = value
  12122. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  12123. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  12124. } else {
  12125. this.lyricTextWeight = value
  12126. this.lyricController.setTextWeight(this.lyricTextWeight)
  12127. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  12128. }
  12129. })
  12130. .width('76%')
  12131. }
  12132. .margin({
  12133. left: 20,
  12134. right: 15,
  12135. top: 5,
  12136. bottom: 5
  12137. })
  12138. Row() {
  12139. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  12140. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  12141. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  12142. }
  12143. .justifyContent(FlexAlign.Center)
  12144. .margin({ top: 3, bottom: 10 })
  12145. }
  12146. }
  12147. private setBlurDegree(index: number, isPip: boolean) {
  12148. if (isPip) {
  12149. this.blurDegreePip = index
  12150. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  12151. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  12152. } else {
  12153. this.blurDegree = index
  12154. this.lyricController.setBlurDegree(this.blurDegree)
  12155. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  12156. }
  12157. }
  12158. private setLyricAlignMode(index: number, isPip: boolean) {
  12159. if (isPip) {
  12160. this.currentLyricAlignModePip = index
  12161. if (this.currentLyricAlignModePip === 1) {
  12162. this.lyricControllerXF.setAlignMode("left")
  12163. } else {
  12164. this.lyricControllerXF.setAlignMode("center")
  12165. }
  12166. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  12167. } else {
  12168. this.currentLyricAlignMode = index
  12169. if (this.currentLyricAlignMode === 1) {
  12170. this.lyricController.setAlignMode("left")
  12171. } else {
  12172. this.lyricController.setAlignMode("center")
  12173. }
  12174. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  12175. }
  12176. }
  12177. private setLyricTextSize(index: number, isPip: boolean) {
  12178. if (isPip) {
  12179. this.currentLyricSizePip = index
  12180. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  12181. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  12182. } else {
  12183. this.currentLyricSize = index
  12184. this.lyricController.setTextSize(this.currentLyricSize)
  12185. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  12186. }
  12187. }
  12188. private setHighLyricTextSize(scale: number, isPip: boolean) {
  12189. if (isPip) {
  12190. this.currentHightLyricSizePip = scale
  12191. this.lyricControllerXF
  12192. .setHighlightScale(this.currentHightLyricSizePip)
  12193. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  12194. } else {
  12195. this.currentHightLyricSize = scale
  12196. this.lyricController
  12197. .setHighlightScale(this.currentHightLyricSize)
  12198. PreferencesUtil.putSync('HighLyricTextSize', scale)
  12199. }
  12200. }
  12201. private setLyricLineSpace(index: number, isPip: boolean) {
  12202. if (isPip) {
  12203. this.currentLyricLineSpacePip = index
  12204. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  12205. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  12206. } else {
  12207. this.currentLyricLineSpace = index
  12208. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  12209. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  12210. }
  12211. }
  12212. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  12213. LogUtil.info('onecold isBG = ' + isBG)
  12214. if (isBG) { //如果是设置悬浮背景
  12215. this.pipBg = color
  12216. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  12217. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  12218. return
  12219. }
  12220. if (isPip) {
  12221. this.currentLyricColorPip = color
  12222. this.lyricControllerXF
  12223. .setTextColor(this.currentLyricColorPip)
  12224. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  12225. } else {
  12226. this.currentLyricColor = color
  12227. this.lyricController
  12228. .setTextColor(this.currentLyricColor)
  12229. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  12230. }
  12231. }
  12232. private changeLyricHightLightColor(color: string, isPip: boolean) {
  12233. if (isPip) {
  12234. this.currentHighLightLyricColorPip = color
  12235. this.lyricControllerXF
  12236. .setHighlightColor(this.currentHighLightLyricColorPip)
  12237. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  12238. } else {
  12239. this.currentHighLightLyricColor = color
  12240. this.lyricController
  12241. .setHighlightColor(this.currentHighLightLyricColor)
  12242. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  12243. }
  12244. }
  12245. // 构建时间控制器
  12246. @Builder
  12247. BuildTimeControls() {
  12248. Column() {
  12249. // 时间显示
  12250. Text(this.getTimeText())
  12251. .fontSize(18)
  12252. .fontColor(Color.White)
  12253. .margin({ bottom: 10 })
  12254. Row() {
  12255. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  12256. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  12257. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  12258. }
  12259. .justifyContent(FlexAlign.Center)
  12260. }
  12261. .margin({ top: 12, bottom: 8 })
  12262. }
  12263. // 精度按钮组件
  12264. @Builder
  12265. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  12266. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12267. Column() {
  12268. Image(icon)
  12269. .width(28)
  12270. .margin({ bottom: 5 })
  12271. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  12272. Text(label)
  12273. .fontSize(12)
  12274. .fontColor('#FFFFFF')
  12275. }
  12276. }
  12277. .backgroundColor(Color.Transparent)
  12278. .enabled(!this.isButtonDisabled(step))
  12279. .onClick(() => this.handlePrecisionAdjust(step))
  12280. .padding(5)
  12281. .width(66)
  12282. .height(66)
  12283. .margin({ left: 18, right: 18 })
  12284. .border({
  12285. color: '#FFFFFF',
  12286. width: 1.8
  12287. })
  12288. }
  12289. private handlePrecisionAdjust(step: number) {
  12290. if (step === 0) {
  12291. this.timeOffset = 0
  12292. this.saveLyricTimeOffset()
  12293. return
  12294. }
  12295. // 精度处理:保留1位小数
  12296. const newOffset = Number((this.timeOffset + step).toFixed(5))
  12297. // 边界保护(±15.0秒)
  12298. if (newOffset < -30.0 || newOffset > 30.0) {
  12299. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  12300. return
  12301. }
  12302. // 状态更新
  12303. this.timeOffset = newOffset
  12304. // 保存歌词时间偏移
  12305. this.saveLyricTimeOffset()
  12306. }
  12307. // 按钮禁用逻辑
  12308. private isButtonDisabled(step: number): boolean {
  12309. const futureOffset = this.timeOffset + step
  12310. return (futureOffset < -30.0) || (futureOffset > 30.0)
  12311. }
  12312. // 时间显示文本升级
  12313. private getTimeText(): string {
  12314. const absValue = Math.abs(this.timeOffset)
  12315. return this.timeOffset === 0
  12316. ? '歌词时间已重置'
  12317. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  12318. }
  12319. /**
  12320. * 获取当前歌曲的唯一标识key
  12321. * 使用歌曲的filePath作为唯一标识
  12322. */
  12323. private getLyricOffsetKey(): string {
  12324. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  12325. // 使用MD5对filePath进行加密,作为存储key
  12326. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  12327. }
  12328. return ''
  12329. }
  12330. /**
  12331. * 保存当前歌曲的歌词时间偏移
  12332. */
  12333. private saveLyricTimeOffset(): void {
  12334. try {
  12335. const key = this.getLyricOffsetKey()
  12336. if (StrUtil.isEmpty(key)) {
  12337. console.warn('heanup saveLyricTimeOffset: key is empty')
  12338. return
  12339. }
  12340. PreferencesUtil.putSync(key, this.timeOffset)
  12341. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  12342. } catch (e) {
  12343. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  12344. }
  12345. }
  12346. /**
  12347. * 加载当前歌曲的歌词时间偏移
  12348. */
  12349. private loadLyricTimeOffset(): void {
  12350. try {
  12351. const key = this.getLyricOffsetKey()
  12352. if (StrUtil.isEmpty(key)) {
  12353. console.warn('heanup loadLyricTimeOffset: key is empty')
  12354. return
  12355. }
  12356. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  12357. if (savedOffset !== 0) {
  12358. this.timeOffset = savedOffset
  12359. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  12360. }else{
  12361. this.timeOffset = 0
  12362. }
  12363. } catch (e) {
  12364. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  12365. }
  12366. }
  12367. // 导入 本地歌词 搜索歌词
  12368. @Builder
  12369. pushLyricButton(icon: Resource, step: number, label: string) {
  12370. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12371. Row() {
  12372. Image(icon)
  12373. .width(14)
  12374. .margin({ left: 13 })
  12375. Text(label)
  12376. .fontSize(12)
  12377. .margin({ left: 6 })
  12378. .fontColor('#FFFFFF')
  12379. }
  12380. }
  12381. .onClick(() => {
  12382. switch (step) {
  12383. case 0:
  12384. this.callFilePickerSelectFileForLyric()
  12385. break;
  12386. case 1:
  12387. //判断有没有设置api
  12388. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  12389. this.isLyricSetting = false
  12390. this.showTipsDialog()
  12391. return
  12392. }
  12393. if (StrUtil.isNotEmpty(this.videoUrl)) {
  12394. ToastUtil.showToast('正在获取')
  12395. this.isLyricSetting = false
  12396. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12397. this.initLyric(lyricPath, true);
  12398. }
  12399. break;
  12400. }
  12401. })
  12402. .padding(5)
  12403. .width(110)
  12404. .backgroundColor(Color.Transparent)
  12405. .height(40)
  12406. .margin({ left: 6, right: 6 })
  12407. .border({
  12408. color: '#FFFFFF',
  12409. radius: 20,
  12410. width: 1.8
  12411. })
  12412. }
  12413. showVipDialog() {
  12414. DialogHelper.showCustomContentDialog({
  12415. dialogId: 'vip',
  12416. title: "友情提示",
  12417. autoCancel: false, //点击遮障层时,不关闭弹窗
  12418. backCancel: true, //点击返回键,不关闭弹窗
  12419. contentBuilder: () => {
  12420. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  12421. },
  12422. buttons: [],
  12423. })
  12424. }
  12425. //去赞助的自定义内容
  12426. @Builder
  12427. customVipBuilder(content: string) {
  12428. Column() {
  12429. Text(content)
  12430. .fontColor(Color.Gray)
  12431. .fontSize(16)
  12432. .alignSelf(ItemAlign.Start)
  12433. .margin({ bottom: 15 })
  12434. .fontSize(16)
  12435. Row() {
  12436. Button('取消')
  12437. .fontColor(Color.White)
  12438. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  12439. .height(50)
  12440. .layoutWeight(1)
  12441. .stateEffect(true)
  12442. .margin({ right: 6 })
  12443. .onClick(() => {
  12444. DialogHelper.closeDialog('vip'); //关闭弹框
  12445. })
  12446. Button('开通')
  12447. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  12448. .layoutWeight(1)
  12449. .height(50)
  12450. .backgroundColor(this.themeColor)
  12451. .stateEffect(true)
  12452. .margin({ left: 6 })
  12453. .onClick(() => {
  12454. DialogHelper.closeDialog('vip'); //关闭弹框
  12455. this.isShowPlay = false
  12456. this.mType = 1 //跳转到用户中心
  12457. // router.pushUrl({
  12458. // url: 'pages/VipPage'
  12459. // }, router.RouterMode.Single);
  12460. })
  12461. }
  12462. }
  12463. .width("100%")
  12464. .padding(10)
  12465. }
  12466. showTipsDialog() {
  12467. DialogHelper.showCustomContentDialog({
  12468. dialogId: 'tips',
  12469. title: "友情提示",
  12470. autoCancel: false, //点击遮障层时,不关闭弹窗
  12471. backCancel: true, //点击返回键,不关闭弹窗
  12472. contentBuilder: () => {
  12473. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  12474. },
  12475. buttons: [],
  12476. })
  12477. }
  12478. @Builder
  12479. customTipsBuilder(content: string) {
  12480. Column() {
  12481. Text(content)
  12482. .fontColor(Color.Gray)
  12483. .fontSize(16)
  12484. .alignSelf(ItemAlign.Start)
  12485. .margin({ bottom: 15 })
  12486. .fontSize(16)
  12487. Row() {
  12488. Button('取消')
  12489. .fontColor(Color.White)
  12490. .backgroundColor(this.themeColor)
  12491. .height(50)
  12492. .layoutWeight(1)
  12493. .stateEffect(true)
  12494. .margin({ right: 6 })
  12495. .onClick(() => {
  12496. DialogHelper.closeDialog('tips'); //关闭弹框
  12497. })
  12498. Button('跳转')
  12499. .fontColor(Color.White)//
  12500. .layoutWeight(1)
  12501. .height(50)
  12502. .backgroundColor(this.themeColor)
  12503. .stateEffect(true)
  12504. .margin({ left: 6 })
  12505. .onClick(() => {
  12506. DialogHelper.closeDialog('tips'); //关闭弹框
  12507. this.isShowEdit = false
  12508. this.longItemFilePath = ''
  12509. // if(this.isGridMusic&&!this.isShowPlay){
  12510. // this.longItemFilePath== ''
  12511. // }else{
  12512. // this.isShowEdit = false
  12513. // }
  12514. this.isShowMoreView = false;
  12515. this.isShowPlay = false
  12516. this.mType = 4
  12517. // router.pushUrl({
  12518. // url: 'pages/SettingPage'
  12519. // }, router.RouterMode.Single);
  12520. })
  12521. }
  12522. }
  12523. .width("100%")
  12524. .padding(10)
  12525. }
  12526. @Builder
  12527. PlayMoreSheet() {
  12528. Column() {
  12529. this.MoreList()
  12530. }
  12531. .width('100%')
  12532. .height('100%')
  12533. }
  12534. @Builder
  12535. MoreList() {
  12536. Scroll() {
  12537. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  12538. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  12539. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12540. Row() {
  12541. if (more.id === 3&&this.currentSong) {
  12542. Image(more.image)
  12543. .width(24)
  12544. .height(24)
  12545. .margin({ left: 10, right: 10 })
  12546. Text(more.title)
  12547. .fontSize(16)
  12548. .fontColor(Color.White)
  12549. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  12550. height: '99%',
  12551. dragBar: true,
  12552. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12553. showClose: true,
  12554. blurStyle: BlurStyle.Thin,
  12555. backgroundColor: Color.Transparent,
  12556. title: { title: '歌曲信息' }
  12557. })
  12558. } else if (more.id === 15 && this.currentSong) { //编辑标签
  12559. Image(more.image)
  12560. .width(24)
  12561. .height(24)
  12562. .margin({ left: 10, right: 10 })
  12563. Text(more.title)
  12564. .fontSize(16)
  12565. .fontColor(Color.White)
  12566. } else if (more.id === 5) { //定时关闭
  12567. Image(more.image)
  12568. .width(24)
  12569. .height(24)
  12570. .margin({ left: 10, right: 10 })
  12571. Text(more.title)
  12572. .fontSize(16)
  12573. .fontColor(Color.White)
  12574. .onClick(() => {
  12575. this.doMore(more.id)
  12576. })
  12577. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  12578. height: this.isCoverOpacity() ? '95%' : '95%',
  12579. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12580. dragBar: true,
  12581. showClose: true,
  12582. title: { title: $r('app.string.time_close') }
  12583. })
  12584. } else if (more.id === 2) { //歌词设置
  12585. Image(more.image)
  12586. .width(24)
  12587. .height(24)
  12588. .margin({ left: 10, right: 10 })
  12589. Text(more.title)
  12590. .fontSize(16)
  12591. .fontColor(Color.White)
  12592. } else if (more.id === 16) { //悬浮歌词设置
  12593. Image(more.image)
  12594. .width(24)
  12595. .height(24)
  12596. .margin({ left: 10, right: 10 })
  12597. Text(more.title)
  12598. .fontSize(16)
  12599. .fontColor(Color.White)
  12600. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  12601. height: '99%',
  12602. dragBar: true,
  12603. preferType: SheetType.CENTER,
  12604. showClose: true,
  12605. blurStyle: BlurStyle.Thin,
  12606. backgroundColor: Color.Transparent,
  12607. title: { title: '悬浮歌词' }
  12608. })
  12609. } else if (more.id === 11) {
  12610. Image(more.image)
  12611. .width(24)
  12612. .height(24)
  12613. .margin({ left: 10, right: 10 })
  12614. Text(more.title)
  12615. .fontSize(16)
  12616. .fontColor(Color.White)
  12617. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  12618. height: this.isCoverOpacity() ? '95%' : '60%',
  12619. dragBar: true,
  12620. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12621. showClose: true,
  12622. blurStyle: BlurStyle.Thin,
  12623. backgroundColor: Color.Transparent,
  12624. title: { title: '跳过头尾' }
  12625. })
  12626. } else if (more.id === 12) { //投播
  12627. AVCastPicker({
  12628. customPicker: (): void => this.TPImageBuilder(more),
  12629. onStateChange: (state) => {
  12630. if (state == AVCastPickerState.STATE_APPEARING) {
  12631. console.log(' The picker starts showing.');
  12632. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  12633. console.log(' The picker finishes presenting.');
  12634. }
  12635. },
  12636. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  12637. sessionType: 'video'
  12638. })
  12639. .id('AVCastPicker')
  12640. } else {
  12641. if(more.id >= 22){
  12642. SymbolGlyph(more.image)
  12643. .fontSize(24)
  12644. .fontColor([Color.White])
  12645. .alignSelf(ItemAlign.Center)
  12646. .margin({ left: 10, right: 10,bottom:5})
  12647. // .padding({bottom:4})
  12648. .onClick(() => {
  12649. this.doMore(more.id)
  12650. })
  12651. }else{
  12652. Image(more.image)
  12653. .width(24)
  12654. .height(24)
  12655. .fillColor(Color.White)
  12656. .margin({ left: 10, right: 10 })
  12657. .onClick(() => {
  12658. this.doMore(more.id)
  12659. })
  12660. }
  12661. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  12662. .fontSize(16)
  12663. .margin({top:more.id >= 22?3:0})
  12664. .fontColor(Color.White)
  12665. .onClick(() => {
  12666. this.doMore(more.id)
  12667. })
  12668. Select([//倍速
  12669. { value: '0.25x' },
  12670. { value: '0.5x' },
  12671. { value: '0.75x' },
  12672. { value: '1x' },
  12673. { value: '1.25x' },
  12674. { value: '1.5x' },
  12675. { value: '1.75x' },
  12676. { value: '2x' },
  12677. { value: '3x' }])
  12678. .font({ size: 16, weight: FontWeight.Medium })
  12679. .fontColor($r('sys.color.white'))
  12680. .margin({ left: 25 })
  12681. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  12682. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  12683. .value(Utility.optimizedFormat(this.playSpeed))
  12684. .onSelect(async (_index: number, text?: string | undefined) => {
  12685. let speed = parseFloat(text?.replace('x', '') || '1');
  12686. if (!CommonConstants.video_speed_list.includes(speed)) {
  12687. speed = 1;
  12688. }
  12689. this.playSpeed = speed
  12690. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12691. })
  12692. Slider({
  12693. value: this.volume,
  12694. min: 0,
  12695. max: 1,
  12696. step: 0.1,
  12697. style: SliderStyle.OutSet
  12698. })
  12699. .margin({ left: 18, right: 8 })
  12700. .blockColor(this.themeColor)
  12701. .trackColor($r('app.color.speed_text_color'))
  12702. .selectedColor(Color.White)
  12703. .trackThickness(9)
  12704. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  12705. .onChange((value: number) => {
  12706. this.volume = value;
  12707. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12708. PreferencesUtil.putSync('DefalutVolume',this.volume)
  12709. })
  12710. .layoutWeight(1)
  12711. Blank()
  12712. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  12713. .selectedColor(this.themeColor)
  12714. .switchPointColor(Color.White)
  12715. .margin({ right: 15 })
  12716. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12717. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  12718. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12719. if (more.id == 6) {
  12720. this.isMusicMemoryPlay = checked;
  12721. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  12722. if (this.isMusicMemoryPlay) {
  12723. ToastUtil.showToast('记忆播放已开启')
  12724. } else {
  12725. ToastUtil.showToast('记忆播放已关闭')
  12726. }
  12727. }
  12728. })
  12729. .width(48)
  12730. .height(24);
  12731. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  12732. .selectedColor(this.themeColor)
  12733. .switchPointColor(Color.White)
  12734. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12735. .margin({ right: 15 })
  12736. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  12737. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12738. if (more.id == 7) {
  12739. this.isMusicBGCover = checked;
  12740. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  12741. if (this.isMusicBGCover) {
  12742. ToastUtil.showToast('播放背景随音乐封面已开启')
  12743. } else {
  12744. ToastUtil.showToast('播放背景随音乐封面已关闭')
  12745. }
  12746. }
  12747. })
  12748. .width(48)
  12749. .height(24);
  12750. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  12751. .selectedColor(this.themeColor)
  12752. .switchPointColor(Color.White)
  12753. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12754. .margin({ right: 15 })
  12755. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  12756. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12757. if (more.id == 8) {
  12758. this.isSavePlayMode = checked;
  12759. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  12760. if (this.isSavePlayMode) {
  12761. ToastUtil.showToast('保存播放模式已开启')
  12762. } else {
  12763. ToastUtil.showToast('保存播放模式已关闭')
  12764. }
  12765. }
  12766. })
  12767. .width(48)
  12768. .height(24);
  12769. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  12770. .selectedColor(this.themeColor)
  12771. .switchPointColor(Color.White)
  12772. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12773. .margin({ right: 15 })
  12774. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  12775. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12776. if (more.id == 13) {
  12777. this.isCoverRectangle = checked;
  12778. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  12779. if (this.isCoverRectangle) {
  12780. ToastUtil.showToast('封面方形已开启')
  12781. this.animationRoFun()
  12782. } else {
  12783. ToastUtil.showToast('封面圆形已开启')
  12784. this.animationRoFun()
  12785. }
  12786. }
  12787. })
  12788. .width(48)
  12789. .height(24);
  12790. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  12791. .selectedColor(this.themeColor)
  12792. .switchPointColor(Color.White)
  12793. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12794. .margin({ right: 15 })
  12795. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  12796. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12797. if (more.id == 25) {
  12798. this.isShowSpectrum = checked;
  12799. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  12800. }
  12801. })
  12802. .width(48)
  12803. .height(24);
  12804. // 频谱特效类型选择器
  12805. Select([
  12806. { value: '柱状' },
  12807. { value: '波形' },
  12808. { value: '圆形' },
  12809. { value: '粒子' },
  12810. { value: '脉冲' },
  12811. { value: '镜像柱' },
  12812. { value: '影子柱' },
  12813. { value: '轨道线' },
  12814. { value: '点阵' },
  12815. { value: '星爆' }
  12816. ])
  12817. .font({ size: 14, weight: FontWeight.Medium })
  12818. .fontColor(Color.White)
  12819. .margin({ left: 25 })
  12820. .margin({top:more.id >= 22?3:0})
  12821. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  12822. .selected(this.spectrumModeIndex)
  12823. .value(['柱状', '波形', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆'][this.spectrumModeIndex])
  12824. .onSelect((index: number, _text?: string) => {
  12825. this.spectrumModeIndex = index;
  12826. // 使用同步方法保存,确保立即生效
  12827. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  12828. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  12829. const modeNames = ['柱状', '波形', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆'];
  12830. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  12831. });
  12832. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  12833. .selectedColor(this.themeColor)
  12834. .switchPointColor(Color.White)
  12835. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12836. .margin({ right: 15 })
  12837. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  12838. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12839. if (more.id == 22) {
  12840. this.showSimple = checked;
  12841. PreferencesUtil.put('showSimple', this.showSimple)
  12842. }
  12843. })
  12844. .width(48)
  12845. .height(24);
  12846. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  12847. .selectedColor(this.themeColor)
  12848. .switchPointColor(Color.White)
  12849. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12850. .margin({ right: 15 })
  12851. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  12852. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12853. if (more.id == 23) {
  12854. this.enablePointLight = checked;
  12855. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  12856. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  12857. }
  12858. })
  12859. .width(48)
  12860. .height(24);
  12861. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  12862. .selectedColor(this.themeColor)
  12863. .switchPointColor(Color.White)
  12864. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12865. .margin({ right: 15 })
  12866. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  12867. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12868. if (more.id == 27) {
  12869. this.isGeKongPlayNext = checked;
  12870. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  12871. }
  12872. })
  12873. .width(48)
  12874. .height(24);
  12875. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  12876. .selectedColor(this.themeColor)
  12877. .switchPointColor(Color.White)
  12878. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12879. .margin({ right: 15 })
  12880. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  12881. .onChange((checked: boolean) => { // 是否开启背景流光效果
  12882. if (more.id == 21) {
  12883. this.isShowBgLiuGUANG = checked;
  12884. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  12885. }
  12886. })
  12887. .width(48)
  12888. .height(24);
  12889. }
  12890. }
  12891. .width('100%')
  12892. .height(45)
  12893. .padding(15)
  12894. .backgroundColor(Color.Transparent)
  12895. .borderRadius(12)
  12896. .margin({ bottom: 6 })
  12897. }
  12898. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  12899. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  12900. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  12901. .backgroundColor(Color.Transparent)
  12902. .onClick(() => {
  12903. this.doMore(more.id)
  12904. })
  12905. });
  12906. }
  12907. .width('100%')
  12908. .padding(16)
  12909. }.margin({ bottom: 18 })
  12910. }
  12911. @Builder
  12912. TPImageBuilder(more: MoreItem): void {
  12913. Row() {
  12914. Image($r('app.media.tuoping'))
  12915. .width(22)
  12916. .height(22)
  12917. .margin({ left: 10, right: 10 })
  12918. Text(more.title)
  12919. .fontSize(16)
  12920. .fontColor(Color.White)
  12921. }
  12922. .width('100%')
  12923. .layoutWeight(1)
  12924. .alignItems(VerticalAlign.Center)
  12925. .justifyContent(FlexAlign.Start)
  12926. }
  12927. private moreItems: MoreItem[] = [
  12928. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  12929. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  12930. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  12931. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  12932. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  12933. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  12934. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  12935. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  12936. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  12937. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  12938. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  12939. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  12940. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  12941. { id: 4, image: $r('app.media.share2'), title: '分享' },
  12942. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  12943. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  12944. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  12945. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  12946. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  12947. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  12948. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  12949. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  12950. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  12951. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  12952. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  12953. ];
  12954. @State isShowBgLiuGUANG: boolean = false;
  12955. @State isShowMoreView: boolean = false;
  12956. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  12957. @State isShowTimeCloseMore: boolean = false
  12958. @State isShowDetailMore: boolean = false
  12959. @State isMusicBGCover: boolean = true
  12960. @State isSavePlayMode: boolean = true
  12961. @State isLyricSetting: boolean = false
  12962. @State isJumpSetting: boolean = false
  12963. @State isShowEdit: boolean = false
  12964. @State showPipLyric: boolean = false
  12965. @State isShowSpectrum: boolean = false//是否显示频谱
  12966. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  12967. async setRingTone() {
  12968. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  12969. return
  12970. }
  12971. // 确定后的逻辑
  12972. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  12973. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  12974. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  12975. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  12976. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  12977. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  12978. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  12979. , this.videoUrl, this.name).then(res => {
  12980. LogUtil.info('onecold setFlag :' + res);
  12981. });
  12982. }
  12983. doMore(moreId: number) {
  12984. switch (moreId) {
  12985. case 2: //歌词
  12986. this.isLyricSetting = !this.isLyricSetting;
  12987. this.isShowMoreView = false
  12988. break;
  12989. case 3: //详情
  12990. this.isShowDetailMore = !this.isShowDetailMore;
  12991. break;
  12992. case 4: //分享
  12993. if (this.currentSong !== undefined) {
  12994. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  12995. }
  12996. this.isShowMoreView = false
  12997. break;
  12998. case 5: //定时关闭
  12999. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  13000. break;
  13001. case 10: //设为铃声
  13002. this.setRingTone()
  13003. this.isShowMoreView = false
  13004. break;
  13005. case 11: //跳过头尾
  13006. this.isJumpSetting = !this.isJumpSetting;
  13007. break;
  13008. case 13: //倍速
  13009. break;
  13010. case 14: //搜索封面
  13011. if (this.currentSong !== undefined) {
  13012. this.doSearchCover(this.currentSong)
  13013. }
  13014. this.isShowMoreView = false
  13015. break;
  13016. case 15: //编辑标签
  13017. this.initEditFields(this.currentSong)
  13018. this.tempLyricContent = this.lyricContent
  13019. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  13020. this.lyricConStr = this.tempLyricContent
  13021. }
  13022. this.isShowEdit = !this.isShowEdit;
  13023. break;
  13024. case 16: //悬浮歌词
  13025. this.showPipLyric = !this.showPipLyric;
  13026. break;
  13027. case 17: //横屏模式
  13028. if (this.isLandscape) {
  13029. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  13030. } else {
  13031. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  13032. }
  13033. this.isShowMoreView = false
  13034. break;
  13035. case 20://AB循环
  13036. this.isABSheet = !this.isABSheet
  13037. break;
  13038. case 24://均衡器
  13039. this.isEqualizerSheet = !this.isEqualizerSheet
  13040. break;
  13041. }
  13042. }
  13043. //AB循环
  13044. @State isOpenAB:boolean = false
  13045. @State jumpATime:number = 0
  13046. @State jumpBTime:number = 0
  13047. @State isABSheet:boolean = false
  13048. @State isEqualizerSheet: boolean = false
  13049. @State eqApplying: boolean = false
  13050. @State eqAppliedAt: number = 0
  13051. @State eqCurrentPresetName: string = '正常'
  13052. @State eqCurrentEnabled: boolean = false
  13053. @Builder
  13054. ABLoopSheet() {
  13055. ABLoopComptent({
  13056. jumpATime:this.jumpATime,
  13057. jumpBTime:this.jumpBTime,
  13058. onClickAItem: async ()=>{
  13059. if(this.mIjkMediaPlayer){
  13060. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  13061. }
  13062. },
  13063. onClickBItem: async ()=>{
  13064. if(this.mIjkMediaPlayer){
  13065. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  13066. if(this.jumpBTime<=this.jumpATime){
  13067. ToastUtil.showToast('设置B点时间不能小于A点时间')
  13068. this.jumpBTime = 0
  13069. }
  13070. }
  13071. },
  13072. onCancleButtonClick: async ()=>{
  13073. this.isOpenAB = false
  13074. this.isABSheet = false
  13075. },
  13076. onStartButtonClick: async ()=>{
  13077. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  13078. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  13079. return
  13080. }
  13081. this.isABSheet = false
  13082. this.startABLoop()
  13083. },
  13084. })
  13085. }
  13086. private syncEqualizerUi(): void {
  13087. const equalizerManager = EqualizerManager.getInstance();
  13088. this.eqCurrentEnabled = equalizerManager.enabled;
  13089. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  13090. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  13091. this.eqAppliedAt = 0;
  13092. }
  13093. }
  13094. private markEqualizerApplied(): void {
  13095. const equalizerManager = EqualizerManager.getInstance();
  13096. this.eqCurrentEnabled = equalizerManager.enabled;
  13097. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  13098. this.eqAppliedAt = Date.now();
  13099. this.eqApplying = false;
  13100. }
  13101. private applyEqualizerToCurrentPlayback(): void {
  13102. if (this.eqApplying) {
  13103. return;
  13104. }
  13105. if (this.castControllerWrapper && this.isCastPlaying) {
  13106. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  13107. return;
  13108. }
  13109. if (!this.currentSong || !this.mIjkMediaPlayer) {
  13110. ToastUtil.showToast('暂无可应用的播放');
  13111. return;
  13112. }
  13113. this.eqApplying = true;
  13114. try {
  13115. const equalizerManager = EqualizerManager.getInstance();
  13116. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  13117. this.markEqualizerApplied();
  13118. ToastUtil.showToast('均衡器已实时生效');
  13119. } catch (error) {
  13120. this.eqApplying = false;
  13121. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  13122. }
  13123. }
  13124. @Builder
  13125. private EqualizerApplyStatusBar(): void {
  13126. Row() {
  13127. Column() {
  13128. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  13129. .fontSize(12)
  13130. .fontColor($r('app.color.text_color'))
  13131. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  13132. .fontSize(10)
  13133. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  13134. }
  13135. .alignItems(HorizontalAlign.Start)
  13136. Blank()
  13137. Button('重新应用')
  13138. .fontSize(12)
  13139. .fontColor(Color.White)
  13140. .backgroundColor('#666666')
  13141. .height(28)
  13142. .padding({ left: 14, right: 14 })
  13143. .borderRadius(14)
  13144. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  13145. .onClick(() => {
  13146. this.applyEqualizerToCurrentPlayback();
  13147. })
  13148. }
  13149. .width('100%')
  13150. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  13151. .backgroundColor($r('app.color.settings_background_main'))
  13152. .borderRadius(12)
  13153. }
  13154. @Builder
  13155. EqualizerSheet() {
  13156. Column() {
  13157. Column() {
  13158. EqualizerViewWithCallback({
  13159. onEqualizerChanged: () => {
  13160. this.syncEqualizerUi();
  13161. if (this.mIjkMediaPlayer) {
  13162. const equalizerManager = EqualizerManager.getInstance();
  13163. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  13164. this.markEqualizerApplied();
  13165. }
  13166. }
  13167. })
  13168. }
  13169. .margin({ top: 8 })
  13170. Column() {
  13171. this.EqualizerApplyStatusBar()
  13172. }
  13173. .margin({ top: 8 })
  13174. }
  13175. .padding({ left: 12, right: 12, bottom: 20 })
  13176. .width('100%')
  13177. }
  13178. //开始AB循环
  13179. startABLoop(){
  13180. if(this.mIjkMediaPlayer){
  13181. this.seekTo(this.jumpATime+'')
  13182. this.isOpenAB = true
  13183. }
  13184. }
  13185. /**
  13186. * 切换横竖屏
  13187. *
  13188. */
  13189. setOrientation(orientation: number) {
  13190. this.windowClass.setPreferredOrientation(orientation).then(() => {
  13191. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  13192. }).catch((err: BusinessError) => {
  13193. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  13194. });
  13195. }
  13196. /**
  13197. * 画中画功能(悬浮歌词功能)
  13198. *
  13199. */
  13200. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  13201. pipController?: PiPWindow.PiPController;
  13202. navigationId: string = '';
  13203. @State curState: string = '';
  13204. @State curError: ResourceStr = '';
  13205. @State pipBg: string = '#E8E8E8'
  13206. @State buttonAction: string = '';
  13207. //开启画中画功能
  13208. async startPip() {
  13209. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  13210. if (!this.pipController) {
  13211. await this.createPipController();
  13212. }
  13213. if (!this.pipController) {
  13214. Logger.info(`[${TAG}] pipController create error`);
  13215. return;
  13216. }
  13217. await this.pipController.startPiP();
  13218. }
  13219. async stopPip() {
  13220. if (!this.pipController) {
  13221. Logger.info(`[${TAG}] pipController is not exist`);
  13222. return;
  13223. }
  13224. this.isOpenPip = false
  13225. await this.pipController.stopPiP();
  13226. }
  13227. async createPipController() {
  13228. this.pipController = await PiPWindow.create({
  13229. context: getContext(this),
  13230. componentController: this.xcomponentController,
  13231. navigationId: this.navigationId,
  13232. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  13233. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  13234. customUIController: this.nodeController,
  13235. });
  13236. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  13237. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  13238. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13239. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  13240. this.onStateChange(state, reason);
  13241. });
  13242. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  13243. this.onActionEvent(event, status);
  13244. });
  13245. }
  13246. destroyPipController() {
  13247. if (!this.pipController) {
  13248. return;
  13249. }
  13250. this.pipController.off('stateChange');
  13251. this.pipController.off('controlPanelActionEvent');
  13252. this.pipController = undefined;
  13253. }
  13254. onStateChange(state: PiPWindow.PiPState, reason: string) {
  13255. switch (state) {
  13256. case PiPWindow.PiPState.ABOUT_TO_START:
  13257. this.curState = 'ABOUT_TO_START';
  13258. this.curError = $r('app.string.current_error_hint');
  13259. break;
  13260. case PiPWindow.PiPState.STARTED:
  13261. this.curState = 'STARTED';
  13262. this.curError = $r('app.string.current_error_hint');
  13263. break;
  13264. case PiPWindow.PiPState.ABOUT_TO_STOP:
  13265. this.curState = 'ABOUT_TO_STOP';
  13266. this.curError = $r('app.string.current_error_hint');
  13267. break;
  13268. case PiPWindow.PiPState.STOPPED:
  13269. this.curState = 'STOPPED';
  13270. this.curError = $r('app.string.current_error_hint');
  13271. this.stopPip()
  13272. this.destroyPipController()
  13273. break;
  13274. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  13275. this.curState = 'ABOUT_TO_RESTORE';
  13276. this.curError = $r('app.string.current_error_hint');
  13277. break;
  13278. case PiPWindow.PiPState.ERROR:
  13279. this.curState = 'ERROR';
  13280. this.curError = reason;
  13281. break;
  13282. default:
  13283. break;
  13284. }
  13285. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  13286. }
  13287. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  13288. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  13289. switch (event) {
  13290. case 'playbackStateChanged':
  13291. if (status === 0) {
  13292. this.pause();
  13293. } else {
  13294. console.info('onecold startPlayOrResumePlay 9869')
  13295. this.startPlayOrResumePlay();
  13296. }
  13297. break;
  13298. case 'nextVideo':
  13299. // 切换到下一个视频
  13300. this.playNext().catch(() => {
  13301. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  13302. });
  13303. break;
  13304. case 'previousVideo':
  13305. // 切换到上一个视频
  13306. this.playPrevious().catch(() => {
  13307. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  13308. });
  13309. break;
  13310. case 'previousVideo':
  13311. // 切换到上一个视频
  13312. this.playPrevious().catch(() => {
  13313. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  13314. });
  13315. break;
  13316. default:
  13317. }
  13318. this.buttonAction = event + `-status:${status}`;
  13319. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  13320. }
  13321. /**
  13322. * 画中画功能(悬浮歌词功能)结束
  13323. *
  13324. */
  13325. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  13326. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  13327. this.isShowMoreView = false;
  13328. this.showTipsDialog();
  13329. return ''; // Return empty string when no API is configured
  13330. }
  13331. if (!item) {
  13332. return ''; // Return empty string if item is undefined
  13333. }
  13334. const titleS = title||item?.name || '';
  13335. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  13336. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  13337. }
  13338. /**
  13339. *api搜索封面
  13340. *item,根据title和artist
  13341. */
  13342. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  13343. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  13344. LogUtil.debug("onecold res =" + res);
  13345. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  13346. if (item.filePath == this.currentSong?.filePath) {
  13347. this.cover = res;
  13348. if (this.currentSong) {
  13349. this.currentSong.pixelMapPath = res;
  13350. }
  13351. }
  13352. // Update pixel map path but always return res regardless of success
  13353. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  13354. if (success) {
  13355. this.doUpdateData();
  13356. console.log("onecold 更新音乐封面成功,数据库已同步");
  13357. } else {
  13358. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  13359. }
  13360. // Note: We don't resolve/reject here because we already returned res
  13361. });
  13362. LogUtil.debug("onecold this.cover =" + this.cover);
  13363. }
  13364. return res; // Always return res regardless of updatePixelMapPath result
  13365. });
  13366. }
  13367. @State jumpTopTime: number = 0
  13368. @State jumpEndTime: number = 0
  13369. @State isOpenJump: boolean = false
  13370. @Builder
  13371. JumpTopEndSheet() {
  13372. Scroll() {
  13373. Column() {
  13374. Column() {
  13375. Text('仅对本播放列表有效')
  13376. .fontSize(16)
  13377. .fontColor($r('app.color.text_color'))
  13378. // 跳过头尾
  13379. Column() {
  13380. Row() {
  13381. Text('跳过片头:')
  13382. .fontSize(16)
  13383. .fontColor($r('app.color.text_color'))
  13384. Text(this.jumpTopTime + 's')
  13385. .fontSize(16)
  13386. .fontColor($r('app.color.text_color'))
  13387. }
  13388. .margin({ bottom: 5 })
  13389. Row() {
  13390. Slider({
  13391. value: this.jumpTopTime,
  13392. min: 0,
  13393. max: 120,
  13394. step: 1,
  13395. style: SliderStyle.OutSet
  13396. })
  13397. .blockColor(this.themeColor)
  13398. .trackColor($r('app.color.speed_text_color'))
  13399. .selectedColor(Color.White)
  13400. .trackThickness(8)
  13401. .onChange((value: number) => {
  13402. this.jumpTopTime = value;
  13403. })
  13404. .width('85%')
  13405. }
  13406. .alignItems(VerticalAlign.Top)
  13407. }
  13408. .margin({ top: 10, bottom: 10 })
  13409. // 跳过头尾
  13410. Column() {
  13411. Row() {
  13412. Text('跳过片尾:')
  13413. .fontSize(16)
  13414. .fontColor($r('app.color.text_color'))
  13415. Text(this.jumpEndTime + 's')
  13416. .fontSize(16)
  13417. .fontColor($r('app.color.text_color'))
  13418. }
  13419. .margin({ bottom: 5 })
  13420. Row() {
  13421. Slider({
  13422. value: this.jumpEndTime,
  13423. min: 0,
  13424. max: 120,
  13425. step: 1,
  13426. style: SliderStyle.OutSet
  13427. })
  13428. .blockColor(this.themeColor)
  13429. .trackColor($r('app.color.speed_text_color'))
  13430. .selectedColor(Color.White)
  13431. .trackThickness(8)
  13432. .onChange((value: number) => {
  13433. this.jumpEndTime = value;
  13434. })
  13435. .width('85%')
  13436. }
  13437. .alignItems(VerticalAlign.Top)
  13438. }
  13439. .margin({ top: 10, bottom: 10 })
  13440. Row() {
  13441. Button('保存设置')
  13442. .fontColor(Color.White)
  13443. .layoutWeight(1)
  13444. .height(40)
  13445. .width(80)
  13446. .backgroundColor(this.themeColor)
  13447. .stateEffect(true)
  13448. .margin({ left: 0, bottom: 20 })
  13449. .onClick(async () => {
  13450. if (!Utility.isNoble()) {
  13451. this.isJumpSetting = false
  13452. this.isShowMoreView = false
  13453. this.showVipDialog()
  13454. return
  13455. }
  13456. if (this.currentSong === undefined) {
  13457. return
  13458. }
  13459. if (this.modeType === 0) {
  13460. let parentPath = FileUtil.getParentPath(this.videoUrl)
  13461. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  13462. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  13463. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  13464. } else if (this.modeType === 1) { //媒体库
  13465. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  13466. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  13467. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  13468. } else if (this.modeType === 2) { //艺术家
  13469. if (this.currentSong?.artist) {
  13470. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  13471. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  13472. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  13473. }
  13474. } else if (this.modeType === 3) { //专辑
  13475. if (this.currentSong?.album) {
  13476. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  13477. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  13478. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  13479. }
  13480. }
  13481. ToastUtil.showShort("保存成功")
  13482. this.isJumpSetting = false
  13483. })
  13484. }
  13485. .margin({
  13486. left: 38,
  13487. right: 38,
  13488. top: 10,
  13489. bottom: 10
  13490. })
  13491. .width(120)
  13492. .height(50)
  13493. }
  13494. }
  13495. }
  13496. .width('100%')
  13497. .height('100%')
  13498. }
  13499. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  13500. private onStateVastChange(state: AVCastPickerState) {
  13501. if (state == AVCastPickerState.STATE_APPEARING) {
  13502. console.log('The picker starts showing.');
  13503. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  13504. console.log('The picker finishes presenting.');
  13505. }
  13506. }
  13507. private showSelectLyric() {
  13508. DialogHelper.showActionSheetDialog({
  13509. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  13510. // sheets: ["本地歌词", "搜索歌词"],
  13511. sheets: [
  13512. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  13513. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  13514. ],
  13515. maskColor: Color.Transparent,
  13516. backgroundColor: $r('app.color.bg_card'),
  13517. transition: AnimationHelper.transitionInDown(666),
  13518. onAction: (index) => {
  13519. switch (index) {
  13520. case 0:
  13521. this.callFilePickerSelectFileForLyric()
  13522. break;
  13523. case 1:
  13524. if (StrUtil.isNotEmpty(this.videoUrl)) {
  13525. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  13526. this.initLyric(lyricPath);
  13527. }
  13528. break;
  13529. }
  13530. }
  13531. })
  13532. }
  13533. // 拉起picker选择文件管理器
  13534. async callFilePickerSelectFileForLyric(): Promise<void> {
  13535. try {
  13536. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  13537. DocumentSelectOptions.maxSelectNumber = 1
  13538. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  13539. let documentPicker = new picker.DocumentViewPicker();
  13540. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  13541. Logger.info(TAG,
  13542. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  13543. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  13544. this.saveVideoDatasLyric(DocumentSelectResult)
  13545. }
  13546. }).catch((err: BusinessError) => {
  13547. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  13548. });
  13549. } catch (err) {
  13550. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  13551. }
  13552. }
  13553. async saveVideoDatasLyric(uris: string[]) {
  13554. if (ArrayUtil.isEmpty(uris)) {
  13555. return
  13556. }
  13557. let newUris: string[] = [];
  13558. for (let i = 0; i < uris.length; i++) {
  13559. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  13560. Logger.info(TAG, 'filePath uri: ' + filePath);
  13561. newUris.push(filePath)
  13562. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  13563. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  13564. fileIo.copyFileSync(file.fd, file2.fd)
  13565. fileIo.closeSync(file);
  13566. fileIo.closeSync(file2);
  13567. this.initLyric(filePath,false,false,true)
  13568. }
  13569. }
  13570. private initDelayPlay(context: object) {
  13571. this.mContext = context;
  13572. }
  13573. startPipLyric() {
  13574. if (this.pipController) {
  13575. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  13576. PiPWindow.PiPControlStatus.PLAY);
  13577. }
  13578. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  13579. if (this.isOpenPip) {
  13580. this.startPip()
  13581. } else {
  13582. this.stopPip()
  13583. }
  13584. }
  13585. //startOffset 从cue分轨时间开始播
  13586. private startPlayOrResumePlay(startOffset?:number) {
  13587. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  13588. //针对dsf文件高采样率,统一转wav播放
  13589. // const sampleRate = this.currentSong?.sampleRate||0
  13590. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  13591. // console.info('onecold 采样率 ='+sampleRate)
  13592. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  13593. // console.info('onecold newDsfPath ='+newDsfPath)
  13594. // if(!FileUtil.accessSync(newDsfPath)){
  13595. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  13596. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  13597. // this.videoUrl = newDsfPath
  13598. // this.startPlay(startOffset)
  13599. // }).catch((e:object)=>{
  13600. // console.info("task1 catch e: " + e);
  13601. // })
  13602. // }else{
  13603. // this.videoUrl = newDsfPath
  13604. // this.startPlay(startOffset)
  13605. // }
  13606. //
  13607. // }else{
  13608. // this.startPlay(startOffset)
  13609. // }
  13610. this.startPlay(startOffset)
  13611. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  13612. // 排除用户拖动进度条的情况
  13613. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  13614. void this.preloadNextSongInternal();
  13615. }
  13616. }
  13617. startPlay(startOffset?:number) {
  13618. this.startPipLyric()
  13619. this.mDestroyPage = false;
  13620. this.animationState = AnimationStatus.Running
  13621. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  13622. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  13623. this.stopProgressTask();
  13624. this.startProgressTask();
  13625. this.clearInitialSeekGuardTimer();
  13626. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  13627. this.remoteRestoreSeekToken++;
  13628. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  13629. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  13630. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  13631. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  13632. this.videoUrl.includes('://');
  13633. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  13634. // 判断是否是HTTP或在线网盘视频,显示加载进度
  13635. this.isPlayerLoading = this.waitInitialSeekBeforeStart;
  13636. this.play(this.videoUrl.toString(),startOffset);
  13637. }
  13638. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  13639. this.mIjkMediaPlayer.start();
  13640. this.setProgress()
  13641. this.CONTROL_PlayStatus = PlayStatus.PLAY
  13642. }
  13643. this.setIsPlaying(true)
  13644. this.updateSessionPlayState(true)
  13645. this.watchStatus();
  13646. this.updateLastPlayTimeStr(this.videoUrl)
  13647. }
  13648. updateLastPlayTimeStr(filePath: string) {
  13649. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  13650. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  13651. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  13652. return;
  13653. }
  13654. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  13655. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  13656. if (success) {
  13657. this.getHistoryList(false)
  13658. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  13659. } else {
  13660. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  13661. }
  13662. });
  13663. }
  13664. private completionNum(num: number): string | number {
  13665. if (num < 10) {
  13666. return '0' + num;
  13667. } else {
  13668. return num;
  13669. }
  13670. }
  13671. private parseDurationToMs(duration?: string): number {
  13672. if (!duration) {
  13673. return 0;
  13674. }
  13675. const parts = duration.split(':').map((item) => Number(item));
  13676. if (parts.some((item) => Number.isNaN(item))) {
  13677. return 0;
  13678. }
  13679. if (parts.length === 2) {
  13680. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  13681. }
  13682. if (parts.length === 3) {
  13683. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  13684. }
  13685. return 0;
  13686. }
  13687. private stringForTime(timeMs: number): string {
  13688. let totalSeconds: number | string = (timeMs / 1000);
  13689. let newSeconds: number | string = totalSeconds % 60;
  13690. let minutes: number | string = (totalSeconds / 60) % 60;
  13691. let hours: number | string = totalSeconds / 3600;
  13692. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  13693. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  13694. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  13695. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  13696. if (this.isCurrentTime) {
  13697. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  13698. this.oldSeconds = newSeconds
  13699. } else {
  13700. newSeconds = this.oldSeconds
  13701. }
  13702. }
  13703. newSeconds = this.completionNum(newSeconds);
  13704. if (hours > 0) {
  13705. return hours + ":" + minutes + ":" + newSeconds;
  13706. } else {
  13707. return minutes + ":" + newSeconds;
  13708. }
  13709. }
  13710. private updateLyricPosition(lyricPosition: number): void {
  13711. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  13712. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  13713. return;
  13714. }
  13715. this.lastLyricRenderPosition = lyricPosition;
  13716. this.lyricController.updatePosition(lyricPosition);
  13717. if(this.showPipLyric){
  13718. this.lyricControllerXF.updatePosition(lyricPosition);
  13719. }
  13720. if(this.isShowSingleLineLyric){
  13721. this.lyricControllerSingle.updatePosition(lyricPosition);
  13722. }
  13723. }
  13724. private setProgress() {
  13725. if (this.castControllerWrapper && this.isCastPlaying) {
  13726. return;
  13727. }
  13728. let position = this.mIjkMediaPlayer.getCurrentPosition();
  13729. let duration = this.mIjkMediaPlayer.getDuration();
  13730. if (duration <= 0 && this.duration > 0) {
  13731. duration = this.duration;
  13732. }
  13733. let pos = 0;
  13734. if (duration > 0) {
  13735. this.slideEnable = true;
  13736. let curPercent = position / duration;
  13737. pos = curPercent * 100;
  13738. if (pos > this.PROGRESS_MAX_VALUE) {
  13739. this.progressValue = this.PROGRESS_MAX_VALUE
  13740. } else {
  13741. this.progressValue = pos;
  13742. }
  13743. }
  13744. // LogUtils.getInstance()
  13745. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  13746. this.totalTime = this.stringForTime(duration);
  13747. if (position > duration) {
  13748. position = duration;
  13749. }
  13750. const lyricPosition = position + this.timeOffset * 1000;
  13751. this.isCurrentTime = true;
  13752. this.updateLyricPosition(lyricPosition);
  13753. // 蓝牙歌词更新逻辑
  13754. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  13755. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  13756. // 仅在歌词行变化时更新,避免频繁调用
  13757. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  13758. this.lastBluetoothLyricLine = currentLyricLine;
  13759. this.avSessionController.updateBluetoothLyric(
  13760. currentLyricLine,
  13761. this.currentSong.name || '',
  13762. this.currentSong.artist || '',
  13763. this.bluetoothLyricMode
  13764. );
  13765. }
  13766. }
  13767. this.currentTime = this.stringForTime(position);
  13768. this.isCurrentTime = false
  13769. if (this.mIjkMediaPlayer.isPlaying()) {
  13770. //如果是开启AB循环
  13771. if(this.isOpenAB){
  13772. if(position >=this.jumpBTime){
  13773. this.seekTo(this.jumpATime+'')
  13774. return
  13775. }
  13776. }
  13777. // 判断是否播放到结束时间
  13778. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  13779. if (position >= duration - this.jumpEndTime * 1000) {
  13780. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  13781. this.CONTROL_PlayStatus = PlayStatus.INIT
  13782. this.startPlayOrResumePlay();
  13783. }else if (this.playType == 2) { //2:正常播放,单片播完
  13784. this.showRePlay();
  13785. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  13786. this.progressValue = this.PROGRESS_MAX_VALUE;
  13787. this.slideEnable = false;
  13788. this.stop();
  13789. // ToastUtil.showToast('开始重新播放')
  13790. }else if (this.playType == 4) { //4:连续播放不循环
  13791. // 检查是否是最后一首
  13792. if (this.curIndex >= this.songList.length - 1) {
  13793. // 已经是最后一首,停止播放
  13794. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  13795. ToastUtil.showToast('已经是最后一首了');
  13796. this.showRePlay();
  13797. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  13798. this.progressValue = this.PROGRESS_MAX_VALUE;
  13799. this.slideEnable = false;
  13800. this.stop();
  13801. } else {
  13802. // 不是最后一首,继续播放下一首
  13803. this.playNext().catch(() => {
  13804. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  13805. });
  13806. }
  13807. }else{
  13808. this.playNext().catch(() => {
  13809. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  13810. });
  13811. }
  13812. }
  13813. }
  13814. }
  13815. }
  13816. private startProgressTask() {
  13817. let that = this;
  13818. this.updateProgressTimer = setInterval(() => {
  13819. //LogUtils.getInstance().LOGI("startProgressTask");
  13820. if (!that.mDestroyPage) {
  13821. that.setProgress();
  13822. }
  13823. }, this.progressUpdateIntervalMs);
  13824. }
  13825. private stopProgressTask() {
  13826. LogUtils.getInstance().LOGI("stopProgressTask");
  13827. clearInterval(this.updateProgressTimer);
  13828. }
  13829. private showLoadIng() {
  13830. this.loadingVisible = Visibility.Visible;
  13831. this.replayVisible = Visibility.None;
  13832. }
  13833. private hideLoadIng() {
  13834. this.loadingVisible = Visibility.None;
  13835. this.replayVisible = Visibility.None;
  13836. }
  13837. private showRePlay() {
  13838. this.loadingVisible = Visibility.None;
  13839. this.replayVisible = Visibility.Visible;
  13840. }
  13841. private clearInitialSeekGuardTimer(): void {
  13842. if (this.initialSeekGuardTimer) {
  13843. clearTimeout(this.initialSeekGuardTimer);
  13844. this.initialSeekGuardTimer = 0;
  13845. }
  13846. }
  13847. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  13848. try {
  13849. if (!this.mIjkMediaPlayer.isPlaying()) {
  13850. this.mIjkMediaPlayer.start();
  13851. }
  13852. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  13853. this.setIsPlaying(true);
  13854. this.updateSessionPlayState(true);
  13855. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  13856. } catch (error) {
  13857. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  13858. }
  13859. }
  13860. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  13861. this.clearInitialSeekGuardTimer();
  13862. const wasWaiting = this.waitInitialSeekBeforeStart;
  13863. this.waitInitialSeekBeforeStart = false;
  13864. this.pendingMemorySeekPosition = 0;
  13865. this.isPlayerLoading = false;
  13866. this.hideLoadIng();
  13867. if (wasWaiting) {
  13868. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  13869. }
  13870. if (shouldStart) {
  13871. this.ensurePlayerStartedAfterInitialSeek(reason);
  13872. }
  13873. }
  13874. private startInitialSeekGuardTimer(scene: string): void {
  13875. this.clearInitialSeekGuardTimer();
  13876. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  13877. return;
  13878. }
  13879. const token = this.remoteRestoreSeekToken;
  13880. this.initialSeekGuardTimer = setTimeout(() => {
  13881. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  13882. return;
  13883. }
  13884. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  13885. this.finishInitialSeekWait('seek-timeout', true);
  13886. }, this.initialSeekGuardTimeoutMs);
  13887. }
  13888. private async play(url: string,startOffset?:number) {
  13889. this.lyricController.setLyric(null)
  13890. this.lyricControllerSingle.setLyric(null)
  13891. this.lastLyricRenderPosition = Number.NaN;
  13892. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  13893. console.info('onecold this.url 1= '+url)
  13894. if(!url.toLowerCase().startsWith('http')){
  13895. let hasPermission = await PermissionUtil.activatePermission(url)
  13896. console.info('onecold this.hasPermission 1= '+hasPermission)
  13897. if(!url.includes(this.packName)){
  13898. const file = fs.openSync(url)
  13899. this.videoUrl = file.path
  13900. url= this.videoUrl
  13901. }
  13902. console.info('onecold this.hasPermission 1= '+hasPermission)
  13903. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  13904. }
  13905. let that = this;
  13906. if (this.waitInitialSeekBeforeStart) {
  13907. that.showLoadIng();
  13908. } else {
  13909. that.hideLoadIng();
  13910. }
  13911. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  13912. this.isOpenAB = false
  13913. //设置XComponent回调的context
  13914. if (!!this.mContext) {
  13915. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  13916. }
  13917. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  13918. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  13919. try {
  13920. this.mIjkMediaPlayer.reset();
  13921. Logger.info(TAG, 'IjkPlayer reset 成功');
  13922. } catch (error) {
  13923. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  13924. }
  13925. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  13926. //设置debug模式(用于EQ日志采集)
  13927. this.mIjkMediaPlayer.setDebug(true);
  13928. //初始化配置
  13929. this.mIjkMediaPlayer.native_setup();
  13930. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  13931. if(this.volumeSmall){
  13932. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  13933. this.mIjkMediaPlayer.setVolume('1', '1');
  13934. }else{
  13935. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  13936. }
  13937. }else{
  13938. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  13939. }
  13940. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  13941. const headers = new Map<string, string>();
  13942. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  13943. headers.set("Accept", "*/*");
  13944. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  13945. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  13946. //如果封面为空,则搜索封面
  13947. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  13948. }
  13949. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  13950. // SMB类型通过本地HTTP代理播放,不需要认证头,排除SMB和百度类型
  13951. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type) && !isSmbType(this.currentSong.type)) {
  13952. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  13953. if (this.currentSong.webdav_account_id) {
  13954. try {
  13955. const webdavManager = RemoteDriveManager.getInstance();
  13956. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  13957. if (webDavHeaders && webDavHeaders.size > 0) {
  13958. webDavHeaders.forEach((value, key) => headers.set(key, value));
  13959. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  13960. } else {
  13961. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  13962. }
  13963. } catch (error) {
  13964. const err = error as Error;
  13965. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  13966. }
  13967. } else {
  13968. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  13969. }
  13970. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  13971. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  13972. }
  13973. // 统一设置带认证的请求头
  13974. // 百度类型也需要特殊请求头
  13975. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  13976. try {
  13977. const webdavManager = RemoteDriveManager.getInstance();
  13978. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  13979. baiduHeaders.forEach((value, key) => headers.set(key, value));
  13980. const headerSnapshot: Record<string, string> = {};
  13981. headers.forEach((value, key) => headerSnapshot[key] = value);
  13982. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  13983. } catch (error) {
  13984. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  13985. }
  13986. }
  13987. //设置视频源(先准备好认证头,再设置数据源)
  13988. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  13989. this.mIjkMediaPlayer.setDataSource(url);
  13990. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  13991. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  13992. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  13993. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  13994. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  13995. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  13996. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  13997. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  13998. // 缓冲和播放优化设置
  13999. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  14000. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  14001. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  14002. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  14003. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  14004. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  14005. // 网络相关设置
  14006. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  14007. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  14008. // 重连设置
  14009. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  14010. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  14011. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  14012. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  14013. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  14014. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  14015. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  14016. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  14017. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  14018. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  14019. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  14020. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  14021. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  14022. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  14023. }
  14024. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  14025. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  14026. // }
  14027. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  14028. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  14029. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  14030. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  14031. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  14032. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  14033. //停止预读的最小帧数
  14034. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  14035. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  14036. // 设置其他缓冲相关选项
  14037. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  14038. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  14039. //启动预加载
  14040. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  14041. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  14042. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  14043. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  14044. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  14045. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  14046. // 因此需要播放器丢包,才不会累积延时
  14047. // 这个和第三个参数packet-buffering无关。
  14048. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  14049. // 无限制收流
  14050. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  14051. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  14052. // 屏幕常亮
  14053. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  14054. // 开启hls起播优化 默认是关闭的
  14055. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  14056. // 设置超时
  14057. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  14058. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  14059. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  14060. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  14061. // 变速播放
  14062. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  14063. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14064. let Speed = this.mIjkMediaPlayer.getSpeed()
  14065. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  14066. //是否开启循环播放
  14067. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  14068. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  14069. (width: number, height: number, sar_num: number, sar_den: number) => {
  14070. if (height === 0) {
  14071. return;
  14072. }
  14073. const va = width / height;
  14074. const vpa = that.videoParentAspectRatio;
  14075. if (vpa > va) {
  14076. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  14077. } else {
  14078. that.videoWidth = '100%';
  14079. }
  14080. if (width && height) {
  14081. that.videoAspectRatio = width / height;
  14082. }
  14083. LogUtils.getInstance()
  14084. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  14085. if (!that.waitInitialSeekBeforeStart) {
  14086. that.hideLoadIng();
  14087. }
  14088. }
  14089. );
  14090. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  14091. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  14092. async () => {
  14093. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  14094. if (!this.waitInitialSeekBeforeStart) {
  14095. // 无记忆seek时,prepared后可直接隐藏加载
  14096. this.isPlayerLoading = false;
  14097. }
  14098. try {
  14099. //保存碰一碰分享的当前的歌曲
  14100. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  14101. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  14102. await this.initLyric(lyricPath);
  14103. const applyDuration = (durationMs: number): void => {
  14104. if (durationMs <= 0) {
  14105. return;
  14106. }
  14107. this.duration = durationMs;
  14108. this.durationTime = Math.floor(durationMs / 1000);
  14109. this.durationStringTime = secondToTime(this.durationTime);
  14110. this.totalTime = this.stringForTime(durationMs);
  14111. if (this.currentSong) {
  14112. this.currentSong.duration = this.totalTime;
  14113. try {
  14114. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  14115. } catch (metaError) {
  14116. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  14117. }
  14118. }
  14119. };
  14120. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  14121. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  14122. return 0;
  14123. }
  14124. const httpRequest = http.createHttp();
  14125. try {
  14126. const response = await httpRequest.request(url, {
  14127. method: http.RequestMethod.GET,
  14128. connectTimeout: 8000,
  14129. readTimeout: 8000,
  14130. expectDataType: http.HttpDataType.STRING,
  14131. header: {
  14132. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  14133. 'Host': 'pan.baidu.com',
  14134. 'Referer': 'https://pan.baidu.com/disk/home',
  14135. 'Accept-Encoding': 'identity'
  14136. }
  14137. });
  14138. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  14139. return 0;
  14140. }
  14141. const text = response.result;
  14142. if (text.indexOf('#EXTM3U') < 0) {
  14143. return 0;
  14144. }
  14145. const lines = text.split('\n');
  14146. let totalSeconds = 0;
  14147. for (let i = 0; i < lines.length; i++) {
  14148. const line = lines[i].trim();
  14149. if (line.startsWith('#EXTINF:')) {
  14150. const colonIndex = line.indexOf(':');
  14151. if (colonIndex < 0) {
  14152. continue;
  14153. }
  14154. const content = line.substring(colonIndex + 1);
  14155. const commaIndex = content.indexOf(',');
  14156. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  14157. const seconds = Number(numberPart);
  14158. if (!Number.isNaN(seconds) && seconds > 0) {
  14159. totalSeconds += seconds;
  14160. }
  14161. }
  14162. }
  14163. if (totalSeconds > 0) {
  14164. return Math.floor(totalSeconds * 1000);
  14165. }
  14166. return 0;
  14167. } catch (fetchError) {
  14168. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  14169. return 0;
  14170. } finally {
  14171. httpRequest.destroy();
  14172. }
  14173. };
  14174. const fetchDurationFallback = async (): Promise<void> => {
  14175. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  14176. if (durationMs > 0) {
  14177. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  14178. applyDuration(durationMs);
  14179. return;
  14180. }
  14181. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  14182. };
  14183. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  14184. console.info("onecold preparedDuration--" + preparedDuration)
  14185. if (preparedDuration > 0) {
  14186. applyDuration(preparedDuration);
  14187. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  14188. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  14189. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  14190. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  14191. applyDuration(durationMs);
  14192. }
  14193. }
  14194. } else {
  14195. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  14196. if (metaDurationMs > 0) {
  14197. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  14198. applyDuration(metaDurationMs);
  14199. } else {
  14200. fetchDurationFallback();
  14201. }
  14202. }
  14203. setTimeout(() => {
  14204. this.avSessionController.initAvSession(false);
  14205. if (this.duration > 0) {
  14206. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  14207. }
  14208. this.setAvSessionListener();
  14209. this.updateSessionPlayState(true)
  14210. this.setCurrentPlayMode()
  14211. if(startOffset&&startOffset>0){//cue分轨播放
  14212. this.seekTo(startOffset + "");
  14213. this.saveLastPlayList()
  14214. return
  14215. }
  14216. }, 500)
  14217. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  14218. let timeoutPlay = 0
  14219. if (StrUtil.isNotEmpty(this.videoUrl) &&
  14220. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  14221. timeoutPlay = 400
  14222. }
  14223. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  14224. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  14225. timeoutPlay = Math.max(timeoutPlay,
  14226. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  14227. }
  14228. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  14229. if (this.modeType === 0) { //文件夹
  14230. let parentPath = FileUtil.getParentPath(this.videoUrl)
  14231. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  14232. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  14233. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  14234. } else if (this.modeType === 1) { //媒体库
  14235. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  14236. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  14237. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  14238. } else if (this.modeType === 2) { //艺术家
  14239. if (this.currentSong?.artist) {
  14240. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  14241. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  14242. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  14243. }
  14244. } else if (this.modeType === 3) { //专辑
  14245. if (this.currentSong?.album) {
  14246. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  14247. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  14248. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  14249. }
  14250. }
  14251. const playerDuration = this.mIjkMediaPlayer.getDuration()
  14252. if (playerDuration > 0) {
  14253. this.duration = playerDuration
  14254. }
  14255. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  14256. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  14257. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  14258. let targetSeekPosition = memoryPosition;
  14259. if (this.isOpenJump) {
  14260. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  14261. }
  14262. this.pendingMemorySeekPosition = targetSeekPosition;
  14263. this.startInitialSeekGuardTimer('prepared-memory-seek');
  14264. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  14265. setTimeout(() => {
  14266. if (!this.waitInitialSeekBeforeStart) {
  14267. return;
  14268. }
  14269. this.restorePlaybackPosition();
  14270. }, timeoutPlay);
  14271. this.isFirstStartPlay = false
  14272. this.saveLastPlayList()
  14273. return
  14274. }
  14275. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  14276. if (this.mIjkMediaPlayer != null) {
  14277. let jumpTopTimeMs = this.jumpTopTime*1000;
  14278. if (jumpTopTimeMs <= this.duration) {
  14279. // 调用 seekTo 方法,跳到指定时间
  14280. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  14281. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  14282. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  14283. }
  14284. }, timeoutPlay)
  14285. } else {
  14286. // 提示用户无法跳过
  14287. ToastUtil.showToast('跳过时间超过视频时长');
  14288. }
  14289. }
  14290. } else {
  14291. this.jumpTopTime = 0
  14292. this.jumpEndTime = 0
  14293. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  14294. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  14295. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  14296. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  14297. //记忆播放(每一首都会记忆播放)
  14298. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  14299. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  14300. if (this.pendingMemorySeekPosition > 0 ||
  14301. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  14302. this.restorePlaybackPosition() //读取播放记忆功能
  14303. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  14304. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  14305. this.restorePlaybackPosition() //读取播放记忆功能
  14306. }
  14307. this.isFirstStartPlay = false
  14308. }, timeoutPlay)
  14309. } else {
  14310. this.isFirstStartPlay = false
  14311. }
  14312. }
  14313. this.saveLastPlayList()
  14314. } catch (error) {
  14315. let err: BusinessError = error as BusinessError;
  14316. console.error('onecold failed with err: ' + JSON.stringify(err));
  14317. if (this.waitInitialSeekBeforeStart) {
  14318. this.finishInitialSeekWait('prepared-exception', true);
  14319. }
  14320. }
  14321. }
  14322. );
  14323. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  14324. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  14325. (text: string) => {
  14326. }
  14327. );
  14328. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  14329. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  14330. () => {
  14331. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  14332. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  14333. // 异步调用playNext
  14334. this.playNext().catch(() => {
  14335. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  14336. });
  14337. } else if (this.playType == 1) { //1:单片重复播放
  14338. this.CONTROL_PlayStatus = PlayStatus.INIT
  14339. that.startPlayOrResumePlay();
  14340. } else if (this.playType == 2) { //2:正常播放,单曲播完
  14341. that.showRePlay();
  14342. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  14343. that.progressValue = this.PROGRESS_MAX_VALUE;
  14344. that.slideEnable = false;
  14345. that.stop();
  14346. // ToastUtil.showToast('开始重新播放')
  14347. } else if (this.playType == 3) { //3:随机播放
  14348. // 异步调用randomPlay
  14349. this.randomPlay().catch(() => {
  14350. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  14351. });
  14352. } else if (this.playType == 4) { //4:连续播放不循环
  14353. // 异步调用playNext
  14354. this.playNext().catch(() => {
  14355. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  14356. });
  14357. }
  14358. }
  14359. );
  14360. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  14361. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  14362. (percent: number) => {
  14363. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  14364. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  14365. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  14366. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  14367. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  14368. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  14369. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  14370. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  14371. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  14372. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  14373. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  14374. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  14375. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  14376. let Looping = this.mIjkMediaPlayer.isLooping()
  14377. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  14378. }
  14379. );
  14380. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  14381. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  14382. () => {
  14383. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  14384. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  14385. setTimeout(() => {
  14386. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  14387. that.isSeekTo = false;
  14388. if (waitingInitialSeek) {
  14389. that.finishInitialSeekWait('seek-complete', true);
  14390. } else {
  14391. that.hideLoadIng();
  14392. }
  14393. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  14394. }
  14395. );
  14396. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  14397. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  14398. (what: number, extra: number) => {
  14399. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  14400. if (!that.waitInitialSeekBeforeStart) {
  14401. that.hideLoadIng();
  14402. }
  14403. }
  14404. );
  14405. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  14406. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  14407. (what: number, extra: number) => {
  14408. this.finishInitialSeekWait('player-error', false);
  14409. this.stopProgressTask();
  14410. console.info("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  14411. console.info('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  14412. // 检查是否为WebDAV播放错误
  14413. let isWebDavError = false;
  14414. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  14415. try {
  14416. const globalContext = GlobalContext.getContext();
  14417. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  14418. if (webDavAuthInfo) {
  14419. isWebDavError = true;
  14420. }
  14421. } catch (error) {
  14422. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  14423. }
  14424. }
  14425. if (isWebDavError) {
  14426. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  14427. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  14428. // this.currentWebDavAuthInfo = null;
  14429. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  14430. // 根据错误代码提供更具体的错误信息
  14431. let errorMessage = "WebDAV播放失败";
  14432. if (what === -1) { // 网络错误
  14433. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  14434. } else if (what === -1004) { // HTTP 404
  14435. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  14436. } else if (what === -1001) { // 超时
  14437. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  14438. } else if (what === -1003) { // 无法解析主机
  14439. errorMessage = "无法连接到WebDAV服务器";
  14440. }
  14441. ToastUtil.showToast(errorMessage);
  14442. } else {
  14443. if (StrUtil.isNotEmpty(this.videoUrl) &&
  14444. !this.videoUrl.startsWith('http') &&
  14445. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  14446. !FileUtil.accessSync(this.videoUrl)) {
  14447. console.info('heanup 播放.文件不存在');
  14448. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  14449. }
  14450. }
  14451. that.hideLoadIng();
  14452. }
  14453. );
  14454. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  14455. this.mIjkMediaPlayer.setMessageListener();
  14456. // 应用均衡器设置
  14457. try {
  14458. const equalizerManager = EqualizerManager.getInstance();
  14459. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14460. Logger.info(TAG, 'heanup 均衡器设置已应用');
  14461. this.markEqualizerApplied();
  14462. } catch (eqError) {
  14463. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  14464. this.eqApplying = false;
  14465. }
  14466. this.mIjkMediaPlayer.prepareAsync();
  14467. this.mIjkMediaPlayer.start();
  14468. }
  14469. //保存最后播放的那首歌和已经对应的播放列表
  14470. saveLastPlayList() {
  14471. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  14472. PreferencesUtil.putSync('LastMusicList', this.songList)
  14473. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  14474. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  14475. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  14476. }
  14477. // 清空播放记录
  14478. clearVideoHistory() {
  14479. this.table.clearPlayHistory((success: boolean, error?: string) => {
  14480. if (success) {
  14481. this.historyList = [];
  14482. this.updateListData(this.historyList)
  14483. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  14484. ToastUtil.showToast('清空播放记录成功')
  14485. } else {
  14486. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  14487. }
  14488. });
  14489. }
  14490. public async setAvSessionListener() {
  14491. if (!this.avSessionController) {
  14492. return;
  14493. }
  14494. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  14495. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  14496. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  14497. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  14498. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  14499. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  14500. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  14501. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  14502. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  14503. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  14504. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  14505. }
  14506. setLoopMode() {
  14507. let itype = this.playType + 1
  14508. if (itype >= 5) {
  14509. this.playType = 0
  14510. ToastUtil.showToast('连续循环播放')
  14511. } else if (itype === 1) {
  14512. this.playType = 1
  14513. ToastUtil.showToast('单曲循环')
  14514. } else if (itype === 2) {
  14515. this.playType = 2
  14516. ToastUtil.showToast('单曲播完')
  14517. } else if (itype === 3) {
  14518. this.playType = 3
  14519. ToastUtil.showToast('随机播放')
  14520. } else if (itype === 4) {
  14521. this.playType = 4
  14522. ToastUtil.showToast('连续播放不循环')
  14523. } else if (itype === 0) {
  14524. this.playType = 0
  14525. ToastUtil.showToast('连续循环播放')
  14526. }
  14527. PreferencesUtil.putSync('musicPlayType', this.playType)
  14528. this.setCurrentPlayMode()
  14529. }
  14530. private sessionSetLoopModeCallback = (mode: number) => {
  14531. if (this.mIjkMediaPlayer != null) {
  14532. ToastUtil.showToast('当前播放模式:' + mode)
  14533. Logger.info('onecold 当前播放模式= ' + mode)
  14534. let hmPlayMode = mode + 1
  14535. if (hmPlayMode >= 4) {
  14536. hmPlayMode = 0
  14537. }
  14538. if (hmPlayMode === 1) {
  14539. this.playType = 1
  14540. ToastUtil.showToast('单曲循环')
  14541. } else if (hmPlayMode === 0) {
  14542. this.playType = 2
  14543. ToastUtil.showToast('单曲播完')
  14544. } else if (hmPlayMode === 3) {
  14545. this.playType = 3
  14546. ToastUtil.showToast('随机播放')
  14547. } else if (hmPlayMode === 2) {
  14548. this.playType = 0
  14549. ToastUtil.showToast('连续循环播放')
  14550. } else if (hmPlayMode === 4) {
  14551. this.playType = 4
  14552. ToastUtil.showToast('连续播放不循环')
  14553. }
  14554. PreferencesUtil.putSync('musicPlayType', this.playType)
  14555. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  14556. let playBackState: avSession.AVPlaybackState = {
  14557. loopMode: hmPlayMode,
  14558. };
  14559. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  14560. console.info(`set setLoopMode AVPlaybackState successfully`);
  14561. }).catch((err: BusinessError) => {
  14562. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  14563. });
  14564. }
  14565. }
  14566. setCurrentPlayMode() {
  14567. if (!this.avSessionController) {
  14568. return;
  14569. }
  14570. let mLoopMode = 0
  14571. switch (this.playType) {
  14572. case 0:
  14573. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  14574. break;
  14575. case 1:
  14576. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  14577. break;
  14578. case 2:
  14579. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  14580. break;
  14581. case 3:
  14582. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  14583. break;
  14584. case 4:
  14585. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  14586. break;
  14587. }
  14588. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  14589. let playBState: avSession.AVPlaybackState = {
  14590. loopMode: mLoopMode,
  14591. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  14592. };
  14593. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  14594. console.info(`set setLoopMode AVPlaybackState successfully`);
  14595. }).catch((err: BusinessError) => {
  14596. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  14597. });
  14598. }
  14599. private sessionToggleFavoriteCallback = (assetId: string) => {
  14600. if (this.mIjkMediaPlayer != null && this.currentSong) {
  14601. console.info(`on toggleFavorite `);
  14602. // 应用收到收藏命令,进行收藏处理。
  14603. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  14604. this.doFav(this.currentSong)
  14605. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  14606. let playbackState: avSession.AVPlaybackState = {
  14607. isFavorite: !this.isFac,
  14608. };
  14609. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  14610. console.info(`SetAVPlaybackState successfully`);
  14611. }).catch((err: BusinessError) => {
  14612. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  14613. });
  14614. }
  14615. }
  14616. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  14617. device: avSession.OutputDeviceInfo) => {
  14618. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  14619. // 将 connectState 转换为可读的字符串
  14620. let stateName = 'UNKNOWN';
  14621. switch (connectState) {
  14622. case avSession.ConnectionState.STATE_CONNECTED:
  14623. stateName = 'CONNECTED(1)';
  14624. break;
  14625. case avSession.ConnectionState.STATE_DISCONNECTED:
  14626. stateName = 'DISCONNECTED(2)';
  14627. break;
  14628. case avSession.ConnectionState.STATE_CONNECTING:
  14629. stateName = 'CONNECTING(3)';
  14630. break;
  14631. default:
  14632. stateName = `OTHER(${connectState})`;
  14633. }
  14634. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  14635. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  14636. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  14637. await this.startCasting();
  14638. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  14639. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  14640. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  14641. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  14642. if (device) {
  14643. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  14644. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  14645. this.endCasting();
  14646. }
  14647. }
  14648. };
  14649. private async startCasting() {
  14650. try {
  14651. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  14652. // 获取原始的 AVCastController
  14653. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  14654. if (!avCastCtrl) {
  14655. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  14656. return;
  14657. }
  14658. this.castController = avCastCtrl;
  14659. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  14660. // 创建新的 CastController 封装器
  14661. this.castControllerWrapper = new CastController(avCastCtrl);
  14662. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  14663. // 设置回调函数
  14664. let callbacks: CastControllerCallbacks = {
  14665. onPlayNext: () => {
  14666. Logger.info('heanup CastController', '收到 playNext 回调');
  14667. this.playNext();
  14668. },
  14669. onPlayPrevious: () => {
  14670. Logger.info('heanup CastController', '收到 playPrevious 回调');
  14671. this.playPrevious();
  14672. },
  14673. onPositionChanged: (position: number) => {
  14674. this.positionChange(position);
  14675. },
  14676. onDurationChanged: (duration: number) => {
  14677. this.playDurationChange(duration);
  14678. }
  14679. };
  14680. this.castControllerWrapper.setCallbacks(callbacks);
  14681. Logger.info('heanup startCasting', '✅ 设置回调成功');
  14682. // 暂停本地播放
  14683. this.pause();
  14684. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  14685. // 初始化投播会话
  14686. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  14687. await this.castControllerWrapper.initAVCast(
  14688. this.songList,
  14689. this.curIndex,
  14690. this.mIjkMediaPlayer.getCurrentPosition(),
  14691. this.videoUrl,
  14692. this.getActiveDuration()
  14693. );
  14694. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  14695. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  14696. refToIsCasting?.set(true);
  14697. this.castSeek = true;
  14698. // 从 CastController 获取投播状态
  14699. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  14700. if (this.isCastPlaying) {
  14701. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  14702. this.setIsPlaying(true);
  14703. this.updateSessionPlayState(true);
  14704. }
  14705. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  14706. } catch (error) {
  14707. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  14708. }
  14709. }
  14710. async changeCasting() {
  14711. Logger.info('heanup changeCasting', '切换投播');
  14712. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  14713. this.initQueueItem();
  14714. await this.prepare();
  14715. this.setPlaybackStateChangeListener();
  14716. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  14717. this.castSeek = true;
  14718. }
  14719. public endCasting() {
  14720. Logger.info('heanup endCasting', 'endCasting被调用');
  14721. this.avSessionController.getAvSession()?.stopCasting();
  14722. this.stopCast();
  14723. // 关闭文件描述符
  14724. if (this.castFile) {
  14725. try {
  14726. fs.closeSync(this.castFile);
  14727. this.castFile = undefined;
  14728. Logger.info('heanup endCasting', '关闭投播文件描述符');
  14729. } catch (error) {
  14730. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  14731. }
  14732. }
  14733. this.isCastPlaying = false;
  14734. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  14735. refToIsCasting?.set(false);
  14736. this.pause();
  14737. this.setIsPlaying(false);
  14738. // if (this.curIndex === this.curSource.index) {
  14739. // this.play
  14740. // this.seek(this.currentTime * 1000);
  14741. // this.setIsPlaying(true);
  14742. // } else {
  14743. // this.pauseVideo();
  14744. // this.setIsPlaying(false);
  14745. // }
  14746. }
  14747. public setIsPlaying(isPlayer: boolean) {
  14748. this.isPlaying = isPlayer;
  14749. // 发送播放状态变化事件给歌单详情页面
  14750. try {
  14751. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  14752. const currentFilePath = this.currentSong?.filePath || ''
  14753. const eventData: emitter.EventData = {
  14754. data: {
  14755. isPlaying: this.isPlaying,
  14756. curIndex: this.curIndex,
  14757. currentFilePath: currentFilePath
  14758. }
  14759. };
  14760. emitter.emit(eventPlaybackStatus, eventData)
  14761. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  14762. } catch (error) {
  14763. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  14764. }
  14765. }
  14766. private setPlaybackStateChangeListener(): void {
  14767. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  14768. // 我们需要通过其他方式来判断播放状态
  14769. // 1. 监听位置变化
  14770. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  14771. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  14772. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  14773. this.positionChange(playbackState.position.elapsedTime);
  14774. }
  14775. });
  14776. // 2. 监听时长变化
  14777. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  14778. const duration = playbackState?.extras?.duration;
  14779. if (typeof duration === 'number') {
  14780. this.playDurationChange(duration);
  14781. }
  14782. });
  14783. // 3. 监听所有状态变化(用于调试和状态判断)
  14784. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  14785. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  14786. // 检查是否有 state 字段(某些设备可能返回)
  14787. if (playbackState.state !== undefined) {
  14788. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  14789. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  14790. this.isCastPlaying = true;
  14791. }
  14792. }
  14793. });
  14794. // 4. 监听播放完成事件
  14795. this.castController?.on('endOfStream', this.playNextCallback);
  14796. this.castController?.on('playNext', this.playNextCallback);
  14797. this.castController?.on('playPrevious', this.playPreviousCallback);
  14798. // 5. 监听错误事件
  14799. this.castController?.on('error', (error: BusinessError) => {
  14800. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  14801. this.isCastPlaying = false;
  14802. });
  14803. }
  14804. private updateSessionPlayState(isPlay: boolean): void {
  14805. // if(!this.isBgPlayOpen)
  14806. // return
  14807. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  14808. : this.mIjkMediaPlayer.getCurrentPosition();
  14809. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  14810. this.setAVSessionPlayState({
  14811. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  14812. position: {
  14813. elapsedTime: elapsedTime,
  14814. updateTime: new Date().getTime()
  14815. }
  14816. });
  14817. }
  14818. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  14819. this.avSessionController.setAvSessionPlayState(playbackState)
  14820. }
  14821. private positionChange(position: number) {
  14822. this.currentTime2 = position / 1000;
  14823. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  14824. if (this.castControllerWrapper && this.isCastPlaying) {
  14825. this.updateCastProgress(position);
  14826. if (this.isSeekTo) {
  14827. this.isSeekTo = false;
  14828. }
  14829. }
  14830. }
  14831. private playDurationChange(duration: number) {
  14832. this.duration = duration;
  14833. this.durationTime = Math.floor(this.duration / 1000);
  14834. this.durationStringTime = secondToTime((this.durationTime));
  14835. if (this.castControllerWrapper && this.isCastPlaying) {
  14836. this.totalTime = this.stringForTime(this.duration);
  14837. }
  14838. }
  14839. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  14840. private reloadCasting = async () => {
  14841. Logger.info('heanup reloadCasting', '重新加载投播');
  14842. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  14843. this.initQueueItem();
  14844. await this.prepare();
  14845. };
  14846. public playNextCallback = (): void => {
  14847. this.playNext().catch(() => {
  14848. Logger.error('heanup playNextCallback', `播放下一首失败`);
  14849. });
  14850. };
  14851. public playPreviousCallback = (): void => {
  14852. this.playPrevious().catch(() => {
  14853. Logger.error('heanup playNextCallback', `播放上一首失败`);
  14854. });
  14855. };
  14856. async prepare() {
  14857. try {
  14858. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  14859. await this.castController?.prepare(this.castItem);
  14860. Logger.info('heanup prepare', '投播prepare成功');
  14861. await this.castController?.start(this.castItem);
  14862. Logger.info('heanup prepare', '投播start成功');
  14863. // 投播启动成功,设置为投播状态
  14864. this.isCastPlaying = true;
  14865. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  14866. } catch (error) {
  14867. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  14868. this.isCastPlaying = false;
  14869. }
  14870. }
  14871. public initQueueItem() {
  14872. let item = this.songList[this.curIndex];
  14873. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  14874. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  14875. let isStreaming = this.isUrl(this.videoUrl);
  14876. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  14877. // 关闭之前的文件描述符
  14878. if (this.castFile) {
  14879. try {
  14880. fs.closeSync(this.castFile);
  14881. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  14882. } catch (error) {
  14883. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  14884. }
  14885. }
  14886. let description: avSession.AVMediaDescription = {
  14887. assetId: 'AUDIO-' + item.filePath,
  14888. title: item.name,
  14889. artist: item.artist || '',
  14890. // 该字段大写,音频'AUDIO',视频'VIDEO'
  14891. mediaType: 'AUDIO',
  14892. mediaSize: item.videoSize,
  14893. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  14894. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  14895. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  14896. duration: this.duration,
  14897. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  14898. appName: this.appName,
  14899. lyricContent: item.lyricContent,
  14900. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  14901. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  14902. };
  14903. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  14904. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  14905. if (isStreaming) {
  14906. // 流媒体地址使用 mediaUri
  14907. description.mediaUri = this.videoUrl;
  14908. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  14909. } else {
  14910. // 本地文件使用 fdSrc
  14911. const localPath = this.videoUrl || item.filePath;
  14912. let uri = fileUri.getUriFromPath(localPath);
  14913. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  14914. let fdSrc: media.AVFileDescriptor = {
  14915. fd: this.castFile.fd
  14916. };
  14917. description.fdSrc = fdSrc;
  14918. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  14919. }
  14920. this.castItem = {
  14921. itemId: this.curIndex,
  14922. description: description
  14923. };
  14924. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  14925. title: description.title,
  14926. mediaType: description.mediaType,
  14927. hasMediaUri: !!description.mediaUri,
  14928. hasFdSrc: !!description.fdSrc,
  14929. duration: description.duration
  14930. })}`);
  14931. }
  14932. // 判断是否是 URL 或流媒体地址
  14933. private isUrl(str: string): boolean {
  14934. if (!str) {
  14935. return false;
  14936. }
  14937. // 检查常见的流媒体协议
  14938. if (str.startsWith('http://') || str.startsWith('https://') ||
  14939. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  14940. str.startsWith('rtp://') || str.startsWith('mms://')) {
  14941. return true;
  14942. }
  14943. // 扩展的URL正则表达式,支持多种协议
  14944. const urlPattern = new RegExp(
  14945. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  14946. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  14947. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  14948. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  14949. 'localhost)' + // 或localhost
  14950. '(\\:\\d+)?' + // 端口号(可选)
  14951. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  14952. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  14953. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  14954. 'i' // 不区分大小写
  14955. );
  14956. return urlPattern.test(str);
  14957. }
  14958. async stopCast() {
  14959. try {
  14960. // 使用 CastController 释放资源
  14961. if (this.castControllerWrapper) {
  14962. await this.castControllerWrapper.releaseAVCast();
  14963. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  14964. }
  14965. // 清空引用
  14966. this.castControllerWrapper = undefined;
  14967. this.castController = undefined;
  14968. this.castItem = undefined;
  14969. this.castFile = undefined;
  14970. } catch (error) {
  14971. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  14972. }
  14973. }
  14974. private sessionPlayCallback = (): void => {
  14975. this.playOrPause()
  14976. };
  14977. private sessionPauseCallback = (): void => {
  14978. this.pause()
  14979. };
  14980. private async playOrPause() {
  14981. if (!this.debounce()) {
  14982. return;
  14983. }
  14984. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  14985. await this.pause();
  14986. } else {
  14987. // 如果是投播模式,使用 CastController 的 play 方法
  14988. if (this.castControllerWrapper && this.isCastPlaying) {
  14989. try {
  14990. Logger.info('heanup playOrPause', '投播模式播放');
  14991. await this.castControllerWrapper.setPlaying();
  14992. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  14993. this.setIsPlaying(true);
  14994. this.updateSessionPlayState(true);
  14995. Logger.info('heanup playOrPause', '投播播放成功');
  14996. this.playChange();
  14997. } catch (error) {
  14998. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  14999. }
  15000. } else {
  15001. console.info('onecold startPlayOrResumePlay 11064')
  15002. this.startPlayOrResumePlay();
  15003. this.playChange()
  15004. }
  15005. }
  15006. }
  15007. private sessionPlayNextCallback = (): void => {
  15008. this.playNext().catch(() => {
  15009. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  15010. });
  15011. };
  15012. private sessionPlayPreviousCallback = (): void => {
  15013. this.playPrevious().catch(() => {
  15014. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  15015. });
  15016. };
  15017. private sessionStopCallback = (): void => {
  15018. this.stop()
  15019. };
  15020. private sessionFastForwardCallback = async (time?: number) => {
  15021. if (!time) {
  15022. return;
  15023. }
  15024. let curPosition: number;
  15025. if (this.castController && this.isCastPlaying) {
  15026. // 投播模式,使用UI显示的时间
  15027. curPosition = this.currentTime2 * 1000;
  15028. } else if (this.mIjkMediaPlayer != null) {
  15029. // 本地播放器模式
  15030. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15031. } else {
  15032. return;
  15033. }
  15034. let seeTime = curPosition + time * 1000;
  15035. // 限制 seekValue 在合法范围内
  15036. if (seeTime < 0) {
  15037. seeTime = 0;
  15038. } else if (seeTime > this.duration) {
  15039. seeTime = this.duration;
  15040. }
  15041. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  15042. this.setSeekToActionProgress(seeTime);
  15043. await this.seekTo(seeTime + "");
  15044. };
  15045. private getActiveDuration(): number {
  15046. let duration = this.mIjkMediaPlayer.getDuration();
  15047. if (this.castControllerWrapper && this.isCastPlaying) {
  15048. return this.duration > 0 ? this.duration : duration;
  15049. }
  15050. if (duration <= 0 && this.duration > 0) {
  15051. duration = this.duration;
  15052. }
  15053. return duration;
  15054. }
  15055. @Builder
  15056. InlineSpectrumView() {
  15057. SpectrumView({
  15058. isVisible: this.currentSwiperIndex === 0,
  15059. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  15060. })
  15061. .width( '83%')
  15062. .height(this.isCoverOpacity() ? 80 : 100)
  15063. .margin({bottom: 3 })
  15064. .clip(true)
  15065. }
  15066. private getSongDurationMs(song?: VideoItem): number {
  15067. if (!song || !song.duration) {
  15068. return 0;
  15069. }
  15070. const raw = song.duration.trim();
  15071. if (!raw) {
  15072. return 0;
  15073. }
  15074. const parts = raw.split(':').map((part) => Number(part));
  15075. if (parts.some((part) => Number.isNaN(part))) {
  15076. return 0;
  15077. }
  15078. let seconds = 0;
  15079. if (parts.length === 3) {
  15080. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  15081. } else if (parts.length === 2) {
  15082. seconds = parts[0] * 60 + parts[1];
  15083. } else if (parts.length === 1) {
  15084. seconds = parts[0];
  15085. }
  15086. return seconds > 0 ? seconds * 1000 : 0;
  15087. }
  15088. private updateCastProgress(position: number): void {
  15089. const duration = this.getActiveDuration();
  15090. if (duration <= 0) {
  15091. return;
  15092. }
  15093. this.slideEnable = true;
  15094. let pos = (position / duration) * 100;
  15095. if (pos > this.PROGRESS_MAX_VALUE) {
  15096. this.progressValue = this.PROGRESS_MAX_VALUE;
  15097. } else if (pos < 0) {
  15098. this.progressValue = 0;
  15099. } else {
  15100. this.progressValue = pos;
  15101. }
  15102. this.totalTime = this.stringForTime(duration);
  15103. if (position > duration) {
  15104. position = duration;
  15105. }
  15106. this.isCurrentTime = true;
  15107. this.currentTime = this.stringForTime(position);
  15108. this.isCurrentTime = false;
  15109. const lyricPosition = position + this.timeOffset * 1000;
  15110. this.updateLyricPosition(lyricPosition);
  15111. }
  15112. /**
  15113. * Gesture method onActionUpdate.
  15114. *
  15115. * @param event Gesture event.手势拖动设置快进和后退
  15116. */
  15117. private setSeekToActionProgress(position: number) {
  15118. // 投播模式使用this.duration,本地模式使用播放器获取
  15119. let duration = this.getActiveDuration();
  15120. let pos = 0;
  15121. if (duration > 0) {
  15122. this.slideEnable = true;
  15123. let curPercent = position / duration;
  15124. pos = curPercent * 100;
  15125. if (pos > this.PROGRESS_MAX_VALUE) {
  15126. this.progressValue = this.PROGRESS_MAX_VALUE
  15127. } else {
  15128. this.progressValue = pos;
  15129. }
  15130. }
  15131. // LogUtils.getInstance()
  15132. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  15133. this.totalTime = this.stringForTime(duration);
  15134. if (position > duration) {
  15135. position = duration;
  15136. }
  15137. this.isCurrentTime = true;
  15138. this.currentTime = this.stringForTime(position);
  15139. this.isCurrentTime = false
  15140. }
  15141. private sessionRewindCallback = async (time?: number) => {
  15142. if (!time) {
  15143. return;
  15144. }
  15145. let curPosition: number;
  15146. if (this.castController && this.isCastPlaying) {
  15147. // 投播模式,使用UI显示的时间
  15148. curPosition = this.currentTime2 * 1000;
  15149. } else if (this.mIjkMediaPlayer != null) {
  15150. // 本地播放器模式
  15151. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15152. } else {
  15153. return;
  15154. }
  15155. let seeTime = curPosition - time * 1000;
  15156. // 限制 seekValue 在合法范围内
  15157. if (seeTime < 0) {
  15158. seeTime = 0;
  15159. } else if (seeTime > this.duration) {
  15160. seeTime = this.duration;
  15161. }
  15162. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  15163. this.setSeekToActionProgress(seeTime);
  15164. await this.seekTo(seeTime + "");
  15165. };
  15166. private sessionSeekCallback = async (seekTime: number) => {
  15167. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  15168. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  15169. await this.seekTo(seekTime + "");
  15170. };
  15171. private async getFileSize(filePath: string): Promise<number> {
  15172. try {
  15173. const stat = await fs.stat(filePath);
  15174. return stat.size;
  15175. } catch (err) {
  15176. console.error('Failed to get file size: ' + err.message);
  15177. return 0;
  15178. }
  15179. }
  15180. private async pause() {
  15181. // 如果是投播模式,使用 CastController 的 pause 方法
  15182. if (this.castControllerWrapper && this.isCastPlaying) {
  15183. try {
  15184. Logger.info('heanup pause', '投播模式暂停');
  15185. await this.castControllerWrapper.setPause();
  15186. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  15187. this.setIsPlaying(false);
  15188. this.updateSessionPlayState(false);
  15189. Logger.info('heanup pause', '投播暂停成功');
  15190. } catch (error) {
  15191. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  15192. }
  15193. } else if (this.mIjkMediaPlayer.isPlaying()) {
  15194. // 本地播放器模式
  15195. this.savePlaybackPosition();
  15196. this.mIjkMediaPlayer.pause();
  15197. this.setProgress();
  15198. this.mDestroyPage = true;
  15199. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  15200. this.updateSessionPlayState(false)
  15201. this.playChange()
  15202. if (this.pipController) {
  15203. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15204. PiPWindow.PiPControlStatus.PAUSE);
  15205. }
  15206. }
  15207. }
  15208. private stop() {
  15209. this.clearInitialSeekGuardTimer();
  15210. this.waitInitialSeekBeforeStart = false;
  15211. this.pendingMemorySeekPosition = 0;
  15212. this.isPlayerLoading = false;
  15213. this.savePlaybackPosition();
  15214. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15215. this.mIjkMediaPlayer.stop();
  15216. this.mIjkMediaPlayer.release();
  15217. this.stopProgressTask();
  15218. this.updateSessionPlayState(false)
  15219. this.playChange()
  15220. this.watchStatus();
  15221. }
  15222. //保持记忆播放功能
  15223. private savePlaybackPosition() {
  15224. if (this.mIjkMediaPlayer != null) {
  15225. const position = this.mIjkMediaPlayer.getCurrentPosition();
  15226. // ToastUtil.showToast('保存记忆播放 = ' + position)
  15227. const duration = this.mIjkMediaPlayer.getDuration();
  15228. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  15229. // 如果播放位置接近视频末尾,则保存 position 为 0
  15230. const playbackPosition = (duration - position < threshold) ? 0 : position;
  15231. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  15232. PreferencesUtil.putSync(memoryKey, playbackPosition);
  15233. }
  15234. }
  15235. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  15236. if (song && isRemoteCloudType(song.type)) {
  15237. const accountId = song.webdav_account_id || 'unknown';
  15238. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  15239. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  15240. }
  15241. return playbackUrl || '';
  15242. }
  15243. private getPlaybackMemoryKey(): string {
  15244. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  15245. }
  15246. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  15247. if (token !== this.remoteRestoreSeekToken) {
  15248. return;
  15249. }
  15250. if (!this.mIjkMediaPlayer || position <= 0) {
  15251. if (this.waitInitialSeekBeforeStart) {
  15252. this.finishInitialSeekWait('invalid-memory-position', true);
  15253. }
  15254. return;
  15255. }
  15256. const duration = this.getActiveDuration();
  15257. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  15258. let safePosition = position;
  15259. if (duration > 0) {
  15260. safePosition = Math.max(0, Math.min(position, duration - 500));
  15261. } else {
  15262. safePosition = Math.max(0, position);
  15263. }
  15264. if (safePosition <= 0) {
  15265. if (this.waitInitialSeekBeforeStart) {
  15266. this.finishInitialSeekWait('memory-position-too-small', true);
  15267. }
  15268. return;
  15269. }
  15270. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  15271. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  15272. }
  15273. this.seekTo(safePosition + "");
  15274. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  15275. return;
  15276. }
  15277. setTimeout(() => {
  15278. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  15279. return;
  15280. }
  15281. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  15282. if (Math.abs(latestPos - safePosition) <= 1500) {
  15283. return;
  15284. }
  15285. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  15286. }, this.remoteMemorySeekRetryIntervalMs);
  15287. }
  15288. //获取记忆播放功能
  15289. private restorePlaybackPosition() {
  15290. const position: number = this.pendingMemorySeekPosition > 0 ?
  15291. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  15292. if (!this.mIjkMediaPlayer || position <= 0) {
  15293. if (this.waitInitialSeekBeforeStart) {
  15294. this.finishInitialSeekWait('no-memory-position', true);
  15295. }
  15296. return;
  15297. }
  15298. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  15299. if (isRemoteSong && this.videoUrl.includes('://')) {
  15300. const token = this.remoteRestoreSeekToken;
  15301. this.restoreRemotePlaybackPositionSafely(position, token);
  15302. return;
  15303. }
  15304. const duration = this.getActiveDuration();
  15305. let safePosition = position;
  15306. if (duration > 0) {
  15307. safePosition = Math.max(0, Math.min(position, duration - 500));
  15308. } else {
  15309. safePosition = Math.max(0, position);
  15310. }
  15311. if (safePosition <= 0) {
  15312. if (this.waitInitialSeekBeforeStart) {
  15313. this.finishInitialSeekWait('memory-position-too-small', true);
  15314. }
  15315. return;
  15316. }
  15317. this.seekTo(safePosition + "");
  15318. }
  15319. private async seekTo(value: string) {
  15320. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  15321. // ToastUtil.showToast('wma格式不支持拖动快进。')
  15322. // return
  15323. // }
  15324. // 如果是投播模式,使用 CastController 的 seek 方法
  15325. if (this.castControllerWrapper && this.isCastPlaying) {
  15326. try {
  15327. let seekPos = Number.parseInt(value);
  15328. const duration = this.getActiveDuration();
  15329. if (duration > 0) {
  15330. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  15331. }
  15332. this.isSeekTo = true;
  15333. Logger.info('heanup seekTo', `投播模式seek到: ${seekPos}ms, 当前时长: ${this.duration}ms`);
  15334. // 检查是否接近末尾
  15335. if (this.duration > 0 && seekPos >= this.duration - 500) {
  15336. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  15337. }
  15338. await this.castControllerWrapper.seek(seekPos);
  15339. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  15340. } catch (error) {
  15341. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  15342. }
  15343. } else {
  15344. // 本地播放器模式
  15345. let seekPos = Number.parseInt(value);
  15346. if (Number.isNaN(seekPos)) {
  15347. return;
  15348. }
  15349. const duration = this.getActiveDuration();
  15350. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  15351. if (duration > 0) {
  15352. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  15353. } else if (seekPos < 0) {
  15354. seekPos = 0;
  15355. }
  15356. if (isRemoteSong && duration <= 0) {
  15357. Logger.info(TAG, `seekTo 远程歌曲时长未知,直接尝试seek: ${seekPos}ms`);
  15358. }
  15359. this.isSeekTo = true
  15360. try {
  15361. this.mIjkMediaPlayer.seekTo(seekPos + "");
  15362. this.setProgress()
  15363. } catch (error) {
  15364. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  15365. } finally {
  15366. this.isSeekTo = false
  15367. }
  15368. }
  15369. }
  15370. // 添加到下一首播放
  15371. private addToNextPlay(song: VideoItem) {
  15372. if (!this.debounce()) {
  15373. return;
  15374. }
  15375. if (this.currentSong) {
  15376. if (this.currentSong === song) {
  15377. ToastUtil.showToast('当前已经在播放这首歌了!')
  15378. return
  15379. }
  15380. }
  15381. // 如果未开始播放或队列为空
  15382. if (this.curIndex === -1 || this.songList.length === 0) {
  15383. this.songList = [song];
  15384. this.curIndex = 0;
  15385. this.doPlay(song)
  15386. return;
  15387. }
  15388. // 插入到当前索引+1的位置
  15389. const insertPos = this.curIndex + 1;
  15390. this.songList.splice(insertPos, 0, song);
  15391. this.songList = [...this.songList]; // 触发状态更新
  15392. this.sonDataSource.pushArrayData(this.songList)
  15393. ToastUtil.showToast('已添加至下一首播放')
  15394. }
  15395. //后退10s,可再设置设置默认几秒
  15396. async backForward() {
  15397. // 如果是投播模式,从currentTime2获取当前位置
  15398. let pos: number;
  15399. if (this.castController && this.isCastPlaying) {
  15400. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  15401. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  15402. } else if (this.mIjkMediaPlayer) {
  15403. pos = this.mIjkMediaPlayer.getCurrentPosition();
  15404. } else {
  15405. return;
  15406. }
  15407. let value = pos - Number(this.fastForwardSeconds) * 1000;
  15408. if (value < 0) {
  15409. value = 0;
  15410. }
  15411. await this.seekTo(value + "");
  15412. }
  15413. //快进10s,可再设置设置默认几秒
  15414. async fastForward() {
  15415. // 如果是投播模式,从currentTime2获取当前位置
  15416. let pos: number;
  15417. if (this.castController && this.isCastPlaying) {
  15418. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  15419. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  15420. } else if (this.mIjkMediaPlayer) {
  15421. pos = this.mIjkMediaPlayer.getCurrentPosition();
  15422. } else {
  15423. return;
  15424. }
  15425. let value = pos + Number(this.fastForwardSeconds) * 1000;
  15426. // 限制不超过总时长
  15427. if (this.duration > 0 && value > this.duration) {
  15428. value = this.duration;
  15429. }
  15430. await this.seekTo(value + "");
  15431. }
  15432. //下一个
  15433. private async playNext() {
  15434. this.lyricController.setLyric(null)
  15435. this.lyricControllerXF.setLyric(null)
  15436. this.lyricControllerSingle.setLyric(null)
  15437. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  15438. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  15439. if (!this.debounce()) {
  15440. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  15441. return;
  15442. }
  15443. Logger.info('heanup playNext', `playType=${this.playType}`);
  15444. if (this.playType == 3) { //3:随机播放
  15445. Logger.info('heanup playNext', '随机播放模式');
  15446. await this.randomPlay()
  15447. return;
  15448. }
  15449. if (ArrayUtil.isNotEmpty(this.songList)) {
  15450. if (this.curIndex >= this.songList.length - 1) {
  15451. // playType=0 或 3: 尝试加载更多或循环
  15452. // playType=4: 不循环,检查是否是最后一首
  15453. if (this.playType == 4) {
  15454. // 连续播放不循环模式:到达最后一首时停止播放
  15455. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  15456. ToastUtil.showToast('已经是最后一首了');
  15457. this.showRePlay();
  15458. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  15459. this.progressValue = this.PROGRESS_MAX_VALUE;
  15460. this.slideEnable = false;
  15461. this.stop();
  15462. return;
  15463. }
  15464. await this.tryLoadNextPageForPlayback();
  15465. }
  15466. if (this.curIndex >= this.songList.length - 1) {
  15467. // playType=4 不应该执行到这里,因为上面已经return了
  15468. this.curIndex = 0;
  15469. } else {
  15470. this.curIndex++;
  15471. }
  15472. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  15473. this.currentSong = this.songList[this.curIndex];
  15474. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  15475. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  15476. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15477. context: this.context,
  15478. autoParseMusicName: this.autoParseMusicName
  15479. });
  15480. this.artist = this.songList[this.curIndex].artist
  15481. this.name = this.songList[this.curIndex].name
  15482. //this.cover = this.songList[this.curIndex].pixelMapPath
  15483. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  15484. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  15485. // 如果是投播模式,使用 CastController 播放下一首
  15486. if (this.castControllerWrapper) {
  15487. console.info('heanup playNext', '使用 CastController 播放下一首');
  15488. try {
  15489. const nextDuration = this.getSongDurationMs(this.currentSong);
  15490. if (nextDuration > 0) {
  15491. this.duration = nextDuration;
  15492. this.durationTime = Math.floor(nextDuration / 1000);
  15493. this.durationStringTime = secondToTime(this.durationTime);
  15494. this.totalTime = this.stringForTime(nextDuration);
  15495. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  15496. }
  15497. this.updateCastProgress(0);
  15498. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  15499. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  15500. console.info('heanup playNext', 'CastController 播放下一首成功');
  15501. return;
  15502. } catch (error) {
  15503. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  15504. // 如果投播失败,回退到本地播放
  15505. this.isCastPlaying = false;
  15506. }
  15507. }
  15508. // 本地播放器模式,需要先stop
  15509. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15510. this.stop();
  15511. this.changeImageAnimation()
  15512. }
  15513. }
  15514. changeImageAnimation() {
  15515. if(this.openSkipSongAnimate){
  15516. // 第一步:淡出动画
  15517. this.getUIContext()?.animateTo({
  15518. duration: 500,
  15519. curve: Curve.EaseOut,
  15520. }, () => {
  15521. this.opacityValueImage = 0.1;
  15522. if(this.isCoverRectangle){
  15523. this.scaleValueImage = 0.88
  15524. }
  15525. });
  15526. // 第二步:切换图片后淡入
  15527. setTimeout(() => {
  15528. this.cover = this.songList[this.curIndex].pixelMapPath
  15529. this.getUIContext()?.animateTo({
  15530. duration: 500,
  15531. curve: Curve.EaseIn,
  15532. }, () => {
  15533. this.opacityValueImage = 1;
  15534. this.scaleValueImage = 1 // 图标恢复到原始大小
  15535. this.startPlayOrResumePlay()
  15536. });
  15537. }, 500);
  15538. }else{
  15539. this.cover = this.songList[this.curIndex].pixelMapPath
  15540. this.startPlayOrResumePlay()
  15541. }
  15542. }
  15543. // 内部方法:提前缓存下一首
  15544. private async preloadNextSongInternal(): Promise<void> {
  15545. // 随机模式下传递已播放索引集合
  15546. if (this.playType === 3) {
  15547. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  15548. this.songList,
  15549. this.curIndex,
  15550. this.playType,
  15551. this.playedIndices
  15552. );
  15553. } else {
  15554. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  15555. this.songList,
  15556. this.curIndex,
  15557. this.playType
  15558. );
  15559. }
  15560. }
  15561. // 存储已播放的歌曲索引
  15562. private playedIndices: Set<number> = new Set();
  15563. // 存储已播放的本地歌曲路径(随机播放去重用)
  15564. private playedLocalFilePaths: Set<string> = new Set();
  15565. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  15566. private randomPlayHistory: VideoItem[] = [];
  15567. //随机播放
  15568. private async randomPlay() {
  15569. // if (!this.debounce()) {
  15570. // return;
  15571. // }
  15572. // 网盘模式: 渐进式扩展播放库的随机播放
  15573. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  15574. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  15575. if (isCloudSong) {
  15576. // 阈值常量
  15577. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  15578. const LOAD_MORE_PAGES = 3; // 每次加载页数
  15579. // 获取网盘播放列表
  15580. const navidromeList = getNavidromeVideoItems();
  15581. const webdavList = getWebdavVideoItems();
  15582. const isNavidrome = navidromeList.length > 0;
  15583. const remoteList = isNavidrome ? navidromeList : webdavList;
  15584. if (remoteList.length > 0) {
  15585. // 将当前歌加入历史栈
  15586. if (this.currentSong) {
  15587. this.randomPlayHistory.unshift(this.currentSong);
  15588. if (this.randomPlayHistory.length > 50) {
  15589. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  15590. }
  15591. // 标记当前歌曲为已播放
  15592. markAsPlayed(this.currentSong.filePath);
  15593. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  15594. }
  15595. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  15596. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  15597. const totalCount = remoteList.length;
  15598. const playedCount = isNavidrome ? getPlayedCount() : 0;
  15599. Logger.info(TAG, `randomPlay(网盘模式): 总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  15600. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  15601. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  15602. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  15603. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  15604. if (loadSuccess) {
  15605. // 重新获取未播放数量
  15606. unplayedCount = getUnplayedCount();
  15607. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  15608. }
  15609. }
  15610. // 从未播放歌曲中随机选择
  15611. let candidates: VideoItem[];
  15612. if (isNavidrome) {
  15613. candidates = getUnplayedSongs();
  15614. // 如果全部播放完,重置已播放记录
  15615. if (candidates.length === 0) {
  15616. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  15617. clearPlayedHistory();
  15618. // 排除当前歌曲
  15619. const currentFilePath = this.currentSong?.filePath;
  15620. candidates = currentFilePath
  15621. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  15622. : getNavidromeVideoItems();
  15623. }
  15624. } else {
  15625. // WebDAV模式:简单排除当前歌曲
  15626. const currentFilePath = this.currentSong?.filePath;
  15627. candidates = currentFilePath
  15628. ? remoteList.filter(v => v.filePath !== currentFilePath)
  15629. : remoteList;
  15630. }
  15631. if (candidates.length > 0) {
  15632. const randomIndex = Math.floor(Math.random() * candidates.length);
  15633. const randomSong = candidates[randomIndex];
  15634. // 标记为已播放
  15635. if (isNavidrome) {
  15636. markAsPlayed(randomSong.filePath);
  15637. }
  15638. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  15639. // 将选中的歌曲加入播放列表(如果不存在)
  15640. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  15641. if (nextIndex < 0) {
  15642. this.songList = [...this.songList, randomSong];
  15643. this.sonDataSource.pushArrayData(this.songList);
  15644. nextIndex = this.songList.length - 1;
  15645. }
  15646. this.curIndex = nextIndex;
  15647. this.playedIndices.add(this.curIndex);
  15648. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15649. this.stop();
  15650. this.currentSong = randomSong;
  15651. // 设置videoUrl
  15652. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15653. context: this.context,
  15654. autoParseMusicName: this.autoParseMusicName
  15655. });
  15656. this.name = this.currentSong.name;
  15657. this.artist = this.currentSong.artist;
  15658. this.changeImageAnimation();
  15659. return;
  15660. }
  15661. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  15662. }
  15663. }
  15664. if (this.currentSong) {
  15665. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  15666. this.randomPlayHistory.unshift(this.currentSong);
  15667. // 限制历史栈大小,避免无限增长
  15668. if (this.randomPlayHistory.length > 50) {
  15669. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  15670. }
  15671. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  15672. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  15673. const currentFilePath = this.currentSong.filePath;
  15674. if (isCurrentRemote) {
  15675. const remoteOptions: RandomSongQueryOptions = {
  15676. type: this.currentSong.type,
  15677. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  15678. };
  15679. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  15680. if (randomRemoteSong) {
  15681. // 验证并修正webdav_account_id
  15682. if (randomRemoteSong.webdav_account_id) {
  15683. const manager = RemoteDriveManager.getInstance();
  15684. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  15685. if (!account) {
  15686. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  15687. // 获取所有账号,查找相同类型的账号
  15688. const allAccounts = manager.getAllWebDavAccounts();
  15689. let foundAccount: WebDavAccount | null = null;
  15690. for (let i = 0; i < allAccounts.length; i++) {
  15691. if (allAccounts[i].webType === randomRemoteSong.type) {
  15692. foundAccount = allAccounts[i];
  15693. break;
  15694. }
  15695. }
  15696. if (foundAccount && foundAccount.id) {
  15697. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  15698. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  15699. // 更新数据库记录
  15700. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  15701. } else {
  15702. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  15703. return;
  15704. }
  15705. }
  15706. }
  15707. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  15708. if (nextIndex < 0) {
  15709. this.songList = [...this.songList, randomRemoteSong];
  15710. this.sonDataSource.pushArrayData(this.songList);
  15711. nextIndex = this.songList.length - 1;
  15712. }
  15713. this.curIndex = nextIndex;
  15714. this.playedIndices.add(this.curIndex);
  15715. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15716. this.stop();
  15717. this.currentSong = randomRemoteSong;
  15718. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  15719. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15720. context: this.context,
  15721. autoParseMusicName: this.autoParseMusicName
  15722. });
  15723. this.name = this.currentSong.name;
  15724. this.artist = this.currentSong.artist;
  15725. this.changeImageAnimation();
  15726. return;
  15727. }
  15728. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  15729. } else {
  15730. if (currentFilePath) {
  15731. this.playedLocalFilePaths.add(currentFilePath);
  15732. }
  15733. // 根据modeType构建不同的查询选项
  15734. const localOptions: RandomSongQueryOptions = {
  15735. type: CommonConstants.TYPE_LOCAL,
  15736. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  15737. };
  15738. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  15739. // modeType==0: 文件夹模式,添加parentPath过滤
  15740. if (this.modeType === 0 && this.currentPath) {
  15741. localOptions.parentPath = this.currentPath;
  15742. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  15743. }
  15744. // modeType==4: 歌单模式,添加playlistSongFilePaths
  15745. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  15746. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  15747. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  15748. } else if (this.modeType === 4) {
  15749. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  15750. }
  15751. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  15752. if (!randomLocalSong) {
  15753. this.playedLocalFilePaths.clear();
  15754. if (currentFilePath) {
  15755. this.playedLocalFilePaths.add(currentFilePath);
  15756. }
  15757. const fallbackLocalOptions: RandomSongQueryOptions = {
  15758. type: CommonConstants.TYPE_LOCAL,
  15759. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  15760. };
  15761. // fallback时也要保持modeType的过滤条件
  15762. if (this.modeType === 0 && this.currentPath) {
  15763. fallbackLocalOptions.parentPath = this.currentPath;
  15764. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  15765. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  15766. }
  15767. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  15768. }
  15769. if (randomLocalSong !== null) {
  15770. const selectedLocalSong = randomLocalSong;
  15771. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  15772. if (nextIndex < 0) {
  15773. this.songList = [...this.songList, selectedLocalSong];
  15774. this.sonDataSource.pushArrayData(this.songList);
  15775. nextIndex = this.songList.length - 1;
  15776. }
  15777. this.curIndex = nextIndex;
  15778. this.playedIndices.add(this.curIndex);
  15779. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15780. this.stop();
  15781. this.currentSong = selectedLocalSong;
  15782. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15783. context: this.context,
  15784. autoParseMusicName: this.autoParseMusicName
  15785. });
  15786. this.name = this.currentSong.name;
  15787. this.artist = this.currentSong.artist;
  15788. this.changeImageAnimation();
  15789. return;
  15790. }
  15791. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  15792. }
  15793. }
  15794. if (ArrayUtil.isNotEmpty(this.songList)) {
  15795. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  15796. this.playedIndices.add(this.curIndex);
  15797. }
  15798. if (this.songList.length > 3) {
  15799. // 优先使用预缓存的随机索引(仅网盘播放时)
  15800. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  15801. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  15802. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  15803. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  15804. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  15805. this.curIndex = this.preloadNextRandomIndex;
  15806. this.playedIndices.add(this.curIndex);
  15807. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  15808. // 立即预缓存下一首,避免下次点击时没有预缓存
  15809. void this.preloadNextSongInternal();
  15810. } else {
  15811. // 如果没有预缓存索引,则正常随机选择
  15812. // 如果所有歌曲都播放过一次,清空已播放索引集合
  15813. if (this.playedIndices.size === this.songList.length) {
  15814. this.playedIndices.clear();
  15815. }
  15816. // 随机选择一个未播放的歌曲索引
  15817. let newIndex: number;
  15818. // 添加超时机制防止无限循环
  15819. let attempt = 0;
  15820. const maxAttempts = 100; // 根据需求调整
  15821. do {
  15822. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  15823. attempt++;
  15824. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  15825. if (attempt >= maxAttempts) {
  15826. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  15827. newIndex = Math.floor(Math.random() * this.songList.length);
  15828. }
  15829. this.curIndex = newIndex;
  15830. this.playedIndices.add(newIndex);
  15831. }
  15832. } else {
  15833. // 当歌曲数量小于或等于3时,直接播放下一首
  15834. if (this.curIndex == this.songList.length - 1) {
  15835. this.curIndex = 0;
  15836. } else {
  15837. this.curIndex++;
  15838. }
  15839. }
  15840. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15841. this.stop();
  15842. this.currentSong = this.songList[this.curIndex];
  15843. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  15844. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15845. context: this.context,
  15846. autoParseMusicName: this.autoParseMusicName
  15847. });
  15848. this.name = this.songList[this.curIndex].name;
  15849. this.artist = this.songList[this.curIndex].artist
  15850. // this.cover = this.songList[this.curIndex].pixelMapPath
  15851. this.changeImageAnimation()
  15852. // 预缓存下一首(包括网盘和本地)
  15853. void this.preloadNextSongInternal();
  15854. }
  15855. }
  15856. private async playIndex(index: number) {
  15857. if (!this.debounce()) {
  15858. return;
  15859. }
  15860. if (ArrayUtil.isNotEmpty(this.songList)) {
  15861. this.curIndex = index;
  15862. this.currentSong = this.songList[index];
  15863. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  15864. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15865. context: this.context,
  15866. autoParseMusicName: this.autoParseMusicName
  15867. });
  15868. this.name = this.currentSong.name
  15869. this.artist = this.currentSong.artist
  15870. // 如果是投播模式,需要为投播设备准备当前歌曲
  15871. if (this.castController && this.isCastPlaying) {
  15872. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  15873. this.initQueueItem();
  15874. await this.prepare();
  15875. this.cover = this.currentSong.pixelMapPath;
  15876. return;
  15877. }
  15878. // 本地播放器模式,需要先stop
  15879. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15880. this.stop();
  15881. this.changeImageAnimation()
  15882. }
  15883. }
  15884. //上一个
  15885. private async playPrevious() {
  15886. if (!this.debounce()) {
  15887. return;
  15888. }
  15889. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  15890. this.randomModePlayFromHistory()
  15891. return;
  15892. }
  15893. if (this.curIndex == 0) {
  15894. this.curIndex = this.songList.length - 1;
  15895. } else {
  15896. this.curIndex--;
  15897. }
  15898. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  15899. this.currentSong = this.songList[this.curIndex];
  15900. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  15901. // 验证并修正webdav_account_id(针对远程类型歌曲)
  15902. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  15903. const manager = RemoteDriveManager.getInstance();
  15904. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  15905. if (!account) {
  15906. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  15907. // 获取所有账号,查找相同类型的账号
  15908. const allAccounts = manager.getAllWebDavAccounts();
  15909. let foundAccount: WebDavAccount | null = null;
  15910. for (let i = 0; i < allAccounts.length; i++) {
  15911. if (allAccounts[i].webType === this.currentSong.type) {
  15912. foundAccount = allAccounts[i];
  15913. break;
  15914. }
  15915. }
  15916. if (foundAccount && foundAccount.id) {
  15917. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  15918. this.currentSong.webdav_account_id = foundAccount.id.toString();
  15919. // 更新数据库记录
  15920. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  15921. } else {
  15922. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  15923. // 跳过无效账号的歌曲,继续查找上一首
  15924. if (this.curIndex == 0) {
  15925. this.curIndex = this.songList.length - 1;
  15926. } else {
  15927. this.curIndex--;
  15928. }
  15929. this.currentSong = this.songList[this.curIndex];
  15930. }
  15931. }
  15932. }
  15933. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  15934. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15935. context: this.context,
  15936. autoParseMusicName: this.autoParseMusicName
  15937. });
  15938. this.name = this.songList[this.curIndex].name
  15939. this.artist = this.songList[this.curIndex].artist
  15940. // 如果是投播模式,使用 CastController 切换上一首
  15941. if (this.castControllerWrapper) {
  15942. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  15943. try {
  15944. const prevDuration = this.getSongDurationMs(this.currentSong);
  15945. if (prevDuration > 0) {
  15946. this.duration = prevDuration;
  15947. this.durationTime = Math.floor(prevDuration / 1000);
  15948. this.durationStringTime = secondToTime(this.durationTime);
  15949. this.totalTime = this.stringForTime(prevDuration);
  15950. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  15951. }
  15952. this.updateCastProgress(0);
  15953. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  15954. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  15955. } catch (error) {
  15956. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  15957. this.isCastPlaying = false;
  15958. }
  15959. this.cover = this.songList[this.curIndex].pixelMapPath;
  15960. return;
  15961. }
  15962. // 本地播放器模式,需要先stop
  15963. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15964. this.stop();
  15965. this.changeImageAnimation()
  15966. }
  15967. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  15968. private async randomModePlayFromHistory() {
  15969. if (this.randomPlayHistory.length >= 1) {
  15970. // 播放历史栈的第一首(刚刚播放过的)
  15971. const prevSong = this.randomPlayHistory[0];
  15972. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  15973. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  15974. this.randomPlayHistory.shift();
  15975. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  15976. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15977. this.stop();
  15978. // 验证并修正webdav_account_id(针对远程类型歌曲)
  15979. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  15980. const manager = RemoteDriveManager.getInstance();
  15981. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  15982. if (!account) {
  15983. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  15984. const allAccounts = manager.getAllWebDavAccounts();
  15985. let foundAccount: WebDavAccount | null = null;
  15986. for (let i = 0; i < allAccounts.length; i++) {
  15987. if (allAccounts[i].webType === prevSong.type) {
  15988. foundAccount = allAccounts[i];
  15989. break;
  15990. }
  15991. }
  15992. if (foundAccount && foundAccount.id) {
  15993. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  15994. prevSong.webdav_account_id = foundAccount.id.toString();
  15995. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  15996. } else {
  15997. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  15998. // 无法播放这首歌,继续尝试下一首历史记录
  15999. if (this.randomPlayHistory.length >= 1) {
  16000. this.randomModePlayFromHistory();
  16001. return;
  16002. } else {
  16003. // 历史记录为空,无法继续
  16004. ToastUtil.showToast('没有更多历史记录');
  16005. return;
  16006. }
  16007. }
  16008. }
  16009. }
  16010. this.currentSong = prevSong;
  16011. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  16012. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  16013. context: this.context,
  16014. autoParseMusicName: this.autoParseMusicName
  16015. });
  16016. this.cover = this.currentSong.pixelMapPath
  16017. this.artist = this.currentSong.artist
  16018. this.name = this.currentSong.name;
  16019. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  16020. this.startPlayOrResumePlay();
  16021. } else {
  16022. ToastUtil.showToast('随机播放模式暂无历史记录');
  16023. }
  16024. }
  16025. debounce() {
  16026. const delay = 600;
  16027. let cur = new Date().getTime();
  16028. if (cur - this.last > delay) {
  16029. this.last = cur;
  16030. return true;
  16031. }
  16032. return false;
  16033. }
  16034. /**
  16035. * Sets whether the screen is a constant based on the playback status.
  16036. */
  16037. watchStatus() {
  16038. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  16039. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  16040. this.windowClass.setWindowKeepScreenOn(true);
  16041. } else {
  16042. this.windowClass.setWindowKeepScreenOn(false);
  16043. }
  16044. }
  16045. /**
  16046. * Volume gesture method onActionStart.
  16047. *
  16048. * @param event Gesture event.
  16049. */
  16050. private customDialogComponentIdMM: number = 0
  16051. @Builder
  16052. customDialogComponentMM() {
  16053. Column() {
  16054. Row() {
  16055. Blank()
  16056. Text('验证密码')
  16057. .fontSize(22)
  16058. .fontColor($r('app.color.pri_bg'))
  16059. .margin({ top: 18 })
  16060. Blank()
  16061. Image($r('app.media.close'))
  16062. .fillColor(Color.White)
  16063. .margin({ top: 18, right: 18 })
  16064. .width(20)
  16065. .onClick(() => {
  16066. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  16067. })
  16068. }
  16069. .width('100%') // 使Row占据整个宽度
  16070. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  16071. Verify({
  16072. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  16073. });
  16074. }.height('60%')
  16075. .backgroundColor($r('app.color.index_background'))
  16076. .justifyContent(FlexAlign.SpaceBetween)
  16077. }
  16078. private handleVerifyCompleted(isSuccess: boolean) {
  16079. if (isSuccess) {
  16080. console.log('验证成功');
  16081. // 在这里处理验证成功后的逻辑
  16082. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  16083. this.currentPath = this.lockPath
  16084. this.getSortedFiles(this.currentPath)
  16085. } else {
  16086. // console.log('验证失败');
  16087. ToastUtil.showToast('验证失败')
  16088. }
  16089. }
  16090. private showVerifyDialog() {
  16091. promptAction.openCustomDialog({
  16092. transition: TransitionEffect.asymmetric(
  16093. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  16094. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  16095. ,
  16096. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  16097. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  16098. ),
  16099. builder: () => {
  16100. this.customDialogComponentMM()
  16101. },
  16102. isModal: true,
  16103. autoCancel: true,
  16104. maskColor: Color.Transparent,
  16105. alignment: DialogAlignment.Bottom,
  16106. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  16107. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  16108. console.log("dialog onWillDismiss")
  16109. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  16110. dismissDialogAction.dismiss()
  16111. }
  16112. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  16113. dismissDialogAction.dismiss()
  16114. }
  16115. }
  16116. }).then((dialogId: number) => {
  16117. this.customDialogComponentIdMM = dialogId
  16118. })
  16119. }
  16120. //左滑操作 移动文件 重命名 删除等操作
  16121. @Builder
  16122. DeleteButton(item: VideoItem, index: number, filePath: string) {
  16123. Row() {
  16124. //加入收藏
  16125. Button() {
  16126. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  16127. .fillColor(Color.White)
  16128. .width(20)
  16129. }
  16130. .width(40)
  16131. .height(40)
  16132. .type(ButtonType.Circle)
  16133. .backgroundColor(this.themeColor)
  16134. .margin(5)
  16135. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16136. .onClick(() => {
  16137. if (item) {
  16138. this.doFav(item)
  16139. }
  16140. })
  16141. //加入下一首播放
  16142. Button() {
  16143. Image($r('app.media.next_to_play'))
  16144. .fillColor(Color.White)
  16145. .width(20)
  16146. }
  16147. .width(40)
  16148. .height(40)
  16149. .type(ButtonType.Circle)
  16150. .backgroundColor(this.themeColor)
  16151. .margin(5)
  16152. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16153. .onClick(() => {
  16154. this.addToNextPlay(item);
  16155. })
  16156. //复制文件
  16157. Button() {
  16158. Image($r('app.media.copy'))
  16159. .fillColor(Color.White)
  16160. .width(20)
  16161. }
  16162. .width(40)
  16163. .height(40)
  16164. .type(ButtonType.Circle)
  16165. .backgroundColor(this.themeColor)
  16166. .margin(5)
  16167. .id(filePath + 'copy')
  16168. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16169. .onClick(() => {
  16170. this.showCopyDialog(false, item, index, filePath + 'copy');
  16171. })
  16172. //移动文件
  16173. Button() {
  16174. Image($r('app.media.cut'))
  16175. .fillColor(Color.White)
  16176. .width(20)
  16177. }
  16178. .width(40)
  16179. .height(40)
  16180. .type(ButtonType.Circle)
  16181. .backgroundColor(this.themeColor)
  16182. .margin(5)
  16183. .id(filePath)
  16184. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16185. .onClick(() => {
  16186. this.showCutDialog(false, item, index, filePath);
  16187. })
  16188. Button() {
  16189. Image($r('app.media.cut_current'))
  16190. .fillColor(Color.White)
  16191. .width(20)
  16192. }
  16193. .width(40)
  16194. .height(40)
  16195. .type(ButtonType.Circle)
  16196. .backgroundColor(this.themeColor)
  16197. .margin(5)
  16198. .id(filePath + 'current')
  16199. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  16200. (this.isHasDir ? Visibility.Visible : Visibility.None))
  16201. .onClick(() => {
  16202. this.showCutDialog(true, item, index, filePath + 'current');
  16203. })
  16204. //重命名
  16205. Button() {
  16206. Image($r('app.media.rename2'))
  16207. .fillColor(Color.White)
  16208. .width(20)
  16209. }
  16210. .width(40)
  16211. .height(40)
  16212. .type(ButtonType.Circle)
  16213. .backgroundColor(this.themeColor)
  16214. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  16215. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  16216. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  16217. .margin(5)
  16218. .onClick(() => {
  16219. this.showReNameDialog(item, index + '', filePath)
  16220. })
  16221. Button() {
  16222. Image($r('app.media.delete2'))
  16223. .fillColor(Color.White)
  16224. .width(20)
  16225. }
  16226. .width(40)
  16227. .height(40)
  16228. .type(ButtonType.Circle)
  16229. .backgroundColor(this.themeColor)
  16230. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  16231. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  16232. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  16233. .margin(5)
  16234. .onClick(() => {
  16235. this.selectedFiles.push(item)
  16236. this.showWarnIsDelete()
  16237. // this.showWarnIsDeleteFile(item, index + '', filePath)
  16238. })
  16239. Button() {
  16240. Image($r('app.media.share2'))
  16241. .fillColor(Color.White)
  16242. .width(20)
  16243. }
  16244. .width(40)
  16245. .height(40)
  16246. .type(ButtonType.Circle)
  16247. .backgroundColor(this.themeColor)
  16248. .margin(5)
  16249. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16250. .onClick(() => {
  16251. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  16252. })
  16253. }
  16254. }
  16255. /**
  16256. * 穿山甲banner广告
  16257. */
  16258. // private declare bannerAd: CSJNativeExpressAd;
  16259. // @State private status: string = "未加载"
  16260. // @State private isShowAd: boolean = false
  16261. // private declare mAdSlot: AdSlot;
  16262. // private mBiddingAdm = '' //服务端bidding才需要设置
  16263. // private expressLoadAdListener: NativeExpressAdListener = {
  16264. // /**
  16265. // * 加载失败的回调
  16266. // *
  16267. // * @param code
  16268. // * @param message
  16269. // */
  16270. // onError: (code: number, message: string) => {
  16271. // console.error("加载广告失败,code=" + code + ",message=" + message);
  16272. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  16273. // },
  16274. //
  16275. // /**
  16276. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  16277. // *
  16278. // * @param ads 返回的广告列表
  16279. // */
  16280. //
  16281. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  16282. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  16283. // if (ads && ads.length > 0) {
  16284. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  16285. // ad.setExpressInteractionListener({
  16286. // /**
  16287. // *广告的点击回调
  16288. // * @param type 广告的交互类型
  16289. // */
  16290. // onAdClicked: (type: number) => {
  16291. // console.log("BannerExpressAdPage==onAdClicked......");
  16292. // },
  16293. //
  16294. // /**
  16295. // * 广告的展示回调 每个广告仅回调一次
  16296. // * @param type 广告的交互类型
  16297. // */
  16298. // onAdShow: (type: number) => {
  16299. // console.log("BannerExpressAdPage==onAdShow......");
  16300. // },
  16301. //
  16302. // /**
  16303. // * 模板渲染失败
  16304. // */
  16305. // onRenderFail: (code: number, msg: string) => {
  16306. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  16307. // },
  16308. //
  16309. // /**
  16310. // * 模板渲染成功
  16311. // * @param width 返回view的宽 单位 vp
  16312. // * @param height 返回view的高 单位 vp
  16313. // */
  16314. // onRenderSuccess: (width: number, height: number) => {
  16315. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  16316. // this.bannerAd = ad;
  16317. // this.status = "广告加载完成待展示";
  16318. //
  16319. // this.showBannerAd()
  16320. // }
  16321. // })
  16322. // //渲染广告
  16323. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  16324. // this.setDislikeCallback(ad); //设置dislike
  16325. // ad.render(this.getUIContext())
  16326. // this.status = "广告加载中...";
  16327. // });
  16328. // }
  16329. // }
  16330. // }
  16331. //
  16332. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  16333. // ad.setDislikeCallback({
  16334. // /**
  16335. // * dislike show
  16336. // */
  16337. // onShow: () => {
  16338. // console.log("BannerExpressAdPage==dislike......show");
  16339. // },
  16340. //
  16341. // /**
  16342. // * @param position 选择的位置
  16343. // * @param value 选择的内容
  16344. // * @param enforceRemove 是否强制关闭广告
  16345. // */
  16346. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  16347. // this.isShowAd = false;
  16348. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  16349. // ",enforce=" + enforceRemove);
  16350. // },
  16351. //
  16352. // /**
  16353. // * 点击取消
  16354. // */
  16355. // onCancel: () => {
  16356. // console.log("BannerExpressAdPage==dislike......onCancel");
  16357. // }
  16358. //
  16359. // })
  16360. // }
  16361. /**
  16362. * 加载Banner广告
  16363. */
  16364. loadBannerAd(rit: string) {
  16365. // if (Utility.isNoble()) {
  16366. // return
  16367. // }
  16368. // if (!Utility.isPassInstallTime(2)) {
  16369. // return
  16370. // }
  16371. // this.isShowAd = false;
  16372. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  16373. // this.mAdSlot = new AdSlotBuilder()
  16374. // .setCodeId(rit)
  16375. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  16376. // .setAdCount(1)
  16377. // .setBidAdm(this.mBiddingAdm)
  16378. // .build()
  16379. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  16380. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  16381. // this.status = "广告加载中..."
  16382. }
  16383. /**
  16384. * 展示Banner广告
  16385. */
  16386. // showBannerAd() {
  16387. // if (!this.bannerAd) {
  16388. // return
  16389. // }
  16390. // this.isShowAd = true
  16391. // this.status = "已展示"
  16392. // }
  16393. /**
  16394. * 穿山甲广告代码结束
  16395. */
  16396. /**
  16397. * 处理歌单播放请求
  16398. */
  16399. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  16400. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  16401. try {
  16402. const totalCount = songCount ?? songFilePaths.length;
  16403. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  16404. // 检查是否为WebDAV播放请求
  16405. if (playlistId === 'webdav-playlist') {
  16406. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  16407. // 从全局内存读取videoItems数据
  16408. const videoItems = getWebdavVideoItems();
  16409. const currentPlayIndex = getWebdavCurrentPlayIndex();
  16410. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  16411. if (videoItems && videoItems.length > 0) {
  16412. // 验证webdav_account_id设置情况
  16413. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  16414. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  16415. if(isJump){
  16416. this.setShowPlayTrue()//显示播放页
  16417. }
  16418. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  16419. return
  16420. } else {
  16421. return
  16422. }
  16423. }
  16424. if (playlistId === 'navidrome-playlist') {
  16425. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  16426. const videoItems = getNavidromeVideoItems();
  16427. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  16428. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  16429. if (videoItems && videoItems.length > 0) {
  16430. if(isJump){
  16431. this.setShowPlayTrue()//显示播放页
  16432. }
  16433. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  16434. return;
  16435. } else {
  16436. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  16437. return;
  16438. }
  16439. }
  16440. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  16441. const songMap: Map<number, VideoItem> = new Map()
  16442. let completedQueries = 0
  16443. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  16444. // 遍历所有文件路径,使用索引记录位置
  16445. for (let i = 0; i < songFilePaths.length; i++) {
  16446. const filePath = songFilePaths[i]
  16447. const index = i
  16448. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  16449. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  16450. const queryPromise = this.table.queryVideoByFilePath(filePath)
  16451. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  16452. queryPromise.then((videoItem) => {
  16453. completedQueries++
  16454. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  16455. if (videoItem) {
  16456. // 使用索引作为key保存到Map中,保持原始顺序
  16457. songMap.set(index, videoItem)
  16458. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  16459. } else {
  16460. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  16461. }
  16462. // 检查是否所有歌曲都已加载完成
  16463. if (completedQueries === songFilePaths.length) {
  16464. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  16465. // 按照索引顺序重建歌曲数组
  16466. const songs: VideoItem[] = []
  16467. for (let j = 0; j < songFilePaths.length; j++) {
  16468. const song = songMap.get(j)
  16469. if (song) {
  16470. songs.push(song)
  16471. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  16472. }
  16473. }
  16474. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  16475. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  16476. }
  16477. }).catch((error: Error) => {
  16478. completedQueries++
  16479. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  16480. // 即使出错也要检查是否完成所有查询
  16481. if (completedQueries === songFilePaths.length) {
  16482. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  16483. // 按照索引顺序重建歌曲数组
  16484. const songs: VideoItem[] = []
  16485. for (let j = 0; j < songFilePaths.length; j++) {
  16486. const song = songMap.get(j)
  16487. if (song) {
  16488. songs.push(song)
  16489. }
  16490. }
  16491. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  16492. }
  16493. })
  16494. }
  16495. } catch (error) {
  16496. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  16497. ToastUtil.showToast('播放失败')
  16498. }
  16499. }
  16500. /**
  16501. * 完成歌单加载并开始播放
  16502. */
  16503. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number) {
  16504. if (songs.length === 0) {
  16505. Logger.error('heanup 没有找到任何可播放的歌曲')
  16506. ToastUtil.showToast('没有找到可播放的歌曲')
  16507. return
  16508. }
  16509. this.songList = songs
  16510. this.currentSongList = songs // 同步更新 currentSongList
  16511. this.sonDataSource.pushArrayData(songs)
  16512. this.sonDataSource.notifyDataReload()
  16513. this.curIndex = startIndex
  16514. // 保存歌单的歌曲路径列表,用于随机播放
  16515. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  16516. const actualTotal = totalCount ?? songs.length;
  16517. // 如果是网盘播放,保存服务端总数到全局存储
  16518. if (totalCount && totalCount > 0 && songs.length > 0) {
  16519. const firstSong = songs[0];
  16520. if (firstSong && (isNavidromeType(firstSong.type) ||
  16521. isJellyfinType(firstSong.type) ||
  16522. isEmbyType(firstSong.type) ||
  16523. isAudioStationType(firstSong.type) ||
  16524. isPlexType(firstSong.type) ||
  16525. isDaoLiYuType(firstSong.type))) {
  16526. setNavidromeTotalCount(totalCount);
  16527. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  16528. }
  16529. }
  16530. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  16531. if (songs[startIndex]) {
  16532. // 确保当前播放的歌曲也更新到存储
  16533. AppStorage.setOrCreate('currentSong', songs[startIndex])
  16534. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  16535. this.doPlay(songs[startIndex], startIndex, true)
  16536. }
  16537. PreferencesUtil.putSync('LastMusicList', this.songList)
  16538. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  16539. }
  16540. }
  16541. //视频气泡窗口的布局
  16542. @Builder
  16543. function customPopupBuilder(dataBu: BubbleBean) {
  16544. List() {
  16545. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  16546. ListItem() {
  16547. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  16548. Row() {
  16549. Column() {
  16550. Image(dataBu.imageRes[index])
  16551. .height(28)
  16552. .fillColor(dataBu.color)
  16553. .alignSelf(ItemAlign.Center)
  16554. }
  16555. .width(32)
  16556. Text(item)
  16557. .padding({
  16558. top: 10,
  16559. bottom: 10,
  16560. right: 10,
  16561. left: 10
  16562. })
  16563. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  16564. .textAlign(TextAlign.Start)
  16565. .width("100%")
  16566. }
  16567. }
  16568. .backgroundColor($r('app.color.settings_background_main'))
  16569. .margin({ top: 6, bottom: 6 })
  16570. }
  16571. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  16572. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  16573. TransitionEffect.scale({ x: 0, y: 0 })))
  16574. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  16575. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  16576. .onClick(() => {
  16577. dataBu.onItemClick?.(index)
  16578. })
  16579. })
  16580. }
  16581. .scrollBar(BarState.Off)
  16582. .width(120)
  16583. .divider({
  16584. strokeWidth: 1,
  16585. color: "#22FFFFFF"
  16586. })
  16587. }
  16588. // Function to calculate a hash for the file list
  16589. function simpleHash(fileList: string[]): string {
  16590. let hash = 0;
  16591. const str = fileList.join(',');
  16592. for (let i = 0; i < str.length; i++) {
  16593. const char = str.charCodeAt(i);
  16594. hash = (hash << 5) - hash + char;
  16595. hash |= 0; // Convert to 32bit integer
  16596. }
  16597. return hash.toString();
  16598. }
  16599. interface MoreItem {
  16600. id: number;
  16601. image: Resource;
  16602. title: string;
  16603. }
  16604. //视频气泡窗口的布局
  16605. @Builder
  16606. function cutPopupBuilder(dataBu: BubbleBean) {
  16607. Column() {
  16608. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  16609. .padding({
  16610. top: 10,
  16611. bottom: 10,
  16612. right: 10,
  16613. left: 10
  16614. })
  16615. .textAlign(TextAlign.Start)
  16616. .width(160)
  16617. .fontWeight(666)
  16618. .fontSize(16)
  16619. List() {
  16620. ForEach(dataBu.data, (item: string, index: number) => {
  16621. ListItem() {
  16622. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  16623. Row() {
  16624. Column() {
  16625. Image($r('app.media.music_group'))
  16626. .height(28)
  16627. .fillColor(dataBu.color)
  16628. .alignSelf(ItemAlign.Center)
  16629. }
  16630. .width(32)
  16631. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  16632. .padding({
  16633. top: 10,
  16634. bottom: 10,
  16635. right: 10,
  16636. left: 10
  16637. })
  16638. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  16639. .fontSize(15)
  16640. }
  16641. }
  16642. .backgroundColor(Color.Transparent)
  16643. .margin({ top: 7, bottom: 7 })
  16644. }
  16645. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  16646. .animation({ duration: 500 }),
  16647. TransitionEffect.scale({ x: 0, y: 0 })))
  16648. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  16649. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  16650. .onClick(() => {
  16651. dataBu.onItemClick?.(index)
  16652. })
  16653. })
  16654. }
  16655. .scrollBar(BarState.Off)
  16656. .width(150)
  16657. .divider({
  16658. strokeWidth: 1,
  16659. color: "#22FFFFFF"
  16660. })
  16661. }
  16662. .height(300)
  16663. .padding({
  16664. bottom: 30
  16665. })
  16666. }
  16667. @Concurrent
  16668. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  16669. const alphabetSet = new Set<string>()
  16670. for (const item of items) {
  16671. let text = isShowFileName ? (item.fileName || '') :
  16672. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  16673. if (sortType === 0 || sortType == 1) {
  16674. text = item.artist || ''
  16675. } else if (sortType === 2 || sortType == 3) {
  16676. text = item.album || ''
  16677. }
  16678. if (text && text.length > 0) {
  16679. const first = getFirstLetter(text)
  16680. if (!alphabetSet.has(first)) {
  16681. alphabetSet.add(first)
  16682. }
  16683. }
  16684. }
  16685. const sorted = Array.from(alphabetSet).sort((a, b) => {
  16686. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  16687. return a.localeCompare(b)
  16688. }
  16689. return b.localeCompare(a)
  16690. })
  16691. return sorted
  16692. }
  16693. function getFileDirName(filePath: string,rootPath:string): string{
  16694. if(filePath===rootPath){
  16695. return '首页'
  16696. }
  16697. let result = FileUtil.getFileName(filePath)
  16698. if(StrUtil.isEmpty(result))
  16699. return ''
  16700. if(result.startsWith('.'))
  16701. result = result.replace(/\./g, '')
  16702. return result
  16703. }
  16704. //只扫描当前目录下文件(不扫描子文件夹)的方法
  16705. @Concurrent
  16706. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  16707. const table: MediaTable = new MediaTable(context);
  16708. try {
  16709. // 直接获取当前目录下的文件列表
  16710. const files = FileUtil.listFileSync(dirPath);
  16711. await Promise.all(files.map(async (file) => {
  16712. const fPath = `${dirPath}/${file}`;
  16713. // 跳过目录,只处理文件
  16714. if (FileUtil.isDirectory(fPath)) {
  16715. return;
  16716. }
  16717. // 跳过特定格式文件
  16718. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  16719. return;
  16720. }
  16721. // 检查是否为媒体文件
  16722. if (Utility.isMeidaByExtension(fPath)) {
  16723. let mType = CommonConstants.TYPE_LOCAL;
  16724. if (fPath.includes(lockPath)) {
  16725. mType = CommonConstants.TYPE_LOCK;
  16726. }
  16727. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  16728. context, fPath, mType, true
  16729. );
  16730. table.insert(mediaItem, (id: number) => {
  16731. // 插入回调函数
  16732. }, cover_api);
  16733. }
  16734. }));
  16735. } catch (error) {
  16736. console.error(' 扫描当前目录失败:', error);
  16737. }
  16738. }
  16739. //内嵌标签后更新库
  16740. @Concurrent
  16741. async function updateInfoDb(
  16742. context: Context,
  16743. filePath: string,
  16744. titleStr: string,
  16745. artistStr: string,
  16746. albumStr: string,
  16747. lyricConStr: string,
  16748. yearStr: string,
  16749. genreStr: string,
  16750. trackStr: string,
  16751. albumArtistStr: string,
  16752. composerStr: string,
  16753. lyricistStr: string,
  16754. commentStr: string,
  16755. discStr: string,
  16756. ): Promise<boolean> {
  16757. const table: MediaTable = new MediaTable(context);
  16758. await new Promise<void>((resolve, reject) => {
  16759. table.getRdbStore(context, (err:Error) => {
  16760. err ? reject(err) : resolve();
  16761. });
  16762. });
  16763. return await new Promise<boolean>((resolve) => {
  16764. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  16765. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  16766. (success: boolean, error?: string) => {
  16767. if (success) {
  16768. console.log("onecold 编辑信息成功,数据库已同步");
  16769. } else {
  16770. console.error("onecold 编辑信息数据库失败原因: " + error);
  16771. }
  16772. resolve(success);
  16773. });
  16774. });
  16775. }
  16776. @Concurrent
  16777. async function replaceLocalMusicCoverTask(
  16778. context: Context,
  16779. filePath: string,
  16780. sandboxCoverPath: string
  16781. ): Promise<boolean> {
  16782. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  16783. if (!coverResult) {
  16784. return false;
  16785. }
  16786. const table: MediaTable = new MediaTable(context);
  16787. await new Promise<void>((resolve, reject) => {
  16788. table.getRdbStore(context, (err: Error) => {
  16789. err ? reject(err) : resolve();
  16790. });
  16791. });
  16792. return await new Promise<boolean>((resolve) => {
  16793. table.updatePixelMapPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  16794. (success: boolean, _error?: string) => {
  16795. resolve(success);
  16796. });
  16797. });
  16798. }