LocalMusic.ets 765 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345
  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 { FindPlaylistMeta, getFindVideoItems, getFindCurrentPlayIndex, getFindPlaylistMeta } from '../common/util/FindPlaylistStore';
  18. import { triggerLoadMoreSongs, hasMoreData } from '../common/util/NavidromeRandomLoader';
  19. import {
  20. DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE,
  21. isFindLocalRandomPagedPlaylist
  22. } from '../common/util/LocalRandomPagedQueueHelper';
  23. import {
  24. ImplOnBufferingUpdateListener,
  25. ImplOnCompletionListener,
  26. ImplOnErrorListener,
  27. ImplOnInfoListener,
  28. ImplOnPreparedListener,
  29. ImplOnSeekCompleteListener,
  30. ImplOnTimedTextListener,
  31. ImplOnVideoSizeChangedListener
  32. } from '../common/IjkPlayerListenerImpls';
  33. import {
  34. ImageFancyModifier,
  35. } from '../common/util/AttributeModifierUtil'
  36. import {
  37. AppUtil,
  38. ArrayUtil,
  39. Base64Util,
  40. DateUtil,
  41. DeviceUtil,
  42. FileUtil,
  43. GlobalContext,
  44. LogUtil,
  45. MD5,
  46. PreferencesUtil,
  47. RandomUtil,
  48. StrUtil,
  49. ToastUtil
  50. } from '@pura/harmony-utils';
  51. import { imagePathToPixelMap } from '../common/util/CommUtils';
  52. import LyricUtil from '../common/util/LyricUtil';
  53. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  54. import { CommonConstants } from '../common/constants/CommonConstants';
  55. import { BaiduConstants } from '../common/constants/BaiduConstants';
  56. import { EventConstants } from '../common/constants/EventConstants';
  57. import Logger from '../common/util/Logger';
  58. import { filterPlaylistSongsByKeyword, findSongIndexByFilePath } from '../common/util/PlaylistSearchHelper';
  59. import { http } from '@kit.NetworkKit';
  60. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  61. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  62. import { BubbleBean } from '../viewmodel/BubbleBean';
  63. import { PopupPosition, XPopup } from '@chinalike/popup';
  64. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  65. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  66. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  67. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  68. import { Verify } from './Verify';
  69. import { taskpool } from '@kit.ArkTS';
  70. import { RotatingCover } from './RotatingCover';
  71. import { SpectrumView } from './spectrum/SpectrumView';
  72. import { PlayingIndicator } from './PlayingIndicator';
  73. import { PointLightButton } from './PointLight/PointLightButton';
  74. import { TitleBarPointLightButton } from './PointLight/TitleBarPointLightButton'
  75. import { PlayConstants } from '../common/constants/PlayConstants';
  76. import { effectKit } from '@kit.ArkGraphics2D';
  77. import { ColorConversion } from '../common/util/ColorConversion';
  78. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  79. import { AvSessionController } from '../controller/AvSessionController';
  80. import { EqualizerManager } from '../common/util/EqualizerManager';
  81. import { EqualizerViewWithCallback } from './EqualizerView';
  82. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  83. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  84. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  85. import { TagsContentCover } from '../view/TagsContentCover';
  86. import {
  87. DeviceChangeReason,
  88. IjkMediaPlayer,
  89. InterruptEvent,
  90. InterruptHintType,
  91. LogUtils,
  92. OnBufferingUpdateListener,
  93. OnCompletionListener,
  94. OnErrorListener,
  95. OnInfoListener,
  96. OnPreparedListener,
  97. OnSeekCompleteListener,
  98. OnTimedTextListener,
  99. OnVideoSizeChangedListener
  100. } from '@ohos/ijkplayer';
  101. import { PlayStatus } from '../common/PlayStatus';
  102. import fs from '@ohos.file.fs';
  103. import { image } from '@kit.ImageKit';
  104. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  105. import { media } from '@kit.MediaKit';
  106. import { UniversalDetector } from '@ohos/juniversalchardet';
  107. import { SettingPage } from '../pages/SettingPage';
  108. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  109. import { CommonConstants2 } from '../common/util/CommonConstants2';
  110. import { hilog } from '@kit.PerformanceAnalysisKit';
  111. import { LazyDataSource } from '../common/util/LazyDataSource';
  112. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  113. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  114. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  115. import { ringtone } from '@kit.RingtoneKit';
  116. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  117. import { resourceManager } from '@kit.LocalizationKit';
  118. import { deviceInfo } from '@kit.BasicServicesKit';
  119. import '../common/network/RemoteCacheRegistry';
  120. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  121. import { lyricService, SongData } from '../common/service/LyricService';
  122. import { shouldResolveRemoteLyricOnPlay, tryResolveRemotePlaybackLyric } from '../common/util/RemotePlaybackLyricUtil';
  123. import { resolvePlayerDismissMorphTarget } from '../common/util/PlayerDismissHelper';
  124. import { isBaiduStreamingPlaybackUrl, resolveSeekGuardDecision } from '../common/util/PlaybackSeekGuard';
  125. import {
  126. cloneVideoItem,
  127. preloadNextSongIfNeeded,
  128. setVideoUrlForSong,
  129. getTypeOrder,
  130. isWebDavType,
  131. isSmbType,
  132. isNavidromeType,
  133. isFtpType,
  134. isBaiduType,
  135. isJellyfinType,
  136. isEmbyType,
  137. isAudioStationType,
  138. isPlexType,
  139. isRemoteCloudType,
  140. mergeCoverWithPriority,
  141. WorkerEditMusicResult,
  142. WebDavMetadataUpdatePayload,
  143. isDaoLiYuType
  144. } from '../common/util/RemotePlayerUtil';
  145. import {
  146. PlaylistPlayRequest,
  147. consumePendingPlaylistPlay,
  148. clearPendingPlaylistPlay
  149. } from '../common/util/PlaylistPlayRequestStore';
  150. import { resolvePlaylistDisplayCount } from '../common/util/PlaylistPlayDispatchHelper'
  151. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  152. import app from '@system.app';
  153. import { TextNodeController } from './PipLyricTextBuilder';
  154. import { IndexerView } from './IndexerView';
  155. import { KeyCode } from '@kit.InputKit';
  156. import { KnockController } from '../controller/KnockController';
  157. import { DeleteComptent } from '../view/DeleteComptent';
  158. import { ABLoopComptent } from '../view/ABLoopComptent';
  159. import { FixMessyView } from '../view/FixMessyView';
  160. import {
  161. parseCueFile,
  162. CueTrack,
  163. CueInfo,
  164. getCueTrackDuration,
  165. getCueTrackEndOffset,
  166. getCueTrackStartOffset,
  167. importCueTracks,
  168. isCueSplitItem
  169. } from '../common/util/CueUtils';
  170. import { CueComptent } from '../view/CueComptent';
  171. import { SearchHistoryUtil } from '../common/util/SearchHistoryUtil';
  172. import { IsoExtractComptent } from '../view/IsoExtractComptent';
  173. import PlaylistTable from '../common/util/PlaylistTable';
  174. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  175. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  176. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  177. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  178. import { Song } from '../viewmodel/Song';
  179. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  180. import { SongType } from '../common/enums/SongType';
  181. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  182. buildHttpHeadersWithWebDav,
  183. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  184. import PermissionUtil from '../common/util/PermissionUtil'
  185. import { EditAudio, setRingTone } from './EditAudio';
  186. import { ExtractAccompaniment } from './ExtractAccompaniment';
  187. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  188. import { AudioFormatConverter } from './AudioFormatConverter';
  189. import { MergeAudio } from './MergeAudio';
  190. import { AIVoiceSeparation } from './AIVoiceSeparation';
  191. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  192. import { ChangeTone } from './ChangeTone';
  193. import {
  194. hdsEffect,
  195. HdsVisualComponent,
  196. HdsSceneController,
  197. HdsSceneType,
  198. HdsVisualComponentAttribute,
  199. } from '@kit.UIDesignKit';
  200. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  201. import { getFirstLetter } from '../Constants';
  202. import { audio } from '@kit.AudioKit';
  203. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  204. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  205. import { LyricCopySheet } from './LyricCopySheet';
  206. import {
  207. IsoArchiveAudioEntry,
  208. IsoExtractFailureDetail,
  209. IsoExtractProgressMessage,
  210. IsoExtractTaskResult,
  211. listIsoAudioEntriesTask,
  212. extractIsoAudioEntriesTask
  213. } from '../common/util/IsoArchiveUtil';
  214. const TAG = 'LocalMusic';
  215. const HICAR_LOG_TAG = 'HiCarWindow';
  216. const PREF_PLAY_COVER_SCALE_GUIDE_SHOWN = 'play_cover_scale_guide_show';
  217. function logHiCarWindow(message: string): void {
  218. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  219. }
  220. export interface WorkerMetadataPayload {
  221. originFilePath: string;
  222. originId?: string;
  223. bit_rate?: string;
  224. duration?: string;
  225. sampleRate?: string;
  226. mimeType?: string;
  227. md5Str?: string;
  228. videoSize?: number;
  229. size?: string;
  230. pixelMapPath?: string;
  231. artist?: string;
  232. album?: string;
  233. name?: string;
  234. lyricContent?: string;
  235. bits_per_raw_sample?: string;
  236. channels?: string;
  237. channel_layout?: string;
  238. start_time?: string;
  239. genre?: string;
  240. year?: string;
  241. probe_score?: number;
  242. track?: string;
  243. disc?: string;
  244. ALBUMARTIST?: string;
  245. COMPOSER?: string;
  246. COMMENT?: string;
  247. LYRICIST?: string;
  248. nb_streams?: number;
  249. nb_programs?: number;
  250. error?: string;
  251. }
  252. interface WorkerMessageScanDone {
  253. code: 101;
  254. data: Record<string, never>;
  255. }
  256. interface WorkerMessageMediaList {
  257. code: 102;
  258. data: Array<VideoItem>;
  259. totalCount: number;
  260. }
  261. interface WorkerMessageArtistList {
  262. code: 103;
  263. data1: Map<string, Array<VideoItem>>;
  264. data2: Array<VideoItem>;
  265. totalCount: number;
  266. }
  267. interface WorkerMessageAlbumList {
  268. code: 104;
  269. data1: Map<string, Array<VideoItem>>;
  270. data2: Array<VideoItem>;
  271. totalCount: number;
  272. }
  273. interface WorkerMessageMetadata {
  274. code: 105;
  275. data: WorkerMetadataPayload;
  276. }
  277. interface WorkerMessageEditResult {
  278. code: 106;
  279. data: WorkerEditMusicResult;
  280. }
  281. interface AlphaTaskItem {
  282. type: number;
  283. name?: string;
  284. pyStr?: string;
  285. fileName?: string;
  286. artist?: string;
  287. album?: string;
  288. }
  289. type LocalMusicWorkerMessage =
  290. WorkerMessageScanDone
  291. | WorkerMessageMediaList
  292. | WorkerMessageArtistList
  293. | WorkerMessageAlbumList
  294. | WorkerMessageMetadata
  295. | WorkerMessageEditResult;
  296. const DEFAULT_INDEX =
  297. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  298. 'X', 'Y', 'Z']
  299. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  300. // 元数据提取状态追踪
  301. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  302. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  303. // 定义接口
  304. interface HiCarAspectRatio {
  305. ratio: number;
  306. name: string;
  307. }
  308. interface GeneratedObjectLiteralInterface_1 {
  309. assetId: string;
  310. title: string;
  311. artist: string;
  312. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  313. mediaUri: string;
  314. // 该字段大写,音频'AUDIO',视频'VIDEO'
  315. mediaType: string;
  316. mediaSize: number;
  317. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  318. startPosition: number;
  319. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  320. duration: number;
  321. albumCoverUri: string;
  322. albumTitle: string;
  323. appName: string;
  324. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  325. drmScheme: string;
  326. }
  327. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  328. const ITEM_HEIGHT: number = 65; // 列表项中高度
  329. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  330. /**
  331. * 排序模式枚举
  332. * 定义各种排序方式的升序基准值
  333. */
  334. export enum SortMode {
  335. ByArtist = 0, // 按艺术家升序
  336. ByAlbum = 2, // 按专辑升序
  337. ByName = 4, // 按名称升序
  338. ByTime = 6, // 按时间升序
  339. ByAddTime = 7, // 按添加时间(只有降序)
  340. ByCount = 8, // 按数量升序
  341. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  342. }
  343. //功能强大的音乐播放器
  344. @Preview
  345. @Component
  346. export struct LocalMusic {
  347. @State default_layout:number = 0
  348. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  349. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  350. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  351. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  352. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  353. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  354. private audioRoutingManager?: audio.AudioRoutingManager
  355. private outputDeviceChangeCallback?: Callback<audio.DeviceChangeAction>
  356. private audioInterruptResumePending: boolean = false
  357. @State showFindLocation: boolean = true
  358. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  359. @State showSimple: boolean = true//开启沉浸模式
  360. @State isPaging: boolean = true;//是否分页加载机制
  361. @State isCoverRectangle: boolean = true;
  362. @State showZMIndex: boolean = false //是否右侧显示字母索引
  363. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  364. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  365. // 字母表
  366. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  367. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  368. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  369. @State selectAlphaBetIndex: number = 0
  370. @State isShowAlphaBet: boolean = false
  371. @State isScrolling: boolean = false
  372. @State isTouchingAlphaBet: boolean = false
  373. @State alphabetHeight: number = 0
  374. public enableShowAlphabet: boolean = true // 是否显示字母表
  375. private alphaBetHideTimer: number = 0
  376. private alphaBetRebuildTimer: number = 0
  377. private alphaBetDirty: boolean = false
  378. private alphaBetCacheKey: string = ''
  379. private alphaBetBuildVersion: number = 0
  380. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  381. //背景两侧流光控制器
  382. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  383. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  384. new HdsSceneController()
  385. .setSceneParams({
  386. backgroundMaskColors: [Color.Green, Color.Red],
  387. firstEdgeFlowLight: {
  388. startPos: 0,
  389. endPos: 0.5,
  390. color: Color.Red
  391. },
  392. secondEdgeFlowLight: {
  393. startPos: 0,
  394. endPos: -0.5,
  395. color: Color.Green
  396. }
  397. }) : undefined;
  398. //背景流光控制器
  399. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  400. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  401. new hdsEffect.ShaderEffectController():undefined;
  402. @State showAddSheet:boolean = false
  403. private loadingDialogId: string = ''
  404. private loadingProgressDialogId: string = ''
  405. @State isoAudioEntries: IsoArchiveAudioEntry[] = []
  406. @State selectedIsoAudioPaths: string[] = []
  407. @State isoSourceFileName: string = ''
  408. @State isIsoExtracting: boolean = false
  409. @State isoExtractProgress: number = 0
  410. @State isoExtractProgressText: string = ''
  411. @State isoExtractCurrentEntryName: string = ''
  412. private isoSourceFilePath: string = ''
  413. private isoExtractDestinationDir: string = ''
  414. private isoComponentId: number = 0
  415. private isoExtractProgressTimer: number = 0
  416. private isoExtractExpectedOutputPaths: Array<string> = []
  417. private isoExtractTotalBytes: number = 0
  418. private isoExtractDisplayedProgress: number = 0
  419. private isoExtractReceivedTaskProgress: boolean = false
  420. private isoExtractTask: taskpool.Task | undefined = undefined
  421. private isoExtractLastActivityTime: number = 0
  422. private readonly isoExtractStallTimeoutMs: number = 15000
  423. private isoExtractCanceled: boolean = false
  424. private isoExtractCancelMessage: string = ''
  425. searchController: SearchController = new SearchController()
  426. @State rightTopImage:Resource = $r('sys.symbol.sort')
  427. @State isEditAudio:boolean = false
  428. @State isExtractAcc:boolean = false
  429. @State isConverter:boolean = false
  430. @State isAIVoiceSeparation:boolean = false
  431. @State isExtractAudio:boolean = false
  432. @State isMergeAudio:boolean = false
  433. @State isCopyFileToDownLoad: boolean = false
  434. @State isChangeTone:boolean = false
  435. @State offHeight: number = 75
  436. @State currentSongList: Array<VideoItem> = []//当前歌单
  437. @Consume currentSongListName:string //当前歌单名称
  438. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  439. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  440. @State isRefreshing: boolean = false;
  441. @State maxRefreshingHeight: number = 100.0;
  442. @State isPlayerLoading: boolean = false; // 播放器加载状态
  443. private contentNode?: ComponentContent<Object> = undefined;
  444. private skipNextPlaylistPersist: boolean = false
  445. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  446. @State ratioL: number = 1;
  447. @State mediaKuCount: number = 0;
  448. @State albumCount: number = 0;
  449. @State artistCount: number = 0;
  450. @State fastForwardSeconds: string = '10'
  451. @State isShowBackFast: boolean = true//快进快退按钮
  452. @State isCanAuto:boolean = true
  453. @State opacityValueImage: number = 1;
  454. @State tipPopup:boolean = false
  455. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  456. @Consume mType: number;
  457. @StorageProp('themeColor') themeColor: string =
  458. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  459. themeMode: number = 0;
  460. @State titleName: string = '文件夹'//首页就是文件夹
  461. @State textStr: string = ''
  462. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  463. // private download_path: string = '';
  464. @Consume rootPath: string //音频根目录
  465. @Consume currentPath: string
  466. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  467. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  468. @State lockPath: string = ''
  469. @State favPath: string = ''
  470. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  471. @State historyPath: string = ''
  472. @State historyList: Array<VideoItem> = []
  473. @Consume isHistory: boolean
  474. static readonly HISTORY_MUSIC: string = 'music_historyList';
  475. private table: MediaTable = new MediaTable(getContext(this))
  476. private playlistTable: PlaylistTable | null = null
  477. private deletionWatcher: FileDeletionWatcher | null = null
  478. @State allPlaylists: Playlist[] = []
  479. @State isZero: boolean = false
  480. @State fileList: Array<string> = []
  481. @State dirList: Array<VideoItem> = []
  482. @Consume videoLocalList:VideoItem[]
  483. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  484. @State listRefreshKey: number = 0
  485. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  486. @State artistList: Array<VideoItem> = []; //艺术家文件
  487. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  488. @State artistSongCountMap: Map<string, number> = new Map();
  489. @State albumList: Array<VideoItem> = []; //专辑文件
  490. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  491. @State albumSongCountMap: Map<string, number> = new Map();
  492. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  493. @State imageOpacities: number[] = [];
  494. @Consume isCanBack: boolean
  495. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  496. @State showSingleLyric: boolean = false
  497. @State sortType: number = 4 //默认排序方式
  498. @State isShowSimi: boolean = false //是否显示私密音频
  499. @State isShowFAV: boolean = true //是否显示我的收藏
  500. @State isShowTitleBar: boolean = true //是否显示分类导航条
  501. @State isShowAllBar: boolean = true //是否显示播放全部条
  502. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  503. @State isEnableWordByWordLyric: boolean = true //是否开启逐字歌词
  504. @State isShowHistory: boolean = true //是否显示最近播放
  505. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  506. @State isHomeBgFollowMusicCover: boolean = true //主页背景随当前播放封面
  507. @State isGridMusic: boolean = false //是否网格布局
  508. @State isCircleBtn: boolean = false //是否圆形播放按钮
  509. @State twoFingerType: number = 3 //双支放大缩小的类型
  510. @State isScrollHide: boolean = false //是否滚动隐藏
  511. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  512. @State isStartAutoPlay: boolean = false //启动后自动播放
  513. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  514. @State isShowHeader: boolean = true
  515. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  516. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  517. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  518. @State rectangleCoverScale: number = 1
  519. @State rectangleCoverPinchValue: number = 1
  520. @State isSwipe: boolean = false //listItem的左滑开关
  521. @State openSkipSongAnimate: boolean = true//切歌动画效果
  522. @State isPlayPageSwipeNext: boolean = true // 播放页上滑切歌
  523. @State isLightText: boolean = true //是否开启歌词发光
  524. @State customizeBgPath: string | undefined = '';
  525. @StorageProp('customizeMusicBgPath') customizeMusicBgPath: string = '';
  526. @State isDarkMode: boolean = false
  527. @State lyricTextWeight: number = 400
  528. @State lyricTextWeightPip: number = 400
  529. @State currentSwiperIndex: number = 0
  530. @State blurValue: number = 0 //背景模糊
  531. @State bgBrightness: number = 0 //背景亮度
  532. private listScroller: ListScroller = new ListScroller()
  533. private playListScroller: Scroller = new Scroller()
  534. @State isOneKeyTags:boolean = false
  535. @State isFixMessy:boolean = false
  536. // 分页相关状态
  537. @State private currentPage: number = 0 // 当前页码
  538. @State private pageSize: number = 53 // 每页数量
  539. @State private totalCount: number = 0 // 总记录数
  540. @State private hasMoreData: boolean = true // 是否还有更多数据
  541. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  542. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  543. private pageHasMoreCache: Map<number, boolean> = new Map()
  544. private pageTotalCountCache: Map<number, number> = new Map()
  545. private prefetchingPages: Set<number> = new Set()
  546. private preloadStartRatio: number = 0.18
  547. private appendStartRatio: number = 0.30
  548. private earlyAppendReserveCount: number = 28
  549. private lastScrollTriggerPage: number = -1
  550. private lastVisibleEndIndex: number = -1
  551. private isPagingTransition: boolean = false
  552. private pagingScheduleTimer: number = 0
  553. private listScrollAlphaCheckAt: number = 0
  554. private listScrollPagingCheckAt: number = 0
  555. private listScrollLastAlphaStart: number = -1
  556. private listScrollLastPagingEnd: number = -1
  557. private gridScrollPagingCheckAt: number = 0
  558. private gridScrollLastPagingEnd: number = -1
  559. private waterScrollPagingCheckAt: number = 0
  560. private waterScrollLastPagingEnd: number = -1
  561. private gridWaterScrollIdleTimer: number = 0
  562. private gridWaterLastActiveTs: number = 0
  563. private listUpdateTimer: number = 0
  564. private listUpdateVersion: number = 0
  565. private detailBackTransitioning: boolean = false
  566. private mediaLibraryEnterTs: number = 0
  567. private mediaLibraryWarmupPrefetchTimer: number = 0
  568. private listVisibleStart: number = -1
  569. private listVisibleEnd: number = -1
  570. private listThumbWarmupCheckAt: number = 0
  571. private listThumbWarmupStart: number = -1
  572. private listThumbWarmupEnd: number = -1
  573. private gridThumbWarmupCheckAt: number = 0
  574. private gridThumbWarmupStart: number = -1
  575. private gridThumbWarmupEnd: number = -1
  576. private waterThumbWarmupCheckAt: number = 0
  577. private waterThumbWarmupStart: number = -1
  578. private waterThumbWarmupEnd: number = -1
  579. private gridVisibleStart: number = -1
  580. private gridVisibleEnd: number = -1
  581. private waterVisibleStart: number = -1
  582. private waterVisibleEnd: number = -1
  583. private titleBarToggleMinDelta: number = 12
  584. private titleBarLastCheckTs: number = 0
  585. @State private coverThumbVersion: number = 0
  586. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  587. private coverThumbCacheReady: boolean = false
  588. private pendingCoverThumbRefresh: boolean = false
  589. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' | 'find_paged_local' = 'view'
  590. private isHydratingPlayList: boolean = false
  591. private preserveExistingQueueOnNextPlay: boolean = false
  592. private nextPlayQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' | 'find_paged_local' = 'view'
  593. private findPagedLocalQueuePageIndex: number = 0
  594. private findPagedLocalQueuePageSize: number = DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE
  595. private findPagedLocalQueueTotalCount: number = 0
  596. private findPagedLocalQueueHasMore: boolean = false
  597. private findPagedLocalQueueSortType: number = 4
  598. private isLoadingFindPagedLocalQueue: boolean = false
  599. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  600. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  601. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  602. @StorageProp('windowWidth') windowWidth: number = 0;
  603. @StorageProp('windowHeight') windowHeight: number = 0;
  604. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  605. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  606. private UNKONWN:string = '';
  607. private listArea: Area = {
  608. width: 0,
  609. height: 0,
  610. position: {},
  611. globalPosition: {}
  612. }
  613. @State private pointLightOptions: hdsEffect.PointLightOptions | undefined = undefined
  614. @State private activePointLightItemKey: string = ''
  615. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  616. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  617. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  618. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  619. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  620. private activePlaybackMemoryKey: string = '';
  621. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  622. private remoteRestoreSeekToken: number = 0;
  623. // 本次是否需要先seek到记忆点再开始播放
  624. private waitInitialSeekBeforeStart: boolean = false;
  625. // 本次播放记忆点(毫秒)
  626. private pendingMemorySeekPosition: number = 0;
  627. // 记忆播放seek兜底,避免一直转圈
  628. private initialSeekGuardTimer: number = 0;
  629. private readonly initialSeekGuardTimeoutMs: number = 2000;
  630. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  631. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  632. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  633. private lastSeekRequestMs: number = -1;
  634. private lastSeekSource: string = '';
  635. private seekTraceUntilTs: number = 0;
  636. private lastSeekTraceLogTs: number = 0;
  637. private readonly seekTraceLogWindowMs: number = 4000;
  638. private readonly seekTraceLogIntervalMs: number = 400;
  639. //瀑布流的列数横竖屏动态切换
  640. onIsLandscapeChange() {
  641. if(this.isLandscape){
  642. this.columns = 4
  643. }else{
  644. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  645. }
  646. }
  647. onColorModeChange() {
  648. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  649. }
  650. //点击某个歌单id发生变化的时候回调
  651. onIDChange(){
  652. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  653. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  654. if(this.modeType==4){
  655. this.titleName = this.currentSongListName
  656. this.rightTopImage = $r('sys.symbol.sort')
  657. //获取缓存
  658. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  659. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  660. if(StrUtil.isNotEmpty(cacheSongs)){
  661. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  662. this.updateListData(this.currentSongList, true)
  663. }
  664. this.doSongListTask()//获取歌单信息
  665. }
  666. }
  667. async doSongListTask() {
  668. // 初始化歌单数据库
  669. const playlistTable = new PlaylistTable(this.context);
  670. // 查询歌单中的所有歌曲
  671. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  672. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  673. if (ArrayUtil.isEmpty(playlistSongs)) {
  674. this.updateListData([], true)
  675. // 清空歌单路径列表
  676. this.currentPlaylistSongFilePaths = [];
  677. } else {
  678. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  679. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  680. this.updateListData(this.currentSongList, true)
  681. // 保存歌单的歌曲路径列表,用于随机播放
  682. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  683. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  684. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  685. // 只保存前100条记录到缓存中
  686. let canceList = this.currentSongList.slice(0, 100);
  687. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  688. JSON.stringify(canceList))
  689. } else {
  690. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  691. }
  692. }
  693. this.isRefreshing = false
  694. }
  695. async onModeChange(preserveList: boolean = false): Promise<void> {
  696. this.isFavMusic = false
  697. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  698. this.refreshDirVisibilitySettings()
  699. if (this.mediaLibraryWarmupPrefetchTimer) {
  700. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  701. this.mediaLibraryWarmupPrefetchTimer = 0
  702. }
  703. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  704. switch (this.modeType) {
  705. case 0:
  706. // 首页模式已在 resetAndLoadFirstPage 中处理
  707. // 切换模式时加载对应的排序类型
  708. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  709. this.sortType = this.loadSortTypeForCurrentMode()
  710. this.mediaLibraryEnterTs = 0
  711. break
  712. case 1:
  713. this.rightTopImage = $r('sys.symbol.sort')
  714. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  715. // 切换模式时加载对应的排序类型
  716. this.sortType = this.loadSortTypeForCurrentMode()
  717. this.mediaLibraryEnterTs = Date.now()
  718. break
  719. case 2:
  720. this.rightTopImage = $r('sys.symbol.sort')
  721. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  722. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  723. this.sortType = this.loadSortTypeForCurrentMode()
  724. this.mediaLibraryEnterTs = 0
  725. break
  726. case 3:
  727. this.rightTopImage = $r('sys.symbol.sort')
  728. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  729. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  730. this.sortType = this.loadSortTypeForCurrentMode()
  731. this.mediaLibraryEnterTs = 0
  732. break
  733. }
  734. // 模式切换时重置分页状态并加载第一页
  735. await this.resetAndLoadFirstPage(!preserveList);
  736. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  737. }
  738. // @Consume currentSong: VideoItem | undefined;
  739. @StorageLink('currentSong') @Watch('onHomeBgCurrentSongChange') currentSong: VideoItem | undefined = undefined;
  740. // @StorageLink('isPlay') isPlay: boolean = false;
  741. @Consume isShowPlay: boolean ;
  742. @State isShowCoverScaleGuide: boolean = false
  743. @StorageLink('songList') songList: Array<VideoItem> = [];
  744. @State translateY: number = 0;
  745. @State playDismissScale: number = 1;
  746. @State playDismissScaleY: number = 1;
  747. @State playDismissOpacity: number = 1;
  748. @State playDismissTranslateX: number = 0;
  749. @State playDismissBorderRadius: number = 0;
  750. @State playDismissProxySize: number = 0;
  751. @State playDismissProxyOpacity: number = 0;
  752. @State isShowSheet: boolean = false;
  753. @State isShowSheetView: boolean = false;
  754. @State isShowLyricCopySheet: boolean = false;
  755. @State lyricCopyLines: string[] = [];
  756. @State lyricSelectedIndexes: number[] = [];
  757. @State isShowTimeCloseView: boolean = false;
  758. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  759. private playDismissTimer: number = -1;
  760. private readonly playDismissContentDuration: number = 260;
  761. private readonly playDismissDotDuration: number = 160;
  762. private playOpenFromMiniBarPending: boolean = false;
  763. private playOpenTimer: number = -1;
  764. private readonly playOpenDotDuration: number = 120;
  765. private readonly playOpenExpandDuration: number = 320;
  766. @StorageLink('currIndex') curIndex: number = 0;
  767. @Consume isShowDrawer: boolean;
  768. @Consume offsetX: number;
  769. @State isFac: boolean = false;
  770. @State favList: Array<VideoItem> = []
  771. @Consume isFavMusic: boolean
  772. @State isClickedPLayAll: boolean = false;
  773. private scrollerForlist: ListScroller = new ListScroller();
  774. private knockController: KnockController | undefined = undefined;
  775. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  776. // 缓存机制
  777. private cache: Map<string, Array<VideoItem>> = new Map();
  778. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  779. // 持久化缓存
  780. private async saveCacheToStorage() {
  781. const cacheArray = Array.from(this.cache.entries());
  782. const stringCacheArray = Array.from(this.stringCache.entries());
  783. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  784. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  785. }
  786. // 载入缓存
  787. private async loadCacheFromStorage() {
  788. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  789. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  790. if (cacheString) {
  791. const parsedCache: Object | null = JSON.parse(cacheString);
  792. if (parsedCache && Array.isArray(parsedCache)) {
  793. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  794. this.cache = new Map(cacheArray);
  795. }
  796. }
  797. if (stringCacheString) {
  798. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  799. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  800. const stringCacheArray: [string, string][] = parsedStringCache;
  801. this.stringCache = new Map(stringCacheArray);
  802. }
  803. }
  804. }
  805. // 查找缓存
  806. private findCache(key: string): Array<VideoItem> | undefined {
  807. return this.cache.get(key);
  808. }
  809. // 查找字符串缓存
  810. private findStringCache(key: string): string | undefined {
  811. return this.stringCache.get(key);
  812. }
  813. // 添加缓存
  814. private addCache(key: string, value: Array<VideoItem>) {
  815. this.cache.set(key, value);
  816. }
  817. // 添加字符串缓存
  818. private addStringCache(key: string, value: string) {
  819. this.stringCache.set(key, value);
  820. }
  821. // 删除缓存
  822. private deleteCache(key: string) {
  823. this.cache.delete(key);
  824. this.saveCacheToStorage()
  825. }
  826. // 删除字符串缓存
  827. private deleteStringCache(key: string) {
  828. this.stringCache.delete(key);
  829. }
  830. // 多选机制
  831. @State selectedFiles: Array<VideoItem> = [];
  832. @Consume isMultiSelect: boolean;
  833. @State isAllSelected: boolean = false;
  834. @State appName: string = ''
  835. @State isHasDir: boolean = false
  836. @State packName: string = ''
  837. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  838. doSwipBack() {
  839. if(this.isSearchMode){
  840. console.info('onecold doSwipBack = ' +this.isSearchMode)
  841. this.isSearchMode = false
  842. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  843. this.searchText = ''
  844. this.getSortedFiles(this.currentPath)
  845. return
  846. }
  847. this.onSearchInput('')
  848. return
  849. }
  850. this.isZero = false
  851. if (this.modeType !== 0 && this.isCanBack) {
  852. if (this.detailBackTransitioning) {
  853. return
  854. }
  855. this.detailBackTransitioning = true
  856. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  857. this.isCanBack = false
  858. this.rightTopImage = $r('sys.symbol.sort')
  859. if (this.modeType == 2) {
  860. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  861. if (ArrayUtil.isNotEmpty(this.artistList)) {
  862. this.updateListData(this.artistList, true, true)
  863. }
  864. } else if (this.modeType == 3) {
  865. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  866. if (ArrayUtil.isNotEmpty(this.albumList)) {
  867. this.updateListData(this.albumList, true, true)
  868. }
  869. }
  870. // 返回列表页时保留当前列表,避免先清空导致闪现
  871. void this.onModeChange(true).then(() => {
  872. if (this.modeType == 2) {
  873. if (this.isGridMusic||this.twoFingerType==4) {
  874. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  875. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  876. if(this.twoFingerType==4){
  877. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  878. }else{
  879. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  880. }
  881. } else {
  882. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  883. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  884. }
  885. } else if (this.modeType == 3) {
  886. if (this.isGridMusic||this.twoFingerType==4) {
  887. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  888. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  889. if(this.twoFingerType==4){
  890. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  891. }else{
  892. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  893. }
  894. } else {
  895. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  896. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  897. }
  898. }
  899. this.detailBackTransitioning = false
  900. }).catch((error: Error) => {
  901. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  902. this.detailBackTransitioning = false
  903. })
  904. return
  905. }
  906. this.mediaLibraryEnterTs = 0
  907. if (this.isHistory || this.isFavMusic) {
  908. this.isHistory = false
  909. this.getSortedFiles(this.currentPath)
  910. return
  911. }
  912. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  913. animateTo({ duration: 555 }, () => {
  914. // 动画闭包内控制Image组件的出现和消失
  915. this.isShowDrawer = !this.isShowDrawer
  916. this.offsetX = 0
  917. })
  918. return
  919. }
  920. //返回上一级歌单的滚动位置
  921. setTimeout(() => {
  922. if (this.modeType == 0) {
  923. if (this.isGridMusic||this.twoFingerType==4) {
  924. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  925. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  926. if(this.twoFingerType==4){
  927. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  928. }else{
  929. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  930. }
  931. } else {
  932. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  933. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  934. }
  935. }
  936. }, 100)
  937. this.currentPath = Utility.getParentDirectory(this.currentPath)
  938. Logger.info('this.currentPath2 = ' + this.currentPath)
  939. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  940. }
  941. private triggerSwipeBackWithAnimation(): void {
  942. animateTo({ duration: 555 }, () => {
  943. this.doSwipBack()
  944. })
  945. }
  946. // 组件生命周期
  947. aboutToAppear() {
  948. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  949. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  950. this.updateListData(this.videoLocalList)
  951. }
  952. // 初始化 PlaylistTable
  953. this.playlistTable = new PlaylistTable(getContext(this))
  954. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  955. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  956. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  957. this.tipPopup = !this.tipPopup
  958. PreferencesUtil.putSync('isFirstTiped',false)
  959. }
  960. this.loadSearchHistory()
  961. this.initSetting()
  962. this.syncEqualizerUi();
  963. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  964. Utility.getAppName(getContext(this)).then((appName: string) => {
  965. this.appName = appName
  966. })
  967. this.packName = AppUtil.getBundleName()
  968. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  969. this.loadCacheFromStorage(); // 加载文件夹缓存
  970. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  971. this.initLoadCache()
  972. this.mkDownLoadDir()
  973. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  974. // 监听广播事件(打开其他应用处理)
  975. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  976. this.saveVideoDatas([eventData.data?.message], true)
  977. });
  978. //侧滑广播接收时间
  979. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  980. // 监听广播事件(手势返回处理)
  981. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  982. this.triggerSwipeBackWithAnimation()
  983. });
  984. //ScanFilePage广播接收时间
  985. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  986. // 监听ScanFilePage广播事件(更新数据库)
  987. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  988. this.doUpdateData()
  989. });
  990. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  991. emitter.on(eventEqualizerChanged, () => {
  992. this.syncEqualizerUi();
  993. if (this.mIjkMediaPlayer) {
  994. const equalizerManager = EqualizerManager.getInstance();
  995. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  996. this.markEqualizerApplied();
  997. }
  998. });
  999. // 监听歌单播放请求事件
  1000. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  1001. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  1002. const data = eventData.data as Record<string, Object>
  1003. if (!data) {
  1004. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  1005. return
  1006. }
  1007. // 检查歌单播放数据结构
  1008. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  1009. const playlistData = new PlaylistPlayRequest(
  1010. data.playlistId as string,
  1011. data.playlistName as string,
  1012. data.songCount as number,
  1013. data.startIndex as number,
  1014. data.songFilePaths as string[],
  1015. data.isJump as boolean,
  1016. data.playType as number
  1017. )
  1018. await this.dispatchPlaylistPlayRequest(playlistData)
  1019. return
  1020. }
  1021. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1022. });
  1023. Promise.resolve().then(async (): Promise<void> => {
  1024. const pendingPlaylistRequest = consumePendingPlaylistPlay();
  1025. if (!pendingPlaylistRequest) {
  1026. return;
  1027. }
  1028. Logger.info(TAG,
  1029. `检测到待处理播放请求,准备补偿执行: ${pendingPlaylistRequest.playlistName}, startIndex=${pendingPlaylistRequest.startIndex}`);
  1030. await this.dispatchPlaylistPlayRequest(pendingPlaylistRequest);
  1031. });
  1032. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1033. // 监听广播事件(通用设置配置更新)
  1034. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1035. if(this.modeType ==4){
  1036. this.doSongListTask()//获取歌单信息
  1037. }
  1038. });
  1039. let eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  1040. emitter.on(eventQueueRefresh, () => {
  1041. this.syncWebdavQueueWithoutRestart();
  1042. });
  1043. let eventOpenLocalSpecialList: emitter.InnerEvent = { eventId: EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST }
  1044. emitter.on(eventOpenLocalSpecialList, (eventData: emitter.EventData) => {
  1045. const data = eventData.data as Record<string, Object>
  1046. const target = data?.target as string
  1047. this.openSpecialLocalList(target)
  1048. });
  1049. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1050. // 监听广播事件(通用设置配置更新)
  1051. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1052. this.initSetting()
  1053. });
  1054. // 监听 WebDAV 元数据更新事件
  1055. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  1056. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  1057. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  1058. if (!payloads || payloads.length === 0) {
  1059. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  1060. return;
  1061. }
  1062. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  1063. // 处理每个元数据更新
  1064. for (let i = 0; i < payloads.length; i++) {
  1065. const payload = payloads[i];
  1066. if (!payload || !payload.filePath) {
  1067. continue;
  1068. }
  1069. // 重要:只更新当前正在播放的歌曲
  1070. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  1071. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  1072. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  1073. if (payload.name && payload.name.length > 0) {
  1074. this.name = payload.name;
  1075. if (this.currentSong) {
  1076. this.currentSong.name = payload.name;
  1077. }
  1078. }
  1079. if (payload.artist && payload.artist.length > 0) {
  1080. this.artist = payload.artist;
  1081. if (this.currentSong) {
  1082. this.currentSong.artist = payload.artist;
  1083. }
  1084. }
  1085. if (this.currentSong) {
  1086. const coverMutated = mergeCoverWithPriority(this.currentSong, payload.pixelMapPath,
  1087. payload.isCustomCover ?? 0);
  1088. if (coverMutated && this.currentSong.pixelMapPath) {
  1089. this.cover = this.currentSong.pixelMapPath;
  1090. Logger.info(TAG, `LocalMusic: 封面已更新: ${this.currentSong.pixelMapPath}`);
  1091. }
  1092. if (payload.md5Str && payload.md5Str.length > 0) {
  1093. this.currentSong.md5Str = payload.md5Str;
  1094. }
  1095. }
  1096. // 同步更新 AppStorage
  1097. AppStorage.setOrCreate('currentSong', this.currentSong);
  1098. } else {
  1099. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  1100. }
  1101. }
  1102. });
  1103. // 监听广播事件(通用设置配置更新)
  1104. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1105. this.doChangeSetting()
  1106. });
  1107. this.mIjkMediaPlayer.on('audioInterrupt', (event: InterruptEvent) => {
  1108. this.handleAudioInterrupt(event)
  1109. });
  1110. this.mIjkMediaPlayer.on('deviceChange', (event: InterruptEvent) => {
  1111. this.handlePlayerDeviceChange(event)
  1112. });
  1113. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1114. // 监听广播事件(hicar断开暂停播放)
  1115. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1116. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1117. this.audioInterruptResumePending = false
  1118. this.pause();
  1119. });
  1120. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1121. this.audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1122. this.outputDeviceChangeCallback = (deviceChanged: audio.DeviceChangeAction) => {
  1123. this.handleOutputDeviceChange(deviceChanged)
  1124. }
  1125. this.audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, this.outputDeviceChangeCallback);
  1126. this.makeWorker()
  1127. //折叠屏的屏幕显示模式变化
  1128. display.on('foldDisplayModeChange', (data) => {
  1129. this.doChangeBarHeight()
  1130. });
  1131. display.on('foldStatusChange', (data) => {
  1132. Logger.info('onecold foldStatusChange ')
  1133. });
  1134. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1135. this.rectangleCoverScale = PreferencesUtil.getNumberSync(SettingPage.RECTANGLE_COVER_SCALE, 1)
  1136. if (this.rectangleCoverScale < 0.7 || this.rectangleCoverScale > 1.4) {
  1137. this.rectangleCoverScale = 1
  1138. }
  1139. // 读取 themeMode 并同步 currentColorMode
  1140. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1141. this.applyThemeMode(this.themeMode)
  1142. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1143. AppStorage.setOrCreate('themeColor', themeColor);
  1144. this.themeColor = themeColor;
  1145. this.doChangeSetting()
  1146. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1147. LogUtil.info('onecold windowSizeChange')
  1148. this.doChangeBarHeight()
  1149. let viewWidth = px2vp(size.width);
  1150. let viewHeight = px2vp(size.height);
  1151. if(this.isPhoneLan()){
  1152. this.is_auto_hide_progress = false
  1153. if(this.isHiCar()){
  1154. return
  1155. }
  1156. setTimeout(() => {
  1157. this.is_auto_hide_progress = true
  1158. }, 6000)
  1159. }else{
  1160. this.startAutoHide()
  1161. }
  1162. });
  1163. this.eventHub.on('onStateChange', (fg: boolean) => {
  1164. this.isAppForeground = fg;
  1165. if (fg && this.curState === 'STARTED') {
  1166. this.stopPip();
  1167. this.syncLyricPositionNow();
  1168. }
  1169. });
  1170. //NewIndex的博空调收到eventHub消息控制播放
  1171. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1172. if (ArrayUtil.isNotEmpty(this.songList)) {
  1173. this.playOrPause();
  1174. } else {
  1175. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1176. }
  1177. });
  1178. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1179. if (ArrayUtil.isNotEmpty(this.songList)) {
  1180. this.playPrevious();
  1181. } else {
  1182. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1183. }
  1184. });
  1185. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1186. if (ArrayUtil.isNotEmpty(this.songList)) {
  1187. this.playNext();
  1188. } else {
  1189. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1190. }
  1191. });
  1192. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1193. if (!this.isShowPlay) {
  1194. this.setShowPlayTrue()
  1195. }
  1196. this.showPlayerView();
  1197. });
  1198. this.getUIContext().getHostContext()!.eventHub.on('openPlayerViewFromMiniBar', () => {
  1199. if (ArrayUtil.isEmpty(this.songList)) {
  1200. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  1201. return
  1202. }
  1203. this.setShowPlayTrue()
  1204. this.showPlayerView();
  1205. });
  1206. this.getUIContext().getHostContext()!.eventHub.on('dismissPlayerView', () => {
  1207. this.setShowPlayFalse()
  1208. });
  1209. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1210. this.openPlayList();
  1211. });
  1212. }
  1213. //载入媒体库,艺术家,专辑等缓存
  1214. initLoadCache(){
  1215. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1216. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1217. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1218. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1219. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1220. if(ArrayUtil.isNotEmpty(cachedList)){
  1221. this.mediaKuList = cachedList
  1222. if(this.modeType==1){
  1223. this.updateListData(this.mediaKuList)
  1224. }
  1225. }
  1226. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1227. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1228. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1229. this.artistList = artistCachedList
  1230. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1231. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1232. this.artistMap = new Map(parsedArray);
  1233. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1234. if(this.modeType==2){
  1235. this.updateListData(this.artistList)
  1236. }
  1237. }
  1238. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1239. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1240. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1241. this.albumList = albumCachedList
  1242. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1243. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1244. this.albumMap = new Map(parsedArray);
  1245. if(this.modeType==3){
  1246. this.updateListData(this.albumList)
  1247. }
  1248. }
  1249. }
  1250. startAutoHide() {
  1251. if(this.isHiCar()){
  1252. return
  1253. }
  1254. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1255. console.info('onecold startAutoHide')
  1256. this.is_auto_hide_progress = false
  1257. setTimeout(() => {
  1258. this.is_auto_hide_progress = true
  1259. }, 6000)
  1260. }
  1261. }
  1262. applyThemeMode(mode: number) {
  1263. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1264. if (mode === 1) {
  1265. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1266. } else if (mode === 2) {
  1267. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1268. }
  1269. AppStorage.setOrCreate('currentColorMode', colorMode)
  1270. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1271. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1272. AppStorage.setOrCreate('themeMode', mode)
  1273. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1274. // 只有强制浅色/深色时才主动设置
  1275. const context = getContext(this) as common.UIAbilityContext
  1276. context.getApplicationContext().setColorMode(colorMode)
  1277. }
  1278. private isAudioPlaybackActive(): boolean {
  1279. return this.CONTROL_PlayStatus === PlayStatus.PLAY
  1280. || this.mIjkMediaPlayer.isPlaying()
  1281. || (!!this.castControllerWrapper && this.isCastPlaying)
  1282. }
  1283. private isBluetoothOutputDeviceType(deviceType: audio.DeviceType): boolean {
  1284. return deviceType === audio.DeviceType.BLUETOOTH_A2DP || deviceType === audio.DeviceType.BLUETOOTH_SCO
  1285. }
  1286. private isWiredOutputDeviceType(deviceType: audio.DeviceType): boolean {
  1287. return deviceType === audio.DeviceType.WIRED_HEADSET
  1288. || deviceType === audio.DeviceType.WIRED_HEADPHONES
  1289. || deviceType === audio.DeviceType.USB_HEADSET
  1290. }
  1291. private handleAudioInterrupt(event: InterruptEvent): void {
  1292. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1293. if (this.isSameTimePlay) {
  1294. Logger.info(TAG, `音频中断已忽略,当前为混音模式: ${JSON.stringify(event)}`)
  1295. return
  1296. }
  1297. const wasPlayingBeforeInterrupt = this.isAudioPlaybackActive()
  1298. switch (event.hintType) {
  1299. case InterruptHintType.INTERRUPT_HINT_PAUSE:
  1300. this.audioInterruptResumePending = wasPlayingBeforeInterrupt
  1301. if (wasPlayingBeforeInterrupt) {
  1302. this.pause(false)
  1303. }
  1304. break
  1305. case InterruptHintType.INTERRUPT_HINT_RESUME:
  1306. if (this.audioInterruptResumePending && this.CONTROL_PlayStatus === PlayStatus.PAUSE) {
  1307. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1308. this.audioInterruptResumePending = false
  1309. this.resumePlaybackAfterAudioInterrupt()
  1310. }
  1311. break
  1312. case InterruptHintType.INTERRUPT_HINT_STOP:
  1313. Logger.info(TAG, `收到音频中断 STOP,改为暂停等待用户手动恢复: ${JSON.stringify(event)}`)
  1314. this.audioInterruptResumePending = false
  1315. if (wasPlayingBeforeInterrupt) {
  1316. this.pause(false)
  1317. }
  1318. break
  1319. default:
  1320. Logger.info(TAG, `忽略未处理的音频中断类型: ${JSON.stringify(event)}`)
  1321. break
  1322. }
  1323. }
  1324. private resumePlaybackAfterAudioInterrupt(): void {
  1325. if (this.castControllerWrapper && this.isCastPlaying) {
  1326. this.castControllerWrapper.setPlaying().then(() => {
  1327. this.CONTROL_PlayStatus = PlayStatus.PLAY
  1328. this.setIsPlaying(true)
  1329. this.updateSessionPlayState(true)
  1330. this.playChange()
  1331. }).catch((error: BusinessError | Error) => {
  1332. Logger.error(TAG, `音频中断后恢复投播失败: ${error}`)
  1333. })
  1334. return
  1335. }
  1336. this.startPlayOrResumePlay()
  1337. }
  1338. private handlePlayerDeviceChange(event: InterruptEvent): void {
  1339. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1340. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) {
  1341. Logger.info(TAG, 'ijk deviceChange 检测到新设备接入,交由 AudioRoutingManager 处理')
  1342. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) {
  1343. Logger.info(TAG, 'ijk deviceChange 检测到旧设备移除,等待 AudioRoutingManager 精确判断是否暂停')
  1344. }
  1345. }
  1346. private handleOutputDeviceChange(deviceChanged: audio.DeviceChangeAction): void {
  1347. const descriptors = deviceChanged?.deviceDescriptors ?? []
  1348. if (descriptors.length <= 0) {
  1349. Logger.warn(TAG, `音频输出设备变化缺少描述信息: ${JSON.stringify(deviceChanged)}`)
  1350. return
  1351. }
  1352. Logger.info(TAG, `音频输出设备变化: type=${deviceChanged.type}, count=${descriptors.length}`)
  1353. const outputDescriptors = descriptors.filter((descriptor) => descriptor.deviceRole === audio.DeviceRole.OUTPUT_DEVICE)
  1354. if (outputDescriptors.length <= 0) {
  1355. Logger.info(TAG, `忽略非输出设备变化: ${JSON.stringify(deviceChanged)}`)
  1356. return
  1357. }
  1358. const hasBluetoothOutput = outputDescriptors.some((descriptor) =>
  1359. this.isBluetoothOutputDeviceType(descriptor.deviceType))
  1360. const hasWiredOutput = outputDescriptors.some((descriptor) =>
  1361. this.isWiredOutputDeviceType(descriptor.deviceType))
  1362. if (deviceChanged.type === audio.DeviceChangeType.CONNECT) {
  1363. if (hasBluetoothOutput) {
  1364. this.isBluetoothConnected = true
  1365. console.info('onecold 蓝牙设备已连接')
  1366. }
  1367. return
  1368. }
  1369. if (deviceChanged.type !== audio.DeviceChangeType.DISCONNECT) {
  1370. return
  1371. }
  1372. if (hasBluetoothOutput) {
  1373. this.isBluetoothConnected = false
  1374. this.lastBluetoothLyricLine = ''
  1375. console.info('onecold 蓝牙设备已断开')
  1376. if (this.currentSong) {
  1377. this.avSessionController.restoreOriginalMetadata(
  1378. this.currentSong.name || '',
  1379. this.currentSong.artist || ''
  1380. )
  1381. }
  1382. if (this.bluetoothDisconnectPause && this.isAudioPlaybackActive()) {
  1383. this.audioInterruptResumePending = false
  1384. console.info('heanup onecold 蓝牙音响断开, 暂停播放')
  1385. this.pause()
  1386. }
  1387. return
  1388. }
  1389. if (hasWiredOutput && this.isAudioPlaybackActive()) {
  1390. this.audioInterruptResumePending = false
  1391. console.info('heanup onecold 有线/USB耳机断开, 暂停播放')
  1392. this.pause()
  1393. }
  1394. }
  1395. initSetting() {
  1396. this.default_layout = PreferencesUtil.getNumberSync('default_layout', 0)
  1397. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1398. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1399. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1400. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1401. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1402. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1403. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1404. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1405. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1406. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1407. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1408. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1409. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1410. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1411. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1412. this.isHomeBgFollowMusicCover = PreferencesUtil.getBooleanSync(SettingPage.IS_HOME_BG_FOLLOW_MUSIC_COVER, true)
  1413. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1414. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  1415. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1416. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1417. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1418. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1419. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1420. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1421. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1422. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1423. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1424. this.syncCustomizeMusicBgPath()
  1425. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  1426. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1427. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, false)
  1428. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1429. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1430. this.isEnableWordByWordLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, true)
  1431. this.isLightText = PreferencesUtil.getBooleanSync(SettingPage.IS_LIGHT_TEXT, true)
  1432. this.syncWordByWordLyricMode()
  1433. this.syncLyricLightTextMode()
  1434. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1435. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1436. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1437. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1438. const volumeBoostPercent = PreferencesUtil.getNumberSync(this.volumeBoostPreferenceKey, 0)
  1439. this.volumeBoostPercent = Math.max(0, Math.min(volumeBoostPercent, this.volumeBoostMaxPercent))
  1440. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1441. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1442. this.isPlayPageSwipeNext = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYPAGE_SWIPE_NEXT, true)
  1443. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1444. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1445. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1446. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1447. this.refreshDirVisibilitySettings()
  1448. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1449. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1450. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1451. let audioManager = audio.getAudioManager();
  1452. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1453. if(this.isSameTimePlay){
  1454. //与其他应用同时播放,关键代码
  1455. let strategy: audio.AudioSessionStrategy = {
  1456. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1457. };
  1458. audioSessionManager.activateAudioSession(strategy).then(() => {
  1459. console.info('onecold Succeeded in doing activateAudioSession.');
  1460. }).catch((err: BusinessError) => {
  1461. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1462. });
  1463. }else{
  1464. let isActivated = audioSessionManager.isAudioSessionActivated();
  1465. if(isActivated){
  1466. audioSessionManager.deactivateAudioSession().then(() => {
  1467. console.info('Succeeded in doing deactivateAudioSession.');
  1468. }).catch((err: BusinessError) => {
  1469. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1470. });
  1471. }
  1472. }
  1473. //如果是hicar连接状态,这些都是false
  1474. if(this.isHiCar()){
  1475. this.autoHideTitle = false
  1476. this.isCoverRectangle= true
  1477. this.columns=4
  1478. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1479. {
  1480. this.isGridMusic= false//用list不用网格
  1481. this.isCoverTopBig = false
  1482. }
  1483. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1484. }
  1485. if (this.isSavePlayMode) {
  1486. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1487. }
  1488. }
  1489. private onHomeBgCurrentSongChange(): void {
  1490. this.syncCustomizeMusicBgPath()
  1491. }
  1492. private syncCustomizeMusicBgPath(): void {
  1493. if (!this.isHomeBgFollowMusicCover) {
  1494. return
  1495. }
  1496. const coverPath: string = this.currentSong?.pixelMapPath ?? ''
  1497. AppStorage.setOrCreate('customizeMusicBgPath', coverPath)
  1498. }
  1499. private isMusicCoverHomeBackgroundActive(): boolean {
  1500. return this.isHomeBgFollowMusicCover && this.customizeMusicBgPath.length > 0
  1501. }
  1502. doChangeSetting() {
  1503. this.initSetting()
  1504. this.deleteCache(this.currentPath)
  1505. if (this.modeType === 0) {
  1506. this.getSortedFiles(this.currentPath)
  1507. }
  1508. }
  1509. doChangeBarHeight() {
  1510. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1511. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1512. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1513. this.setBarHeightNormal()
  1514. }
  1515. }
  1516. onPageShow() {
  1517. this.knockController?.immersiveListening();
  1518. app.setImageCacheCount(100);
  1519. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1520. app.setImageRawDataCacheSize(104857600);
  1521. this.refreshDirVisibilitySettings();
  1522. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1523. }
  1524. //开启线程查看各个数据库
  1525. makeWorker() {
  1526. setTimeout(() => {
  1527. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1528. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1529. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1530. // workerInstance.postMessage({
  1531. // code: 1,
  1532. // data1: this.context,
  1533. // data2: this.rootPath,
  1534. // data3: this.lockPath,
  1535. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1536. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1537. // });
  1538. PreferencesUtil.putSync('isFirstApp', false)
  1539. } else {
  1540. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1541. workerInstance.postMessage({ code: 3, data: this.context });
  1542. workerInstance.postMessage({ code: 4, data: this.context });
  1543. this.getHistoryList(false)
  1544. }
  1545. }, 1000)
  1546. workerInstance.onmessage = (e: MessageEvents): void => {
  1547. const message = e.data as LocalMusicWorkerMessage;
  1548. switch (message.code) {
  1549. case 101: //第一次扫描文件夹入库
  1550. ToastUtil.showToast('刷新同步数据库成功!')
  1551. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1552. this.doAllUpdateData()
  1553. break;
  1554. case 102: //查询媒体库列表
  1555. this.isRefreshing = false
  1556. this.mediaKuList = message.data // 只包含前100条
  1557. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1558. this.mediaKuCount = mediaTotalCount;
  1559. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1560. Utility.doSortListAscending(this.mediaKuList)
  1561. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1562. // 媒体库模式下重新加载第一页(分页查询)
  1563. if (this.modeType === 1) {
  1564. this.resetAndLoadFirstPage();
  1565. }
  1566. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1567. // 只保存前100条记录到缓存中
  1568. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1569. break;
  1570. case 103: //收到查询艺术家列表
  1571. this.isRefreshing = false
  1572. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1573. this.artistList = message.data2; // 只包含前100个艺术家
  1574. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1575. this.artistCount = artistTotalCount;
  1576. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1577. this.artistMap.forEach((songs, artist) => {
  1578. nextArtistCountMap.set(artist, songs.length);
  1579. });
  1580. this.artistSongCountMap = nextArtistCountMap;
  1581. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1582. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1583. // 艺术家模式下重新加载第一页(分页查询)
  1584. if (this.modeType === 2) {
  1585. this.resetAndLoadFirstPage();
  1586. }
  1587. // 保存前100条艺术家列表
  1588. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1589. // 保存前60条艺术家的歌曲Map
  1590. const sortedEntries = Array.from(this.artistMap.entries());
  1591. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1592. break;
  1593. case 104: //收到查询专辑列表
  1594. this.isRefreshing = false
  1595. this.albumMap = message.data1;
  1596. this.albumList = message.data2
  1597. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1598. this.albumCount = albumTotalCount;
  1599. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1600. this.albumMap.forEach((songs, album) => {
  1601. nextAlbumCountMap.set(album, songs.length);
  1602. });
  1603. this.albumSongCountMap = nextAlbumCountMap;
  1604. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1605. // 专辑模式下重新加载第一页(分页查询)
  1606. if (this.modeType === 3) {
  1607. this.resetAndLoadFirstPage();
  1608. }
  1609. //查询完毕在启动是否自动播放
  1610. if (this.isStartAutoPlay&&this.isCanAuto) {
  1611. this.isCanAuto = false
  1612. console.info('onecold startPlayOrResumePlay 757')
  1613. this.startPlayOrResumePlay()
  1614. }
  1615. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1616. // 保存前100条专辑列表(Worker已经只发送了100条)
  1617. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1618. // 保存前60条专辑Map(Worker已经只发送了60条)
  1619. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1620. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1621. break;
  1622. case 105: // 缓存完成后返回的元数据
  1623. this.handleWorkerMetadataPayload(message.data);
  1624. break;
  1625. case 106: // 编辑音乐元数据和封面完成
  1626. this.handleEditMusicResult(message.data);
  1627. break;
  1628. }
  1629. };
  1630. // 在调用terminate后,执行onexit
  1631. workerInstance.onexit = (code) => {
  1632. metadataExtractionInFlight.clear();
  1633. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1634. }
  1635. workerInstance.onerror = (err: ErrorEvent) => {
  1636. metadataExtractionInFlight.clear();
  1637. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1638. }
  1639. }
  1640. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1641. if (!payload || !payload.originFilePath) {
  1642. return;
  1643. }
  1644. metadataExtractionInFlight.delete(payload.originFilePath);
  1645. if (payload.error) {
  1646. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1647. return;
  1648. }
  1649. this.applyMetadataToCollections(payload.originFilePath, payload);
  1650. }
  1651. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1652. const targets: Array<VideoItem> = [];
  1653. let mainListUpdated = false;
  1654. let playlistUpdated = false;
  1655. if (this.currentSong && this.currentSong.filePath === filePath) {
  1656. targets.push(this.currentSong);
  1657. }
  1658. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1659. if (!list || list.length === 0) {
  1660. return;
  1661. }
  1662. const found = Utility.getItemByFilePath(list, filePath);
  1663. if (found) {
  1664. markUpdated?.();
  1665. targets.push(found);
  1666. }
  1667. };
  1668. collectFromList(this.videoLocalList, () => {
  1669. mainListUpdated = true;
  1670. });
  1671. collectFromList(this.songList, () => {
  1672. playlistUpdated = true;
  1673. });
  1674. collectFromList(this.historyList);
  1675. collectFromList(this.favList);
  1676. const remoteManager = RemoteDriveManager.getInstance();
  1677. collectFromList(remoteManager.webDavSongs);
  1678. const updated = new Set<VideoItem>();
  1679. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1680. for (let i = 0; i < targets.length; i++) {
  1681. const target = targets[i];
  1682. if (!target || updated.has(target)) {
  1683. continue;
  1684. }
  1685. updated.add(target);
  1686. this.mergeVideoItemWithPayload(target, payload);
  1687. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1688. remoteMetadataUpdates.set(target.filePath, {
  1689. filePath: target.filePath,
  1690. pixelMapPath: target.pixelMapPath,
  1691. isCustomCover: target.isCustomCover,
  1692. md5Str: target.md5Str,
  1693. name: target.name,
  1694. artist: target.artist
  1695. });
  1696. }
  1697. }
  1698. if (this.currentSong && this.currentSong.filePath === filePath) {
  1699. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1700. if (payload.name) {
  1701. this.name = payload.name;
  1702. }
  1703. if (payload.artist) {
  1704. this.artist = payload.artist;
  1705. }
  1706. if (payload.pixelMapPath && this.currentSong?.pixelMapPath) {
  1707. this.cover = this.currentSong.pixelMapPath;
  1708. }
  1709. if (payload.lyricContent) {
  1710. this.applyInlineLyricContent(payload.lyricContent);
  1711. }
  1712. let avSessionDurationMs: number = this.duration;
  1713. if (payload.duration) {
  1714. const durationSeconds = Number(payload.duration);
  1715. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1716. avSessionDurationMs = durationSeconds * 1000;
  1717. this.duration = avSessionDurationMs;
  1718. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1719. this.durationStringTime = secondToTime(this.durationTime);
  1720. }
  1721. }
  1722. if (avSessionDurationMs > 0) {
  1723. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1724. }
  1725. this.currentSong = cloneVideoItem(this.currentSong);
  1726. AppStorage.setOrCreate('currentSong', this.currentSong);
  1727. }
  1728. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1729. if (primaryTarget) {
  1730. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1731. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1732. });
  1733. }
  1734. if (remoteMetadataUpdates.size > 0) {
  1735. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1736. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1737. }
  1738. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1739. }
  1740. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1741. // 关闭进度条
  1742. DialogHelper.closeDialog(this.loadingDialogId)
  1743. if (result.success) {
  1744. console.log("heanup 编辑信息成功,数据库已同步");
  1745. if (result.coverResult) {
  1746. ToastUtil.showToast('内嵌封面成功');
  1747. }
  1748. ToastUtil.showToast('内嵌音乐标签成功');
  1749. this.isShowMoreView = false;
  1750. this.name = this.titleStr;
  1751. // 同步当前播放的歌曲信息
  1752. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1753. this.currentSong.name = this.titleStr;
  1754. this.artist = this.artistStr;
  1755. this.currentSong.artist = this.artistStr;
  1756. this.currentSong.album = this.ablumStr;
  1757. this.currentSong.year = this.yearStr;
  1758. this.currentSong.genre = this.genreStr;
  1759. this.currentSong.track = this.trackStr;
  1760. this.currentSong.lyricContent = this.lyricConStr;
  1761. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1762. this.currentSong.COMPOSER = this.composerStr;
  1763. this.currentSong.LYRICIST = this.lyricistStr;
  1764. this.currentSong.COMMENT = this.commentStr;
  1765. }
  1766. // if (result.needRefreshList && this.modeType == 0) {
  1767. // this.deleteCache(this.currentPath);
  1768. // this.getSortedFiles(this.currentPath);
  1769. // }
  1770. // 同步编辑字段到本地列表
  1771. if (this.editingItem) {
  1772. this.syncEditedFields(this.editingItem);
  1773. this.syncListsAfterEdit(this.editingItem.filePath);
  1774. this.doUpateEditedFields(this.editingItem);
  1775. }
  1776. // 清理临时变量
  1777. this.longItemFilePath = '';
  1778. this.tempLyricContent = '';
  1779. this.isShowEdit = false;
  1780. this.imagePathStr = '';
  1781. } else {
  1782. console.error("heanup 编辑信息失败: " + result.error);
  1783. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1784. // 清理临时变量
  1785. this.longItemFilePath = '';
  1786. this.tempLyricContent = '';
  1787. this.isShowEdit = false;
  1788. this.imagePathStr = '';
  1789. }
  1790. }
  1791. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1792. if (value === undefined || value === null) {
  1793. return;
  1794. }
  1795. const text = value.toString();
  1796. if (!allowEmpty && text.trim().length === 0) {
  1797. return;
  1798. }
  1799. Reflect.set(target, key as string, value);
  1800. }
  1801. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1802. if (value === undefined || value === null || Number.isNaN(value)) {
  1803. return;
  1804. }
  1805. Reflect.set(target, key as string, value);
  1806. }
  1807. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1808. if (!target || !payload) {
  1809. return;
  1810. }
  1811. this.assignStringMetadata(target, 'name', payload.name);
  1812. this.assignStringMetadata(target, 'artist', payload.artist);
  1813. this.assignStringMetadata(target, 'album', payload.album);
  1814. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1815. this.assignStringMetadata(target, 'duration', payload.duration);
  1816. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1817. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1818. this.assignStringMetadata(target, 'md5Str', payload.md5Str);
  1819. this.assignStringMetadata(target, 'size', payload.size);
  1820. mergeCoverWithPriority(target, payload.pixelMapPath);
  1821. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1822. this.assignStringMetadata(target, 'genre', payload.genre);
  1823. this.assignStringMetadata(target, 'track', payload.track);
  1824. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1825. this.assignStringMetadata(target, 'channels', payload.channels);
  1826. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1827. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1828. this.assignStringMetadata(target, 'year', payload.year);
  1829. this.assignStringMetadata(target, 'disc', payload.disc);
  1830. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1831. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1832. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1833. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1834. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1835. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1836. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1837. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1838. }
  1839. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1840. if (!target || !source) {
  1841. return;
  1842. }
  1843. this.assignStringMetadata(target, 'name', source.name);
  1844. this.assignStringMetadata(target, 'artist', source.artist);
  1845. this.assignStringMetadata(target, 'album', source.album);
  1846. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1847. this.assignStringMetadata(target, 'duration', source.duration);
  1848. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1849. this.assignStringMetadata(target, 'md5Str', source.md5Str);
  1850. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1851. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1852. this.assignStringMetadata(target, 'size', source.size);
  1853. mergeCoverWithPriority(target, source.pixelMapPath, source.isCustomCover ?? 0);
  1854. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1855. this.assignStringMetadata(target, 'genre', source.genre);
  1856. this.assignStringMetadata(target, 'track', source.track);
  1857. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1858. this.assignStringMetadata(target, 'channels', source.channels);
  1859. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1860. this.assignStringMetadata(target, 'start_time', source.start_time);
  1861. this.assignStringMetadata(target, 'year', source.year);
  1862. this.assignStringMetadata(target, 'disc', source.disc);
  1863. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1864. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1865. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1866. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1867. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1868. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1869. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1870. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1871. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1872. target.remote_rel_path = source.remote_rel_path;
  1873. }
  1874. }
  1875. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1876. if (!item || !isRemoteCloudType(item.type)) {
  1877. return;
  1878. }
  1879. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1880. if (!storagePath) {
  1881. return;
  1882. }
  1883. try {
  1884. const cached = await this.table.queryVideoByFilePath(storagePath);
  1885. if (!cached) {
  1886. return;
  1887. }
  1888. this.mergeVideoItemFromSource(item, cached);
  1889. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1890. item.remote_rel_path = storagePath;
  1891. }
  1892. if (item === this.currentSong) {
  1893. if (StrUtil.isNotEmpty(item.name)) {
  1894. this.name = item.name;
  1895. }
  1896. if (StrUtil.isNotEmpty(item.artist)) {
  1897. this.artist = item.artist!;
  1898. }
  1899. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1900. this.cover = item.pixelMapPath!;
  1901. }
  1902. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1903. this.applyInlineLyricContent(item.lyricContent as string);
  1904. }
  1905. }
  1906. } catch (error) {
  1907. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1908. }
  1909. }
  1910. private applyInlineLyricContent(content: string): void {
  1911. if (StrUtil.isEmpty(content)) {
  1912. return;
  1913. }
  1914. this.lyricContent = content;
  1915. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1916. const lyric: Lyric = this.parser.parse(lines);
  1917. this.lyricController.setLyric(lyric);
  1918. this.lyricControllerXF.setLyric(lyric);
  1919. this.lyricControllerSingle.setLyric(lyric);
  1920. }
  1921. private extractParentPathFromStoragePath(path: string): string {
  1922. if (!path) {
  1923. return '';
  1924. }
  1925. const lastSlash = path.lastIndexOf('/');
  1926. if (lastSlash <= 0) {
  1927. return '';
  1928. }
  1929. return path.substring(0, lastSlash);
  1930. }
  1931. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1932. if (!target || !isRemoteCloudType(target.type)) {
  1933. return null;
  1934. }
  1935. if (isWebDavType(target.type)) {
  1936. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1937. if (storagePath) {
  1938. target.remote_rel_path = storagePath;
  1939. return storagePath;
  1940. }
  1941. return null;
  1942. }
  1943. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1944. return target.remote_rel_path;
  1945. }
  1946. return null;
  1947. }
  1948. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1949. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1950. return;
  1951. }
  1952. const storagePath = this.resolveRemoteStoragePath(target);
  1953. if (!storagePath) {
  1954. return;
  1955. }
  1956. const table = new MediaTable(this.context);
  1957. await new Promise<void>((resolve) => {
  1958. table.getRdbStore(this.context as Context, () => resolve());
  1959. });
  1960. const cloneItem = cloneVideoItem(target);
  1961. cloneItem.filePath = storagePath;
  1962. cloneItem.remote_rel_path = storagePath;
  1963. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1964. await table.saveOrUpdateWebDavItem(cloneItem);
  1965. }
  1966. onPageHide() {
  1967. this.knockController?.immersiveDisableListening();
  1968. }
  1969. @State isFirstStartPlay: boolean = false
  1970. private async startFileDeletionWatcher(): Promise<void> {
  1971. if (!this.rootPath) {
  1972. return;
  1973. }
  1974. if (!this.deletionWatcher) {
  1975. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1976. }
  1977. try {
  1978. await this.deletionWatcher.watchDirectories([
  1979. this.rootPath,
  1980. this.lockPath,
  1981. this.favPath,
  1982. this.historyPath
  1983. ]);
  1984. } catch (error) {
  1985. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1986. }
  1987. }
  1988. //获取download_path
  1989. async mkDownLoadDir() {
  1990. const documentViewPicker = new picker.DocumentViewPicker()
  1991. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1992. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1993. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1994. this.currentPath = this.rootPath
  1995. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1996. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1997. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1998. Logger.info('onecold rootPath = ' + this.rootPath)
  1999. if (!FileUtil.accessSync(this.favPath)) {
  2000. FileUtil.mkdirSync(this.favPath)
  2001. }
  2002. if (!FileUtil.accessSync(this.historyPath)) {
  2003. FileUtil.mkdirSync(this.historyPath)
  2004. }
  2005. // await this.startFileDeletionWatcher();
  2006. this.getSortedFiles(this.rootPath).then(async () => {
  2007. this.isFavMusic = false
  2008. //穿山甲
  2009. // this.loadBannerAd(CSJUtil.getBannerID())
  2010. this.restoreLastPlayContext();
  2011. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  2012. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  2013. if (ArrayUtil.isEmpty(this.songList)) {
  2014. this.songList = this.videoLocalList.filter(item =>
  2015. item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2016. } else {
  2017. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  2018. }
  2019. if (ArrayUtil.isNotEmpty(this.songList)) {
  2020. this.isFirstStartPlay = true
  2021. this.sonDataSource.pushArrayData(this.songList)
  2022. if (this.currentSong === undefined) {
  2023. this.isFirstStartPlay = false
  2024. this.currentSong = this.songList[0]
  2025. }
  2026. const restoredUrl = await this.resolvePlaybackUrlForCurrentSong('restore-last-song');
  2027. if (!restoredUrl) {
  2028. return;
  2029. }
  2030. this.videoUrl = restoredUrl;
  2031. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  2032. this.name = this.currentSong.name
  2033. this.cover = this.currentSong.pixelMapPath
  2034. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  2035. } else {
  2036. this.name = '空空如也'
  2037. }
  2038. })
  2039. this.getFavList(false)
  2040. }
  2041. getFavList(isFavRefresh: boolean) {
  2042. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  2043. this.favList = result
  2044. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  2045. this.videoLocalList = this.favList
  2046. this.updateListData(this.videoLocalList, true)
  2047. }
  2048. })
  2049. }
  2050. getHistoryList(isRefresh: boolean) {
  2051. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  2052. this.historyList = result
  2053. // for (let i = 0; i < this.historyList.length; i++) {
  2054. //
  2055. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  2056. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  2057. // }
  2058. if (isRefresh) {
  2059. this.videoLocalList = this.historyList
  2060. this.updateListData(this.videoLocalList, true)
  2061. }
  2062. })
  2063. }
  2064. // 组件消失生命周期
  2065. aboutToDisappear() {
  2066. console.info('LifeCycleComponent aboutToDisappear');
  2067. if (this.alphaBetHideTimer) {
  2068. clearTimeout(this.alphaBetHideTimer);
  2069. this.alphaBetHideTimer = 0;
  2070. }
  2071. if (this.alphaBetRebuildTimer) {
  2072. clearTimeout(this.alphaBetRebuildTimer);
  2073. this.alphaBetRebuildTimer = 0;
  2074. }
  2075. if (this.pagingScheduleTimer) {
  2076. clearTimeout(this.pagingScheduleTimer);
  2077. this.pagingScheduleTimer = 0;
  2078. }
  2079. if (this.gridWaterScrollIdleTimer) {
  2080. clearTimeout(this.gridWaterScrollIdleTimer);
  2081. this.gridWaterScrollIdleTimer = 0;
  2082. }
  2083. if (this.listUpdateTimer) {
  2084. clearTimeout(this.listUpdateTimer);
  2085. this.listUpdateTimer = 0;
  2086. }
  2087. if (this.mediaLibraryWarmupPrefetchTimer) {
  2088. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  2089. this.mediaLibraryWarmupPrefetchTimer = 0;
  2090. }
  2091. this.clearInitialSeekGuardTimer();
  2092. this.alphaBetBuildVersion++;
  2093. this.gridWaterLastActiveTs = 0;
  2094. this.coverThumbCache.dispose();
  2095. this.coverThumbCacheReady = false;
  2096. this.pendingCoverThumbRefresh = false;
  2097. this.deletionWatcher?.stop();
  2098. this.knockController?.immersiveDisableListening();
  2099. this.curIndex = 0
  2100. this.isAppForeground = false;
  2101. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  2102. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  2103. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  2104. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  2105. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  2106. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  2107. emitter.off(EventConstants.EVENT_PLAYLIST_PLAY);
  2108. emitter.off(EventConstants.EVENT_PLAYLIST_REFRESH_SORT);
  2109. emitter.off(EventConstants.EVENT_PLAY_QUEUE_REFRESH);
  2110. emitter.off(EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST);
  2111. emitter.off(EventConstants.EVENT_PLAY_PAUSE);
  2112. this.mDestroyPage = true;
  2113. this.audioInterruptResumePending = false;
  2114. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  2115. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  2116. this.stop();
  2117. }
  2118. this.mIjkMediaPlayer.off('audioInterrupt');
  2119. this.mIjkMediaPlayer.off('deviceChange');
  2120. if (this.audioRoutingManager && this.outputDeviceChangeCallback) {
  2121. try {
  2122. this.audioRoutingManager.off('deviceChange', this.outputDeviceChangeCallback);
  2123. } catch (error) {
  2124. Logger.warn(TAG, `注销音频输出设备监听失败: ${(error as BusinessError).message ?? error}`);
  2125. }
  2126. }
  2127. this.outputDeviceChangeCallback = undefined;
  2128. this.audioRoutingManager = undefined;
  2129. if (workerInstance) {
  2130. workerInstance.terminate();
  2131. }
  2132. this.stopPip();
  2133. this.destroyPipController()
  2134. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  2135. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  2136. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2137. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2138. this.getUIContext().getHostContext()!.eventHub.off('openPlayerViewFromMiniBar');
  2139. this.getUIContext().getHostContext()!.eventHub.off('dismissPlayerView');
  2140. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2141. this.eventHub.off('onStateChange');
  2142. }
  2143. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  2144. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  2145. this.isFavMusic = false
  2146. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2147. if (isWorkerPost) {
  2148. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2149. }
  2150. if (this.modeType !== 0) {
  2151. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  2152. if (isOpen && destPath) {
  2153. this.openMusic(true, destPath, openItem)
  2154. }
  2155. return
  2156. }
  2157. console.info('onecold getSortedFiles 2')
  2158. this.isCanBack = false
  2159. this.currentPath = curPath
  2160. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2161. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2162. if (curPath === this.rootPath) {
  2163. this.rightTopImage = $r('sys.symbol.sort')
  2164. } else {
  2165. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2166. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2167. this.rightTopImage = $r('sys.symbol.chevron_left')
  2168. }
  2169. }
  2170. // Get the current file list and calculate its hash
  2171. this.fileList = FileUtil.listFileSync(curPath);
  2172. const currentHash = simpleHash(this.fileList);
  2173. // Check cache
  2174. const cachedValue = this.findCache(curPath);
  2175. Logger.info('onecold cachedValue = ' + cachedValue)
  2176. const cachedHash = this.findStringCache(curPath + '_hash');
  2177. const cachedDirList = this.findCache(curPath + "_dirList");
  2178. if (cachedValue !== undefined&&!this.isRefreshing) {
  2179. // this.videoLocalList = cachedValue;
  2180. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2181. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2182. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2183. }
  2184. this.isRefreshing = false
  2185. this.updateListData(cachedValue, undefined, immediateListUpdate)
  2186. if (scrollTopAfterUpdate) {
  2187. this.scrollToTopForCurrentLayout()
  2188. }
  2189. }
  2190. if (cachedDirList !== undefined) {
  2191. this.dirList = cachedDirList
  2192. }
  2193. //通过当前hash值和缓存hash判断list有没有变化
  2194. if (cachedValue && cachedHash === currentHash) {
  2195. return;
  2196. }
  2197. // this.fileList = FileUtil.listFileSync(curPath)
  2198. let directories: Array<VideoItem> = [];
  2199. let isoFiles: Array<VideoItem> = this.getLocalIsoItems(curPath, this.fileList);
  2200. let files: Array<VideoItem> = [];
  2201. for (let i = 0; i < this.fileList.length; i++) {
  2202. // console.info(`The name of file: ${this.fileList[i]}`);
  2203. let path = curPath + '/' + this.fileList[i]
  2204. if (FileUtil.isDirectory(path)) {
  2205. let item: VideoItem =
  2206. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2207. '')
  2208. if (this.isShowDir(item.name)) {
  2209. directories.push(item);
  2210. }
  2211. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2212. // Utility.doSortListAscending(directories)
  2213. } else {
  2214. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2215. let item: VideoItem =
  2216. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2217. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2218. files.push(item);
  2219. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2220. // this.doSortListAscending(files)
  2221. }
  2222. }
  2223. }
  2224. }
  2225. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2226. if (this.currentPath !== this.lockPath) {
  2227. files = result.filter(item => !this.isIsoLocalFile(item));
  2228. }
  2229. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2230. Utility.doSortListAscending(files)
  2231. Utility.doSortListAscending(isoFiles)
  2232. if (this.currentPath === this.rootPath) {
  2233. this.dirList = directories
  2234. this.addCache(curPath + "_dirList", this.dirList);
  2235. }
  2236. //插入广告先注释掉
  2237. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2238. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2239. // directories.push(adItem)
  2240. // }
  2241. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2242. this.videoLocalList = directories.concat(isoFiles).concat(files);
  2243. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2244. if (scrollTopAfterUpdate) {
  2245. this.scrollToTopForCurrentLayout()
  2246. }
  2247. if (ArrayUtil.isNotEmpty(files)) {
  2248. if (this.currentPath != this.rootPath) {
  2249. if (files) {
  2250. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2251. }
  2252. }
  2253. }
  2254. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2255. this.addCache(curPath, this.videoLocalList);
  2256. await this.saveCacheToStorage();
  2257. this.addStringCache(curPath + '_hash', currentHash);
  2258. }
  2259. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2260. for (let i = 0; i < this.videoLocalList.length; i++) {
  2261. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2262. }
  2263. // this.setButtonStatus()
  2264. this.openMusic(isOpen, destPath,openItem)
  2265. this.isRefreshing = false
  2266. });
  2267. }
  2268. //第三方app打开天天静听导入音乐后播放
  2269. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2270. if (isOpen&&destPath) {
  2271. if (destPath === undefined) {
  2272. // 处理 destPath 为 undefined 的情况
  2273. return
  2274. }
  2275. if (destPath.endsWith('.lrc')) {
  2276. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2277. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2278. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2279. this.initLyric(lyricPath);
  2280. }
  2281. return
  2282. }
  2283. if(openItem){
  2284. this.doPlay(openItem,0,false,true)
  2285. // this.isShowPlay = true
  2286. this.setShowPlayTrue()
  2287. }
  2288. }
  2289. }
  2290. //扫描文件夹入库
  2291. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2292. const files = FileUtil.listFileSync(curPath);
  2293. let mediaItems: VideoItem[] = [];
  2294. Logger.info('onecold scanDirectory start ')
  2295. for (const file of files) {
  2296. const fPath = `${curPath}/${file}`;
  2297. if (fPath === this.lockPath) {
  2298. Logger.info(`Skipping locked path: ${fPath}`);
  2299. continue;
  2300. }
  2301. if (FileUtil.isDirectory(fPath)) {
  2302. // Recursively scan subdirectories
  2303. const subDirItems = await this.scanDirectory(fPath);
  2304. mediaItems = mediaItems.concat(subDirItems);
  2305. } else {
  2306. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2307. // Process media files
  2308. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2309. let mediaItem: VideoItem =
  2310. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2311. mediaItems.push(mediaItem);
  2312. this.table.insert(mediaItem, (id: number) => {
  2313. });
  2314. }
  2315. }
  2316. }
  2317. return mediaItems;
  2318. }
  2319. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2320. this.isShowTitleBar = true
  2321. const shouldAnimate = !immediate
  2322. if (this.listUpdateTimer) {
  2323. clearTimeout(this.listUpdateTimer)
  2324. this.listUpdateTimer = 0
  2325. }
  2326. const updateVersion = ++this.listUpdateVersion
  2327. if (shouldAnimate) {
  2328. this.getUIContext().animateTo({ duration: 666 }, () => {
  2329. this.opacityItem = 0.5;
  2330. });
  2331. }
  2332. const applyListData = () => {
  2333. if (updateVersion !== this.listUpdateVersion) {
  2334. return
  2335. }
  2336. this.videoLocalList = mList;
  2337. if (!noSort) {
  2338. if (this.modeType === 0 || this.modeType === 1) {
  2339. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2340. this.doSortType(this.sortType)
  2341. }
  2342. }
  2343. this.dataSource.pushArrayData(this.videoLocalList)
  2344. if (shouldAnimate) {
  2345. this.getUIContext().animateTo({ duration: 666 }, () => {
  2346. this.opacityItem = 1;
  2347. });
  2348. } else {
  2349. this.opacityItem = 1;
  2350. }
  2351. this.setButtonStatus()
  2352. //添加到字母索引表
  2353. this.markAlphaBetDirty()
  2354. };
  2355. if (immediate) {
  2356. applyListData();
  2357. return;
  2358. }
  2359. this.listUpdateTimer = setTimeout(() => {
  2360. this.listUpdateTimer = 0
  2361. applyListData();
  2362. }, 200);
  2363. }
  2364. getCurFileList(): Array<VideoItem> {
  2365. const source = this.isSearchMode ? this.filteredList : this.videoLocalList
  2366. let files: Array<VideoItem> = [];
  2367. if (ArrayUtil.isNotEmpty(source)) {
  2368. for (let i = 0; i < source.length; i++) {
  2369. if (this.isSelectableLocalItem(source[i])) {
  2370. files.push(source[i]);
  2371. }
  2372. }
  2373. }
  2374. return files
  2375. }
  2376. private isProtectedLocalDirectory(item: VideoItem): boolean {
  2377. return item.type === CommonConstants.TYPE_IS_DIR &&
  2378. (item.name === LocalMusic.STR_LOCK_VIDEO ||
  2379. item.name === LocalMusic.STR_FAC_VIDEO ||
  2380. item.name === LocalMusic.STR_HISTORY_MUSIC)
  2381. }
  2382. private isIsoLocalFile(item?: VideoItem | null): boolean {
  2383. if (!item || item.type !== CommonConstants.TYPE_LOCAL) {
  2384. return false
  2385. }
  2386. return Utility.isIsoByExtension(item.filePath || item.fileName || item.name || '')
  2387. }
  2388. private supportsLocalAudioActions(item: VideoItem): boolean {
  2389. return !!item && item.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(item)
  2390. }
  2391. private buildLocalIsoItem(filePath: string, fileName?: string): VideoItem {
  2392. const displayName = fileName || FileUtil.getFileName(filePath) || filePath
  2393. let fileSize = 0
  2394. try {
  2395. const stat = fs.statSync(filePath) as fs.Stat
  2396. if (typeof stat.size === 'number') {
  2397. fileSize = stat.size
  2398. }
  2399. } catch (_error) {
  2400. }
  2401. const item = new VideoItem(
  2402. displayName,
  2403. filePath,
  2404. filePath,
  2405. CommonConstants.TYPE_LOCAL,
  2406. fileSize,
  2407. Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
  2408. Utility.formatFSize(fileSize),
  2409. '',
  2410. 'ISO 镜像',
  2411. '可提取音频',
  2412. displayName
  2413. )
  2414. item.mimeType = 'application/x-iso9660-image'
  2415. item.duration = ''
  2416. return item
  2417. }
  2418. private getLocalIsoItems(curPath: string, fileNames?: Array<string>): Array<VideoItem> {
  2419. let sourceNames: Array<string> = []
  2420. if (fileNames !== undefined && fileNames.length > 0) {
  2421. sourceNames = fileNames
  2422. } else {
  2423. const listedNames = FileUtil.listFileSync(curPath)
  2424. sourceNames = listedNames ? listedNames : []
  2425. }
  2426. const isoItems: Array<VideoItem> = []
  2427. for (let i = 0; i < sourceNames.length; i++) {
  2428. const name = sourceNames[i]
  2429. const fullPath = `${curPath}/${name}`
  2430. if (FileUtil.isDirectory(fullPath) || !Utility.isIsoByExtension(fullPath)) {
  2431. continue
  2432. }
  2433. isoItems.push(this.buildLocalIsoItem(fullPath, name))
  2434. }
  2435. Utility.doSortListAscending(isoItems)
  2436. return isoItems
  2437. }
  2438. private filterOutLocalIsoItems(items: Array<VideoItem>): Array<VideoItem> {
  2439. return items.filter(item => !this.isIsoLocalFile(item))
  2440. }
  2441. private isSelectableLocalItem(item: VideoItem): boolean {
  2442. if (!item) {
  2443. return false
  2444. }
  2445. if (item.type === CommonConstants.TYPE_LOCAL) {
  2446. return true
  2447. }
  2448. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2449. return !this.isProtectedLocalDirectory(item)
  2450. }
  2451. return false
  2452. }
  2453. private isLocalItemSelected(item: VideoItem): boolean {
  2454. return this.selectedFiles.some(x => x.filePath === item.filePath)
  2455. }
  2456. private hasSelectedDirectories(): boolean {
  2457. return this.selectedFiles.some(item => item.type === CommonConstants.TYPE_IS_DIR)
  2458. }
  2459. private getSelectedPlayableFiles(): Array<VideoItem> {
  2460. return this.selectedFiles.filter(item => item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2461. }
  2462. private syncLocalSelectionState(): void {
  2463. const selectableItems = this.getCurFileList()
  2464. const selectableKeys: Set<string> = new Set(selectableItems.map(item => item.filePath))
  2465. const nextSelected = this.selectedFiles.filter(item => selectableKeys.has(item.filePath))
  2466. if (nextSelected.length !== this.selectedFiles.length) {
  2467. this.selectedFiles = [...nextSelected]
  2468. }
  2469. this.isAllSelected = nextSelected.length > 0 && nextSelected.length === selectableItems.length
  2470. }
  2471. private enterLocalMultiSelect(item: VideoItem): void {
  2472. if (!this.isSelectableLocalItem(item)) {
  2473. return
  2474. }
  2475. if (!this.isMultiSelect) {
  2476. this.isMultiSelect = true
  2477. }
  2478. if (!this.isLocalItemSelected(item)) {
  2479. this.selectedFiles = [...this.selectedFiles, item]
  2480. }
  2481. this.syncLocalSelectionState()
  2482. }
  2483. private selectSingleItemForDelete(item: VideoItem): void {
  2484. if (!this.isSelectableLocalItem(item)) {
  2485. return
  2486. }
  2487. this.selectedFiles = [item]
  2488. this.isAllSelected = false
  2489. }
  2490. setButtonStatus() {
  2491. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2492. this.isZero = false
  2493. } else {
  2494. this.isZero = true
  2495. }
  2496. if (this.currentPath !== this.rootPath &&
  2497. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2498. this.isHasDir = true //不为空,说明有子文件夹
  2499. } else {
  2500. this.isHasDir = false
  2501. }
  2502. }
  2503. private getPlayListDisplayCount(): number {
  2504. if (this.playQueueScope === 'history') {
  2505. return this.historyList.length;
  2506. }
  2507. if (this.playQueueScope === 'fav') {
  2508. return this.favList.length;
  2509. }
  2510. if (this.playQueueScope === 'find_paged_local') {
  2511. const pagedCount = this.findPagedLocalQueueTotalCount > 0 ? this.findPagedLocalQueueTotalCount : this.totalCount;
  2512. if (pagedCount > 0) {
  2513. return pagedCount;
  2514. }
  2515. }
  2516. if (this.playQueueScope === 'playlist') {
  2517. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2518. // 如果是,优先返回服务端总数
  2519. const navidromeTotalCount = getNavidromeTotalCount();
  2520. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2521. if (navidromeTotalCount > 0 && this.currentSong && (
  2522. isNavidromeType(this.currentSong.type) ||
  2523. isJellyfinType(this.currentSong.type) ||
  2524. isEmbyType(this.currentSong.type) ||
  2525. isAudioStationType(this.currentSong.type) ||
  2526. isPlexType(this.currentSong.type) ||
  2527. isDaoLiYuType(this.currentSong.type)
  2528. )) {
  2529. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2530. return navidromeTotalCount;
  2531. }
  2532. const displayCount = resolvePlaylistDisplayCount(this.currentSongList.length, this.songList.length);
  2533. Logger.info('heanup getPlayListDisplayCount',
  2534. `返回歌单数量: currentSongList=${this.currentSongList.length}, songList=${this.songList.length}, display=${displayCount}`);
  2535. return displayCount;
  2536. }
  2537. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2538. return this.totalCount;
  2539. }
  2540. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2541. return this.songList.length;
  2542. }
  2543. private restoreLastPlayContext(): void {
  2544. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2545. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single' ||
  2546. scope === 'find_paged_local') {
  2547. this.playQueueScope = scope;
  2548. } else {
  2549. this.playQueueScope = 'view';
  2550. }
  2551. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2552. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2553. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2554. this.totalCount = lastTotalCount;
  2555. }
  2556. if (this.playQueueScope === 'find_paged_local' && lastTotalCount > 0) {
  2557. this.findPagedLocalQueueTotalCount = lastTotalCount;
  2558. this.findPagedLocalQueueHasMore = this.songList.length < lastTotalCount;
  2559. }
  2560. }
  2561. private resetFindPagedLocalQueueState(): void {
  2562. // 退出“随心所欲”分页队列时,避免旧分页状态污染后续普通播放队列。
  2563. this.findPagedLocalQueuePageIndex = 0;
  2564. this.findPagedLocalQueuePageSize = DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE;
  2565. this.findPagedLocalQueueTotalCount = 0;
  2566. this.findPagedLocalQueueHasMore = false;
  2567. this.findPagedLocalQueueSortType = 4;
  2568. this.isLoadingFindPagedLocalQueue = false;
  2569. }
  2570. private applyFindPagedLocalQueueState(meta?: FindPlaylistMeta, totalCount?: number): void {
  2571. // 播放器只持有当前页数据,但总数、页码和排序要单独记住,后面才能继续按页补队列。
  2572. this.findPagedLocalQueuePageIndex = meta?.pageIndex ?? 0;
  2573. this.findPagedLocalQueuePageSize = meta?.pageSize && meta.pageSize > 0
  2574. ? Math.max(1, Math.floor(meta.pageSize))
  2575. : DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE;
  2576. this.findPagedLocalQueueSortType = meta?.sortType !== undefined ? meta.sortType : 4;
  2577. const actualTotalCount = meta?.totalCount && meta.totalCount > 0
  2578. ? meta.totalCount
  2579. : (totalCount ?? 0);
  2580. this.findPagedLocalQueueTotalCount = actualTotalCount;
  2581. this.findPagedLocalQueueHasMore =
  2582. (this.findPagedLocalQueuePageIndex + 1) * this.findPagedLocalQueuePageSize < actualTotalCount;
  2583. if (actualTotalCount > 0) {
  2584. this.totalCount = actualTotalCount;
  2585. }
  2586. }
  2587. private isFindPagedLocalQueueActive(): boolean {
  2588. return this.playQueueScope === 'find_paged_local';
  2589. }
  2590. private shouldHydrateFullMediaPlayListOnOpen(): boolean {
  2591. // 特殊分页队列禁止打开播放列表时自动补全全量歌曲,否则会回到 3000+ 首卡顿问题。
  2592. return !!this.currentSong &&
  2593. this.currentSong.type === CommonConstants.TYPE_LOCAL &&
  2594. !this.isFindPagedLocalQueueActive();
  2595. }
  2596. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2597. if (this.isHydratingPlayList) {
  2598. return;
  2599. }
  2600. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2601. return;
  2602. }
  2603. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2604. return;
  2605. }
  2606. this.isHydratingPlayList = true;
  2607. try {
  2608. const fullList: VideoItem[] = [];
  2609. let pageIndex = 0;
  2610. let hasMore = true;
  2611. while (hasMore) {
  2612. const result = await this.table.queryMediaLibraryPaged({
  2613. pageIndex,
  2614. pageSize: this.pageSize,
  2615. sortType: this.sortType,
  2616. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2617. isShowFileName: this.isShowFileName
  2618. });
  2619. if (result.items.length === 0) {
  2620. break;
  2621. }
  2622. fullList.push(...result.items);
  2623. hasMore = result.hasMore;
  2624. pageIndex += 1;
  2625. if (fullList.length >= result.totalCount) {
  2626. hasMore = false;
  2627. }
  2628. }
  2629. if (fullList.length > 0) {
  2630. if(isSonList){
  2631. this.songList = fullList;
  2632. this.sonDataSource.pushArrayData(this.songList);
  2633. }else{
  2634. this.videoLocalList = fullList;
  2635. this.dataSource.pushArrayData(this.videoLocalList);
  2636. }
  2637. }
  2638. } finally {
  2639. this.isHydratingPlayList = false;
  2640. }
  2641. }
  2642. @Builder
  2643. SortMenuBuilder() {
  2644. Menu() {
  2645. MenuItem({
  2646. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2647. content: "按艺术家",
  2648. builder: this.SubSortBuilder(SortMode.ByArtist),
  2649. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2650. })
  2651. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByArtist)))
  2652. MenuItem({
  2653. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2654. content: "按专辑",
  2655. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2656. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2657. })
  2658. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByAlbum)))
  2659. MenuItem({
  2660. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2661. content: "按名称",
  2662. builder: this.SubSortBuilder(SortMode.ByName),
  2663. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2664. })
  2665. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2666. MenuItem({
  2667. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2668. content: $r('app.string.sort_by_time'),
  2669. builder: this.SubSortBuilder(SortMode.ByTime),
  2670. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2671. })
  2672. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByTime)))
  2673. MenuItem({
  2674. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2675. content: '按碟片音轨号',
  2676. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2677. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2678. })
  2679. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByDiscTrack)))
  2680. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2681. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2682. }.attributeModifier(new MenuModifier())
  2683. }
  2684. @Builder
  2685. SortMenuForArtistAblumBuilder() {
  2686. Menu() {
  2687. MenuItem({
  2688. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2689. content: "按名称",
  2690. builder: this.SubSortBuilder(SortMode.ByName),
  2691. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2692. })
  2693. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2694. MenuItem({
  2695. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2696. content: '按数量',
  2697. builder: this.SubSortBuilder(SortMode.ByCount),
  2698. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2699. })
  2700. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByCount)))
  2701. }.attributeModifier(new MenuModifier())
  2702. }
  2703. @Builder SubSortBuilder(sortType: number){
  2704. Menu(){
  2705. MenuItem({
  2706. content: "升序",
  2707. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2708. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2709. })
  2710. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType, true))
  2711. .onClick(async () => {
  2712. await this.doSortType(sortType)
  2713. })
  2714. MenuItem({
  2715. content: "降序",
  2716. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2717. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2718. })
  2719. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType + 1, false))
  2720. .onClick(async () => {
  2721. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2722. })
  2723. }
  2724. }
  2725. async doSortType(index: number): Promise<void> {
  2726. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2727. this.sortType = index;
  2728. this.saveSortTypeForCurrentMode(index);
  2729. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2730. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2731. await this.reloadCurrentDetailSongs();
  2732. } else {
  2733. // 分页模式下,排序需要重新从数据库查询
  2734. await this.resetAndLoadFirstPage();
  2735. }
  2736. }
  2737. /**
  2738. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2739. * 用于详情页切换排序方式时重新查询并排序
  2740. */
  2741. private async reloadCurrentDetailSongs(): Promise<void> {
  2742. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2743. try {
  2744. if (this.modeType === 2) {
  2745. // 艺术家详情页: 重新查询该艺术家的歌曲
  2746. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2747. if (ArrayUtil.isNotEmpty(mList)) {
  2748. // 使用带排序类型的缓存键
  2749. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2750. this.artistMap.set(cacheKey, mList);
  2751. this.totalCount = mList.length;
  2752. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2753. this.updateListData(mList, true);
  2754. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2755. }
  2756. } else if (this.modeType === 3) {
  2757. // 专辑详情页: 重新查询该专辑的歌曲
  2758. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2759. if (ArrayUtil.isNotEmpty(albumList)) {
  2760. // 使用带排序类型的缓存键
  2761. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2762. this.albumMap.set(cacheKey, albumList);
  2763. this.totalCount = albumList.length;
  2764. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2765. this.updateListData(albumList, true);
  2766. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2767. }
  2768. }
  2769. } catch (err) {
  2770. const error = err as Error;
  2771. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2772. ToastUtil.showToast('重新加载数据失败');
  2773. }
  2774. }
  2775. /**
  2776. * 根据当前模式保存排序类型到不同的存储键
  2777. * 区分列表页和详情页的排序设置
  2778. */
  2779. private saveSortTypeForCurrentMode(sortType: number): void {
  2780. let storageKey = SettingPage.SORT_TYPE;
  2781. if (this.modeType === 2) {
  2782. // 艺术家模式
  2783. if (this.isCanBack) {
  2784. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2785. } else {
  2786. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2787. }
  2788. } else if (this.modeType === 3) {
  2789. // 专辑模式
  2790. if (this.isCanBack) {
  2791. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2792. } else {
  2793. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2794. }
  2795. } else {
  2796. storageKey = SettingPage.SORT_TYPE;
  2797. }
  2798. PreferencesUtil.putSync(storageKey, sortType);
  2799. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2800. }
  2801. /**
  2802. * 根据当前模式加载排序类型
  2803. * 区分列表页和详情页的排序设置
  2804. */
  2805. private loadSortTypeForCurrentMode(): number {
  2806. let storageKey = SettingPage.SORT_TYPE;
  2807. let defaultSortType = 4;
  2808. if (this.modeType === 2) {
  2809. // 艺术家模式
  2810. if (this.isCanBack) {
  2811. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2812. defaultSortType = 4; // 详情页默认按名称升序
  2813. } else {
  2814. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2815. defaultSortType = 9; // 列表页默认按数量降序
  2816. }
  2817. } else if (this.modeType === 3) {
  2818. // 专辑模式
  2819. if (this.isCanBack) {
  2820. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2821. defaultSortType = 4; // 详情页默认按名称升序
  2822. } else {
  2823. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2824. defaultSortType = 9; // 列表页默认按数量降序
  2825. }
  2826. }
  2827. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2828. }
  2829. /**
  2830. * 检查当前sortType是否在指定排序类型的范围内
  2831. * 用于判断是否显示打勾图标
  2832. * @param baseSortType 基础排序类型(升序的值)
  2833. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2834. */
  2835. private isSortTypeInRange(baseSortType: number): boolean {
  2836. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2837. }
  2838. private getSortModeItemBackground(isSelected: boolean): ResourceColor {
  2839. if (!isSelected) {
  2840. return Color.Transparent;
  2841. }
  2842. return this.isDarkMode ? '#334967' : '#EAF2FF';
  2843. }
  2844. private getSortOrderItemBackground(isSelected: boolean, isAsc: boolean): ResourceColor {
  2845. if (!isSelected) {
  2846. return Color.Transparent;
  2847. }
  2848. if (isAsc) {
  2849. return this.isDarkMode ? '#295B8A' : '#DCEEFF';
  2850. }
  2851. return this.isDarkMode ? '#7A4D22' : '#FFE9D5';
  2852. }
  2853. showSheelDialog() {
  2854. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2855. // this.showTips()
  2856. // return
  2857. // }
  2858. this.showAddDialog()
  2859. }
  2860. showAddDialog() {
  2861. if (this.modeType === 2 || this.modeType === 3) {
  2862. return
  2863. }
  2864. DialogHelper.showActionSheetDialog({
  2865. title: "请选择添加方式(建议歌词文件一起导入)",
  2866. sheets: [
  2867. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2868. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2869. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2870. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2871. ],
  2872. maskColor: Color.Transparent,
  2873. backgroundColor: $r('app.color.bg_card'),
  2874. transition: AnimationHelper.transitionInDown(555),
  2875. onAction: (index) => {
  2876. switch (index) {
  2877. case 0:
  2878. if (this.modeType === 0) {
  2879. this.showMkDialog()
  2880. } else {
  2881. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2882. }
  2883. break;
  2884. case 1:
  2885. this.callFilePickerSelectFile()
  2886. break;
  2887. case 2:
  2888. this.showTips()
  2889. break;
  2890. case 3:
  2891. this.goSelectMusic()
  2892. break;
  2893. }
  2894. }
  2895. })
  2896. }
  2897. //拉起音频
  2898. goSelectMusic() {
  2899. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2900. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2901. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2902. ) {
  2903. ToastUtil.showToast('暂时不支持该设备')
  2904. return
  2905. }
  2906. try {
  2907. let documentSelectOptions = new picker.DocumentSelectOptions();
  2908. documentSelectOptions.authMode = true
  2909. documentSelectOptions.multiAuthMode = true
  2910. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2911. documentSelectOptions.maxSelectNumber = 20000
  2912. }
  2913. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2914. let documentPicker = new picker.DocumentViewPicker(this.context);
  2915. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2916. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2917. this.saveVideoDatas(documentSelectResult)
  2918. }
  2919. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2920. JSON.stringify(documentSelectResult));
  2921. }).catch((err: BusinessError) => {
  2922. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2923. });
  2924. } catch (error) {
  2925. let err: BusinessError = error as BusinessError;
  2926. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2927. }
  2928. }
  2929. async showTips() {
  2930. try {
  2931. this.getUIContext().getPromptAction().showDialog({
  2932. title: '导入指南',
  2933. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2934. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2935. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2936. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2937. buttons: [
  2938. {
  2939. text: '知道了',
  2940. color: '#000000'
  2941. },
  2942. ]
  2943. }, (err, data) => {
  2944. if (err) {
  2945. console.error('showDialog err: ' + err);
  2946. return;
  2947. }
  2948. console.info('showDialog success callback, click button: ' + data.index);
  2949. });
  2950. } catch (error) {
  2951. let message = (error as BusinessError).message;
  2952. let code = (error as BusinessError).code;
  2953. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2954. };
  2955. }
  2956. showMkDialog() {
  2957. DialogHelper.showTextInputDialog({
  2958. title: '新建歌单',
  2959. maskColor: Color.Transparent,
  2960. text: '',
  2961. transition: AnimationHelper.transitionInDown(666),
  2962. onChange: (text) => {
  2963. console.error("onChange: " + text);
  2964. },
  2965. onAction: (action, dialogId, content) => {
  2966. // ToastUtil.showToast('content = ' +content)
  2967. if (action == DialogAction.TWO) {
  2968. const newName = content
  2969. const newPath = this.currentPath + '/' + newName
  2970. FileUtil.mkdir(newPath, true).then(() => {
  2971. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2972. this.getSortedFiles(this.currentPath)
  2973. }).catch((error: BusinessError) => {
  2974. console.error(error.message);
  2975. });
  2976. }
  2977. }
  2978. })
  2979. }
  2980. @State progress: number = 0;
  2981. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2982. if (ArrayUtil.isEmpty(uris)) {
  2983. return;
  2984. }
  2985. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2986. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2987. this.saveVideoDatasToDownLoad(uris,isOpen)
  2988. return
  2989. }
  2990. // 初始化进度条
  2991. this.progress = 0;
  2992. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2993. progress: this.progress,
  2994. backCancel: false,
  2995. autoCancel: false,
  2996. loadColor: $r('app.color.title_bar_bg'),
  2997. fontColor: $r('app.color.title_bar_bg')
  2998. });
  2999. // 计算处理总数用于进度计算
  3000. const totalItems = uris.length;
  3001. let processedItems = 0;
  3002. for (let i = 0; i < uris.length; i++) {
  3003. let filePath = uris[i];
  3004. try {
  3005. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  3006. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  3007. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  3008. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3009. console.info('onecold saveVideoDatas filePath = ' + filePath)
  3010. if (!filePath.includes(this.rootPath)) {
  3011. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  3012. mediaItem.parentPath = this.currentPath;
  3013. }
  3014. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  3015. this.table.insert(mediaItem, (id: number) => {
  3016. // 插入完成回调
  3017. });
  3018. }
  3019. }
  3020. // 更新进度
  3021. processedItems++;
  3022. this.progress = Math.floor((processedItems / totalItems) * 100);
  3023. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  3024. } catch (error) {
  3025. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  3026. // 即使出错也更新进度
  3027. processedItems++;
  3028. this.progress = Math.floor((processedItems / totalItems) * 100);
  3029. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  3030. }
  3031. }
  3032. // 关闭进度条
  3033. DialogHelper.closeDialog(this.loadingProgressDialogId)
  3034. this.isZero = false
  3035. // 删除目标路径缓存
  3036. setTimeout(() => {
  3037. this.cache.delete(this.currentPath);
  3038. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  3039. this.setButtonStatus()
  3040. }, 500);
  3041. }
  3042. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  3043. if (ArrayUtil.isEmpty(uris)) {
  3044. return;
  3045. }
  3046. let newUris: string[] = [];
  3047. this.progress = 0
  3048. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  3049. progress: this.progress,
  3050. backCancel: false,
  3051. autoCancel: false,
  3052. loadColor: this.themeColor,
  3053. fontColor: this.themeColor
  3054. });
  3055. // 计算所有文件的总大小
  3056. let totalSize = 0;
  3057. for (let uri of uris) {
  3058. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  3059. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  3060. await fileIo.close(sourceFile.fd);
  3061. }
  3062. let totalRead = 0;
  3063. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  3064. Logger.info(TAG, 'destPath uri: ' + destPath);
  3065. for (let i = 0; i < uris.length; i++) {
  3066. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  3067. Logger.info(TAG, 'filePath uri: ' + filePath);
  3068. newUris.push(filePath);
  3069. try {
  3070. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  3071. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  3072. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  3073. const buffer = new ArrayBuffer(buffSize);
  3074. let len = await fileIo.read(sourceFile.fd, buffer);
  3075. while (len > 0) {
  3076. await fileIo.write(destFile.fd, buffer.slice(0, len));
  3077. totalRead += len;
  3078. // 计算总进度
  3079. this.progress = Math.floor((totalRead / totalSize) * 100);
  3080. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  3081. len = await fileIo.read(sourceFile.fd, buffer);
  3082. }
  3083. await fileIo.close(sourceFile.fd);
  3084. await fileIo.close(destFile.fd);
  3085. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  3086. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  3087. let mediaItem: VideoItem =
  3088. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3089. this.table.insert(mediaItem, (id: number) => {
  3090. // 删除目标路径缓存
  3091. this.cache.delete(this.currentPath);
  3092. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  3093. });
  3094. }
  3095. }
  3096. } catch (error) {
  3097. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  3098. }
  3099. }
  3100. DialogHelper.closeDialog(this.loadingProgressDialogId);
  3101. this.isZero = false
  3102. Logger.info(TAG, 'scan select video result:' + newUris)
  3103. }
  3104. //拉起音频
  3105. // goSelectMusic(){
  3106. //
  3107. // try {
  3108. // let audioSelectOptions = new picker.AudioSelectOptions();
  3109. // let audioPicker = new picker.AudioViewPicker(this.context);
  3110. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  3111. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  3112. // this.saveVideoDatas(audioSelectResult)
  3113. // }
  3114. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  3115. // }).catch((err: BusinessError) => {
  3116. //
  3117. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  3118. // });
  3119. // } catch (error) {
  3120. // let err: BusinessError = error as BusinessError;
  3121. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  3122. // }
  3123. //
  3124. //
  3125. //
  3126. // }
  3127. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  3128. if (!item) {
  3129. return undefined;
  3130. }
  3131. try {
  3132. let selectUris: Array<string> = [];
  3133. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  3134. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  3135. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  3136. photoSelectOptions.maxSelectNumber = 1;
  3137. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  3138. selectUris = photoSelectResult.photoUris;
  3139. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  3140. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  3141. console.info('file fd: ' + file.fd);
  3142. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  3143. let imagePath = this.context.filesDir + FileUtil.separator + name
  3144. imagePath = fileUri.getUriFromPath(imagePath)
  3145. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  3146. fileIo.copyFileSync(file.fd, file2.fd)
  3147. fileIo.closeSync(file);
  3148. fileIo.closeSync(file2);
  3149. if (item.filePath == this.currentSong?.filePath) {
  3150. this.cover = imagePath
  3151. if (this.currentSong) {
  3152. this.currentSong.isCustomCover = 1;
  3153. }
  3154. }
  3155. if (item) {
  3156. item.pixelMapPath = imagePath
  3157. item.isCustomCover = 1;
  3158. }
  3159. if (isRemoteCloudType(item.type)) {
  3160. return FileUtil.getFilePath(imagePath);
  3161. }
  3162. this.table.updateCustomCoverPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  3163. if (success) {
  3164. this.doUpdateData()
  3165. console.log("onecold 更新音乐封面成功,数据库已同步");
  3166. } else {
  3167. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  3168. }
  3169. });
  3170. LogUtil.debug("onecold this.cover =" + this.cover)
  3171. return FileUtil.getFilePath(imagePath); // Return the image path here
  3172. } catch (err) {
  3173. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  3174. return undefined;
  3175. }
  3176. }
  3177. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  3178. try {
  3179. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  3180. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  3181. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  3182. photoSelectOptions.maxSelectNumber = 1;
  3183. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  3184. const selectUris = photoSelectResult.photoUris;
  3185. if (!selectUris || selectUris.length === 0) {
  3186. return undefined;
  3187. }
  3188. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  3189. if (!FileUtil.accessSync(coverDir)) {
  3190. FileUtil.mkdirSync(coverDir);
  3191. }
  3192. const sourceUri = selectUris[0];
  3193. const sourceName = FileUtil.getFileName(sourceUri) || '';
  3194. let suffix = '.jpg';
  3195. const dotIndex = sourceName.lastIndexOf('.');
  3196. if (dotIndex >= 0) {
  3197. suffix = sourceName.substring(dotIndex);
  3198. }
  3199. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  3200. const targetPath = coverDir + FileUtil.separator + targetName;
  3201. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  3202. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  3203. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  3204. fileIo.closeSync(sourceFile.fd);
  3205. fileIo.closeSync(targetFile.fd);
  3206. return fileUri.getUriFromPath(targetPath);
  3207. } catch (error) {
  3208. const err = error as BusinessError;
  3209. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  3210. return undefined;
  3211. }
  3212. }
  3213. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  3214. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  3215. ToastUtil.showToast('当前歌曲无效');
  3216. return;
  3217. }
  3218. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  3219. if (StrUtil.isEmpty(sandboxCoverUri)) {
  3220. return;
  3221. }
  3222. const coverUri = sandboxCoverUri as string;
  3223. this.loadingDialogId = DialogHelper.showLoadingDialog();
  3224. try {
  3225. if (isRemoteCloudType(this.currentSong.type)) {
  3226. this.cover = coverUri;
  3227. this.currentSong.pixelMapPath = coverUri;
  3228. this.currentSong.isCustomCover = 1;
  3229. this.syncRemoteManagerSong(this.currentSong);
  3230. await this.persistRemoteMetadataToDb(this.currentSong);
  3231. this.emitRemoteMetadataUpdated(this.currentSong);
  3232. this.currentSong = cloneVideoItem(this.currentSong);
  3233. AppStorage.setOrCreate('currentSong', this.currentSong);
  3234. ToastUtil.showToast('更换封面成功');
  3235. return;
  3236. }
  3237. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  3238. ToastUtil.showToast('当前歌曲类型暂不支持更换封面');
  3239. return;
  3240. }
  3241. const task = new taskpool.Task(
  3242. replaceLocalMusicCoverTask,
  3243. this.context,
  3244. this.currentSong.filePath,
  3245. FileUtil.getFilePath(coverUri)
  3246. );
  3247. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  3248. if (!result) {
  3249. ToastUtil.showToast('更换封面失败');
  3250. return;
  3251. }
  3252. this.cover = coverUri;
  3253. this.currentSong.pixelMapPath = coverUri;
  3254. this.currentSong.isCustomCover = 1;
  3255. await this.doUpateEditedFields(this.currentSong);
  3256. ToastUtil.showToast('更换封面成功');
  3257. } catch (error) {
  3258. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  3259. ToastUtil.showToast('更换封面失败');
  3260. } finally {
  3261. DialogHelper.closeDialog(this.loadingDialogId);
  3262. }
  3263. }
  3264. // 拉起picker选择文件管理器
  3265. async callFilePickerSelectFile(): Promise<void> {
  3266. try {
  3267. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  3268. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  3269. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  3270. } else {
  3271. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  3272. }
  3273. let documentPicker = new picker.DocumentViewPicker();
  3274. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  3275. Logger.info(TAG,
  3276. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  3277. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  3278. this.saveVideoDatas(DocumentSelectResult)
  3279. }
  3280. }).catch((err: BusinessError) => {
  3281. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  3282. });
  3283. } catch (err) {
  3284. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  3285. }
  3286. }
  3287. //重命名的对话框
  3288. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  3289. if(!item.filePath.includes(this.packName)){
  3290. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  3291. return
  3292. }
  3293. DialogHelper.showTextInputDialog({
  3294. title: '重命名',
  3295. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : (item.fileName || item.name),
  3296. maskColor: Color.Transparent,
  3297. backgroundColor: Color.Grey,
  3298. transition: AnimationHelper.transitionInDown(666),
  3299. onChange: (text) => {
  3300. console.error("onChange: " + text);
  3301. },
  3302. onAction: (action, dialogId, content) => {
  3303. // ToastUtil.showToast('content = ' +content)
  3304. if (action == DialogAction.TWO) {
  3305. const newName = content
  3306. const newPath = this.currentPath + '/' + newName
  3307. console.log("onecold item = " + item.type);
  3308. this.doReName(index, newName, filePath, newPath, item)
  3309. }
  3310. }
  3311. })
  3312. }
  3313. //剪切 移动到另个文件夹的对话框
  3314. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3315. Logger.info('onecold showCutDialog')
  3316. let mList: Array<string> = []
  3317. let rPath = this.rootPath
  3318. if (isCurrent) {
  3319. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3320. rPath = this.currentPath
  3321. } else {
  3322. mList = Utility.getNameList(this.dirList);
  3323. rPath = this.rootPath
  3324. }
  3325. let dataBean = new BubbleBean()
  3326. dataBean.data = mList
  3327. dataBean.color = this.themeColor
  3328. dataBean.onItemClick = (i) => {
  3329. const targetName = item.fileName || item.name
  3330. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3331. Logger.info('newPath = ' + newPath)
  3332. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3333. ToastUtil.showToast('移动成功')
  3334. this.table.deleteData(item, () => {
  3335. });
  3336. if (!Utility.isIsoByExtension(newPath)) {
  3337. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3338. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3339. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3340. this.table.insert(newItem, (id: number) => {
  3341. //加入数据库
  3342. });
  3343. }
  3344. }
  3345. this.cache.delete(this.currentPath); // 删除原路径缓存
  3346. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3347. this.getSortedFiles(this.currentPath, true)
  3348. }).catch((error: BusinessError) => {
  3349. console.error(error.message);
  3350. });
  3351. XPopup.dismissTop()
  3352. }
  3353. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3354. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3355. popupPosition = PopupPosition.TOP
  3356. }
  3357. if (index <= 3) {
  3358. popupPosition = PopupPosition.BOTTOM
  3359. }
  3360. let pup: XPopup
  3361. if (this.isDarkMode) {
  3362. pup = XPopup.Builder()
  3363. .setPopupPosition(popupPosition)
  3364. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  3365. .setBackgroundColor(Color.Black)
  3366. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3367. .show()
  3368. } else {
  3369. pup = XPopup.Builder()
  3370. .setPopupPosition(popupPosition)
  3371. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  3372. .setBackgroundColor(Color.White)
  3373. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3374. .show()
  3375. }
  3376. }
  3377. //复制 到另个文件夹的对话框
  3378. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3379. Logger.info('onecoldv showCopyDialog')
  3380. let mList: Array<string> = []
  3381. let rPath = this.rootPath
  3382. if (isCurrent) {
  3383. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3384. rPath = this.currentPath
  3385. } else {
  3386. mList = Utility.getNameList(this.dirList);
  3387. rPath = this.rootPath
  3388. }
  3389. let dataBean = new BubbleBean()
  3390. dataBean.data = mList
  3391. dataBean.isCopy = true
  3392. dataBean.color = this.themeColor
  3393. dataBean.onItemClick = (i) => {
  3394. const targetName = item.fileName || item.name
  3395. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3396. Logger.info('newPath = ' + newPath)
  3397. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3398. ToastUtil.showToast('复制成功')
  3399. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3400. this.getSortedFiles(this.currentPath)
  3401. if (!Utility.isIsoByExtension(newPath)) {
  3402. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3403. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3404. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3405. this.table.insert(newItem, (id: number) => {
  3406. //加入数据库
  3407. });
  3408. }
  3409. }
  3410. }).catch((error: BusinessError) => {
  3411. console.error(error.message);
  3412. });
  3413. XPopup.dismissTop()
  3414. }
  3415. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3416. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3417. popupPosition = PopupPosition.TOP
  3418. }
  3419. if (index <= 3) {
  3420. popupPosition = PopupPosition.BOTTOM
  3421. }
  3422. let pup: XPopup
  3423. if (this.isDarkMode) {
  3424. pup = XPopup.Builder()
  3425. .setPopupPosition(popupPosition)
  3426. .atView(id)
  3427. .setMaxHeight('60%')
  3428. .setBackgroundColor(Color.Black)
  3429. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3430. .show();
  3431. } else {
  3432. pup = XPopup.Builder()
  3433. .setPopupPosition(popupPosition)
  3434. .atView(id)
  3435. .setMaxHeight('60%')
  3436. .setBackgroundColor(Color.White)
  3437. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3438. .show();
  3439. }
  3440. }
  3441. //重命名索引index的视频
  3442. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3443. FileUtil.rename(oldPath, newPath).then(async () => {
  3444. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3445. let refreshedItem: VideoItem = info
  3446. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3447. //如果是文件夹先删除源数据,再添加新数据
  3448. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3449. if (success) {
  3450. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3451. } else {
  3452. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3453. }
  3454. });
  3455. this.scanDirectory(newPath)
  3456. refreshedItem = new VideoItem(newName, newName, newPath, CommonConstants.TYPE_IS_DIR, 0, '')
  3457. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3458. if (Utility.isIsoByExtension(oldPath) || Utility.isIsoByExtension(newPath)) {
  3459. refreshedItem = this.buildLocalIsoItem(newPath, newName)
  3460. } else {
  3461. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3462. if (success) {
  3463. console.log(" onecold 重命名成功,数据库已同步");
  3464. } else {
  3465. console.error(" onecold 重命名数据库失败原因: " + error);
  3466. }
  3467. });
  3468. refreshedItem =
  3469. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3470. }
  3471. } else {
  3472. return
  3473. }
  3474. this.videoLocalList[index] = refreshedItem;
  3475. }
  3476. this.cache.delete(this.currentPath)
  3477. this.cache.delete(oldPath)
  3478. this.cache.delete(newPath)
  3479. this.getSortedFiles(this.currentPath, true)
  3480. }).catch((error: BusinessError) => {
  3481. console.error(error.message);
  3482. });
  3483. }
  3484. build() {
  3485. Stack() {
  3486. this.ContentBuild()
  3487. Stack() {
  3488. Column()
  3489. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3490. height: '95%',
  3491. dragBar: true,
  3492. showClose: true,
  3493. blurStyle: BlurStyle.Thin,
  3494. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3495. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3496. title: {
  3497. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3498. + `(${this.getPlayListDisplayCount()}首)`
  3499. }
  3500. })
  3501. }
  3502. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3503. modalTransition: ModalTransition.DEFAULT,
  3504. onWillDisappear: () => {
  3505. this.setShowPlayFalse()
  3506. },
  3507. })
  3508. }
  3509. .alignContent(Alignment.Bottom)
  3510. .width('100%')
  3511. .height('100%')
  3512. }
  3513. @Builder
  3514. ContentBuild() {
  3515. Scroll() {
  3516. Column() {
  3517. Stack() {
  3518. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3519. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3520. controller: this.xcomponentController })
  3521. .onLoad(async (event?: object) => {
  3522. })
  3523. .focusable(true)
  3524. .height(0)
  3525. .focusOnTouch(true)
  3526. .defaultFocus(true) // 自动获取键盘焦点
  3527. .onKeyEvent((event?: KeyEvent) => {
  3528. console.info('onecold点击 onKeyEvent')
  3529. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3530. if (!event || event.type !== KeyType.Down) {
  3531. return;
  3532. }
  3533. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3534. //空格键 Space key controls pause/play
  3535. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3536. this.playOrPause()
  3537. }
  3538. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3539. this.playPrevious()
  3540. }
  3541. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3542. this.playNext()
  3543. }
  3544. // Right-click to fast forward
  3545. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3546. this.fastForward()
  3547. }
  3548. // Left-click to rewind
  3549. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3550. this.backForward()
  3551. }
  3552. })
  3553. Column() {
  3554. XComponent({
  3555. id: 'xcomponentId',
  3556. type: 'surface',
  3557. libraryname: 'ijkplayer_napi',
  3558. controller: this.xcomponentController
  3559. })
  3560. .onLoad((event?: object) => {
  3561. if (!!event) {
  3562. this.initDelayPlay(event);
  3563. }
  3564. })
  3565. .onDestroy(() => {
  3566. })
  3567. .width('100%')// .width(this.videoWidth)
  3568. .aspectRatio(this.videoAspectRatio)
  3569. }
  3570. .aspectRatio(this.videoAspectRatio)
  3571. .justifyContent(FlexAlign.Center)
  3572. .backgroundColor(Color.Transparent)
  3573. .visibility(Visibility.Hidden)
  3574. .height(CommonConstants.FULL_PERCENT)
  3575. .width(CommonConstants.FULL_PERCENT)
  3576. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3577. height:this.isLandscape?'80%': '43%',
  3578. dragBar: true,
  3579. showClose: true,
  3580. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3581. blurStyle:BlurStyle.Thin,
  3582. backgroundColor:Color.Transparent,
  3583. title: { title: 'AB循环' }
  3584. })
  3585. Stack() {
  3586. Column() {
  3587. if(this.twoFingerType==4){
  3588. this.getWaterView()
  3589. }else{
  3590. if(this.isGridMusic){
  3591. this.getGridView()
  3592. }else {
  3593. this.getListView()
  3594. }
  3595. }
  3596. if (this.modeType ==0||this.modeType==4) {
  3597. Column() {
  3598. emptyView(this.themeColor)
  3599. }
  3600. .padding({ right:6 })
  3601. .onClick(()=>{
  3602. this.asyncCurrentPathOnlyFile()
  3603. })
  3604. .alignItems(HorizontalAlign.Center)
  3605. .position({ top: 200 })
  3606. .justifyContent(FlexAlign.Center)
  3607. .opacity(this.isZero ? 1 : 0)
  3608. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3609. ? Visibility.Visible : Visibility.None)
  3610. .animation({
  3611. duration: 500,
  3612. curve: Curve.Friction // 可选动画曲线
  3613. })
  3614. .width('100%')
  3615. }
  3616. }
  3617. .layoutWeight(1)
  3618. .height('100%')
  3619. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3620. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3621. .onDrop((event?: DragEvent) => {
  3622. try {
  3623. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3624. if (dragData !== undefined) {
  3625. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3626. if (records.length > 0) {
  3627. for (let i = 0; i < records.length; i++) {
  3628. let types = records[i].getTypes();
  3629. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3630. const fileUriUds =
  3631. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3632. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3633. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3634. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3635. this.targetFile = fileUriUds.oriUri;
  3636. this.saveVideoDatas([this.targetFile])
  3637. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3638. }
  3639. }
  3640. }
  3641. } else {
  3642. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3643. }
  3644. } else {
  3645. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3646. }
  3647. } catch (error) {
  3648. const err = error as BusinessError;
  3649. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3650. }
  3651. })
  3652. // 右侧居中的字母表索引
  3653. this.indexBuilder()
  3654. this.topTitleBar()
  3655. }
  3656. .alignContent(Alignment.Top)
  3657. .layoutWeight(1)
  3658. .height('100%')
  3659. Row() {
  3660. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3661. .width(45)
  3662. .height(45)
  3663. .fontSize(10)
  3664. .margin({ top: 10, bottom: 10, right: 6 })
  3665. .backgroundColor(this.themeColor)
  3666. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3667. .onClick(() => {
  3668. if (this.isAllSelected) {
  3669. // 全不选
  3670. this.selectedFiles = [];
  3671. } else {
  3672. // 全选
  3673. this.selectedFiles = [...this.getCurFileList()];
  3674. }
  3675. this.syncLocalSelectionState();
  3676. })
  3677. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3678. .width(72)
  3679. .height(45)
  3680. .fontSize(10)
  3681. .margin({ top: 10, bottom: 10, right: 6 })
  3682. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3683. .backgroundColor(this.themeColor)
  3684. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3685. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3686. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3687. })
  3688. .onClick(() => {
  3689. if (this.hasSelectedDirectories()) {
  3690. ToastUtil.showToast('文件夹不支持批量内嵌标签')
  3691. return
  3692. }
  3693. this.isOneKeyTags = !this.isOneKeyTags
  3694. })
  3695. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3696. .width(45)
  3697. .height(45)
  3698. .fontSize(10)
  3699. .margin({ top: 10, bottom: 10, right: 6 })
  3700. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3701. .backgroundColor(this.themeColor)
  3702. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3703. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3704. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3705. })
  3706. .onClick(() => {
  3707. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3708. if (this.hasSelectedDirectories()) {
  3709. ToastUtil.showToast('文件夹不支持合并')
  3710. return
  3711. }
  3712. if(ArrayUtil.isNotEmpty(selectedMediaFiles)&&Utility.isMerge(selectedMediaFiles,this.packName)){
  3713. this.isMergeAudio = !this.isMergeAudio
  3714. }else{
  3715. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3716. }
  3717. })
  3718. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3719. .width(45)
  3720. .height(45)
  3721. .fontSize(10)
  3722. .margin({ top: 10, bottom: 10, right: 6 })
  3723. .backgroundColor(this.themeColor)
  3724. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3725. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3726. .onClick(async () => {
  3727. this.longItemFilePath = ''
  3728. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3729. if (ArrayUtil.isEmpty(selectedMediaFiles)) {
  3730. ToastUtil.showToast('请先选择音频文件')
  3731. return
  3732. }
  3733. await this.openAddToPlaylistDialog(selectedMediaFiles)
  3734. })
  3735. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3736. // .width(45)
  3737. // .height(45)
  3738. // .fontSize(10)
  3739. // .margin({ top: 10, bottom: 10, right: 6 })
  3740. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3741. // .backgroundColor(this.themeColor)
  3742. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3743. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3744. // })
  3745. // .onClick(() => {
  3746. // this.isFixMessy = !this.isFixMessy
  3747. // })
  3748. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3749. // .width('35%')
  3750. // .height(60)
  3751. // .id('music_cut')
  3752. // .margin({ top: 10, bottom: 10, right: 6 })
  3753. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3754. // .backgroundColor(this.themeColor)
  3755. // .onClick(() => {
  3756. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3757. // })
  3758. //
  3759. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3760. // .width('35%')
  3761. // .height(60)
  3762. // .id('music_cut_current')
  3763. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3764. // .margin({ top: 10, bottom: 10, right: 6 })
  3765. // .backgroundColor(this.themeColor)
  3766. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3767. // .onClick(() => {
  3768. //
  3769. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3770. // })
  3771. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3772. // .width('35%')
  3773. // .height(60)
  3774. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3775. // .margin({ top: 10, bottom: 10, right: 6 })
  3776. // .backgroundColor(this.themeColor)
  3777. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3778. // .onClick(() => {
  3779. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3780. // })
  3781. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3782. .width(45)
  3783. .height(45)
  3784. .fontSize(10)
  3785. .margin({ top: 10, bottom: 10, right: 6 })
  3786. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3787. .backgroundColor(this.themeColor)
  3788. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3789. .onClick(() => {
  3790. this.showWarnIsDelete()
  3791. })
  3792. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3793. .width(45)
  3794. .height(45)
  3795. .fontSize(10)
  3796. .margin({ top: 10, bottom: 10, right: 6 })
  3797. .backgroundColor(this.themeColor)
  3798. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3799. .onClick(() => {
  3800. this.selectedFiles = [];
  3801. this.isAllSelected = false
  3802. this.isMultiSelect = false
  3803. })
  3804. }
  3805. .width('100%')
  3806. .justifyContent(FlexAlign.Center)
  3807. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3808. .opacity(this.isMultiSelect ? 1 : 0)
  3809. .animation({
  3810. duration: 666,
  3811. curve: 'ease-in-out' // 可选动画曲线
  3812. })
  3813. .position({ bottom: 20 }) // 将 Row 固定在底部
  3814. }
  3815. .width('100%')
  3816. .height('100%')
  3817. .alignContent(Alignment.Top)
  3818. }
  3819. .width('100%')
  3820. .height('100%')
  3821. .backgroundImage(this.isMusicCoverHomeBackgroundActive()
  3822. ? this.customizeMusicBgPath
  3823. : (this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background')))
  3824. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3825. .backgroundImagePosition(Alignment.Center)
  3826. .backdropBlur(this.blurValue)
  3827. .backgroundBrightness({ rate: this.isMusicCoverHomeBackgroundActive() || this.isCustomizeBg ? 0.1 : 0,
  3828. lightUpDegree: this.bgBrightness })
  3829. .backgroundBlurStyle(this.isMusicCoverHomeBackgroundActive()
  3830. ? BlurStyle.BACKGROUND_ULTRA_THICK :
  3831. BlurStyle.NONE)
  3832. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3833. }
  3834. }
  3835. //字母表索引
  3836. @Builder
  3837. indexBuilder(){
  3838. Column({space: 5}){
  3839. if(this.showZMIndex&&this.enableShowAlphabet){
  3840. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3841. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3842. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3843. .attributeModifier(this.alphaBetStyle)
  3844. .usingPopup(this.isTouchingAlphaBet)
  3845. .onAreaChange((old_value,new_value)=>{
  3846. this.alphabetHeight = new_value.height as number
  3847. })
  3848. .popupPosition({
  3849. x: 40,
  3850. y: this.alphabetHeight / 2
  3851. })
  3852. .onSelect((index: number) => {
  3853. void this.onSelectIndexItem(this.alphaBet[index])
  3854. })
  3855. .onTouch((event: TouchEvent) =>{
  3856. this.showAlphabetIndex()
  3857. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3858. this.isTouchingAlphaBet = false
  3859. this.hideAlphabetIndexAfterDelay(1500)
  3860. }else{
  3861. this.isTouchingAlphaBet = true
  3862. }
  3863. })
  3864. .transition(
  3865. TransitionEffect.translate({x: 10})
  3866. .combine(TransitionEffect.opacity(0.1))
  3867. .animation({
  3868. duration: 150,
  3869. curve: Curve.EaseInOut,
  3870. })
  3871. )
  3872. }
  3873. }
  3874. if(this.showFindLocation){
  3875. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3876. Blank()
  3877. .layoutWeight(1)
  3878. }
  3879. PointLightDefaultButton({
  3880. isSysBol:true,
  3881. pointColor:Color.Gray,
  3882. imageResource:$r('sys.symbol.local_fill'),
  3883. isPx: false,
  3884. builderHeight: 30,
  3885. builderWidth: 30,
  3886. })
  3887. .onClick(() =>{
  3888. void this.locateCurrentSong();
  3889. })
  3890. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3891. .margin({
  3892. bottom: this.bottomSafeHeight+100,right:10
  3893. })
  3894. }
  3895. }
  3896. .padding({
  3897. bottom: 0
  3898. })
  3899. .margin({right:5})
  3900. .position({x:'92%'})
  3901. .height('100%')
  3902. .justifyContent(FlexAlign.Center)
  3903. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3904. height: '100%',
  3905. dragBar: true,
  3906. showClose: true,
  3907. preferType: SheetType.CENTER ,
  3908. blurStyle: BlurStyle.Thin,
  3909. title: { title: '均衡器' },
  3910. onDisappear: () => {
  3911. this.isEqualizerSheet = false
  3912. }
  3913. })
  3914. }
  3915. async onSelectIndexItem(letter: string) {
  3916. await this.ensureFullListForAlphabetIndex();
  3917. const findTargetIndex = (): number => {
  3918. const songs = this.videoLocalList;
  3919. for (let i = 0; i < songs.length; i++) {
  3920. const song = songs[i];
  3921. let text = this.isShowFileName ? song.fileName :
  3922. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3923. if (this.sortType === 0 || this.sortType == 1) {
  3924. text = song.artist;
  3925. } else if (this.sortType === 2 || this.sortType == 3) {
  3926. text = song.album;
  3927. }
  3928. if (text) {
  3929. const firstPinyin = getFirstLetter(text);
  3930. if (firstPinyin && firstPinyin === letter) {
  3931. return i;
  3932. }
  3933. }
  3934. }
  3935. return -1;
  3936. };
  3937. const targetIndex = findTargetIndex();
  3938. if (targetIndex !== -1) {
  3939. if (this.isGridMusic || this.twoFingerType == 4) {
  3940. this.scroller.scrollToIndex(targetIndex, false);
  3941. } else {
  3942. this.listScroller.scrollToIndex(targetIndex);
  3943. }
  3944. }
  3945. }
  3946. private showAlphabetIndex(): void {
  3947. this.isShowAlphaBet = true;
  3948. if (this.alphaBetHideTimer) {
  3949. clearTimeout(this.alphaBetHideTimer);
  3950. this.alphaBetHideTimer = 0;
  3951. }
  3952. }
  3953. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3954. if (this.alphaBetHideTimer) {
  3955. clearTimeout(this.alphaBetHideTimer);
  3956. }
  3957. this.alphaBetHideTimer = setTimeout(() => {
  3958. if (!this.isTouchingAlphaBet) {
  3959. this.isShowAlphaBet = false;
  3960. }
  3961. this.alphaBetHideTimer = 0;
  3962. }, delayMs) as number;
  3963. }
  3964. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  3965. if (!this.showZMIndex) {
  3966. return;
  3967. }
  3968. if (this.alphaBetRebuildTimer) {
  3969. clearTimeout(this.alphaBetRebuildTimer);
  3970. }
  3971. this.alphaBetRebuildTimer = setTimeout(() => {
  3972. this.alphaBetRebuildTimer = 0;
  3973. if (this.isScrolling) {
  3974. this.alphaBetDirty = true;
  3975. return;
  3976. }
  3977. this.alphaBetDirty = false;
  3978. void this.setAlphaBet();
  3979. }, delayMs) as number;
  3980. }
  3981. private markAlphaBetDirty(): void {
  3982. if (!this.showZMIndex) {
  3983. return;
  3984. }
  3985. if (this.isMediaLibraryWarmupWindow()) {
  3986. this.alphaBetDirty = true;
  3987. this.scheduleAlphaBetRebuild(900);
  3988. return;
  3989. }
  3990. this.alphaBetDirty = true;
  3991. if (!this.isScrolling) {
  3992. this.scheduleAlphaBetRebuild(80);
  3993. }
  3994. }
  3995. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3996. if (this.isLoadingPage) {
  3997. return;
  3998. }
  3999. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  4000. return;
  4001. }
  4002. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  4003. return;
  4004. }
  4005. if (this.modeType !== 0 && this.modeType !== 1) {
  4006. return;
  4007. }
  4008. this.isLoadingPage = true;
  4009. try {
  4010. const options: PageQueryOptions = {
  4011. pageIndex: 0,
  4012. pageSize: this.totalCount,
  4013. sortType: this.sortType,
  4014. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  4015. isShowFileName: this.isShowFileName
  4016. };
  4017. if (this.modeType === 0) {
  4018. options.parentPath = this.currentPath;
  4019. }
  4020. let result: PageQueryResult;
  4021. if (this.modeType === 0) {
  4022. result = await this.table.queryByParentPathPaged(options);
  4023. const dbItems = this.filterOutLocalIsoItems(result.items);
  4024. if (!this.isSearchMode) {
  4025. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  4026. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  4027. result.items = [...directories, ...isoItems, ...dbItems];
  4028. } else {
  4029. result.items = dbItems;
  4030. }
  4031. } else {
  4032. result = await this.table.queryMediaLibraryPaged(options);
  4033. }
  4034. this.videoLocalList = result.items;
  4035. this.dataSource.pushArrayData(this.videoLocalList);
  4036. this.pageCache.clear();
  4037. this.pageHasMoreCache.clear();
  4038. this.pageTotalCountCache.clear();
  4039. this.prefetchingPages.clear();
  4040. this.currentPage = 0;
  4041. this.totalCount = this.modeType === 0 ? result.items.length : result.totalCount;
  4042. this.hasMoreData = false;
  4043. this.lastScrollTriggerPage = -1;
  4044. this.lastVisibleEndIndex = -1;
  4045. this.isPagingTransition = false;
  4046. if (this.pagingScheduleTimer) {
  4047. clearTimeout(this.pagingScheduleTimer);
  4048. this.pagingScheduleTimer = 0;
  4049. }
  4050. if (this.modeType === 1) {
  4051. this.mediaKuCount = result.totalCount;
  4052. }
  4053. this.setButtonStatus();
  4054. this.markAlphaBetDirty();
  4055. } catch (err) {
  4056. const error = err as Error;
  4057. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  4058. } finally {
  4059. this.isLoadingPage = false;
  4060. }
  4061. }
  4062. // 找到对应字母表的索引
  4063. findAlphaBetIndex(song: VideoItem):number{
  4064. let text = this.isShowFileName?song.fileName:
  4065. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  4066. if(this.sortType === 0||this.sortType==1){
  4067. text = song.artist
  4068. }else if(this.sortType === 2||this.sortType==3){
  4069. text = song.album
  4070. }
  4071. if(text){
  4072. let firstLetter = getFirstLetter(text)
  4073. for(let i=0;i<this.alphaBet.length;i++){
  4074. if(this.alphaBet[i] === firstLetter){
  4075. return i
  4076. }
  4077. }
  4078. }
  4079. return 0
  4080. }
  4081. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  4082. const items: Array<AlphaTaskItem> = []
  4083. for (const song of songs) {
  4084. items.push({
  4085. type: song.type,
  4086. name: song.name,
  4087. pyStr: song.pyStr,
  4088. fileName: song.fileName,
  4089. artist: song.artist,
  4090. album: song.album
  4091. })
  4092. }
  4093. return items
  4094. }
  4095. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  4096. const taskItems = this.buildAlphaTaskItems(songs)
  4097. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  4098. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  4099. if (version !== this.alphaBetBuildVersion) {
  4100. return
  4101. }
  4102. this.alphaBet = result
  4103. if (this.videoLocalList.length > 0) {
  4104. this.selectAlphaBetIndex = 0
  4105. }
  4106. }
  4107. async setAlphaBet(){
  4108. if(!this.showZMIndex){
  4109. return
  4110. }
  4111. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  4112. await this.refreshAlphaBetFromMediaLibrary()
  4113. return
  4114. }
  4115. try {
  4116. const songs = this.videoLocalList
  4117. if (songs.length > 40000) {
  4118. this.alphaBet = []
  4119. return
  4120. }
  4121. const version = ++this.alphaBetBuildVersion
  4122. await this.buildAlphaBetByTask(songs, version)
  4123. } catch (e) {
  4124. console.error('testTag','排序字母表出错',JSON.stringify(e))
  4125. }
  4126. }
  4127. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  4128. if (this.totalCount <= 0) {
  4129. return
  4130. }
  4131. if (this.totalCount > 40000) {
  4132. this.alphaBet = []
  4133. return
  4134. }
  4135. const keyword = this.isSearchMode ? this.searchText : ''
  4136. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  4137. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  4138. return
  4139. }
  4140. const result = await this.table.queryMediaLibraryPaged({
  4141. pageIndex: 0,
  4142. pageSize: this.totalCount,
  4143. sortType: this.sortType,
  4144. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  4145. isShowFileName: this.isShowFileName
  4146. })
  4147. const version = ++this.alphaBetBuildVersion
  4148. await this.buildAlphaBetByTask(result.items, version)
  4149. this.alphaBetCacheKey = cacheKey
  4150. }
  4151. @Builder
  4152. topTitleBar(){
  4153. Column() {
  4154. Row({ space: 15 }) {
  4155. if (!this.isSearchMode ) {
  4156. //左侧滑动按钮
  4157. TitleBarPointLightButton({
  4158. iconResource: this.rightTopImage,
  4159. iconSize: 25,
  4160. pointColor: this.themeColor,
  4161. clickScale: 0.6,
  4162. clickHandler: () => {
  4163. this.triggerSwipeBackWithAnimation()
  4164. }
  4165. })
  4166. }else{
  4167. //左侧搜索返回按钮
  4168. TitleBarPointLightButton({
  4169. iconResource: $r('sys.symbol.chevron_left'),
  4170. iconSize: 25,
  4171. pointColor: this.themeColor,
  4172. clickScale: 0.6,
  4173. clickHandler: () => {
  4174. this.isSearchMode = false
  4175. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  4176. this.searchText = ''
  4177. this.getSortedFiles(this.currentPath)
  4178. return
  4179. }
  4180. this.onSearchInput('')
  4181. }
  4182. })
  4183. .margin({bottom:5})
  4184. }
  4185. if (!this.isSearchMode) {
  4186. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  4187. .margin({left:3,right:10})
  4188. .fontColor($r('app.color.text_color'))
  4189. .fontSize(this.twoFingerType==3?17:16)
  4190. .maxLines(1)
  4191. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4192. .layoutWeight(1)
  4193. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4194. }
  4195. //搜索框
  4196. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  4197. .searchButton('搜索',{fontColor:this.themeColor})
  4198. .searchIcon({
  4199. src: $r('sys.media.ohos_ic_public_search_filled')
  4200. })
  4201. .cancelButton({
  4202. style: CancelButtonStyle.CONSTANT,
  4203. icon: {
  4204. src: $r('sys.media.ohos_ic_public_cancel_filled')
  4205. }
  4206. })
  4207. .layoutWeight(1)
  4208. .height(40)
  4209. .maxLength(20)
  4210. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  4211. .placeholderColor(Color.Grey)
  4212. .placeholderFont({ size: 14, weight: 400 })
  4213. .textFont({ size: 14, weight: 400 })
  4214. .onSubmit((value: string) => {
  4215. console.log('onecold onSubmit ='+value)
  4216. this.searchController.stopEditing()
  4217. if(this.modeType==0){
  4218. this.modeType =1//如果是首页 切换到媒体库搜索
  4219. }
  4220. this.commitSearchHistory(value)
  4221. this.onSearchInput(this.searchText);
  4222. })
  4223. .onChange((value: string) => {
  4224. console.log('onecold onChange ='+value)
  4225. if(this.modeType==0){
  4226. this.modeType =1//如果是首页 切换到媒体库搜索
  4227. }
  4228. this.onSearchInput(value);
  4229. })
  4230. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  4231. .animation({ duration: 300, curve: Curve.Ease })
  4232. //搜索按钮
  4233. if (!this.isSearchMode) {
  4234. TitleBarPointLightButton({
  4235. iconResource: $r('sys.symbol.magnifyingglass'),
  4236. iconSize: 25,
  4237. pointColor: this.themeColor,
  4238. clickScale: 0.6,
  4239. clickHandler: () => {
  4240. this.isSearchMode = true
  4241. this.loadSearchHistory()
  4242. }
  4243. })
  4244. //排序按钮
  4245. TitleBarPointLightButton({
  4246. iconResource: $r('sys.symbol.list_number'),
  4247. iconSize: 25,
  4248. pointColor: this.themeColor,
  4249. clickScale: 0.6,
  4250. menuBuilder: () => {
  4251. if ((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)) {
  4252. this.SortMenuForArtistAblumBuilder()
  4253. return
  4254. }
  4255. this.SortMenuBuilder()
  4256. }
  4257. })
  4258. //添加按钮
  4259. TitleBarPointLightButton({
  4260. iconResource: $r('sys.symbol.plus'),
  4261. iconSize: 25,
  4262. pointColor: this.themeColor,
  4263. clickScale: 0.6,
  4264. clickHandler: () => {
  4265. this.showAddSheet = !this.showAddSheet;
  4266. }
  4267. })
  4268. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  4269. .bindSheet($$this.showAddSheet, this.addSheet(), {
  4270. height: SheetSize.FIT_CONTENT,
  4271. dragBar: true,
  4272. showClose: true,
  4273. preferType: SheetType.CENTER ,
  4274. title: {
  4275. title: '导入音乐'
  4276. }
  4277. })
  4278. }
  4279. }
  4280. }
  4281. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  4282. .width('100%')
  4283. .translate({
  4284. x: 0,
  4285. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  4286. })
  4287. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  4288. .animation({
  4289. duration: 240,
  4290. curve: Curve.EaseInOut
  4291. })
  4292. }
  4293. @Builder
  4294. addSheet() {
  4295. Scroll() {
  4296. Column() {
  4297. Column() {
  4298. Row() {
  4299. SymbolGlyph($r('sys.symbol.info_circle'))
  4300. .fontSize(22)
  4301. .fontColor([this.themeColor])
  4302. .alignSelf(ItemAlign.Center)
  4303. .margin({ left: 8 })
  4304. Text('导入音乐复制到DownLoad目录')
  4305. .margin({ left: 8 })
  4306. .fontSize(14)
  4307. .fontColor($r('app.color.text_color'))
  4308. .fontWeight(480)
  4309. .layoutWeight(1)
  4310. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  4311. .selectedColor(this.themeColor)
  4312. .switchPointColor(Color.White)
  4313. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4314. .margin({ right: 2 })
  4315. .onChange((checked: boolean) => {
  4316. this.isCopyFileToDownLoad = checked;
  4317. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  4318. })
  4319. .width(50)
  4320. .height(30);
  4321. }
  4322. .height(72)
  4323. .padding({ left:8,right:8 })
  4324. }
  4325. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4326. .backgroundColor($r('app.color.start_window_background'))
  4327. .borderRadius(15)
  4328. .width('85%')
  4329. .margin({
  4330. top: 10,
  4331. bottom: 10
  4332. })
  4333. .padding(0)
  4334. .border({
  4335. color: Color.White,
  4336. width: 1.8
  4337. })
  4338. Menu() {
  4339. MenuItem({
  4340. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  4341. content: "新建文件夹"
  4342. })
  4343. .backgroundColor($r('app.color.silvery'))
  4344. .border({
  4345. width: { bottom: 1 },
  4346. color: '#12ec5c87'
  4347. })
  4348. .margin(10)
  4349. .height(60)
  4350. .padding({left:15,right:15})
  4351. .onClick(async () => {
  4352. this.showMkDialog()
  4353. this.showAddSheet = !this.showAddSheet
  4354. })
  4355. MenuItem({
  4356. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  4357. content: $r('app.string.import_from_files')
  4358. })
  4359. .padding({left:15,right:15})
  4360. .backgroundColor($r('app.color.silvery'))
  4361. .border({
  4362. width: { bottom: 1 },
  4363. color: '#12ec5c87'
  4364. })
  4365. .margin(10)
  4366. .height(60)
  4367. .onClick(async () => {
  4368. this.callFilePickerSelectFile()
  4369. this.showAddSheet = !this.showAddSheet
  4370. })
  4371. MenuItem({
  4372. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  4373. content: '全选导入'
  4374. // content: '从下载文件夹导入(路径:Download/' +
  4375. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  4376. })
  4377. .padding({left:15,right:15})
  4378. .backgroundColor($r('app.color.silvery'))
  4379. .border({
  4380. width: { bottom: 1 },
  4381. color: '#12ec5c87'
  4382. })
  4383. .margin(10)
  4384. .height(60)
  4385. .onClick(async () => {
  4386. this.goSelectMusic()
  4387. this.showAddSheet = !this.showAddSheet
  4388. })
  4389. MenuItem({
  4390. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  4391. content: '自动导入教程'
  4392. })
  4393. .padding({left:15,right:15})
  4394. .backgroundColor($r('app.color.silvery'))
  4395. .border({
  4396. width: { bottom: 1 },
  4397. color: '#12ec5c87'
  4398. })
  4399. .margin(10)
  4400. .height(60)
  4401. .onClick(async () => {
  4402. this.showTips()
  4403. this.showAddSheet = !this.showAddSheet
  4404. })
  4405. MenuItem({
  4406. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  4407. content: '导入疑问'
  4408. })
  4409. .height(60)
  4410. .padding({left:15,right:15})
  4411. .backgroundColor($r('app.color.silvery'))
  4412. .border({
  4413. width: { bottom: 1 },
  4414. color: '#12ec5c87'
  4415. })
  4416. .margin(10)
  4417. .onClick(async () => {
  4418. this.showProblomTips()
  4419. this.showAddSheet = !this.showAddSheet
  4420. })
  4421. }.attributeModifier(new MenuModifier())
  4422. .margin({bottom:30})
  4423. .width('90%')
  4424. .borderRadius(15)
  4425. }
  4426. .layoutWeight(1)
  4427. }
  4428. }
  4429. async showProblomTips() {
  4430. try {
  4431. this.getUIContext().getPromptAction().showDialog({
  4432. title: '导入疑问',
  4433. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  4434. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  4435. buttons: [
  4436. {
  4437. text: '知道了',
  4438. color: '#000000'
  4439. },
  4440. ]
  4441. }, (err, data) => {
  4442. if (err) {
  4443. console.error('showDialog err: ' + err);
  4444. return;
  4445. }
  4446. console.info('showDialog success callback, click button: ' + data.index);
  4447. });
  4448. } catch (error) {
  4449. let message = (error as BusinessError).message;
  4450. let code = (error as BusinessError).code;
  4451. console.error(`showDialog args error code is ${code}, message is ${message}`);
  4452. };
  4453. }
  4454. @Builder
  4455. TagsContentCoverBuilder() {
  4456. Scroll() {
  4457. Column() {
  4458. TagsContentCover(
  4459. {
  4460. selectedFiles:this.selectedFiles,
  4461. isOneKeyTags:this.isOneKeyTags,
  4462. onSeePath:(path:string)=>{
  4463. this.modeType = 0
  4464. this.deleteCache(path)
  4465. this.getSortedFiles(path)
  4466. },
  4467. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4468. this.isMultiSelect = false
  4469. if(result){//如果嵌入成功,更新数据
  4470. this.listRefreshKey++
  4471. setTimeout(()=>{
  4472. this.doUpdateData()
  4473. },500)
  4474. }
  4475. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4476. if(deleteCache_path){
  4477. this.deleteCache(deleteCache_path)
  4478. }
  4479. }
  4480. }
  4481. )
  4482. }
  4483. }
  4484. .width('100%')
  4485. .height('100%')
  4486. }
  4487. @Builder
  4488. FixMessyViewBuilder() {
  4489. Scroll() {
  4490. Column() {
  4491. FixMessyView(
  4492. {
  4493. selectedFiles:this.selectedFiles,
  4494. isFixMessy:this.isFixMessy,
  4495. onFixResult:(result: boolean)=>{
  4496. this.isMultiSelect = false
  4497. if(result){//如果嵌入成功,更新数据
  4498. this.deleteCache(this.currentPath)
  4499. this.doUpdateData()
  4500. }
  4501. }
  4502. }
  4503. )
  4504. }
  4505. }
  4506. .width('100%')
  4507. .height('100%')
  4508. }
  4509. //剪辑音频
  4510. @Builder
  4511. EditAudioBuilder(item:VideoItem) {
  4512. Scroll() {
  4513. Column() {
  4514. EditAudio(
  4515. {
  4516. mVideoItem:item,
  4517. currentPath:this.currentPath,
  4518. videoUrl:this.videoUrl,
  4519. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4520. currentTime:this.currentTime,
  4521. progressValue:this.progressValue,
  4522. onBack:()=>{
  4523. this.isEditAudio = !this.isEditAudio
  4524. },
  4525. onSeeOutputPath:(outPutPath:string)=>{
  4526. this.isEditAudio = !this.isEditAudio
  4527. this.longItemFilePath = ''
  4528. this.modeType = 0
  4529. this.isShowFileName = true
  4530. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4531. },
  4532. onPlayOrPause:()=>{
  4533. if(this.videoUrl==item.filePath){
  4534. this.playOrPause()
  4535. }else{//如果不是当前播放的,则播放该文件
  4536. this.videoUrl==item.filePath
  4537. this.doPlay(item,0,false,true)
  4538. }
  4539. },
  4540. onSliderChange:(value:number)=>{
  4541. if(this.videoUrl!=item.filePath){
  4542. this.videoUrl==item.filePath
  4543. return
  4544. }
  4545. this.isSeekTo = true;
  4546. this.mDestroyPage = false;
  4547. this.showLoadIng();
  4548. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4549. let seekValue = value * (this.getActiveDuration() / 100);
  4550. this.seekTo(seekValue + "");
  4551. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4552. this.isSeekTo = false;
  4553. },
  4554. onResult:(result: boolean,outPath:string)=>{
  4555. if(result){//如果剪辑成功,更新数据
  4556. this.doUpdateData()
  4557. }else{
  4558. ToastUtil.showToast('剪辑失败')
  4559. }
  4560. }
  4561. }
  4562. )
  4563. }
  4564. }
  4565. .width('100%')
  4566. .height('100%')
  4567. }
  4568. //提取伴奏
  4569. @Builder
  4570. ConverterBuilder(item:VideoItem) {
  4571. Scroll() {
  4572. Column() {
  4573. AudioFormatConverter(
  4574. {
  4575. mVideoItem:item,
  4576. videoUrl:this.videoUrl,
  4577. currentPath:this.currentPath,
  4578. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4579. currentTime:this.currentTime,
  4580. progressValue:this.progressValue,
  4581. onBack:()=>{
  4582. this.isConverter = !this.isConverter
  4583. this.longItemFilePath = ''
  4584. },
  4585. onPlayOrPause:()=>{
  4586. if(this.videoUrl==item.filePath){
  4587. this.playOrPause()
  4588. }else{//如果不是当前播放的,则播放该文件
  4589. this.videoUrl==item.filePath
  4590. this.doPlay(item,0,false,true)
  4591. }
  4592. },
  4593. onSeeOutputPath:(outPutPath:string)=>{
  4594. this.isConverter = !this.isConverter
  4595. this.longItemFilePath = ''
  4596. this.modeType = 0
  4597. this.isShowFileName = true
  4598. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4599. },
  4600. onSliderChange:(value:number)=>{
  4601. if(this.videoUrl!=item.filePath){
  4602. this.videoUrl==item.filePath
  4603. return
  4604. }
  4605. this.isSeekTo = true;
  4606. this.mDestroyPage = false;
  4607. this.showLoadIng();
  4608. let seekValue = value * (this.getActiveDuration() / 100);
  4609. this.seekTo(seekValue + "");
  4610. this.isSeekTo = false;
  4611. },
  4612. onResult:(result: boolean,outPath:string)=>{
  4613. if(result){//如果成功,更新数据
  4614. this.doUpdateData()
  4615. }else{
  4616. ToastUtil.showToast('格式转化失败')
  4617. }
  4618. }
  4619. }
  4620. )
  4621. }
  4622. }
  4623. .width('100%')
  4624. .height('100%')
  4625. }
  4626. //提取伴奏
  4627. @Builder
  4628. ExtractAccBuilder(item:VideoItem) {
  4629. Scroll() {
  4630. Column() {
  4631. ExtractAccompaniment(
  4632. {
  4633. mVideoItem:item,
  4634. currentPath:this.currentPath,
  4635. videoUrl:this.videoUrl,
  4636. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4637. currentTime:this.currentTime,
  4638. progressValue:this.progressValue,
  4639. onBack:()=>{
  4640. this.isExtractAcc = !this.isExtractAcc
  4641. this.longItemFilePath = ''
  4642. },
  4643. onPlayOrPause:()=>{
  4644. if(this.videoUrl==item.filePath){
  4645. this.playOrPause()
  4646. }else{//如果不是当前播放的,则播放该文件
  4647. this.videoUrl==item.filePath
  4648. this.doPlay(item,0,false,true)
  4649. }
  4650. },
  4651. onSeeOutputPath:(outPutPath:string)=>{
  4652. this.isExtractAcc = !this.isExtractAcc
  4653. this.longItemFilePath = ''
  4654. this.modeType = 0
  4655. this.isShowFileName = true
  4656. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4657. },
  4658. onSliderChange:(value:number)=>{
  4659. if(this.videoUrl!=item.filePath){
  4660. this.videoUrl==item.filePath
  4661. return
  4662. }
  4663. this.isSeekTo = true;
  4664. this.mDestroyPage = false;
  4665. this.showLoadIng();
  4666. let seekValue = value * (this.getActiveDuration() / 100);
  4667. this.seekTo(seekValue + "");
  4668. this.isSeekTo = false;
  4669. },
  4670. onResult:(result: boolean,outPath:string)=>{
  4671. if(result){//如果成功,更新数据
  4672. this.doUpdateData()
  4673. }else{
  4674. ToastUtil.showToast('提取伴奏失败')
  4675. }
  4676. }
  4677. }
  4678. )
  4679. }
  4680. }
  4681. .width('100%')
  4682. .height('100%')
  4683. }
  4684. //AI人声分离
  4685. @Builder
  4686. AiBuilder(item:VideoItem) {
  4687. Scroll() {
  4688. Column() {
  4689. AIVoiceSeparation(
  4690. {
  4691. mVideoItem:item,
  4692. videoUrl:this.videoUrl,
  4693. currentPath:this.currentPath,
  4694. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4695. currentTime:this.currentTime,
  4696. progressValue:this.progressValue,
  4697. onBack:()=>{
  4698. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4699. this.longItemFilePath = ''
  4700. },
  4701. onPlayOrPause:()=>{
  4702. if(this.videoUrl==item.filePath||this.isPlaying){
  4703. this.playOrPause()
  4704. }else{//如果不是当前播放的,则播放该文件
  4705. this.videoUrl==item.filePath
  4706. this.doPlay(item,0,false,true)
  4707. }
  4708. },
  4709. onPlayPath:(path:string)=>{
  4710. this.videoUrl==path
  4711. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4712. if(itemP)
  4713. this.doPlay(itemP,0,false,true)
  4714. },
  4715. onSeeOutputPath:(outPutPath:string)=>{
  4716. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4717. this.longItemFilePath = ''
  4718. this.modeType = 0
  4719. this.isShowFileName = true
  4720. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4721. },
  4722. onSliderChange:(value:number)=>{
  4723. if(this.videoUrl!=item.filePath){
  4724. this.videoUrl==item.filePath
  4725. return
  4726. }
  4727. this.isSeekTo = true;
  4728. this.mDestroyPage = false;
  4729. this.showLoadIng();
  4730. let seekValue = value * (this.getActiveDuration() / 100);
  4731. this.seekTo(seekValue + "");
  4732. this.isSeekTo = false;
  4733. },
  4734. onResult:(result: boolean,outPath:string)=>{
  4735. if(result){//如果成功,更新数据
  4736. this.doUpdateData()
  4737. }else{
  4738. ToastUtil.showToast('Ai人声分离失败')
  4739. }
  4740. }
  4741. }
  4742. )
  4743. }
  4744. }
  4745. .width('100%')
  4746. .height('100%')
  4747. }
  4748. //变速变调
  4749. @Builder
  4750. ChangeToneBuilder(item:VideoItem) {
  4751. Scroll() {
  4752. Column() {
  4753. ChangeTone(
  4754. {
  4755. mVideoItem:item,
  4756. currentPath:this.currentPath,
  4757. videoUrl:this.videoUrl,
  4758. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4759. currentTime:this.currentTime,
  4760. progressValue:this.progressValue,
  4761. onBack:()=>{
  4762. this.isChangeTone = !this.isChangeTone
  4763. this.longItemFilePath = ''
  4764. },
  4765. onPlayOrPause:()=>{
  4766. if(this.videoUrl==item.filePath){
  4767. this.playOrPause()
  4768. }else{//如果不是当前播放的,则播放该文件
  4769. this.videoUrl==item.filePath
  4770. this.doPlay(item,0,false,true)
  4771. }
  4772. },
  4773. onSeeOutputPath:(outPutPath:string)=>{
  4774. this.isChangeTone = !this.isChangeTone
  4775. this.longItemFilePath = ''
  4776. this.modeType = 0
  4777. this.isShowFileName = true
  4778. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4779. },
  4780. onSliderChange:(value:number)=>{
  4781. if(this.videoUrl!=item.filePath){
  4782. this.videoUrl==item.filePath
  4783. return
  4784. }
  4785. this.isSeekTo = true;
  4786. this.mDestroyPage = false;
  4787. this.showLoadIng();
  4788. let seekValue = value * (this.getActiveDuration() / 100);
  4789. this.seekTo(seekValue + "");
  4790. this.isSeekTo = false;
  4791. },
  4792. onResult:(result: boolean,outPath:string)=>{
  4793. if(result){//如果成功,更新数据
  4794. this.doUpdateData()
  4795. }else{
  4796. ToastUtil.showToast('变速变调失败')
  4797. }
  4798. }
  4799. }
  4800. )
  4801. }
  4802. }
  4803. .width('100%')
  4804. .height('100%')
  4805. }
  4806. //提取视频中的音频
  4807. @Builder
  4808. extractAudioFromVideoBuilder(item:VideoItem) {
  4809. Scroll() {
  4810. Column() {
  4811. ExtractAudioFromVideo(
  4812. {
  4813. mVideoItem:item,
  4814. currentPath:this.currentPath,
  4815. videoUrl:this.videoUrl,
  4816. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4817. currentTime:this.currentTime,
  4818. progressValue:this.progressValue,
  4819. onBack:()=>{
  4820. this.isExtractAudio = !this.isExtractAudio
  4821. this.longItemFilePath = ''
  4822. },
  4823. onPlayOrPause:()=>{
  4824. if(this.videoUrl==item.filePath){
  4825. this.playOrPause()
  4826. }else{//如果不是当前播放的,则播放该文件
  4827. this.videoUrl==item.filePath
  4828. this.doPlay(item,0,false,true)
  4829. }
  4830. },
  4831. onSeeOutputPath:(outPutPath:string)=>{
  4832. this.isExtractAudio = !this.isExtractAudio
  4833. this.longItemFilePath = ''
  4834. this.modeType = 0
  4835. this.isShowFileName = true
  4836. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4837. },
  4838. onSliderChange:(value:number)=>{
  4839. if(this.videoUrl!=item.filePath){
  4840. this.videoUrl==item.filePath
  4841. return
  4842. }
  4843. this.isSeekTo = true;
  4844. this.mDestroyPage = false;
  4845. this.showLoadIng();
  4846. let seekValue = value * (this.getActiveDuration() / 100);
  4847. this.seekTo(seekValue + "");
  4848. this.isSeekTo = false;
  4849. },
  4850. onResult:(result: boolean,outPath:string)=>{
  4851. if(result){//如果成功,更新数据
  4852. this.doUpdateData()
  4853. }else{
  4854. ToastUtil.showToast('提取音频失败')
  4855. }
  4856. }
  4857. }
  4858. )
  4859. }
  4860. }
  4861. .width('100%')
  4862. .height('100%')
  4863. }
  4864. //合并音频
  4865. @Builder
  4866. MergeAudioBuilder() {
  4867. Scroll() {
  4868. Column() {
  4869. MergeAudio(
  4870. {
  4871. videoUrl:this.videoUrl,
  4872. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4873. currentPath:this.currentPath,
  4874. selectedFiles:this.selectedFiles,
  4875. currentTime:this.currentTime,
  4876. progressValue:this.progressValue,
  4877. onBack:()=>{
  4878. this.isMergeAudio = !this.isMergeAudio
  4879. this.longItemFilePath = ''
  4880. },
  4881. // onPlayPath:(path:string)=>{
  4882. // if(this.videoUrl==item.filePath){
  4883. // this.playOrPause()
  4884. // }else{//如果不是当前播放的,则播放该文件
  4885. // this.videoUrl==item.filePath
  4886. // this.doPlay(item,0,false,true)
  4887. // }
  4888. //
  4889. // },
  4890. onSeeOutputPath:(outPutPath:string)=>{
  4891. this.isMergeAudio = !this.isMergeAudio
  4892. this.longItemFilePath = ''
  4893. this.modeType = 0
  4894. this.isShowFileName = true
  4895. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4896. },
  4897. onResult:(result: boolean,outPath:string)=>{
  4898. if(result){//如果成功,更新数据
  4899. this.doUpdateData()
  4900. }else{
  4901. if(this.selectedFiles.length>=3){
  4902. ToastUtil.showToast('合并数量太多导致失败')
  4903. }else{
  4904. ToastUtil.showToast('合并失败')
  4905. }
  4906. }
  4907. }
  4908. }
  4909. )
  4910. }
  4911. }
  4912. .width('100%')
  4913. .height('100%')
  4914. }
  4915. asyncCurrentPathData() {
  4916. if (this.modeType == 0) {
  4917. workerInstance.postMessage({
  4918. code: 1,
  4919. data1: this.context,
  4920. data2: this.currentPath,
  4921. data3: this.lockPath,
  4922. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4923. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4924. });
  4925. }
  4926. }
  4927. // 处理文件选择的函数
  4928. handleFileSelection(item: VideoItem, checked: boolean) {
  4929. if (!this.isSelectableLocalItem(item)) {
  4930. return
  4931. }
  4932. const exists = this.isLocalItemSelected(item)
  4933. if (checked) {
  4934. if (!exists) {
  4935. this.selectedFiles = [...this.selectedFiles, item];
  4936. }
  4937. } else if (exists) {
  4938. this.selectedFiles = this.selectedFiles.filter(selected => selected.filePath !== item.filePath);
  4939. if (this.selectedFiles.length === 0) {
  4940. this.isAllSelected = false
  4941. }
  4942. }
  4943. this.syncLocalSelectionState()
  4944. }
  4945. private deleteComponentId: number = 0
  4946. private closeDeleteDialog(afterClose?: () => void): void {
  4947. if (this.deleteComponentId > 0) {
  4948. try {
  4949. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4950. } catch (_error) {
  4951. }
  4952. this.deleteComponentId = 0
  4953. }
  4954. if (afterClose) {
  4955. setTimeout(() => {
  4956. afterClose()
  4957. }, 16)
  4958. }
  4959. }
  4960. private resetDeleteSelectionState(): void {
  4961. this.isMultiSelect = false
  4962. this.selectedFiles = []
  4963. this.isAllSelected = false
  4964. }
  4965. private removeDisplayedLocalItemsByKeys(deletedKeys: Set<string>): void {
  4966. for (let index = this.dataSource.dataArray.length - 1; index >= 0; index--) {
  4967. const item = this.dataSource.dataArray[index]
  4968. if (item && deletedKeys.has(item.filePath)) {
  4969. this.dataSource.deleteData(index)
  4970. }
  4971. }
  4972. }
  4973. private async removeDeletedLocalItemsLocally(deletedItems: Array<VideoItem>): Promise<void> {
  4974. if (ArrayUtil.isEmpty(deletedItems) || this.modeType !== 0) {
  4975. return
  4976. }
  4977. const deletedKeys: Set<string> = new Set<string>()
  4978. for (let i = 0; i < deletedItems.length; i++) {
  4979. const item = deletedItems[i]
  4980. if (StrUtil.isNotEmpty(item?.filePath)) {
  4981. deletedKeys.add(item.filePath)
  4982. }
  4983. }
  4984. if (deletedKeys.size <= 0) {
  4985. return
  4986. }
  4987. const nextVideoLocalList = this.videoLocalList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4988. const nextDirList = this.dirList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4989. const nextFilteredList = this.filteredList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4990. const removedCount = this.videoLocalList.length - nextVideoLocalList.length
  4991. this.videoLocalList = nextVideoLocalList
  4992. this.dirList = nextDirList
  4993. this.filteredList = nextFilteredList
  4994. this.removeDisplayedLocalItemsByKeys(deletedKeys)
  4995. if (removedCount > 0 && this.totalCount > 0) {
  4996. this.totalCount = Math.max(0, this.totalCount - removedCount)
  4997. }
  4998. this.pageCache.clear()
  4999. this.pageHasMoreCache.clear()
  5000. this.pageTotalCountCache.clear()
  5001. this.setButtonStatus()
  5002. this.markAlphaBetDirty()
  5003. this.syncLocalSelectionState()
  5004. this.addCache(this.currentPath, nextVideoLocalList)
  5005. if (this.currentPath === this.rootPath) {
  5006. this.addCache(this.currentPath + '_dirList', nextDirList)
  5007. }
  5008. this.deleteStringCache(this.currentPath + '_hash')
  5009. await this.saveCacheToStorage()
  5010. }
  5011. //多选删除文件
  5012. showWarnIsDelete(){
  5013. this.getUIContext().getPromptAction().openCustomDialog({
  5014. builder: () => {
  5015. this.deleteComptentBuilder()
  5016. },
  5017. isModal:true,
  5018. showInSubWindow:false,
  5019. maskColor: Color.Transparent,
  5020. dialogTransition: // 设置弹窗内容显示的过渡效果
  5021. TransitionEffect.translate({ x: 0, y: 120, z: 0 })
  5022. .combine(TransitionEffect.opacity(0.01))
  5023. .animation({ duration: 260, curve: Curve.EaseOut }),
  5024. maskTransition: // 设置蒙层显示的过渡效果
  5025. TransitionEffect.opacity(0)
  5026. .animation({ duration: 220, curve: Curve.EaseOut })
  5027. }).then((dialogId: number) => {
  5028. this.deleteComponentId = dialogId
  5029. })
  5030. .catch((error: BusinessError) => {
  5031. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5032. })
  5033. }
  5034. @Builder
  5035. deleteComptentBuilder(){
  5036. DeleteComptent({
  5037. selectedFiles:this.selectedFiles,
  5038. isPlaylistMode: this.modeType == 4,
  5039. playlistId: this.currentSongListID,
  5040. onCancel:()=>{
  5041. this.closeDeleteDialog(() => {
  5042. this.resetDeleteSelectionState()
  5043. })
  5044. },
  5045. onDeleteResult:(result: boolean)=>{
  5046. const deletedItems = [...this.selectedFiles]
  5047. this.closeDeleteDialog(() => {
  5048. this.resetDeleteSelectionState()
  5049. if(result){//如果删除成功,更新数据
  5050. if (this.modeType == 4) {
  5051. this.doSongListTask()
  5052. } else {
  5053. void this.removeDeletedLocalItemsLocally(deletedItems)
  5054. }
  5055. }
  5056. })
  5057. }
  5058. })
  5059. }
  5060. //多选移动文件
  5061. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5062. Logger.info('onecold showCutDialogForMultipleFiles')
  5063. let mList: Array<string> = []
  5064. let rPath = this.rootPath
  5065. if (isCurrent) {
  5066. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5067. rPath = this.currentPath
  5068. } else {
  5069. mList = Utility.getNameList(this.dirList);
  5070. rPath = this.rootPath
  5071. }
  5072. let dataBean = new BubbleBean();
  5073. dataBean.data = mList;
  5074. dataBean.color = this.themeColor
  5075. dataBean.onItemClick = (i) => {
  5076. const newDirPath = rPath + '/' + mList[i];
  5077. // Logger.info('newDirPath = ' + newDirPath)
  5078. this.selectedFiles.forEach((item) => {
  5079. const targetName = item.fileName || item.name;
  5080. const newPath = newDirPath + '/' + targetName;
  5081. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  5082. ToastUtil.showToast('移动成功');
  5083. this.table.deleteData(item, () => {
  5084. this.cache.delete(this.currentPath); // 删除原路径缓存
  5085. this.cache.delete(newDirPath); // 删除目标路径缓存
  5086. this.getSortedFiles(this.currentPath, true);
  5087. });
  5088. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5089. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5090. if (!Utility.isIsoByExtension(newPath)) {
  5091. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5092. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5093. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5094. this.table.insert(newItem, (id: number) => {
  5095. //加入数据库
  5096. });
  5097. }
  5098. }
  5099. }).catch((error: Error) => {
  5100. console.error(error.message);
  5101. });
  5102. });
  5103. this.isMultiSelect = false
  5104. this.selectedFiles = [];
  5105. this.isAllSelected = false
  5106. XPopup.dismissTop();
  5107. };
  5108. let pup: XPopup
  5109. if (this.isDarkMode) {
  5110. pup = XPopup.Builder()
  5111. .setPopupPosition(PopupPosition.TOP)
  5112. .atView(viewId)
  5113. .setBackgroundColor(Color.Black)
  5114. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5115. .show();
  5116. } else {
  5117. pup = XPopup.Builder()
  5118. .setPopupPosition(PopupPosition.TOP)
  5119. .atView(viewId)
  5120. .setBackgroundColor(Color.White)
  5121. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5122. .show();
  5123. }
  5124. }
  5125. /**
  5126. * 加载所有歌单
  5127. */
  5128. async loadAllPlaylists() {
  5129. try {
  5130. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  5131. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  5132. } catch (error) {
  5133. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  5134. }
  5135. }
  5136. /**
  5137. * 显示添加到歌单对话框
  5138. */
  5139. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  5140. const songs = Array.isArray(items) ? items : [items]
  5141. const musicItems = songs.filter(song =>
  5142. song.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(song))
  5143. if (musicItems.length === 0) {
  5144. ToastUtil.showToast('请选择要添加的歌曲')
  5145. return
  5146. }
  5147. // 加载最新的歌单列表
  5148. await this.loadAllPlaylists()
  5149. showAddToPlaylistDialog(
  5150. musicItems,
  5151. this.allPlaylists,
  5152. async (playlistId: string) => {
  5153. // 添加歌曲到歌单
  5154. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  5155. musicItems.map(song => song.filePath))
  5156. if (success) {
  5157. const count = musicItems.length
  5158. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  5159. // 重新加载歌单列表
  5160. await this.loadAllPlaylists()
  5161. } else {
  5162. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  5163. }
  5164. this.longItemFilePath = ''
  5165. if (this.isMultiSelect) {
  5166. this.isMultiSelect = false
  5167. this.isAllSelected = false
  5168. this.selectedFiles = []
  5169. }
  5170. },
  5171. () => {
  5172. LogUtil.info('取消添加到歌单')
  5173. },
  5174. () => {
  5175. // 创建新歌单
  5176. showCreatePlaylistDialog(
  5177. async (name: string, description: string, coverPath?: string) => {
  5178. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  5179. if (success) {
  5180. ToastUtil.showToast('歌单创建成功')
  5181. // 重新加载歌单列表并打开添加对话框
  5182. await this.loadAllPlaylists()
  5183. await this.openAddToPlaylistDialog(musicItems)
  5184. } else {
  5185. ToastUtil.showToast('歌单创建失败')
  5186. }
  5187. },
  5188. () => {
  5189. // 取消创建歌单
  5190. }
  5191. )
  5192. }
  5193. )
  5194. }
  5195. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  5196. const nextFavList = [...this.favList];
  5197. const itemFavKey = Utility.getFavMatchKey(item);
  5198. const favIndex = nextFavList.findIndex((favItem: VideoItem) => Utility.getFavMatchKey(favItem) === itemFavKey);
  5199. if (isFav === 1) {
  5200. if (favIndex >= 0) {
  5201. nextFavList[favIndex].isFav = 1;
  5202. } else {
  5203. const favItem = cloneVideoItem(item);
  5204. favItem.isFav = 1;
  5205. nextFavList.push(favItem);
  5206. }
  5207. } else if (favIndex >= 0) {
  5208. nextFavList.splice(favIndex, 1);
  5209. }
  5210. this.favList = nextFavList;
  5211. item.isFav = isFav;
  5212. if (this.currentSong && Utility.getFavMatchKey(this.currentSong) === itemFavKey) {
  5213. this.currentSong.isFav = isFav;
  5214. this.isFac = isFav === 1;
  5215. }
  5216. }
  5217. private syncFavoriteStateForPlainList(list: Array<VideoItem> | undefined, targetKey: string, isFav: number): boolean {
  5218. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5219. return false;
  5220. }
  5221. let changed = false;
  5222. for (let index = 0; index < list.length; index += 1) {
  5223. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5224. continue;
  5225. }
  5226. list[index].isFav = isFav;
  5227. changed = true;
  5228. }
  5229. return changed;
  5230. }
  5231. private syncFavoriteStateForVisibleList(list: Array<VideoItem> | undefined, dataSource: LazyDataSource<VideoItem>,
  5232. targetKey: string, isFav: number, removeOnCancel: boolean): boolean {
  5233. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5234. return false;
  5235. }
  5236. let changed = false;
  5237. for (let index = list.length - 1; index >= 0; index -= 1) {
  5238. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5239. continue;
  5240. }
  5241. changed = true;
  5242. if (removeOnCancel) {
  5243. list.splice(index, 1);
  5244. if (index < dataSource.dataArray.length) {
  5245. dataSource.deleteData(index);
  5246. }
  5247. } else {
  5248. list[index].isFav = isFav;
  5249. if (index < dataSource.dataArray.length) {
  5250. dataSource.dataArray[index].isFav = isFav;
  5251. dataSource.notifyDataChange(index);
  5252. }
  5253. }
  5254. }
  5255. return changed;
  5256. }
  5257. private syncFavoriteStateInCaches(targetKey: string, isFav: number): void {
  5258. if (StrUtil.isEmpty(targetKey) || this.cache.size === 0) {
  5259. return;
  5260. }
  5261. let changed = false;
  5262. this.cache.forEach((items: Array<VideoItem>) => {
  5263. for (let index = 0; index < items.length; index += 1) {
  5264. if (Utility.getFavMatchKey(items[index]) !== targetKey) {
  5265. continue;
  5266. }
  5267. items[index].isFav = isFav;
  5268. changed = true;
  5269. }
  5270. });
  5271. if (changed) {
  5272. void this.saveCacheToStorage();
  5273. }
  5274. }
  5275. private syncFavoriteStateAcrossCollections(item: VideoItem, isFav: number): void {
  5276. const targetKey = Utility.getFavMatchKey(item);
  5277. if (StrUtil.isEmpty(targetKey)) {
  5278. return;
  5279. }
  5280. const removeFromCurrentView = this.isFavMusic && isFav === 0;
  5281. const currentViewChanged = this.syncFavoriteStateForVisibleList(this.videoLocalList, this.dataSource, targetKey, isFav,
  5282. removeFromCurrentView);
  5283. this.syncFavoriteStateForVisibleList(this.songList, this.sonDataSource, targetKey, isFav, false);
  5284. this.syncFavoriteStateForPlainList(this.currentSongList, targetKey, isFav);
  5285. this.syncFavoriteStateForPlainList(this.historyList, targetKey, isFav);
  5286. this.syncFavoriteStateForPlainList(this.mediaKuList, targetKey, isFav);
  5287. this.syncFavoriteStateForPlainList(this.artistList, targetKey, isFav);
  5288. this.syncFavoriteStateForPlainList(this.albumList, targetKey, isFav);
  5289. this.syncFavoriteStateForPlainList(this.filteredList, targetKey, isFav);
  5290. this.syncFavoriteStateInCaches(targetKey, isFav);
  5291. if (this.isFavMusic) {
  5292. this.currentTitleCover = ArrayUtil.isNotEmpty(this.favList) ? Utility.getFirstCoverFromList(this.favList) :
  5293. $r('app.media.alt');
  5294. }
  5295. if (currentViewChanged) {
  5296. this.setButtonStatus();
  5297. if (removeFromCurrentView) {
  5298. this.markAlphaBetDirty();
  5299. }
  5300. }
  5301. }
  5302. private syncRemoteFavoriteState(item: VideoItem, isFav: number): void {
  5303. if (!item || !isRemoteCloudType(item.type) || StrUtil.isEmpty(item.filePath)) {
  5304. return;
  5305. }
  5306. const remoteManager = RemoteDriveManager.getInstance();
  5307. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  5308. if (target) {
  5309. target.isFav = isFav;
  5310. }
  5311. }
  5312. doFav(item: VideoItem) {
  5313. LogUtil.info('onecold doFav isFav=' + item.isFav)
  5314. let isFav = 0
  5315. if (Utility.getIsFav(this.favList, item)) {
  5316. isFav = 0
  5317. } else {
  5318. isFav = 1
  5319. }
  5320. const targetFilePath = isRemoteCloudType(item.type) ? (this.resolveRemoteStoragePath(item) || item.filePath) :
  5321. item.filePath;
  5322. const onUpdateSuccess = (): void => {
  5323. this.syncFavStateLocal(item, isFav);
  5324. this.syncRemoteFavoriteState(item, isFav);
  5325. this.syncFavoriteStateAcrossCollections(item, isFav);
  5326. if (isFav === 1) {
  5327. ToastUtil.showToast('收藏成功');
  5328. } else {
  5329. ToastUtil.showToast('取消收藏成功');
  5330. }
  5331. };
  5332. const updateFavorite = (): void => {
  5333. this.table.updateIsFavByFilePath(targetFilePath, isFav, async (result: boolean, error?: string) => {
  5334. if (result) {
  5335. onUpdateSuccess();
  5336. return;
  5337. }
  5338. if (isRemoteCloudType(item.type)) {
  5339. Logger.warn(TAG, `远程歌曲收藏更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  5340. try {
  5341. await this.persistRemoteMetadataToDb(item);
  5342. this.table.updateIsFavByFilePath(targetFilePath, isFav, (retryResult: boolean, retryError?: string) => {
  5343. if (retryResult) {
  5344. onUpdateSuccess();
  5345. } else {
  5346. Logger.error(TAG, `远程歌曲收藏补入库后仍失败: ${targetFilePath}, error=${retryError}`);
  5347. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5348. }
  5349. });
  5350. } catch (persistError) {
  5351. Logger.error(TAG,
  5352. `远程歌曲收藏补入库失败: ${targetFilePath}, error=${(persistError as Error).message}`);
  5353. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5354. }
  5355. return;
  5356. }
  5357. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5358. })
  5359. };
  5360. updateFavorite()
  5361. }
  5362. //多选复制文件
  5363. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5364. console.log('onecold showCopyDialogForMultipleFiles');
  5365. let mList: Array<string> = []
  5366. let rPath = this.rootPath
  5367. if (isCurrent) {
  5368. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5369. rPath = this.currentPath
  5370. } else {
  5371. mList = Utility.getNameList(this.dirList);
  5372. rPath = this.rootPath
  5373. }
  5374. let dataBean = new BubbleBean();
  5375. dataBean.data = mList;
  5376. dataBean.isCopy = true
  5377. dataBean.color = this.themeColor
  5378. dataBean.onItemClick = (i) => {
  5379. const newDirPath = rPath + '/' + mList[i];
  5380. // Logger.info('newDirPath = ' + newDirPath)
  5381. this.selectedFiles.forEach((item) => {
  5382. const targetName = item.fileName || item.name;
  5383. const newPath = newDirPath + '/' + targetName;
  5384. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  5385. ToastUtil.showToast('复制成功');
  5386. this.cache.delete(newDirPath); // 删除目标路径缓存
  5387. this.getSortedFiles(this.currentPath);
  5388. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5389. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5390. if (!Utility.isIsoByExtension(newPath)) {
  5391. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5392. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5393. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5394. this.table.insert(newItem, (id: number) => {
  5395. //加入数据库
  5396. });
  5397. }
  5398. }
  5399. }).catch((error: Error) => {
  5400. console.error(error.message);
  5401. });
  5402. });
  5403. this.isMultiSelect = false
  5404. this.selectedFiles = [];
  5405. this.isAllSelected = false
  5406. XPopup.dismissTop();
  5407. };
  5408. let pup: XPopup
  5409. if (this.isDarkMode) {
  5410. pup = XPopup.Builder()
  5411. .setPopupPosition(PopupPosition.TOP)
  5412. .atView(viewId)
  5413. .setBackgroundColor(Color.Black)
  5414. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5415. .show();
  5416. } else {
  5417. pup = XPopup.Builder()
  5418. .setPopupPosition(PopupPosition.TOP)
  5419. .atView(viewId)
  5420. .setBackgroundColor(Color.White)
  5421. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5422. .show();
  5423. }
  5424. }
  5425. @Builder
  5426. private DirItem(item: VideoItem, index?: number) {
  5427. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5428. Row() {
  5429. SymbolGlyph($r('sys.symbol.folder'))
  5430. .fontSize(this.twoFingerType==3?55:this.twoFingerType==2?50:45)
  5431. .fontColor([this.themeColor])
  5432. .alignSelf(ItemAlign.Center)
  5433. .margin({ left: 20 ,top:8,bottom:8})
  5434. Column() {
  5435. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5436. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5437. .maxLines(1)// .width('88%')
  5438. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  5439. .margin({ left: 10, right: 20 })
  5440. .fontColor($r('app.color.text_color'))
  5441. Row() {
  5442. Text(`${this.getArtistSongCount(item.name)}首`)
  5443. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5444. .padding({ top: 8 })
  5445. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  5446. .fontColor($r('app.color.text_color'))
  5447. .margin({ left: 10 })
  5448. Text(`${this.getAlbumSongCount(item.name)}首`)
  5449. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5450. .padding({ top: 8 })
  5451. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  5452. .fontColor($r('app.color.text_color'))
  5453. .margin({ left: 10 })
  5454. Blank()
  5455. }
  5456. }
  5457. .height('100%')
  5458. .width('100%')
  5459. .justifyContent(FlexAlign.Center)
  5460. .alignItems(HorizontalAlign.Start)
  5461. Blank()
  5462. Checkbox({ name: 'dir_checkbox' + (index ?? -1) })
  5463. .select(this.isLocalItemSelected(item))
  5464. .selectedColor(this.themeColor)
  5465. .shape(CheckBoxShape.CIRCLE)
  5466. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5467. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible : Visibility.None)
  5468. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5469. .margin({ left: 20, top: 8, bottom: 8, right: 18 })
  5470. .width(22)
  5471. .height(22)
  5472. Image($r('app.media.arrow_right'))
  5473. .height(25)
  5474. .alignSelf(ItemAlign.Center)
  5475. .id(item.filePath)
  5476. .visibility(this.isShowAlphaBet || (this.isMultiSelect && this.isSelectableLocalItem(item)) ?
  5477. Visibility.None : Visibility.Visible)
  5478. }
  5479. }
  5480. .backgroundColor(Color.Transparent)
  5481. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5482. .width('98%')
  5483. .reuseId('dir_item')
  5484. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  5485. .opacity(this.opacityItem) // 绑定透明度
  5486. .onTouch((event: TouchEvent) => {
  5487. this.handlePointLightTouch(this.getPointLightItemKey('list_dir', item, index), event)
  5488. })
  5489. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5490. ? new hdsEffect.HdsEffectBuilder()
  5491. .pointLight({
  5492. options: this.getPointLightOptions(this.getPointLightItemKey('list_dir', item, index)),
  5493. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5494. })
  5495. .buildEffect()
  5496. : undefined)
  5497. }
  5498. private refreshDirVisibilitySettings(): void {
  5499. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  5500. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  5501. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  5502. }
  5503. isShowDir(dirName: string) {
  5504. if (dirName === undefined) {
  5505. return true
  5506. }
  5507. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  5508. return this.isShowSimi
  5509. }
  5510. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  5511. return this.isShowFAV
  5512. }
  5513. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  5514. return this.isShowHistory
  5515. }
  5516. return true
  5517. }
  5518. private getPointLightItemKey(prefix: string, item: VideoItem, index?: number): string {
  5519. const itemPath = StrUtil.isNotEmpty(item.filePath) ? item.filePath : `${item.name}_${index ?? -1}`
  5520. return `${prefix}_${itemPath}`
  5521. }
  5522. private handlePointLightTouch(itemKey: string, event: TouchEvent): void {
  5523. if (deviceInfo.sdkApiVersion < 20) {
  5524. return
  5525. }
  5526. if (event.type === TouchType.Down) {
  5527. this.activePointLightItemKey = itemKey
  5528. this.pointLightOptions = {
  5529. color: this.themeColor,
  5530. intensity: 1,
  5531. height: 60
  5532. }
  5533. return
  5534. }
  5535. if ((event.type === TouchType.Up || event.type === TouchType.Cancel) && this.activePointLightItemKey === itemKey) {
  5536. this.activePointLightItemKey = ''
  5537. this.pointLightOptions = undefined
  5538. }
  5539. }
  5540. private getPointLightOptions(itemKey: string): hdsEffect.PointLightOptions | undefined {
  5541. if (this.activePointLightItemKey !== itemKey) {
  5542. return undefined
  5543. }
  5544. return this.pointLightOptions
  5545. }
  5546. @State opacityItem: number = 1; // 控制透明度的状态变量
  5547. @Builder
  5548. private MusicItem(item: VideoItem, index?: number) {
  5549. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5550. Row() {
  5551. Stack() {
  5552. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5553. .fillColor(this.themeColor)
  5554. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5555. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5556. .alt($r('app.media.alt'))
  5557. .borderRadius(this.isCoverRectangle?9:'100%')
  5558. .clip(true)
  5559. .draggable(false)
  5560. .sourceSize({width:38, height:38})
  5561. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5562. // .autoResize(true) // 重采样,可减少内存占用
  5563. .opacity(this.opacityItem)// 绑定透明度
  5564. .margin({ left: 20 })
  5565. .shadow({
  5566. radius: this.isScrolling ? 0 : 10,
  5567. type: ShadowType.BLUR,
  5568. color: 'on_primary'
  5569. })
  5570. .onClick(()=>{
  5571. if (this.isMultiSelect) {
  5572. const isChecked = this.isLocalItemSelected(item);
  5573. this.handleFileSelection(item, !isChecked);
  5574. } else {
  5575. this.doPlay(item,index)
  5576. this.setShowPlayTrue()
  5577. }
  5578. })
  5579. }
  5580. Column() {
  5581. Column() {
  5582. Text(this.isShowFileName?item.fileName :item.name)
  5583. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5584. .maxLines(1)
  5585. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5586. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5587. $r('app.color.text_color'))
  5588. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5589. .padding({right:25})
  5590. .bindPopup(this.longItemFilePath === item.filePath, {
  5591. builder: this.MenuBuilder(item,index,item.filePath),
  5592. placement: Placement.Top,
  5593. // autoCancel: true,
  5594. mask: {color:'#33000000'},
  5595. // popupColor: Color.Yellow,
  5596. enableArrow: false,//是否显示箭头
  5597. showInSubWindow: false,
  5598. onStateChange: (e) => {
  5599. if (!e.isVisible) {
  5600. this.longItemFilePath = ''
  5601. this.tempLyricContent = ''
  5602. }
  5603. }
  5604. })
  5605. Row() {
  5606. Column(){
  5607. Text(item.md5Str?.includes('Lossless')?
  5608. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5609. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5610. .padding({ top: 3,right:6,left:6,bottom:3 })
  5611. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5612. $r('app.color.text_color'))
  5613. .fontWeight(500)
  5614. .borderRadius(12)
  5615. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  5616. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5617. .backgroundColor('#FFC107')
  5618. }
  5619. .padding({ top: 8 })
  5620. Text(StrUtil.isEmpty(item.artist) ? item.duration
  5621. :this.twoFingerType==2? item.artist +' ' + item.duration
  5622. : item.artist + ' ' + item?.duration)
  5623. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5624. .padding({ top: 8 ,right:25})
  5625. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  5626. .maxLines(1)
  5627. .opacity(0.85)
  5628. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  5629. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5630. $r('app.color.text_color'))
  5631. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5632. Blank()
  5633. Text(this.isShowFileName?item.duration:item.size)
  5634. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5635. .padding({ top: 8 })
  5636. .maxLines(1)
  5637. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  5638. ? Visibility.Visible : Visibility.None)
  5639. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5640. Color.Gray)
  5641. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  5642. }
  5643. }
  5644. .height('100%')
  5645. .width('100%')
  5646. .margin({ right: 10 })
  5647. .justifyContent(FlexAlign.Center)
  5648. .alignItems(HorizontalAlign.Start)
  5649. }
  5650. .height('100%')
  5651. .margin({ left: 5 })
  5652. .layoutWeight(1)
  5653. Column() {
  5654. Checkbox({ name: 'checkbox' + index })
  5655. .select(this.isLocalItemSelected(item))
  5656. .selectedColor(this.themeColor)
  5657. .shape(CheckBoxShape.CIRCLE)
  5658. .opacity(this.isMultiSelect ? 1 : 0)
  5659. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  5660. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5661. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  5662. .width(22)
  5663. .height(22)
  5664. PlayingIndicator({
  5665. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  5666. indicatorSize: 18,
  5667. marginRight: 20,
  5668. marginTop: 8,
  5669. marginBottom: 8
  5670. })
  5671. }
  5672. }
  5673. }
  5674. .gesture(LongPressGesture()
  5675. .onAction(async () => {
  5676. //如果是专辑和艺术家的首页,不能长按
  5677. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5678. return
  5679. //如果是我的收藏 最近播放等也不能长按
  5680. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5681. item.name === LocalMusic.STR_HISTORY_MUSIC
  5682. )
  5683. return
  5684. this.longItemFilePath = item.filePath
  5685. this.tempLyricContent = this.supportsLocalAudioActions(item) ? await this.getLyricContent(item) : ''
  5686. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5687. })
  5688. .onActionEnd((event: GestureEvent) => {
  5689. }))
  5690. .backgroundColor(Color.Transparent)
  5691. .width('100%')
  5692. .reuseId('file_item')
  5693. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5694. .onTouch((event: TouchEvent) => {
  5695. this.handlePointLightTouch(this.getPointLightItemKey('list_music', item, index), event)
  5696. })
  5697. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5698. ? new hdsEffect.HdsEffectBuilder()
  5699. .pointLight({
  5700. options: this.getPointLightOptions(this.getPointLightItemKey('list_music', item, index)),
  5701. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5702. })
  5703. .buildEffect()
  5704. : undefined)
  5705. }
  5706. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5707. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5708. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5709. direction: Direction.Ltr,
  5710. buttonPadding:{top:12,bottom:12},
  5711. backgroundColor: Color.Transparent,
  5712. fontSize:14,
  5713. selectedFontSize:15,
  5714. selectedFontColor:Color.White,
  5715. selectedBackgroundColor: this.themeColor,
  5716. localizedTextPadding: {
  5717. end: LengthMetrics.vp(20),
  5718. start: LengthMetrics.vp(20)
  5719. }
  5720. })
  5721. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5722. //当胶囊按钮的选择发生变化时调用此函数
  5723. capsuleSelectedIndexesChanged() {
  5724. this.modeType = this.tabSelectedIndexes[0]
  5725. }
  5726. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5727. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5728. isShowCoverHeader() {
  5729. if (!this.isShowHeader) {
  5730. return false
  5731. }
  5732. if (this.modeType == 0) {
  5733. if (this.isHistory || this.isFavMusic) {
  5734. return true
  5735. }
  5736. if (this.currentPath != this.rootPath) {
  5737. return true
  5738. }
  5739. }
  5740. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5741. }
  5742. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5743. if (this.isCustomizeBg) {
  5744. return ('rgba(255,255,255,0.2)')
  5745. }
  5746. if (this.isDarkMode) {
  5747. return $r('app.color.user_center_card_background')
  5748. }
  5749. return this.currentTitleCover
  5750. }
  5751. // 第二步:popup构造器定义弹框内容
  5752. @Builder popupBuilder() {
  5753. Column({ space: 2 }) {
  5754. Text('友情提示:双指缩放可以放大缩小列表')
  5755. .fontSize(12)
  5756. .fontWeight(FontWeight.Regular)
  5757. .fontColor($r('app.color.text_color'))
  5758. }
  5759. .justifyContent(FlexAlign.SpaceAround)
  5760. .width(220)
  5761. .height(55)
  5762. .padding(15)
  5763. }
  5764. //搜索功能的实现
  5765. @State searchText: string = ''; // 用户输入内容
  5766. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5767. @State isSearchMode: boolean = false
  5768. @State searchHistoryItems: string[] = []
  5769. private readonly searchHistoryScope: string = 'local_music'
  5770. private loadSearchHistory(): void {
  5771. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope)
  5772. }
  5773. private saveSearchHistory(keyword: string): void {
  5774. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword)
  5775. }
  5776. private commitSearchHistory(keyword: string): void {
  5777. const normalized = keyword.trim()
  5778. if (normalized.length === 0) {
  5779. return
  5780. }
  5781. this.saveSearchHistory(normalized)
  5782. }
  5783. private applySearchHistory(keyword: string): void {
  5784. this.searchText = keyword
  5785. this.searchController.stopEditing()
  5786. void this.onSearchInput(keyword)
  5787. }
  5788. // 实时搜索逻辑(带防抖)
  5789. private async onSearchInput(value: string): Promise<void> {
  5790. this.searchText = value.trim();
  5791. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5792. // 歌单模式不走媒体库分页查询,直接在当前歌单中筛选,避免混入非歌单歌曲并打乱顺序。
  5793. if (this.modeType === 4) {
  5794. if (this.searchText === '') {
  5795. this.loadSearchHistory()
  5796. this.filteredList = []
  5797. this.updateListData(this.currentSongList, true, true)
  5798. Logger.info('heanup LocalMusic', `onSearchInput: restore playlist list, count=${this.currentSongList.length}`)
  5799. return
  5800. }
  5801. if (!this.isSearchMode) {
  5802. this.isSearchMode = true
  5803. }
  5804. const filteredSongs = filterPlaylistSongsByKeyword(this.currentSongList, this.searchText)
  5805. this.filteredList = filteredSongs
  5806. this.updateListData(filteredSongs, true, true)
  5807. Logger.info('heanup LocalMusic', `onSearchInput: playlist filter applied, keyword="${this.searchText}", count=${filteredSongs.length}`)
  5808. return
  5809. }
  5810. // 清空搜索文本时保持搜索态,只重置为不带关键词的结果列表
  5811. if (this.searchText === '') {
  5812. this.loadSearchHistory()
  5813. await this.resetAndLoadFirstPage();
  5814. return;
  5815. }
  5816. // 进入搜索模式
  5817. if (!this.isSearchMode) {
  5818. this.isSearchMode = true;
  5819. }
  5820. // 使用数据库分页查询(带搜索条件)
  5821. await this.resetAndLoadFirstPage();
  5822. }
  5823. @Builder
  5824. private SearchHistoryView(): void {
  5825. Column({ space: 10 }) {
  5826. Row() {
  5827. Text('搜索历史')
  5828. .fontSize(14)
  5829. .fontWeight(FontWeight.Medium)
  5830. .fontColor($r('app.color.text_color'))
  5831. Blank()
  5832. Button('清空')
  5833. .fontSize(12)
  5834. .fontColor(this.themeColor)
  5835. .backgroundColor(Color.Transparent)
  5836. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  5837. .onClick(() => {
  5838. SearchHistoryUtil.clear(this.searchHistoryScope)
  5839. this.searchHistoryItems = []
  5840. })
  5841. }
  5842. .width('100%')
  5843. Flex({ wrap: FlexWrap.Wrap }) {
  5844. ForEach(this.searchHistoryItems, (keyword: string) => {
  5845. Button(keyword)
  5846. .fontSize(12)
  5847. .fontColor($r('app.color.text_color'))
  5848. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  5849. .borderRadius(16)
  5850. .margin({ right: 8, bottom: 8 })
  5851. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  5852. .onClick(() => {
  5853. this.applySearchHistory(keyword)
  5854. })
  5855. })
  5856. }
  5857. .width('100%')
  5858. }
  5859. .width('100%')
  5860. .padding({ left: 16, right: 16, top: 10, bottom: 10 })
  5861. }
  5862. @State dragItem: number = -1
  5863. @State scaleItem: number = -1
  5864. @State neighborItem: number = -1
  5865. @State neighborScale: number = -1
  5866. @State offsetY: number = 0
  5867. private dragRefOffset: number = 0
  5868. private ITEM_INTV: number = 78
  5869. scaleSelect(item: number): number {
  5870. if (this.scaleItem === item) {
  5871. return 1.05
  5872. } else if (this.neighborItem === item) {
  5873. return this.neighborScale
  5874. } else {
  5875. return 1
  5876. }
  5877. }
  5878. itemMove(index: number, newIndex: number): void {
  5879. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5880. return;
  5881. }
  5882. let tmp = this.videoLocalList.splice(index, 1);
  5883. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5884. this.dataSource.pushArrayData(this.videoLocalList)
  5885. if(this.modeType==4&&this.playlistTable){
  5886. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5887. }
  5888. }
  5889. //瀑布流布局 支持双指缩放
  5890. @State columns: number = 2;
  5891. @State waterFlowScale: number = 1;
  5892. @State imageScale: number = 1;
  5893. @State waterFlowOpacity: number = 1;
  5894. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5895. private columnChanged: boolean = false;
  5896. private oldColumn: number = this.columns;
  5897. private pinchTime: number = 0;
  5898. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5899. changeColumns(scale: number): void {
  5900. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5901. this.columns--;
  5902. this.columnChanged = true;
  5903. } else if (scale < 1 && this.columns < 4) {
  5904. this.columns++;
  5905. this.columnChanged = true;
  5906. }
  5907. }
  5908. @Builder
  5909. getWaterView(){
  5910. Scroll(this.scroller) {
  5911. Column() {
  5912. Blank().height(this.topSafeHeight + 55)
  5913. WaterFlow({
  5914. scroller:this.waterScroller,
  5915. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5916. }) {
  5917. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5918. FlowItem() {
  5919. this.MusicWaterCardItem(item,index)
  5920. }
  5921. .width('100%')
  5922. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5923. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5924. {
  5925. preview: MenuPreviewMode.IMAGE
  5926. })
  5927. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5928. {
  5929. preview: MenuPreviewMode.IMAGE
  5930. })
  5931. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5932. }
  5933. // .columnsTemplate('repeat(auto-fit, 160)')
  5934. .id('waterflow') // 设置id用于截图
  5935. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5936. .columnsGap(12) // 列间距
  5937. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5938. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5939. .padding({bottom:this.bottomBarHeight+10})
  5940. .scrollBar(BarState.Off)
  5941. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5942. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5943. .edgeEffect(EdgeEffect.None)
  5944. .width('90%')
  5945. .height('100%')
  5946. .opacity(this.waterFlowOpacity)
  5947. .scale({
  5948. x: this.waterFlowScale,
  5949. y: this.waterFlowScale,
  5950. centerX: 0,
  5951. centerY: 0
  5952. })
  5953. .onReachEnd(() => {
  5954. if(this.modeType === 4 )
  5955. return;
  5956. // 触底加载下一页
  5957. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5958. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5959. return;
  5960. }
  5961. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5962. this.scheduleLoadNextPage();
  5963. }
  5964. })
  5965. .onAppear(() => {
  5966. this.scroller.scrollEdge(Edge.Top)
  5967. })
  5968. .nestedScroll({
  5969. scrollForward: NestedScrollMode.PARENT_FIRST,
  5970. scrollBackward: NestedScrollMode.SELF_FIRST
  5971. })
  5972. .priorityGesture(
  5973. PinchGesture()
  5974. .onActionStart((event: GestureEvent) => {
  5975. // 双指捏合手势识别成功时截图
  5976. this.pinchTime = event.timestamp;
  5977. this.columnChanged = false;
  5978. this.oldColumn = this.columns;
  5979. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5980. if (error) {
  5981. console.info('error:' + JSON.stringify(error));
  5982. return;
  5983. }
  5984. this.waterFlowSnapshot = pixmap;
  5985. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5986. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5987. if (this.oldColumn ===4) {
  5988. this.twoFingerType =3
  5989. this.isGridMusic = true
  5990. }else if (this.oldColumn ===1) {
  5991. this.twoFingerType =1
  5992. this.isGridMusic = false
  5993. }
  5994. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5995. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5996. return;
  5997. }
  5998. })
  5999. })
  6000. .onActionUpdate((event: GestureEvent) => {
  6001. // 手势更新:处理缩放逻辑和视觉效果
  6002. // 边界限制:防止超出列数范围时继续缩放
  6003. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  6004. return;
  6005. }
  6006. // 节流处理:避免过于频繁的更新,提升性能
  6007. if (event.timestamp - this.pinchTime < 10000000) {
  6008. return;
  6009. }
  6010. this.pinchTime = event.timestamp;
  6011. this.waterFlowScale = event.scale;
  6012. this.imageScale = event.scale;
  6013. // 根据缩放比例设置WaterFlow透明度
  6014. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  6015. this.waterFlowOpacity *= 3;
  6016. if (!this.columnChanged) {
  6017. this.changeColumns(event.scale);
  6018. }
  6019. // 列数改变后的缩放比例调整:避免出现空白区域
  6020. if (this.columnChanged) {
  6021. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  6022. // 限制缩放范围,确保视觉效果自然
  6023. if (event.scale < 1) {
  6024. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  6025. } else {
  6026. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  6027. }
  6028. }
  6029. })
  6030. .onActionEnd((event: GestureEvent) => {
  6031. // 手势结束:执行归位动画并保存状态
  6032. // 执行归位动画:平滑过渡到正常状态
  6033. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  6034. this.waterFlowScale = 1;
  6035. this.waterFlowOpacity = 1;
  6036. })
  6037. // 持久化保存当前列数:下次启动时恢复
  6038. PreferencesUtil.putSync('lastColumns', this.columns);
  6039. })
  6040. )
  6041. .onScrollFrameBegin((offset: number) => {
  6042. this.markGridWaterScrollingActive()
  6043. // 获取当前滚动偏移量
  6044. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  6045. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  6046. this.updateTitleBarByScrollOffset(currentOffsetY)
  6047. return { offsetRemain: offset };
  6048. })
  6049. }
  6050. }
  6051. .scrollBar(BarState.Off)
  6052. }
  6053. //瀑布流卡片布局
  6054. @Builder
  6055. private MusicWaterCardItem(item: VideoItem, index: number) {
  6056. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6057. Stack() {
  6058. Column() {
  6059. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  6060. .backgroundImageSize(ImageSize.Auto)
  6061. .borderRadius({
  6062. topLeft: 12,
  6063. topRight : 12,
  6064. bottomLeft: 0,
  6065. bottomRight: 0
  6066. })
  6067. .draggable(false)// 禁止长按手势拖动
  6068. .autoResize(true) // 重采样,可减少内存占用
  6069. .sourceSize({
  6070. width: this.getCoverThumbTargetSize(true),
  6071. height: this.getCoverThumbTargetSize(true)
  6072. })
  6073. .width('100%')
  6074. .height('auto')
  6075. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6076. .objectFit(ImageFit.Cover)
  6077. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6078. height: '99%' ,
  6079. dragBar: true,
  6080. onDisappear: () => {
  6081. this.longItemFilePath = '';
  6082. this.tempLyricContent = ''
  6083. },
  6084. showClose: true,
  6085. preferType: SheetType.CENTER ,
  6086. title: { title: '编辑标签' }
  6087. })
  6088. .draggable(false)
  6089. .opacity(this.opacityItem)// 绑定透明度
  6090. .margin({
  6091. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6092. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6093. })
  6094. Column() {
  6095. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6096. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  6097. .maxLines(1)
  6098. .fontWeight(FontWeight.Bold)
  6099. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6100. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6101. height: '95%',
  6102. dragBar: true,
  6103. showClose: true,
  6104. onDisappear: () => {
  6105. this.longItemFilePathDetail = '';
  6106. },
  6107. blurStyle:BlurStyle.Thin,
  6108. backgroundColor:Color.Transparent,
  6109. preferType: SheetType.CENTER ,
  6110. title: { title: '详情' }
  6111. })
  6112. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6113. $r('app.color.text_color'))
  6114. Column() {
  6115. Text(`${this.getArtistSongCount(item.name)}首`)
  6116. .fontSize(11)
  6117. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6118. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6119. .fontColor($r('app.color.text_color'))
  6120. Text(`${this.getAlbumSongCount(item.name)}首`)
  6121. .fontSize(11)
  6122. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6123. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6124. .fontColor($r('app.color.text_color'))
  6125. Row(){
  6126. Column(){
  6127. Text(item.md5Str?.includes('Lossless')?
  6128. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6129. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  6130. .padding({ top: 3,right:6,left:6,bottom:3 })
  6131. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6132. $r('app.color.text_color'))
  6133. .fontWeight(500)
  6134. .borderRadius(12)
  6135. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6136. .backgroundColor('#FFC107')
  6137. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6138. }
  6139. .margin({ top: 2 ,right:6})
  6140. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6141. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6142. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6143. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  6144. .maxLines(1)
  6145. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  6146. .margin({ top: 2})
  6147. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6148. || item.type == CommonConstants.TYPE_IS_ALBUM
  6149. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6150. .fontWeight(FontWeight.Medium)
  6151. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6152. $r('app.color.text_color'))
  6153. }
  6154. }
  6155. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6156. }
  6157. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  6158. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  6159. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  6160. .width('100%')
  6161. .justifyContent(FlexAlign.Center)
  6162. .margin({
  6163. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6164. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6165. })
  6166. }
  6167. .width('100%')
  6168. .borderRadius(12)
  6169. .backgroundColor($r('app.color.com_bg'))
  6170. Checkbox({ name: 'checkbox' + index })
  6171. .select(this.isLocalItemSelected(item))
  6172. .selectedColor(this.themeColor)
  6173. .shape(CheckBoxShape.CIRCLE)
  6174. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6175. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6176. Visibility.None)
  6177. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6178. .margin({ left: 20, top: 8, bottom: 8 })
  6179. .width(38)
  6180. .height(38)
  6181. }
  6182. }
  6183. .backgroundColor(Color.Transparent)
  6184. .width('100%')
  6185. .height('auto')
  6186. .padding({top:2})
  6187. .shadow({
  6188. radius: this.isScrolling ? 0 : 8,
  6189. type: ShadowType.BLUR,
  6190. color: 'on_primary'
  6191. })
  6192. .reuseId('card_item')
  6193. .onTouch((event: TouchEvent) => {
  6194. this.handlePointLightTouch(this.getPointLightItemKey('water_music', item, index), event)
  6195. })
  6196. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6197. ? new hdsEffect.HdsEffectBuilder()
  6198. .pointLight({
  6199. options: this.getPointLightOptions(this.getPointLightItemKey('water_music', item, index)),
  6200. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6201. })
  6202. .buildEffect()
  6203. : undefined)
  6204. .onClick(() => {
  6205. if (this.isMultiSelect) {
  6206. if (this.isSelectableLocalItem(item)) {
  6207. const isChecked = this.isLocalItemSelected(item);
  6208. this.handleFileSelection(item, !isChecked);
  6209. }
  6210. return
  6211. }
  6212. this.doPlay(item, index)
  6213. })
  6214. }
  6215. // Grid布局的开始
  6216. private dragRefOffSetX: number = 0;
  6217. private dragRefOffSetY: number = 0;
  6218. private FIX_VP_X: number = 180;
  6219. private FIX_VP_Y: number = 84;
  6220. isDraggable(index: number): boolean {
  6221. return index >= 0;
  6222. }
  6223. getRowEnd(item: number) {
  6224. if (item.toString() === '0') {
  6225. return 1;
  6226. } else {
  6227. return 0;
  6228. }
  6229. }
  6230. isInLeft(index: number) {
  6231. return index % 2 == 0;
  6232. }
  6233. down(index: number): void {
  6234. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  6235. return;
  6236. }
  6237. this.offsetY -= this.FIX_VP_Y;
  6238. this.dragRefOffSetY += this.FIX_VP_Y;
  6239. this.itemMove(index, index + 1);
  6240. }
  6241. up(index: number): void {
  6242. if (!this.isDraggable(index - 2)) {
  6243. return;
  6244. }
  6245. this.offsetY += this.FIX_VP_Y;
  6246. this.dragRefOffSetY -= this.FIX_VP_Y;
  6247. this.itemMove(index, index - 1);
  6248. }
  6249. left(index: number): void {
  6250. if (this.isInLeft(index)) {
  6251. return;
  6252. }
  6253. if (!this.isDraggable(index - 1)) {
  6254. return;
  6255. }
  6256. this.offsetX += this.FIX_VP_X;
  6257. this.dragRefOffSetX -= this.FIX_VP_X;
  6258. this.itemMove(index, index - 1)
  6259. }
  6260. right(index: number): void {
  6261. if (!this.isInLeft(index)) {
  6262. return;
  6263. }
  6264. if (!this.isDraggable(index + 1)) {
  6265. return;
  6266. }
  6267. this.offsetX -= this.FIX_VP_X;
  6268. this.dragRefOffSetX += this.FIX_VP_X;
  6269. this.itemMove(index, index + 1)
  6270. }
  6271. private scroller: Scroller = new Scroller();
  6272. private waterScroller: Scroller = new Scroller();
  6273. private startIndex: number = 0
  6274. private endIndex: number = 0
  6275. @State scaleValue: number = 1
  6276. @State pinchValue: number = 1
  6277. layoutOptionsForHeader: GridLayoutOptions = {
  6278. regularSize: [1, 1], // 只支持[1, 1]
  6279. irregularIndexes: [0], // 索引为0的GridItem占用一行
  6280. };
  6281. @Builder
  6282. getGridView() {
  6283. Grid(this.scroller, this.layoutOptionsForHeader) {
  6284. GridItem() {
  6285. Column(){
  6286. Blank().height(this.topSafeHeight + 45)
  6287. }
  6288. }
  6289. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6290. GridItem() {
  6291. Stack() {
  6292. this.MusicItemGrid(item, index)
  6293. }
  6294. }
  6295. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  6296. {
  6297. preview: MenuPreviewMode.IMAGE
  6298. })
  6299. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  6300. {
  6301. preview: MenuPreviewMode.IMAGE
  6302. })
  6303. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  6304. // TransitionEffect.scale({ x: 0, y: 0 })))
  6305. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6306. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  6307. .zIndex(this.dragItem === index ? 1 : 0)
  6308. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  6309. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6310. }
  6311. .width('94%')
  6312. .height('100%')
  6313. .editMode(true)
  6314. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  6315. .reuseId('grid_item')
  6316. .layoutWeight(1)
  6317. .scrollBar(BarState.Off)
  6318. .supportAnimation(false)
  6319. .onReachEnd(() => {
  6320. if(this.modeType === 4 )
  6321. return;
  6322. // 触底加载下一页
  6323. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6324. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6325. return;
  6326. }
  6327. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6328. this.scheduleLoadNextPage();
  6329. }
  6330. })
  6331. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  6332. .columnsTemplate(
  6333. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  6334. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  6335. )
  6336. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  6337. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  6338. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6339. .gesture(PinchGesture({ fingers: 2 })
  6340. .onActionEnd((event: GestureEvent) => {
  6341. this.setGridTwoFingers()
  6342. })
  6343. .onActionUpdate(e => {
  6344. this.scaleValue = this.pinchValue * e.scale
  6345. })
  6346. .onActionStart(e => {
  6347. }))
  6348. .enableScrollInteraction(true)
  6349. .onScrollIndex((start: number, end: number) => {
  6350. this.startIndex = start
  6351. this.endIndex = end
  6352. this.gridVisibleStart = start
  6353. this.gridVisibleEnd = end
  6354. this.lastVisibleEndIndex = end
  6355. this.warmupGridWaterVisibleThumbs(start, end, false)
  6356. const now = Date.now()
  6357. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  6358. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  6359. this.gridScrollPagingCheckAt = now
  6360. this.gridScrollLastPagingEnd = end
  6361. this.tryTriggerLoadNextPageByScroll(end)
  6362. }
  6363. })
  6364. .onScrollFrameBegin((offset: number) => {
  6365. this.markGridWaterScrollingActive()
  6366. const currentOffsetY = this.scroller.currentOffset().yOffset;
  6367. this.updateTitleBarByScrollOffset(currentOffsetY)
  6368. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6369. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6370. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6371. if (this.isScrollHide) {
  6372. this.setBarHeightHide2(offset)
  6373. } else {
  6374. this.setBarHeightNormal()
  6375. }
  6376. } else {
  6377. this.setBarHeightHide(offset)
  6378. }
  6379. return { offsetRemain: offset };
  6380. })
  6381. }
  6382. @State targetFile: string = '';
  6383. setGridTwoFingers() {
  6384. this.pinchValue = this.scaleValue;
  6385. Logger.info('this.pinchValue = ' + this.pinchValue);
  6386. if (this.pinchValue >= 1) {
  6387. this.twoFingerType++
  6388. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6389. if(this.twoFingerType >= 4){
  6390. this.twoFingerType = 4//切换成瀑布流
  6391. this.columns = 4
  6392. }
  6393. } else {
  6394. this.twoFingerType--
  6395. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6396. if (this.twoFingerType < 1) {
  6397. this.twoFingerType = 3
  6398. this.isGridMusic = false
  6399. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6400. }
  6401. }
  6402. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6403. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6404. this.pinchValue = 1;
  6405. this.scaleValue = 1;
  6406. }
  6407. @State longItemFilePath: string = ''
  6408. @State tempLyricContent: string = ''
  6409. @State editingItem: VideoItem | null = null
  6410. @Builder
  6411. private MusicItemGrid(item: VideoItem, index: number) {
  6412. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6413. Stack() {
  6414. Column() {
  6415. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  6416. .height(this.getGridHeight())
  6417. .width(this.getGridWight())
  6418. .draggable(false)
  6419. .autoResize(true) // 重采样,可减少内存占用
  6420. .sourceSize({
  6421. width: this.getCoverThumbTargetSize(false),
  6422. height: this.getCoverThumbTargetSize(false)
  6423. })
  6424. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6425. .clip(true)
  6426. .borderRadius({
  6427. topLeft: 12,
  6428. topRight: 12,
  6429. bottomLeft: 0,
  6430. bottomRight: 0
  6431. })
  6432. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6433. height: '99%' ,
  6434. dragBar: true,
  6435. onDisappear: () => {
  6436. this.longItemFilePath = '';
  6437. this.tempLyricContent = ''
  6438. },
  6439. showClose: true,
  6440. preferType: SheetType.CENTER ,
  6441. title: { title: '编辑标签' }
  6442. })
  6443. .draggable(false)
  6444. .opacity(this.opacityItem)// 绑定透明度
  6445. .margin({
  6446. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6447. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6448. })
  6449. Column() {
  6450. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  6451. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6452. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  6453. .maxLines(1)
  6454. .fontWeight(FontWeight.Bold)
  6455. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6456. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6457. height: '100%',
  6458. dragBar: true,
  6459. showClose: true,
  6460. onDisappear: () => {
  6461. this.longItemFilePathDetail = '';
  6462. },
  6463. blurStyle:BlurStyle.Thin,
  6464. backgroundColor:Color.Transparent,
  6465. preferType: SheetType.CENTER ,
  6466. title: { title: '详情' }
  6467. })
  6468. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6469. $r('app.color.text_color'))
  6470. Column() {
  6471. Text(`${this.getArtistSongCount(item.name)}首`)
  6472. .fontSize(11)
  6473. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6474. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6475. .fontColor($r('app.color.text_color'))
  6476. Text(`${this.getAlbumSongCount(item.name)}首`)
  6477. .fontSize(11)
  6478. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6479. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6480. .fontColor($r('app.color.text_color'))
  6481. Row(){
  6482. Column(){
  6483. Text(item.md5Str?.includes('Lossless')?
  6484. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6485. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  6486. .padding({ top: 3,right:6,left:6,bottom:3 })
  6487. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6488. $r('app.color.text_color'))
  6489. .fontWeight(500)
  6490. .borderRadius(12)
  6491. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6492. .backgroundColor('#FFC107')
  6493. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6494. }
  6495. .margin({ top: 2 ,right:6})
  6496. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6497. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6498. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6499. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  6500. .maxLines(1)
  6501. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  6502. .margin({ top: 2})
  6503. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6504. || item.type == CommonConstants.TYPE_IS_ALBUM
  6505. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6506. .fontWeight(FontWeight.Medium)
  6507. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6508. $r('app.color.text_color'))
  6509. }
  6510. }
  6511. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6512. }
  6513. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  6514. .width(this.getGridWight())
  6515. .justifyContent(FlexAlign.Center)
  6516. .margin({
  6517. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6518. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6519. })
  6520. }
  6521. .width(this.getGridWight())
  6522. .borderRadius(12)
  6523. .backgroundColor($r('app.color.com_bg'))
  6524. Checkbox({ name: 'checkbox' + index })
  6525. .select(this.isLocalItemSelected(item))
  6526. .selectedColor(this.themeColor)
  6527. .shape(CheckBoxShape.CIRCLE)
  6528. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6529. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6530. Visibility.None)
  6531. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6532. .margin({ left: 20, top: 8, bottom: 8 })
  6533. .width(38)
  6534. .height(38)
  6535. }
  6536. }
  6537. .backgroundColor(Color.Transparent)
  6538. .width('100%')
  6539. .padding({ top: 15 })
  6540. .height(this.getGridAllHeight())
  6541. .onTouch((event: TouchEvent) => {
  6542. this.handlePointLightTouch(this.getPointLightItemKey('grid_music', item, index), event)
  6543. })
  6544. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6545. ? new hdsEffect.HdsEffectBuilder()
  6546. .pointLight({
  6547. options: this.getPointLightOptions(this.getPointLightItemKey('grid_music', item, index)),
  6548. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6549. })
  6550. .buildEffect()
  6551. : undefined)
  6552. .onClick(() => {
  6553. if (this.isMultiSelect) {
  6554. if (this.isSelectableLocalItem(item)) {
  6555. const isChecked = this.isLocalItemSelected(item);
  6556. this.handleFileSelection(item, !isChecked);
  6557. }
  6558. return
  6559. }
  6560. this.doPlay(item, index)
  6561. })
  6562. }
  6563. getGridAllHeight() {
  6564. let heightG = 222
  6565. switch (this.twoFingerType) {
  6566. case 1:
  6567. heightG = 143
  6568. break;
  6569. case 2:
  6570. heightG = 178
  6571. break;
  6572. case 3:
  6573. heightG = 222
  6574. break;
  6575. }
  6576. return heightG
  6577. }
  6578. getGridHeight() {
  6579. let heightG = 150
  6580. switch (this.twoFingerType) {
  6581. case 1:
  6582. heightG = 80
  6583. break;
  6584. case 2:
  6585. heightG = 110
  6586. break;
  6587. case 3:
  6588. heightG = 150
  6589. break;
  6590. }
  6591. return heightG
  6592. }
  6593. getGridWight() {
  6594. let wightG = 158
  6595. switch (this.twoFingerType) {
  6596. case 1:
  6597. wightG = 80
  6598. break;
  6599. case 2:
  6600. wightG = 110
  6601. break;
  6602. case 3:
  6603. wightG = 158
  6604. break;
  6605. }
  6606. return wightG
  6607. }
  6608. @State isShowDetail:boolean = false
  6609. @State longItemFilePathDetail:string =''
  6610. @Builder
  6611. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  6612. if(
  6613. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  6614. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6615. item.name === LocalMusic.STR_HISTORY_MUSIC)
  6616. ){
  6617. //如果是专辑和艺术家的首页,不能长按
  6618. //如果是我的收藏 最近播放等也不能长按
  6619. }else{
  6620. Scroll() {
  6621. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  6622. Menu() {
  6623. MenuItem({
  6624. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  6625. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  6626. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  6627. })
  6628. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6629. .onClick(() => {
  6630. if (item) {
  6631. this.doFav(item)
  6632. }
  6633. this.longItemFilePath = ''
  6634. })
  6635. MenuItem({
  6636. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  6637. content: '下一首播放'
  6638. })
  6639. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6640. .onClick(() => {
  6641. this.addToNextPlay(item);
  6642. this.longItemFilePath = ''
  6643. })
  6644. MenuItem({
  6645. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6646. content: '添加到歌单'
  6647. })
  6648. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6649. .onClick(async () => {
  6650. this.longItemFilePath = ''
  6651. await this.openAddToPlaylistDialog(item)
  6652. })
  6653. MenuItem({
  6654. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  6655. content: '编辑标签'
  6656. })
  6657. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  6658. height: '99%',
  6659. dragBar: true,
  6660. showClose: true,
  6661. preferType: SheetType.CENTER ,
  6662. title: { title: '编辑标签' }
  6663. })
  6664. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6665. .onClick(async() => {
  6666. this.initEditFields(item)
  6667. this.tempLyricContent = await this.getLyricContent(item);
  6668. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  6669. this.lyricConStr = this.tempLyricContent
  6670. }
  6671. if(this.isGridMusic||this.twoFingerType==4){
  6672. this.longItemFilePath = item.filePath
  6673. }else{
  6674. this.isShowEdit = !this.isShowEdit;
  6675. }
  6676. })
  6677. MenuItem({
  6678. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  6679. content: $r('app.string.select_all')
  6680. })
  6681. .onClick(() => {
  6682. this.longItemFilePath = ''
  6683. this.enterLocalMultiSelect(item)
  6684. })
  6685. MenuItem({
  6686. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6687. content: '提取ISO文件'
  6688. })
  6689. .visibility(this.isIsoLocalFile(item) ? Visibility.Visible : Visibility.None)
  6690. .onClick(async () => {
  6691. this.longItemFilePath = ''
  6692. await this.openIsoArchiveDialog(item)
  6693. })
  6694. MenuItem({
  6695. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  6696. content: $r('app.string.edit_audio')
  6697. })
  6698. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  6699. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6700. })
  6701. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6702. .onClick(() => {
  6703. this.isEditAudio = !this.isEditAudio
  6704. })
  6705. MenuItem({
  6706. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  6707. content: $r('app.string.extract_accompaniment')
  6708. })
  6709. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  6710. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6711. })
  6712. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6713. .onClick(() => {
  6714. if (!Utility.isNoble()) {
  6715. this.showVipDialog()
  6716. return
  6717. }
  6718. this.isExtractAcc = !this.isExtractAcc
  6719. })
  6720. MenuItem({
  6721. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  6722. content: $r('app.string.converter_audio')
  6723. })
  6724. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  6725. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6726. })
  6727. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6728. .onClick(() => {
  6729. if (!Utility.isNoble()) {
  6730. this.showVipDialog()
  6731. return
  6732. }
  6733. this.isConverter = !this.isConverter
  6734. })
  6735. // MenuItem({
  6736. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  6737. // content: $r('app.string.vocal_separation')
  6738. // })
  6739. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  6740. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6741. // })
  6742. // .onClick(() => {
  6743. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  6744. // })
  6745. MenuItem({
  6746. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  6747. content: $r('app.string.change_tone')
  6748. })
  6749. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  6750. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6751. })
  6752. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6753. .onClick(() => {
  6754. this.isChangeTone = !this.isChangeTone
  6755. })
  6756. if(Utility.isVideoByExtension(item.filePath)){
  6757. MenuItem({
  6758. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  6759. content: $r('app.string.extract_audio')
  6760. })
  6761. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  6762. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6763. })
  6764. .onClick(() => {
  6765. this.isExtractAudio = !this.isExtractAudio
  6766. })
  6767. }
  6768. MenuItem({
  6769. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  6770. content: $r('app.string.set_ring')
  6771. })
  6772. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6773. .onClick(async () => {
  6774. await PermissionUtil.activatePermission(item.filePath)
  6775. // if(item.filePath.includes(this.packName)){
  6776. setRingTone(this.context, item.filePath,item.name)
  6777. // }else{
  6778. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  6779. // }
  6780. this.longItemFilePath = ''
  6781. })
  6782. MenuItem({
  6783. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  6784. content: $r('app.string.rename')
  6785. })
  6786. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6787. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6788. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6789. .onClick(() => {
  6790. this.showReNameDialog(item, index + '', filePath)
  6791. this.longItemFilePath = ''
  6792. })
  6793. MenuItem({
  6794. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  6795. content: $r('app.string.delete')
  6796. })
  6797. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6798. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6799. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6800. .onClick(() => {
  6801. this.selectSingleItemForDelete(item)
  6802. this.showWarnIsDelete()
  6803. this.longItemFilePath = ''
  6804. })
  6805. MenuItem({
  6806. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6807. content: $r('app.string.detail')
  6808. })
  6809. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6810. height:'100%',
  6811. dragBar: true,
  6812. showClose: true,
  6813. blurStyle:BlurStyle.Thin,
  6814. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6815. backgroundColor:Color.Transparent,
  6816. title: { title: '详情信息' }
  6817. })
  6818. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6819. .onClick(() => {
  6820. if(this.isGridMusic||this.twoFingerType==4){
  6821. this.longItemFilePathDetail = item.filePath
  6822. }else{
  6823. this.isShowDetail = !this.isShowDetail
  6824. }
  6825. })
  6826. MenuItem({
  6827. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6828. content: $r('app.string.share')
  6829. })
  6830. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6831. .onClick(() => {
  6832. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6833. this.longItemFilePath = ''
  6834. })
  6835. }
  6836. .font({ size: 14, weight: FontWeight.Normal })
  6837. }
  6838. .width(180)
  6839. }
  6840. .height('auto')
  6841. .enableScrollInteraction(true)
  6842. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6843. }
  6844. }
  6845. private listMaxScrollOffsetY: number = 0
  6846. private selectedIndex: number = -1
  6847. setlistTwoFingers() {
  6848. this.pinchValue = this.scaleValue;
  6849. Logger.info('this.pinchValue = ' + this.pinchValue);
  6850. if (this.pinchValue >= 1) {
  6851. this.twoFingerType++
  6852. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6853. if (this.twoFingerType > 3) {
  6854. this.twoFingerType = 1
  6855. this.isGridMusic = true
  6856. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6857. }
  6858. } else {
  6859. this.twoFingerType--
  6860. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6861. if (this.twoFingerType < 1) {
  6862. this.twoFingerType = 4
  6863. this.columns = 1
  6864. }
  6865. }
  6866. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6867. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6868. this.pinchValue = 1;
  6869. this.scaleValue = 1;
  6870. }
  6871. @Builder
  6872. getList(){
  6873. Stack() {
  6874. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6875. this.getListView()
  6876. }
  6877. .pullDownRatio(this.ratioL)
  6878. .pullToRefresh(true)
  6879. .refreshOffset(0)
  6880. .onOffsetChange((offset: number) => {
  6881. // 越接近最大距离,下拉跟手系数越小。
  6882. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6883. })
  6884. .onStateChange((refreshStatus: RefreshStatus) => {
  6885. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6886. })
  6887. .onRefreshing(async () => {
  6888. if(this.modeType==0){
  6889. this.getHistoryList(false)
  6890. this.asyncCurrentPathOnlyFile()
  6891. }else if(this.modeType == 1){
  6892. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6893. }else if(this.modeType == 2){
  6894. workerInstance.postMessage({ code: 3, data: this.context });
  6895. }else if(this.modeType == 3){
  6896. workerInstance.postMessage({ code: 4, data: this.context });
  6897. }else if(this.modeType == 4){
  6898. this.doSongListTask()
  6899. }
  6900. console.log('onRefreshing test');
  6901. })
  6902. if (this.isLoadingPage) {
  6903. Row() {
  6904. LoadingProgress()
  6905. .width(24)
  6906. .height(24)
  6907. .color(this.themeColor)
  6908. Text('加载中...')
  6909. .margin({ left: 8 })
  6910. .fontSize(13)
  6911. .fontColor($r('app.color.text_color'))
  6912. }
  6913. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6914. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6915. .borderRadius(16)
  6916. .align(Alignment.Bottom)
  6917. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6918. }
  6919. }
  6920. }
  6921. // 扫描当前目录下的文件,不扫描子目录
  6922. asyncCurrentPathOnlyFile(){
  6923. if(this.modeType==0){
  6924. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6925. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6926. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6927. if(this.modeType==0){
  6928. setTimeout(()=>{
  6929. this.isRefreshing =false
  6930. this.deleteCache(this.currentPath)
  6931. this.getSortedFiles(this.currentPath)
  6932. },500)
  6933. }
  6934. }).catch((e:object)=>{
  6935. this.isRefreshing =false
  6936. console.info("onecold task1 catch e: " + e);
  6937. })
  6938. }
  6939. }
  6940. @Builder
  6941. getListView() {
  6942. List({ scroller: this.listScroller }) {
  6943. // ListItemGroup({ header: this.coverHeader() }) {
  6944. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6945. ListItem() {
  6946. Column() {
  6947. if (item.type === CommonConstants.TYPE_IS_DIR
  6948. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6949. this.DirItem(item, index)
  6950. } else {
  6951. this.MusicItem(item, index)
  6952. }
  6953. }
  6954. }
  6955. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6956. .swipeAction((
  6957. ((this.isSwipe && !this.isScrolling) &&
  6958. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6959. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6960. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6961. edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6962. .onClick(() => {
  6963. if (this.isMultiSelect) {
  6964. if (this.isSelectableLocalItem(item)) {
  6965. const isChecked = this.isLocalItemSelected(item);
  6966. this.handleFileSelection(item, !isChecked);
  6967. }
  6968. return
  6969. }
  6970. this.doPlay(item, index)
  6971. })
  6972. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6973. }
  6974. .onScrollStart(() => {
  6975. this.isScrolling = true
  6976. this.listVisibleStart = -1
  6977. this.listVisibleEnd = -1
  6978. this.listScrollAlphaCheckAt = 0
  6979. this.listScrollPagingCheckAt = 0
  6980. this.listScrollLastAlphaStart = -1
  6981. this.listScrollLastPagingEnd = -1
  6982. if (this.alphaBetRebuildTimer) {
  6983. clearTimeout(this.alphaBetRebuildTimer)
  6984. this.alphaBetRebuildTimer = 0
  6985. }
  6986. this.showAlphabetIndex()
  6987. })
  6988. .onScrollIndex((start: number,center:number,end:number) => {
  6989. this.selectedIndex = start
  6990. this.listVisibleStart = start
  6991. this.listVisibleEnd = end
  6992. this.lastVisibleEndIndex = end
  6993. if (!this.isMediaLibraryWarmupWindow()) {
  6994. this.warmupListVisibleThumbs(start, end)
  6995. }
  6996. const now = Date.now()
  6997. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  6998. if (!this.isMediaLibraryWarmupWindow() &&
  6999. start >= 0 && start < this.videoLocalList.length &&
  7000. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  7001. this.listScrollAlphaCheckAt = now
  7002. this.listScrollLastAlphaStart = start
  7003. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  7004. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  7005. this.selectAlphaBetIndex = nextAlphaIndex
  7006. }
  7007. }
  7008. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  7009. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  7010. this.listScrollPagingCheckAt = now
  7011. this.listScrollLastPagingEnd = end
  7012. this.tryTriggerLoadNextPageByScroll(end)
  7013. }
  7014. })
  7015. .onScrollStop(() => {
  7016. if(this.isScrolling){
  7017. this.isScrolling = false
  7018. }
  7019. this.flushPendingCoverThumbRefresh()
  7020. if (this.alphaBetDirty) {
  7021. this.scheduleAlphaBetRebuild(0)
  7022. }
  7023. this.hideAlphabetIndexAfterDelay(1500)
  7024. })
  7025. .onReachEnd(() => {
  7026. if(this.modeType === 4 )//歌单不能加载下一页
  7027. return;
  7028. // 触底加载下一页
  7029. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  7030. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  7031. return;
  7032. }
  7033. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  7034. this.scheduleLoadNextPage();
  7035. }
  7036. })
  7037. .scrollBar(BarState.Off)
  7038. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7039. .gesture(PinchGesture({ fingers: 2 })
  7040. .onActionEnd((event: GestureEvent) => {
  7041. this.setlistTwoFingers()
  7042. })
  7043. .onActionUpdate(e => {
  7044. this.scaleValue = this.pinchValue * e.scale
  7045. })
  7046. .onActionStart(e => {
  7047. }))
  7048. .contentStartOffset(this.topSafeHeight + 55)
  7049. .scrollBar(BarState.Off)
  7050. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  7051. .cachedCount(this.modeType == 1 ? 4 : 8)
  7052. // .reuseId('list_item')
  7053. .borderRadius(20)
  7054. .layoutWeight(1)
  7055. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  7056. .lanes(
  7057. new BreakpointType<number>({
  7058. sm: 1,
  7059. md: 2,
  7060. lg: 2,
  7061. xl: 3,
  7062. xxl: 4
  7063. }).getValue(this.currentBreakpoint),
  7064. new BreakpointType<number>({
  7065. sm: 0,
  7066. md: 12,
  7067. lg: 12,
  7068. xl: 16,
  7069. xxl: 20
  7070. }).getValue(this.currentBreakpoint)
  7071. )
  7072. .onAreaChange((oldValue: Area, newValue: Area) => {
  7073. this.listArea = newValue
  7074. if (this.twoFingerType == 3) {
  7075. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  7076. } else if (this.twoFingerType == 2) {
  7077. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  7078. } else if (this.twoFingerType == 1) {
  7079. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  7080. }
  7081. })
  7082. .onScrollFrameBegin((offset: number) => {
  7083. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  7084. this.updateTitleBarByScrollOffset(currentOffsetY)
  7085. return { offsetRemain: offset };
  7086. })
  7087. }
  7088. setBarHeightNormal() {
  7089. this.hideDone = false;
  7090. this.getUIContext().animateTo({
  7091. duration: 300
  7092. }, () => {
  7093. this.bottomBarHeight = 68 + 0;
  7094. this.topBarHeight = 50 + 0;
  7095. this.barOpacity = 1;
  7096. this.barBottomOpacity = 1
  7097. this.currentYOffset = 0;
  7098. this.isHiding = false;
  7099. });
  7100. }
  7101. setBarHeightHide(offset: number) {
  7102. if (offset > 0 && !this.hideDone) {
  7103. this.currentYOffset += offset;
  7104. if (this.currentYOffset <= 100) {
  7105. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  7106. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7107. this.barOpacity = 1 - this.currentYOffset / 100;
  7108. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  7109. } else {
  7110. this.topBarHeight = 0;
  7111. this.bottomBarHeight = 0;
  7112. this.barBottomOpacity = 0
  7113. this.barOpacity = 0;
  7114. this.hideDone = true;
  7115. }
  7116. this.isHiding = true;
  7117. }
  7118. if (offset < 0 && this.isHiding) {
  7119. this.hideDone = false;
  7120. this.getUIContext().animateTo({
  7121. duration: 300
  7122. }, () => {
  7123. this.bottomBarHeight = 68 + 0;
  7124. this.topBarHeight = 50 + 0;
  7125. this.barOpacity = 1;
  7126. this.barBottomOpacity = 1
  7127. this.currentYOffset = 0;
  7128. this.isHiding = false;
  7129. });
  7130. }
  7131. }
  7132. //这个方法没隐藏bottomBar,只隐藏topbar
  7133. setBarHeightHide2(offset: number) {
  7134. if (offset > 0 && !this.hideDone) {
  7135. this.currentYOffset += offset;
  7136. if (this.currentYOffset <= 100) {
  7137. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7138. this.barOpacity = 1 - this.currentYOffset / 100;
  7139. } else {
  7140. this.topBarHeight = 0;
  7141. this.barOpacity = 0;
  7142. this.hideDone = true;
  7143. }
  7144. this.isHiding = true;
  7145. }
  7146. if (offset < 0 && this.isHiding) {
  7147. this.hideDone = false;
  7148. this.getUIContext().animateTo({
  7149. duration: 300
  7150. }, () => {
  7151. this.topBarHeight = 50 + 0;
  7152. this.barOpacity = 1;
  7153. this.currentYOffset = 0;
  7154. this.isHiding = false;
  7155. });
  7156. }
  7157. }
  7158. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  7159. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  7160. switch (item.type) {
  7161. case CommonConstants.TYPE_IS_DIR:
  7162. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  7163. let shouldScrollTopNow = true
  7164. let offsetB = 0
  7165. if(this.twoFingerType==4){
  7166. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7167. let cur = this.waterScroller.currentOffset()
  7168. if (cur && typeof cur.yOffset === 'number') {
  7169. offsetB = cur.yOffset
  7170. }
  7171. }
  7172. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  7173. }else
  7174. if (this.isGridMusic) {
  7175. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7176. let cur = this.scroller.currentOffset()
  7177. if (cur && typeof cur.yOffset === 'number') {
  7178. offsetB = cur.yOffset
  7179. }
  7180. }
  7181. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  7182. } else {
  7183. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7184. let cur = this.listScroller.currentOffset()
  7185. if (cur && typeof cur.yOffset === 'number') {
  7186. offsetB = cur.yOffset
  7187. }
  7188. }
  7189. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  7190. }
  7191. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  7192. this.showVerifyDialog()
  7193. this.currentTitleName = '私密音频'
  7194. this.currentTitleCover = $r('app.media.alt')
  7195. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  7196. this.titleName = '最近播放'
  7197. this.currentTitleCover = $r('app.media.alt')
  7198. this.currentTitleName = '最近播放'
  7199. //加载动画效果
  7200. this.updateListData(this.historyList, true)
  7201. // this.videoLocalList = this.historyList
  7202. if (ArrayUtil.isEmpty(this.historyList)) {
  7203. ToastUtil.showToast('最近播放记录空空如也')
  7204. } else {
  7205. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  7206. }
  7207. this.isHistory = true
  7208. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  7209. this.titleName = '我的收藏'
  7210. this.currentTitleName = '我的收藏'
  7211. this.currentTitleCover = $r('app.media.alt')
  7212. //加载动画效果
  7213. this.updateListData(this.favList, true)
  7214. if (ArrayUtil.isEmpty(this.favList)) {
  7215. ToastUtil.showToast('无音乐收藏记录')
  7216. } else {
  7217. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  7218. }
  7219. this.isFavMusic = true
  7220. } else {
  7221. this.currentTitleName = item.name
  7222. this.currentPath = item.filePath
  7223. this.currentTitleCover = $r('app.media.alt')
  7224. shouldScrollTopNow = false
  7225. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  7226. }
  7227. //进入歌单的时候的滚动位置在顶部
  7228. if (shouldScrollTopNow) {
  7229. if(this.twoFingerType==4){
  7230. setTimeout(() => {
  7231. this.waterScroller.scrollEdge(Edge.Top)
  7232. this.scroller.scrollEdge(Edge.Top)
  7233. }, 200)
  7234. }else{
  7235. if (this.isGridMusic) {
  7236. this.scroller.scrollToIndex(0,false)
  7237. }else{
  7238. this.listScroller.scrollToIndex(0,false)
  7239. }
  7240. }
  7241. }
  7242. this.rightTopImage = $r('sys.symbol.chevron_left')
  7243. break;
  7244. case CommonConstants.TYPE_IS_ARTIST:
  7245. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  7246. let offsetA = 0
  7247. if(this.twoFingerType==4){
  7248. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7249. let cur = this.waterScroller.currentOffset()
  7250. if (cur && typeof cur.yOffset === 'number') {
  7251. offsetA = cur.yOffset
  7252. }
  7253. }
  7254. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  7255. }else
  7256. if (this.isGridMusic) {
  7257. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7258. let cur = this.scroller.currentOffset()
  7259. if (cur && typeof cur.yOffset === 'number') {
  7260. offsetA = cur.yOffset
  7261. }
  7262. }
  7263. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  7264. } else {
  7265. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7266. let cur = this.listScroller.currentOffset()
  7267. if (cur && typeof cur.yOffset === 'number') {
  7268. offsetA = cur.yOffset
  7269. }
  7270. }
  7271. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  7272. }
  7273. // 进入艺术家详情页前,先加载详情页的排序类型
  7274. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7275. const artistOriginalIsCanBack = this.isCanBack;
  7276. this.isCanBack = true;
  7277. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  7278. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  7279. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  7280. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7281. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  7282. let mList = this.artistMap.get(artistCacheKey)
  7283. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  7284. // 使用详情页的排序类型查询
  7285. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  7286. if (ArrayUtil.isNotEmpty(mList)) {
  7287. this.artistMap.set(artistCacheKey, mList);
  7288. }
  7289. }
  7290. // 设置当前排序类型为详情页排序
  7291. this.sortType = artistDetailSortType;
  7292. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  7293. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  7294. const nextArtistCountMap = new Map(this.artistSongCountMap);
  7295. nextArtistCountMap.set(item.name, mList.length);
  7296. this.artistSongCountMap = nextArtistCountMap;
  7297. this.isCanBack = true
  7298. this.hasMoreData = false
  7299. this.isLoadingPage = false
  7300. this.pageCache.clear()
  7301. this.pageHasMoreCache.clear()
  7302. this.pageTotalCountCache.clear()
  7303. this.prefetchingPages.clear()
  7304. this.lastScrollTriggerPage = -1
  7305. this.lastVisibleEndIndex = -1
  7306. this.isPagingTransition = false
  7307. if (this.pagingScheduleTimer) {
  7308. clearTimeout(this.pagingScheduleTimer)
  7309. this.pagingScheduleTimer = 0
  7310. }
  7311. this.totalCount = mList.length
  7312. this.titleName = item.name
  7313. this.currentTitleName = '艺术家:' + item.name
  7314. if (item.pixelMapPath) {
  7315. this.currentTitleCover = item.pixelMapPath
  7316. }
  7317. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7318. } else {
  7319. ToastUtil.showToast('未找到该艺术家的歌曲');
  7320. return;
  7321. }
  7322. this.rightTopImage = $r('sys.symbol.chevron_left')
  7323. //进入歌单的时候的滚动位置在顶部
  7324. if(this.twoFingerType==4){
  7325. setTimeout(() => {
  7326. this.waterScroller.scrollEdge(Edge.Top)
  7327. this.scroller.scrollEdge(Edge.Top)
  7328. }, 380)
  7329. }else{
  7330. if (this.isGridMusic) {
  7331. this.scroller.scrollEdge(Edge.Top)
  7332. }else{
  7333. this.listScroller.scrollEdge(Edge.Top)
  7334. }
  7335. }
  7336. break;
  7337. case CommonConstants.TYPE_IS_ALBUM:
  7338. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  7339. let offset = 0
  7340. if(this.twoFingerType==4){
  7341. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7342. let cur = this.waterScroller.currentOffset()
  7343. if (cur && typeof cur.yOffset === 'number') {
  7344. offset = cur.yOffset
  7345. }
  7346. }
  7347. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  7348. }else
  7349. if (this.isGridMusic) {
  7350. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7351. let cur = this.scroller.currentOffset()
  7352. if (cur && typeof cur.yOffset === 'number') {
  7353. offset = cur.yOffset
  7354. }
  7355. }
  7356. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  7357. } else {
  7358. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7359. let cur = this.listScroller.currentOffset()
  7360. if (cur && typeof cur.yOffset === 'number') {
  7361. offset = cur.yOffset
  7362. }
  7363. }
  7364. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  7365. }
  7366. // 进入专辑详情页前,先加载详情页的排序类型
  7367. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7368. const albumOriginalIsCanBack = this.isCanBack;
  7369. this.isCanBack = true;
  7370. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  7371. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  7372. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  7373. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7374. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  7375. let albumList = this.albumMap.get(albumCacheKey)
  7376. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  7377. // 使用详情页的排序类型查询
  7378. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  7379. if (ArrayUtil.isNotEmpty(albumList)) {
  7380. this.albumMap.set(albumCacheKey, albumList);
  7381. }
  7382. }
  7383. // 设置当前排序类型为详情页排序
  7384. this.sortType = albumDetailSortType;
  7385. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  7386. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  7387. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  7388. nextAlbumCountMap.set(item.name, albumList.length);
  7389. this.albumSongCountMap = nextAlbumCountMap;
  7390. this.isCanBack = true
  7391. this.hasMoreData = false
  7392. this.isLoadingPage = false
  7393. this.pageCache.clear()
  7394. this.pageHasMoreCache.clear()
  7395. this.pageTotalCountCache.clear()
  7396. this.prefetchingPages.clear()
  7397. this.lastScrollTriggerPage = -1
  7398. this.lastVisibleEndIndex = -1
  7399. this.isPagingTransition = false
  7400. if (this.pagingScheduleTimer) {
  7401. clearTimeout(this.pagingScheduleTimer)
  7402. this.pagingScheduleTimer = 0
  7403. }
  7404. this.totalCount = albumList.length
  7405. this.titleName = item.name
  7406. this.currentTitleName = '专辑:' + item.name
  7407. if (item.pixelMapPath) {
  7408. this.currentTitleCover = item.pixelMapPath
  7409. }
  7410. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7411. this.mScrollMap.set(item.name, this.selectedIndex)
  7412. this.rightTopImage = $r('sys.symbol.chevron_left')
  7413. } else {
  7414. ToastUtil.showToast('未找到该专辑的歌曲');
  7415. return;
  7416. }
  7417. //进入歌单的时候的滚动位置在顶部
  7418. if(this.twoFingerType==4){
  7419. setTimeout(() => {
  7420. this.waterScroller.scrollEdge(Edge.Top)
  7421. this.scroller.scrollEdge(Edge.Top)
  7422. }, 380)
  7423. }else{
  7424. if (this.isGridMusic) {
  7425. this.scroller.scrollEdge(Edge.Top)
  7426. }else{
  7427. this.listScroller.scrollEdge(Edge.Top)
  7428. }
  7429. }
  7430. break;
  7431. case CommonConstants.TYPE_IS_CSJAD:
  7432. return
  7433. break;
  7434. case CommonConstants.TYPE_LOCAL:
  7435. if (this.isIsoLocalFile(item)) {
  7436. await this.openIsoArchiveDialog(item)
  7437. return
  7438. }
  7439. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  7440. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  7441. const cueTracks:CueTrack[] = cueinfo.tracks
  7442. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  7443. if(ArrayUtil.isNotEmpty(cueTracks)){
  7444. this.showCueDialog(cueTracks,cueinfo)
  7445. }
  7446. // this.showCueSheet = !this.showCueSheet
  7447. return
  7448. }
  7449. console.info('kkMusic doPlay this.CONTROL_PlayStatus ='+this.CONTROL_PlayStatus )
  7450. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7451. console.info('kkMusic doPlay stop =' )
  7452. this.stop();
  7453. }
  7454. const useExistingQueueForPlayback = this.preserveExistingQueueOnNextPlay;
  7455. const nextQueueScope = this.nextPlayQueueScope;
  7456. this.preserveExistingQueueOnNextPlay = false;
  7457. this.nextPlayQueueScope = 'view';
  7458. if (isOpen) {
  7459. this.resetFindPagedLocalQueueState();
  7460. this.currentSong = item
  7461. if (index !== undefined) {
  7462. this.curIndex = index
  7463. }
  7464. this.songList = []
  7465. this.songList.push(item)
  7466. this.sonDataSource.pushArrayData(this.songList)
  7467. this.playQueueScope = 'single'
  7468. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  7469. this.currentSong = item
  7470. if (index !== undefined) {
  7471. this.curIndex = index
  7472. }
  7473. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  7474. if (this.isFindPagedLocalQueueActive()) {
  7475. // 这类队列来自发现页分页随机,点击播放列表里的歌也要继续保持“分页队列”身份。
  7476. this.playQueueScope = 'find_paged_local'
  7477. this.currentPlaylistSongFilePaths = [];
  7478. } else {
  7479. this.resetFindPagedLocalQueueState();
  7480. this.playQueueScope = 'playlist'
  7481. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7482. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7483. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7484. }
  7485. }
  7486. }else if (useExistingQueueForPlayback) {
  7487. // 特殊分页队列初始化时,直接复用 finishLoadingPlaylist 准备好的当前页,不再按视图重建全量队列。
  7488. this.currentSong = item
  7489. if (index !== undefined) {
  7490. this.curIndex = index
  7491. }
  7492. this.playQueueScope = nextQueueScope
  7493. this.currentPlaylistSongFilePaths = [];
  7494. this.sonDataSource.pushArrayData(this.songList)
  7495. }else {
  7496. this.resetFindPagedLocalQueueState();
  7497. const globalVideoList = this.buildPlayQueueFromView();
  7498. this.curIndex = findSongIndexByFilePath(globalVideoList, item.filePath)
  7499. if (this.curIndex < 0) {
  7500. globalVideoList.push(item);
  7501. this.curIndex = globalVideoList.length - 1;
  7502. }
  7503. this.songList = globalVideoList
  7504. this.sonDataSource.pushArrayData(this.songList)
  7505. this.currentSong = this.songList[this.curIndex]
  7506. // 只在非歌单模式下清空歌单路径列表
  7507. if (this.modeType !== 4) {
  7508. this.currentPlaylistSongFilePaths = [];
  7509. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  7510. } else {
  7511. // 歌单模式:确保歌单路径列表已设置
  7512. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7513. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7514. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7515. } else {
  7516. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7517. }
  7518. }
  7519. }
  7520. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7521. try {
  7522. const localUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-local');
  7523. this.videoUrl = localUrl || this.currentSong.filePath
  7524. } catch (error) {
  7525. Logger.error(TAG, `本地歌曲构建播放地址失败: ${(error as Error).message}`);
  7526. this.videoUrl = this.currentSong.filePath
  7527. }
  7528. this.name = this.currentSong.name
  7529. this.cover = this.currentSong.pixelMapPath
  7530. this.artist = this.currentSong.artist
  7531. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  7532. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  7533. this.startPlayOrResumePlay()
  7534. break;
  7535. case CommonConstants.TYPE_WEBDAV:
  7536. case CommonConstants.TYPE_SMB:
  7537. case CommonConstants.TYPE_NAVIDROME:
  7538. case CommonConstants.TYPE_FTP:
  7539. case CommonConstants.TYPE_BAIDU:
  7540. case CommonConstants.TYPE_JELLYFIN:
  7541. case CommonConstants.TYPE_EMBY:
  7542. case CommonConstants.TYPE_AUDIOSTATION:
  7543. case CommonConstants.TYPE_PLEX:
  7544. case CommonConstants.TYPE_DAOLIYU:
  7545. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  7546. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  7547. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7548. this.stop();
  7549. }
  7550. this.resetFindPagedLocalQueueState();
  7551. this.preserveExistingQueueOnNextPlay = false;
  7552. this.nextPlayQueueScope = 'view';
  7553. if (isOpen) {
  7554. this.currentSong = item
  7555. if (index !== undefined) {
  7556. this.curIndex = index
  7557. }
  7558. this.songList = []
  7559. this.songList.push(item)
  7560. this.sonDataSource.pushArrayData(this.songList)
  7561. } else if (isFromSonPlayList) {
  7562. // 点击来自右下角的播放列表
  7563. this.currentSong = item
  7564. if (index !== undefined) {
  7565. this.curIndex = index
  7566. }
  7567. // 设置播放队列作用域为歌单
  7568. this.playQueueScope = 'playlist'
  7569. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7570. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  7571. } else {
  7572. // 从全局网络音频列表中查找
  7573. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  7574. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  7575. if (this.curIndex === -1 && index !== undefined) {
  7576. this.curIndex = index;
  7577. }
  7578. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  7579. this.currentSong = this.songList[this.curIndex];
  7580. this.sonDataSource.pushArrayData(this.songList)
  7581. }
  7582. await this.hydrateRemoteSongFromDb(this.currentSong);
  7583. await this.hydrateRemoteSongFromDb(this.currentSong);
  7584. AppStorage.setOrCreate('currentSong', this.currentSong);
  7585. const remotePlayLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  7586. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-remote');
  7587. if (!playbackUrl) {
  7588. if (remotePlayLoading) {
  7589. this.hideLoadIng();
  7590. }
  7591. return;
  7592. }
  7593. this.videoUrl = playbackUrl;
  7594. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  7595. this.name = this.currentSong.name
  7596. this.cover = this.currentSong.pixelMapPath
  7597. this.artist = this.currentSong.artist
  7598. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  7599. this.startPlayOrResumePlay()
  7600. break;
  7601. }
  7602. }
  7603. private async openIsoArchiveDialog(item: VideoItem): Promise<void> {
  7604. if (!item || StrUtil.isEmpty(item.filePath)) {
  7605. Logger.error(TAG, `heanup ISO open dialog invalid path=${item ? item.filePath : ''}`)
  7606. ToastUtil.showToast('ISO 文件无效')
  7607. return
  7608. }
  7609. if (this.isIsoExtracting) {
  7610. if (ArrayUtil.isNotEmpty(this.isoAudioEntries)) {
  7611. if (this.isoSourceFilePath !== item.filePath) {
  7612. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行,已打开提取进度窗口')
  7613. }
  7614. this.presentIsoArchiveDialog()
  7615. return
  7616. }
  7617. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行')
  7618. return
  7619. }
  7620. Logger.info(TAG, `heanup ISO open dialog path=${item.filePath}, name=${item.fileName || item.name}`)
  7621. this.closeIsoDialog()
  7622. this.isoSourceFilePath = item.filePath
  7623. this.isoSourceFileName = item.fileName || item.name
  7624. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  7625. progress: 0,
  7626. backCancel: false,
  7627. autoCancel: false,
  7628. loadColor: this.themeColor,
  7629. fontColor: this.themeColor
  7630. })
  7631. try {
  7632. const task = new taskpool.Task(listIsoAudioEntriesTask, item.filePath)
  7633. const entries = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoArchiveAudioEntry[]
  7634. this.isoAudioEntries = Array.isArray(entries) ? entries : []
  7635. Logger.info(TAG, `heanup ISO list entries done count=${this.isoAudioEntries.length}, path=${item.filePath}`)
  7636. if (ArrayUtil.isEmpty(this.isoAudioEntries)) {
  7637. Logger.error(TAG, `heanup ISO list entries empty path=${item.filePath}`)
  7638. ToastUtil.showToast('ISO 内未发现可提取的媒体文件')
  7639. this.closeIsoDialog()
  7640. return
  7641. }
  7642. this.selectedIsoAudioPaths = []
  7643. } catch (error) {
  7644. Logger.error(TAG, `heanup 解析 ISO 失败: ${(error as Error).message}`)
  7645. ToastUtil.showToast('解析 ISO 失败')
  7646. this.closeIsoDialog()
  7647. return
  7648. } finally {
  7649. if (this.loadingProgressDialogId) {
  7650. DialogHelper.closeDialog(this.loadingProgressDialogId)
  7651. this.loadingProgressDialogId = ''
  7652. }
  7653. }
  7654. this.presentIsoArchiveDialog()
  7655. }
  7656. private presentIsoArchiveDialog(): void {
  7657. if (this.isoComponentId > 0) {
  7658. return
  7659. }
  7660. this.getUIContext().getPromptAction().openCustomDialog({
  7661. builder: () => {
  7662. this.isoComptentBuilder()
  7663. },
  7664. isModal: true,
  7665. showInSubWindow: false,
  7666. maskColor: Color.Transparent,
  7667. dialogTransition: TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7668. .animation({ duration: 600, curve: Curve.Smooth }),
  7669. maskTransition: TransitionEffect.opacity(0.5)
  7670. .animation({ duration: 600, curve: Curve.Smooth })
  7671. }).then((dialogId: number) => {
  7672. this.isoComponentId = dialogId
  7673. }).catch((error: BusinessError) => {
  7674. Logger.error(TAG, `heanup 打开 ISO 弹窗失败: ${error.message}`)
  7675. this.closeIsoDialog()
  7676. })
  7677. }
  7678. private toggleIsoEntrySelection(path: string, checked: boolean): void {
  7679. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7680. if (checked) {
  7681. selectedPathSet.add(path)
  7682. } else {
  7683. selectedPathSet.delete(path)
  7684. }
  7685. this.selectedIsoAudioPaths = this.isoAudioEntries
  7686. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7687. .map((entry: IsoArchiveAudioEntry) => entry.path)
  7688. Logger.info(TAG,
  7689. `heanup ISO toggle selection path=${path}, checked=${checked}, total=${this.selectedIsoAudioPaths.length}`)
  7690. }
  7691. private toggleIsoEntrySelectAll(): void {
  7692. if (this.selectedIsoAudioPaths.length === this.isoAudioEntries.length) {
  7693. this.selectedIsoAudioPaths = []
  7694. Logger.info(TAG, 'heanup ISO toggle select all cleared')
  7695. return
  7696. }
  7697. this.selectedIsoAudioPaths = this.isoAudioEntries.map((entry: IsoArchiveAudioEntry) => entry.path)
  7698. Logger.info(TAG, `heanup ISO toggle select all count=${this.selectedIsoAudioPaths.length}`)
  7699. }
  7700. private startIsoExtractProgressWatcher(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): void {
  7701. this.stopIsoExtractProgressWatcher()
  7702. this.isoExtractExpectedOutputPaths = this.buildIsoExtractExpectedOutputPaths(entries, destinationDir)
  7703. this.isoExtractTotalBytes = entries.reduce((total: number, entry: IsoArchiveAudioEntry) => {
  7704. const size = entry && entry.size > 0 ? entry.size : 0
  7705. return total + size
  7706. }, 0)
  7707. this.isoExtractReceivedTaskProgress = false
  7708. this.isoExtractDisplayedProgress = 0
  7709. this.isoExtractLastActivityTime = Date.now()
  7710. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths)) {
  7711. return
  7712. }
  7713. this.isoExtractProgressTimer = setInterval(() => {
  7714. this.updateIsoExtractProgressFromFiles()
  7715. }, 500)
  7716. }
  7717. private stopIsoExtractProgressWatcher(): void {
  7718. if (this.isoExtractProgressTimer) {
  7719. clearInterval(this.isoExtractProgressTimer)
  7720. this.isoExtractProgressTimer = 0
  7721. }
  7722. this.isoExtractExpectedOutputPaths = []
  7723. this.isoExtractTotalBytes = 0
  7724. this.isoExtractReceivedTaskProgress = false
  7725. this.isoExtractLastActivityTime = 0
  7726. }
  7727. private markIsoExtractActivity(): void {
  7728. this.isoExtractLastActivityTime = Date.now()
  7729. }
  7730. private updateIsoExtractProgressFromFiles(): void {
  7731. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths) ||
  7732. this.isoExtractReceivedTaskProgress) {
  7733. return
  7734. }
  7735. let writtenBytes = 0
  7736. let existingCount = 0
  7737. for (let i = 0; i < this.isoExtractExpectedOutputPaths.length; i++) {
  7738. const outputPath = this.isoExtractExpectedOutputPaths[i]
  7739. if (!FileUtil.accessSync(outputPath)) {
  7740. continue
  7741. }
  7742. existingCount++
  7743. try {
  7744. const stat = fs.statSync(outputPath) as fs.Stat
  7745. if (typeof stat.size === 'number' && stat.size > 0) {
  7746. writtenBytes += stat.size
  7747. }
  7748. } catch (_error) {
  7749. }
  7750. }
  7751. let progress = 0
  7752. if (writtenBytes > 0) {
  7753. progress = Math.ceil((writtenBytes / this.isoExtractTotalBytes) * 100)
  7754. if (progress > 99) {
  7755. progress = 99
  7756. }
  7757. this.markIsoExtractActivity()
  7758. } else if (existingCount > 0) {
  7759. progress = 1
  7760. this.markIsoExtractActivity()
  7761. }
  7762. if (progress > 0) {
  7763. this.updateIsoExtractProgressState(progress,
  7764. `正在提取 ${progress}% (${existingCount}/${this.isoExtractExpectedOutputPaths.length})`)
  7765. return
  7766. }
  7767. if (this.isoExtractTask && this.isoExtractLastActivityTime > 0 &&
  7768. Date.now() - this.isoExtractLastActivityTime > this.isoExtractStallTimeoutMs) {
  7769. Logger.warn(TAG, `heanup ISO 提取进度长时间无变化: timeout=${this.isoExtractStallTimeoutMs}`)
  7770. this.markIsoExtractActivity()
  7771. this.updateIsoExtractProgressState(1, '准备提取 1%')
  7772. }
  7773. }
  7774. private updateIsoExtractProgressState(progress: number, message: string, currentName: string = '',
  7775. force: boolean = false): void {
  7776. let safeProgress = progress
  7777. if (safeProgress < 0) {
  7778. safeProgress = 0
  7779. }
  7780. if (safeProgress > 100) {
  7781. safeProgress = 100
  7782. }
  7783. if (!force && safeProgress < this.isoExtractDisplayedProgress) {
  7784. return
  7785. }
  7786. this.isoExtractDisplayedProgress = safeProgress
  7787. this.isoExtractProgress = safeProgress
  7788. this.isoExtractProgressText = message
  7789. if (force || StrUtil.isNotEmpty(currentName)) {
  7790. this.isoExtractCurrentEntryName = currentName
  7791. }
  7792. }
  7793. private resetIsoExtractProgressState(): void {
  7794. this.isoExtractProgress = 0
  7795. this.isoExtractProgressText = ''
  7796. this.isoExtractCurrentEntryName = ''
  7797. this.isoExtractDisplayedProgress = 0
  7798. }
  7799. private buildIsoExtractExpectedOutputPaths(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): Array<string> {
  7800. const outputPaths: Array<string> = []
  7801. const occupiedPaths: Set<string> = new Set<string>()
  7802. for (let i = 0; i < entries.length; i++) {
  7803. const entry = entries[i]
  7804. const fileName = entry.name || this.getIsoLastPathSegment(entry.path)
  7805. const outputPath = this.buildIsoExpectedOutputPath(destinationDir, fileName, occupiedPaths)
  7806. occupiedPaths.add(outputPath)
  7807. outputPaths.push(outputPath)
  7808. }
  7809. return outputPaths
  7810. }
  7811. private buildIsoExpectedOutputPath(destinationDir: string, fileName: string, occupiedPaths: Set<string>): string {
  7812. const cleanName = this.sanitizeIsoOutputFileName(fileName)
  7813. const extension = this.getIsoOutputFileExtension(cleanName)
  7814. const baseName = extension.length > 0 ? cleanName.substring(0, cleanName.length - extension.length) : cleanName
  7815. let candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${cleanName}`
  7816. let suffix = 0
  7817. while (occupiedPaths.has(candidatePath) || FileUtil.accessSync(candidatePath)) {
  7818. suffix++
  7819. candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${baseName} (${suffix})${extension}`
  7820. }
  7821. return candidatePath
  7822. }
  7823. private sanitizeIsoOutputFileName(fileName: string): string {
  7824. const lastSegment = this.getIsoLastPathSegment(fileName)
  7825. let sanitized = ''
  7826. for (let i = 0; i < lastSegment.length; i++) {
  7827. const char = lastSegment[i]
  7828. if (char === '/' || char === '\\' || char === ':' || char === '*' || char === '?' || char === '"' ||
  7829. char === '<' || char === '>' || char === '|') {
  7830. sanitized += '_'
  7831. } else {
  7832. sanitized += char
  7833. }
  7834. }
  7835. if (sanitized.trim().length === 0) {
  7836. return 'iso_audio.bin'
  7837. }
  7838. return sanitized
  7839. }
  7840. private getIsoLastPathSegment(path: string): string {
  7841. const normalizedPath = path.replace(/\\/g, '/')
  7842. const lastSeparator = normalizedPath.lastIndexOf('/')
  7843. if (lastSeparator < 0) {
  7844. return normalizedPath
  7845. }
  7846. return normalizedPath.substring(lastSeparator + 1)
  7847. }
  7848. private getIsoOutputFileExtension(fileName: string): string {
  7849. const lastDot = fileName.lastIndexOf('.')
  7850. if (lastDot < 0) {
  7851. return ''
  7852. }
  7853. return fileName.substring(lastDot)
  7854. }
  7855. private trimIsoOutputTrailingSeparator(path: string): string {
  7856. if (path.endsWith('/')) {
  7857. return path.substring(0, path.length - 1)
  7858. }
  7859. return path
  7860. }
  7861. private cancelIsoExtraction(reason?: string): void {
  7862. const currentTask = this.isoExtractTask
  7863. Logger.info(TAG,
  7864. `heanup ISO cancel request reason=${reason || ''}, hasTask=${currentTask ? 'true' : 'false'}`)
  7865. this.isoExtractCanceled = true
  7866. this.isoExtractCancelMessage = reason ? reason : ''
  7867. this.isoExtractTask = undefined
  7868. this.updateIsoExtractProgressState(this.isoExtractProgress, '正在停止提取...', this.isoExtractCurrentEntryName, true)
  7869. if (currentTask) {
  7870. try {
  7871. taskpool.terminateTask(currentTask)
  7872. } catch (error) {
  7873. Logger.error(TAG, `heanup 终止 ISO 提取任务失败: ${(error as Error).message}`)
  7874. }
  7875. }
  7876. }
  7877. private moveIsoExtractionToBackground(): void {
  7878. this.closeIsoDialog(false)
  7879. ToastUtil.showToast('ISO 提取已转入后台')
  7880. }
  7881. private async extractSelectedIsoAudioFiles(): Promise<void> {
  7882. if (this.isIsoExtracting) {
  7883. return
  7884. }
  7885. if (ArrayUtil.isEmpty(this.selectedIsoAudioPaths)) {
  7886. ToastUtil.showToast('请先选择要提取的文件')
  7887. return
  7888. }
  7889. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7890. const selectedEntries = this.isoAudioEntries
  7891. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7892. if (ArrayUtil.isEmpty(selectedEntries)) {
  7893. ToastUtil.showToast('未找到要提取的文件')
  7894. return
  7895. }
  7896. const hasSacdTrack: boolean = selectedEntries.some((entry: IsoArchiveAudioEntry) => entry.entryType === 'sacd_track')
  7897. const destinationDir: string = this.currentPath
  7898. this.isIsoExtracting = true
  7899. this.isoExtractCanceled = false
  7900. this.isoExtractCancelMessage = ''
  7901. this.isoExtractDestinationDir = destinationDir
  7902. Logger.info(TAG,
  7903. `heanup ISO extract start file=${this.isoSourceFilePath}, selected=${selectedEntries.length}, ` +
  7904. `hasSacd=${hasSacdTrack}, destinationDir=${destinationDir}`)
  7905. Logger.info(TAG,
  7906. `heanup ISO selected entries: ${selectedEntries.map((entry: IsoArchiveAudioEntry) => entry.path).join(', ')}`)
  7907. this.resetIsoExtractProgressState()
  7908. this.updateIsoExtractProgressState(1, '准备提取 1%', '', true)
  7909. this.startIsoExtractProgressWatcher(selectedEntries, destinationDir)
  7910. try {
  7911. const extractStartedAt = Date.now()
  7912. const outputPaths: string[] = this.buildIsoExtractExpectedOutputPaths(selectedEntries, destinationDir)
  7913. const payloadJson = JSON.stringify({
  7914. isoPath: this.isoSourceFilePath,
  7915. destinationDir,
  7916. entries: selectedEntries,
  7917. outputPaths
  7918. })
  7919. const task = new taskpool.Task(extractIsoAudioEntriesTask, payloadJson)
  7920. this.isoExtractTask = task
  7921. task.onReceiveData((progressData: IsoExtractProgressMessage) => {
  7922. this.markIsoExtractActivity()
  7923. const progress = typeof progressData.progress === 'number' ? Math.floor(progressData.progress) : 0
  7924. Logger.info(TAG,
  7925. `heanup ISO task receive stage=${progressData.stage || ''}, progress=${progress}, name=${progressData.name || ''}`)
  7926. if (progress > 1 && !this.isoExtractReceivedTaskProgress) {
  7927. this.isoExtractReceivedTaskProgress = true
  7928. if (this.isoExtractProgressTimer) {
  7929. clearInterval(this.isoExtractProgressTimer)
  7930. this.isoExtractProgressTimer = 0
  7931. }
  7932. Logger.info(TAG, `heanup ISO 提取切换为任务进度: progress=${progress}, stage=${progressData.stage || ''}`)
  7933. }
  7934. const stageText = progressData.stage === 'prepare' ? '准备提取' :
  7935. (progressData.stage === 'done' ? '提取完成' : (progressData.stage === 'error' ? '提取异常' : '正在提取'))
  7936. if (progress > this.isoExtractDisplayedProgress || progressData.stage !== 'extract') {
  7937. Logger.info(TAG,
  7938. `heanup ISO 提取任务进度: stage=${progressData.stage || ''}, progress=${progress}, ` +
  7939. `name=${progressData.name || ''}`)
  7940. }
  7941. this.updateIsoExtractProgressState(progress, `${stageText} ${progress}%`, progressData.name || '')
  7942. })
  7943. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoExtractTaskResult
  7944. const extractElapsedMs = Date.now() - extractStartedAt
  7945. this.isoExtractTask = undefined
  7946. Logger.info(TAG, `heanup ISO extract task completed canceled=${this.isoExtractCanceled}, elapsedMs=${extractElapsedMs}`)
  7947. if (this.isoExtractCanceled) {
  7948. return
  7949. }
  7950. const extractedPaths = result?.extractedPaths || []
  7951. const failedEntries = result?.failedEntries || []
  7952. const failureDetails = result?.failureDetails || []
  7953. Logger.info(TAG,
  7954. `heanup ISO extract result extracted=${extractedPaths.length}, failed=${failedEntries.length}, details=${failureDetails.length}`)
  7955. let importErrorMessage: string = ''
  7956. let importedCount: number = 0
  7957. if (ArrayUtil.isNotEmpty(extractedPaths)) {
  7958. const importStartedAt = Date.now()
  7959. try {
  7960. await this.postProcessExtractedIsoFiles(extractedPaths, selectedEntries, outputPaths)
  7961. importedCount = await this.importExtractedFilesToDirectory(extractedPaths, destinationDir)
  7962. Logger.info(TAG,
  7963. `heanup ISO import extracted files success elapsedMs=${Date.now() - importStartedAt}, ` +
  7964. `importedCount=${importedCount}`)
  7965. } catch (importError) {
  7966. importErrorMessage = (importError as Error).message || '导入媒体库失败'
  7967. Logger.error(TAG,
  7968. `heanup ISO import extracted files failed elapsedMs=${Date.now() - importStartedAt}, ` +
  7969. `message=${importErrorMessage}`)
  7970. }
  7971. }
  7972. if (extractedPaths.length > 0 && failedEntries.length > 0) {
  7973. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7974. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,导入失败`)
  7975. } else if (importedCount > 0) {
  7976. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,已入库 ${importedCount} 个音频文件`)
  7977. } else {
  7978. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个`)
  7979. }
  7980. } else if (extractedPaths.length > 0) {
  7981. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7982. ToastUtil.showToast(`提取完成,但导入媒体库失败: ${importErrorMessage}`)
  7983. } else if (importedCount > 0) {
  7984. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件,入库 ${importedCount} 个音频文件`)
  7985. } else {
  7986. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件`)
  7987. }
  7988. } else if (ArrayUtil.isNotEmpty(failureDetails)) {
  7989. const firstFailure: IsoExtractFailureDetail = failureDetails[0]
  7990. const reasonText = firstFailure.reason && firstFailure.reason.length > 0 ? firstFailure.reason : '提取失败'
  7991. ToastUtil.showToast(reasonText)
  7992. } else if (hasSacdTrack) {
  7993. ToastUtil.showToast('SACD ISO 轨道提取失败')
  7994. } else {
  7995. ToastUtil.showToast('提取失败')
  7996. }
  7997. } catch (error) {
  7998. this.isoExtractTask = undefined
  7999. if (this.isoExtractCanceled) {
  8000. return
  8001. }
  8002. Logger.error(TAG, `heanup 提取 ISO 文件失败: ${(error as Error).message}`)
  8003. ToastUtil.showToast('提取 ISO 文件失败')
  8004. } finally {
  8005. const shouldResetDialogState: boolean = this.isoComponentId <= 0
  8006. this.stopIsoExtractProgressWatcher()
  8007. this.isoExtractTask = undefined
  8008. this.isIsoExtracting = false
  8009. Logger.info(TAG,
  8010. `heanup ISO extract finally canceled=${this.isoExtractCanceled}, cancelMessage=${this.isoExtractCancelMessage}`)
  8011. if (this.isoExtractCanceled && this.isoExtractCancelMessage.length > 0) {
  8012. ToastUtil.showToast(this.isoExtractCancelMessage)
  8013. }
  8014. this.isoExtractCanceled = false
  8015. this.isoExtractCancelMessage = ''
  8016. if (shouldResetDialogState) {
  8017. this.resetIsoDialogState()
  8018. } else {
  8019. this.selectedIsoAudioPaths = []
  8020. this.resetIsoExtractProgressState()
  8021. }
  8022. }
  8023. }
  8024. private async postProcessExtractedIsoFiles(extractedPaths: Array<string>, selectedEntries: Array<IsoArchiveAudioEntry>,
  8025. outputPaths: Array<string>): Promise<void> {
  8026. if (ArrayUtil.isEmpty(extractedPaths) || ArrayUtil.isEmpty(selectedEntries) || ArrayUtil.isEmpty(outputPaths)) {
  8027. return
  8028. }
  8029. const entryByOutputPath: Map<string, IsoArchiveAudioEntry> = new Map<string, IsoArchiveAudioEntry>()
  8030. for (let i = 0; i < outputPaths.length && i < selectedEntries.length; i++) {
  8031. entryByOutputPath.set(outputPaths[i], selectedEntries[i])
  8032. }
  8033. for (let i = 0; i < extractedPaths.length; i++) {
  8034. const extractedPath = extractedPaths[i]
  8035. const entry = entryByOutputPath.get(extractedPath)
  8036. if (!entry) {
  8037. continue
  8038. }
  8039. await this.postProcessExtractedIsoEntry(extractedPath, entry)
  8040. }
  8041. }
  8042. private async postProcessExtractedIsoEntry(filePath: string, entry: IsoArchiveAudioEntry): Promise<void> {
  8043. if (!Utility.isMusicByExtension(filePath)) {
  8044. return
  8045. }
  8046. const hasEmbeddedMetadata: boolean = StrUtil.isNotEmpty(entry.title) || StrUtil.isNotEmpty(entry.album) ||
  8047. StrUtil.isNotEmpty(entry.artist) || StrUtil.isNotEmpty(entry.albumArtist) || StrUtil.isNotEmpty(entry.comment) ||
  8048. !!(entry.trackNumber && entry.trackNumber > 0)
  8049. if (entry.entryType !== 'sacd_track' && !hasEmbeddedMetadata) {
  8050. return
  8051. }
  8052. const tags: FFMpegTags = this.buildIsoExtractedMetadata(entry)
  8053. if (Object.keys(tags).length > 0) {
  8054. try {
  8055. const metadataResult = await repairAudioMetadata(filePath, '', tags, true, '')
  8056. Logger.info(TAG,
  8057. `heanup ISO metadata post-process path=${filePath}, success=${metadataResult}, type=${entry.entryType || ''}`)
  8058. } catch (error) {
  8059. Logger.error(TAG, `heanup ISO metadata post-process failed path=${filePath}, message=${(error as Error).message}`)
  8060. }
  8061. }
  8062. if (!filePath.toLowerCase().endsWith('.dsf')) {
  8063. return
  8064. }
  8065. const coverUrl = await this.resolveIsoExtractCoverUrl(entry)
  8066. if (StrUtil.isEmpty(coverUrl)) {
  8067. return
  8068. }
  8069. try {
  8070. const coverResult = await changeMusicCover(this.context, filePath, coverUrl, true, '')
  8071. Logger.info(TAG, `heanup ISO cover post-process path=${filePath}, success=${coverResult}`)
  8072. } catch (error) {
  8073. Logger.error(TAG, `heanup ISO cover post-process failed path=${filePath}, message=${(error as Error).message}`)
  8074. }
  8075. }
  8076. private buildIsoExtractedMetadata(entry: IsoArchiveAudioEntry): FFMpegTags {
  8077. const metadata: FFMpegTags = {}
  8078. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  8079. if (StrUtil.isNotEmpty(title)) {
  8080. metadata.title = title
  8081. metadata.TITLE = title
  8082. }
  8083. if (StrUtil.isNotEmpty(entry.artist)) {
  8084. metadata.artist = entry.artist
  8085. metadata.ARTIST = entry.artist
  8086. }
  8087. if (StrUtil.isNotEmpty(entry.album)) {
  8088. metadata.album = entry.album
  8089. metadata.ALBUM = entry.album
  8090. }
  8091. if (entry.trackNumber && entry.trackNumber > 0) {
  8092. metadata.track = `${entry.trackNumber}`
  8093. metadata.TRACK = `${entry.trackNumber}`
  8094. }
  8095. if (StrUtil.isNotEmpty(entry.albumArtist)) {
  8096. metadata.ALBUMARTIST = entry.albumArtist
  8097. metadata.album_artist = entry.albumArtist
  8098. metadata.TPE2 = entry.albumArtist
  8099. }
  8100. if (StrUtil.isNotEmpty(entry.comment)) {
  8101. metadata.comment = entry.comment
  8102. metadata.COMMENT = entry.comment
  8103. metadata.COMM = entry.comment
  8104. }
  8105. return metadata
  8106. }
  8107. private getIsoEntryBaseName(fileName: string): string {
  8108. const lastSegment = this.getIsoLastPathSegment(fileName)
  8109. const lastDot = lastSegment.lastIndexOf('.')
  8110. if (lastDot <= 0) {
  8111. return lastSegment
  8112. }
  8113. return lastSegment.substring(0, lastDot)
  8114. }
  8115. private async resolveIsoExtractCoverUrl(entry: IsoArchiveAudioEntry): Promise<string> {
  8116. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  8117. const artist = entry.artist || entry.albumArtist || ''
  8118. if (StrUtil.isEmpty(title) || PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8119. return ''
  8120. }
  8121. try {
  8122. const coverUrl = await NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', ''))
  8123. if (StrUtil.isNotEmpty(coverUrl) && coverUrl !== 'unknown') {
  8124. return coverUrl
  8125. }
  8126. } catch (error) {
  8127. Logger.error(TAG,
  8128. `heanup ISO resolve cover failed title=${title}, artist=${artist}, message=${(error as Error).message}`)
  8129. }
  8130. return ''
  8131. }
  8132. private async importExtractedFilesToDirectory(paths: Array<string>, destinationDir: string): Promise<number> {
  8133. if (ArrayUtil.isEmpty(paths)) {
  8134. return 0
  8135. }
  8136. let importedCount: number = 0
  8137. for (let i = 0; i < paths.length; i++) {
  8138. const filePath = paths[i]
  8139. if (destinationDir === this.lockPath || !Utility.isMeidaByExtension(filePath) ||
  8140. filePath.endsWith('.lrc') || filePath.endsWith('.srt') || Utility.isIsoByExtension(filePath)) {
  8141. continue
  8142. }
  8143. const mediaItem = await Utility.uriGetMusicAssetsFromFile(this.context, filePath,
  8144. CommonConstants.TYPE_LOCAL, this.autoParseMusicName)
  8145. await new Promise<void>((resolve) => {
  8146. this.table.insert(mediaItem, (_id: number) => resolve())
  8147. })
  8148. importedCount++
  8149. }
  8150. this.cache.delete(destinationDir)
  8151. if (this.currentPath === destinationDir) {
  8152. this.pageCache.clear()
  8153. this.pageHasMoreCache.clear()
  8154. this.pageTotalCountCache.clear()
  8155. if (destinationDir === this.lockPath) {
  8156. this.getSortedFiles(destinationDir, true)
  8157. } else {
  8158. await this.resetAndLoadFirstPage()
  8159. }
  8160. }
  8161. return importedCount
  8162. }
  8163. private resetIsoDialogState(): void {
  8164. this.isoAudioEntries = []
  8165. this.selectedIsoAudioPaths = []
  8166. this.isoSourceFileName = ''
  8167. this.isoSourceFilePath = ''
  8168. this.isoExtractDestinationDir = ''
  8169. this.isIsoExtracting = false
  8170. this.stopIsoExtractProgressWatcher()
  8171. this.isoExtractTask = undefined
  8172. this.resetIsoExtractProgressState()
  8173. }
  8174. private closeIsoDialog(reset: boolean = true): void {
  8175. if (this.isoComponentId > 0) {
  8176. try {
  8177. this.getUIContext().getPromptAction().closeCustomDialog(this.isoComponentId)
  8178. } catch (_error) {
  8179. }
  8180. this.isoComponentId = 0
  8181. }
  8182. if (!reset) {
  8183. return
  8184. }
  8185. this.resetIsoDialogState()
  8186. }
  8187. @Builder
  8188. isoComptentBuilder() {
  8189. IsoExtractComptent({
  8190. isoFileName: this.isoSourceFileName,
  8191. entries: this.isoAudioEntries,
  8192. selectedPaths: this.selectedIsoAudioPaths,
  8193. isLongNameRoLL: this.isLongNameRoLL,
  8194. isExtracting: this.isIsoExtracting,
  8195. extractProgress: this.isoExtractProgress,
  8196. extractProgressText: this.isoExtractProgressText,
  8197. extractCurrentName: this.isoExtractCurrentEntryName,
  8198. onToggleSelection: (path: string, checked: boolean) => {
  8199. this.toggleIsoEntrySelection(path, checked)
  8200. },
  8201. onToggleSelectAll: () => {
  8202. this.toggleIsoEntrySelectAll()
  8203. },
  8204. onExtract: async () => {
  8205. await this.extractSelectedIsoAudioFiles()
  8206. },
  8207. onRunInBackground: () => {
  8208. this.moveIsoExtractionToBackground()
  8209. },
  8210. onStopExtract: () => {
  8211. this.cancelIsoExtraction('已取消 ISO 提取')
  8212. },
  8213. onCancel: () => {
  8214. if (this.isIsoExtracting) {
  8215. this.moveIsoExtractionToBackground()
  8216. return
  8217. }
  8218. this.closeIsoDialog()
  8219. }
  8220. })
  8221. }
  8222. private cueComponentId: number = 0
  8223. private async handleCueTrackImport(cueinfo: CueInfo): Promise<void> {
  8224. try {
  8225. let sourceItem = Utility.getItemByFilePath(this.videoLocalList, cueinfo.filePath);
  8226. if (!sourceItem) {
  8227. sourceItem = await this.table.queryVideoByFilePath(cueinfo.filePath) || undefined;
  8228. }
  8229. const importedItems = await importCueTracks(this.context, this.table, cueinfo, sourceItem);
  8230. if (ArrayUtil.isEmpty(importedItems)) {
  8231. ToastUtil.showToast('未导入到任何分轨');
  8232. return;
  8233. }
  8234. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId);
  8235. await this.resetAndLoadFirstPage();
  8236. ToastUtil.showToast(`分轨完成,已入库 ${importedItems.length} 首`);
  8237. } catch (error) {
  8238. Logger.error(TAG, `CUE 分轨入库失败: ${(error as Error).message}`);
  8239. ToastUtil.showToast('分轨失败');
  8240. }
  8241. }
  8242. //显示cue分轨列表对话框
  8243. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  8244. this.getUIContext().getPromptAction().openCustomDialog({
  8245. builder: () => {
  8246. this.cueComptentBuilder(cueTracks,cueinfo)
  8247. },
  8248. isModal:true,
  8249. showInSubWindow:false,
  8250. maskColor: Color.Transparent,
  8251. dialogTransition: // 设置弹窗内容显示的过渡效果
  8252. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  8253. .animation({ duration: 600, curve: Curve.Smooth }),
  8254. maskTransition: // 设置蒙层显示的过渡效果
  8255. TransitionEffect.opacity(0.5)
  8256. .animation({ duration: 600, curve: Curve.Smooth })
  8257. }).then((dialogId: number) => {
  8258. this.cueComponentId = dialogId
  8259. })
  8260. .catch((error: BusinessError) => {
  8261. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  8262. })
  8263. }
  8264. @Builder
  8265. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  8266. CueComptent({
  8267. title:cueinfo.title,
  8268. cueTracks:cueTracks,
  8269. isLongNameRoLL:this.isLongNameRoLL,
  8270. onCancel:()=>{
  8271. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  8272. },
  8273. onSplitTracks: async ()=>{
  8274. await this.handleCueTrackImport(cueinfo)
  8275. },
  8276. onDoItemClick: async (item: CueTrack, index: number)=>{
  8277. //获取cueinfo对应的filePath
  8278. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  8279. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  8280. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  8281. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  8282. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  8283. if (this.currentSong){
  8284. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  8285. this.stop();//播放之前先停止之前播放。
  8286. }
  8287. this.songList = globalVideoList
  8288. this.sonDataSource.pushArrayData(this.songList)
  8289. if (this.currentSong) {
  8290. try {
  8291. const cueUrl = await this.resolvePlaybackUrlForCurrentSong('cue-track-play');
  8292. if (!cueUrl) {
  8293. return;
  8294. }
  8295. this.videoUrl = cueUrl;
  8296. } catch (error) {
  8297. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  8298. this.videoUrl = this.currentSong.filePath;
  8299. }
  8300. }
  8301. this.name = item.title||this.currentSong.name
  8302. this.cover = this.currentSong.pixelMapPath
  8303. this.artist = item.performer||this.currentSong.artist
  8304. this.currentSong.name = this.name
  8305. this.currentSong.artist = this.artist
  8306. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  8307. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  8308. }
  8309. }
  8310. })
  8311. }
  8312. @State isFrontWhite: boolean = false
  8313. private showCoverScaleGuideIfNeeded(): void {
  8314. const hasShown = PreferencesUtil.getBooleanSync(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, false)
  8315. if (hasShown) {
  8316. return
  8317. }
  8318. this.isShowCoverScaleGuide = true
  8319. setTimeout(() => {
  8320. if (this.isShowCoverScaleGuide) {
  8321. this.dismissCoverScaleGuide()
  8322. }
  8323. }, 9000)
  8324. }
  8325. private dismissCoverScaleGuide(): void {
  8326. this.isShowCoverScaleGuide = false
  8327. PreferencesUtil.put(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, true)
  8328. }
  8329. private resolveMiniBarDismissTarget() {
  8330. const viewportWidthVp = this.windowWidth > 0 ? px2vp(this.windowWidth) : 360
  8331. const viewportHeightVp = this.windowHeight > 0 ? px2vp(this.windowHeight) : 800
  8332. const useFixedBottomMargin = DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  8333. || this.curDisplayIsHiCar
  8334. return resolvePlayerDismissMorphTarget(viewportWidthVp, viewportHeightVp, this.bottomSafeHeight, useFixedBottomMargin)
  8335. }
  8336. private clearPlayDismissTimer(): void {
  8337. if (this.playDismissTimer >= 0) {
  8338. clearTimeout(this.playDismissTimer)
  8339. this.playDismissTimer = -1
  8340. }
  8341. }
  8342. private clearPlayOpenTimer(): void {
  8343. if (this.playOpenTimer >= 0) {
  8344. clearTimeout(this.playOpenTimer)
  8345. this.playOpenTimer = -1
  8346. }
  8347. }
  8348. private resetMusicPlayDismissState(): void {
  8349. this.clearPlayDismissTimer()
  8350. this.clearPlayOpenTimer()
  8351. this.playOpenFromMiniBarPending = false
  8352. this.translateY = 0
  8353. this.playDismissTranslateX = 0
  8354. this.playDismissScale = 1
  8355. this.playDismissScaleY = 1
  8356. this.playDismissOpacity = 1
  8357. this.playDismissBorderRadius = 0
  8358. this.playDismissProxySize = 0
  8359. this.playDismissProxyOpacity = 0
  8360. this.scaleValueImage = 1
  8361. this.scaleValueText = 1
  8362. this.playDragUiOpacity = 1
  8363. }
  8364. private preparePlayerViewOpenFromMiniBar(): void {
  8365. const target = this.resolveMiniBarDismissTarget()
  8366. this.playOpenFromMiniBarPending = true
  8367. this.translateY = target.translateY
  8368. this.playDismissTranslateX = 0
  8369. this.playDismissScale = 0.9
  8370. this.playDismissScaleY = 0.8
  8371. this.playDismissOpacity = 0
  8372. this.playDismissBorderRadius = 48
  8373. this.playDismissProxySize = 0
  8374. this.playDismissProxyOpacity = 0
  8375. this.playDragUiOpacity = 0
  8376. this.scaleValueImage = 0.82
  8377. this.scaleValueText = 0.88
  8378. }
  8379. private startPlayerViewOpenAnimationIfNeeded(): void {
  8380. if (!this.playOpenFromMiniBarPending) {
  8381. return
  8382. }
  8383. this.playOpenFromMiniBarPending = false
  8384. this.getUIContext()?.animateTo({
  8385. duration: this.playOpenExpandDuration,
  8386. curve: Curve.Friction
  8387. }, () => {
  8388. this.playDismissProxySize = 0
  8389. this.playDismissProxyOpacity = 0
  8390. this.translateY = 0
  8391. this.playDismissTranslateX = 0
  8392. this.playDismissScale = 1
  8393. this.playDismissScaleY = 1
  8394. this.playDismissOpacity = 1
  8395. this.playDismissBorderRadius = 0
  8396. this.playDragUiOpacity = 1
  8397. this.scaleValueImage = 1
  8398. this.scaleValueText = 1
  8399. })
  8400. }
  8401. setShowPlayTrue(){
  8402. this.getUIContext()?.animateTo({
  8403. duration: 500,
  8404. curve: Curve.Friction
  8405. }, () => {
  8406. this.isShowPlay = true;
  8407. this.showCoverScaleGuideIfNeeded()
  8408. });
  8409. }
  8410. setShowPlayFalse(){
  8411. this.getUIContext()?.animateTo({
  8412. duration: 500,
  8413. curve: Curve.Friction
  8414. }, () => {
  8415. this.isShowPlay = false;
  8416. });
  8417. this.isShowCoverScaleGuide = false
  8418. }
  8419. //打开播放页
  8420. showPlayerView() {
  8421. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  8422. if (ArrayUtil.isNotEmpty(this.songList)) {
  8423. // this.setShowPlayTrue()
  8424. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  8425. this.initLyric(lyricPath);
  8426. this.startAutoHide();
  8427. } else {
  8428. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  8429. }
  8430. }
  8431. //打开播放列表
  8432. openPlayList(){
  8433. if (ArrayUtil.isNotEmpty(this.songList)) {
  8434. this.isShowSheet = !this.isShowSheet;
  8435. this.isFrontWhite = false
  8436. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  8437. this.scrollIndex()
  8438. if (this.shouldHydrateFullMediaPlayListOnOpen()) {
  8439. void this.hydrateFullMediaPlayListIfNeeded();
  8440. }
  8441. } else {
  8442. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  8443. }
  8444. }
  8445. scrollIndex(){
  8446. try {
  8447. setTimeout(() => {
  8448. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8449. if(this.curIndex>60){
  8450. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  8451. }else{
  8452. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  8453. }
  8454. })
  8455. }, 123)
  8456. }catch (error) {
  8457. console.error(`onecold scrollIndex出错: ${error}`);
  8458. }
  8459. }
  8460. scrollIndexMain(dialogId?:string){
  8461. try {
  8462. setTimeout(() => {
  8463. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8464. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  8465. if(dialogId)
  8466. DialogHelper.closeDialog(dialogId)
  8467. let isAni:boolean = false
  8468. if(this.curIndex<50){
  8469. isAni = true
  8470. }
  8471. if(this.twoFingerType==4){
  8472. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8473. }else{
  8474. if(this.isGridMusic){
  8475. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8476. }else{
  8477. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8478. }
  8479. }
  8480. })
  8481. }, 123)
  8482. }catch (error) {
  8483. console.error(`onecold scrollIndexMain出错: ${error}`);
  8484. }
  8485. }
  8486. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  8487. async locateCurrentSong(): Promise<void> {
  8488. if (!this.currentSong) {
  8489. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  8490. return;
  8491. }
  8492. // 检查当前播放歌曲是否在已加载的列表中
  8493. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8494. if (targetIndex > 0) {
  8495. // 歌曲在当前列表中,直接滚动
  8496. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  8497. this.curIndex = targetIndex;
  8498. this.scrollIndexMain();
  8499. } else {
  8500. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  8501. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  8502. const dialogID = DialogHelper.showLoadingDialog()
  8503. await this.hydrateFullMediaPlayListIfNeeded(false);
  8504. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8505. this.scrollIndexMain(dialogID);
  8506. }
  8507. }
  8508. //播放列表布局
  8509. @Builder
  8510. PlayListSheet() {
  8511. Column() {
  8512. this.PlayList()
  8513. }
  8514. .width('100%')
  8515. .height('100%')
  8516. }
  8517. @State titleStr: string = ''
  8518. @State ablumStr: string = ''
  8519. @State artistStr: string = ''
  8520. @State lyricConStr: string = ''
  8521. @State currentEditItem: string = ''
  8522. @State yearStr: string = ''
  8523. @State trackStr: string = ''
  8524. @State genreStr: string = ''
  8525. @State imagePathStr: string = ''
  8526. @State albumArtistStr: string = ''
  8527. @State composerStr: string = ''
  8528. @State lyricistStr: string = ''
  8529. @State commentStr: string = ''
  8530. @State discStr: string = ''
  8531. doUpdateData() {
  8532. setTimeout(async () => {
  8533. if (this.modeType === 0) {
  8534. this.deleteCache(this.currentPath)
  8535. await this.resetAndLoadFirstPage();
  8536. }else if (this.modeType === 1){
  8537. await this.resetAndLoadFirstPage();
  8538. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8539. }
  8540. }, 500)
  8541. }
  8542. doAllUpdateData() {
  8543. setTimeout(async () => {
  8544. if (this.modeType === 0) {
  8545. this.deleteCache(this.currentPath)
  8546. await this.resetAndLoadFirstPage();
  8547. }else{
  8548. await this.resetAndLoadFirstPage();
  8549. }
  8550. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8551. workerInstance.postMessage({ code: 3, data: this.context });
  8552. workerInstance.postMessage({ code: 4, data: this.context });
  8553. }, 999)
  8554. }
  8555. private delayMs(ms: number): Promise<void> {
  8556. return new Promise(resolve => {
  8557. setTimeout(() => resolve(), ms);
  8558. });
  8559. }
  8560. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  8561. if (!items || items.length === 0) {
  8562. return;
  8563. }
  8564. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  8565. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  8566. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  8567. if (!this.isScrolling || items.length <= directAppendThreshold) {
  8568. this.videoLocalList.push(...items);
  8569. this.dataSource.appendArrayData(items);
  8570. return;
  8571. }
  8572. const chunkSize = isHeavyGridWaterMode
  8573. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  8574. : (isMediaLibraryListMode
  8575. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  8576. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  8577. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  8578. for (let index = 0; index < items.length; index += chunkSize) {
  8579. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  8580. this.videoLocalList.push(...chunk);
  8581. this.dataSource.appendArrayData(chunk);
  8582. if (index + chunkSize < items.length) {
  8583. await this.delayMs(chunkDelay);
  8584. }
  8585. }
  8586. }
  8587. /**
  8588. * 加载指定页的数据
  8589. */
  8590. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  8591. try {
  8592. // 1. 检查缓存
  8593. if (this.pageCache.has(pageIndex)) {
  8594. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  8595. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8596. const cachedData = this.pageCache.get(pageIndex)!;
  8597. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  8598. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  8599. if (cachedHasMore !== undefined) {
  8600. this.hasMoreData = cachedHasMore;
  8601. }
  8602. if (cachedTotal !== undefined) {
  8603. this.totalCount = cachedTotal;
  8604. if (this.modeType === 1) {
  8605. this.mediaKuCount = cachedTotal;
  8606. }
  8607. }
  8608. if (append) {
  8609. this.prefetchListThumbsFromItems(cachedData, 26);
  8610. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8611. await this.appendItemsSmoothly(cachedData);
  8612. } else {
  8613. this.videoLocalList = cachedData;
  8614. this.dataSource.pushArrayData(this.videoLocalList);
  8615. if (inMediaLibraryWarmup) {
  8616. this.prefetchListThumbsFromItems(cachedData, 8);
  8617. } else {
  8618. this.prefetchListThumbsFromItems(cachedData, 30);
  8619. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8620. }
  8621. }
  8622. this.setButtonStatus();
  8623. if (inMediaLibraryWarmup) {
  8624. this.scheduleAlphaBetRebuild(900);
  8625. } else {
  8626. this.markAlphaBetDirty();
  8627. }
  8628. if (this.hasMoreData) {
  8629. if (inMediaLibraryWarmup) {
  8630. if (this.mediaLibraryWarmupPrefetchTimer) {
  8631. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8632. }
  8633. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8634. this.mediaLibraryWarmupPrefetchTimer = 0;
  8635. if (this.modeType === 1 && !this.isCanBack) {
  8636. this.prefetchFollowingPages(pageIndex + 1);
  8637. }
  8638. }, 900) as number;
  8639. } else {
  8640. this.prefetchFollowingPages(pageIndex + 1);
  8641. }
  8642. }
  8643. return;
  8644. }
  8645. this.isLoadingPage = true;
  8646. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  8647. // 2. 构造查询参数
  8648. const options: PageQueryOptions = {
  8649. pageIndex: pageIndex,
  8650. pageSize: this.pageSize,
  8651. sortType: this.sortType,
  8652. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8653. isShowFileName: this.isShowFileName
  8654. };
  8655. // 根据 modeType 补充查询条件
  8656. if (this.modeType === 0) {
  8657. options.parentPath = this.currentPath;
  8658. }
  8659. // 3. 执行查询
  8660. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8661. switch (this.modeType) {
  8662. case 0:
  8663. result = await this.table.queryByParentPathPaged(options);
  8664. result.items = this.filterOutLocalIsoItems(result.items);
  8665. // modeType=0时,第一页需要添加文件夹列表
  8666. if (pageIndex === 0 && !this.isSearchMode) {
  8667. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  8668. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  8669. result.items = [...directories, ...isoItems, ...result.items];
  8670. result.totalCount += directories.length + isoItems.length;
  8671. }
  8672. break;
  8673. case 1:
  8674. result = await this.table.queryMediaLibraryPaged(options);
  8675. break;
  8676. case 2:
  8677. result = await this.table.queryArtistsPaged(options);
  8678. break;
  8679. case 3:
  8680. result = await this.table.queryAlbumsPaged(options);
  8681. break;
  8682. default:
  8683. result = await this.table.queryMediaLibraryPaged(options);
  8684. break;
  8685. }
  8686. if (!result || result.items.length === 0) {
  8687. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  8688. this.isLoadingPage = false;
  8689. this.hasMoreData = false;
  8690. // 仅首页为空时清空,后续页为空只终止继续分页
  8691. if (pageIndex === 0) {
  8692. this.totalCount = 0;
  8693. this.videoLocalList = [];
  8694. this.dataSource.pushArrayData(this.videoLocalList);
  8695. this.setButtonStatus();
  8696. this.markAlphaBetDirty();
  8697. }
  8698. return;
  8699. }
  8700. // 4. 更新状态和缓存
  8701. this.totalCount = result.totalCount;
  8702. this.hasMoreData = result.hasMore;
  8703. if (this.modeType === 1) {
  8704. this.mediaKuCount = result.totalCount;
  8705. }
  8706. if (this.modeType === 2 && result.countMap) {
  8707. this.mergeArtistCountMap(result.countMap);
  8708. } else if (this.modeType === 3 && result.countMap) {
  8709. this.mergeAlbumCountMap(result.countMap);
  8710. }
  8711. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  8712. // 缓存管理 - 只保留最近3页
  8713. this.pageCache.set(pageIndex, result.items);
  8714. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  8715. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  8716. this.cleanOldCache(pageIndex);
  8717. // 5. 更新显示列表
  8718. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8719. if (append) {
  8720. this.prefetchListThumbsFromItems(result.items, 26);
  8721. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8722. await this.appendItemsSmoothly(result.items);
  8723. } else {
  8724. this.videoLocalList = result.items;
  8725. this.dataSource.pushArrayData(this.videoLocalList);
  8726. if (inMediaLibraryWarmup) {
  8727. this.prefetchListThumbsFromItems(result.items, 8);
  8728. } else {
  8729. this.prefetchListThumbsFromItems(result.items, 30);
  8730. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8731. }
  8732. }
  8733. this.setButtonStatus();
  8734. if (inMediaLibraryWarmup) {
  8735. this.scheduleAlphaBetRebuild(900);
  8736. } else {
  8737. this.markAlphaBetDirty();
  8738. }
  8739. if (inMediaLibraryWarmup) {
  8740. if (this.mediaLibraryWarmupPrefetchTimer) {
  8741. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8742. }
  8743. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8744. this.mediaLibraryWarmupPrefetchTimer = 0;
  8745. if (this.modeType === 1 && !this.isCanBack) {
  8746. this.prefetchFollowingPages(pageIndex + 1);
  8747. }
  8748. }, 900) as number;
  8749. } else {
  8750. this.prefetchFollowingPages(pageIndex + 1);
  8751. }
  8752. this.isLoadingPage = false;
  8753. } catch (err) {
  8754. const error = err as Error;
  8755. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  8756. // ToastUtil.showToast('加载数据失败');
  8757. this.isLoadingPage = false;
  8758. this.hasMoreData = false;
  8759. }
  8760. }
  8761. /**
  8762. * 清理旧缓存 - 只保留当前页前后各1页
  8763. */
  8764. private cleanOldCache(currentPage: number): void {
  8765. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  8766. const keysToDelete: number[] = [];
  8767. this.pageCache.forEach((_, page) => {
  8768. if (!pagesToKeep.has(page)) {
  8769. keysToDelete.push(page);
  8770. }
  8771. });
  8772. keysToDelete.forEach(page => {
  8773. this.pageCache.delete(page);
  8774. this.pageHasMoreCache.delete(page);
  8775. this.pageTotalCountCache.delete(page);
  8776. });
  8777. if (keysToDelete.length > 0) {
  8778. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  8779. }
  8780. }
  8781. private async prefetchNextPage(nextPage: number): Promise<void> {
  8782. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8783. return;
  8784. }
  8785. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  8786. return;
  8787. }
  8788. const expectedModeType = this.modeType;
  8789. const expectedSortType = this.sortType;
  8790. const expectedIsShowFileName = this.isShowFileName;
  8791. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  8792. const expectedParentPath = this.currentPath;
  8793. this.prefetchingPages.add(nextPage);
  8794. try {
  8795. const options: PageQueryOptions = {
  8796. pageIndex: nextPage,
  8797. pageSize: this.pageSize,
  8798. sortType: this.sortType,
  8799. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8800. isShowFileName: this.isShowFileName
  8801. };
  8802. if (this.modeType === 0) {
  8803. options.parentPath = this.currentPath;
  8804. }
  8805. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8806. switch (this.modeType) {
  8807. case 0:
  8808. result = await this.table.queryByParentPathPaged(options);
  8809. result.items = this.filterOutLocalIsoItems(result.items);
  8810. break;
  8811. case 1:
  8812. result = await this.table.queryMediaLibraryPaged(options);
  8813. break;
  8814. case 2:
  8815. result = await this.table.queryArtistsPaged(options);
  8816. if (result.countMap) {
  8817. this.mergeArtistCountMap(result.countMap);
  8818. }
  8819. break;
  8820. case 3:
  8821. result = await this.table.queryAlbumsPaged(options);
  8822. if (result.countMap) {
  8823. this.mergeAlbumCountMap(result.countMap);
  8824. }
  8825. break;
  8826. default:
  8827. result = await this.table.queryMediaLibraryPaged(options);
  8828. break;
  8829. }
  8830. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  8831. if (expectedModeType !== this.modeType ||
  8832. expectedSortType !== this.sortType ||
  8833. expectedIsShowFileName !== this.isShowFileName ||
  8834. expectedSearchKeyword !== currentSearchKeyword ||
  8835. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  8836. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  8837. return;
  8838. }
  8839. this.pageHasMoreCache.set(nextPage, result.hasMore);
  8840. this.pageTotalCountCache.set(nextPage, result.totalCount);
  8841. if (result.items.length > 0) {
  8842. this.pageCache.set(nextPage, result.items);
  8843. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  8844. this.cleanOldCache(nextPage);
  8845. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  8846. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  8847. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  8848. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  8849. Logger.info('heanup LocalMusic',
  8850. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  8851. this.scheduleLoadNextPage(8);
  8852. }
  8853. }
  8854. }
  8855. } catch (err) {
  8856. const error = err as Error;
  8857. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  8858. } finally {
  8859. this.prefetchingPages.delete(nextPage);
  8860. }
  8861. }
  8862. private mergeArtistCountMap(countMap: Map<string, number>): void {
  8863. const nextMap = new Map(this.artistSongCountMap);
  8864. countMap.forEach((count, artist) => {
  8865. nextMap.set(artist, count);
  8866. });
  8867. this.artistSongCountMap = nextMap;
  8868. }
  8869. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  8870. const nextMap = new Map(this.albumSongCountMap);
  8871. countMap.forEach((count, album) => {
  8872. nextMap.set(album, count);
  8873. });
  8874. this.albumSongCountMap = nextMap;
  8875. }
  8876. private getArtistSongCount(artist: string): number {
  8877. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  8878. }
  8879. private getAlbumSongCount(album: string): number {
  8880. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  8881. }
  8882. /**
  8883. * 加载文件夹列表(仅用于modeType=0的首页模式)
  8884. */
  8885. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  8886. try {
  8887. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  8888. // 检查缓存
  8889. const cacheKey = curPath + "_dirList";
  8890. const cachedDirList = this.findCache(cacheKey);
  8891. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  8892. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  8893. return cachedDirList as VideoItem[];
  8894. }
  8895. // 从文件系统读取
  8896. const fileList = FileUtil.listFileSync(curPath);
  8897. const directories: VideoItem[] = [];
  8898. for (let i = 0; i < fileList.length; i++) {
  8899. const path = curPath + '/' + fileList[i];
  8900. if (FileUtil.isDirectory(path)) {
  8901. const item: VideoItem = new VideoItem(
  8902. fileList[i].toString(),
  8903. fileList[i].toString(),
  8904. path,
  8905. CommonConstants.TYPE_IS_DIR,
  8906. 0,
  8907. ''
  8908. );
  8909. if (this.isShowDir(item.name)) {
  8910. directories.push(item);
  8911. }
  8912. }
  8913. }
  8914. // 排序
  8915. Utility.doSortListAscending(directories);
  8916. // 缓存文件夹列表
  8917. if (curPath === this.rootPath) {
  8918. this.dirList = directories;
  8919. this.addCache(cacheKey, directories);
  8920. }
  8921. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  8922. return directories;
  8923. } catch (err) {
  8924. const error = err as Error;
  8925. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  8926. return [];
  8927. }
  8928. }
  8929. /**
  8930. * 构建播放队列(避免一次性加载全量)
  8931. */
  8932. private buildPlayQueueFromView(): Array<VideoItem> {
  8933. if (this.modeType === 4) {
  8934. this.playQueueScope = 'playlist';
  8935. return this.currentSongList;
  8936. }
  8937. if (this.isHistory) {
  8938. this.playQueueScope = 'history';
  8939. return this.historyList;
  8940. }
  8941. if (this.isFavMusic) {
  8942. this.playQueueScope = 'fav';
  8943. return this.favList;
  8944. }
  8945. this.playQueueScope = 'view';
  8946. return Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8947. }
  8948. private openSpecialLocalList(target: string): void {
  8949. this.mType = 0
  8950. this.isShowDrawer = false
  8951. this.offsetX = 0
  8952. this.isHistory = false
  8953. this.isFavMusic = false
  8954. if (target === 'recent') {
  8955. this.titleName = '最近播放'
  8956. this.currentTitleName = '最近播放'
  8957. this.currentTitleCover = $r('app.media.alt')
  8958. this.updateListData(this.historyList, true)
  8959. if (ArrayUtil.isNotEmpty(this.historyList)) {
  8960. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  8961. }
  8962. this.isHistory = true
  8963. return
  8964. }
  8965. if (target === 'favorite') {
  8966. this.titleName = '我的收藏'
  8967. this.currentTitleName = '我的收藏'
  8968. this.currentTitleCover = $r('app.media.alt')
  8969. this.updateListData(this.favList, true)
  8970. if (ArrayUtil.isNotEmpty(this.favList)) {
  8971. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  8972. }
  8973. this.isFavMusic = true
  8974. }
  8975. }
  8976. private async tryLoadNextPageForPlayback(): Promise<void> {
  8977. if (this.playQueueScope === 'find_paged_local') {
  8978. // 发现页的本地随机分页队列单独补页,不去动主媒体库列表状态。
  8979. await this.loadMoreFindPagedLocalSongs();
  8980. return;
  8981. }
  8982. if (this.playQueueScope !== 'view') {
  8983. return;
  8984. }
  8985. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8986. return;
  8987. }
  8988. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  8989. return;
  8990. }
  8991. await this.loadNextPage();
  8992. const nextList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8993. if (nextList.length > this.songList.length) {
  8994. this.songList = nextList;
  8995. this.sonDataSource.pushArrayData(this.songList);
  8996. }
  8997. }
  8998. private async loadMoreFindPagedLocalSongs(): Promise<void> {
  8999. if (!this.findPagedLocalQueueHasMore || this.isLoadingFindPagedLocalQueue) {
  9000. return;
  9001. }
  9002. this.isLoadingFindPagedLocalQueue = true;
  9003. const nextPage = this.findPagedLocalQueuePageIndex + 1;
  9004. Logger.info(TAG,
  9005. `loadMoreFindPagedLocalSongs: page=${nextPage}, size=${this.findPagedLocalQueuePageSize}, ` +
  9006. `loaded=${this.songList.length}, total=${this.findPagedLocalQueueTotalCount}`);
  9007. try {
  9008. // 继续按发现页建立队列时的排序规则查询下一页,保证后续页和初始页顺序一致。
  9009. const result = await this.table.queryMediaLibraryPaged({
  9010. pageIndex: nextPage,
  9011. pageSize: this.findPagedLocalQueuePageSize,
  9012. sortType: this.findPagedLocalQueueSortType,
  9013. isShowFileName: this.isShowFileName
  9014. });
  9015. this.findPagedLocalQueuePageIndex = nextPage;
  9016. this.findPagedLocalQueueHasMore = result.hasMore;
  9017. if (result.totalCount > 0) {
  9018. this.findPagedLocalQueueTotalCount = result.totalCount;
  9019. this.totalCount = result.totalCount;
  9020. }
  9021. if (!result.items || result.items.length === 0) {
  9022. return;
  9023. }
  9024. const existingPaths = new Set(this.songList.map((item: VideoItem) => item.filePath));
  9025. // 随机播放过程中可能已经把“未加载页里的歌曲”临时插进队列,这里要去重后再追加。
  9026. const newItems = result.items.filter((item: VideoItem) => !existingPaths.has(item.filePath));
  9027. if (newItems.length === 0) {
  9028. return;
  9029. }
  9030. this.songList.push(...newItems);
  9031. this.currentSongList = this.songList;
  9032. this.sonDataSource.appendArrayData(newItems);
  9033. PreferencesUtil.putSync('LastMusicList', this.songList);
  9034. } catch (error) {
  9035. Logger.error(TAG, `loadMoreFindPagedLocalSongs failed: ${(error as Error).message}`);
  9036. } finally {
  9037. this.isLoadingFindPagedLocalQueue = false;
  9038. }
  9039. }
  9040. /**
  9041. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  9042. * 当播放列表弹窗滚动到底部时调用
  9043. */
  9044. private async loadMoreNavidromeSongs(): Promise<void> {
  9045. const beforeCount = this.songList.length;
  9046. const hasMore = hasMoreData();
  9047. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  9048. if (!hasMore) {
  9049. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  9050. return;
  9051. }
  9052. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  9053. const success = await triggerLoadMoreSongs(1);
  9054. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  9055. if (success) {
  9056. // 获取更新后的完整列表
  9057. const updatedList = getNavidromeVideoItems();
  9058. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  9059. if (updatedList.length > beforeCount) {
  9060. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  9061. this.songList = updatedList;
  9062. this.sonDataSource.pushArrayData(this.songList);
  9063. } else {
  9064. Logger.info('heanup', '列表长度未增加');
  9065. }
  9066. } else {
  9067. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  9068. }
  9069. }
  9070. /**
  9071. * 重置分页状态并加载首页
  9072. */
  9073. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  9074. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  9075. this.currentPage = 0;
  9076. if (clearExistingList) {
  9077. this.videoLocalList = [];
  9078. }
  9079. this.pageCache.clear();
  9080. this.pageHasMoreCache.clear();
  9081. this.pageTotalCountCache.clear();
  9082. this.prefetchingPages.clear();
  9083. this.hasMoreData = true;
  9084. this.totalCount = 0;
  9085. this.lastScrollTriggerPage = -1;
  9086. this.lastVisibleEndIndex = -1;
  9087. this.listScrollAlphaCheckAt = 0;
  9088. this.listScrollPagingCheckAt = 0;
  9089. this.listScrollLastAlphaStart = -1;
  9090. this.listScrollLastPagingEnd = -1;
  9091. this.gridScrollPagingCheckAt = 0;
  9092. this.gridScrollLastPagingEnd = -1;
  9093. this.waterScrollPagingCheckAt = 0;
  9094. this.waterScrollLastPagingEnd = -1;
  9095. this.listVisibleStart = -1;
  9096. this.listVisibleEnd = -1;
  9097. this.listThumbWarmupCheckAt = 0;
  9098. this.listThumbWarmupStart = -1;
  9099. this.listThumbWarmupEnd = -1;
  9100. this.gridThumbWarmupCheckAt = 0;
  9101. this.gridThumbWarmupStart = -1;
  9102. this.gridThumbWarmupEnd = -1;
  9103. this.waterThumbWarmupCheckAt = 0;
  9104. this.waterThumbWarmupStart = -1;
  9105. this.waterThumbWarmupEnd = -1;
  9106. this.gridVisibleStart = -1;
  9107. this.gridVisibleEnd = -1;
  9108. this.waterVisibleStart = -1;
  9109. this.waterVisibleEnd = -1;
  9110. this.gridWaterLastActiveTs = 0;
  9111. this.isPagingTransition = false;
  9112. if (this.pagingScheduleTimer) {
  9113. clearTimeout(this.pagingScheduleTimer);
  9114. this.pagingScheduleTimer = 0;
  9115. }
  9116. if (this.gridWaterScrollIdleTimer) {
  9117. clearTimeout(this.gridWaterScrollIdleTimer);
  9118. this.gridWaterScrollIdleTimer = 0;
  9119. }
  9120. this.coverThumbCache.clearPending();
  9121. this.pendingCoverThumbRefresh = false;
  9122. if (this.modeType === 2) {
  9123. this.artistSongCountMap = new Map();
  9124. } else if (this.modeType === 3) {
  9125. this.albumSongCountMap = new Map();
  9126. }
  9127. await this.loadPage(0, false);
  9128. }
  9129. private markGridWaterScrollingActive(): void {
  9130. if (!this.isScrolling) {
  9131. this.isScrolling = true;
  9132. }
  9133. const now = Date.now();
  9134. if (now - this.gridWaterLastActiveTs < 80) {
  9135. return;
  9136. }
  9137. this.gridWaterLastActiveTs = now;
  9138. if (this.gridWaterScrollIdleTimer) {
  9139. clearTimeout(this.gridWaterScrollIdleTimer);
  9140. }
  9141. this.gridWaterScrollIdleTimer = setTimeout(() => {
  9142. this.gridWaterScrollIdleTimer = 0;
  9143. if (this.isScrolling) {
  9144. this.isScrolling = false;
  9145. }
  9146. this.flushPendingCoverThumbRefresh();
  9147. }, 120);
  9148. }
  9149. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  9150. if (!this.autoHideTitle) {
  9151. return;
  9152. }
  9153. const now = Date.now();
  9154. if (now - this.titleBarLastCheckTs < 36) {
  9155. return;
  9156. }
  9157. this.titleBarLastCheckTs = now;
  9158. const delta = currentOffsetY - this.prevOffsetY;
  9159. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  9160. return;
  9161. }
  9162. if (delta > 0) {
  9163. if (this.isShowTitleBar) {
  9164. this.isShowTitleBar = false;
  9165. }
  9166. } else {
  9167. if (!this.isShowTitleBar) {
  9168. this.isShowTitleBar = true;
  9169. }
  9170. }
  9171. this.prevOffsetY = currentOffsetY;
  9172. }
  9173. private shouldPrefetchSecondPage(): boolean {
  9174. if (this.isMediaLibraryListMode()) {
  9175. return this.pageSize <= 120;
  9176. }
  9177. if (this.pageSize > 60) {
  9178. return false;
  9179. }
  9180. return this.isGridMusic || this.twoFingerType == 4;
  9181. }
  9182. private isMediaLibraryListMode(): boolean {
  9183. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  9184. }
  9185. private isMediaLibraryWarmupWindow(): boolean {
  9186. if (this.modeType !== 1 || this.isCanBack) {
  9187. return false;
  9188. }
  9189. if (this.mediaLibraryEnterTs <= 0) {
  9190. return false;
  9191. }
  9192. return Date.now() - this.mediaLibraryEnterTs < 1800;
  9193. }
  9194. private getDynamicPreloadStartRatio(): number {
  9195. if (this.twoFingerType == 4) {
  9196. return 0.10;
  9197. }
  9198. if (this.isGridMusic) {
  9199. return 0.14;
  9200. }
  9201. if (this.isMediaLibraryListMode()) {
  9202. return 0.12;
  9203. }
  9204. return this.preloadStartRatio;
  9205. }
  9206. private getDynamicAppendStartRatio(): number {
  9207. if (this.twoFingerType == 4) {
  9208. return 0.18;
  9209. }
  9210. if (this.isGridMusic) {
  9211. return 0.22;
  9212. }
  9213. if (this.isMediaLibraryListMode()) {
  9214. return 0.22;
  9215. }
  9216. return this.appendStartRatio;
  9217. }
  9218. private getDynamicEarlyAppendReserveCount(): number {
  9219. if (this.twoFingerType == 4) {
  9220. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9221. }
  9222. if (this.isGridMusic) {
  9223. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  9224. }
  9225. if (this.isMediaLibraryListMode()) {
  9226. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  9227. }
  9228. return this.earlyAppendReserveCount;
  9229. }
  9230. private prefetchFollowingPages(nextPage: number): void {
  9231. void this.prefetchNextPage(nextPage);
  9232. if (this.shouldPrefetchSecondPage()) {
  9233. void this.prefetchNextPage(nextPage + 1);
  9234. }
  9235. }
  9236. private scrollToTopForCurrentLayout(): void {
  9237. if (this.twoFingerType == 4) {
  9238. this.waterScroller.scrollEdge(Edge.Top);
  9239. this.scroller.scrollEdge(Edge.Top);
  9240. return;
  9241. }
  9242. if (this.isGridMusic) {
  9243. this.scroller.scrollEdge(Edge.Top);
  9244. return;
  9245. }
  9246. this.listScroller.scrollEdge(Edge.Top);
  9247. }
  9248. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  9249. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9250. if (coverVersion < -1) {
  9251. return fallback;
  9252. }
  9253. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9254. return fallback;
  9255. }
  9256. const sourceUri = item.pixelMapPath as string;
  9257. this.initCoverThumbCacheIfNeeded();
  9258. const targetSize = this.getListThumbTargetSize();
  9259. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9260. if (cachedThumb) {
  9261. return cachedThumb;
  9262. }
  9263. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9264. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  9265. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  9266. const isNearVisible = !hasRange ||
  9267. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  9268. if (isNearVisible) {
  9269. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9270. }
  9271. }
  9272. return sourceUri;
  9273. }
  9274. private getListThumbTargetSize(): number {
  9275. if (this.twoFingerType == 1) {
  9276. return 96;
  9277. }
  9278. if (this.twoFingerType == 2) {
  9279. return 112;
  9280. }
  9281. return 128;
  9282. }
  9283. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  9284. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  9285. return;
  9286. }
  9287. this.initCoverThumbCacheIfNeeded();
  9288. const targetSize = this.getListThumbTargetSize();
  9289. const maxCount = Math.min(limit, items.length);
  9290. for (let i = 0; i < maxCount; i++) {
  9291. const item = items[i];
  9292. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9293. continue;
  9294. }
  9295. const sourceUri = item.pixelMapPath as string;
  9296. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9297. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9298. }
  9299. }
  9300. }
  9301. private warmupListVisibleThumbs(start: number, end: number): void {
  9302. if (!this.isMediaLibraryListMode()) {
  9303. return;
  9304. }
  9305. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9306. return;
  9307. }
  9308. const now = Date.now();
  9309. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  9310. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  9311. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  9312. return;
  9313. }
  9314. this.listThumbWarmupCheckAt = now;
  9315. this.listThumbWarmupStart = start;
  9316. this.listThumbWarmupEnd = end;
  9317. this.initCoverThumbCacheIfNeeded();
  9318. const targetSize = this.getListThumbTargetSize();
  9319. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  9320. const begin = Math.max(0, start - 4);
  9321. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9322. for (let index = begin; index <= last; index++) {
  9323. const item = this.videoLocalList[index];
  9324. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9325. continue;
  9326. }
  9327. const sourceUri = item.pixelMapPath as string;
  9328. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9329. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9330. }
  9331. }
  9332. }
  9333. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  9334. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  9335. return;
  9336. }
  9337. this.initCoverThumbCacheIfNeeded();
  9338. const isWater = this.twoFingerType == 4;
  9339. const targetSize = this.getCoverThumbTargetSize(isWater);
  9340. const maxCount = Math.min(limit, items.length);
  9341. for (let i = 0; i < maxCount; i++) {
  9342. const item = items[i];
  9343. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9344. continue;
  9345. }
  9346. const sourceUri = item.pixelMapPath as string;
  9347. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9348. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9349. }
  9350. }
  9351. }
  9352. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  9353. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  9354. return;
  9355. }
  9356. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9357. return;
  9358. }
  9359. const now = Date.now();
  9360. let lastStart = -1;
  9361. let lastEnd = -1;
  9362. let lastCheckAt = 0;
  9363. if (isWater) {
  9364. lastStart = this.waterThumbWarmupStart;
  9365. lastEnd = this.waterThumbWarmupEnd;
  9366. lastCheckAt = this.waterThumbWarmupCheckAt;
  9367. } else {
  9368. lastStart = this.gridThumbWarmupStart;
  9369. lastEnd = this.gridThumbWarmupEnd;
  9370. lastCheckAt = this.gridThumbWarmupCheckAt;
  9371. }
  9372. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  9373. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  9374. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  9375. return;
  9376. }
  9377. if (isWater) {
  9378. this.waterThumbWarmupCheckAt = now;
  9379. this.waterThumbWarmupStart = start;
  9380. this.waterThumbWarmupEnd = end;
  9381. } else {
  9382. this.gridThumbWarmupCheckAt = now;
  9383. this.gridThumbWarmupStart = start;
  9384. this.gridThumbWarmupEnd = end;
  9385. }
  9386. this.initCoverThumbCacheIfNeeded();
  9387. const columns = isWater ? Math.max(this.columns, 1) :
  9388. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9389. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  9390. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  9391. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9392. const targetSize = this.getCoverThumbTargetSize(isWater);
  9393. for (let index = begin; index <= last; index++) {
  9394. const item = this.videoLocalList[index];
  9395. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9396. continue;
  9397. }
  9398. const sourceUri = item.pixelMapPath as string;
  9399. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9400. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9401. }
  9402. }
  9403. }
  9404. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  9405. coverVersion: number = 0): ResourceStr {
  9406. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9407. if (coverVersion < -1) {
  9408. return fallback;
  9409. }
  9410. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9411. return fallback;
  9412. }
  9413. const sourceUri = item.pixelMapPath as string;
  9414. this.initCoverThumbCacheIfNeeded();
  9415. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  9416. const targetSize = this.getCoverThumbTargetSize(isWater);
  9417. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9418. if (cachedThumb) {
  9419. return cachedThumb;
  9420. }
  9421. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  9422. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  9423. const columns = isWater ? Math.max(this.columns, 1) :
  9424. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9425. const preloadBuffer = Math.max(columns * 2, 8);
  9426. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  9427. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  9428. if (!isRemoteCover && isNearVisible) {
  9429. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9430. }
  9431. if (!this.isScrolling) {
  9432. return sourceUri;
  9433. }
  9434. if (isNearVisible) {
  9435. return sourceUri;
  9436. }
  9437. return fallback;
  9438. }
  9439. private flushPendingCoverThumbRefresh(): void {
  9440. if (!this.pendingCoverThumbRefresh) {
  9441. return;
  9442. }
  9443. this.pendingCoverThumbRefresh = false;
  9444. this.coverThumbVersion++;
  9445. }
  9446. private initCoverThumbCacheIfNeeded(): void {
  9447. if (this.coverThumbCacheReady) {
  9448. return;
  9449. }
  9450. this.coverThumbCache.setContext(this.context);
  9451. this.coverThumbCache.setOnThumbReady(() => {
  9452. if (this.isScrolling) {
  9453. this.pendingCoverThumbRefresh = true;
  9454. return;
  9455. }
  9456. this.coverThumbVersion++;
  9457. });
  9458. this.coverThumbCacheReady = true;
  9459. }
  9460. private getCoverThumbTargetSize(isWater: boolean): number {
  9461. if (isWater) {
  9462. if (this.columns >= 4) {
  9463. return 160;
  9464. }
  9465. if (this.columns == 3) {
  9466. return 200;
  9467. }
  9468. return 260;
  9469. }
  9470. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  9471. if (this.twoFingerType == 1) {
  9472. return baseSize;
  9473. }
  9474. if (this.twoFingerType == 2) {
  9475. return Math.floor(baseSize * 1.1);
  9476. }
  9477. return Math.floor(baseSize * 1.15);
  9478. }
  9479. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  9480. if (this.videoLocalList.length <= 0) {
  9481. return;
  9482. }
  9483. const columns = Math.max(this.columns, 1);
  9484. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  9485. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  9486. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  9487. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  9488. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  9489. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  9490. this.waterVisibleStart = startIndex;
  9491. this.waterVisibleEnd = estimatedEnd;
  9492. this.lastVisibleEndIndex = estimatedEnd;
  9493. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  9494. const now = Date.now();
  9495. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  9496. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  9497. this.waterScrollPagingCheckAt = now;
  9498. this.waterScrollLastPagingEnd = estimatedEnd;
  9499. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  9500. }
  9501. }
  9502. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  9503. if (this.modeType === 4) {
  9504. return;
  9505. }
  9506. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  9507. return;
  9508. }
  9509. if (this.isHistory || this.isFavMusic) {
  9510. return;
  9511. }
  9512. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9513. return;
  9514. }
  9515. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  9516. return;
  9517. }
  9518. const nextPage = this.currentPage + 1;
  9519. const next2Page = this.currentPage + 2;
  9520. const totalLoaded = this.videoLocalList.length;
  9521. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  9522. const remainCount = this.videoLocalList.length - endIndex - 1;
  9523. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  9524. const appendStartRatio = this.getDynamicAppendStartRatio();
  9525. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  9526. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  9527. if (seenRatio >= preloadStartRatio) {
  9528. if (!this.pageCache.has(nextPage)) {
  9529. void this.prefetchNextPage(nextPage);
  9530. }
  9531. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  9532. void this.prefetchNextPage(next2Page);
  9533. }
  9534. }
  9535. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  9536. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  9537. const shouldGapAppend = this.pageCache.has(nextPage) &&
  9538. seenRatio >= (appendStartRatio - 0.08) &&
  9539. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9540. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  9541. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  9542. return;
  9543. }
  9544. if (this.lastScrollTriggerPage === this.currentPage) {
  9545. return;
  9546. }
  9547. this.lastScrollTriggerPage = this.currentPage;
  9548. Logger.info('heanup LocalMusic',
  9549. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  9550. this.scheduleLoadNextPage(8);
  9551. }
  9552. private scheduleLoadNextPage(delayMs: number = 0): void {
  9553. if (this.pagingScheduleTimer) {
  9554. return;
  9555. }
  9556. this.pagingScheduleTimer = setTimeout(() => {
  9557. this.pagingScheduleTimer = 0;
  9558. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9559. return;
  9560. }
  9561. void this.loadNextPage();
  9562. }, delayMs);
  9563. }
  9564. /**
  9565. * 加载下一页
  9566. */
  9567. private async loadNextPage(): Promise<void> {
  9568. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9569. return;
  9570. }
  9571. this.isPagingTransition = true;
  9572. this.currentPage++;
  9573. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  9574. try {
  9575. await this.loadPage(this.currentPage, true);
  9576. } finally {
  9577. this.isPagingTransition = false;
  9578. }
  9579. }
  9580. //编辑信息
  9581. async doEdit(item: VideoItem) {
  9582. if (!item) {
  9583. return
  9584. }
  9585. if (StrUtil.isEmpty(this.titleStr)) {
  9586. ToastUtil.showToast('标题不能为空')
  9587. return
  9588. }
  9589. //内嵌音乐标签不能开启监听
  9590. // this.deletionWatcher?.stop();
  9591. this.loadingDialogId = DialogHelper.showLoadingDialog()
  9592. if (isRemoteCloudType(item.type)) {
  9593. await this.saveRemoteSongEdit(item);
  9594. return;
  9595. }
  9596. await PermissionUtil.activatePermission(item.filePath)
  9597. let tempOutPath = ''
  9598. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  9599. if(!item.filePath.toLowerCase().includes(this.packName)){
  9600. tempOutPath = this.currentPath + '/' + item.fileName
  9601. }
  9602. console.info('onecold tempOutPath ='+tempOutPath)
  9603. //用户更改了封面,那就内嵌下封面
  9604. if(StrUtil.isNotEmpty(this.imagePathStr)){
  9605. const resultCover:boolean = await changeMusicCover(this.context,
  9606. item.filePath,this.imagePathStr,true,tempOutPath);
  9607. this.imagePathStr = ''
  9608. if(resultCover){
  9609. ToastUtil.showToast('内嵌封面成功')
  9610. }
  9611. }
  9612. const metadata:FFMpegTags = {
  9613. title: this.titleStr,
  9614. artist: this.artistStr,
  9615. album: this.ablumStr,
  9616. TYER:this.yearStr,
  9617. genre:this.genreStr,
  9618. track:this.trackStr,
  9619. album_artist:this.albumArtistStr,
  9620. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  9621. COMPOSER:this.composerStr,
  9622. lyricist:this.lyricistStr,
  9623. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  9624. comment:this.commentStr,
  9625. disc:this.discStr,
  9626. };
  9627. let newInput = item.filePath
  9628. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  9629. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  9630. newInput = tempOutPath
  9631. tempOutPath = ''
  9632. }
  9633. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  9634. ||newInput.toLowerCase().endsWith('.ape')
  9635. ||newInput.toLowerCase().endsWith('.dsf')
  9636. ||newInput.toLowerCase().endsWith('.dff');
  9637. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  9638. const result:boolean = await repairAudioMetadata(
  9639. newInput,
  9640. this.lyricConStr,
  9641. metadata,
  9642. true,
  9643. tempOutPath
  9644. );
  9645. // ToastUtil.showToast('result ='+ result)
  9646. if (result||isWav) {
  9647. if(!item.filePath.includes(this.packName)){
  9648. //内嵌成功的歌路径如果不是包含包名,则要入库
  9649. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  9650. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  9651. this.table.insert(newItem, (id: number) => {
  9652. //加入数据库
  9653. if(this.modeType==0){
  9654. this.deleteCache(this.currentPath)
  9655. this.getSortedFiles(this.currentPath)
  9656. }
  9657. });
  9658. }
  9659. const task = new taskpool.Task(
  9660. updateInfoDb,
  9661. this.context,
  9662. item.filePath,
  9663. this.titleStr,
  9664. this.artistStr,
  9665. this.ablumStr,
  9666. this.lyricConStr,
  9667. this.yearStr,this.genreStr,
  9668. this.trackStr,this.albumArtistStr,
  9669. this.composerStr, this.lyricistStr,
  9670. this.commentStr,this.discStr
  9671. );
  9672. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  9673. if (result) {
  9674. console.log(" onecold 编辑信息成功,数据库已同步");
  9675. if(isWav){
  9676. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  9677. }else{
  9678. ToastUtil.showToast('内嵌音乐标签成功')
  9679. }
  9680. this.isShowMoreView = false
  9681. this.name = this.titleStr
  9682. this.syncEditedFields(item)
  9683. if (item.filePath == this.currentSong?.filePath) {
  9684. this.currentSong.name = this.titleStr
  9685. this.artist = this.artistStr
  9686. this.currentSong.artist = this.artistStr
  9687. this.currentSong.album = this.ablumStr
  9688. this.currentSong.year = this.yearStr
  9689. this.currentSong.genre = this.genreStr
  9690. this.currentSong.track = this.trackStr
  9691. this.currentSong.lyricContent = this.lyricConStr
  9692. this.currentSong.ALBUMARTIST = this.albumArtistStr
  9693. this.currentSong.COMPOSER = this.composerStr
  9694. this.currentSong.LYRICIST = this.lyricistStr
  9695. this.currentSong.COMMENT = this.commentStr
  9696. }
  9697. this.syncListsAfterEdit(item.filePath)
  9698. this.doUpateEditedFields(item)
  9699. //this.doUpdateData()
  9700. } else {
  9701. // ToastUtil.showToast('保存失败' + error?.toString())
  9702. console.error(" onecold 编辑信息数据库失败 ");
  9703. }
  9704. // 关闭进度条
  9705. DialogHelper.closeDialog(this.loadingDialogId)
  9706. }).catch((error: Error) => {
  9707. // 关闭进度条
  9708. DialogHelper.closeDialog(this.loadingDialogId)
  9709. console.error('onecold Subtitle sync failed:', error);
  9710. });
  9711. console.log(' onecold 元数据标签更新成功,');
  9712. } else {
  9713. // 关闭进度条
  9714. DialogHelper.closeDialog(this.loadingDialogId)
  9715. ToastUtil.showToast('内嵌音乐标签失败')
  9716. console.log('onecold 内嵌音乐标签失败');
  9717. }
  9718. this.longItemFilePath = ''
  9719. this.tempLyricContent = ''
  9720. this.isShowEdit = false
  9721. }
  9722. private normalizeEditedCoverPath(path: string): string {
  9723. if (StrUtil.isEmpty(path)) {
  9724. return '';
  9725. }
  9726. const lowerPath = path.toLowerCase();
  9727. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  9728. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  9729. return path;
  9730. }
  9731. return fileUri.getUriFromPath(path);
  9732. }
  9733. private emitRemoteMetadataUpdated(item: VideoItem): void {
  9734. if (!item || StrUtil.isEmpty(item.filePath)) {
  9735. return;
  9736. }
  9737. const payload: WebDavMetadataUpdatePayload = {
  9738. filePath: item.filePath,
  9739. pixelMapPath: item.pixelMapPath,
  9740. isCustomCover: item.isCustomCover,
  9741. md5Str: item.md5Str,
  9742. name: item.name,
  9743. artist: item.artist
  9744. };
  9745. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  9746. emitter.emit(eventUpdate, { data: [payload] });
  9747. }
  9748. private syncRemoteManagerSong(item: VideoItem): void {
  9749. if (!item || StrUtil.isEmpty(item.filePath)) {
  9750. return;
  9751. }
  9752. const remoteManager = RemoteDriveManager.getInstance();
  9753. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  9754. if (!target) {
  9755. return;
  9756. }
  9757. this.mergeVideoItemFromSource(target, item);
  9758. }
  9759. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  9760. try {
  9761. this.syncEditedFields(item);
  9762. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  9763. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  9764. item.isCustomCover = 1;
  9765. }
  9766. this.name = this.titleStr;
  9767. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  9768. this.syncEditedFields(this.currentSong);
  9769. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  9770. mergeCoverWithPriority(this.currentSong, item.pixelMapPath, item.isCustomCover ?? 0);
  9771. this.cover = this.currentSong.pixelMapPath || item.pixelMapPath;
  9772. }
  9773. this.artist = this.currentSong.artist ?? '';
  9774. this.currentSong = cloneVideoItem(this.currentSong);
  9775. AppStorage.setOrCreate('currentSong', this.currentSong);
  9776. }
  9777. this.syncListsAfterEdit(item.filePath);
  9778. this.syncRemoteManagerSong(item);
  9779. await this.persistRemoteMetadataToDb(item);
  9780. this.emitRemoteMetadataUpdated(item);
  9781. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  9782. } catch (error) {
  9783. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  9784. ToastUtil.showToast('网盘歌曲编辑失败');
  9785. } finally {
  9786. DialogHelper.closeDialog(this.loadingDialogId);
  9787. this.longItemFilePath = '';
  9788. this.tempLyricContent = '';
  9789. this.isShowEdit = false;
  9790. this.imagePathStr = '';
  9791. this.isShowMoreView = false;
  9792. }
  9793. }
  9794. // 内嵌标签更新当前内嵌的Item
  9795. async doUpateEditedFields(item: VideoItem) {
  9796. // 找到当前项在 videoLocalList 中的索引
  9797. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  9798. if (index !== -1) {
  9799. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  9800. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  9801. // 只有当查询结果不为 null 时才更新列表
  9802. if (updatedItem !== null) {
  9803. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  9804. this.videoLocalList = [
  9805. ...this.videoLocalList.slice(0, index),
  9806. updatedItem,
  9807. ...this.videoLocalList.slice(index + 1)
  9808. ];
  9809. // 同步更新 LazyDataSource
  9810. this.dataSource.pushArrayData(this.videoLocalList)
  9811. } else {
  9812. ToastUtil.showToast('未找到更新的数据');
  9813. }
  9814. }
  9815. DialogHelper.closeDialog(this.loadingDialogId)
  9816. }
  9817. @Builder
  9818. editSheet(item: VideoItem) {
  9819. Scroll() {
  9820. Column() {
  9821. this.editDetail(item)
  9822. }
  9823. }
  9824. .width('100%')
  9825. .height('100%')
  9826. }
  9827. @Builder
  9828. editDetail(item: VideoItem) {
  9829. Column() {
  9830. if (item) {
  9831. Row() {
  9832. Stack() {
  9833. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  9834. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  9835. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  9836. item.pixelMapPath)
  9837. .fillColor(this.themeColor)
  9838. .height(88)
  9839. .width(88)
  9840. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9841. .borderRadius(12)
  9842. .clip(true)
  9843. .opacity(this.opacityItem)// 绑定透明度
  9844. .margin({ left: 25 })
  9845. }
  9846. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9847. .onClick(async () => {
  9848. const imagePath:string | undefined = await this.goSelectImage(item);
  9849. if (imagePath) {
  9850. //用户更改过图片
  9851. this.imagePathStr = imagePath
  9852. }
  9853. })
  9854. .width('28%')
  9855. Row() {
  9856. Column() {
  9857. Text(item.name)
  9858. .fontSize(17)
  9859. .maxLines(1)
  9860. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9861. .animation({
  9862. duration: 555,
  9863. curve: 'Linear',
  9864. })
  9865. .fontColor(this.themeColor)
  9866. .margin({ left: 8 })
  9867. Row() {
  9868. Text(item.artist)
  9869. .fontSize(14)
  9870. .maxLines(1)
  9871. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9872. .padding({ top: 8 })
  9873. .fontColor(this.themeColor)
  9874. .margin({ left: 8 })
  9875. }
  9876. }
  9877. .height('100%')
  9878. .width(100)
  9879. .layoutWeight(1)
  9880. .justifyContent(FlexAlign.Center)
  9881. .alignItems(HorizontalAlign.Start)
  9882. Column() {
  9883. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9884. Row(){
  9885. SymbolGlyph($r('sys.symbol.picture'))
  9886. .fontSize(18)
  9887. .fontColor([Color.White])
  9888. Text('获取封面')
  9889. .margin({ left: 4 })
  9890. .fontSize(11)
  9891. .fontColor(Color.White)
  9892. .fontWeight(480)
  9893. .textAlign(TextAlign.Center)
  9894. }
  9895. .justifyContent(FlexAlign.Center)
  9896. }
  9897. .height(38)
  9898. .width(100)
  9899. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9900. .backgroundColor(this.themeColor)
  9901. .stateEffect(true)
  9902. .margin({ right: 35 })
  9903. .onClick(async () => {
  9904. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9905. this.showTipsDialog();
  9906. return; // Return empty string when no API is configured
  9907. }
  9908. const imagePath:string | undefined = await this.doSearchCover(item,
  9909. this.titleStr,this.artistStr);
  9910. console.info('onecold imagePath = '+imagePath)
  9911. if (StrUtil.isNotEmpty(imagePath)) {
  9912. //用户更改过图片
  9913. this.imagePathStr = imagePath
  9914. ToastUtil.showToast('获取封面成功')
  9915. }else{
  9916. ToastUtil.showToast('获取封面失败,请重试')
  9917. }
  9918. })
  9919. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9920. Row(){
  9921. SymbolGlyph($r('sys.symbol.input_mode'))
  9922. .fontSize(18)
  9923. .fontColor([Color.White])
  9924. Text('获取歌词')
  9925. .margin({ left: 4 })
  9926. .fontSize(11)
  9927. .fontColor(Color.White)
  9928. .fontWeight(480)
  9929. .textAlign(TextAlign.Center)
  9930. }
  9931. .justifyContent(FlexAlign.Center)
  9932. }
  9933. .height(38)
  9934. .width(100)
  9935. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9936. .backgroundColor(this.themeColor)
  9937. .stateEffect(true)
  9938. .margin({ top: 9, right: 35 })
  9939. .onClick(async () => {
  9940. //判断有没有设置api
  9941. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  9942. if (StrUtil.isEmpty(apiUrl)) {
  9943. this.isLyricSetting = false
  9944. this.showTipsDialog()
  9945. return
  9946. }
  9947. let res: string | undefined = await getApiLyric(apiUrl,
  9948. this.titleStr, this.artistStr, false);
  9949. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9950. this.lyricConStr = res;
  9951. ToastUtil.showToast('获取歌词成功')
  9952. }else{
  9953. ToastUtil.showToast('获取歌词失败,请重试')
  9954. }
  9955. })
  9956. }
  9957. .justifyContent(FlexAlign.Start)
  9958. }
  9959. .height('100%')
  9960. .justifyContent(FlexAlign.Start)
  9961. .layoutWeight(1)
  9962. }
  9963. .width('100%')
  9964. .height(98)
  9965. Row() {
  9966. Text('标题:')
  9967. .fontSize(14)
  9968. .fontColor($r('app.color.text_color'))
  9969. .margin({ left: 22 })
  9970. TextInput({ text: this.titleStr })
  9971. .height(40)
  9972. .maxLines(1)
  9973. .fontSize(14)
  9974. .layoutWeight(1)
  9975. .fontColor($r('app.color.text_color'))
  9976. .margin({ right: 15, left: 10 })
  9977. .onChange((val: string) => {
  9978. this.titleStr = val
  9979. })
  9980. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  9981. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9982. .backgroundColor(this.themeColor)
  9983. .fontSize(10)
  9984. .margin({ right: 20})
  9985. .onClick(async () => {
  9986. let hwTags = await extractHwMediaMetadata(item.filePath)
  9987. let artist = hwTags?.artist|| '';
  9988. let title = hwTags?.title|| '';
  9989. let album = hwTags?.album|| '';
  9990. console.info('onecold 乱码修正 artist='+artist);
  9991. console.info('onecold 乱码修正 title='+title);
  9992. console.info('onecold 乱码修正 album='+album);
  9993. this.titleStr = title;
  9994. this.artistStr = artist;
  9995. this.ablumStr = album;
  9996. })
  9997. }
  9998. .width('100%')
  9999. .margin({ top: 10, bottom: 10 })
  10000. .justifyContent(FlexAlign.Start)
  10001. Row() {
  10002. Text('艺术家:')
  10003. .fontSize(14)
  10004. .fontColor($r('app.color.text_color'))
  10005. .margin({ left: 22 })
  10006. TextInput({ text: this.artistStr })
  10007. .height(40)
  10008. .maxLines(1)
  10009. .fontSize(14)
  10010. .layoutWeight(1)
  10011. .fontColor($r('app.color.text_color'))
  10012. .margin({ right: 20, left: 10 })
  10013. .onChange((val: string) => {
  10014. this.artistStr = val
  10015. })
  10016. }
  10017. .width('100%')
  10018. .margin({ top: 10, bottom: 10 })
  10019. .justifyContent(FlexAlign.Start)
  10020. Row() {
  10021. Text('专辑名:')
  10022. .fontSize(14)
  10023. .fontColor($r('app.color.text_color'))
  10024. .margin({ left: 22 })
  10025. TextInput({ text: this.ablumStr})
  10026. .height(40)
  10027. .maxLines(1)
  10028. .fontSize(14)
  10029. .layoutWeight(1)
  10030. .fontColor($r('app.color.text_color'))
  10031. .margin({ right: 20, left: 10 })
  10032. .onChange((val: string) => {
  10033. this.ablumStr = val
  10034. })
  10035. }
  10036. .width('100%')
  10037. .margin({ top: 10, bottom: 10 })
  10038. .justifyContent(FlexAlign.Start)
  10039. Row() {
  10040. Column(){
  10041. Column(){
  10042. Text('歌词:')
  10043. .fontSize(14)
  10044. .fontColor($r('app.color.text_color'))
  10045. .margin({ top:9,left: 22 })
  10046. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10047. SymbolGlyph($r('sys.symbol.trash_fill'))
  10048. .fontSize(25)
  10049. .alignSelf(ItemAlign.Center)
  10050. .margin({ left: 22,top:25})
  10051. }
  10052. .backgroundColor(Color.Transparent)
  10053. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10054. Visibility.None:Visibility.Visible)
  10055. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10056. .onClick(()=>{
  10057. this.lyricConStr = ''
  10058. this.lyricContent = ''
  10059. this.tempLyricContent = ''
  10060. })
  10061. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10062. SymbolGlyph($r('sys.symbol.plus'))
  10063. .fontSize(25)
  10064. .alignSelf(ItemAlign.Center)
  10065. .margin({ left: 22,top:25})
  10066. }
  10067. .backgroundColor(Color.Transparent)
  10068. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10069. .onClick( ()=>{
  10070. this.callFilePickerSelectFileForLyric()
  10071. })
  10072. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10073. SymbolGlyph($r('sys.symbol.traditional_square'))
  10074. .fontSize(25)
  10075. .alignSelf(ItemAlign.Center)
  10076. .margin({ left: 22,top:25})
  10077. }
  10078. .backgroundColor(Color.Transparent)
  10079. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10080. Visibility.None:Visibility.Visible)
  10081. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10082. .onClick( ()=>{
  10083. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  10084. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  10085. })
  10086. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10087. Image($r('app.media.jianti'))
  10088. .height(25)
  10089. .fillColor($r('app.color.text_color'))
  10090. .alignSelf(ItemAlign.Center)
  10091. .margin({ left: 22,top:25})
  10092. }
  10093. .backgroundColor(Color.Transparent)
  10094. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10095. Visibility.None:Visibility.Visible)
  10096. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10097. .onClick( ()=>{
  10098. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  10099. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  10100. })
  10101. }
  10102. .layoutWeight(1)
  10103. }
  10104. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  10105. this.tempLyricContent })
  10106. .type(TextAreaType.NORMAL)
  10107. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  10108. .fontSize(14)
  10109. .layoutWeight(1)
  10110. .fontColor($r('app.color.text_color'))
  10111. .margin({ right: 20, left: 10 })
  10112. .onChange((val: string) => {
  10113. this.lyricConStr = val
  10114. })
  10115. }
  10116. .width('100%')
  10117. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  10118. .margin({ top: 10, bottom: 10 })
  10119. .justifyContent(FlexAlign.Start)
  10120. Row() {
  10121. Text('年份:')
  10122. .fontSize(14)
  10123. .fontColor($r('app.color.text_color'))
  10124. .margin({ left: 22 })
  10125. TextInput({ text: item.year })
  10126. .height(40)
  10127. .maxLines(1)
  10128. .fontSize(14)
  10129. .type(InputType.Number)
  10130. .layoutWeight(1)
  10131. .fontColor($r('app.color.text_color'))
  10132. .margin({ right: 20, left: 10 })
  10133. .onChange((val: string) => {
  10134. this.yearStr = val
  10135. })
  10136. }
  10137. .width('100%')
  10138. .margin({ top: 10, bottom: 10 })
  10139. .justifyContent(FlexAlign.Start)
  10140. Row() {
  10141. Text('音轨号:')
  10142. .fontSize(14)
  10143. .fontColor($r('app.color.text_color'))
  10144. .margin({ left: 22 })
  10145. TextInput({ text:item.track=='未知'?'': item.track })
  10146. .height(40)
  10147. .maxLines(1)
  10148. .fontSize(14)
  10149. .type(InputType.Number)
  10150. .layoutWeight(1)
  10151. .fontColor($r('app.color.text_color'))
  10152. .margin({ right: 20, left: 10 })
  10153. .onChange((val: string) => {
  10154. this.trackStr = val
  10155. })
  10156. }
  10157. .width('100%')
  10158. .margin({ top: 10, bottom: 10 })
  10159. .justifyContent(FlexAlign.Start)
  10160. Row() {
  10161. Text('碟号:')
  10162. .fontSize(14)
  10163. .fontColor($r('app.color.text_color'))
  10164. .margin({ left: 22 })
  10165. TextInput({ text:item.disc })
  10166. .height(40)
  10167. .maxLines(1)
  10168. .fontSize(14)
  10169. .type(InputType.Number)
  10170. .layoutWeight(1)
  10171. .fontColor($r('app.color.text_color'))
  10172. .margin({ right: 20, left: 10 })
  10173. .onChange((val: string) => {
  10174. this.discStr = val
  10175. })
  10176. }
  10177. .width('100%')
  10178. .margin({ top: 10, bottom: 10 })
  10179. .justifyContent(FlexAlign.Start)
  10180. Row() {
  10181. Text('风格:')
  10182. .fontSize(14)
  10183. .fontColor($r('app.color.text_color'))
  10184. .margin({ left: 22 })
  10185. TextInput({ text: item.genre })
  10186. .height(40)
  10187. .maxLines(1)
  10188. .fontSize(14)
  10189. .layoutWeight(1)
  10190. .fontColor($r('app.color.text_color'))
  10191. .margin({ right: 20, left: 10 })
  10192. .onChange((val: string) => {
  10193. this.genreStr = val
  10194. })
  10195. }
  10196. .width('100%')
  10197. .margin({ top: 10, bottom: 10 })
  10198. .justifyContent(FlexAlign.Start)
  10199. Row() {
  10200. Text('专辑艺术家:')
  10201. .fontSize(14)
  10202. .fontColor($r('app.color.text_color'))
  10203. .margin({ left: 22 })
  10204. TextInput({ text: item.ALBUMARTIST })
  10205. .height(40)
  10206. .maxLines(1)
  10207. .fontSize(14)
  10208. .layoutWeight(1)
  10209. .fontColor($r('app.color.text_color'))
  10210. .margin({ right: 20, left: 10 })
  10211. .onChange((val: string) => {
  10212. this.albumArtistStr = val
  10213. })
  10214. }
  10215. .width('100%')
  10216. .margin({ top: 10, bottom: 10 })
  10217. .justifyContent(FlexAlign.Start)
  10218. Row() {
  10219. Text('作曲:')
  10220. .fontSize(14)
  10221. .fontColor($r('app.color.text_color'))
  10222. .margin({ left: 22 })
  10223. TextInput({ text: item.COMPOSER })
  10224. .height(40)
  10225. .maxLines(1)
  10226. .fontSize(14)
  10227. .layoutWeight(1)
  10228. .fontColor($r('app.color.text_color'))
  10229. .margin({ right: 20, left: 10 })
  10230. .onChange((val: string) => {
  10231. this.composerStr = val
  10232. })
  10233. }
  10234. .width('100%')
  10235. .margin({ top: 10, bottom: 10 })
  10236. .justifyContent(FlexAlign.Start)
  10237. Row() {
  10238. Text('作词:')
  10239. .fontSize(14)
  10240. .fontColor($r('app.color.text_color'))
  10241. .margin({ left: 22 })
  10242. TextInput({ text: item.LYRICIST })
  10243. .height(40)
  10244. .maxLines(1)
  10245. .fontSize(14)
  10246. .layoutWeight(1)
  10247. .fontColor($r('app.color.text_color'))
  10248. .margin({ right: 20, left: 10 })
  10249. .onChange((val: string) => {
  10250. this.lyricistStr = val
  10251. })
  10252. }
  10253. .width('100%')
  10254. .margin({ top: 10, bottom: 10 })
  10255. .justifyContent(FlexAlign.Start)
  10256. Row() {
  10257. Text('注释:')
  10258. .fontSize(14)
  10259. .fontColor($r('app.color.text_color'))
  10260. .margin({ left: 22 })
  10261. TextInput({ text: item.COMMENT })
  10262. .height(40)
  10263. .maxLines(1)
  10264. .fontSize(14)
  10265. .layoutWeight(1)
  10266. .fontColor($r('app.color.text_color'))
  10267. .margin({ right: 20, left: 10 })
  10268. .onChange((val: string) => {
  10269. this.commentStr = val
  10270. })
  10271. }
  10272. .width('100%')
  10273. .margin({ top: 10, bottom: 10 })
  10274. .justifyContent(FlexAlign.Start)
  10275. Row() {
  10276. Button('保存')
  10277. .fontColor(Color.White)
  10278. .layoutWeight(1)
  10279. .height(50)
  10280. .width(100)
  10281. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10282. .backgroundColor(this.themeColor)
  10283. .stateEffect(true)
  10284. .margin({ right: 20, bottom: 20 })
  10285. .onClick(async () => {
  10286. this.doEdit(item)
  10287. })
  10288. Button('取消')
  10289. .fontColor(Color.White)
  10290. .layoutWeight(1)
  10291. .height(50)
  10292. .width(100)
  10293. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10294. .backgroundColor(this.themeColor)
  10295. .stateEffect(true)
  10296. .margin({ left: 20, bottom: 20 })
  10297. .onClick(async () => {
  10298. if(this.isGridMusic){
  10299. this.longItemFilePath =''
  10300. }else{
  10301. this.isShowEdit = false
  10302. }
  10303. this.setEditStrEmpty()
  10304. if(this.isShowPlay){
  10305. this.isShowEdit = false
  10306. }
  10307. })
  10308. }
  10309. .margin({
  10310. left: 38,
  10311. right: 38,
  10312. top: 10,
  10313. bottom: 10
  10314. })
  10315. .width(250)
  10316. .height(60)
  10317. }
  10318. }
  10319. .margin({ bottom: 20 })
  10320. }
  10321. setEditStrEmpty(){
  10322. this.imagePathStr = ''
  10323. this.lyricConStr = ''
  10324. this.artistStr = ''
  10325. this.titleStr = ''
  10326. this.ablumStr = ''
  10327. this.genreStr = ''
  10328. this.yearStr = ''
  10329. this.trackStr = ''
  10330. this.albumArtistStr = ''
  10331. this.composerStr = ''
  10332. this.lyricistStr = ''
  10333. this.commentStr = ''
  10334. this.discStr = ''
  10335. }
  10336. initEditFields(item?: VideoItem) {
  10337. if (!item) {
  10338. this.setEditStrEmpty()
  10339. return
  10340. }
  10341. this.imagePathStr = ''
  10342. this.titleStr = item.name ?? ''
  10343. this.artistStr = item.artist ?? ''
  10344. this.ablumStr = item.album ?? ''
  10345. this.genreStr = item.genre ?? ''
  10346. this.yearStr = item.year ?? ''
  10347. this.trackStr = item.track ?? ''
  10348. this.albumArtistStr = item.ALBUMARTIST ?? ''
  10349. this.composerStr = item.COMPOSER ?? ''
  10350. this.lyricistStr = item.LYRICIST ?? ''
  10351. this.commentStr = item.COMMENT ?? ''
  10352. this.discStr = item.disc ?? ''
  10353. this.lyricConStr = item.lyricContent ?? ''
  10354. }
  10355. private syncEditedFields(target?: VideoItem) {
  10356. if (!target) {
  10357. return
  10358. }
  10359. target.name = this.titleStr
  10360. target.artist = this.artistStr
  10361. target.album = this.ablumStr
  10362. target.lyricContent = this.lyricConStr
  10363. target.year = this.yearStr
  10364. target.genre = this.genreStr
  10365. target.track = this.trackStr
  10366. target.ALBUMARTIST = this.albumArtistStr
  10367. target.COMPOSER = this.composerStr
  10368. target.LYRICIST = this.lyricistStr
  10369. target.COMMENT = this.commentStr
  10370. target.disc = this.discStr
  10371. }
  10372. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  10373. apply?: (next: Array<VideoItem>) => void) {
  10374. if (!list || ArrayUtil.isEmpty(list)) {
  10375. return
  10376. }
  10377. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  10378. if (index < 0) {
  10379. return
  10380. }
  10381. const nextList = [...list]
  10382. this.syncEditedFields(nextList[index])
  10383. apply?.(nextList)
  10384. }
  10385. private syncListsAfterEdit(filePath: string) {
  10386. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  10387. this.videoLocalList = next
  10388. this.dataSource.pushArrayData(next)
  10389. })
  10390. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  10391. this.songList = next
  10392. this.sonDataSource.pushArrayData(next)
  10393. })
  10394. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  10395. this.favList = next
  10396. })
  10397. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  10398. this.historyList = next
  10399. })
  10400. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  10401. this.currentSongList = next
  10402. })
  10403. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  10404. this.mediaKuList = next
  10405. })
  10406. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  10407. this.filteredList = next
  10408. })
  10409. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  10410. this.artistList = next
  10411. })
  10412. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  10413. this.albumList = next
  10414. })
  10415. this.listRefreshKey++
  10416. }
  10417. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  10418. if (!mainListUpdated && !playlistUpdated) {
  10419. return;
  10420. }
  10421. this.listRefreshKey++;
  10422. if (mainListUpdated) {
  10423. this.dataSource.notifyDataReload();
  10424. }
  10425. if (playlistUpdated) {
  10426. this.sonDataSource.notifyDataReload();
  10427. }
  10428. }
  10429. @Builder
  10430. detailSheet(item:VideoItem) {
  10431. Scroll() {
  10432. Column() {
  10433. this.songDetail(item)
  10434. }
  10435. }
  10436. .width('100%')
  10437. .height('100%')
  10438. }
  10439. @Builder
  10440. songDetail(currentItem:VideoItem) {
  10441. Column() {
  10442. if (currentItem) {
  10443. Row() {
  10444. Stack() {
  10445. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  10446. currentItem.pixelMapPath)
  10447. .fillColor(this.themeColor)
  10448. .height(80)
  10449. .width(80)
  10450. .borderRadius(10)
  10451. .opacity(this.opacityItem)// 绑定透明度
  10452. .margin({ left: 22 })
  10453. }
  10454. Column() {
  10455. Column() {
  10456. Text(currentItem.name)
  10457. .fontSize(16)
  10458. .maxLines(1)
  10459. .animation({
  10460. duration: 555,
  10461. curve: 'Linear',
  10462. })
  10463. .fontColor($r('app.color.text_color'))
  10464. .margin({ left: 15 })
  10465. }
  10466. .height('100%')
  10467. .width('100%')
  10468. .justifyContent(FlexAlign.Center)
  10469. .alignItems(HorizontalAlign.Start)
  10470. }
  10471. .height('100%')
  10472. }
  10473. .width('100%')
  10474. .height(90)
  10475. .justifyContent(FlexAlign.SpaceBetween)
  10476. Row() {
  10477. Text('艺术家:')
  10478. .fontSize(14)
  10479. .fontColor($r('app.color.text_color'))
  10480. .margin({ left: 22 })
  10481. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  10482. .fontSize(14)
  10483. .fontColor($r('app.color.text_color'))
  10484. .margin({ left: 10 })
  10485. .layoutWeight(1)
  10486. }
  10487. .width('100%')
  10488. .margin({ top: 10, bottom: 10 })
  10489. .justifyContent(FlexAlign.Start)
  10490. Row() {
  10491. Text('专辑名:')
  10492. .fontSize(14)
  10493. .fontColor($r('app.color.text_color'))
  10494. .margin({ left: 22 })
  10495. Text(currentItem?.album ?currentItem.album : '未知专辑')
  10496. .fontSize(14)
  10497. .margin({ left: 10 })
  10498. .fontColor($r('app.color.text_color'))
  10499. .layoutWeight(1)
  10500. }
  10501. .width('100%')
  10502. .margin({ top: 10, bottom: 10 })
  10503. .justifyContent(FlexAlign.Start)
  10504. Row() {
  10505. Text('时长:')
  10506. .fontSize(14)
  10507. .fontColor($r('app.color.text_color'))
  10508. .margin({ left: 22 })
  10509. Text(StrUtil.isEmpty(currentItem.duration)?
  10510. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  10511. .fontSize(14)
  10512. .margin({ left: 10 })
  10513. .fontColor($r('app.color.text_color'))
  10514. .layoutWeight(1)
  10515. }
  10516. .width('100%')
  10517. .margin({ top: 10, bottom: 10 })
  10518. .justifyContent(FlexAlign.Start)
  10519. Row() {
  10520. Text('采样率:')
  10521. .fontSize(14)
  10522. .fontColor($r('app.color.text_color'))
  10523. .margin({ left: 22 })
  10524. Text(Utility.convertToKHz(currentItem.sampleRate))
  10525. .fontSize(14)
  10526. .margin({ left: 10 })
  10527. .fontColor($r('app.color.text_color'))
  10528. .layoutWeight(1)
  10529. }
  10530. .width('100%')
  10531. .margin({ top: 10, bottom: 10 })
  10532. .justifyContent(FlexAlign.Start)
  10533. Row() {
  10534. Text('比特率:')
  10535. .fontSize(14)
  10536. .fontColor($r('app.color.text_color'))
  10537. .margin({ left: 22 })
  10538. Text(currentItem.bit_rate)
  10539. .fontSize(14)
  10540. .margin({ left: 10 })
  10541. .fontColor($r('app.color.text_color'))
  10542. .layoutWeight(1)
  10543. }
  10544. .width('100%')
  10545. .margin({ top: 10, bottom: 10 })
  10546. .justifyContent(FlexAlign.Start)
  10547. Row() {
  10548. Text('位深:')
  10549. .fontSize(14)
  10550. .fontColor($r('app.color.text_color'))
  10551. .margin({ left: 22 })
  10552. Text(`${currentItem.bits_per_raw_sample} bits`)
  10553. .fontSize(14)
  10554. .margin({ left: 10 })
  10555. .fontColor($r('app.color.text_color'))
  10556. .layoutWeight(1)
  10557. }
  10558. .width('100%')
  10559. .margin({ top: 10, bottom: 10 })
  10560. .justifyContent(FlexAlign.Start)
  10561. Row() {
  10562. Text('声道:')
  10563. .fontSize(14)
  10564. .fontColor($r('app.color.text_color'))
  10565. .margin({ left: 22 })
  10566. Text(`${currentItem.channels}`)
  10567. .fontSize(14)
  10568. .margin({ left: 10 })
  10569. .fontColor($r('app.color.text_color'))
  10570. .layoutWeight(1)
  10571. }
  10572. .width('100%')
  10573. .margin({ top: 10, bottom: 10 })
  10574. .justifyContent(FlexAlign.Start)
  10575. Row() {
  10576. Text('声道布局:')
  10577. .fontSize(14)
  10578. .fontColor($r('app.color.text_color'))
  10579. .margin({ left: 22 })
  10580. Text(`${currentItem.channel_layout}`)
  10581. .fontSize(14)
  10582. .margin({ left: 10 })
  10583. .fontColor($r('app.color.text_color'))
  10584. .layoutWeight(1)
  10585. }
  10586. .width('100%')
  10587. .margin({ top: 10, bottom: 10 })
  10588. .justifyContent(FlexAlign.Start)
  10589. Row() {
  10590. Text('起始播放点:')
  10591. .fontSize(14)
  10592. .fontColor($r('app.color.text_color'))
  10593. .margin({ left: 22 })
  10594. Text(`${currentItem.start_time}`)
  10595. .fontSize(14)
  10596. .margin({ left: 10 })
  10597. .fontColor($r('app.color.text_color'))
  10598. .layoutWeight(1)
  10599. }
  10600. .width('100%')
  10601. .margin({ top: 10, bottom: 10 })
  10602. .justifyContent(FlexAlign.Start)
  10603. Row() {
  10604. Text('风格:')
  10605. .fontSize(14)
  10606. .fontColor($r('app.color.text_color'))
  10607. .margin({ left: 22 })
  10608. Text(currentItem.genre)
  10609. .fontSize(14)
  10610. .margin({ left: 10 })
  10611. .fontColor($r('app.color.text_color'))
  10612. .layoutWeight(1)
  10613. }
  10614. .width('100%')
  10615. .margin({ top: 10, bottom: 10 })
  10616. .justifyContent(FlexAlign.Start)
  10617. Row() {
  10618. Text('发行时间:')
  10619. .fontSize(14)
  10620. .fontColor($r('app.color.text_color'))
  10621. .margin({ left: 22 })
  10622. Text(currentItem.year)
  10623. .fontSize(14)
  10624. .margin({ left: 10 })
  10625. .fontColor($r('app.color.text_color'))
  10626. .layoutWeight(1)
  10627. }
  10628. .width('100%')
  10629. .margin({ top: 10, bottom: 10 })
  10630. .justifyContent(FlexAlign.Start)
  10631. Row() {
  10632. Text('质量评分:')
  10633. .fontSize(14)
  10634. .fontColor($r('app.color.text_color'))
  10635. .margin({ left: 22 })
  10636. Text(currentItem.probe_score+"")
  10637. .fontSize(14)
  10638. .margin({ left: 10 })
  10639. .fontColor($r('app.color.text_color'))
  10640. .layoutWeight(1)
  10641. }
  10642. .width('100%')
  10643. .margin({ top: 10, bottom: 10 })
  10644. .justifyContent(FlexAlign.Start)
  10645. Row() {
  10646. Text('音轨号:')
  10647. .fontSize(14)
  10648. .fontColor($r('app.color.text_color'))
  10649. .margin({ left: 22 })
  10650. Text(currentItem.track)
  10651. .fontSize(14)
  10652. .margin({ left: 10 })
  10653. .fontColor($r('app.color.text_color'))
  10654. .layoutWeight(1)
  10655. }
  10656. .width('100%')
  10657. .margin({ top: 10, bottom: 10 })
  10658. .justifyContent(FlexAlign.Start)
  10659. Row() {
  10660. Text('碟号:')
  10661. .fontSize(14)
  10662. .fontColor($r('app.color.text_color'))
  10663. .margin({ left: 22 })
  10664. Text(currentItem.disc)
  10665. .fontSize(14)
  10666. .margin({ left: 10 })
  10667. .fontColor($r('app.color.text_color'))
  10668. .layoutWeight(1)
  10669. }
  10670. .width('100%')
  10671. .margin({ top: 10, bottom: 10 })
  10672. .justifyContent(FlexAlign.Start)
  10673. Row() {
  10674. Text('专辑艺术家:')
  10675. .fontSize(14)
  10676. .fontColor($r('app.color.text_color'))
  10677. .margin({ left: 22 })
  10678. Text(currentItem.ALBUMARTIST)
  10679. .fontSize(14)
  10680. .margin({ left: 10 })
  10681. .fontColor($r('app.color.text_color'))
  10682. .layoutWeight(1)
  10683. }
  10684. .width('100%')
  10685. .margin({ top: 10, bottom: 10 })
  10686. .justifyContent(FlexAlign.Start)
  10687. Row() {
  10688. Text('作曲家:')
  10689. .fontSize(14)
  10690. .fontColor($r('app.color.text_color'))
  10691. .margin({ left: 22 })
  10692. Text(currentItem.COMPOSER)
  10693. .fontSize(14)
  10694. .margin({ left: 10 })
  10695. .fontColor($r('app.color.text_color'))
  10696. .layoutWeight(1)
  10697. }
  10698. .width('100%')
  10699. .margin({ top: 10, bottom: 10 })
  10700. .justifyContent(FlexAlign.Start)
  10701. Row() {
  10702. Text('作词家:')
  10703. .fontSize(14)
  10704. .fontColor($r('app.color.text_color'))
  10705. .margin({ left: 22 })
  10706. Text(currentItem.LYRICIST)
  10707. .fontSize(14)
  10708. .margin({ left: 10 })
  10709. .fontColor($r('app.color.text_color'))
  10710. .layoutWeight(1)
  10711. }
  10712. .width('100%')
  10713. .margin({ top: 10, bottom: 10 })
  10714. .justifyContent(FlexAlign.Start)
  10715. Row() {
  10716. Text('注释:')
  10717. .fontSize(14)
  10718. .fontColor($r('app.color.text_color'))
  10719. .margin({ left: 22 })
  10720. Text(currentItem.COMMENT)
  10721. .fontSize(14)
  10722. .margin({ left: 10 })
  10723. .fontColor($r('app.color.text_color'))
  10724. .layoutWeight(1)
  10725. }
  10726. .width('100%')
  10727. .margin({ top: 10, bottom: 10 })
  10728. .justifyContent(FlexAlign.Start)
  10729. Row() {
  10730. Text('格式:')
  10731. .fontSize(14)
  10732. .fontColor($r('app.color.text_color'))
  10733. .margin({ left: 22 })
  10734. Text(Utility.formatMimeType(currentItem.mimeType))
  10735. .fontSize(14)
  10736. .margin({ left: 10 })
  10737. .fontColor($r('app.color.text_color'))
  10738. .layoutWeight(1)
  10739. }
  10740. .width('100%')
  10741. .margin({ top: 10, bottom: 10 })
  10742. .justifyContent(FlexAlign.Start)
  10743. Row() {
  10744. Text('播放次数:')
  10745. .fontSize(14)
  10746. .fontColor($r('app.color.text_color'))
  10747. .margin({ left: 22 })
  10748. Text(currentItem.playCount?.toString())
  10749. .fontSize(14)
  10750. .margin({ left: 10 })
  10751. .fontColor($r('app.color.text_color'))
  10752. .layoutWeight(1)
  10753. }
  10754. .width('100%')
  10755. .margin({ top: 10, bottom: 10 })
  10756. .justifyContent(FlexAlign.Start)
  10757. Row() {
  10758. Text('流数量:')
  10759. .fontSize(14)
  10760. .fontColor($r('app.color.text_color'))
  10761. .margin({ left: 22 })
  10762. Text(currentItem.nb_streams?.toString())
  10763. .fontSize(14)
  10764. .margin({ left: 10 })
  10765. .fontColor($r('app.color.text_color'))
  10766. .layoutWeight(1)
  10767. }
  10768. .width('100%')
  10769. .margin({ top: 10, bottom: 10 })
  10770. .justifyContent(FlexAlign.Start)
  10771. Row() {
  10772. Text('文件大小:')
  10773. .fontSize(14)
  10774. .fontColor($r('app.color.text_color'))
  10775. .margin({ left: 22 })
  10776. Text(currentItem.size)
  10777. .fontSize(14)
  10778. .margin({ left: 10 })
  10779. .fontColor($r('app.color.text_color'))
  10780. .layoutWeight(1)
  10781. }
  10782. .width('100%')
  10783. .margin({ top: 10, bottom: 10 })
  10784. .justifyContent(FlexAlign.Start)
  10785. Row() {
  10786. Text('文件名:')
  10787. .fontSize(14)
  10788. .fontColor($r('app.color.text_color'))
  10789. .margin({ left: 22 })
  10790. Text(currentItem.fileName)
  10791. .fontSize(14)
  10792. .margin({ left: 10 })
  10793. .fontColor($r('app.color.text_color'))
  10794. .layoutWeight(1)
  10795. }
  10796. .width('100%')
  10797. .margin({ top: 10, bottom: 10 })
  10798. .justifyContent(FlexAlign.Start)
  10799. Row() {
  10800. Text('修改时间:')
  10801. .fontSize(14)
  10802. .fontColor($r('app.color.text_color'))
  10803. .margin({ left: 22 })
  10804. Text(currentItem.cTime)
  10805. .fontSize(14)
  10806. .margin({ left: 10 })
  10807. .fontColor($r('app.color.text_color'))
  10808. .layoutWeight(1)
  10809. }
  10810. .width('100%')
  10811. .margin({ top: 10, bottom: 10 })
  10812. .justifyContent(FlexAlign.Start)
  10813. Row() {
  10814. Text('存放目录:')
  10815. .fontSize(14)
  10816. .fontColor($r('app.color.text_color'))
  10817. .margin({ left: 22 })
  10818. Text(currentItem.filePath)
  10819. .fontSize(12)
  10820. .margin({ left: 10 })
  10821. .fontColor($r('app.color.text_color'))
  10822. .layoutWeight(1)
  10823. }
  10824. .margin({ top: 10, bottom: 10 })
  10825. .width('100%')
  10826. .justifyContent(FlexAlign.Start)
  10827. Row() {
  10828. Text('内嵌歌词:')
  10829. .fontSize(14)
  10830. .fontColor($r('app.color.text_color'))
  10831. .margin({ left: 22 })
  10832. Text(currentItem.lyricContent)
  10833. .fontSize(12)
  10834. .copyOption(CopyOptions.InApp)
  10835. .margin({ left: 10 })
  10836. .fontColor($r('app.color.text_color'))
  10837. .layoutWeight(1)
  10838. }
  10839. .margin({ top: 10, bottom: 10 })
  10840. .width('100%')
  10841. .justifyContent(FlexAlign.Start)
  10842. }
  10843. }
  10844. .margin({ bottom: 20 })
  10845. }
  10846. //定时关闭布局
  10847. @Builder
  10848. TimeCloseSheet() {
  10849. Scroll() {
  10850. Column() {
  10851. this.TimeClose()
  10852. }
  10853. }
  10854. .width('100%')
  10855. .height('100%')
  10856. }
  10857. //倒计时关闭音乐,退出App功能实现。
  10858. @State selectedMinutes: number = 0 // 0表示未开启
  10859. @State remainingSeconds: number = 0
  10860. // 预设时间选项
  10861. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  10862. private formatTime(seconds: number): string {
  10863. const mins = Math.floor(seconds / 60)
  10864. const secs = seconds % 60
  10865. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  10866. }
  10867. // 开始倒计时
  10868. private handleTimeSelect(minutes: number) {
  10869. if (minutes === this.selectedMinutes) {
  10870. this.stopCountdown();
  10871. this.selectedMinutes = 0;
  10872. return;
  10873. }
  10874. this.selectedMinutes = minutes;
  10875. this.remainingSeconds = minutes * 60;
  10876. this.startCountdown(); // 新增调用
  10877. }
  10878. @Builder
  10879. TimeClose() {
  10880. Column() {
  10881. // 倒计时显示区域
  10882. Text(this.selectedMinutes > 0 ?
  10883. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  10884. "定时关闭未开启")
  10885. .fontSize(17)
  10886. .fontColor($r('app.color.text_color'))
  10887. .margin({ top: 2, bottom: 8 });
  10888. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10889. ForEach(this.presetTimes, (minutes: number, index: number) => {
  10890. // 单行时间选项容器
  10891. Row() {
  10892. // 文字描述区域
  10893. Text(this.getDisplayText(minutes))
  10894. .fontSize(15)
  10895. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  10896. $r('app.color.text_color'))// 选中态颜色变化
  10897. .textAlign(TextAlign.Start)
  10898. .layoutWeight(1); // 占据剩余空间
  10899. // 复选框样式的选择器
  10900. Row() {
  10901. if (minutes === this.selectedMinutes) {
  10902. // 选中状态 - 带勾号的圆形复选框
  10903. Row() {
  10904. // 使用系统内置的勾号图标
  10905. Image($r('sys.media.ohos_ic_public_ok'))
  10906. .width(14)
  10907. .height(14)
  10908. .fillColor(Color.White)
  10909. }
  10910. .width(24)
  10911. .height(24)
  10912. .borderRadius(12)
  10913. .backgroundColor(this.themeColor)
  10914. .justifyContent(FlexAlign.Center)
  10915. .alignItems(VerticalAlign.Center)
  10916. } else {
  10917. // 未选中状态的圆形边框
  10918. Row()
  10919. .width(24)
  10920. .height(24)
  10921. .borderRadius(12)
  10922. .border({
  10923. width: 2,
  10924. color: $r('app.color.text_color'),
  10925. style: BorderStyle.Solid
  10926. })
  10927. .backgroundColor(Color.Transparent)
  10928. }
  10929. }
  10930. .width(24)
  10931. .height(24)
  10932. .margin({ left: 20 })
  10933. .justifyContent(FlexAlign.Center)
  10934. .alignItems(VerticalAlign.Center)
  10935. }
  10936. .width('100%')
  10937. .padding({
  10938. top: 18,
  10939. bottom: 18,
  10940. left: 18,
  10941. right: 18
  10942. })
  10943. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  10944. $r('app.color.bottom_control_background')) // 选中背景高亮
  10945. .borderRadius(12)
  10946. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10947. .margin({ bottom: 18 })
  10948. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  10949. });
  10950. }
  10951. .width('100%')
  10952. .padding(16)
  10953. }
  10954. }
  10955. // 获取显示文本
  10956. private getDisplayText(minutes: number): string {
  10957. if (minutes === -1) {
  10958. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  10959. }
  10960. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  10961. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  10962. }
  10963. // 处理选择事件
  10964. private handleSelect(minutes: number): void {
  10965. if (minutes === -1) { // 自定义
  10966. // 弹出自定义时间对话框
  10967. DialogHelper.showTextInputDialog({
  10968. title: '自定义时间',
  10969. maskColor: Color.Transparent,
  10970. inputType: InputType.Number,
  10971. text: '',
  10972. onChange: (text) => {
  10973. console.error("onChange: " + text);
  10974. },
  10975. onAction: (action, dialogId, content) => {
  10976. if (action == DialogAction.TWO) {
  10977. const customMinutes = Number(content);
  10978. if (customMinutes > 0) {
  10979. this.handleTimeSelect(customMinutes); // 设置自定义时间
  10980. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  10981. }
  10982. }
  10983. }
  10984. });
  10985. } else {
  10986. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  10987. }
  10988. }
  10989. // 添加定时器引用
  10990. private timerId: number = -1;
  10991. // 启动/重置倒计时
  10992. private startCountdown() {
  10993. // 清除旧定时器
  10994. if (this.timerId !== -1) {
  10995. clearInterval(this.timerId);
  10996. }
  10997. // 创建新定时器
  10998. if (this.selectedMinutes > 0) {
  10999. this.timerId = setInterval(() => {
  11000. if (this.remainingSeconds === 15) {
  11001. this.showConfirmationDialog();
  11002. }
  11003. if (this.remainingSeconds > 0) {
  11004. this.remainingSeconds -= 1;
  11005. } else {
  11006. this.stopCountdown();
  11007. this.handleTimeout();
  11008. }
  11009. }, 1000);
  11010. }
  11011. }
  11012. // 15倒计时后再次提示显示确认是否关闭App对话框
  11013. private showConfirmationDialog() {
  11014. DialogHelper.showAlertDialog({
  11015. backgroundColor: $r('app.color.btn_green'),
  11016. title: '确认关闭',
  11017. maskColor: Color.Transparent,
  11018. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  11019. borderStyle: BorderStyle.Dashed,
  11020. primaryButton: '暂不关闭',
  11021. secondaryButton: '确定',
  11022. onAction: (action) => {
  11023. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  11024. this.stopCountdown();
  11025. this.selectedMinutes = 0
  11026. } else if (action == DialogAction.TWO) {
  11027. }
  11028. }
  11029. })
  11030. }
  11031. // 停止倒计时
  11032. private stopCountdown() {
  11033. if (this.timerId !== -1) {
  11034. clearInterval(this.timerId);
  11035. this.timerId = -1;
  11036. }
  11037. }
  11038. // 超时处理
  11039. private handleTimeout() {
  11040. // 执行播放器关闭逻辑
  11041. this.selectedMinutes = 0;
  11042. ToastUtil.showToast(" 定时关闭已完成");
  11043. this.stop(); // 假设存在的播放器实例
  11044. //退出APP
  11045. const mContext = getContext(this) as common.UIAbilityContext
  11046. mContext.terminateSelf();
  11047. AvSessionController.getInstance(true).unregisterSessionListener()
  11048. }
  11049. //倒计时关闭音乐,退出App功能实现结束。
  11050. //播放列表的拖动List 重新排序
  11051. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  11052. //左滑操作 移动文件 重命名 删除等操作
  11053. @Builder
  11054. sonButton(item: VideoItem, index: number, filePath: string) {
  11055. Row() {
  11056. //加入下一首播放
  11057. Button() {
  11058. Image($r('app.media.next_to_play'))
  11059. .fillColor(Color.White)
  11060. .width(20)
  11061. }
  11062. .width(40)
  11063. .height(40)
  11064. .type(ButtonType.Circle)
  11065. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11066. .backgroundColor(this.themeColor)
  11067. .margin(5)
  11068. .onClick(() => {
  11069. this.addToNextPlay(item);
  11070. })
  11071. Button() {
  11072. Image($r('app.media.close'))
  11073. .fillColor(Color.White)
  11074. .width(20)
  11075. }
  11076. .width(40)
  11077. .height(40)
  11078. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11079. .type(ButtonType.Circle)
  11080. .backgroundColor(this.themeColor)
  11081. .margin(5)
  11082. .onClick(() => {
  11083. this.songList.splice(Number(index), 1)
  11084. this.sonDataSource.pushArrayData(this.songList)
  11085. })
  11086. Button() {
  11087. Image($r('app.media.share2'))
  11088. .fillColor(Color.White)
  11089. .width(20)
  11090. }
  11091. .width(40)
  11092. .height(40)
  11093. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11094. .type(ButtonType.Circle)
  11095. .backgroundColor(this.themeColor)
  11096. .margin(5)
  11097. .onClick(() => {
  11098. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11099. })
  11100. }
  11101. }
  11102. itemMoveSon(index: number, newIndex: number): void {
  11103. if (newIndex < 0 || newIndex >= this.songList.length) {
  11104. return;
  11105. }
  11106. let tmp = this.songList.splice(index, 1);
  11107. this.songList.splice(newIndex, 0, tmp[0]);
  11108. this.sonDataSource.pushArrayData(this.songList)
  11109. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  11110. if(this.modeType==4&&this.playlistTable){
  11111. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  11112. }
  11113. }
  11114. @Builder
  11115. PlayList() {
  11116. List({ scroller: this.playListScroller }) {
  11117. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  11118. ListItem() {
  11119. this.MusicItemSon(item, index)
  11120. }
  11121. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  11122. .animation({
  11123. duration: 666,
  11124. curve: 'ease-in-out' // 可选动画曲线
  11125. })
  11126. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  11127. // TransitionEffect.scale({ x: 0, y: 0 })))
  11128. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  11129. //拖动List关键代码开始
  11130. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  11131. .zIndex(this.dragItem === index ? 1 : 0)
  11132. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  11133. .gesture(
  11134. GestureGroup(GestureMode.Sequence,
  11135. LongPressGesture({ repeat: true })
  11136. .onAction((event?: GestureEvent) => {
  11137. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11138. this.scaleItem = index
  11139. })
  11140. })
  11141. .onActionEnd(() => {
  11142. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11143. this.scaleItem = -1
  11144. })
  11145. }),
  11146. PanGesture({ fingers: 1, direction: null, distance: 0 })
  11147. .onActionStart(() => {
  11148. this.dragItem = index // 记录当前拖动项索引
  11149. this.dragRefOffset = 0 // 重置偏移基准
  11150. })
  11151. .onActionUpdate((event: GestureEvent) => {
  11152. this.offsetY = event.offsetY - this.dragRefOffset;
  11153. this.neighborItem = -1;
  11154. let indexA = this.songList.indexOf(item);
  11155. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  11156. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  11157. let value: number = 0;
  11158. if (this.offsetY < 0) {
  11159. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  11160. this.neighborItem = indexA - 1;
  11161. this.neighborScale = 1 - value / 20;
  11162. } else if (this.offsetY > 0) {
  11163. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  11164. this.neighborItem = indexA + 1;
  11165. this.neighborScale = 1 - value / 20;
  11166. }
  11167. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  11168. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11169. this.offsetY -= this.ITEM_INTV;
  11170. this.dragRefOffset += this.ITEM_INTV;
  11171. this.itemMoveSon(indexA, indexA + 1);
  11172. });
  11173. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  11174. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11175. this.offsetY += this.ITEM_INTV;
  11176. this.dragRefOffset -= this.ITEM_INTV;
  11177. this.itemMoveSon(indexA, indexA - 1);
  11178. });
  11179. }
  11180. })
  11181. .onActionEnd((event: GestureEvent) => {
  11182. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11183. this.dragItem = -1
  11184. this.neighborItem = -1
  11185. })
  11186. animateTo({
  11187. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11188. }, () => {
  11189. this.scaleItem = -1
  11190. })
  11191. })
  11192. )
  11193. .onCancel(() => {
  11194. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11195. this.dragItem = -1
  11196. this.neighborItem = -1
  11197. })
  11198. animateTo({
  11199. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11200. }, () => {
  11201. this.scaleItem = -1
  11202. })
  11203. })
  11204. ) //拖动List关键代码结束
  11205. .onClick(() => {
  11206. this.doPlay(item, index, true)
  11207. })
  11208. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  11209. }
  11210. .width('100%')
  11211. .height('100%')
  11212. .onReachEnd(() => {
  11213. if(this.modeType === 4 && !this.isFindPagedLocalQueueActive())
  11214. return;
  11215. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  11216. const isStreamingSong = this.currentSong && (
  11217. isNavidromeType(this.currentSong.type) ||
  11218. isJellyfinType(this.currentSong.type) ||
  11219. isEmbyType(this.currentSong.type) ||
  11220. isAudioStationType(this.currentSong.type) ||
  11221. isPlexType(this.currentSong.type)
  11222. );
  11223. if (isStreamingSong && hasMoreData()) {
  11224. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  11225. void this.loadMoreNavidromeSongs();
  11226. } else {
  11227. void this.tryLoadNextPageForPlayback();
  11228. }
  11229. })
  11230. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11231. // .animation({ duration: 500, curve: Curve.Ease }))
  11232. .cachedCount(10)
  11233. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  11234. .gesture(PinchGesture({ fingers: 2 })
  11235. .onActionEnd((event: GestureEvent) => {
  11236. this.setSonListTwoFingers()
  11237. })
  11238. .onActionUpdate(e => {
  11239. this.scaleValue = this.pinchValue * e.scale
  11240. })
  11241. .onActionStart(e => {
  11242. }))
  11243. .padding({
  11244. bottom: 0
  11245. })
  11246. }
  11247. setSonListTwoFingers() {
  11248. this.pinchValue = this.scaleValue;
  11249. Logger.info('this.pinchValue = ' + this.pinchValue);
  11250. if (this.pinchValue >= 1) {
  11251. this.sonTwoFingerType++
  11252. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  11253. if (this.sonTwoFingerType > 3) {
  11254. this.sonTwoFingerType = 1
  11255. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  11256. }
  11257. } else {
  11258. this.sonTwoFingerType--
  11259. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  11260. if (this.sonTwoFingerType < 1) {
  11261. this.sonTwoFingerType = 1
  11262. }
  11263. }
  11264. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  11265. this.pinchValue = 1;
  11266. this.scaleValue = 1;
  11267. }
  11268. @State sonTwoFingerType:number = 3
  11269. @Builder
  11270. private MusicItemSon(item: VideoItem, index?: number) {
  11271. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11272. Row() {
  11273. Stack() {
  11274. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  11275. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11276. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11277. .alt($r('app.media.alt'))
  11278. .fillColor(this.themeColor)
  11279. .borderRadius(this.isCoverRectangle?11:'100%')
  11280. .clip(true)
  11281. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  11282. .draggable(false)// 禁止长按手势拖动
  11283. .autoResize(true) // 重采样,可减少内存占用
  11284. .margin({ left: 20 })
  11285. }
  11286. .width('15%')
  11287. Column() {
  11288. Column() {
  11289. Text(this.isShowFileName?item.fileName :item.name)
  11290. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  11291. .fontColor(this.curIndex === index ? this.themeColor :
  11292. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  11293. .maxLines(1)
  11294. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  11295. Row() {
  11296. Column(){
  11297. Text(item.md5Str?.includes('Lossless')?
  11298. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  11299. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  11300. .padding({ top: 3,right:6,left:6,bottom:3 })
  11301. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  11302. $r('app.color.text_color'))
  11303. .fontWeight(500)
  11304. .borderRadius(12)
  11305. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  11306. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  11307. .backgroundColor('#FFC107')
  11308. }
  11309. .padding({ top: 8 })
  11310. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  11311. item.artist + ' ' + item?.duration)
  11312. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11313. .padding({ top: 8 })
  11314. .maxLines(1)
  11315. .fontColor(this.curIndex === index ? this.themeColor :
  11316. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11317. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  11318. Blank()
  11319. Text(item.size)
  11320. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11321. .padding({ top: 8 })
  11322. .maxLines(1)
  11323. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  11324. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  11325. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11326. .margin({ left: 10 })
  11327. }
  11328. }
  11329. .height('100%')
  11330. .width('100%')
  11331. .justifyContent(FlexAlign.Center)
  11332. .alignItems(HorizontalAlign.Start)
  11333. }
  11334. .height('100%')
  11335. .width('65%')
  11336. Column() {
  11337. PlayingIndicator({
  11338. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  11339. indicatorSize: 18
  11340. })
  11341. }
  11342. .width('20%')
  11343. }
  11344. }
  11345. .backgroundColor(Color.Transparent)
  11346. .width('100%')
  11347. .reuseId('son_item')
  11348. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  11349. .shadow(this.scaleItem === index ? {
  11350. radius: 70,
  11351. color: '#15000000',
  11352. offsetX: 0,
  11353. offsetY: 0
  11354. } :
  11355. {
  11356. radius: 0,
  11357. color: '#15000000',
  11358. offsetX: 0,
  11359. offsetY: 0
  11360. })
  11361. .animation({ curve: Curve.Sharp, duration: 300 })
  11362. }
  11363. @Builder
  11364. private MusicPlayDismissProxyDot() {
  11365. Stack({ alignContent: Alignment.Center }) {
  11366. Image(StrUtil.isNotEmpty(this.cover) ? this.cover as string : $r('app.media.alt'))
  11367. .width('100%')
  11368. .height('100%')
  11369. .objectFit(ImageFit.Cover)
  11370. .alt($r('app.media.alt'))
  11371. }
  11372. .width(this.playDismissProxySize)
  11373. .height(this.playDismissProxySize)
  11374. .borderRadius(this.playDismissProxySize)
  11375. .clip(true)
  11376. .opacity(this.playDismissProxyOpacity)
  11377. .translate({ x: this.playDismissTranslateX, y: this.translateY })
  11378. .shadow({
  11379. radius: 18,
  11380. type: ShadowType.BLUR,
  11381. color: 'on_primary'
  11382. })
  11383. }
  11384. @Builder
  11385. MusicPlayBuilder() {
  11386. Column() {
  11387. this.IjkMusicPlayerView()
  11388. }
  11389. .transition(TransitionEffect.asymmetric(
  11390. TransitionEffect.opacity(1),
  11391. TransitionEffect.OPACITY
  11392. ))
  11393. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  11394. new hdsEffect.HdsEffectBuilder()
  11395. .shaderEffect({
  11396. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  11397. animation: {
  11398. duration: 10000,
  11399. iterations: -1,
  11400. autoPlay: true,
  11401. onFinish: ()=> {
  11402. console.info('Succeeded in finishing');
  11403. }
  11404. },
  11405. controller: this.bgController,
  11406. })
  11407. .buildEffect():null)
  11408. .height('100%')
  11409. .width('100%')
  11410. .onDisAppear(() => {
  11411. this.translateY = 0;
  11412. this.playDragUiOpacity = 1
  11413. })
  11414. .translate({ y: this.translateY })
  11415. .gesture(
  11416. PanGesture(this.panOption)
  11417. .onActionUpdate((event?: GestureEvent) => {
  11418. if (event) {
  11419. // 判断滑动方向
  11420. const offsetY = event.offsetY ?? 0;
  11421. const isSwipeUp = offsetY < 0;
  11422. if (isSwipeUp) {
  11423. // 向上滑动:不应用位移动画,保持 translateY = 0
  11424. this.translateY = 0;
  11425. this.scaleValueImage = 1
  11426. this.scaleValueText = 1
  11427. this.playDragUiOpacity = 1
  11428. } else {
  11429. if(this.isGeKongPlayNext){
  11430. return
  11431. }
  11432. // 向下滑动:应用位移动画
  11433. this.translateY = offsetY;
  11434. // 向下滑动时的缩放效果
  11435. this.getUIContext().animateTo({
  11436. duration: 500,
  11437. curve: Curve.Sharp
  11438. }, () => {
  11439. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - this.translateY / 880));
  11440. console.info('onecold scaleValueImage:', this.scaleValueImage)
  11441. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  11442. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  11443. })
  11444. }
  11445. }
  11446. })
  11447. .onActionEnd((event?: GestureEvent) => {
  11448. // 判断滑动方向
  11449. const offsetY = event?.offsetY ?? 0;
  11450. const isSwipeUp = offsetY < 0;
  11451. const minDistance = 300; // 最小滑动距离
  11452. const minVelocity = 500; // 最小滑动速度
  11453. const velocity = event?.velocityY ?? 0;
  11454. if (isSwipeUp) {
  11455. // 向上滑动:切换下一首
  11456. const shouldSwitch = this.isPlayPageSwipeNext &&
  11457. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  11458. if (shouldSwitch) {
  11459. // 直接切换下一首,无需动画(因为界面没有移动)
  11460. this.playNext().catch(() => {
  11461. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  11462. });
  11463. }
  11464. } else {
  11465. //这里加个变量,是否开启隔空手势播放下一首
  11466. if(this.isGeKongPlayNext){
  11467. this.playNext()
  11468. return
  11469. }
  11470. // 向下滑动:关闭播放页
  11471. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  11472. if (shouldClose) {
  11473. // 添加关闭动画
  11474. this.getUIContext().animateTo({
  11475. duration: 600,
  11476. curve: Curve.Friction
  11477. }, () => {
  11478. this.isShowPlay = false;
  11479. this.scaleValueImage = 1
  11480. this.scaleValueText = 1
  11481. this.playDragUiOpacity = 1
  11482. this.translateY = 0;
  11483. })
  11484. } else {
  11485. // 回弹动画
  11486. this.getUIContext().animateTo({
  11487. duration: 600,
  11488. curve: Curve.Friction
  11489. }, () => {
  11490. this.scaleValueImage = 1
  11491. this.scaleValueText = 1
  11492. this.playDragUiOpacity = 1
  11493. this.translateY = 0;
  11494. })
  11495. }
  11496. }
  11497. })
  11498. )
  11499. }
  11500. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  11501. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  11502. HeightBreakpoint.HEIGHT_LG;
  11503. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  11504. @State topBarHeight: number = 50
  11505. @State barOpacity: number = 1
  11506. @State barBottomOpacity: number = 1
  11507. private hideDone: boolean = false;
  11508. @State currentYOffset: number = 0;
  11509. @State bottomBarHeight: number = 68;
  11510. private isHiding: boolean = false;
  11511. //是否是Pura X外屏,或者小屏幕
  11512. isPuraWP() {
  11513. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  11514. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  11515. }
  11516. //是否是Pura X外屏,或者小屏幕,手机横屏
  11517. /**
  11518. * 是否是Pura X外屏,或者小屏幕,手机横屏
  11519. * @returns
  11520. */
  11521. isCoverOpacity() {
  11522. if (this.isPuraWP()) {
  11523. return true
  11524. }
  11525. if (this.isPhoneLan()) {
  11526. return true
  11527. }
  11528. if (deviceInfo.marketName.includes('Pura X')
  11529. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  11530. return true
  11531. }
  11532. return false
  11533. }
  11534. //是不是手机横屏
  11535. isPhoneLan() {
  11536. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  11537. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  11538. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  11539. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  11540. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  11541. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  11542. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  11543. if (this.isHiCarKuanBianPing()) {
  11544. return true
  11545. }
  11546. if (this.isHiCar()) {
  11547. return false
  11548. }
  11549. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11550. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  11551. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  11552. return true
  11553. }
  11554. return false
  11555. }
  11556. //是不是1920x720的hicar的屏幕分辨率
  11557. isHiCarKuanBianPing(){
  11558. // if(!this.isHiCar()){
  11559. // return false
  11560. // }
  11561. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11562. { ratio: 1920 / 720, name: "1920x720" },
  11563. ];
  11564. const currentRatio: number = this.windowWidth / this.windowHeight;
  11565. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11566. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  11567. for (const hiCarRatio of hiCarAspectRatios) {
  11568. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  11569. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11570. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11571. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11572. //宽扁平的尺寸设置列表展示
  11573. this.twoFingerType ==3
  11574. this.isGridMusic = false
  11575. return true;
  11576. }
  11577. }
  11578. return false;
  11579. }
  11580. //是不是hicar的屏幕分辨率
  11581. isHiCarSmall() {
  11582. if(!this.isHiCar()){
  11583. return false
  11584. }
  11585. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  11586. {
  11587. this.columns = 6
  11588. return false
  11589. }
  11590. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11591. { ratio: 800 / 480, name: "800x480" },
  11592. { ratio: 1280 / 720, name: "1280x720" },
  11593. { ratio: 1920 / 1080, name: "1920x1080" },
  11594. ];
  11595. const currentRatio: number = this.windowWidth / this.windowHeight;
  11596. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11597. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  11598. for (const hiCarRatio of hiCarAspectRatios) {
  11599. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  11600. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11601. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  11602. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11603. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11604. //宽扁平的尺寸设置列表展示
  11605. return true;
  11606. }
  11607. }
  11608. return false;
  11609. }
  11610. isHiCar(): boolean {
  11611. return this.curDisplayIsHiCar;
  11612. }
  11613. //是不是正常的手机竖屏
  11614. isPhonePortrait() {
  11615. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  11616. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  11617. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  11618. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11619. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  11620. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  11621. return true
  11622. }
  11623. return false
  11624. }
  11625. @State showSpeedDialog: boolean = false
  11626. @State longPressSpeed: number = 3 //长按默认倍数
  11627. @Builder
  11628. SpeedDialog() {
  11629. Stack() {
  11630. Column() {
  11631. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11632. .fontColor(Color.White)
  11633. .visibility(Visibility.Hidden)
  11634. }
  11635. .backgroundColor(Color.Black)
  11636. .borderRadius(20)
  11637. .padding({
  11638. top: 10,
  11639. right: 20,
  11640. left: 15,
  11641. bottom: 20
  11642. })
  11643. .opacity(0.6)
  11644. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11645. .fontColor(Color.White)
  11646. }
  11647. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  11648. .zIndex(5)
  11649. .margin({ top: 80 })
  11650. }
  11651. @Builder
  11652. IjkMusicPlayerView() {
  11653. Stack() {
  11654. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  11655. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  11656. HdsVisualComponent()
  11657. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  11658. console.info('Succeeded in finishing');
  11659. })
  11660. .width('100%')
  11661. .height('100%')
  11662. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  11663. }
  11664. Column() {
  11665. Column() {
  11666. //播放标题
  11667. Column() {
  11668. this.PlayTitle()
  11669. }
  11670. .opacity(this.playDragUiOpacity)
  11671. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 40 })
  11672. .width('100%')
  11673. .margin({ top: 0 })
  11674. .height(PlayConstants.HEIGHT)
  11675. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  11676. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  11677. if (this.showSpeedDialog) {
  11678. this.SpeedDialog()
  11679. }
  11680. Stack() {
  11681. //手势拖动快进
  11682. Column()
  11683. .width(CommonConstants.FULL_PERCENT)
  11684. .height('100%')
  11685. .gesture(
  11686. GestureGroup(GestureMode.Parallel,
  11687. // 长按屏幕倍数播放
  11688. LongPressGesture({ repeat: true })
  11689. .onAction(() => {
  11690. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11691. this.showSpeedDialog = true;
  11692. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  11693. }
  11694. })
  11695. .onActionEnd(() => {
  11696. this.showSpeedDialog = false;
  11697. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11698. }),
  11699. )
  11700. )
  11701. }
  11702. .height('65%')
  11703. Swiper() {
  11704. this.CoverInfo()
  11705. this.PlayerLyrics()
  11706. }
  11707. .onChange((index: number) => {
  11708. this.currentSwiperIndex = index
  11709. if (index === 1) {
  11710. this.syncLyricPositionNow()
  11711. }
  11712. })
  11713. .indicator(false)
  11714. .displayCount(this.getPlayerSwiperDisplayCount())
  11715. .clip(false)
  11716. .loop(false)
  11717. .autoPlay(false)
  11718. // .interval(8000)
  11719. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  11720. .height('100%')
  11721. .hitTestBehavior(HitTestMode.Transparent)
  11722. Image($r('app.media.icon_replay'))
  11723. .objectFit(ImageFit.Auto)
  11724. .width('120px')
  11725. .height('120px')
  11726. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  11727. .border({ width: 0 })
  11728. .visibility(Visibility.None)
  11729. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  11730. .onClick(() => {
  11731. console.info('onecold startPlayOrResumePlay 6744')
  11732. this.startPlayOrResumePlay();
  11733. })
  11734. }
  11735. .width(CommonConstants.FULL_PERCENT)
  11736. .height(CommonConstants.FULL_PERCENT)
  11737. .justifyContent(FlexAlign.End)
  11738. }
  11739. .justifyContent(FlexAlign.End)
  11740. .margin({ bottom: 5 })
  11741. }
  11742. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  11743. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  11744. .animation({
  11745. duration: 666,
  11746. curve: 'ease-in-out' // 可选动画曲线
  11747. })
  11748. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  11749. ? BlurStyle.NONE :
  11750. BlurStyle.BACKGROUND_ULTRA_THICK)
  11751. .hitTestBehavior(HitTestMode.Transparent)
  11752. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  11753. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  11754. .onClick(() => {
  11755. if(this.isHiCar())
  11756. return
  11757. if(this.is_auto_hide_progress){
  11758. this.is_auto_hide_progress = false
  11759. }
  11760. this.startAutoHide()
  11761. })
  11762. }
  11763. @Consume progressValue: number ;
  11764. @State currentTime: string = "00:00";
  11765. @State totalTime: string = "00:00";
  11766. @State loadingVisible: Visibility = Visibility.None;
  11767. @State replayVisible: Visibility = Visibility.None;
  11768. @State slideEnable: boolean = false;
  11769. @State aspRatio: number = 0.5;
  11770. @State mContext: object | undefined = undefined;
  11771. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  11772. @State mFirst: boolean = true;
  11773. @State mDestroyPage: boolean = false;
  11774. @State playSpeed: number = 1;
  11775. @State oldSeconds: number = 0;
  11776. @State isSeekTo: boolean = false;
  11777. @State isCurrentTime: boolean = false;
  11778. @State videoWidth: string = '100%';
  11779. @State videoHeight: string = '100%';
  11780. @State initAspectRatio: number = 1;
  11781. @State videoAspectRatio: number = this.initAspectRatio;
  11782. @State videoUrl: string = '';
  11783. private last: number = 0;
  11784. @State videoParentAspectRatio: number = this.initAspectRatio;
  11785. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  11786. @Consume CONTROL_PlayStatus: number ;
  11787. @State PROGRESS_MAX_VALUE: number = 100;
  11788. @State updateProgressTimer: number = 0;
  11789. private readonly progressUpdateIntervalMs: number = 120;
  11790. private readonly lyricUpdateMinDeltaMs: number = 24;
  11791. private lastLyricRenderPosition: number = Number.NaN;
  11792. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  11793. @State name: string = '';
  11794. // @State loop: boolean = false;
  11795. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  11796. @State multiple: string = '1.0X';
  11797. xcomponentController: XComponentController = new XComponentController()
  11798. private panOptionBright: PanGestureOptions =
  11799. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  11800. private panOptionVolume: PanGestureOptions =
  11801. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  11802. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  11803. //手势的音量控制和亮度控制
  11804. private positionX: number = PlayConstants.POSITION_X;
  11805. private positionY: number = PlayConstants.POSITION_Y;
  11806. private windowClass: window.Window = globalThis.windowClass
  11807. @State volume: number = 0.8;
  11808. @State volumeBoostPercent: number = 0
  11809. @State volumeSmall: boolean = false
  11810. @State autoParseMusicName: boolean = true
  11811. @State isShowFileName: boolean = false
  11812. @State isLongNameRoLL: boolean = true//长歌名滚动
  11813. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  11814. private readonly volumeBoostMaxPercent: number = 500;
  11815. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  11816. @State bright: number = PlayConstants.BRIGHT;
  11817. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  11818. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  11819. @State screenWidth: number = 0
  11820. @State screenHeight: number = 0
  11821. @State statusBarHeight: number = 0
  11822. @State isYesFull: boolean = false
  11823. private seekValue: number = 0
  11824. @State isVideoLock: boolean = false; // Whether the video playback is locked
  11825. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  11826. private playbackUrlRequestSerial: number = 0;
  11827. eventHub = getContext().eventHub;
  11828. private isAppForeground: boolean = true;
  11829. private lastBufferingLogTs: number = 0;
  11830. private readonly bufferingLogIntervalMs: number = 5000;
  11831. //投播组件
  11832. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  11833. // 新的投播控制器(封装了官方示例的逻辑)
  11834. private castControllerWrapper: CastController | undefined = undefined;
  11835. // 保留原始的 avCastController 引用(用于兼容旧代码)
  11836. private castController: avSession.AVCastController | undefined = undefined;
  11837. @State isCastPlaying: boolean = false;
  11838. @State currentTime2: number = 0;
  11839. @State currentStringTime: string = '00:00';
  11840. @State duration: number = 0;
  11841. @State isReady: boolean = false;
  11842. @State durationTime: number = 0;
  11843. @State durationStringTime: string = '00:00';
  11844. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  11845. // @State isPlaying: boolean = false;
  11846. private castSeek: boolean = false;
  11847. private castItem: avSession.AVQueueItem | undefined = undefined;
  11848. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  11849. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  11850. @State rotateAngle2: number = -9
  11851. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  11852. @Consume cover: string | undefined ;
  11853. @State artist: string | undefined = ''
  11854. // 1.初始化controller
  11855. private lyricController: LyricController = new LyricController()
  11856. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  11857. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  11858. private parser = new LyricParser()
  11859. @State randomShakenX: number = 0
  11860. @State randomShakenY: number = 0
  11861. @State lyricTextSize: number = 24
  11862. @State lyricContent: string = ''
  11863. @State isDebug: boolean = false
  11864. @State isHightLightCenter: boolean = true
  11865. private syncWordByWordLyricMode(): void {
  11866. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11867. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11868. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11869. }
  11870. private syncLyricLightTextMode(): void {
  11871. this.lyricController.setLightText(this.isLightText)
  11872. this.lyricControllerXF.setLightText(this.isLightText)
  11873. this.lyricControllerSingle.setLightText(this.isLightText)
  11874. }
  11875. /**
  11876. * 初始化歌词加载与展示逻辑
  11877. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  11878. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  11879. * @param isApi2 是否使用API2获取歌词(可选)
  11880. *
  11881. * 主要流程:
  11882. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  11883. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  11884. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  11885. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  11886. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  11887. * 6. 解析失败或读取失败时,清空歌词显示。
  11888. *
  11889. * 注意事项:
  11890. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  11891. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  11892. * - 歌词内容解析后通过lyricController驱动UI渲染。
  11893. */
  11894. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  11895. if (StrUtil.isEmpty(lyricPath)) {
  11896. return
  11897. }
  11898. this.syncWordByWordLyricMode()
  11899. this.syncLyricLightTextMode()
  11900. this.initPipLyricSetting()
  11901. this.lyricControllerSingle
  11902. .setTextSize(15)
  11903. .setCacheSize(4)
  11904. .setTextColor("#FFFFFF")
  11905. .setHighlightColor(this.currentHighLightLyricColor)
  11906. .setHighlightScale(1.2)
  11907. .setEmptyHint("")
  11908. .setLineSpace(1)
  11909. .setAlignMode('center')
  11910. .setAnimationDuration(500)
  11911. .setSingleLine(true)
  11912. this.lyricContent = ''
  11913. this.lyricController
  11914. .setTextSize(this.currentLyricSize)
  11915. .setCacheSize(4)
  11916. .setTextColor("#DDDDDD")
  11917. .setHighlightColor("#FFFFFF")
  11918. .setEmptyHint("")
  11919. .setAnimationDuration(1000)
  11920. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  11921. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  11922. this.setBlurDegree(this.blurDegree, false)
  11923. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  11924. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  11925. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  11926. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  11927. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  11928. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  11929. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  11930. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  11931. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  11932. this.lyricController.setTextWeight(this.lyricTextWeight)
  11933. this.showSingleLyric = false
  11934. // 加载已保存的歌词时间偏移
  11935. this.loadLyricTimeOffset()
  11936. this.lyricController.setLyric(null)
  11937. this.lyricControllerSingle.setLyric(null)
  11938. console.log("onecold lyricPath =" + lyricPath)
  11939. // 1. 检查内嵌歌词
  11940. let neiqianLrc = ''
  11941. let lyContent = this.currentSong?.lyricContent
  11942. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  11943. neiqianLrc = lyContent
  11944. }
  11945. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  11946. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  11947. // Navidrome JSON歌词转换
  11948. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  11949. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  11950. if (convertedLyric) {
  11951. neiqianLrc = convertedLyric;
  11952. console.log("onecold Navidrome歌词转换成功");
  11953. }
  11954. }
  11955. this.setLyricToControllers(neiqianLrc);
  11956. return
  11957. }
  11958. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  11959. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  11960. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  11961. song: this.currentSong,
  11962. playbackUrl: this.videoUrl,
  11963. manager: RemoteDriveManager.getInstance(),
  11964. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  11965. });
  11966. if (StrUtil.isNotEmpty(remoteLyric)) {
  11967. this.currentSong.lyricContent = remoteLyric;
  11968. this.setLyricToControllers(remoteLyric);
  11969. void this.persistRemoteMetadataToDb(this.currentSong);
  11970. return;
  11971. }
  11972. }
  11973. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  11974. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  11975. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  11976. || isPlexType(this.currentSong.type))) {
  11977. const manager = RemoteDriveManager.getInstance();
  11978. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  11979. // 将currentSong转换为SongData接口
  11980. const songData: SongData = {
  11981. webdav_account_id: this.currentSong.webdav_account_id,
  11982. artist: this.currentSong.artist,
  11983. name: this.currentSong.name,
  11984. webdav_id: this.currentSong.webdav_id,
  11985. lyricIndex: this.currentSong.lyricIndex,
  11986. type: this.currentSong.type
  11987. };
  11988. let serverLyric = '';
  11989. if (!serverLyric && isNavidromeType(songData.type)) {
  11990. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  11991. }
  11992. if (!serverLyric && isJellyfinType(songData.type)) {
  11993. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  11994. }
  11995. if (!serverLyric && isEmbyType(songData.type)) {
  11996. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  11997. }
  11998. if (!serverLyric && isAudioStationType(songData.type)) {
  11999. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  12000. }
  12001. if (!serverLyric && isPlexType(songData.type)) {
  12002. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  12003. }
  12004. if (serverLyric) {
  12005. this.setLyricToControllers(serverLyric, lyricPath);
  12006. return;
  12007. }
  12008. }
  12009. // 4. 尝试在线歌词API
  12010. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  12011. && !Utility.isVideoByExtension(this.videoUrl))) {
  12012. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  12013. return;
  12014. }
  12015. // 5. 从本地文件读取歌词
  12016. await this.loadLyricFromFile(lyricPath, isLocal || false);
  12017. }
  12018. /**
  12019. * 从本地文件加载歌词
  12020. */
  12021. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  12022. try {
  12023. let realLyricPath = lyricPath;
  12024. // 读取文件内容
  12025. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  12026. const stat = await fileIo.stat(file.fd);
  12027. const arrayBuffer = new ArrayBuffer(stat.size);
  12028. fs.read(file.fd, arrayBuffer)
  12029. .then((readLen: number) => {
  12030. console.info("read file data succeed");
  12031. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  12032. if (buf.length === 0) {
  12033. throw new Error("Buffer is empty after reading the file");
  12034. }
  12035. try {
  12036. // 检测文件编码
  12037. let detectedEncoding = this.detect(arrayBuffer);
  12038. console.info("onecoldT Detected encoding: " + detectedEncoding);
  12039. // 使用检测到的编码解码,解决中文乱码问题
  12040. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  12041. console.info("onecoldT Detected textDecoder: " + textDecoder);
  12042. let fileContent = textDecoder.decode(buf);
  12043. console.info(`onecoldT The content of file1: ${fileContent}`);
  12044. console.info(`onecold The content of file2: ${fileContent}`);
  12045. this.lyricContent = fileContent;
  12046. if(isLocal){
  12047. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  12048. this.lyricConStr = fileContent;
  12049. }
  12050. this.setLyricToControllers(fileContent);
  12051. console.info(`The content of file: ${fileContent}`);
  12052. } catch (chardetError) {
  12053. console.error("chardet.detect failed with error: " + chardetError.message);
  12054. this.clearLyricControllers();
  12055. }
  12056. })
  12057. .catch((err: BusinessError) => {
  12058. this.clearLyricControllers();
  12059. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  12060. })
  12061. .catch((err: Error) => {
  12062. this.clearLyricControllers();
  12063. console.error("read file 2 data failed with error message: " + err.message);
  12064. })
  12065. .finally(() => {
  12066. fs.closeSync(file);
  12067. });
  12068. } catch (error) {
  12069. this.clearLyricControllers();
  12070. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  12071. }
  12072. }
  12073. detect(data: ArrayBuffer): string {
  12074. //创建检测对象
  12075. let detector: UniversalDetector = new UniversalDetector();
  12076. // 限制检测数据大小,避免内存溢出
  12077. // 通常只需要检测文件前16KB就足够判断编码格式
  12078. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  12079. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  12080. // 传入检测数据并实时判断编码格式
  12081. detector.handleData(data, 0, detectSize);
  12082. // 标记检测数据 读取结束
  12083. detector.dataEnd();
  12084. // 获取检测结果
  12085. let detected: string = detector.getDetectedCharset();
  12086. // 释放资源
  12087. detector.reset();
  12088. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  12089. return detected;
  12090. }
  12091. /**
  12092. * 设置歌词到所有控制器
  12093. * @param lyricText 歌词文本
  12094. * @param savePath 可选,如果提供则保存到本地文件
  12095. */
  12096. private setLyricToControllers(lyricText: string, savePath?: string): void {
  12097. if (StrUtil.isEmpty(lyricText)) {
  12098. this.clearLyricControllers();
  12099. return;
  12100. }
  12101. this.lyricContent = lyricText;
  12102. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  12103. const lyric: Lyric = this.parser.parse(lines);
  12104. this.lyricController.setLyric(lyric);
  12105. this.lyricControllerXF.setLyric(lyric);
  12106. this.lyricControllerSingle.setLyric(lyric);
  12107. this.showSingleLyric = true;
  12108. // 如果提供了保存路径,保存歌词到本地
  12109. if (savePath) {
  12110. this.saveDataToFile(lyricText, savePath);
  12111. }
  12112. }
  12113. /**
  12114. * 清空所有歌词控制器
  12115. */
  12116. private clearLyricControllers(): void {
  12117. this.lyricController.setLyric(null);
  12118. this.lyricControllerXF.setLyric(null);
  12119. this.lyricControllerSingle.setLyric(null);
  12120. }
  12121. private extractLyricCopyLines(lyricText: string): string[] {
  12122. if (StrUtil.isEmpty(lyricText)) {
  12123. return [];
  12124. }
  12125. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  12126. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  12127. const lines = source.split('\n');
  12128. const result: string[] = [];
  12129. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  12130. for (let i = 0; i < lines.length; i++) {
  12131. const line = lines[i].trim();
  12132. if (!line || metaTagPattern.test(line)) {
  12133. continue;
  12134. }
  12135. const pureLine = line
  12136. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  12137. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  12138. .trim();
  12139. if (pureLine.length > 0) {
  12140. result.push(pureLine);
  12141. }
  12142. }
  12143. return result;
  12144. }
  12145. private openLyricCopySheet(): void {
  12146. const lines = this.extractLyricCopyLines(this.lyricContent);
  12147. if (ArrayUtil.isEmpty(lines)) {
  12148. ToastUtil.showToast('暂无可复制歌词');
  12149. return;
  12150. }
  12151. this.lyricCopyLines = lines;
  12152. this.lyricSelectedIndexes = [];
  12153. this.isShowLyricCopySheet = true;
  12154. }
  12155. private toggleLyricLineSelection(index: number): void {
  12156. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  12157. if (selectedIndex >= 0) {
  12158. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  12159. nextSelectedIndexes.splice(selectedIndex, 1);
  12160. this.lyricSelectedIndexes = nextSelectedIndexes;
  12161. return;
  12162. }
  12163. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  12164. }
  12165. private toggleLyricSelectAll(): void {
  12166. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  12167. this.lyricSelectedIndexes = [];
  12168. return;
  12169. }
  12170. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  12171. }
  12172. private copySelectedLyricLines(): void {
  12173. const selectedLines = this.getSelectedLyricLines();
  12174. if (ArrayUtil.isEmpty(selectedLines)) {
  12175. ToastUtil.showToast('暂无可复制歌词');
  12176. return;
  12177. }
  12178. Utility.copyText(selectedLines.join('\n'));
  12179. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  12180. }
  12181. private getSelectedLyricLines(): string[] {
  12182. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  12183. return [];
  12184. }
  12185. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  12186. const selectedLines: string[] = [];
  12187. for (let i = 0; i < selectedIndexes.length; i++) {
  12188. const index = selectedIndexes[i];
  12189. if (index >= 0 && index < this.lyricCopyLines.length) {
  12190. selectedLines.push(this.lyricCopyLines[index]);
  12191. }
  12192. }
  12193. return selectedLines;
  12194. }
  12195. private shareSelectedLyricLines(): void {
  12196. const selectedLines = this.getSelectedLyricLines();
  12197. if (ArrayUtil.isEmpty(selectedLines)) {
  12198. ToastUtil.showToast('暂无可分享歌词');
  12199. return;
  12200. }
  12201. const shareTitle = `${this.currentSong?.name ?? '歌词'}歌词`;
  12202. Utility.doShareText(selectedLines.join('\n'), this.context, shareTitle, '分享歌词');
  12203. }
  12204. /**
  12205. * 从在线API获取歌词
  12206. */
  12207. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  12208. if (!this.currentSong) {
  12209. this.clearLyricControllers();
  12210. if (isOnLineAndToast) {
  12211. ToastUtil.showShort('未获取到歌词!');
  12212. }
  12213. return;
  12214. }
  12215. let artist = this.currentSong.artist || '';
  12216. if (isApi2 === undefined) {
  12217. isApi2 = false;
  12218. }
  12219. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  12220. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  12221. this.setLyricToControllers(res, lyricPath);
  12222. } else {
  12223. this.clearLyricControllers();
  12224. if (isOnLineAndToast) {
  12225. ToastUtil.showShort('未获取到歌词!');
  12226. }
  12227. }
  12228. });
  12229. }
  12230. //初始化悬浮歌词的自定义设置
  12231. initPipLyricSetting() {
  12232. this.lyricControllerXF
  12233. .setTextSize(this.currentLyricSize)
  12234. .setCacheSize(4)
  12235. .setTextColor("#DDDDDD")
  12236. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  12237. .setEmptyHint("")
  12238. .setAnimationDuration(1000)
  12239. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  12240. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  12241. this.setBlurDegree(this.blurDegreePip, true)
  12242. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  12243. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  12244. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  12245. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  12246. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  12247. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  12248. this.lyricControllerXF.setHightLightCenter(true)
  12249. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  12250. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  12251. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  12252. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  12253. if (this.pipBgIndex === 0) {
  12254. if (this.cover) {
  12255. this.pipBg = this.cover
  12256. } else {
  12257. this.pipBg = this.imageColor
  12258. }
  12259. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  12260. }
  12261. }
  12262. //根据item返回歌词内容
  12263. async getLyricContent(item: VideoItem): Promise<string> {
  12264. let neiqianLrc = ''
  12265. let lyContent = item?.lyricContent
  12266. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  12267. neiqianLrc = lyContent
  12268. return neiqianLrc
  12269. }
  12270. try {
  12271. //取数据库里面的歌词lyContent
  12272. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  12273. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  12274. console.log("onecold Lyrics:", lyricContent);
  12275. neiqianLrc = lyricContent
  12276. return neiqianLrc
  12277. }
  12278. } catch (error) {
  12279. console.error("Error fetching lyrics:", error);
  12280. }
  12281. try {
  12282. let filePath = item.filePath;
  12283. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  12284. let realLyricPath = lyricPath;
  12285. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  12286. const stat = await fileIo.stat(file.fd);
  12287. const arrayBuffer = new ArrayBuffer(stat.size);
  12288. const readLen = await fs.read(file.fd, arrayBuffer);
  12289. console.info("read file data succeed");
  12290. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  12291. if (buf.length === 0) {
  12292. throw new Error("Buffer is empty after reading the file");
  12293. }
  12294. // let detectedEncoding = chardet.detect(buf);
  12295. let detectedEncoding = this.detect(arrayBuffer)
  12296. console.info("Detected encoding: " + detectedEncoding);
  12297. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  12298. let fileContent = textDecoder.decode(buf);
  12299. console.info(`onecold The content of file1: ${fileContent}`);
  12300. fs.closeSync(file);
  12301. return fileContent;
  12302. } catch (error) {
  12303. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  12304. return '';
  12305. }
  12306. }
  12307. async saveDataToFile(content: string, filePath: string) {
  12308. if (StrUtil.isEmpty(filePath)) {
  12309. return
  12310. }
  12311. try {
  12312. let lyricContent = ''
  12313. lyricContent = content
  12314. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  12315. // 清空文件内容
  12316. await fileIo.truncate(file.fd, 0);
  12317. await fileIo.write(file.fd, lyricContent);
  12318. await fileIo.close(file);
  12319. console.log('onecold lyric file Data saved successfully.');
  12320. } catch (error) {
  12321. console.error('onecold lyric file Failed to save data:', error);
  12322. }
  12323. }
  12324. // 定义开始旋转的方法
  12325. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  12326. @State timer: number = 0
  12327. @State rotateAngle: number = 0
  12328. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  12329. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  12330. // 页面可见性变化回调
  12331. onPageVisibilityChange() {
  12332. // 当页面可见性改变时,重新启动/停止旋转动画
  12333. this.animationRoFun()
  12334. }
  12335. //封面旋转动画
  12336. animationRoFun() {
  12337. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  12338. // 启动旋转动画
  12339. if (!this.isRotationRunning) {
  12340. this.isRotationRunning = true
  12341. this.startContinuousRotation()
  12342. }
  12343. this.startRotation()
  12344. } else {
  12345. // 停止旋转动画
  12346. this.isRotationRunning = false
  12347. clearInterval(this.timer)
  12348. this.stopRotation()
  12349. }
  12350. }
  12351. // 使用持续的动画进行旋转,避免频繁状态更新
  12352. private startContinuousRotation() {
  12353. clearInterval(this.timer)
  12354. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  12355. // 不使用 % 360 取模,让角度持续累加,避免反转
  12356. this.timer = setInterval(() => {
  12357. if (this.isRotationRunning) {
  12358. this.rotateAngle = this.rotateAngle + 36
  12359. }
  12360. }, 1000)
  12361. }
  12362. // 定义开始旋转的方法
  12363. startRotation() {
  12364. if (this.isPlaying) {
  12365. animateTo({
  12366. duration: 777,
  12367. iterations: 1,
  12368. curve: Curve.Linear
  12369. }, () => {
  12370. this.rotateAngle2 = -9
  12371. })
  12372. }
  12373. }
  12374. // 回调,暂停和播放按钮回调,下一首和上一首
  12375. playChange() {
  12376. // if(this.isCoverRectangle){
  12377. // return
  12378. // }
  12379. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12380. this.setIsPlaying(true)
  12381. this.animationState = AnimationStatus.Running
  12382. } else {
  12383. this.setIsPlaying(false)
  12384. this.animationState = AnimationStatus.Paused
  12385. }
  12386. AppStorage.setOrCreate('animationState', this.animationState);
  12387. }
  12388. // 定义停止旋转的方法
  12389. stopRotation() {
  12390. if (this.isCoverRectangle) {
  12391. this.rotateAngle = 0
  12392. } else {
  12393. //唱针以左上角为点选择逆时针40度
  12394. animateTo({
  12395. duration: 1000,
  12396. curve: Curve.Linear,
  12397. iterations: 1,
  12398. }, () => {
  12399. this.rotateAngle2 = -45;
  12400. });
  12401. }
  12402. }
  12403. @Builder
  12404. private LyricsTopItem() {
  12405. Row() {
  12406. Stack({ alignContent: Alignment.Center }) {
  12407. Image( StrUtil.isNotEmpty(this.cover)?
  12408. this.cover:$r('app.media.alt'))
  12409. .height(58)
  12410. .width(58)
  12411. .clip(true)
  12412. .sourceSize({width:38, height:38})
  12413. .alt($r('app.media.alt'))
  12414. .borderRadius(8)
  12415. .clickEffect({ level: ClickEffectLevel.HEAVY })
  12416. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  12417. .shadow({
  12418. radius: 22,
  12419. type: ShadowType.BLUR,
  12420. color: 'on_primary'
  12421. })
  12422. }
  12423. .width(62)
  12424. .height('100%')
  12425. Column() {
  12426. Column() {
  12427. Text(this.name)
  12428. .fontSize(16)
  12429. .maxLines(1)
  12430. .fontWeight(FontWeight.Bolder)
  12431. .fontColor(Color.White)
  12432. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12433. .margin({ left: 10 })
  12434. Row() {
  12435. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  12436. .fontSize(13)
  12437. .fontWeight(FontWeight.Bolder)
  12438. .padding({ top: 8 })
  12439. .fontColor(Color.White)
  12440. .margin({ left: 10 })
  12441. Blank()
  12442. }
  12443. }
  12444. .height('100%')
  12445. .width('100%')
  12446. .justifyContent(FlexAlign.Center)
  12447. .alignItems(HorizontalAlign.Start)
  12448. }
  12449. .height('100%')
  12450. .layoutWeight(1)
  12451. .margin({ right: 8 })
  12452. Column() {
  12453. PointLightDefaultButton({
  12454. isSysBol:false,
  12455. pointColor:Color.White,
  12456. imageResource:$r('app.media.lyric'),
  12457. isPx: false,
  12458. builderHeight: 23,
  12459. builderWidth: 23,
  12460. })
  12461. .onClick(() => {
  12462. this.isLyricSetting = !this.isLyricSetting;
  12463. })
  12464. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  12465. height: '99%',
  12466. dragBar: true,
  12467. preferType: SheetType.CENTER,
  12468. showClose: true,
  12469. blurStyle: BlurStyle.Thin,
  12470. backgroundColor: Color.Transparent,
  12471. title: { title: $r('app.string.lyric_setting') }
  12472. })
  12473. }
  12474. .width(44)
  12475. .height('100%')
  12476. .justifyContent(FlexAlign.Center)
  12477. .alignItems(HorizontalAlign.End)
  12478. }
  12479. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  12480. .padding({ left: 28, right: 28 })
  12481. .height(58)
  12482. .alignItems(VerticalAlign.Center)
  12483. }
  12484. //歌词显示
  12485. @Builder
  12486. PlayerLyrics() {
  12487. Column() {
  12488. Column() {
  12489. this.LyricsTopItem()
  12490. }
  12491. .height(this.isPuraWP() ? 15 : 58)
  12492. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  12493. Visibility.None : Visibility.Visible)
  12494. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  12495. .width("100%")
  12496. Column() {
  12497. LyricView2({
  12498. controller: this.lyricController,
  12499. enableSeek: true,
  12500. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12501. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12502. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12503. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  12504. if (!this.isPlaying) {
  12505. console.info('onecold startPlayOrResumePlay 7527')
  12506. this.startPlayOrResumePlay()
  12507. }
  12508. else {
  12509. this.isSeekTo = true;
  12510. this.mDestroyPage = false;
  12511. // 只有播放网盘歌曲时才显示转圈圈
  12512. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12513. this.showLoadIng();
  12514. }
  12515. this.seekTo(position + "");
  12516. }
  12517. return true
  12518. }
  12519. })
  12520. .width("100%")
  12521. .layoutWeight(1)
  12522. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  12523. .gesture(LongPressGesture()
  12524. .onAction(() => {
  12525. this.openLyricCopySheet();
  12526. }))
  12527. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  12528. height: '99%',
  12529. dragBar: true,
  12530. showClose: true,
  12531. preferType: SheetType.CENTER,
  12532. blurStyle: BlurStyle.Thin,
  12533. title: { title: '歌词' }
  12534. })
  12535. if (this.isPhoneLan()) {
  12536. Column() {
  12537. if (this.isShowSpectrum) {
  12538. this.InlineSpectrumView()
  12539. }
  12540. this.playProgressView()
  12541. }
  12542. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  12543. }
  12544. }
  12545. .position({
  12546. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  12547. (this.isPuraWP() ? 58 : 99)
  12548. })
  12549. .justifyContent(FlexAlign.Center)
  12550. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  12551. }
  12552. }
  12553. @Builder
  12554. LyricCopySheetBuilder() {
  12555. LyricCopySheet({
  12556. lyricCopyLines: this.lyricCopyLines,
  12557. lyricSelectedIndexes: this.lyricSelectedIndexes,
  12558. isDarkMode: this.isDarkMode,
  12559. themeColor: this.themeColor,
  12560. bottomSafeHeight: this.bottomSafeHeight,
  12561. onToggleLyricLine: (index: number) => {
  12562. this.toggleLyricLineSelection(index);
  12563. },
  12564. onToggleSelectAll: () => {
  12565. this.toggleLyricSelectAll();
  12566. },
  12567. onCopySelectedLines: () => {
  12568. this.copySelectedLyricLines();
  12569. },
  12570. onShareSelectedLines: () => {
  12571. this.shareSelectedLyricLines();
  12572. }
  12573. })
  12574. }
  12575. @Builder
  12576. SingleLyricView() {
  12577. Column() {
  12578. Column() {
  12579. LyricView2({
  12580. controller: this.lyricControllerSingle,
  12581. enableSeek: false,
  12582. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12583. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12584. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12585. })
  12586. .gesture(LongPressGesture()
  12587. .onAction(() => {
  12588. this.openLyricCopySheet();
  12589. }))
  12590. }
  12591. .height(82)
  12592. .margin({ bottom: 20 })
  12593. }
  12594. .opacity(this.playDragUiOpacity)
  12595. }
  12596. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  12597. @Builder
  12598. BottomControl() {
  12599. Column() {
  12600. if (this.isShowSpectrum) {
  12601. this.InlineSpectrumView()
  12602. }
  12603. this.TopPlayProgressView()
  12604. //播放 暂停,下一首,上一首
  12605. this.playCenterView()
  12606. if(!this.curDisplayIsHiCar){
  12607. //播放进度条
  12608. this.BottomView()
  12609. }
  12610. }
  12611. .justifyContent(FlexAlign.Center)
  12612. .alignItems(HorizontalAlign.Center)
  12613. .opacity(this.playDragUiOpacity)
  12614. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  12615. }
  12616. @Builder
  12617. playMenuBuilder(){
  12618. Image($r('app.media.menu'))
  12619. .width(24)
  12620. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12621. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  12622. height: '99%',
  12623. preferType:SheetType.CENTER,
  12624. dragBar: true,
  12625. showClose: true,
  12626. blurStyle: BlurStyle.Thin,
  12627. title: { title: $r('app.string.more') },
  12628. backgroundColor: Color.Transparent,
  12629. })
  12630. }
  12631. //播放控制上一首 下一首 暂停和播放
  12632. @Builder
  12633. playCenterView(){
  12634. Row() {
  12635. PointLightButton({
  12636. builder: () => {
  12637. this.playMenuBuilder()
  12638. },
  12639. isPx: false,
  12640. builderHeight: 26,
  12641. builderWidth: 26,
  12642. })
  12643. .onClick(async () =>{
  12644. this.isShowMoreView = !this.isShowMoreView;
  12645. })
  12646. PointLightButton({
  12647. builder: () => {
  12648. this.playPreviousBuilder()
  12649. },
  12650. isPx: false,
  12651. builderHeight: 26,
  12652. builderWidth: 26,
  12653. })
  12654. .onClick(async () =>{
  12655. await this.playPrevious()
  12656. })
  12657. PointLightButton({
  12658. builder: () => {
  12659. this.PlayOrPauseButton()
  12660. },
  12661. isPx: false,
  12662. builderHeight: this.isPhoneLan()?38:41,
  12663. builderWidth: this.isPhoneLan()?38:41,
  12664. })
  12665. .onClick(() =>{
  12666. this.playOrPause()
  12667. })
  12668. PointLightButton({
  12669. builder: () => {
  12670. this.playNextBuilder()
  12671. },
  12672. isPx: false,
  12673. builderHeight: 26,
  12674. builderWidth: 26,
  12675. })
  12676. .onClick(async () =>{
  12677. await this.playNext()
  12678. })
  12679. this.playModeButton()
  12680. }
  12681. .width('95%')
  12682. .margin({ bottom:this.isCoverOpacity()?0:15 })
  12683. .justifyContent(FlexAlign.SpaceEvenly)
  12684. }
  12685. @Builder
  12686. playPreviousBuilder(){
  12687. Image($r('app.media.ic_previous'))
  12688. .width(32)
  12689. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12690. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12691. }
  12692. @Builder
  12693. playNextBuilder(){
  12694. Image($r('app.media.ic_next'))
  12695. .width(32)
  12696. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12697. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12698. }
  12699. @Builder
  12700. PlayOrPauseButton(){
  12701. Stack() {
  12702. Column() {
  12703. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  12704. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  12705. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  12706. .width(this.isPhoneLan()?38:40)
  12707. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12708. .fillColor(Color.White)
  12709. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12710. }
  12711. // 加载进度圈
  12712. if (this.isPlayerLoading) {
  12713. Progress({value:0,total:100,type:ProgressType.Ring })
  12714. .width(this.isPhoneLan()?40:43)
  12715. .height(this.isPhoneLan()?40:43)
  12716. .color(Color.White)
  12717. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  12718. }
  12719. }
  12720. .width(this.isPhoneLan()?38:41)
  12721. .height(this.isPhoneLan()?38:41)
  12722. }
  12723. @Builder
  12724. TopPlayProgressView(){
  12725. Column() {
  12726. Row(){
  12727. Stack(){
  12728. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  12729. .fontColor([Color.White])
  12730. .fontSize(21)
  12731. .effectStrategy(1)
  12732. Text(this.fastForwardSeconds)
  12733. .fontColor(Color.White)
  12734. .fontSize(10)
  12735. .fontWeight(FontWeight.Bold)
  12736. }
  12737. .padding({left:12,bottom:6})
  12738. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12739. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12740. .onClick(()=>{
  12741. this.backForward()
  12742. })
  12743. Slider({
  12744. value: this.progressValue,
  12745. min: 0,
  12746. max: this.PROGRESS_MAX_VALUE,
  12747. step: 1,
  12748. style: SliderStyle.InSet
  12749. })
  12750. .height(20)
  12751. .blockColor('rgba(255,255,255,1)')
  12752. .trackColor('rgba(255,255,255,0.3)')
  12753. .selectedColor(Color.White)
  12754. .trackThickness(4)
  12755. .showSteps(false)
  12756. .showTips(true)
  12757. .layoutWeight(1)
  12758. .enabled(this.slideEnable)
  12759. .onChange((value: number, mode: SliderChangeMode) => {
  12760. if (mode !== 2) {
  12761. return
  12762. }
  12763. if(this.isSeekTo)
  12764. return
  12765. this.isSeekTo = true;
  12766. this.mDestroyPage = false;
  12767. // 只有播放网盘歌曲时才显示转圈圈
  12768. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12769. this.showLoadIng();
  12770. }
  12771. let seekValue = value * (this.getActiveDuration() / 100);
  12772. this.seekTo(seekValue + "", "top-progress-slider");
  12773. })
  12774. Stack(){
  12775. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  12776. .fontColor([Color.White])
  12777. .fontSize(21)
  12778. .effectStrategy(1)
  12779. Text(this.fastForwardSeconds)
  12780. .fontColor(Color.White)
  12781. .fontSize(10)
  12782. .fontWeight(FontWeight.Bold)
  12783. }
  12784. .padding({right:10,bottom:6})
  12785. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12786. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12787. .onClick(()=>{
  12788. this.fastForward()
  12789. })
  12790. }
  12791. .justifyContent(FlexAlign.Center)
  12792. .padding({left:20,right:20})
  12793. .width(this.isLandscape?'88%':'95%')
  12794. Row() {
  12795. Text(this.currentTime)
  12796. .fontSize(10)
  12797. .fontColor(Color.White)
  12798. .margin({left:25})
  12799. Blank()
  12800. Text(this.totalTime)
  12801. .fontSize(10)
  12802. .fontColor(Color.White)
  12803. .margin({right:25})
  12804. }
  12805. .width(this.isLandscape?'85%':'90%')
  12806. .height(10)
  12807. }
  12808. .width('100%')
  12809. .alignItems(HorizontalAlign.Center)
  12810. }
  12811. @Builder
  12812. playModeButton(){
  12813. PointLightButton({
  12814. builder: () => {
  12815. this.playModeBuilder()
  12816. },
  12817. isPx: false,
  12818. builderHeight: 26,
  12819. builderWidth: 26,
  12820. })
  12821. .onClick(async () =>{
  12822. this.setLoopMode()
  12823. })
  12824. }
  12825. @Builder
  12826. playModeBuilder(){
  12827. Column() {
  12828. if (this.playType === 0) {
  12829. Image($r('app.media.loop'))
  12830. .width(24)
  12831. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12832. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12833. } else if (this.playType === 1) {
  12834. Image($r('app.media.single'))
  12835. .width(24)
  12836. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12837. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12838. } else if (this.playType === 2) {
  12839. Image($r('app.media.normal_play'))
  12840. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12841. .width(24)
  12842. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12843. } else if (this.playType === 3) {
  12844. Image($r('app.media.random'))
  12845. .width(24)
  12846. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12847. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12848. } else if (this.playType === 4) {
  12849. Image($r('app.media.noloop'))
  12850. .width(24)
  12851. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12852. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12853. }
  12854. }
  12855. }
  12856. //播放进度条
  12857. @Builder
  12858. BottomView(){
  12859. Row() {
  12860. PointLightDefaultButton({
  12861. isSysBol:true,
  12862. pointColor:Color.White,
  12863. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12864. isPx: false,
  12865. builderHeight: 22,
  12866. builderWidth: 22,
  12867. })
  12868. .onClick(async () =>{
  12869. if (this.isLandscape) {
  12870. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12871. } else {
  12872. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12873. }
  12874. })
  12875. if(this.currentSong){
  12876. PointLightDefaultButton({
  12877. isSysBol:true,
  12878. pointColor:Color.White,
  12879. imageResource:$r('sys.symbol.rename'),
  12880. isPx: false,
  12881. builderHeight: 22,
  12882. builderWidth: 22,
  12883. })
  12884. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  12885. height: '99%',
  12886. dragBar: true,
  12887. showClose: true,
  12888. preferType: SheetType.BOTTOM,
  12889. title: { title: '编辑标签' }
  12890. })
  12891. .onClick(async () => {
  12892. this.initEditFields(this.currentSong)
  12893. this.tempLyricContent = this.lyricContent
  12894. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  12895. this.lyricConStr = this.tempLyricContent
  12896. }
  12897. this.isShowEdit = !this.isShowEdit;
  12898. })
  12899. }
  12900. PointLightDefaultButton({
  12901. isSysBol:true,
  12902. pointColor:Color.White,
  12903. imageResource:$r('sys.symbol.slider_vertical_3'),
  12904. isPx: false,
  12905. builderHeight: 22,
  12906. builderWidth: 22,
  12907. })
  12908. .onClick(async () => {
  12909. this.isEqualizerSheet = !this.isEqualizerSheet;
  12910. })
  12911. PointLightDefaultButton({
  12912. isSysBol:true,
  12913. pointColor:Color.White,
  12914. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  12915. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  12916. isPx: false,
  12917. builderHeight: 22,
  12918. builderWidth: 22,
  12919. })
  12920. .onClick(async () => {
  12921. if(this.currentSong){
  12922. this.doFav(this.currentSong)
  12923. }
  12924. })
  12925. this.playListBuilder()
  12926. }
  12927. .width(this.isLandscape?'88%':'95%')
  12928. .justifyContent(FlexAlign.SpaceAround)
  12929. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  12930. .height(30)
  12931. .animation({
  12932. duration: 666,
  12933. curve: 'ease-in-out' // 可选动画曲线
  12934. })
  12935. }
  12936. @Builder
  12937. fullButton(){
  12938. Column() {
  12939. Image($r('app.media.full_4'))
  12940. .width(25)
  12941. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12942. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12943. }
  12944. }
  12945. @Builder
  12946. playListBuilder(){
  12947. PointLightDefaultButton({
  12948. isSysBol:true,
  12949. pointColor:Color.White,
  12950. imageResource:$r('sys.symbol.music_note_list'),
  12951. isPx: false,
  12952. builderHeight: 26,
  12953. builderWidth: 26,
  12954. })
  12955. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  12956. height: '95%',
  12957. dragBar: true,
  12958. showClose: true,
  12959. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12960. blurStyle: BlurStyle.Thin,
  12961. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  12962. title: {
  12963. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12964. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12965. + `(${this.getPlayListDisplayCount()}首)`
  12966. }
  12967. })
  12968. .onClick(() => {
  12969. this.isShowSheetView = !this.isShowSheetView;
  12970. if(this.isPlayListBgGrass){
  12971. this.isFrontWhite = true
  12972. }else{
  12973. this.isFrontWhite = false
  12974. }
  12975. this.scrollIndex()
  12976. if (this.shouldHydrateFullMediaPlayListOnOpen()) {
  12977. void this.hydrateFullMediaPlayListIfNeeded();
  12978. }
  12979. })
  12980. }
  12981. //旧版本播放进度条(现在是手机横屏的播放条)
  12982. @Builder
  12983. playProgressView() {
  12984. Row() {
  12985. Column(){
  12986. PointLightDefaultButton({
  12987. isSysBol:true,
  12988. pointColor:Color.White,
  12989. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12990. isPx: false,
  12991. builderHeight: 26,
  12992. builderWidth: 26,
  12993. })
  12994. .onClick(async () =>{
  12995. if (this.isLandscape) {
  12996. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12997. } else {
  12998. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12999. }
  13000. })
  13001. }
  13002. .margin({ right: 10,bottom:6})
  13003. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  13004. .animation({
  13005. duration: 666,
  13006. curve: 'ease-in-out' // 可选动画曲线
  13007. })
  13008. Text(this.currentTime)
  13009. .fontSize($r('app.float.slider_font_size'))
  13010. .fontColor(Color.White)
  13011. .margin(3)
  13012. Slider({
  13013. value: this.progressValue,
  13014. min: 0,
  13015. max: this.PROGRESS_MAX_VALUE,
  13016. step: 1,
  13017. style: SliderStyle.InSet
  13018. })
  13019. .width('600px')
  13020. .blockColor('rgba(255,255,255,1)')
  13021. .trackColor('rgba(255,255,255,0.3)')
  13022. .selectedColor(Color.White)
  13023. .trackThickness(5)
  13024. .layoutWeight(1)
  13025. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  13026. .showSteps(false)
  13027. .showTips(true)
  13028. .enabled(this.slideEnable)
  13029. .onChange((value: number, mode: SliderChangeMode) => {
  13030. if (mode !== 2) {
  13031. return
  13032. }
  13033. this.isSeekTo = true;
  13034. this.mDestroyPage = false;
  13035. // 只有播放网盘歌曲时才显示转圈圈
  13036. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  13037. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  13038. this.showLoadIng();
  13039. }
  13040. let seekValue = value * (this.getActiveDuration() / 100);
  13041. this.seekTo(seekValue + "", "landscape-progress-slider");
  13042. })
  13043. Text(this.totalTime)
  13044. .fontSize($r('app.float.slider_font_size'))
  13045. .fontColor(Color.White)
  13046. .margin(3)
  13047. //播放列表
  13048. Column(){
  13049. this.playListBuilder()
  13050. }
  13051. .margin({ left: 10,bottom:6})
  13052. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  13053. .animation({
  13054. duration: 666,
  13055. curve: 'ease-in-out' // 可选动画曲线
  13056. })
  13057. }
  13058. //x5的竖屏模式需要99%
  13059. .width(this.isPhonePortrait() ? '93.4%'
  13060. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  13061. .height(this.isPhoneLan() ? 25 : 33)
  13062. .alignItems(VerticalAlign.Bottom)
  13063. .animation({
  13064. duration: 666,
  13065. curve: 'ease-in-out' // 可选动画曲线
  13066. })
  13067. }
  13068. isBigScreen() {
  13069. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  13070. return true
  13071. }
  13072. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  13073. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  13074. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  13075. return false
  13076. } else {
  13077. return true
  13078. }
  13079. return false
  13080. }
  13081. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  13082. // 添加控制缩放的状态变量
  13083. @State scaleValueImage: number = 1
  13084. @State scaleValueText: number = 1
  13085. @State playDragUiOpacity: number = 1
  13086. @Builder
  13087. private CoverScaleGuideOverlay() {
  13088. Stack() {
  13089. Column({ space: 10 }) {
  13090. SymbolGlyph($r('sys.symbol.arrow_up_left_and_arrow_down_right'))
  13091. .fontSize(34)
  13092. .fontColor([Color.White])
  13093. Text('双指缩放封面')
  13094. .fontSize(16)
  13095. .fontWeight(FontWeight.Bold)
  13096. .fontColor(Color.White)
  13097. Text('在封面区域双指捏合,可调整封面大小')
  13098. .fontSize(12)
  13099. .fontColor(Color.White)
  13100. .opacity(0.88)
  13101. .textAlign(TextAlign.Center)
  13102. }
  13103. .padding({ left: 18, right: 18, top: 16, bottom: 16 })
  13104. .backgroundColor('#A6000000')
  13105. .borderRadius(18)
  13106. .width(this.isPhoneLan() ? 230 : 240)
  13107. }
  13108. .width('100%')
  13109. .height(this.isPhoneLan() ? 260 : 360)
  13110. .align(Alignment.Center)
  13111. .zIndex(10)
  13112. .visibility(this.isShowCoverScaleGuide ? Visibility.Visible : Visibility.None)
  13113. .onClick(() => {
  13114. this.dismissCoverScaleGuide()
  13115. })
  13116. }
  13117. @Builder
  13118. CoverInfo() {
  13119. Column() {
  13120. Stack() {
  13121. Column() {
  13122. //方形封面布局
  13123. if (this.isCoverRectangle) {
  13124. this.RectangleCoverView()
  13125. } else {
  13126. //圆形封面布局
  13127. this.CicleCoverView()
  13128. }
  13129. this.musicNameInfo(false)
  13130. if (this.isPhoneLan()) {
  13131. Text(this.name+"--"+this.artist)
  13132. .fontSize(18)
  13133. .fontWeight(FontWeight.Bold)
  13134. .margin({ top: 13 })
  13135. .textOverflow({ overflow: TextOverflow.Ellipsis })
  13136. .maxLines(1)
  13137. .width('99%')
  13138. .textAlign(TextAlign.Center)
  13139. .fontColor(Color.White)
  13140. }
  13141. }
  13142. .width('100%')
  13143. Column({ space: 8 }) {
  13144. Text(this.name)
  13145. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  13146. .fontWeight(FontWeight.Bold)
  13147. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13148. .maxLines(1)
  13149. .width('85%')
  13150. .textAlign(TextAlign.Center)
  13151. .fontColor(Color.White)
  13152. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13153. Text(this.artist)
  13154. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  13155. .fontColor(Color.White)
  13156. .fontWeight(FontWeight.Bold)
  13157. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13158. }
  13159. .justifyContent(FlexAlign.Start)
  13160. .zIndex(1)
  13161. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  13162. this.CoverScaleGuideOverlay()
  13163. }
  13164. .margin({
  13165. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  13166. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  13167. top: this.isCoverOpacity() ? 0 : 20
  13168. })
  13169. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  13170. this.SingleLyricView()
  13171. }
  13172. if (this.isPhoneLan()) {
  13173. Column() {
  13174. this.playCenterView()
  13175. }
  13176. .position({ left: 28, bottom: 35 })
  13177. } else {
  13178. this.BottomControl()
  13179. }
  13180. }
  13181. .width(CommonConstants.FULL_PERCENT)
  13182. .clip(true)
  13183. }
  13184. //方形封面布局
  13185. @Builder
  13186. RectangleCoverView(){
  13187. Stack({alignContent:Alignment.Center}){
  13188. Image( StrUtil.isNotEmpty(this.cover)?
  13189. this.cover:$r('app.media.alt'))
  13190. .height(this.getRectangleCoverHeight())
  13191. .width(this.getRectangleCoverWidth())
  13192. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13193. .alt($r('app.media.alt'))
  13194. .margin({ right: 8, left: 8, top: 5 })
  13195. .aspectRatio(1)
  13196. .opacity(this.opacityValueImage)
  13197. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13198. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  13199. {
  13200. preview: MenuPreviewMode.IMAGE,
  13201. previewAnimationOptions: { scale: [0.8, 1.0] },
  13202. })
  13203. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  13204. {
  13205. preview: MenuPreviewMode.IMAGE,
  13206. previewAnimationOptions: { scale: [0.8, 1.0] },
  13207. })
  13208. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13209. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13210. .clip(true)
  13211. .animation({
  13212. duration: 1000, // 与 setInterval 同步
  13213. curve: Curve.Linear,
  13214. iterations: 1
  13215. })
  13216. .shadow({
  13217. radius: 22,
  13218. type: ShadowType.BLUR,
  13219. color: 'on_primary'
  13220. })
  13221. .onClick(() => {
  13222. this.isMusicBGCover = !this.isMusicBGCover
  13223. })
  13224. .gesture(PinchGesture({ fingers: 2 })
  13225. .onActionUpdate((event: GestureEvent) => {
  13226. this.updateRectangleCoverScaleByPinch(event.scale)
  13227. })
  13228. .onActionEnd(() => {
  13229. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13230. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13231. }))
  13232. }
  13233. .scale({ x: this.scaleValueImage, y: this.scaleValueImage})
  13234. }
  13235. private getRectangleCoverWidth(): string | number {
  13236. if (this.isHiCar() || this.isCoverOpacity()) {
  13237. return 'auto'
  13238. }
  13239. const baseWidth = this.isBigScreen() ? 72 : this.isCoverTopBig ? 100 : 88
  13240. return `${Math.min(100, Math.max(48, baseWidth * this.rectangleCoverScale))}%`
  13241. }
  13242. private getRectangleCoverHeight(): string | number {
  13243. if (this.isHiCar()) {
  13244. return px2vp(this.windowHeight) * 0.4 * this.rectangleCoverScale
  13245. }
  13246. if (this.isCoverOpacity()) {
  13247. return px2vp(this.windowHeight) * 0.54 * this.rectangleCoverScale
  13248. }
  13249. return 'auto'
  13250. }
  13251. private updateCoverScaleByPinch(scale: number): void {
  13252. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * scale))
  13253. }
  13254. private updateRectangleCoverScaleByPinch(scale: number): void {
  13255. const dampedScale = 1 + (scale - 1) * 0.45
  13256. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * dampedScale))
  13257. }
  13258. private persistCoverScaleAfterPinch(): void {
  13259. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13260. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13261. }
  13262. @Builder
  13263. CicleCoverView() {
  13264. //圆形封面布局
  13265. Stack({alignContent:Alignment.Center}) {
  13266. Image($r('app.media.ic_music_disc'))
  13267. .width(245)
  13268. .height(245)
  13269. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  13270. .aspectRatio(1)
  13271. .opacity(this.isCoverOpacity() ? 0 : 1)
  13272. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  13273. .borderRadius('100%')
  13274. .align(Alignment.Center)
  13275. .clip(true)
  13276. .rotate({
  13277. angle: this.rotateAngle,
  13278. centerX: "50%",
  13279. centerY: "50%",
  13280. })
  13281. .animation({
  13282. duration: 1000, // 改为 1000ms 与 setInterval 同步
  13283. curve: Curve.Linear,
  13284. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  13285. })
  13286. .shadow({
  13287. radius: 22,
  13288. type: ShadowType.BLUR,
  13289. color: 'on_primary'
  13290. })
  13291. Image( StrUtil.isNotEmpty(this.cover)?
  13292. this.cover:$r('app.media.alt'))
  13293. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  13294. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  13295. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13296. .alt($r('app.media.alt'))
  13297. .margin({ right: 20, left: 20,
  13298. top:this.isCoverRectangle||this.isLandscape?0:50})
  13299. .aspectRatio(1)
  13300. .opacity(this.opacityValueImage)
  13301. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13302. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13303. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13304. .align(Alignment.Center)//
  13305. .clip(true)
  13306. .shadow({
  13307. radius: 22,
  13308. type: ShadowType.BLUR,
  13309. color: 'on_primary'
  13310. })
  13311. .rotate({
  13312. x: 0,
  13313. y: 0,
  13314. z: 1,
  13315. angle: this.rotateAngle
  13316. })
  13317. .animation({
  13318. duration: 1000, // 与 setInterval 同步
  13319. curve: Curve.Linear,
  13320. iterations: 1
  13321. })
  13322. .onClick(() => {
  13323. this.isMusicBGCover = !this.isMusicBGCover
  13324. })
  13325. // 唱针以左上角为点选择逆时针40度
  13326. Image($r('app.media.ic_music_cover_hand'))
  13327. .height(130)
  13328. .margin({ bottom: 200, top: 0 })
  13329. // .position({ x: this.windowWidth/2, y: 0 })
  13330. .align(Alignment.Top)
  13331. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  13332. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  13333. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  13334. }
  13335. .scale({ x: this.scaleValueImage * this.rectangleCoverScale, y: this.scaleValueImage * this.rectangleCoverScale,
  13336. centerX: '50%',
  13337. centerY: '50%' })
  13338. .priorityGesture(PinchGesture({ fingers: 2 })
  13339. .onActionStart(() => {
  13340. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13341. })
  13342. .onActionUpdate((event: GestureEvent) => {
  13343. this.updateCoverScaleByPinch(event.scale)
  13344. })
  13345. .onActionEnd(() => {
  13346. this.persistCoverScaleAfterPinch()
  13347. }))
  13348. }
  13349. @Builder
  13350. MenuImageBuilder(cover: string|undefined) {
  13351. Menu(){
  13352. MenuItem({
  13353. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  13354. content: '查看封面'
  13355. })
  13356. .onClick(async() => {
  13357. if (StrUtil.isEmpty(cover)) {
  13358. ToastUtil.showToast('当前没有可用封面')
  13359. return;
  13360. }
  13361. this.getUIContext().getRouter().pushUrl({
  13362. url: 'pages/WallpaperPreviewPage',
  13363. params: {
  13364. imageUri: cover
  13365. }
  13366. })
  13367. })
  13368. MenuItem({
  13369. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  13370. content: '更换封面'
  13371. })
  13372. .onClick(async() => {
  13373. await this.replaceCurrentSongCoverByAlbum();
  13374. })
  13375. }
  13376. }
  13377. @Builder
  13378. private musicNameInfo(isHidden: boolean) {
  13379. Row(){
  13380. Column({ space: 8 }) {
  13381. Text(this.name)
  13382. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  13383. .fontWeight(FontWeight.Bold)
  13384. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13385. .maxLines(1)
  13386. .width('99%')
  13387. .textAlign(TextAlign.Start)
  13388. .fontColor(Color.White)
  13389. Text(this.artist + ' ' + this.currentSong?.album)
  13390. .fontSize(this.isCoverOpacity() ? 12 : 15)
  13391. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13392. .fontColor(Color.White)
  13393. .textAlign(TextAlign.Start)
  13394. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  13395. .width('99%')
  13396. .maxLines(1)
  13397. }
  13398. .zIndex(1)
  13399. .layoutWeight(1)
  13400. .margin({ left: 15 })
  13401. Blank()
  13402. Row(){
  13403. PointLightDefaultButton({
  13404. isSysBol:true,
  13405. pointColor:Color.White,
  13406. imageResource:this.showSimple?
  13407. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  13408. isPx: false,
  13409. builderHeight: 26,
  13410. builderWidth: 26,
  13411. })
  13412. .onClick(async () => {
  13413. this.showSimple = !this.showSimple
  13414. PreferencesUtil.put('showSimple', this.showSimple)
  13415. })
  13416. }
  13417. .margin({ left: 8,right:8 })
  13418. }
  13419. .width(this.isLandscape?'83%':'90%')
  13420. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  13421. .opacity(this.playDragUiOpacity)
  13422. .margin({ top:this.isCoverRectangle?15: 0 })
  13423. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  13424. }
  13425. @Builder
  13426. private PlayTitle() {
  13427. Row() {
  13428. Row() {
  13429. PointLightDefaultButton({
  13430. isSysBol: true,
  13431. pointColor: Color.White,
  13432. imageResource: $r('sys.symbol.chevron_down'),
  13433. isPx: false,
  13434. builderHeight: 26,
  13435. builderWidth: 26,
  13436. })
  13437. .onClick(() => {
  13438. this.setShowPlayFalse()
  13439. })
  13440. }
  13441. .width('100%')
  13442. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  13443. }
  13444. .width(PlayConstants.ROW_WIDTH)
  13445. }
  13446. @Builder
  13447. lyricSettingSheet(isPip: boolean) {
  13448. Scroll() {
  13449. this.lyricSetting(isPip)
  13450. }
  13451. .width('100%')
  13452. .height('100%')
  13453. }
  13454. @Builder
  13455. lyricSetting(isPip: boolean) {
  13456. Column() {
  13457. // 时间调节模块
  13458. if (!isPip) {
  13459. this.BuildTimeControls()
  13460. }
  13461. // 字号控制模块
  13462. this.BuildFontControls(isPip)
  13463. }
  13464. }
  13465. // 歌词时间偏移状态
  13466. @State timeOffset: number = 0.0
  13467. @State currentLyricColor: string = '#FFFFFF'
  13468. @State currentLyricColorPip: string = '#FFFFFF'
  13469. @State currentHighLightLyricColor: string = '#FF4081'
  13470. @State currentHighLightLyricColorPip: string = '#FF4081'
  13471. // 歌词字号状态
  13472. @State currentLyricSize: number = 20
  13473. @State currentLyricSizePip: number = 20
  13474. // 高亮歌词放大倍数
  13475. @State currentHightLyricSize: number = 1.2
  13476. @State currentHightLyricSizePip: number = 1.2
  13477. @State currentLyricLineSpace: number = 10
  13478. @State currentLyricLineSpacePip: number = 10
  13479. @State currentLyricAlignMode: number = 1
  13480. @State currentLyricAlignModePip: number = 1
  13481. @State blurDegree: number = 2
  13482. @State blurDegreePip: number = 2
  13483. @State isShowSelectColor: boolean = false
  13484. @State isShowHLSelectColor: boolean = false
  13485. @State isShowPipBgSelectColor: boolean = false
  13486. @State pipLyWidth: number = 330
  13487. @State pipLyHeight: number = 120
  13488. // 构建颜色选择器
  13489. @Builder
  13490. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  13491. Row({ space: 10 }) {
  13492. HSBColorPicker({
  13493. color: '#FFFFFF',
  13494. radius: 8,
  13495. layout: HSBColorPickerLayout.COLUMN,
  13496. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  13497. '#fa7105'],
  13498. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  13499. this.changeLyricColor(value, isPip, isBGPip)
  13500. })
  13501. .height(250)
  13502. .layoutWeight(1)
  13503. .padding(25)
  13504. }
  13505. .width('66%')
  13506. }
  13507. @State isOpenPip: boolean = false
  13508. @State pipBgIndex: number = 0
  13509. // 构建字号控制器
  13510. @Builder
  13511. BuildFontControls(isPip: boolean) {
  13512. Column() {
  13513. if (isPip) {
  13514. Column() {
  13515. Row() {
  13516. Text('悬浮歌词')
  13517. .margin({ left: 18 })
  13518. .fontSize(15)
  13519. .fontColor(Color.White)
  13520. .fontWeight(480)
  13521. .layoutWeight(1)
  13522. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  13523. .selectedColor(this.themeColor)
  13524. .switchPointColor(Color.White)
  13525. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13526. .margin({ right: 18 })
  13527. .onChange((checked: boolean) => {
  13528. this.isOpenPip = checked;
  13529. if (this.isOpenPip) {
  13530. this.startPip()
  13531. } else {
  13532. this.stopPip()
  13533. }
  13534. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  13535. })
  13536. .width(50)
  13537. .height(30);
  13538. }
  13539. .height(55)
  13540. }
  13541. .backgroundColor(Color.Transparent)
  13542. .borderRadius(15)
  13543. .margin({
  13544. left: 30,
  13545. right: 30,
  13546. top: 0,
  13547. bottom: 20
  13548. })
  13549. .padding(0)
  13550. .border({
  13551. color: Color.White,
  13552. width: 1.8
  13553. })
  13554. }else{
  13555. Row() {
  13556. Row() {
  13557. Text(`迷你歌词:`)
  13558. .fontSize(14)
  13559. .fontColor(Color.White)
  13560. .width(88)
  13561. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  13562. .selectedColor(this.themeColor)
  13563. .switchPointColor(Color.White)
  13564. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13565. .onChange((checked: boolean) => {
  13566. this.isShowSingleLineLyric = checked;
  13567. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  13568. })
  13569. .width(50)
  13570. .height(30)
  13571. .alignSelf(ItemAlign.Start)
  13572. .margin({ left: 12 })
  13573. Blank()
  13574. }
  13575. .layoutWeight(1)
  13576. Row() {
  13577. Text(`逐字歌词:`)
  13578. .fontSize(14)
  13579. .fontColor(Color.White)
  13580. .width(88)
  13581. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  13582. .selectedColor(this.themeColor)
  13583. .switchPointColor(Color.White)
  13584. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13585. .onChange((checked: boolean) => {
  13586. this.isEnableWordByWordLyric = checked;
  13587. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  13588. this.syncWordByWordLyricMode()
  13589. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13590. })
  13591. .width(50)
  13592. .height(30)
  13593. .alignSelf(ItemAlign.Start)
  13594. .margin({ left: 12 })
  13595. Blank()
  13596. }
  13597. .layoutWeight(1)
  13598. }
  13599. .width('100%')
  13600. .margin({
  13601. left: 20,
  13602. right: 15,
  13603. top: 10,
  13604. bottom: 10
  13605. })
  13606. }
  13607. if (!isPip) {
  13608. Row() {
  13609. Row() {
  13610. Text(`歌词发光:`)
  13611. .fontSize(14)
  13612. .fontColor(Color.White)
  13613. .width(88)
  13614. Toggle({ type: ToggleType.Switch, isOn: this.isLightText })
  13615. .selectedColor(this.themeColor)
  13616. .switchPointColor(Color.White)
  13617. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13618. .onChange((checked: boolean) => {
  13619. this.isLightText = checked;
  13620. PreferencesUtil.putSync(SettingPage.IS_LIGHT_TEXT, this.isLightText)
  13621. this.syncLyricLightTextMode()
  13622. })
  13623. .width(50)
  13624. .height(30)
  13625. .alignSelf(ItemAlign.Start)
  13626. .margin({ left: 12 })
  13627. Blank()
  13628. }
  13629. .layoutWeight(1)
  13630. Row() {
  13631. Text(`高亮居中:`)
  13632. .fontSize(14)
  13633. .fontColor(Color.White)
  13634. .width(88)
  13635. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  13636. .selectedColor(this.themeColor)
  13637. .switchPointColor(Color.White)
  13638. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13639. .onChange((checked: boolean) => {
  13640. this.isHightLightCenter = checked;
  13641. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  13642. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  13643. })
  13644. .width(50)
  13645. .height(30)
  13646. .alignSelf(ItemAlign.Start)
  13647. .margin({ left: 12 })
  13648. Blank()
  13649. }
  13650. .layoutWeight(1)
  13651. }
  13652. .width('100%')
  13653. .margin({
  13654. left: 20,
  13655. right: 15,
  13656. top: 10,
  13657. bottom: 10
  13658. })
  13659. }
  13660. Row() {
  13661. Text(`歌词居中:`)
  13662. .fontSize(14)
  13663. .fontColor(Color.White)
  13664. Row() {
  13665. ForEach(['居中', '居左'], (size: string, index: number) => {
  13666. Button(size)
  13667. .width(60)
  13668. .height(28)
  13669. .fontSize(12)
  13670. .fontColor('#FFFFFF')
  13671. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  13672. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  13673. .border({
  13674. color: (!isPip && this.currentLyricAlignMode === index) ||
  13675. (isPip && this.currentLyricAlignModePip === index) ?
  13676. '#007DFF' : '#DDDDDD',
  13677. width: 1.8
  13678. })
  13679. .onClick(() => {
  13680. this.setLyricAlignMode(index, isPip)
  13681. })
  13682. .margin({ left: 10, right: 8 })
  13683. })
  13684. }
  13685. .layoutWeight(1)
  13686. Blank()
  13687. }
  13688. .width('100%')
  13689. .margin({
  13690. top: 10,
  13691. bottom: 10,
  13692. right: 15,
  13693. left: 20
  13694. })
  13695. if (isPip) {
  13696. Row() {
  13697. Text(`悬浮背景:`)
  13698. .fontSize(14)
  13699. .fontColor(Color.White)
  13700. Select([
  13701. { value: CommonConstants.PIP_LYRIC_BG[0] },
  13702. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  13703. .font({ size: 13, weight: FontWeight.Medium })
  13704. .fontColor(Color.White)
  13705. .margin({ left: 10 })
  13706. .selected(this.pipBgIndex)
  13707. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  13708. .onSelect(async (_index: number, text?: string | undefined) => {
  13709. this.pipBgIndex = _index
  13710. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  13711. if (this.pipBgIndex === 0) {
  13712. if (this.cover) {
  13713. this.pipBg = this.cover
  13714. } else {
  13715. this.pipBg = this.imageColor
  13716. }
  13717. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13718. } else {
  13719. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  13720. }
  13721. })
  13722. Column() {
  13723. }
  13724. .backgroundColor(this.pipBg)
  13725. .margin({ left: 10, right: 10 })
  13726. .borderRadius(20)
  13727. .height(28)
  13728. .width(28)
  13729. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13730. Row() {
  13731. SymbolGlyph($r('sys.symbol.paintbrush'))
  13732. .fontColor([Color.White])
  13733. .effectStrategy(1)
  13734. Text(`选择颜色`)
  13735. .fontSize(13)
  13736. .margin({ left: 10 })
  13737. .fontColor(Color.White)
  13738. }
  13739. }
  13740. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  13741. .backgroundColor(Color.Transparent)
  13742. .border({
  13743. color: '#FFFFFF',
  13744. radius: 20,
  13745. width: 1.8
  13746. })
  13747. .height(36)
  13748. .width(110)
  13749. .onClick(() => {
  13750. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  13751. })
  13752. .bindPopup(this.isShowPipBgSelectColor, {
  13753. builder: this.SelectColor(false, isPip, true),
  13754. placement: Placement.Top,
  13755. mask: { color: '#33000000' },
  13756. enableArrow: false, //是否显示箭头
  13757. showInSubWindow: false,
  13758. onStateChange: (e) => {
  13759. if (!e.isVisible) {
  13760. this.isShowPipBgSelectColor = false
  13761. }
  13762. }
  13763. })
  13764. }
  13765. .width('100%')
  13766. .margin({ bottom: 5, right: 15, left: 20 })
  13767. }
  13768. Row() {
  13769. Text(`歌词颜色:`)
  13770. .fontSize(14)
  13771. .fontColor(Color.White)
  13772. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13773. .fontSize(15)
  13774. .fontColor(Color.White)
  13775. .margin({ left: 6, right: 6 })
  13776. Column() {
  13777. }
  13778. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13779. .margin({ right: 12 })
  13780. .borderRadius(20)
  13781. .height(28)
  13782. .width(28)
  13783. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13784. Row() {
  13785. SymbolGlyph($r('sys.symbol.paintbrush'))
  13786. .fontColor([Color.White])
  13787. .effectStrategy(1)
  13788. Text(`选择颜色`)
  13789. .fontSize(13)
  13790. .margin({ left: 10 })
  13791. .fontColor(Color.White)
  13792. }
  13793. }
  13794. .backgroundColor(Color.Transparent)
  13795. .border({
  13796. color: '#FFFFFF',
  13797. radius: 20,
  13798. width: 1.8
  13799. })
  13800. .height(36)
  13801. .width(110)
  13802. .onClick(() => {
  13803. this.isShowSelectColor = !this.isShowSelectColor
  13804. })
  13805. .bindPopup(this.isShowSelectColor, {
  13806. builder: this.SelectColor(false, isPip),
  13807. placement: Placement.Top,
  13808. mask: { color: '#33000000' },
  13809. enableArrow: false, //是否显示箭头
  13810. showInSubWindow: false,
  13811. onStateChange: (e) => {
  13812. if (!e.isVisible) {
  13813. this.isShowSelectColor = false
  13814. }
  13815. }
  13816. })
  13817. }
  13818. .width('100%')
  13819. .margin({
  13820. top: 10,
  13821. bottom: 10,
  13822. right: 15,
  13823. left: 20
  13824. })
  13825. Row() {
  13826. Text(`高亮颜色:`)
  13827. .fontSize(14)
  13828. .fontColor(Color.White)
  13829. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13830. .fontSize(15)
  13831. .fontColor(Color.White)
  13832. .margin({ left: 6, right: 6 })
  13833. Column() {
  13834. }
  13835. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13836. .margin({ right: 12 })
  13837. .borderRadius(20)
  13838. .height(28)
  13839. .width(28)
  13840. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13841. Row() {
  13842. SymbolGlyph($r('sys.symbol.paintbrush'))
  13843. .fontColor([Color.White])
  13844. .effectStrategy(1)
  13845. Text(`选择颜色`)
  13846. .fontSize(13)
  13847. .margin({ left: 10 })
  13848. .fontColor(Color.White)
  13849. }
  13850. }
  13851. .backgroundColor(Color.Transparent)
  13852. .border({
  13853. color: '#FFFFFF',
  13854. radius: 20,
  13855. width: 1.8
  13856. })
  13857. .height(36)
  13858. .width(110)
  13859. .onClick(() => {
  13860. this.isShowHLSelectColor = !this.isShowHLSelectColor
  13861. })
  13862. .bindPopup(this.isShowHLSelectColor, {
  13863. builder: this.SelectColor(true, isPip),
  13864. placement: Placement.Top,
  13865. mask: { color: '#33000000' },
  13866. enableArrow: false, //是否显示箭头
  13867. showInSubWindow: false,
  13868. onStateChange: (e) => {
  13869. if (!e.isVisible) {
  13870. this.isShowHLSelectColor = false
  13871. }
  13872. }
  13873. })
  13874. }
  13875. .width('100%')
  13876. .margin({
  13877. top: 10,
  13878. bottom: 10,
  13879. right: 15,
  13880. left: 20
  13881. })
  13882. if (isPip) {
  13883. Row() {
  13884. Text(`显示宽度:`)
  13885. .fontSize(14)
  13886. .fontColor(Color.White)
  13887. Slider({
  13888. value: this.pipLyWidth,
  13889. min: 10,
  13890. max: 800,
  13891. step: 1,
  13892. style: SliderStyle.OutSet
  13893. })
  13894. .blockColor(this.themeColor)
  13895. .trackColor($r('app.color.speed_text_color'))
  13896. .selectedColor(Color.White)
  13897. .trackThickness(6)
  13898. .onChange((value: number) => {
  13899. this.pipLyWidth = value
  13900. if (this.pipController) {
  13901. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13902. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  13903. }
  13904. })
  13905. .layoutWeight(1)
  13906. }
  13907. .justifyContent(FlexAlign.Start)
  13908. .margin({
  13909. left: 20,
  13910. right: 15,
  13911. top: 5,
  13912. bottom: 5
  13913. })
  13914. Row() {
  13915. Text(`显示高度:`)
  13916. .fontSize(14)
  13917. .fontColor(Color.White)
  13918. Slider({
  13919. value: this.pipLyHeight,
  13920. min: 10,
  13921. max: 1000,
  13922. step: 1,
  13923. style: SliderStyle.OutSet
  13924. })
  13925. .blockColor(this.themeColor)
  13926. .trackColor($r('app.color.speed_text_color'))
  13927. .selectedColor(Color.White)
  13928. .trackThickness(6)
  13929. .onChange((value: number) => {
  13930. this.pipLyHeight = value
  13931. if (this.pipController) {
  13932. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13933. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  13934. }
  13935. })
  13936. .layoutWeight(1)
  13937. }
  13938. .justifyContent(FlexAlign.Start)
  13939. .margin({
  13940. left: 20,
  13941. right: 15,
  13942. top: 5,
  13943. bottom: 5
  13944. })
  13945. }
  13946. Row() {
  13947. Text(`歌词字号:`)
  13948. .fontSize(14)
  13949. .fontColor(Color.White)
  13950. Slider({
  13951. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  13952. min: 12,
  13953. max: 30,
  13954. step: 0.1,
  13955. style: SliderStyle.OutSet
  13956. })
  13957. .blockColor(this.themeColor)
  13958. .trackColor($r('app.color.speed_text_color'))
  13959. .selectedColor(Color.White)
  13960. .trackThickness(6)
  13961. .onChange((value: number) => {
  13962. this.setLyricTextSize(value, isPip)
  13963. })
  13964. .layoutWeight(1)
  13965. .margin({ right: 3 })
  13966. Text(this.getLyricSizeDisplayValue(isPip))
  13967. .fontSize(13)
  13968. .fontColor(Color.White)
  13969. .textAlign(TextAlign.Start)
  13970. }
  13971. .width('100%')
  13972. .margin({
  13973. left: 20,
  13974. right: 15,
  13975. top: 5,
  13976. bottom: 5
  13977. })
  13978. Row() {
  13979. Text(`高亮倍数:`)
  13980. .fontSize(14)
  13981. .fontColor(Color.White)
  13982. Slider({
  13983. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  13984. min: 1,
  13985. max: 2,
  13986. step: 0.1,
  13987. style: SliderStyle.OutSet
  13988. })
  13989. .blockColor(this.themeColor)
  13990. .trackColor($r('app.color.speed_text_color'))
  13991. .selectedColor(Color.White)
  13992. .trackThickness(6)
  13993. .onChange((value: number) => {
  13994. this.setHighLyricTextSize(value, isPip)
  13995. })
  13996. .layoutWeight(1)
  13997. .margin({ right: 3 })
  13998. Text(this.getHighLyricSizeDisplayValue(isPip))
  13999. .fontSize(13)
  14000. .fontColor(Color.White)
  14001. .textAlign(TextAlign.Start)
  14002. }
  14003. .width('100%')
  14004. .margin({
  14005. left: 20,
  14006. right: 15,
  14007. top: 5,
  14008. bottom: 5
  14009. })
  14010. Row() {
  14011. Text(`歌词间隙:`)
  14012. .fontSize(14)
  14013. .fontColor(Color.White)
  14014. Slider({
  14015. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  14016. min: 0,
  14017. max: 100,
  14018. step: 1,
  14019. style: SliderStyle.OutSet
  14020. })
  14021. .blockColor(this.themeColor)
  14022. .trackColor($r('app.color.speed_text_color'))
  14023. .selectedColor(Color.White)
  14024. .trackThickness(6)
  14025. .onChange((value: number) => {
  14026. this.setLyricLineSpace(value, isPip)
  14027. })
  14028. .layoutWeight(1)
  14029. .margin({ right: 3 })
  14030. Text(this.getLyricLineSpaceDisplayValue(isPip))
  14031. .fontSize(13)
  14032. .fontColor(Color.White)
  14033. .textAlign(TextAlign.Start)
  14034. }
  14035. .width('100%')
  14036. .margin({
  14037. left: 20,
  14038. right: 15,
  14039. top: 5,
  14040. bottom: 5
  14041. })
  14042. //取值间隔为100,默认为400,取值越大,字体越粗
  14043. Row() {
  14044. Text(`歌词字重:`)
  14045. .fontSize(14)
  14046. .fontColor(Color.White)
  14047. Slider({
  14048. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  14049. min: 100,
  14050. max: 900,
  14051. step: 100,
  14052. style: SliderStyle.OutSet
  14053. })
  14054. .blockColor(this.themeColor)
  14055. .trackColor($r('app.color.speed_text_color'))
  14056. .selectedColor(Color.White)
  14057. .trackThickness(6)
  14058. .onChange((value: number) => {
  14059. if (isPip) {
  14060. this.lyricTextWeightPip = value
  14061. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  14062. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  14063. } else {
  14064. this.lyricTextWeight = value
  14065. this.lyricController.setTextWeight(this.lyricTextWeight)
  14066. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  14067. }
  14068. })
  14069. .layoutWeight(1)
  14070. .margin({ right: 3 })
  14071. Text(this.getLyricTextWeightDisplayValue(isPip))
  14072. .fontSize(13)
  14073. .fontColor(Color.White)
  14074. .textAlign(TextAlign.Start)
  14075. }
  14076. .width('100%')
  14077. .margin({
  14078. left: 20,
  14079. right: 15,
  14080. top: 5,
  14081. bottom: 5
  14082. })
  14083. Row() {
  14084. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  14085. this.pushLyricButton($r('app.media.share2'), 2, '分享歌词')
  14086. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  14087. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  14088. }
  14089. .justifyContent(FlexAlign.Center)
  14090. .margin({ top: 3, bottom: 10 })
  14091. }
  14092. .width('88%')
  14093. }
  14094. private getLyricSizeDisplayValue(isPip: boolean): string {
  14095. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  14096. return lyricSize.toFixed(1);
  14097. }
  14098. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  14099. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  14100. return highLyricSize.toFixed(1);
  14101. }
  14102. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  14103. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  14104. return Math.round(lyricLineSpace).toString();
  14105. }
  14106. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  14107. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  14108. return Math.round(lyricTextWeightValue).toString();
  14109. }
  14110. private setBlurDegree(index: number, isPip: boolean) {
  14111. if (isPip) {
  14112. this.blurDegreePip = index
  14113. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  14114. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  14115. } else {
  14116. this.blurDegree = index
  14117. this.lyricController.setBlurDegree(this.blurDegree)
  14118. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  14119. }
  14120. }
  14121. private setLyricAlignMode(index: number, isPip: boolean) {
  14122. if (isPip) {
  14123. this.currentLyricAlignModePip = index
  14124. if (this.currentLyricAlignModePip === 1) {
  14125. this.lyricControllerXF.setAlignMode("left")
  14126. } else {
  14127. this.lyricControllerXF.setAlignMode("center")
  14128. }
  14129. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  14130. } else {
  14131. this.currentLyricAlignMode = index
  14132. if (this.currentLyricAlignMode === 1) {
  14133. this.lyricController.setAlignMode("left")
  14134. } else {
  14135. this.lyricController.setAlignMode("center")
  14136. }
  14137. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  14138. }
  14139. }
  14140. private setLyricTextSize(index: number, isPip: boolean) {
  14141. if (isPip) {
  14142. this.currentLyricSizePip = index
  14143. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  14144. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  14145. } else {
  14146. this.currentLyricSize = index
  14147. this.lyricController.setTextSize(this.currentLyricSize)
  14148. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  14149. }
  14150. }
  14151. private setHighLyricTextSize(scale: number, isPip: boolean) {
  14152. if (isPip) {
  14153. this.currentHightLyricSizePip = scale
  14154. this.lyricControllerXF
  14155. .setHighlightScale(this.currentHightLyricSizePip)
  14156. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  14157. } else {
  14158. this.currentHightLyricSize = scale
  14159. this.lyricController
  14160. .setHighlightScale(this.currentHightLyricSize)
  14161. PreferencesUtil.putSync('HighLyricTextSize', scale)
  14162. }
  14163. }
  14164. private setLyricLineSpace(index: number, isPip: boolean) {
  14165. if (isPip) {
  14166. this.currentLyricLineSpacePip = index
  14167. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  14168. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  14169. } else {
  14170. this.currentLyricLineSpace = index
  14171. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  14172. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  14173. }
  14174. }
  14175. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  14176. LogUtil.info('onecold isBG = ' + isBG)
  14177. if (isBG) { //如果是设置悬浮背景
  14178. this.pipBg = color
  14179. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  14180. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  14181. return
  14182. }
  14183. if (isPip) {
  14184. this.currentLyricColorPip = color
  14185. this.lyricControllerXF
  14186. .setTextColor(this.currentLyricColorPip)
  14187. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  14188. } else {
  14189. this.currentLyricColor = color
  14190. this.lyricController
  14191. .setTextColor(this.currentLyricColor)
  14192. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  14193. }
  14194. }
  14195. private changeLyricHightLightColor(color: string, isPip: boolean) {
  14196. if (isPip) {
  14197. this.currentHighLightLyricColorPip = color
  14198. this.lyricControllerXF
  14199. .setHighlightColor(this.currentHighLightLyricColorPip)
  14200. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  14201. } else {
  14202. this.currentHighLightLyricColor = color
  14203. this.lyricController
  14204. .setHighlightColor(this.currentHighLightLyricColor)
  14205. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  14206. }
  14207. }
  14208. // 构建时间控制器
  14209. @Builder
  14210. BuildTimeControls() {
  14211. Column() {
  14212. // 时间显示
  14213. Text(this.getTimeText())
  14214. .fontSize(18)
  14215. .fontColor(Color.White)
  14216. .margin({ bottom: 10 })
  14217. Row() {
  14218. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  14219. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  14220. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  14221. }
  14222. .justifyContent(FlexAlign.Center)
  14223. }
  14224. .margin({ top: 12, bottom: 8 })
  14225. }
  14226. // 精度按钮组件
  14227. @Builder
  14228. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  14229. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14230. Column() {
  14231. Image(icon)
  14232. .width(28)
  14233. .margin({ bottom: 5 })
  14234. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  14235. Text(label)
  14236. .fontSize(12)
  14237. .fontColor('#FFFFFF')
  14238. }
  14239. }
  14240. .backgroundColor(Color.Transparent)
  14241. .enabled(!this.isButtonDisabled(step))
  14242. .onClick(() => this.handlePrecisionAdjust(step))
  14243. .padding(5)
  14244. .width(66)
  14245. .height(66)
  14246. .margin({ left: 18, right: 18 })
  14247. .border({
  14248. color: '#FFFFFF',
  14249. width: 1.8
  14250. })
  14251. }
  14252. private handlePrecisionAdjust(step: number) {
  14253. if (step === 0) {
  14254. this.timeOffset = 0
  14255. this.saveLyricTimeOffset()
  14256. return
  14257. }
  14258. // 精度处理:保留1位小数
  14259. const newOffset = Number((this.timeOffset + step).toFixed(5))
  14260. // 边界保护(±15.0秒)
  14261. if (newOffset < -30.0 || newOffset > 30.0) {
  14262. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  14263. return
  14264. }
  14265. // 状态更新
  14266. this.timeOffset = newOffset
  14267. // 保存歌词时间偏移
  14268. this.saveLyricTimeOffset()
  14269. }
  14270. // 按钮禁用逻辑
  14271. private isButtonDisabled(step: number): boolean {
  14272. const futureOffset = this.timeOffset + step
  14273. return (futureOffset < -30.0) || (futureOffset > 30.0)
  14274. }
  14275. // 时间显示文本升级
  14276. private getTimeText(): string {
  14277. const absValue = Math.abs(this.timeOffset)
  14278. return this.timeOffset === 0
  14279. ? '歌词时间已重置'
  14280. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  14281. }
  14282. /**
  14283. * 获取当前歌曲的唯一标识key
  14284. * 使用歌曲的filePath作为唯一标识
  14285. */
  14286. private getLyricOffsetKey(): string {
  14287. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  14288. // 使用MD5对filePath进行加密,作为存储key
  14289. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  14290. }
  14291. return ''
  14292. }
  14293. /**
  14294. * 保存当前歌曲的歌词时间偏移
  14295. */
  14296. private saveLyricTimeOffset(): void {
  14297. try {
  14298. const key = this.getLyricOffsetKey()
  14299. if (StrUtil.isEmpty(key)) {
  14300. console.warn('heanup saveLyricTimeOffset: key is empty')
  14301. return
  14302. }
  14303. PreferencesUtil.putSync(key, this.timeOffset)
  14304. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  14305. } catch (e) {
  14306. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  14307. }
  14308. }
  14309. /**
  14310. * 加载当前歌曲的歌词时间偏移
  14311. */
  14312. private loadLyricTimeOffset(): void {
  14313. try {
  14314. const key = this.getLyricOffsetKey()
  14315. if (StrUtil.isEmpty(key)) {
  14316. console.warn('heanup loadLyricTimeOffset: key is empty')
  14317. return
  14318. }
  14319. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  14320. if (savedOffset !== 0) {
  14321. this.timeOffset = savedOffset
  14322. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  14323. }else{
  14324. this.timeOffset = 0
  14325. }
  14326. } catch (e) {
  14327. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  14328. }
  14329. }
  14330. // 导入 本地歌词 搜索歌词
  14331. @Builder
  14332. pushLyricButton(icon: Resource, step: number, label: string) {
  14333. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14334. Row() {
  14335. Image(icon)
  14336. .width(14)
  14337. .margin({ left: 13 })
  14338. Text(label)
  14339. .fontSize(12)
  14340. .margin({ left: 6 })
  14341. .fontColor('#FFFFFF')
  14342. }
  14343. }
  14344. .onClick(() => {
  14345. switch (step) {
  14346. case 0:
  14347. this.callFilePickerSelectFileForLyric()
  14348. break;
  14349. case 1:
  14350. //判断有没有设置api
  14351. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  14352. this.isLyricSetting = false
  14353. this.showTipsDialog()
  14354. return
  14355. }
  14356. if (StrUtil.isNotEmpty(this.videoUrl)) {
  14357. ToastUtil.showToast('正在获取')
  14358. this.isLyricSetting = false
  14359. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  14360. this.initLyric(lyricPath, true);
  14361. }
  14362. break;
  14363. case 2:
  14364. this.isLyricSetting = false
  14365. this.openLyricCopySheet()
  14366. break;
  14367. }
  14368. })
  14369. .padding(5)
  14370. .layoutWeight(1)
  14371. .backgroundColor(Color.Transparent)
  14372. .height(40)
  14373. .margin({ left: 4, right: 4 })
  14374. .border({
  14375. color: '#FFFFFF',
  14376. radius: 20,
  14377. width: 1.8
  14378. })
  14379. }
  14380. showVipDialog() {
  14381. DialogHelper.showCustomContentDialog({
  14382. dialogId: 'vip',
  14383. title: "友情提示",
  14384. autoCancel: false, //点击遮障层时,不关闭弹窗
  14385. backCancel: true, //点击返回键,不关闭弹窗
  14386. contentBuilder: () => {
  14387. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  14388. },
  14389. buttons: [],
  14390. })
  14391. }
  14392. //去赞助的自定义内容
  14393. @Builder
  14394. customVipBuilder(content: string) {
  14395. Column() {
  14396. Text(content)
  14397. .fontColor(Color.Gray)
  14398. .fontSize(16)
  14399. .alignSelf(ItemAlign.Start)
  14400. .margin({ bottom: 15 })
  14401. .fontSize(16)
  14402. Row() {
  14403. Button('取消')
  14404. .fontColor(Color.White)
  14405. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14406. .height(50)
  14407. .layoutWeight(1)
  14408. .stateEffect(true)
  14409. .margin({ right: 6 })
  14410. .onClick(() => {
  14411. DialogHelper.closeDialog('vip'); //关闭弹框
  14412. })
  14413. Button('开通')
  14414. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14415. .layoutWeight(1)
  14416. .height(50)
  14417. .backgroundColor(this.themeColor)
  14418. .stateEffect(true)
  14419. .margin({ left: 6 })
  14420. .onClick(() => {
  14421. DialogHelper.closeDialog('vip'); //关闭弹框
  14422. this.isShowPlay = false
  14423. this.mType = 1 //跳转到用户中心
  14424. // router.pushUrl({
  14425. // url: 'pages/VipPage'
  14426. // }, router.RouterMode.Single);
  14427. })
  14428. }
  14429. }
  14430. .width("100%")
  14431. .padding(10)
  14432. }
  14433. showTipsDialog() {
  14434. DialogHelper.showCustomContentDialog({
  14435. dialogId: 'tips',
  14436. title: "友情提示",
  14437. autoCancel: false, //点击遮障层时,不关闭弹窗
  14438. backCancel: true, //点击返回键,不关闭弹窗
  14439. contentBuilder: () => {
  14440. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  14441. },
  14442. buttons: [],
  14443. })
  14444. }
  14445. @Builder
  14446. customTipsBuilder(content: string) {
  14447. Column() {
  14448. Text(content)
  14449. .fontColor(Color.Gray)
  14450. .fontSize(16)
  14451. .alignSelf(ItemAlign.Start)
  14452. .margin({ bottom: 15 })
  14453. .fontSize(16)
  14454. Row() {
  14455. Button('取消')
  14456. .fontColor(Color.White)
  14457. .backgroundColor(this.themeColor)
  14458. .height(50)
  14459. .layoutWeight(1)
  14460. .stateEffect(true)
  14461. .margin({ right: 6 })
  14462. .onClick(() => {
  14463. DialogHelper.closeDialog('tips'); //关闭弹框
  14464. })
  14465. Button('跳转')
  14466. .fontColor(Color.White)//
  14467. .layoutWeight(1)
  14468. .height(50)
  14469. .backgroundColor(this.themeColor)
  14470. .stateEffect(true)
  14471. .margin({ left: 6 })
  14472. .onClick(() => {
  14473. DialogHelper.closeDialog('tips'); //关闭弹框
  14474. this.isShowEdit = false
  14475. this.longItemFilePath = ''
  14476. // if(this.isGridMusic&&!this.isShowPlay){
  14477. // this.longItemFilePath== ''
  14478. // }else{
  14479. // this.isShowEdit = false
  14480. // }
  14481. this.isShowMoreView = false;
  14482. this.isShowPlay = false
  14483. this.mType = 4
  14484. // router.pushUrl({
  14485. // url: 'pages/SettingPage'
  14486. // }, router.RouterMode.Single);
  14487. })
  14488. }
  14489. }
  14490. .width("100%")
  14491. .padding(10)
  14492. }
  14493. @Builder
  14494. PlayMoreSheet() {
  14495. Column() {
  14496. this.MoreList()
  14497. }
  14498. .width('100%')
  14499. .height('100%')
  14500. }
  14501. @Builder
  14502. MoreList() {
  14503. Scroll() {
  14504. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  14505. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  14506. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14507. Row() {
  14508. if (more.id === 3&&this.currentSong) {
  14509. Image(more.image)
  14510. .width(24)
  14511. .height(24)
  14512. .margin({ left: 10, right: 10 })
  14513. Text(more.title)
  14514. .fontSize(16)
  14515. .fontColor(Color.White)
  14516. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  14517. height: '99%',
  14518. dragBar: true,
  14519. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14520. showClose: true,
  14521. blurStyle: BlurStyle.Thin,
  14522. backgroundColor: Color.Transparent,
  14523. title: { title: '歌曲信息' }
  14524. })
  14525. } else if (more.id === 15 && this.currentSong) { //编辑标签
  14526. Image(more.image)
  14527. .width(24)
  14528. .height(24)
  14529. .margin({ left: 10, right: 10 })
  14530. Text(more.title)
  14531. .fontSize(16)
  14532. .fontColor(Color.White)
  14533. } else if (more.id === 5) { //定时关闭
  14534. Image(more.image)
  14535. .width(24)
  14536. .height(24)
  14537. .margin({ left: 10, right: 10 })
  14538. Text(more.title)
  14539. .fontSize(16)
  14540. .fontColor(Color.White)
  14541. .onClick(() => {
  14542. this.doMore(more.id)
  14543. })
  14544. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  14545. height: this.isCoverOpacity() ? '95%' : '95%',
  14546. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14547. dragBar: true,
  14548. showClose: true,
  14549. title: { title: $r('app.string.time_close') }
  14550. })
  14551. } else if (more.id === 2) { //歌词设置
  14552. Image(more.image)
  14553. .width(24)
  14554. .height(24)
  14555. .margin({ left: 10, right: 10 })
  14556. Text(more.title)
  14557. .fontSize(16)
  14558. .fontColor(Color.White)
  14559. } else if (more.id === 16) { //悬浮歌词设置
  14560. Image(more.image)
  14561. .width(24)
  14562. .height(24)
  14563. .margin({ left: 10, right: 10 })
  14564. Text(more.title)
  14565. .fontSize(16)
  14566. .fontColor(Color.White)
  14567. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  14568. height: '99%',
  14569. dragBar: true,
  14570. preferType: SheetType.CENTER,
  14571. showClose: true,
  14572. blurStyle: BlurStyle.Thin,
  14573. backgroundColor: Color.Transparent,
  14574. title: { title: '悬浮歌词' }
  14575. })
  14576. } else if (more.id === 11) {
  14577. Image(more.image)
  14578. .width(24)
  14579. .height(24)
  14580. .margin({ left: 10, right: 10 })
  14581. Text(more.title)
  14582. .fontSize(16)
  14583. .fontColor(Color.White)
  14584. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  14585. height: this.isCoverOpacity() ? '95%' : '60%',
  14586. dragBar: true,
  14587. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14588. showClose: true,
  14589. blurStyle: BlurStyle.Thin,
  14590. backgroundColor: Color.Transparent,
  14591. title: { title: '跳过头尾' }
  14592. })
  14593. } else if (more.id === 12) { //投播
  14594. AVCastPicker({
  14595. customPicker: (): void => this.TPImageBuilder(more),
  14596. onStateChange: (state) => {
  14597. if (state == AVCastPickerState.STATE_APPEARING) {
  14598. console.log(' The picker starts showing.');
  14599. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14600. console.log(' The picker finishes presenting.');
  14601. }
  14602. },
  14603. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  14604. sessionType: 'video'
  14605. })
  14606. .id('AVCastPicker')
  14607. } else {
  14608. if(more.id >= 22){
  14609. SymbolGlyph(more.image)
  14610. .fontSize(24)
  14611. .fontColor([Color.White])
  14612. .alignSelf(ItemAlign.Center)
  14613. .margin({ left: 10, right: 10,bottom:5})
  14614. // .padding({bottom:4})
  14615. .onClick(() => {
  14616. this.doMore(more.id)
  14617. })
  14618. }else{
  14619. Image(more.image)
  14620. .width(24)
  14621. .height(24)
  14622. .fillColor(Color.White)
  14623. .margin({ left: 10, right: 10 })
  14624. .onClick(() => {
  14625. this.doMore(more.id)
  14626. })
  14627. }
  14628. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  14629. .fontSize(16)
  14630. .margin({top:more.id >= 22?3:0})
  14631. .fontColor(Color.White)
  14632. .onClick(() => {
  14633. this.doMore(more.id)
  14634. })
  14635. Select([//倍速
  14636. { value: '0.25x' },
  14637. { value: '0.5x' },
  14638. { value: '0.75x' },
  14639. { value: '1x' },
  14640. { value: '1.25x' },
  14641. { value: '1.5x' },
  14642. { value: '1.75x' },
  14643. { value: '2x' },
  14644. { value: '3x' }])
  14645. .font({ size: 16, weight: FontWeight.Medium })
  14646. .fontColor($r('sys.color.white'))
  14647. .margin({ left: 25 })
  14648. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  14649. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  14650. .value(Utility.optimizedFormat(this.playSpeed))
  14651. .onSelect(async (_index: number, text?: string | undefined) => {
  14652. let speed = parseFloat(text?.replace('x', '') || '1');
  14653. if (!CommonConstants.video_speed_list.includes(speed)) {
  14654. speed = 1;
  14655. }
  14656. this.playSpeed = speed
  14657. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14658. })
  14659. Slider({
  14660. value: this.volume,
  14661. min: 0,
  14662. max: 1,
  14663. step: 0.1,
  14664. style: SliderStyle.OutSet
  14665. })
  14666. .margin({ left: 18, right: 8 })
  14667. .blockColor(this.themeColor)
  14668. .trackColor($r('app.color.speed_text_color'))
  14669. .selectedColor(Color.White)
  14670. .trackThickness(9)
  14671. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14672. .onChange((value: number) => {
  14673. this.volume = value;
  14674. this.applyCurrentVolume();
  14675. PreferencesUtil.putSync('DefalutVolume',this.volume)
  14676. })
  14677. .layoutWeight(1)
  14678. Slider({
  14679. value: this.volumeBoostPercent,
  14680. min: 0,
  14681. max: this.volumeBoostMaxPercent,
  14682. step: 1,
  14683. style: SliderStyle.OutSet
  14684. })
  14685. .margin({ left: 18, right: 8 })
  14686. .blockColor(this.themeColor)
  14687. .trackColor($r('app.color.speed_text_color'))
  14688. .selectedColor(Color.White)
  14689. .trackThickness(9)
  14690. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14691. .onChange((value: number) => {
  14692. this.volumeBoostPercent = Math.round(value);
  14693. this.applyCurrentVolume();
  14694. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  14695. })
  14696. .layoutWeight(1)
  14697. Text(`${Math.round(this.volumeBoostPercent)}%`)
  14698. .fontSize(13)
  14699. .fontColor(Color.White)
  14700. .margin({ left: 8, right: 8 })
  14701. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14702. Text(`${Math.round(this.volume*100)}%`)
  14703. .fontSize(13)
  14704. .fontColor(Color.White)
  14705. .margin({ left: 8, right: 8 })
  14706. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14707. Blank()
  14708. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  14709. .selectedColor(this.themeColor)
  14710. .switchPointColor(Color.White)
  14711. .margin({ right: 15 })
  14712. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14713. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  14714. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14715. if (more.id == 6) {
  14716. this.isMusicMemoryPlay = checked;
  14717. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  14718. if (this.isMusicMemoryPlay) {
  14719. ToastUtil.showToast('记忆播放已开启')
  14720. } else {
  14721. ToastUtil.showToast('记忆播放已关闭')
  14722. }
  14723. }
  14724. })
  14725. .width(48)
  14726. .height(24);
  14727. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  14728. .selectedColor(this.themeColor)
  14729. .switchPointColor(Color.White)
  14730. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14731. .margin({ right: 15 })
  14732. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  14733. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14734. if (more.id == 7) {
  14735. this.isMusicBGCover = checked;
  14736. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  14737. if (this.isMusicBGCover) {
  14738. ToastUtil.showToast('播放背景随音乐封面已开启')
  14739. } else {
  14740. ToastUtil.showToast('播放背景随音乐封面已关闭')
  14741. }
  14742. }
  14743. })
  14744. .width(48)
  14745. .height(24);
  14746. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  14747. .selectedColor(this.themeColor)
  14748. .switchPointColor(Color.White)
  14749. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14750. .margin({ right: 15 })
  14751. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  14752. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14753. if (more.id == 8) {
  14754. this.isSavePlayMode = checked;
  14755. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  14756. if (this.isSavePlayMode) {
  14757. ToastUtil.showToast('保存播放模式已开启')
  14758. } else {
  14759. ToastUtil.showToast('保存播放模式已关闭')
  14760. }
  14761. }
  14762. })
  14763. .width(48)
  14764. .height(24);
  14765. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  14766. .selectedColor(this.themeColor)
  14767. .switchPointColor(Color.White)
  14768. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14769. .margin({ right: 15 })
  14770. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  14771. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14772. if (more.id == 13) {
  14773. this.isCoverRectangle = checked;
  14774. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  14775. if (this.isCoverRectangle) {
  14776. ToastUtil.showToast('封面方形已开启,双指缩放封面可以调整封面大小')
  14777. this.animationRoFun()
  14778. } else {
  14779. ToastUtil.showToast('封面圆形已开启,双指缩放封面可以调整封面大小')
  14780. this.animationRoFun()
  14781. }
  14782. }
  14783. })
  14784. .width(48)
  14785. .height(24);
  14786. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  14787. .selectedColor(this.themeColor)
  14788. .switchPointColor(Color.White)
  14789. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14790. .margin({ right: 15 })
  14791. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  14792. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14793. if (more.id == 25) {
  14794. this.isShowSpectrum = checked;
  14795. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  14796. }
  14797. })
  14798. .width(48)
  14799. .height(24);
  14800. // 频谱特效类型选择器
  14801. Select([
  14802. { value: '柱状' },
  14803. { value: '波形' },
  14804. { value: '水波纹' },
  14805. { value: '圆形' },
  14806. { value: '粒子' },
  14807. { value: '脉冲' },
  14808. { value: '镜像柱' },
  14809. { value: '影子柱' },
  14810. { value: '轨道线' },
  14811. { value: '点阵' },
  14812. { value: '星爆' },
  14813. { value: '心电图' },
  14814. { value: '特效' }
  14815. ])
  14816. .font({ size: 14, weight: FontWeight.Medium })
  14817. .fontColor(Color.White)
  14818. .margin({ left: 25 })
  14819. .margin({top:more.id >= 22?3:0})
  14820. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  14821. .selected(this.spectrumModeIndex)
  14822. .value(['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'][this.spectrumModeIndex])
  14823. .onSelect((index: number, _text?: string) => {
  14824. this.spectrumModeIndex = index;
  14825. // 使用同步方法保存,确保立即生效
  14826. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  14827. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  14828. const modeNames = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  14829. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  14830. });
  14831. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  14832. .selectedColor(this.themeColor)
  14833. .switchPointColor(Color.White)
  14834. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14835. .margin({ right: 15 })
  14836. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  14837. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14838. if (more.id == 22) {
  14839. this.showSimple = checked;
  14840. PreferencesUtil.put('showSimple', this.showSimple)
  14841. }
  14842. })
  14843. .width(48)
  14844. .height(24);
  14845. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  14846. .selectedColor(this.themeColor)
  14847. .switchPointColor(Color.White)
  14848. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14849. .margin({ right: 15 })
  14850. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  14851. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14852. if (more.id == 23) {
  14853. this.enablePointLight = checked;
  14854. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  14855. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  14856. }
  14857. })
  14858. .width(48)
  14859. .height(24);
  14860. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  14861. .selectedColor(this.themeColor)
  14862. .switchPointColor(Color.White)
  14863. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14864. .margin({ right: 15 })
  14865. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  14866. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14867. if (more.id == 27) {
  14868. this.isGeKongPlayNext = checked;
  14869. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  14870. }
  14871. })
  14872. .width(48)
  14873. .height(24);
  14874. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  14875. .selectedColor(this.themeColor)
  14876. .switchPointColor(Color.White)
  14877. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14878. .margin({ right: 15 })
  14879. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  14880. .onChange((checked: boolean) => { // 是否开启背景流光效果
  14881. if (more.id == 21) {
  14882. this.isShowBgLiuGUANG = checked;
  14883. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  14884. }
  14885. })
  14886. .width(48)
  14887. .height(24);
  14888. }
  14889. }
  14890. .width('100%')
  14891. .height(45)
  14892. .padding(15)
  14893. .backgroundColor(Color.Transparent)
  14894. .borderRadius(12)
  14895. .margin({ bottom: 6 })
  14896. }
  14897. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  14898. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  14899. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  14900. .backgroundColor(Color.Transparent)
  14901. .onClick(() => {
  14902. this.doMore(more.id)
  14903. })
  14904. });
  14905. }
  14906. .width('100%')
  14907. .padding(16)
  14908. }.margin({ bottom: 18 })
  14909. }
  14910. @Builder
  14911. TPImageBuilder(more: MoreItem): void {
  14912. Row() {
  14913. Image($r('app.media.tuoping'))
  14914. .width(22)
  14915. .height(22)
  14916. .margin({ left: 10, right: 10 })
  14917. Text(more.title)
  14918. .fontSize(16)
  14919. .fontColor(Color.White)
  14920. }
  14921. .width('100%')
  14922. .layoutWeight(1)
  14923. .alignItems(VerticalAlign.Center)
  14924. .justifyContent(FlexAlign.Start)
  14925. }
  14926. private moreItems: MoreItem[] = [
  14927. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  14928. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  14929. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  14930. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  14931. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  14932. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  14933. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  14934. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  14935. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  14936. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  14937. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  14938. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  14939. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  14940. { id: 4, image: $r('app.media.share2'), title: '分享' },
  14941. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  14942. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  14943. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  14944. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  14945. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  14946. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  14947. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  14948. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  14949. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  14950. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  14951. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  14952. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  14953. ];
  14954. @State isShowBgLiuGUANG: boolean = false;
  14955. @State isShowMoreView: boolean = false;
  14956. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  14957. @State isShowTimeCloseMore: boolean = false
  14958. @State isShowDetailMore: boolean = false
  14959. @State isMusicBGCover: boolean = true
  14960. @State isSavePlayMode: boolean = true
  14961. @State isLyricSetting: boolean = false
  14962. @State isJumpSetting: boolean = false
  14963. @State isShowEdit: boolean = false
  14964. @State showPipLyric: boolean = false
  14965. @State isShowSpectrum: boolean = false//是否显示频谱
  14966. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  14967. private getEqualizerVolumeBoostRisk(): number {
  14968. const equalizerManager = EqualizerManager.getInstance();
  14969. if (!equalizerManager.enabled) {
  14970. return 0;
  14971. }
  14972. const gainStats = equalizerManager.getCurrentGainStats();
  14973. if (gainStats.maxPositiveGain <= 0 || gainStats.positiveGainSum <= 0) {
  14974. return 0;
  14975. }
  14976. const peakRisk = (gainStats.maxPositiveGain / 12) * 0.65;
  14977. const spreadRisk = (gainStats.positiveGainSum / 24) * 0.35;
  14978. return Math.max(0, Math.min(peakRisk + spreadRisk, 1));
  14979. }
  14980. private getSafeBoostPercent(): number {
  14981. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  14982. let compressedBoostPercent = rawBoostPercent;
  14983. if (rawBoostPercent <= 150) {
  14984. compressedBoostPercent = rawBoostPercent;
  14985. } else if (rawBoostPercent <= 300) {
  14986. compressedBoostPercent = 150 + (rawBoostPercent - 150) * 0.45;
  14987. } else {
  14988. compressedBoostPercent = 217.5 + (rawBoostPercent - 300) * 0.15;
  14989. }
  14990. const equalizerRisk = this.getEqualizerVolumeBoostRisk();
  14991. if (equalizerRisk <= 0) {
  14992. return compressedBoostPercent;
  14993. }
  14994. const protectedBoostPercent = compressedBoostPercent * (1 - equalizerRisk * 0.45);
  14995. const cappedBoostPercent = 220 - equalizerRisk * 140;
  14996. return Math.max(0, Math.min(protectedBoostPercent, cappedBoostPercent));
  14997. }
  14998. private getVolumeBoostFactor(): number {
  14999. return 1 + this.getSafeBoostPercent() / 100;
  15000. }
  15001. private getCurrentOutputVolume(): number {
  15002. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  15003. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  15004. const maxOutputVolume = this.getVolumeBoostFactor();
  15005. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  15006. }
  15007. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  15008. if (!this.mIjkMediaPlayer) {
  15009. return;
  15010. }
  15011. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  15012. this.mIjkMediaPlayer.setVolume('1', '1');
  15013. return;
  15014. }
  15015. const outputVolume = this.getCurrentOutputVolume();
  15016. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  15017. }
  15018. async setRingTone() {
  15019. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  15020. return
  15021. }
  15022. // 确定后的逻辑
  15023. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  15024. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  15025. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  15026. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  15027. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  15028. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  15029. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  15030. , this.videoUrl, this.name).then(res => {
  15031. LogUtil.info('onecold setFlag :' + res);
  15032. });
  15033. }
  15034. doMore(moreId: number) {
  15035. switch (moreId) {
  15036. case 30: //歌词
  15037. this.isLyricSetting = !this.isLyricSetting;
  15038. this.isShowMoreView = false
  15039. break;
  15040. case 3: //详情
  15041. this.isShowDetailMore = !this.isShowDetailMore;
  15042. break;
  15043. case 4: //分享
  15044. if (this.currentSong !== undefined) {
  15045. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  15046. }
  15047. this.isShowMoreView = false
  15048. break;
  15049. case 5: //定时关闭
  15050. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  15051. break;
  15052. case 10: //设为铃声
  15053. this.setRingTone()
  15054. this.isShowMoreView = false
  15055. break;
  15056. case 11: //跳过头尾
  15057. this.isJumpSetting = !this.isJumpSetting;
  15058. break;
  15059. case 13: //倍速
  15060. break;
  15061. case 14: //搜索封面
  15062. if (this.currentSong !== undefined) {
  15063. this.doSearchCover(this.currentSong)
  15064. }
  15065. this.isShowMoreView = false
  15066. break;
  15067. case 15: //编辑标签
  15068. this.initEditFields(this.currentSong)
  15069. this.tempLyricContent = this.lyricContent
  15070. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  15071. this.lyricConStr = this.tempLyricContent
  15072. }
  15073. this.isShowEdit = !this.isShowEdit;
  15074. break;
  15075. case 16: //悬浮歌词
  15076. this.showPipLyric = !this.showPipLyric;
  15077. break;
  15078. case 17: //横屏模式
  15079. if (this.isLandscape) {
  15080. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  15081. } else {
  15082. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  15083. }
  15084. this.isShowMoreView = false
  15085. break;
  15086. case 20://AB循环
  15087. this.isABSheet = !this.isABSheet
  15088. break;
  15089. case 24://均衡器
  15090. this.isEqualizerSheet = !this.isEqualizerSheet
  15091. break;
  15092. }
  15093. }
  15094. //AB循环
  15095. @State isOpenAB:boolean = false
  15096. @State jumpATime:number = 0
  15097. @State jumpBTime:number = 0
  15098. @State isABSheet:boolean = false
  15099. @State isEqualizerSheet: boolean = false
  15100. @State eqApplying: boolean = false
  15101. @State eqAppliedAt: number = 0
  15102. @State eqCurrentPresetName: string = '正常'
  15103. @State eqCurrentEnabled: boolean = false
  15104. @Builder
  15105. ABLoopSheet() {
  15106. ABLoopComptent({
  15107. jumpATime:this.jumpATime,
  15108. jumpBTime:this.jumpBTime,
  15109. onClickAItem: async ()=>{
  15110. if(this.mIjkMediaPlayer){
  15111. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  15112. }
  15113. },
  15114. onClickBItem: async ()=>{
  15115. if(this.mIjkMediaPlayer){
  15116. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  15117. if(this.jumpBTime<=this.jumpATime){
  15118. ToastUtil.showToast('设置B点时间不能小于A点时间')
  15119. this.jumpBTime = 0
  15120. }
  15121. }
  15122. },
  15123. onCancleButtonClick: async ()=>{
  15124. this.isOpenAB = false
  15125. this.isABSheet = false
  15126. },
  15127. onStartButtonClick: async ()=>{
  15128. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  15129. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  15130. return
  15131. }
  15132. this.isABSheet = false
  15133. this.startABLoop()
  15134. },
  15135. })
  15136. }
  15137. private syncEqualizerUi(): void {
  15138. const equalizerManager = EqualizerManager.getInstance();
  15139. this.eqCurrentEnabled = equalizerManager.enabled;
  15140. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15141. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  15142. this.eqAppliedAt = 0;
  15143. }
  15144. }
  15145. private markEqualizerApplied(): void {
  15146. const equalizerManager = EqualizerManager.getInstance();
  15147. this.eqCurrentEnabled = equalizerManager.enabled;
  15148. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15149. this.eqAppliedAt = Date.now();
  15150. this.eqApplying = false;
  15151. }
  15152. private applyEqualizerToCurrentPlayback(): void {
  15153. if (this.eqApplying) {
  15154. return;
  15155. }
  15156. if (this.castControllerWrapper && this.isCastPlaying) {
  15157. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  15158. return;
  15159. }
  15160. if (!this.currentSong || !this.mIjkMediaPlayer) {
  15161. ToastUtil.showToast('暂无可应用的播放');
  15162. return;
  15163. }
  15164. this.eqApplying = true;
  15165. try {
  15166. const equalizerManager = EqualizerManager.getInstance();
  15167. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15168. this.applyCurrentVolume();
  15169. this.markEqualizerApplied();
  15170. ToastUtil.showToast('均衡器已实时生效');
  15171. } catch (error) {
  15172. this.eqApplying = false;
  15173. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  15174. }
  15175. }
  15176. @Builder
  15177. private EqualizerApplyStatusBar(): void {
  15178. Row() {
  15179. Column() {
  15180. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  15181. .fontSize(12)
  15182. .fontColor($r('app.color.text_color'))
  15183. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  15184. .fontSize(10)
  15185. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  15186. }
  15187. .alignItems(HorizontalAlign.Start)
  15188. Blank()
  15189. Button('重新应用')
  15190. .fontSize(12)
  15191. .fontColor(Color.White)
  15192. .backgroundColor('#666666')
  15193. .height(28)
  15194. .padding({ left: 14, right: 14 })
  15195. .borderRadius(14)
  15196. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  15197. .onClick(() => {
  15198. this.applyEqualizerToCurrentPlayback();
  15199. })
  15200. }
  15201. .width('100%')
  15202. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  15203. .backgroundColor($r('app.color.settings_background_main'))
  15204. .borderRadius(12)
  15205. }
  15206. @Builder
  15207. EqualizerSheet() {
  15208. Column() {
  15209. Column() {
  15210. EqualizerViewWithCallback({
  15211. onEqualizerChanged: () => {
  15212. this.syncEqualizerUi();
  15213. if (this.mIjkMediaPlayer) {
  15214. const equalizerManager = EqualizerManager.getInstance();
  15215. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15216. this.applyCurrentVolume();
  15217. this.markEqualizerApplied();
  15218. }
  15219. }
  15220. })
  15221. }
  15222. .margin({ top: 8 })
  15223. Column() {
  15224. this.EqualizerApplyStatusBar()
  15225. }
  15226. .margin({ top: 8 })
  15227. }
  15228. .padding({ left: 12, right: 12, bottom: 20 })
  15229. .width('100%')
  15230. }
  15231. //开始AB循环
  15232. startABLoop(){
  15233. if(this.mIjkMediaPlayer){
  15234. this.seekTo(this.jumpATime+'')
  15235. this.isOpenAB = true
  15236. }
  15237. }
  15238. /**
  15239. * 切换横竖屏
  15240. *
  15241. */
  15242. setOrientation(orientation: number) {
  15243. this.windowClass.setPreferredOrientation(orientation).then(() => {
  15244. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  15245. }).catch((err: BusinessError) => {
  15246. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  15247. });
  15248. }
  15249. /**
  15250. * 画中画功能(悬浮歌词功能)
  15251. *
  15252. */
  15253. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  15254. pipController?: PiPWindow.PiPController;
  15255. navigationId: string = '';
  15256. @State curState: string = '';
  15257. @State curError: ResourceStr = '';
  15258. @State pipBg: string = '#E8E8E8'
  15259. @State buttonAction: string = '';
  15260. //开启画中画功能
  15261. async startPip() {
  15262. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  15263. if (!this.pipController) {
  15264. await this.createPipController();
  15265. }
  15266. if (!this.pipController) {
  15267. Logger.info(`[${TAG}] pipController create error`);
  15268. return;
  15269. }
  15270. await this.pipController.startPiP();
  15271. }
  15272. async stopPip() {
  15273. if (!this.pipController) {
  15274. Logger.info(`[${TAG}] pipController is not exist`);
  15275. return;
  15276. }
  15277. this.isOpenPip = false
  15278. await this.pipController.stopPiP();
  15279. }
  15280. async createPipController() {
  15281. this.pipController = await PiPWindow.create({
  15282. context: getContext(this),
  15283. componentController: this.xcomponentController,
  15284. navigationId: this.navigationId,
  15285. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  15286. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  15287. customUIController: this.nodeController,
  15288. });
  15289. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  15290. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  15291. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  15292. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  15293. this.onStateChange(state, reason);
  15294. });
  15295. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  15296. this.onActionEvent(event, status);
  15297. });
  15298. }
  15299. destroyPipController() {
  15300. if (!this.pipController) {
  15301. return;
  15302. }
  15303. this.pipController.off('stateChange');
  15304. this.pipController.off('controlPanelActionEvent');
  15305. this.pipController = undefined;
  15306. }
  15307. onStateChange(state: PiPWindow.PiPState, reason: string) {
  15308. switch (state) {
  15309. case PiPWindow.PiPState.ABOUT_TO_START:
  15310. this.curState = 'ABOUT_TO_START';
  15311. this.curError = $r('app.string.current_error_hint');
  15312. break;
  15313. case PiPWindow.PiPState.STARTED:
  15314. this.curState = 'STARTED';
  15315. this.curError = $r('app.string.current_error_hint');
  15316. break;
  15317. case PiPWindow.PiPState.ABOUT_TO_STOP:
  15318. this.curState = 'ABOUT_TO_STOP';
  15319. this.curError = $r('app.string.current_error_hint');
  15320. break;
  15321. case PiPWindow.PiPState.STOPPED:
  15322. this.curState = 'STOPPED';
  15323. this.curError = $r('app.string.current_error_hint');
  15324. this.stopPip()
  15325. this.destroyPipController()
  15326. break;
  15327. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  15328. this.curState = 'ABOUT_TO_RESTORE';
  15329. this.curError = $r('app.string.current_error_hint');
  15330. break;
  15331. case PiPWindow.PiPState.ERROR:
  15332. this.curState = 'ERROR';
  15333. this.curError = reason;
  15334. break;
  15335. default:
  15336. break;
  15337. }
  15338. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  15339. }
  15340. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  15341. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  15342. switch (event) {
  15343. case 'playbackStateChanged':
  15344. if (status === 0) {
  15345. this.pause();
  15346. } else {
  15347. console.info('onecold startPlayOrResumePlay 9869')
  15348. this.startPlayOrResumePlay();
  15349. }
  15350. break;
  15351. case 'nextVideo':
  15352. // 切换到下一个视频
  15353. this.playNext().catch(() => {
  15354. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  15355. });
  15356. break;
  15357. case 'previousVideo':
  15358. // 切换到上一个视频
  15359. this.playPrevious().catch(() => {
  15360. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  15361. });
  15362. break;
  15363. case 'previousVideo':
  15364. // 切换到上一个视频
  15365. this.playPrevious().catch(() => {
  15366. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  15367. });
  15368. break;
  15369. default:
  15370. }
  15371. this.buttonAction = event + `-status:${status}`;
  15372. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  15373. }
  15374. /**
  15375. * 画中画功能(悬浮歌词功能)结束
  15376. *
  15377. */
  15378. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  15379. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  15380. this.isShowMoreView = false;
  15381. this.showTipsDialog();
  15382. return ''; // Return empty string when no API is configured
  15383. }
  15384. if (!item) {
  15385. return ''; // Return empty string if item is undefined
  15386. }
  15387. const titleS = title||item?.name || '';
  15388. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  15389. return this.searchCover(item, titleS, artistS, true); // Await is not needed here as we return the promise directly
  15390. }
  15391. /**
  15392. *api搜索封面
  15393. *item,根据title和artist
  15394. */
  15395. searchCover(item: VideoItem, title: string, artist: string, markAsCustomCover: boolean = false): Promise<string> {
  15396. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  15397. LogUtil.debug("onecold res =" + res);
  15398. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  15399. if (item.filePath == this.currentSong?.filePath) {
  15400. if (this.currentSong) {
  15401. mergeCoverWithPriority(this.currentSong, res, markAsCustomCover ? 1 : 0);
  15402. this.cover = this.currentSong.pixelMapPath || res;
  15403. }
  15404. }
  15405. if (isRemoteCloudType(item.type)) {
  15406. mergeCoverWithPriority(item, res, markAsCustomCover ? 1 : 0);
  15407. this.syncRemoteManagerSong(item);
  15408. try {
  15409. await this.persistRemoteMetadataToDb(item);
  15410. this.emitRemoteMetadataUpdated(item);
  15411. } catch (error) {
  15412. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  15413. }
  15414. } else {
  15415. // Update pixel map path but always return res regardless of success
  15416. if (markAsCustomCover) {
  15417. item.isCustomCover = 1;
  15418. this.table.updateCustomCoverPath(item.filePath, res, (success: boolean, error?: string) => {
  15419. if (success) {
  15420. this.doUpdateData();
  15421. console.log("onecold 更新音乐封面成功,数据库已同步");
  15422. } else {
  15423. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15424. }
  15425. });
  15426. } else {
  15427. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  15428. if (success) {
  15429. this.doUpdateData();
  15430. console.log("onecold 更新音乐封面成功,数据库已同步");
  15431. } else {
  15432. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15433. }
  15434. });
  15435. }
  15436. }
  15437. LogUtil.debug("onecold this.cover =" + this.cover);
  15438. }
  15439. return res; // Always return res regardless of updatePixelMapPath result
  15440. });
  15441. }
  15442. @State jumpTopTime: number = 0
  15443. @State jumpEndTime: number = 0
  15444. @State isOpenJump: boolean = false
  15445. @Builder
  15446. JumpTopEndSheet() {
  15447. Scroll() {
  15448. Column() {
  15449. Column() {
  15450. Text('仅对本播放列表有效')
  15451. .fontSize(16)
  15452. .fontColor($r('app.color.text_color'))
  15453. // 跳过头尾
  15454. Column() {
  15455. Row() {
  15456. Text('跳过片头:')
  15457. .fontSize(16)
  15458. .fontColor($r('app.color.text_color'))
  15459. Text(this.jumpTopTime + 's')
  15460. .fontSize(16)
  15461. .fontColor($r('app.color.text_color'))
  15462. }
  15463. .margin({ bottom: 5 })
  15464. Row() {
  15465. Slider({
  15466. value: this.jumpTopTime,
  15467. min: 0,
  15468. max: 120,
  15469. step: 1,
  15470. style: SliderStyle.OutSet
  15471. })
  15472. .blockColor(this.themeColor)
  15473. .trackColor($r('app.color.speed_text_color'))
  15474. .selectedColor(Color.White)
  15475. .trackThickness(8)
  15476. .onChange((value: number) => {
  15477. this.jumpTopTime = value;
  15478. })
  15479. .width('85%')
  15480. }
  15481. .alignItems(VerticalAlign.Top)
  15482. }
  15483. .margin({ top: 10, bottom: 10 })
  15484. // 跳过头尾
  15485. Column() {
  15486. Row() {
  15487. Text('跳过片尾:')
  15488. .fontSize(16)
  15489. .fontColor($r('app.color.text_color'))
  15490. Text(this.jumpEndTime + 's')
  15491. .fontSize(16)
  15492. .fontColor($r('app.color.text_color'))
  15493. }
  15494. .margin({ bottom: 5 })
  15495. Row() {
  15496. Slider({
  15497. value: this.jumpEndTime,
  15498. min: 0,
  15499. max: 120,
  15500. step: 1,
  15501. style: SliderStyle.OutSet
  15502. })
  15503. .blockColor(this.themeColor)
  15504. .trackColor($r('app.color.speed_text_color'))
  15505. .selectedColor(Color.White)
  15506. .trackThickness(8)
  15507. .onChange((value: number) => {
  15508. this.jumpEndTime = value;
  15509. })
  15510. .width('85%')
  15511. }
  15512. .alignItems(VerticalAlign.Top)
  15513. }
  15514. .margin({ top: 10, bottom: 10 })
  15515. Row() {
  15516. Button('保存设置')
  15517. .fontColor(Color.White)
  15518. .layoutWeight(1)
  15519. .height(40)
  15520. .width(80)
  15521. .backgroundColor(this.themeColor)
  15522. .stateEffect(true)
  15523. .margin({ left: 0, bottom: 20 })
  15524. .onClick(async () => {
  15525. if (!Utility.isNoble()) {
  15526. this.isJumpSetting = false
  15527. this.isShowMoreView = false
  15528. this.showVipDialog()
  15529. return
  15530. }
  15531. if (this.currentSong === undefined) {
  15532. return
  15533. }
  15534. if (this.modeType === 0) {
  15535. let parentPath = FileUtil.getParentPath(this.videoUrl)
  15536. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  15537. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  15538. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  15539. } else if (this.modeType === 1) { //媒体库
  15540. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  15541. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  15542. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  15543. } else if (this.modeType === 2) { //艺术家
  15544. if (this.currentSong?.artist) {
  15545. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  15546. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  15547. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  15548. }
  15549. } else if (this.modeType === 3) { //专辑
  15550. if (this.currentSong?.album) {
  15551. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  15552. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  15553. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  15554. }
  15555. }
  15556. ToastUtil.showShort("保存成功")
  15557. this.isJumpSetting = false
  15558. })
  15559. }
  15560. .margin({
  15561. left: 38,
  15562. right: 38,
  15563. top: 10,
  15564. bottom: 10
  15565. })
  15566. .width(120)
  15567. .height(50)
  15568. }
  15569. }
  15570. }
  15571. .width('100%')
  15572. .height('100%')
  15573. }
  15574. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  15575. private onStateVastChange(state: AVCastPickerState) {
  15576. if (state == AVCastPickerState.STATE_APPEARING) {
  15577. console.log('The picker starts showing.');
  15578. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  15579. console.log('The picker finishes presenting.');
  15580. }
  15581. }
  15582. private showSelectLyric() {
  15583. DialogHelper.showActionSheetDialog({
  15584. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  15585. // sheets: ["本地歌词", "搜索歌词"],
  15586. sheets: [
  15587. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  15588. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  15589. ],
  15590. maskColor: Color.Transparent,
  15591. backgroundColor: $r('app.color.bg_card'),
  15592. transition: AnimationHelper.transitionInDown(666),
  15593. onAction: (index) => {
  15594. switch (index) {
  15595. case 0:
  15596. this.callFilePickerSelectFileForLyric()
  15597. break;
  15598. case 1:
  15599. if (StrUtil.isNotEmpty(this.videoUrl)) {
  15600. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15601. this.initLyric(lyricPath);
  15602. }
  15603. break;
  15604. }
  15605. }
  15606. })
  15607. }
  15608. // 拉起picker选择文件管理器
  15609. async callFilePickerSelectFileForLyric(): Promise<void> {
  15610. try {
  15611. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  15612. DocumentSelectOptions.maxSelectNumber = 1
  15613. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  15614. let documentPicker = new picker.DocumentViewPicker();
  15615. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  15616. Logger.info(TAG,
  15617. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  15618. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  15619. this.saveVideoDatasLyric(DocumentSelectResult)
  15620. }
  15621. }).catch((err: BusinessError) => {
  15622. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  15623. });
  15624. } catch (err) {
  15625. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  15626. }
  15627. }
  15628. async saveVideoDatasLyric(uris: string[]) {
  15629. if (ArrayUtil.isEmpty(uris)) {
  15630. return
  15631. }
  15632. let newUris: string[] = [];
  15633. for (let i = 0; i < uris.length; i++) {
  15634. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  15635. Logger.info(TAG, 'filePath uri: ' + filePath);
  15636. newUris.push(filePath)
  15637. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  15638. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  15639. fileIo.copyFileSync(file.fd, file2.fd)
  15640. fileIo.closeSync(file);
  15641. fileIo.closeSync(file2);
  15642. this.initLyric(filePath,false,false,true)
  15643. }
  15644. }
  15645. private initDelayPlay(context: object) {
  15646. this.mContext = context;
  15647. }
  15648. startPipLyric() {
  15649. if (this.pipController) {
  15650. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15651. PiPWindow.PiPControlStatus.PLAY);
  15652. }
  15653. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  15654. if (this.isOpenPip) {
  15655. this.startPip()
  15656. } else {
  15657. this.stopPip()
  15658. }
  15659. }
  15660. //startOffset 从cue分轨时间开始播
  15661. private startPlayOrResumePlay(startOffset?:number) {
  15662. let finalStartOffset = startOffset
  15663. if ((finalStartOffset === undefined || finalStartOffset === null) && this.currentSong && isCueSplitItem(this.currentSong)) {
  15664. finalStartOffset = 0
  15665. }
  15666. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  15667. //针对dsf文件高采样率,统一转wav播放
  15668. // const sampleRate = this.currentSong?.sampleRate||0
  15669. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  15670. // console.info('onecold 采样率 ='+sampleRate)
  15671. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  15672. // console.info('onecold newDsfPath ='+newDsfPath)
  15673. // if(!FileUtil.accessSync(newDsfPath)){
  15674. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  15675. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  15676. // this.videoUrl = newDsfPath
  15677. // this.startPlay(startOffset)
  15678. // }).catch((e:object)=>{
  15679. // console.info("task1 catch e: " + e);
  15680. // })
  15681. // }else{
  15682. // this.videoUrl = newDsfPath
  15683. // this.startPlay(startOffset)
  15684. // }
  15685. //
  15686. // }else{
  15687. // this.startPlay(startOffset)
  15688. // }
  15689. this.startPlay(finalStartOffset)
  15690. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  15691. // 排除用户拖动进度条的情况
  15692. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  15693. void this.preloadNextSongInternal();
  15694. }
  15695. }
  15696. startPlay(startOffset?:number) {
  15697. this.startPipLyric()
  15698. this.mDestroyPage = false;
  15699. this.animationState = AnimationStatus.Running
  15700. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  15701. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  15702. this.stopProgressTask();
  15703. this.startProgressTask();
  15704. this.clearInitialSeekGuardTimer();
  15705. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  15706. this.remoteRestoreSeekToken++;
  15707. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  15708. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  15709. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  15710. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  15711. this.videoUrl.includes('://');
  15712. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  15713. // 网盘歌曲起播阶段统一显示加载圈,prepared/首帧后再收起
  15714. this.isPlayerLoading = !!isRemoteStreamSong;
  15715. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15716. Logger.info(
  15717. TAG,
  15718. `[remote-play] startPlay type=${this.currentSong.type}, memory=${this.pendingMemorySeekPosition}, ` +
  15719. `waitInitial=${this.waitInitialSeekBeforeStart}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15720. );
  15721. }
  15722. this.play(this.videoUrl.toString(),startOffset);
  15723. }
  15724. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  15725. this.mIjkMediaPlayer.start();
  15726. this.setProgress()
  15727. this.CONTROL_PlayStatus = PlayStatus.PLAY
  15728. }
  15729. this.setIsPlaying(true)
  15730. this.updateSessionPlayState(true)
  15731. this.watchStatus();
  15732. this.updateLastPlayTimeStr(this.videoUrl)
  15733. }
  15734. updateLastPlayTimeStr(filePath: string) {
  15735. const activeSong = this.currentSong;
  15736. let targetFilePath = this.currentSong?.filePath || filePath;
  15737. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15738. const remoteStoragePath = this.resolveRemoteStoragePath(activeSong);
  15739. if (remoteStoragePath) {
  15740. targetFilePath = remoteStoragePath;
  15741. }
  15742. Logger.info(`heanup 检测到网络音频播放,改为更新远程歌曲最近播放: ${targetFilePath}`)
  15743. }
  15744. if (!targetFilePath) {
  15745. Logger.warn(TAG, `更新最近播放时间失败,目标路径为空: ${filePath}`);
  15746. return;
  15747. }
  15748. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  15749. const applyHistoryUpdate = (): void => {
  15750. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (success: boolean, error?: string) => {
  15751. if (success) {
  15752. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15753. this.currentSong.lastPlayedStr = lastPlayTime
  15754. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15755. }
  15756. this.getHistoryList(false)
  15757. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  15758. return;
  15759. }
  15760. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15761. Logger.warn(TAG, `远程歌曲最近播放更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  15762. this.persistRemoteMetadataToDb(activeSong)
  15763. .then(() => {
  15764. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (retrySuccess: boolean,
  15765. retryError?: string) => {
  15766. if (retrySuccess) {
  15767. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15768. this.currentSong.lastPlayedStr = lastPlayTime
  15769. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15770. }
  15771. this.getHistoryList(false)
  15772. Logger.info(TAG, `远程歌曲最近播放补入库后更新成功: ${targetFilePath}`);
  15773. } else {
  15774. Logger.error(TAG,
  15775. `远程歌曲最近播放补入库后仍更新失败: ${targetFilePath}, error=${retryError}`);
  15776. }
  15777. });
  15778. })
  15779. .catch((persistError: Error) => {
  15780. Logger.error(TAG,
  15781. `远程歌曲最近播放补入库失败: ${targetFilePath}, error=${persistError.message}`);
  15782. });
  15783. return;
  15784. }
  15785. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  15786. });
  15787. };
  15788. applyHistoryUpdate();
  15789. }
  15790. private completionNum(num: number): string | number {
  15791. if (num < 10) {
  15792. return '0' + num;
  15793. } else {
  15794. return num;
  15795. }
  15796. }
  15797. private parseDurationToMs(duration?: string): number {
  15798. if (!duration) {
  15799. return 0;
  15800. }
  15801. const parts = duration.split(':').map((item) => Number(item));
  15802. if (parts.some((item) => Number.isNaN(item))) {
  15803. return 0;
  15804. }
  15805. if (parts.length === 2) {
  15806. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  15807. }
  15808. if (parts.length === 3) {
  15809. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  15810. }
  15811. return 0;
  15812. }
  15813. private sanitizePlaybackUrl(url?: string): string {
  15814. if (!url) {
  15815. return '';
  15816. }
  15817. let sanitized = url.replace(/(access_token=)[^&]+/ig, '$1***');
  15818. sanitized = sanitized.replace(/(refresh_token=)[^&]+/ig, '$1***');
  15819. sanitized = sanitized.replace(/(Authorization=)[^&]+/ig, '$1***');
  15820. if (sanitized.length > 220) {
  15821. return `${sanitized.substring(0, 220)}...`;
  15822. }
  15823. return sanitized;
  15824. }
  15825. private sanitizePlaylistDebugPath(path?: string): string {
  15826. if (!path) {
  15827. return '';
  15828. }
  15829. return path.length > 48 ? `...${path.substring(path.length - 48)}` : path;
  15830. }
  15831. private buildSongDebugItem(item?: VideoItem): string {
  15832. if (!item) {
  15833. return 'unknown';
  15834. }
  15835. const title = item.name || item.fileName || '未知歌曲';
  15836. return `${title}|type=${item.type}|acc=${item.webdav_account_id || ''}|path=${this.sanitizePlaylistDebugPath(item.filePath)}`;
  15837. }
  15838. private buildSongListDebugLog(items: VideoItem[], limit: number = 5): string {
  15839. if (!items || items.length === 0) {
  15840. return '[]';
  15841. }
  15842. const parts: string[] = [];
  15843. const maxCount = Math.min(limit, items.length);
  15844. for (let i = 0; i < maxCount; i++) {
  15845. parts.push(this.buildSongDebugItem(items[i]));
  15846. }
  15847. return `[${parts.join('; ')}](${items.length})`;
  15848. }
  15849. private buildPathListDebugLog(paths: string[], limit: number = 5): string {
  15850. if (!paths || paths.length === 0) {
  15851. return '[]';
  15852. }
  15853. const parts: string[] = [];
  15854. const maxCount = Math.min(limit, paths.length);
  15855. for (let i = 0; i < maxCount; i++) {
  15856. parts.push(this.sanitizePlaylistDebugPath(paths[i]));
  15857. }
  15858. return `[${parts.join('; ')}](${paths.length})`;
  15859. }
  15860. private async dispatchPlaylistPlayRequest(playlistData: PlaylistPlayRequest): Promise<void> {
  15861. clearPendingPlaylistPlay();
  15862. Logger.info(
  15863. TAG,
  15864. `[remote-debug] dispatchPlaylistPlayRequest id=${playlistData.playlistId}, name=${playlistData.playlistName}, ` +
  15865. `songCount=${playlistData.songCount}, startIndex=${playlistData.startIndex}, playType=${playlistData.playType ?? -1}, ` +
  15866. `paths=${this.buildPathListDebugLog(playlistData.songFilePaths)}`
  15867. );
  15868. if (playlistData.playType !== undefined) {
  15869. this.applyRequestedPlayType(playlistData.playType);
  15870. }
  15871. await this.handlePlaylistPlayRequest(
  15872. playlistData.playlistId,
  15873. playlistData.playlistName,
  15874. playlistData.songFilePaths,
  15875. playlistData.startIndex,
  15876. playlistData.isJump ?? false,
  15877. playlistData.songCount
  15878. );
  15879. }
  15880. private async resolvePlaybackUrlForCurrentSong(source: string): Promise<string | null> {
  15881. const song = this.currentSong;
  15882. if (!song) {
  15883. Logger.warn(TAG, `[play-url] skip source=${source}, currentSong is null`);
  15884. return null;
  15885. }
  15886. const expectedFilePath = song.filePath || '';
  15887. const requestSerial = ++this.playbackUrlRequestSerial;
  15888. Logger.info(
  15889. TAG,
  15890. `[play-url] begin serial=${requestSerial}, source=${source}, song=${song.name}, path=${expectedFilePath}`
  15891. );
  15892. const resolvedUrl = await setVideoUrlForSong(song, {
  15893. context: this.context,
  15894. autoParseMusicName: this.autoParseMusicName
  15895. });
  15896. const currentFilePath = this.currentSong?.filePath || '';
  15897. if (requestSerial !== this.playbackUrlRequestSerial || currentFilePath !== expectedFilePath) {
  15898. Logger.warn(
  15899. TAG,
  15900. `[play-url] stale serial=${requestSerial}, source=${source}, expected=${expectedFilePath}, ` +
  15901. `current=${currentFilePath}, drop=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15902. );
  15903. return null;
  15904. }
  15905. Logger.info(
  15906. TAG,
  15907. `[play-url] apply serial=${requestSerial}, source=${source}, song=${song.name}, ` +
  15908. `url=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15909. );
  15910. return resolvedUrl;
  15911. }
  15912. private beginSeekTrace(source: string, requestMs: number): void {
  15913. this.lastSeekSource = source;
  15914. this.lastSeekRequestMs = requestMs;
  15915. this.seekTraceUntilTs = Date.now() + this.seekTraceLogWindowMs;
  15916. this.lastSeekTraceLogTs = 0;
  15917. }
  15918. private isSeekTraceActive(): boolean {
  15919. return this.seekTraceUntilTs > 0 && Date.now() <= this.seekTraceUntilTs;
  15920. }
  15921. private logSeekTrace(stage: string, position?: number, playerDuration?: number, force: boolean = false): void {
  15922. if (!force && !this.isSeekTraceActive()) {
  15923. return;
  15924. }
  15925. const now = Date.now();
  15926. if (!force && now - this.lastSeekTraceLogTs < this.seekTraceLogIntervalMs) {
  15927. return;
  15928. }
  15929. this.lastSeekTraceLogTs = now;
  15930. const currentPosition = typeof position === 'number' ? position : this.mIjkMediaPlayer.getCurrentPosition();
  15931. const resolvedPlayerDuration = typeof playerDuration === 'number' ? playerDuration : this.mIjkMediaPlayer.getDuration();
  15932. Logger.info(
  15933. TAG,
  15934. `[seek-trace] stage=${stage}, source=${this.lastSeekSource || 'unknown'}, req=${this.lastSeekRequestMs}, ` +
  15935. `current=${currentPosition}, playerDuration=${resolvedPlayerDuration}, uiDuration=${this.duration}, ` +
  15936. `activeDuration=${this.getActiveDuration()}, isPlaying=${this.mIjkMediaPlayer.isPlaying()}, ` +
  15937. `isSeekTo=${this.isSeekTo}, waitInitial=${this.waitInitialSeekBeforeStart}, ` +
  15938. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15939. );
  15940. }
  15941. private shouldShowSeekBlockedToast(source: string): boolean {
  15942. return source === 'top-progress-slider' ||
  15943. source === 'landscape-progress-slider' ||
  15944. source === 'fast-forward-button' ||
  15945. source === 'rewind-button' ||
  15946. source === 'session-fast-forward' ||
  15947. source === 'session-rewind' ||
  15948. source === 'session-seek';
  15949. }
  15950. private handleBlockedSeek(seekPos: number, source: string): boolean {
  15951. const decision = resolveSeekGuardDecision(this.videoUrl, seekPos);
  15952. if (decision.allow) {
  15953. return false;
  15954. }
  15955. Logger.warn(
  15956. TAG,
  15957. `[seek] blocked source=${source}, target=${seekPos}, reason=${decision.reason}, ` +
  15958. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15959. );
  15960. if (this.shouldShowSeekBlockedToast(source) && StrUtil.isNotEmpty(decision.toastMessage)) {
  15961. ToastUtil.showToast(decision.toastMessage);
  15962. }
  15963. if (this.waitInitialSeekBeforeStart) {
  15964. this.finishInitialSeekWait(`blocked-${decision.reason}`, true);
  15965. } else {
  15966. this.hideLoadIng();
  15967. }
  15968. this.isSeekTo = false;
  15969. this.logSeekTrace(`seek-blocked-${decision.reason}`, undefined, undefined, true);
  15970. return true;
  15971. }
  15972. private stringForTime(timeMs: number): string {
  15973. let totalSeconds: number | string = (timeMs / 1000);
  15974. let newSeconds: number | string = totalSeconds % 60;
  15975. let minutes: number | string = (totalSeconds / 60) % 60;
  15976. let hours: number | string = totalSeconds / 3600;
  15977. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  15978. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  15979. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  15980. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  15981. if (this.isCurrentTime) {
  15982. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  15983. this.oldSeconds = newSeconds
  15984. } else {
  15985. newSeconds = this.oldSeconds
  15986. }
  15987. }
  15988. newSeconds = this.completionNum(newSeconds);
  15989. if (hours > 0) {
  15990. return hours + ":" + minutes + ":" + newSeconds;
  15991. } else {
  15992. return minutes + ":" + newSeconds;
  15993. }
  15994. }
  15995. private getPlayerSwiperDisplayCount(): number {
  15996. return new BreakpointType<number>({
  15997. sm: 1,
  15998. md: 2,
  15999. lg: 2,
  16000. xl: 2,
  16001. xxl: 2
  16002. }).getValue(this.currentBreakpoint) ?? 1
  16003. }
  16004. private shouldUpdateMainLyricPanel(): boolean {
  16005. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  16006. }
  16007. private getActivePlaybackPositionMs(): number {
  16008. if (this.castControllerWrapper && this.isCastPlaying) {
  16009. return this.currentTime2 * 1000
  16010. }
  16011. return this.mIjkMediaPlayer.getCurrentPosition()
  16012. }
  16013. private syncLyricPositionNow(): void {
  16014. const position = this.getActivePlaybackPositionMs()
  16015. if (position < 0) {
  16016. return
  16017. }
  16018. this.updateLyricPosition(position + this.timeOffset * 1000)
  16019. }
  16020. private updateLyricPosition(lyricPosition: number): void {
  16021. if (!this.isAppForeground || !this.isPageVisible) {
  16022. return;
  16023. }
  16024. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  16025. const shouldUpdatePipLyric = this.showPipLyric
  16026. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  16027. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  16028. return
  16029. }
  16030. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  16031. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  16032. return;
  16033. }
  16034. this.lastLyricRenderPosition = lyricPosition;
  16035. if (shouldUpdateMainLyric) {
  16036. this.lyricController.updatePosition(lyricPosition);
  16037. }
  16038. if (shouldUpdatePipLyric) {
  16039. this.lyricControllerXF.updatePosition(lyricPosition);
  16040. }
  16041. if (shouldUpdateSingleLineLyric) {
  16042. this.lyricControllerSingle.updatePosition(lyricPosition);
  16043. }
  16044. }
  16045. private setProgress() {
  16046. if (this.castControllerWrapper && this.isCastPlaying) {
  16047. return;
  16048. }
  16049. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  16050. const rawPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16051. const rawDuration = this.mIjkMediaPlayer.getDuration();
  16052. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  16053. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  16054. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  16055. const cueTrackDuration = cueTrackItem ? getCueTrackDuration(cueTrackItem) : 0;
  16056. let position = rawPosition;
  16057. let duration = rawDuration;
  16058. if (cueTrackItem) {
  16059. position = Math.max(0, rawPosition - cueTrackStartOffset);
  16060. if (cueTrackDuration > 0) {
  16061. duration = cueTrackDuration;
  16062. } else if (cueTrackEndOffset > cueTrackStartOffset) {
  16063. duration = cueTrackEndOffset - cueTrackStartOffset;
  16064. } else if (rawDuration > cueTrackStartOffset) {
  16065. duration = rawDuration - cueTrackStartOffset;
  16066. }
  16067. if (duration > 0 && position > duration) {
  16068. position = duration;
  16069. }
  16070. }
  16071. if (duration <= 0 && this.duration > 0) {
  16072. duration = this.duration;
  16073. }
  16074. let pos = 0;
  16075. if (duration > 0) {
  16076. this.slideEnable = true;
  16077. let curPercent = position / duration;
  16078. pos = curPercent * 100;
  16079. if (shouldRefreshUi) {
  16080. if (pos > this.PROGRESS_MAX_VALUE) {
  16081. this.progressValue = this.PROGRESS_MAX_VALUE
  16082. } else {
  16083. this.progressValue = pos;
  16084. }
  16085. }
  16086. }
  16087. this.logSeekTrace('progress-tick', position, duration);
  16088. // LogUtils.getInstance()
  16089. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  16090. if (shouldRefreshUi) {
  16091. this.totalTime = this.stringForTime(duration);
  16092. }
  16093. if (position > duration) {
  16094. position = duration;
  16095. }
  16096. if (shouldRefreshUi) {
  16097. const lyricPosition = (cueTrackItem ? rawPosition : position) + this.timeOffset * 1000;
  16098. this.isCurrentTime = true;
  16099. this.updateLyricPosition(lyricPosition);
  16100. // 蓝牙歌词更新逻辑
  16101. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  16102. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  16103. // 仅在歌词行变化时更新,避免频繁调用
  16104. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  16105. this.lastBluetoothLyricLine = currentLyricLine;
  16106. this.avSessionController.updateBluetoothLyric(
  16107. currentLyricLine,
  16108. this.currentSong.name || '',
  16109. this.currentSong.artist || '',
  16110. this.bluetoothLyricMode
  16111. );
  16112. }
  16113. }
  16114. this.currentTime = this.stringForTime(position);
  16115. this.isCurrentTime = false
  16116. }
  16117. if (this.mIjkMediaPlayer.isPlaying()) {
  16118. const isCueTrackCompleted = cueTrackItem &&
  16119. cueTrackEndOffset > cueTrackStartOffset &&
  16120. rawPosition >= cueTrackEndOffset;
  16121. //如果是开启AB循环
  16122. if(this.isOpenAB){
  16123. if(position >=this.jumpBTime){
  16124. this.seekTo(this.jumpATime+'')
  16125. return
  16126. }
  16127. }
  16128. // 判断是否播放到结束时间
  16129. if ((this.isOpenJump && duration > this.jumpEndTime * 1000 &&
  16130. position >= duration - this.jumpEndTime * 1000) || isCueTrackCompleted) {
  16131. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  16132. this.CONTROL_PlayStatus = PlayStatus.INIT
  16133. this.startPlayOrResumePlay();
  16134. }else if (this.playType == 2) { //2:正常播放,单片播完
  16135. this.showRePlay();
  16136. this.currentTime = this.stringForTime(duration);
  16137. this.progressValue = this.PROGRESS_MAX_VALUE;
  16138. this.slideEnable = false;
  16139. this.stop();
  16140. // ToastUtil.showToast('开始重新播放')
  16141. }else if (this.playType == 4) { //4:连续播放不循环
  16142. // 检查是否是最后一首
  16143. if (this.curIndex >= this.songList.length - 1) {
  16144. // 已经是最后一首,停止播放
  16145. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  16146. ToastUtil.showToast('已经是最后一首了');
  16147. this.showRePlay();
  16148. this.currentTime = this.stringForTime(duration);
  16149. this.progressValue = this.PROGRESS_MAX_VALUE;
  16150. this.slideEnable = false;
  16151. this.stop();
  16152. } else {
  16153. // 不是最后一首,继续播放下一首
  16154. this.playNext().catch(() => {
  16155. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  16156. });
  16157. }
  16158. }else{
  16159. this.playNext().catch(() => {
  16160. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  16161. });
  16162. }
  16163. }
  16164. }
  16165. }
  16166. private startProgressTask() {
  16167. let that = this;
  16168. if (this.updateProgressTimer) {
  16169. clearInterval(this.updateProgressTimer);
  16170. this.updateProgressTimer = 0;
  16171. }
  16172. this.updateProgressTimer = setInterval(() => {
  16173. //LogUtils.getInstance().LOGI("startProgressTask");
  16174. if (!that.mDestroyPage) {
  16175. that.setProgress();
  16176. }
  16177. }, this.progressUpdateIntervalMs);
  16178. }
  16179. private stopProgressTask() {
  16180. LogUtils.getInstance().LOGI("stopProgressTask");
  16181. clearInterval(this.updateProgressTimer);
  16182. this.updateProgressTimer = 0;
  16183. }
  16184. private showLoadIng() {
  16185. this.isPlayerLoading = true;
  16186. this.loadingVisible = Visibility.Visible;
  16187. this.replayVisible = Visibility.None;
  16188. }
  16189. private hideLoadIng() {
  16190. this.isPlayerLoading = false;
  16191. this.loadingVisible = Visibility.None;
  16192. this.replayVisible = Visibility.None;
  16193. }
  16194. private showRePlay() {
  16195. this.isPlayerLoading = false;
  16196. this.loadingVisible = Visibility.None;
  16197. this.replayVisible = Visibility.Visible;
  16198. }
  16199. private beginRemoteSongSwitchLoading(song?: VideoItem): boolean {
  16200. const shouldShow = !!song && isRemoteCloudType(song.type);
  16201. if (shouldShow) {
  16202. this.showLoadIng();
  16203. }
  16204. return shouldShow;
  16205. }
  16206. private clearInitialSeekGuardTimer(): void {
  16207. if (this.initialSeekGuardTimer) {
  16208. clearTimeout(this.initialSeekGuardTimer);
  16209. this.initialSeekGuardTimer = 0;
  16210. }
  16211. }
  16212. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  16213. try {
  16214. if (!this.mIjkMediaPlayer.isPlaying()) {
  16215. this.mIjkMediaPlayer.start();
  16216. }
  16217. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16218. this.setIsPlaying(true);
  16219. this.updateSessionPlayState(true);
  16220. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  16221. } catch (error) {
  16222. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  16223. }
  16224. }
  16225. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  16226. this.clearInitialSeekGuardTimer();
  16227. const wasWaiting = this.waitInitialSeekBeforeStart;
  16228. this.waitInitialSeekBeforeStart = false;
  16229. this.pendingMemorySeekPosition = 0;
  16230. this.isPlayerLoading = false;
  16231. this.hideLoadIng();
  16232. if (wasWaiting) {
  16233. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  16234. }
  16235. if (shouldStart) {
  16236. this.ensurePlayerStartedAfterInitialSeek(reason);
  16237. }
  16238. }
  16239. private startInitialSeekGuardTimer(scene: string): void {
  16240. this.clearInitialSeekGuardTimer();
  16241. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  16242. return;
  16243. }
  16244. const token = this.remoteRestoreSeekToken;
  16245. this.initialSeekGuardTimer = setTimeout(() => {
  16246. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  16247. return;
  16248. }
  16249. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  16250. this.finishInitialSeekWait('seek-timeout', true);
  16251. }, this.initialSeekGuardTimeoutMs);
  16252. }
  16253. private async play(url: string,startOffset?:number) {
  16254. this.lyricController.setLyric(null)
  16255. this.lyricControllerSingle.setLyric(null)
  16256. this.lastLyricRenderPosition = Number.NaN;
  16257. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  16258. console.info('onecold this.url 1= '+url)
  16259. if(!url.toLowerCase().startsWith('http')){
  16260. let hasPermission = await PermissionUtil.activatePermission(url)
  16261. console.info('onecold this.hasPermission 1= '+hasPermission)
  16262. if(!url.includes(this.packName)){
  16263. const file = fs.openSync(url)
  16264. this.videoUrl = file.path
  16265. url= this.videoUrl
  16266. }
  16267. console.info('onecold this.hasPermission 1= '+hasPermission)
  16268. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  16269. }
  16270. let that = this;
  16271. const isBaiduStreamingPlayback = isBaiduStreamingPlaybackUrl(url);
  16272. if (this.waitInitialSeekBeforeStart) {
  16273. that.showLoadIng();
  16274. } else {
  16275. that.hideLoadIng();
  16276. }
  16277. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  16278. this.isOpenAB = false
  16279. //设置XComponent回调的context
  16280. if (!!this.mContext) {
  16281. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  16282. }
  16283. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  16284. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  16285. try {
  16286. this.mIjkMediaPlayer.reset();
  16287. Logger.info(TAG, 'IjkPlayer reset 成功');
  16288. } catch (error) {
  16289. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  16290. }
  16291. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16292. //设置debug模式(用于EQ日志采集)
  16293. this.mIjkMediaPlayer.setDebug(true);
  16294. //初始化配置
  16295. this.mIjkMediaPlayer.native_setup();
  16296. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  16297. this.applyCurrentVolume(true);
  16298. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  16299. const headers = new Map<string, string>();
  16300. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  16301. headers.set("Accept", "*/*");
  16302. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  16303. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  16304. //如果封面为空,则搜索封面
  16305. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  16306. }
  16307. // 仅对确实需要额外认证头的远程类型补充请求头。
  16308. // Navidrome/Plex/AudioStation/DaoLiYu 等类型的播放链接已自带认证参数,这里不要再误走 WebDAV 认证分支。
  16309. if (this.currentSong
  16310. && (isWebDavType(this.currentSong.type) || isJellyfinType(this.currentSong.type) || isEmbyType(this.currentSong.type))) {
  16311. Logger.info(`heanup 远程歌曲认证头构建 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  16312. if (this.currentSong.webdav_account_id) {
  16313. try {
  16314. const webdavManager = RemoteDriveManager.getInstance();
  16315. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16316. if (webDavHeaders && webDavHeaders.size > 0) {
  16317. webDavHeaders.forEach((value, key) => headers.set(key, value));
  16318. Logger.info(`heanup 成功通过webdav_account_id获取并合并远程认证头`);
  16319. } else {
  16320. Logger.warn(`heanup 通过webdav_account_id未获取到额外认证头`);
  16321. }
  16322. } catch (error) {
  16323. const err = error as Error;
  16324. Logger.error(`heanup 获取远程认证头时出错: ${err.message}`);
  16325. }
  16326. } else {
  16327. Logger.error(`heanup 远程歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法构建认证头`);
  16328. }
  16329. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  16330. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  16331. }
  16332. // 统一设置带认证的请求头
  16333. // 百度类型也需要特殊请求头
  16334. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  16335. try {
  16336. const webdavManager = RemoteDriveManager.getInstance();
  16337. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16338. baiduHeaders.forEach((value, key) => headers.set(key, value));
  16339. const headerSnapshot: Record<string, string> = {};
  16340. headers.forEach((value, key) => headerSnapshot[key] = value);
  16341. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  16342. } catch (error) {
  16343. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  16344. }
  16345. }
  16346. //设置视频源(先准备好认证头,再设置数据源)
  16347. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  16348. this.mIjkMediaPlayer.setDataSource(url);
  16349. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  16350. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  16351. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  16352. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  16353. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  16354. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  16355. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  16356. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  16357. // 缓冲和播放优化设置
  16358. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  16359. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  16360. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  16361. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  16362. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  16363. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  16364. // 网络相关设置
  16365. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  16366. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  16367. // 重连设置
  16368. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  16369. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  16370. } else if ((this.currentSong && isBaiduType(this.currentSong.type)) || isBaiduStreamingPlayback) {
  16371. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  16372. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  16373. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  16374. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  16375. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  16376. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  16377. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  16378. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  16379. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  16380. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  16381. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  16382. }
  16383. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  16384. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  16385. // }
  16386. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  16387. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  16388. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  16389. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  16390. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  16391. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  16392. //停止预读的最小帧数
  16393. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  16394. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  16395. // 设置其他缓冲相关选项
  16396. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  16397. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  16398. //启动预加载
  16399. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  16400. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  16401. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  16402. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  16403. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  16404. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  16405. // 因此需要播放器丢包,才不会累积延时
  16406. // 这个和第三个参数packet-buffering无关。
  16407. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  16408. // 无限制收流
  16409. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  16410. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  16411. // 屏幕常亮
  16412. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  16413. // 开启hls起播优化 默认是关闭的
  16414. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  16415. // 设置超时
  16416. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  16417. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  16418. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  16419. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  16420. // 变速播放
  16421. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  16422. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  16423. let Speed = this.mIjkMediaPlayer.getSpeed()
  16424. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  16425. //是否开启循环播放
  16426. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  16427. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  16428. (width: number, height: number, sar_num: number, sar_den: number) => {
  16429. if (height === 0) {
  16430. return;
  16431. }
  16432. const va = width / height;
  16433. const vpa = that.videoParentAspectRatio;
  16434. if (vpa > va) {
  16435. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  16436. } else {
  16437. that.videoWidth = '100%';
  16438. }
  16439. if (width && height) {
  16440. that.videoAspectRatio = width / height;
  16441. }
  16442. LogUtils.getInstance()
  16443. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  16444. if (!that.waitInitialSeekBeforeStart) {
  16445. that.hideLoadIng();
  16446. }
  16447. }
  16448. );
  16449. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  16450. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  16451. async () => {
  16452. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  16453. Logger.info(
  16454. TAG,
  16455. `[seek] prepared enter, waitInitial=${this.waitInitialSeekBeforeStart}, pendingMemory=${this.pendingMemorySeekPosition}, ` +
  16456. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16457. );
  16458. if (!this.waitInitialSeekBeforeStart) {
  16459. // 无记忆seek时,prepared后可直接隐藏加载
  16460. this.isPlayerLoading = false;
  16461. }
  16462. try {
  16463. //保存碰一碰分享的当前的歌曲
  16464. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  16465. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  16466. await this.initLyric(lyricPath);
  16467. const applyDuration = (durationMs: number): void => {
  16468. const cueTrackDuration = this.currentSong && isCueSplitItem(this.currentSong)
  16469. ? getCueTrackDuration(this.currentSong)
  16470. : 0;
  16471. const effectiveDuration = cueTrackDuration > 0 ? cueTrackDuration : durationMs;
  16472. if (effectiveDuration <= 0) {
  16473. return;
  16474. }
  16475. this.duration = effectiveDuration;
  16476. this.durationTime = Math.floor(effectiveDuration / 1000);
  16477. this.durationStringTime = secondToTime(this.durationTime);
  16478. this.totalTime = this.stringForTime(effectiveDuration);
  16479. if (this.currentSong) {
  16480. this.currentSong.duration = this.totalTime;
  16481. try {
  16482. this.avSessionController.setAVMetadataMusic(this.currentSong, effectiveDuration, this.lyricContent);
  16483. } catch (metaError) {
  16484. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  16485. }
  16486. }
  16487. };
  16488. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  16489. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  16490. return 0;
  16491. }
  16492. const httpRequest = http.createHttp();
  16493. try {
  16494. const response = await httpRequest.request(url, {
  16495. method: http.RequestMethod.GET,
  16496. connectTimeout: 8000,
  16497. readTimeout: 8000,
  16498. expectDataType: http.HttpDataType.STRING,
  16499. header: {
  16500. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  16501. 'Host': 'pan.baidu.com',
  16502. 'Referer': 'https://pan.baidu.com/disk/home',
  16503. 'Accept-Encoding': 'identity'
  16504. }
  16505. });
  16506. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  16507. return 0;
  16508. }
  16509. const text = response.result;
  16510. if (text.indexOf('#EXTM3U') < 0) {
  16511. return 0;
  16512. }
  16513. const lines = text.split('\n');
  16514. let totalSeconds = 0;
  16515. for (let i = 0; i < lines.length; i++) {
  16516. const line = lines[i].trim();
  16517. if (line.startsWith('#EXTINF:')) {
  16518. const colonIndex = line.indexOf(':');
  16519. if (colonIndex < 0) {
  16520. continue;
  16521. }
  16522. const content = line.substring(colonIndex + 1);
  16523. const commaIndex = content.indexOf(',');
  16524. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  16525. const seconds = Number(numberPart);
  16526. if (!Number.isNaN(seconds) && seconds > 0) {
  16527. totalSeconds += seconds;
  16528. }
  16529. }
  16530. }
  16531. if (totalSeconds > 0) {
  16532. return Math.floor(totalSeconds * 1000);
  16533. }
  16534. return 0;
  16535. } catch (fetchError) {
  16536. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  16537. return 0;
  16538. } finally {
  16539. httpRequest.destroy();
  16540. }
  16541. };
  16542. const fetchDurationFallback = async (): Promise<void> => {
  16543. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16544. if (durationMs > 0) {
  16545. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  16546. applyDuration(durationMs);
  16547. return;
  16548. }
  16549. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  16550. };
  16551. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  16552. Logger.info(
  16553. TAG,
  16554. `[seek] prepared duration snapshot, playerDuration=${preparedDuration}, metaDuration=${this.currentSong?.duration ?? ''}, ` +
  16555. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16556. );
  16557. if (preparedDuration > 0) {
  16558. applyDuration(preparedDuration);
  16559. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  16560. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16561. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  16562. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  16563. applyDuration(durationMs);
  16564. }
  16565. }
  16566. } else {
  16567. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  16568. if (metaDurationMs > 0) {
  16569. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  16570. applyDuration(metaDurationMs);
  16571. } else {
  16572. fetchDurationFallback();
  16573. }
  16574. }
  16575. setTimeout(() => {
  16576. this.avSessionController.initAvSession(false);
  16577. if (this.duration > 0) {
  16578. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  16579. }
  16580. this.setAvSessionListener();
  16581. this.updateSessionPlayState(true)
  16582. this.setCurrentPlayMode()
  16583. const cueTrackStartOffset = this.currentSong && isCueSplitItem(this.currentSong)
  16584. ? getCueTrackStartOffset(this.currentSong)
  16585. : 0;
  16586. if ((startOffset && startOffset > 0) || cueTrackStartOffset > 0) {//cue分轨播放
  16587. const cueSeekValue = cueTrackStartOffset > 0 && (!startOffset || startOffset <= 0) ? 0 : startOffset;
  16588. this.seekTo((cueSeekValue || 0) + "");
  16589. this.saveLastPlayList()
  16590. return
  16591. }
  16592. }, 500)
  16593. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16594. let timeoutPlay = 0
  16595. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16596. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  16597. timeoutPlay = 400
  16598. }
  16599. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  16600. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  16601. timeoutPlay = Math.max(timeoutPlay,
  16602. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  16603. }
  16604. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  16605. if (this.modeType === 0) { //文件夹
  16606. let parentPath = FileUtil.getParentPath(this.videoUrl)
  16607. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  16608. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  16609. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  16610. } else if (this.modeType === 1) { //媒体库
  16611. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  16612. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  16613. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  16614. } else if (this.modeType === 2) { //艺术家
  16615. if (this.currentSong?.artist) {
  16616. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  16617. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  16618. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  16619. }
  16620. } else if (this.modeType === 3) { //专辑
  16621. if (this.currentSong?.album) {
  16622. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  16623. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  16624. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  16625. }
  16626. }
  16627. const playerDuration = this.mIjkMediaPlayer.getDuration()
  16628. if (playerDuration > 0 && (!this.currentSong || !isCueSplitItem(this.currentSong))) {
  16629. this.duration = playerDuration
  16630. }
  16631. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  16632. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  16633. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  16634. let targetSeekPosition = memoryPosition;
  16635. if (this.isOpenJump) {
  16636. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  16637. }
  16638. this.pendingMemorySeekPosition = targetSeekPosition;
  16639. this.startInitialSeekGuardTimer('prepared-memory-seek');
  16640. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  16641. setTimeout(() => {
  16642. if (!this.waitInitialSeekBeforeStart) {
  16643. return;
  16644. }
  16645. this.restorePlaybackPosition();
  16646. }, timeoutPlay);
  16647. this.isFirstStartPlay = false
  16648. this.saveLastPlayList()
  16649. return
  16650. }
  16651. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  16652. if (this.mIjkMediaPlayer != null) {
  16653. let jumpTopTimeMs = this.jumpTopTime*1000;
  16654. if (jumpTopTimeMs <= this.duration) {
  16655. // 调用 seekTo 方法,跳到指定时间
  16656. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16657. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16658. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  16659. }
  16660. }, timeoutPlay)
  16661. } else {
  16662. // 提示用户无法跳过
  16663. ToastUtil.showToast('跳过时间超过视频时长');
  16664. }
  16665. }
  16666. } else {
  16667. this.jumpTopTime = 0
  16668. this.jumpEndTime = 0
  16669. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  16670. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  16671. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  16672. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  16673. //记忆播放(每一首都会记忆播放)
  16674. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16675. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16676. if (this.pendingMemorySeekPosition > 0 ||
  16677. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  16678. this.restorePlaybackPosition() //读取播放记忆功能
  16679. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  16680. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  16681. this.restorePlaybackPosition() //读取播放记忆功能
  16682. }
  16683. this.isFirstStartPlay = false
  16684. }, timeoutPlay)
  16685. } else {
  16686. this.isFirstStartPlay = false
  16687. }
  16688. }
  16689. this.saveLastPlayList()
  16690. } catch (error) {
  16691. let err: BusinessError = error as BusinessError;
  16692. console.error('onecold failed with err: ' + JSON.stringify(err));
  16693. if (this.waitInitialSeekBeforeStart) {
  16694. this.finishInitialSeekWait('prepared-exception', true);
  16695. }
  16696. }
  16697. }
  16698. );
  16699. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  16700. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  16701. (text: string) => {
  16702. }
  16703. );
  16704. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  16705. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  16706. () => {
  16707. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  16708. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  16709. // 异步调用playNext
  16710. this.playNext().catch(() => {
  16711. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16712. });
  16713. } else if (this.playType == 1) { //1:单片重复播放
  16714. this.CONTROL_PlayStatus = PlayStatus.INIT
  16715. that.startPlayOrResumePlay();
  16716. } else if (this.playType == 2) { //2:正常播放,单曲播完
  16717. that.showRePlay();
  16718. that.currentTime = that.stringForTime(that.getActiveDuration());
  16719. that.progressValue = this.PROGRESS_MAX_VALUE;
  16720. that.slideEnable = false;
  16721. that.stop();
  16722. // ToastUtil.showToast('开始重新播放')
  16723. } else if (this.playType == 3) { //3:随机播放
  16724. // 异步调用randomPlay
  16725. this.randomPlay().catch(() => {
  16726. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  16727. });
  16728. } else if (this.playType == 4) { //4:连续播放不循环
  16729. // 异步调用playNext
  16730. this.playNext().catch(() => {
  16731. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16732. });
  16733. }
  16734. }
  16735. );
  16736. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  16737. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  16738. (percent: number) => {
  16739. if (this.isDebug) {
  16740. const now = Date.now();
  16741. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  16742. this.lastBufferingLogTs = now;
  16743. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  16744. }
  16745. }
  16746. }
  16747. );
  16748. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  16749. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  16750. () => {
  16751. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  16752. that.logSeekTrace('seek-complete', undefined, undefined, true);
  16753. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  16754. setTimeout(() => {
  16755. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  16756. that.isSeekTo = false;
  16757. if (waitingInitialSeek) {
  16758. that.finishInitialSeekWait('seek-complete', true);
  16759. } else {
  16760. that.hideLoadIng();
  16761. }
  16762. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  16763. }
  16764. );
  16765. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  16766. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  16767. (what: number, extra: number) => {
  16768. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  16769. if (that.isSeekTraceActive()) {
  16770. Logger.info(
  16771. TAG,
  16772. `[seek] onInfo what=${what}, extra=${extra}, source=${that.lastSeekSource || 'unknown'}, ` +
  16773. `req=${that.lastSeekRequestMs}, url=${that.sanitizePlaybackUrl(that.videoUrl)}`
  16774. );
  16775. that.logSeekTrace(`info-${what}`, undefined, undefined, true);
  16776. }
  16777. if (!that.waitInitialSeekBeforeStart) {
  16778. that.hideLoadIng();
  16779. }
  16780. }
  16781. );
  16782. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  16783. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  16784. (what: number, extra: number) => {
  16785. this.finishInitialSeekWait('player-error', false);
  16786. this.stopProgressTask();
  16787. this.logSeekTrace(`error-${what}-${extra}`, undefined, undefined, true);
  16788. Logger.error(
  16789. TAG,
  16790. `[seek] onError what=${what}, extra=${extra}, url=${this.sanitizePlaybackUrl(this.videoUrl)}, ` +
  16791. `song=${JSON.stringify(this.currentSong)}`
  16792. );
  16793. // 检查是否为WebDAV播放错误
  16794. let isWebDavError = false;
  16795. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  16796. try {
  16797. const globalContext = GlobalContext.getContext();
  16798. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  16799. if (webDavAuthInfo) {
  16800. isWebDavError = true;
  16801. }
  16802. } catch (error) {
  16803. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  16804. }
  16805. }
  16806. if (isWebDavError) {
  16807. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  16808. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  16809. // this.currentWebDavAuthInfo = null;
  16810. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  16811. // 根据错误代码提供更具体的错误信息
  16812. let errorMessage = "WebDAV播放失败";
  16813. if (what === -1) { // 网络错误
  16814. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  16815. } else if (what === -1004) { // HTTP 404
  16816. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  16817. } else if (what === -1001) { // 超时
  16818. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  16819. } else if (what === -1003) { // 无法解析主机
  16820. errorMessage = "无法连接到WebDAV服务器";
  16821. }
  16822. ToastUtil.showToast(errorMessage);
  16823. } else {
  16824. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16825. !this.videoUrl.startsWith('http') &&
  16826. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  16827. !FileUtil.accessSync(this.videoUrl)) {
  16828. console.info('heanup 播放.文件不存在');
  16829. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  16830. }
  16831. }
  16832. that.hideLoadIng();
  16833. }
  16834. );
  16835. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  16836. this.mIjkMediaPlayer.setMessageListener();
  16837. // 应用均衡器设置
  16838. try {
  16839. const equalizerManager = EqualizerManager.getInstance();
  16840. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  16841. Logger.info(TAG, 'heanup 均衡器设置已应用');
  16842. this.markEqualizerApplied();
  16843. } catch (eqError) {
  16844. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  16845. this.eqApplying = false;
  16846. }
  16847. this.mIjkMediaPlayer.prepareAsync();
  16848. this.mIjkMediaPlayer.start();
  16849. }
  16850. //保存最后播放的那首歌和已经对应的播放列表
  16851. saveLastPlayList() {
  16852. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  16853. // 新队列刚刚完成落盘时,首帧 prepared 会立刻再进一次这里,跳过这次重复写入即可。
  16854. if (this.skipNextPlaylistPersist) {
  16855. this.skipNextPlaylistPersist = false
  16856. } else {
  16857. PreferencesUtil.putSync('LastMusicList', this.songList)
  16858. }
  16859. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  16860. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  16861. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  16862. }
  16863. // 清空播放记录
  16864. clearVideoHistory() {
  16865. this.table.clearPlayHistory((success: boolean, error?: string) => {
  16866. if (success) {
  16867. this.historyList = [];
  16868. this.updateListData(this.historyList)
  16869. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  16870. ToastUtil.showToast('清空播放记录成功')
  16871. } else {
  16872. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  16873. }
  16874. });
  16875. }
  16876. public async setAvSessionListener() {
  16877. if (!this.avSessionController) {
  16878. return;
  16879. }
  16880. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  16881. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  16882. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  16883. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  16884. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  16885. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  16886. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  16887. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  16888. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  16889. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  16890. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  16891. }
  16892. setLoopMode() {
  16893. let itype = this.playType + 1
  16894. if (itype >= 5) {
  16895. this.playType = 0
  16896. ToastUtil.showToast('连续循环播放')
  16897. } else if (itype === 1) {
  16898. this.playType = 1
  16899. ToastUtil.showToast('单曲循环')
  16900. } else if (itype === 2) {
  16901. this.playType = 2
  16902. ToastUtil.showToast('单曲播完')
  16903. } else if (itype === 3) {
  16904. this.playType = 3
  16905. ToastUtil.showToast('随机播放')
  16906. } else if (itype === 4) {
  16907. this.playType = 4
  16908. ToastUtil.showToast('连续播放不循环')
  16909. } else if (itype === 0) {
  16910. this.playType = 0
  16911. ToastUtil.showToast('连续循环播放')
  16912. }
  16913. PreferencesUtil.putSync('musicPlayType', this.playType)
  16914. this.setCurrentPlayMode()
  16915. }
  16916. private sessionSetLoopModeCallback = (mode: number) => {
  16917. if (this.mIjkMediaPlayer != null) {
  16918. ToastUtil.showToast('当前播放模式:' + mode)
  16919. Logger.info('onecold 当前播放模式= ' + mode)
  16920. let hmPlayMode = mode + 1
  16921. if (hmPlayMode >= 4) {
  16922. hmPlayMode = 0
  16923. }
  16924. if (hmPlayMode === 1) {
  16925. this.playType = 1
  16926. ToastUtil.showToast('单曲循环')
  16927. } else if (hmPlayMode === 0) {
  16928. this.playType = 2
  16929. ToastUtil.showToast('单曲播完')
  16930. } else if (hmPlayMode === 3) {
  16931. this.playType = 3
  16932. ToastUtil.showToast('随机播放')
  16933. } else if (hmPlayMode === 2) {
  16934. this.playType = 0
  16935. ToastUtil.showToast('连续循环播放')
  16936. } else if (hmPlayMode === 4) {
  16937. this.playType = 4
  16938. ToastUtil.showToast('连续播放不循环')
  16939. }
  16940. PreferencesUtil.putSync('musicPlayType', this.playType)
  16941. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  16942. let playBackState: avSession.AVPlaybackState = {
  16943. loopMode: hmPlayMode,
  16944. };
  16945. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  16946. console.info(`set setLoopMode AVPlaybackState successfully`);
  16947. }).catch((err: BusinessError) => {
  16948. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16949. });
  16950. }
  16951. }
  16952. setCurrentPlayMode() {
  16953. if (!this.avSessionController) {
  16954. return;
  16955. }
  16956. let mLoopMode = 0
  16957. switch (this.playType) {
  16958. case 0:
  16959. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  16960. break;
  16961. case 1:
  16962. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  16963. break;
  16964. case 2:
  16965. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  16966. break;
  16967. case 3:
  16968. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  16969. break;
  16970. case 4:
  16971. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  16972. break;
  16973. }
  16974. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  16975. let playBState: avSession.AVPlaybackState = {
  16976. loopMode: mLoopMode,
  16977. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  16978. };
  16979. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  16980. console.info(`set setLoopMode AVPlaybackState successfully`);
  16981. }).catch((err: BusinessError) => {
  16982. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16983. });
  16984. }
  16985. private applyRequestedPlayType(playType: number): void {
  16986. if (playType < 0 || playType > 4 || this.playType === playType) {
  16987. return
  16988. }
  16989. this.playType = playType
  16990. PreferencesUtil.putSync('musicPlayType', this.playType)
  16991. this.setCurrentPlayMode()
  16992. }
  16993. private sessionToggleFavoriteCallback = (assetId: string) => {
  16994. if (this.mIjkMediaPlayer != null && this.currentSong) {
  16995. console.info(`on toggleFavorite `);
  16996. // 应用收到收藏命令,进行收藏处理。
  16997. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  16998. this.doFav(this.currentSong)
  16999. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  17000. let playbackState: avSession.AVPlaybackState = {
  17001. isFavorite: !this.isFac,
  17002. };
  17003. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  17004. console.info(`SetAVPlaybackState successfully`);
  17005. }).catch((err: BusinessError) => {
  17006. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  17007. });
  17008. }
  17009. }
  17010. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  17011. device: avSession.OutputDeviceInfo) => {
  17012. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  17013. // 将 connectState 转换为可读的字符串
  17014. let stateName = 'UNKNOWN';
  17015. switch (connectState) {
  17016. case avSession.ConnectionState.STATE_CONNECTED:
  17017. stateName = 'CONNECTED(1)';
  17018. break;
  17019. case avSession.ConnectionState.STATE_DISCONNECTED:
  17020. stateName = 'DISCONNECTED(2)';
  17021. break;
  17022. case avSession.ConnectionState.STATE_CONNECTING:
  17023. stateName = 'CONNECTING(3)';
  17024. break;
  17025. default:
  17026. stateName = `OTHER(${connectState})`;
  17027. }
  17028. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  17029. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  17030. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  17031. await this.startCasting();
  17032. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  17033. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  17034. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  17035. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  17036. if (device) {
  17037. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  17038. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  17039. this.endCasting();
  17040. }
  17041. }
  17042. };
  17043. private async startCasting() {
  17044. try {
  17045. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  17046. // 获取原始的 AVCastController
  17047. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  17048. if (!avCastCtrl) {
  17049. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  17050. return;
  17051. }
  17052. this.castController = avCastCtrl;
  17053. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  17054. // 创建新的 CastController 封装器
  17055. this.castControllerWrapper = new CastController(avCastCtrl);
  17056. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  17057. // 设置回调函数
  17058. let callbacks: CastControllerCallbacks = {
  17059. onPlayNext: () => {
  17060. Logger.info('heanup CastController', '收到 playNext 回调');
  17061. this.playNext();
  17062. },
  17063. onPlayPrevious: () => {
  17064. Logger.info('heanup CastController', '收到 playPrevious 回调');
  17065. this.playPrevious();
  17066. },
  17067. onPositionChanged: (position: number) => {
  17068. this.positionChange(position);
  17069. },
  17070. onDurationChanged: (duration: number) => {
  17071. this.playDurationChange(duration);
  17072. }
  17073. };
  17074. this.castControllerWrapper.setCallbacks(callbacks);
  17075. Logger.info('heanup startCasting', '✅ 设置回调成功');
  17076. // 暂停本地播放
  17077. this.pause();
  17078. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  17079. // 初始化投播会话
  17080. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  17081. await this.castControllerWrapper.initAVCast(
  17082. this.songList,
  17083. this.curIndex,
  17084. this.mIjkMediaPlayer.getCurrentPosition(),
  17085. this.videoUrl,
  17086. this.getActiveDuration()
  17087. );
  17088. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  17089. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  17090. refToIsCasting?.set(true);
  17091. this.castSeek = true;
  17092. // 从 CastController 获取投播状态
  17093. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17094. if (this.isCastPlaying) {
  17095. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  17096. this.setIsPlaying(true);
  17097. this.updateSessionPlayState(true);
  17098. }
  17099. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  17100. } catch (error) {
  17101. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  17102. }
  17103. }
  17104. async changeCasting() {
  17105. Logger.info('heanup changeCasting', '切换投播');
  17106. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  17107. this.initQueueItem();
  17108. await this.prepare();
  17109. this.setPlaybackStateChangeListener();
  17110. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  17111. this.castSeek = true;
  17112. }
  17113. public endCasting() {
  17114. Logger.info('heanup endCasting', 'endCasting被调用');
  17115. this.avSessionController.getAvSession()?.stopCasting();
  17116. this.stopCast();
  17117. // 关闭文件描述符
  17118. if (this.castFile) {
  17119. try {
  17120. fs.closeSync(this.castFile);
  17121. this.castFile = undefined;
  17122. Logger.info('heanup endCasting', '关闭投播文件描述符');
  17123. } catch (error) {
  17124. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  17125. }
  17126. }
  17127. this.isCastPlaying = false;
  17128. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  17129. refToIsCasting?.set(false);
  17130. this.pause();
  17131. this.setIsPlaying(false);
  17132. // if (this.curIndex === this.curSource.index) {
  17133. // this.play
  17134. // this.seek(this.currentTime * 1000);
  17135. // this.setIsPlaying(true);
  17136. // } else {
  17137. // this.pauseVideo();
  17138. // this.setIsPlaying(false);
  17139. // }
  17140. }
  17141. public setIsPlaying(isPlayer: boolean) {
  17142. this.isPlaying = isPlayer;
  17143. // 发送播放状态变化事件给歌单详情页面
  17144. try {
  17145. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  17146. const currentFilePath = this.currentSong?.filePath || ''
  17147. const eventData: emitter.EventData = {
  17148. data: {
  17149. isPlaying: this.isPlaying,
  17150. curIndex: this.curIndex,
  17151. currentFilePath: currentFilePath
  17152. }
  17153. };
  17154. emitter.emit(eventPlaybackStatus, eventData)
  17155. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  17156. } catch (error) {
  17157. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  17158. }
  17159. }
  17160. private setPlaybackStateChangeListener(): void {
  17161. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  17162. // 我们需要通过其他方式来判断播放状态
  17163. // 1. 监听位置变化
  17164. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  17165. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  17166. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  17167. this.positionChange(playbackState.position.elapsedTime);
  17168. }
  17169. });
  17170. // 2. 监听时长变化
  17171. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  17172. const duration = playbackState?.extras?.duration;
  17173. if (typeof duration === 'number') {
  17174. this.playDurationChange(duration);
  17175. }
  17176. });
  17177. // 3. 监听所有状态变化(用于调试和状态判断)
  17178. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  17179. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  17180. // 检查是否有 state 字段(某些设备可能返回)
  17181. if (playbackState.state !== undefined) {
  17182. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  17183. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  17184. this.isCastPlaying = true;
  17185. }
  17186. }
  17187. });
  17188. // 4. 监听播放完成事件
  17189. this.castController?.on('endOfStream', this.playNextCallback);
  17190. this.castController?.on('playNext', this.playNextCallback);
  17191. this.castController?.on('playPrevious', this.playPreviousCallback);
  17192. // 5. 监听错误事件
  17193. this.castController?.on('error', (error: BusinessError) => {
  17194. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  17195. this.isCastPlaying = false;
  17196. });
  17197. }
  17198. private updateSessionPlayState(isPlay: boolean): void {
  17199. // if(!this.isBgPlayOpen)
  17200. // return
  17201. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  17202. : this.mIjkMediaPlayer.getCurrentPosition();
  17203. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  17204. this.setAVSessionPlayState({
  17205. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  17206. position: {
  17207. elapsedTime: elapsedTime,
  17208. updateTime: new Date().getTime()
  17209. }
  17210. });
  17211. }
  17212. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  17213. this.avSessionController.setAvSessionPlayState(playbackState)
  17214. }
  17215. private positionChange(position: number) {
  17216. this.currentTime2 = position / 1000;
  17217. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  17218. if (this.castControllerWrapper && this.isCastPlaying) {
  17219. this.updateCastProgress(position);
  17220. if (this.isSeekTo) {
  17221. this.isSeekTo = false;
  17222. }
  17223. }
  17224. }
  17225. private playDurationChange(duration: number) {
  17226. this.duration = duration;
  17227. this.durationTime = Math.floor(this.duration / 1000);
  17228. this.durationStringTime = secondToTime((this.durationTime));
  17229. if (this.castControllerWrapper && this.isCastPlaying) {
  17230. this.totalTime = this.stringForTime(this.duration);
  17231. }
  17232. }
  17233. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  17234. private reloadCasting = async () => {
  17235. Logger.info('heanup reloadCasting', '重新加载投播');
  17236. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  17237. this.initQueueItem();
  17238. await this.prepare();
  17239. };
  17240. public playNextCallback = (): void => {
  17241. this.playNext().catch(() => {
  17242. Logger.error('heanup playNextCallback', `播放下一首失败`);
  17243. });
  17244. };
  17245. public playPreviousCallback = (): void => {
  17246. this.playPrevious().catch(() => {
  17247. Logger.error('heanup playNextCallback', `播放上一首失败`);
  17248. });
  17249. };
  17250. async prepare() {
  17251. try {
  17252. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  17253. await this.castController?.prepare(this.castItem);
  17254. Logger.info('heanup prepare', '投播prepare成功');
  17255. await this.castController?.start(this.castItem);
  17256. Logger.info('heanup prepare', '投播start成功');
  17257. // 投播启动成功,设置为投播状态
  17258. this.isCastPlaying = true;
  17259. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  17260. } catch (error) {
  17261. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  17262. this.isCastPlaying = false;
  17263. }
  17264. }
  17265. public initQueueItem() {
  17266. let item = this.songList[this.curIndex];
  17267. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  17268. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  17269. let isStreaming = this.isUrl(this.videoUrl);
  17270. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  17271. // 关闭之前的文件描述符
  17272. if (this.castFile) {
  17273. try {
  17274. fs.closeSync(this.castFile);
  17275. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  17276. } catch (error) {
  17277. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  17278. }
  17279. }
  17280. let description: avSession.AVMediaDescription = {
  17281. assetId: 'AUDIO-' + item.filePath,
  17282. title: item.name,
  17283. artist: item.artist || '',
  17284. // 该字段大写,音频'AUDIO',视频'VIDEO'
  17285. mediaType: 'AUDIO',
  17286. mediaSize: item.videoSize,
  17287. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  17288. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  17289. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  17290. duration: this.duration,
  17291. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  17292. appName: this.appName,
  17293. lyricContent: item.lyricContent,
  17294. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  17295. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  17296. };
  17297. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  17298. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  17299. if (isStreaming) {
  17300. // 流媒体地址使用 mediaUri
  17301. description.mediaUri = this.videoUrl;
  17302. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  17303. } else {
  17304. // 本地文件使用 fdSrc
  17305. const localPath = this.videoUrl || item.filePath;
  17306. let uri = fileUri.getUriFromPath(localPath);
  17307. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  17308. let fdSrc: media.AVFileDescriptor = {
  17309. fd: this.castFile.fd
  17310. };
  17311. description.fdSrc = fdSrc;
  17312. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  17313. }
  17314. this.castItem = {
  17315. itemId: this.curIndex,
  17316. description: description
  17317. };
  17318. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  17319. title: description.title,
  17320. mediaType: description.mediaType,
  17321. hasMediaUri: !!description.mediaUri,
  17322. hasFdSrc: !!description.fdSrc,
  17323. duration: description.duration
  17324. })}`);
  17325. }
  17326. // 判断是否是 URL 或流媒体地址
  17327. private isUrl(str: string): boolean {
  17328. if (!str) {
  17329. return false;
  17330. }
  17331. // 检查常见的流媒体协议
  17332. if (str.startsWith('http://') || str.startsWith('https://') ||
  17333. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  17334. str.startsWith('rtp://') || str.startsWith('mms://')) {
  17335. return true;
  17336. }
  17337. // 扩展的URL正则表达式,支持多种协议
  17338. const urlPattern = new RegExp(
  17339. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  17340. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  17341. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  17342. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  17343. 'localhost)' + // 或localhost
  17344. '(\\:\\d+)?' + // 端口号(可选)
  17345. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  17346. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  17347. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  17348. 'i' // 不区分大小写
  17349. );
  17350. return urlPattern.test(str);
  17351. }
  17352. async stopCast() {
  17353. try {
  17354. // 使用 CastController 释放资源
  17355. if (this.castControllerWrapper) {
  17356. await this.castControllerWrapper.releaseAVCast();
  17357. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  17358. }
  17359. // 清空引用
  17360. this.castControllerWrapper = undefined;
  17361. this.castController = undefined;
  17362. this.castItem = undefined;
  17363. this.castFile = undefined;
  17364. } catch (error) {
  17365. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  17366. }
  17367. }
  17368. private sessionPlayCallback = (): void => {
  17369. this.playOrPause()
  17370. };
  17371. private sessionPauseCallback = (): void => {
  17372. this.pause()
  17373. };
  17374. private async playOrPause() {
  17375. if (!this.debounce()) {
  17376. return;
  17377. }
  17378. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17379. await this.pause();
  17380. } else {
  17381. // 如果是投播模式,使用 CastController 的 play 方法
  17382. if (this.castControllerWrapper && this.isCastPlaying) {
  17383. try {
  17384. Logger.info('heanup playOrPause', '投播模式播放');
  17385. await this.castControllerWrapper.setPlaying();
  17386. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  17387. this.setIsPlaying(true);
  17388. this.updateSessionPlayState(true);
  17389. Logger.info('heanup playOrPause', '投播播放成功');
  17390. this.playChange();
  17391. } catch (error) {
  17392. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  17393. }
  17394. } else {
  17395. console.info('onecold startPlayOrResumePlay 11064')
  17396. this.startPlayOrResumePlay();
  17397. this.playChange()
  17398. }
  17399. }
  17400. }
  17401. private sessionPlayNextCallback = (): void => {
  17402. this.playNext().catch(() => {
  17403. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  17404. });
  17405. };
  17406. private sessionPlayPreviousCallback = (): void => {
  17407. this.playPrevious().catch(() => {
  17408. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  17409. });
  17410. };
  17411. private sessionStopCallback = (): void => {
  17412. this.stop()
  17413. };
  17414. private sessionFastForwardCallback = async (time?: number) => {
  17415. if (!time) {
  17416. return;
  17417. }
  17418. let curPosition: number;
  17419. if (this.castController && this.isCastPlaying) {
  17420. // 投播模式,使用UI显示的时间
  17421. curPosition = this.currentTime2 * 1000;
  17422. } else if (this.mIjkMediaPlayer != null) {
  17423. // 本地播放器模式
  17424. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17425. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17426. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17427. }
  17428. } else {
  17429. return;
  17430. }
  17431. let seeTime = curPosition + time * 1000;
  17432. // 限制 seekValue 在合法范围内
  17433. if (seeTime < 0) {
  17434. seeTime = 0;
  17435. } else if (seeTime > this.duration) {
  17436. seeTime = this.duration;
  17437. }
  17438. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  17439. this.setSeekToActionProgress(seeTime);
  17440. await this.seekTo(seeTime + "", 'session-fast-forward');
  17441. };
  17442. private getActiveDuration(): number {
  17443. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17444. const cueDuration = getCueTrackDuration(this.currentSong);
  17445. if (cueDuration > 0) {
  17446. return cueDuration;
  17447. }
  17448. }
  17449. let duration = this.mIjkMediaPlayer.getDuration();
  17450. if (this.castControllerWrapper && this.isCastPlaying) {
  17451. return this.duration > 0 ? this.duration : duration;
  17452. }
  17453. if (duration <= 0 && this.duration > 0) {
  17454. duration = this.duration;
  17455. }
  17456. return duration;
  17457. }
  17458. @Builder
  17459. InlineSpectrumView() {
  17460. SpectrumView({
  17461. isVisible: this.currentSwiperIndex === 0,
  17462. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  17463. })
  17464. .width( '83%')
  17465. .height(this.isCoverOpacity() ? 80 : 100)
  17466. .margin({bottom: 3 })
  17467. .clip(true)
  17468. .zIndex(-2)
  17469. .onClick(()=>{
  17470. this.cycleSpectrumMode();
  17471. })
  17472. }
  17473. private cycleSpectrumMode(): void {
  17474. const modeNames: string[] = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  17475. if (modeNames.length <= 0) {
  17476. return;
  17477. }
  17478. const nextIndex: number = (this.spectrumModeIndex + 1) % modeNames.length;
  17479. this.spectrumModeIndex = nextIndex;
  17480. PreferencesUtil.putSync('spectrumModeIndex', nextIndex);
  17481. AppStorage.setOrCreate<number>('spectrumMode', nextIndex);
  17482. Logger.info('heanup-LocalMusic', `频谱特效已顺序切换为: ${modeNames[nextIndex]}`);
  17483. }
  17484. private getSongDurationMs(song?: VideoItem): number {
  17485. if (!song || !song.duration) {
  17486. return 0;
  17487. }
  17488. const raw = song.duration.trim();
  17489. if (!raw) {
  17490. return 0;
  17491. }
  17492. const parts = raw.split(':').map((part) => Number(part));
  17493. if (parts.some((part) => Number.isNaN(part))) {
  17494. return 0;
  17495. }
  17496. let seconds = 0;
  17497. if (parts.length === 3) {
  17498. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  17499. } else if (parts.length === 2) {
  17500. seconds = parts[0] * 60 + parts[1];
  17501. } else if (parts.length === 1) {
  17502. seconds = parts[0];
  17503. }
  17504. return seconds > 0 ? seconds * 1000 : 0;
  17505. }
  17506. private updateCastProgress(position: number): void {
  17507. const duration = this.getActiveDuration();
  17508. if (duration <= 0) {
  17509. return;
  17510. }
  17511. this.slideEnable = true;
  17512. let pos = (position / duration) * 100;
  17513. if (pos > this.PROGRESS_MAX_VALUE) {
  17514. this.progressValue = this.PROGRESS_MAX_VALUE;
  17515. } else if (pos < 0) {
  17516. this.progressValue = 0;
  17517. } else {
  17518. this.progressValue = pos;
  17519. }
  17520. this.totalTime = this.stringForTime(duration);
  17521. if (position > duration) {
  17522. position = duration;
  17523. }
  17524. this.isCurrentTime = true;
  17525. this.currentTime = this.stringForTime(position);
  17526. this.isCurrentTime = false;
  17527. const lyricPosition = position + this.timeOffset * 1000;
  17528. this.updateLyricPosition(lyricPosition);
  17529. }
  17530. /**
  17531. * Gesture method onActionUpdate.
  17532. *
  17533. * @param event Gesture event.手势拖动设置快进和后退
  17534. */
  17535. private setSeekToActionProgress(position: number) {
  17536. // 投播模式使用this.duration,本地模式使用播放器获取
  17537. let duration = this.getActiveDuration();
  17538. let pos = 0;
  17539. if (duration > 0) {
  17540. this.slideEnable = true;
  17541. let curPercent = position / duration;
  17542. pos = curPercent * 100;
  17543. if (pos > this.PROGRESS_MAX_VALUE) {
  17544. this.progressValue = this.PROGRESS_MAX_VALUE
  17545. } else {
  17546. this.progressValue = pos;
  17547. }
  17548. }
  17549. // LogUtils.getInstance()
  17550. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  17551. this.totalTime = this.stringForTime(duration);
  17552. if (position > duration) {
  17553. position = duration;
  17554. }
  17555. this.isCurrentTime = true;
  17556. this.currentTime = this.stringForTime(position);
  17557. this.isCurrentTime = false
  17558. }
  17559. private sessionRewindCallback = async (time?: number) => {
  17560. if (!time) {
  17561. return;
  17562. }
  17563. let curPosition: number;
  17564. if (this.castController && this.isCastPlaying) {
  17565. // 投播模式,使用UI显示的时间
  17566. curPosition = this.currentTime2 * 1000;
  17567. } else if (this.mIjkMediaPlayer != null) {
  17568. // 本地播放器模式
  17569. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17570. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17571. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17572. }
  17573. } else {
  17574. return;
  17575. }
  17576. let seeTime = curPosition - time * 1000;
  17577. // 限制 seekValue 在合法范围内
  17578. if (seeTime < 0) {
  17579. seeTime = 0;
  17580. } else if (seeTime > this.duration) {
  17581. seeTime = this.duration;
  17582. }
  17583. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  17584. this.setSeekToActionProgress(seeTime);
  17585. await this.seekTo(seeTime + "", 'session-rewind');
  17586. };
  17587. private sessionSeekCallback = async (seekTime: number) => {
  17588. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  17589. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  17590. await this.seekTo(seekTime + "", 'session-seek');
  17591. };
  17592. private async getFileSize(filePath: string): Promise<number> {
  17593. try {
  17594. const stat = await fs.stat(filePath);
  17595. return stat.size;
  17596. } catch (err) {
  17597. console.error('Failed to get file size: ' + err.message);
  17598. return 0;
  17599. }
  17600. }
  17601. private async pause(clearInterruptResumeFlag: boolean = true) {
  17602. if (clearInterruptResumeFlag) {
  17603. this.audioInterruptResumePending = false;
  17604. }
  17605. // 如果是投播模式,使用 CastController 的 pause 方法
  17606. if (this.castControllerWrapper && this.isCastPlaying) {
  17607. try {
  17608. Logger.info('heanup pause', '投播模式暂停');
  17609. await this.castControllerWrapper.setPause();
  17610. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17611. this.setIsPlaying(false);
  17612. this.updateSessionPlayState(false);
  17613. Logger.info('heanup pause', '投播暂停成功');
  17614. } catch (error) {
  17615. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  17616. }
  17617. } else if (this.mIjkMediaPlayer.isPlaying() || this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17618. // 本地播放器模式
  17619. this.savePlaybackPosition();
  17620. if (this.mIjkMediaPlayer.isPlaying()) {
  17621. this.mIjkMediaPlayer.pause();
  17622. this.setProgress();
  17623. }
  17624. this.mDestroyPage = true;
  17625. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17626. this.updateSessionPlayState(false)
  17627. this.playChange()
  17628. if (this.pipController) {
  17629. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  17630. PiPWindow.PiPControlStatus.PAUSE);
  17631. }
  17632. }
  17633. }
  17634. private stop() {
  17635. this.audioInterruptResumePending = false;
  17636. this.savePlaybackPosition();
  17637. this.clearInitialSeekGuardTimer();
  17638. this.waitInitialSeekBeforeStart = false;
  17639. this.pendingMemorySeekPosition = 0;
  17640. this.isPlayerLoading = false;
  17641. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17642. this.mIjkMediaPlayer.stop();
  17643. this.mIjkMediaPlayer.release();
  17644. console.info('kkMusic stop ..this.CONTROL_PlayStatus '+this.CONTROL_PlayStatus )
  17645. this.stopProgressTask();
  17646. this.updateSessionPlayState(false)
  17647. this.playChange()
  17648. this.watchStatus();
  17649. }
  17650. //保持记忆播放功能
  17651. private savePlaybackPosition() {
  17652. if (this.mIjkMediaPlayer != null) {
  17653. let position = this.mIjkMediaPlayer.getCurrentPosition();
  17654. // ToastUtil.showToast('保存记忆播放 = ' + position)
  17655. let duration = this.mIjkMediaPlayer.getDuration();
  17656. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17657. position = Math.max(0, position - getCueTrackStartOffset(this.currentSong));
  17658. const cueDuration = getCueTrackDuration(this.currentSong);
  17659. if (cueDuration > 0) {
  17660. duration = cueDuration;
  17661. }
  17662. }
  17663. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  17664. // 如果播放位置接近视频末尾,则保存 position 为 0
  17665. const playbackPosition = (duration - position < threshold) ? 0 : position;
  17666. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  17667. PreferencesUtil.putSync(memoryKey, playbackPosition);
  17668. }
  17669. }
  17670. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  17671. if (song && isRemoteCloudType(song.type)) {
  17672. const accountId = song.webdav_account_id || 'unknown';
  17673. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  17674. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  17675. }
  17676. if (song && isCueSplitItem(song)) {
  17677. return `memory_play_local_cue:${song.filePath}`;
  17678. }
  17679. return playbackUrl || '';
  17680. }
  17681. private getPlaybackMemoryKey(): string {
  17682. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  17683. }
  17684. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  17685. if (token !== this.remoteRestoreSeekToken) {
  17686. return;
  17687. }
  17688. if (!this.mIjkMediaPlayer || position <= 0) {
  17689. if (this.waitInitialSeekBeforeStart) {
  17690. this.finishInitialSeekWait('invalid-memory-position', true);
  17691. }
  17692. return;
  17693. }
  17694. const duration = this.getActiveDuration();
  17695. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  17696. let safePosition = position;
  17697. if (duration > 0) {
  17698. safePosition = Math.max(0, Math.min(position, duration - 500));
  17699. } else {
  17700. safePosition = Math.max(0, position);
  17701. }
  17702. if (safePosition <= 0) {
  17703. if (this.waitInitialSeekBeforeStart) {
  17704. this.finishInitialSeekWait('memory-position-too-small', true);
  17705. }
  17706. return;
  17707. }
  17708. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  17709. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  17710. }
  17711. this.seekTo(safePosition + "", retryCount === 0 ? 'remote-memory-restore' : 'remote-memory-retry');
  17712. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  17713. return;
  17714. }
  17715. setTimeout(() => {
  17716. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  17717. return;
  17718. }
  17719. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  17720. if (Math.abs(latestPos - safePosition) <= 1500) {
  17721. return;
  17722. }
  17723. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  17724. }, this.remoteMemorySeekRetryIntervalMs);
  17725. }
  17726. //获取记忆播放功能
  17727. private restorePlaybackPosition() {
  17728. const position: number = this.pendingMemorySeekPosition > 0 ?
  17729. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  17730. if (!this.mIjkMediaPlayer || position <= 0) {
  17731. if (this.waitInitialSeekBeforeStart) {
  17732. this.finishInitialSeekWait('no-memory-position', true);
  17733. }
  17734. return;
  17735. }
  17736. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17737. if (isRemoteSong && this.videoUrl.includes('://')) {
  17738. const token = this.remoteRestoreSeekToken;
  17739. this.restoreRemotePlaybackPositionSafely(position, token);
  17740. return;
  17741. }
  17742. const duration = this.getActiveDuration();
  17743. let safePosition = position;
  17744. if (duration > 0) {
  17745. safePosition = Math.max(0, Math.min(position, duration - 500));
  17746. } else {
  17747. safePosition = Math.max(0, position);
  17748. }
  17749. if (safePosition <= 0) {
  17750. if (this.waitInitialSeekBeforeStart) {
  17751. this.finishInitialSeekWait('memory-position-too-small', true);
  17752. }
  17753. return;
  17754. }
  17755. this.seekTo(safePosition + "", isRemoteSong ? 'remote-memory-restore' : 'memory-restore');
  17756. }
  17757. private async seekTo(value: string, source: string = 'internal') {
  17758. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  17759. // ToastUtil.showToast('wma格式不支持拖动快进。')
  17760. // return
  17761. // }
  17762. // 如果是投播模式,使用 CastController 的 seek 方法
  17763. if (this.castControllerWrapper && this.isCastPlaying) {
  17764. try {
  17765. let seekPos = Number.parseInt(value);
  17766. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17767. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17768. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17769. const duration = this.getActiveDuration();
  17770. if (duration > 0) {
  17771. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17772. }
  17773. if (cueTrackItem) {
  17774. seekPos += cueTrackStartOffset;
  17775. if (cueTrackEndOffset > cueTrackStartOffset) {
  17776. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17777. }
  17778. }
  17779. this.beginSeekTrace(source, seekPos);
  17780. this.isSeekTo = true;
  17781. Logger.info(
  17782. TAG,
  17783. `[seek] cast dispatch, source=${source}, target=${seekPos}, duration=${duration}, ` +
  17784. `uiDuration=${this.duration}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17785. );
  17786. // 检查是否接近末尾
  17787. if (this.duration > 0 && seekPos >= this.duration - 500) {
  17788. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  17789. }
  17790. await this.castControllerWrapper.seek(seekPos);
  17791. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  17792. } catch (error) {
  17793. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  17794. }
  17795. } else {
  17796. // 本地播放器模式
  17797. let seekPos = Number.parseInt(value);
  17798. if (Number.isNaN(seekPos)) {
  17799. return;
  17800. }
  17801. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17802. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17803. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17804. const duration = this.getActiveDuration();
  17805. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17806. if (duration > 0) {
  17807. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17808. } else if (seekPos < 0) {
  17809. seekPos = 0;
  17810. }
  17811. if (cueTrackItem) {
  17812. seekPos += cueTrackStartOffset;
  17813. if (cueTrackEndOffset > cueTrackStartOffset) {
  17814. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17815. }
  17816. }
  17817. if (isRemoteSong && duration <= 0 && seekPos > 0) {
  17818. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${seekPos}ms`);
  17819. return;
  17820. }
  17821. if (isRemoteSong && duration <= 0) {
  17822. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  17823. }
  17824. if (source !== 'internal') {
  17825. this.beginSeekTrace(source, seekPos);
  17826. }
  17827. if (this.handleBlockedSeek(seekPos, source)) {
  17828. return;
  17829. }
  17830. this.isSeekTo = true
  17831. try {
  17832. if (isRemoteSong || source !== 'internal' || this.isSeekTraceActive()) {
  17833. Logger.info(
  17834. TAG,
  17835. `[seek] player dispatch, source=${source}, target=${seekPos}, activeDuration=${duration}, ` +
  17836. `playerDuration=${this.mIjkMediaPlayer.getDuration()}, current=${this.mIjkMediaPlayer.getCurrentPosition()}, ` +
  17837. `isPlaying=${this.mIjkMediaPlayer.isPlaying()}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17838. );
  17839. }
  17840. this.mIjkMediaPlayer.seekTo(seekPos + "");
  17841. this.logSeekTrace('seek-dispatched', this.mIjkMediaPlayer.getCurrentPosition(), this.mIjkMediaPlayer.getDuration(), true);
  17842. this.setProgress()
  17843. } catch (error) {
  17844. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  17845. this.logSeekTrace('seek-dispatch-error', undefined, undefined, true);
  17846. } finally {
  17847. this.isSeekTo = false
  17848. }
  17849. }
  17850. }
  17851. // 添加到下一首播放
  17852. private addToNextPlay(song: VideoItem) {
  17853. if (!this.debounce()) {
  17854. return;
  17855. }
  17856. if (this.currentSong) {
  17857. if (this.currentSong === song) {
  17858. ToastUtil.showToast('当前已经在播放这首歌了!')
  17859. return
  17860. }
  17861. }
  17862. // 如果未开始播放或队列为空
  17863. if (this.curIndex === -1 || this.songList.length === 0) {
  17864. this.songList = [song];
  17865. this.curIndex = 0;
  17866. this.doPlay(song)
  17867. return;
  17868. }
  17869. // 插入到当前索引+1的位置
  17870. const insertPos = this.curIndex + 1;
  17871. this.songList.splice(insertPos, 0, song);
  17872. this.songList = [...this.songList]; // 触发状态更新
  17873. this.sonDataSource.pushArrayData(this.songList)
  17874. ToastUtil.showToast('已添加至下一首播放')
  17875. }
  17876. //后退10s,可再设置设置默认几秒
  17877. async backForward() {
  17878. // 如果是投播模式,从currentTime2获取当前位置
  17879. let pos: number;
  17880. if (this.castController && this.isCastPlaying) {
  17881. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17882. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  17883. } else if (this.mIjkMediaPlayer) {
  17884. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17885. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17886. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17887. }
  17888. } else {
  17889. return;
  17890. }
  17891. let value = pos - Number(this.fastForwardSeconds) * 1000;
  17892. if (value < 0) {
  17893. value = 0;
  17894. }
  17895. await this.seekTo(value + "", 'rewind-button');
  17896. }
  17897. //快进10s,可再设置设置默认几秒
  17898. async fastForward() {
  17899. // 如果是投播模式,从currentTime2获取当前位置
  17900. let pos: number;
  17901. if (this.castController && this.isCastPlaying) {
  17902. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17903. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  17904. } else if (this.mIjkMediaPlayer) {
  17905. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17906. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17907. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17908. }
  17909. } else {
  17910. return;
  17911. }
  17912. let value = pos + Number(this.fastForwardSeconds) * 1000;
  17913. // 限制不超过总时长
  17914. if (this.duration > 0 && value > this.duration) {
  17915. value = this.duration;
  17916. }
  17917. await this.seekTo(value + "", 'fast-forward-button');
  17918. }
  17919. //下一个
  17920. private async playNext() {
  17921. this.lyricController.setLyric(null)
  17922. this.lyricControllerXF.setLyric(null)
  17923. this.lyricControllerSingle.setLyric(null)
  17924. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  17925. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  17926. if (!this.debounce()) {
  17927. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  17928. return;
  17929. }
  17930. Logger.info('heanup playNext', `playType=${this.playType}`);
  17931. if (this.playType == 3) { //3:随机播放
  17932. Logger.info('heanup playNext', '随机播放模式');
  17933. await this.randomPlay()
  17934. return;
  17935. }
  17936. if (ArrayUtil.isNotEmpty(this.songList)) {
  17937. if (this.curIndex >= this.songList.length - 1) {
  17938. // playType=0 或 3: 尝试加载更多或循环
  17939. // playType=4: 不循环,检查是否是最后一首
  17940. if (this.playType == 4) {
  17941. // 连续播放不循环模式:到达最后一首时停止播放
  17942. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  17943. ToastUtil.showToast('已经是最后一首了');
  17944. this.showRePlay();
  17945. this.currentTime = this.stringForTime(this.getActiveDuration());
  17946. this.progressValue = this.PROGRESS_MAX_VALUE;
  17947. this.slideEnable = false;
  17948. this.stop();
  17949. return;
  17950. }
  17951. await this.tryLoadNextPageForPlayback();
  17952. }
  17953. if (this.curIndex >= this.songList.length - 1) {
  17954. // playType=4 不应该执行到这里,因为上面已经return了
  17955. this.curIndex = 0;
  17956. } else {
  17957. this.curIndex++;
  17958. }
  17959. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17960. this.currentSong = this.songList[this.curIndex];
  17961. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17962. const nextLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17963. const nextUrl = await this.resolvePlaybackUrlForCurrentSong('playNext');
  17964. if (!nextUrl) {
  17965. if (nextLoading) {
  17966. this.hideLoadIng();
  17967. }
  17968. return;
  17969. }
  17970. this.videoUrl = nextUrl;
  17971. this.artist = this.songList[this.curIndex].artist
  17972. this.name = this.songList[this.curIndex].name
  17973. //this.cover = this.songList[this.curIndex].pixelMapPath
  17974. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  17975. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  17976. // 如果是投播模式,使用 CastController 播放下一首
  17977. if (this.castControllerWrapper) {
  17978. console.info('heanup playNext', '使用 CastController 播放下一首');
  17979. try {
  17980. const nextDuration = this.getSongDurationMs(this.currentSong);
  17981. if (nextDuration > 0) {
  17982. this.duration = nextDuration;
  17983. this.durationTime = Math.floor(nextDuration / 1000);
  17984. this.durationStringTime = secondToTime(this.durationTime);
  17985. this.totalTime = this.stringForTime(nextDuration);
  17986. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  17987. }
  17988. this.updateCastProgress(0);
  17989. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  17990. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17991. if (nextLoading) {
  17992. this.hideLoadIng();
  17993. }
  17994. console.info('heanup playNext', 'CastController 播放下一首成功');
  17995. return;
  17996. } catch (error) {
  17997. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  17998. // 如果投播失败,回退到本地播放
  17999. this.isCastPlaying = false;
  18000. }
  18001. }
  18002. // 本地播放器模式,需要先stop
  18003. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18004. this.stop();
  18005. if (nextLoading) {
  18006. this.showLoadIng();
  18007. }
  18008. this.changeImageAnimation()
  18009. }
  18010. }
  18011. changeImageAnimation() {
  18012. if(this.openSkipSongAnimate){
  18013. // 第一步:淡出动画
  18014. this.getUIContext()?.animateTo({
  18015. duration: 500,
  18016. curve: Curve.EaseOut,
  18017. }, () => {
  18018. this.opacityValueImage = 0.1;
  18019. if(this.isCoverRectangle){
  18020. this.scaleValueImage = 0.88
  18021. }
  18022. });
  18023. // 第二步:切换图片后淡入
  18024. setTimeout(() => {
  18025. this.cover = this.songList[this.curIndex].pixelMapPath
  18026. this.getUIContext()?.animateTo({
  18027. duration: 500,
  18028. curve: Curve.EaseIn,
  18029. }, () => {
  18030. this.opacityValueImage = 1;
  18031. this.scaleValueImage = 1 // 图标恢复到原始大小
  18032. this.startPlayOrResumePlay()
  18033. });
  18034. }, 500);
  18035. }else{
  18036. this.cover = this.songList[this.curIndex].pixelMapPath
  18037. this.startPlayOrResumePlay()
  18038. }
  18039. }
  18040. // 内部方法:提前缓存下一首
  18041. private async preloadNextSongInternal(): Promise<void> {
  18042. // 随机模式下传递已播放索引集合
  18043. if (this.playType === 3) {
  18044. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  18045. this.songList,
  18046. this.curIndex,
  18047. this.playType,
  18048. this.playedIndices
  18049. );
  18050. } else {
  18051. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  18052. this.songList,
  18053. this.curIndex,
  18054. this.playType
  18055. );
  18056. }
  18057. }
  18058. // 存储已播放的歌曲索引
  18059. private playedIndices: Set<number> = new Set();
  18060. // 存储已播放的本地歌曲路径(随机播放去重用)
  18061. private playedLocalFilePaths: Set<string> = new Set();
  18062. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  18063. private randomPlayHistory: VideoItem[] = [];
  18064. //随机播放
  18065. private async randomPlay() {
  18066. // if (!this.debounce()) {
  18067. // return;
  18068. // }
  18069. // 网盘模式: 渐进式扩展播放库的随机播放
  18070. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  18071. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  18072. if (isCloudSong) {
  18073. const findRemoteQueue = getFindVideoItems();
  18074. const isSameFindQueue = this.songList.length === findRemoteQueue.length &&
  18075. this.songList.every((item: VideoItem, index: number) => item.filePath === findRemoteQueue[index]?.filePath);
  18076. const useFindRemoteQueue = this.playQueueScope === 'playlist' &&
  18077. findRemoteQueue.length > 0 &&
  18078. isSameFindQueue &&
  18079. findRemoteQueue.every((item: VideoItem) => isRemoteCloudType(item.type)) &&
  18080. findRemoteQueue.some((item: VideoItem) => item.filePath === this.currentSong?.filePath);
  18081. // 阈值常量
  18082. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  18083. const LOAD_MORE_PAGES = 3; // 每次加载页数
  18084. // 获取网盘播放列表
  18085. const navidromeList = useFindRemoteQueue ? [] : getNavidromeVideoItems();
  18086. const webdavList = useFindRemoteQueue ? [] : getWebdavVideoItems();
  18087. const isNavidrome = !useFindRemoteQueue && navidromeList.length > 0;
  18088. const remoteList = useFindRemoteQueue ? findRemoteQueue : (isNavidrome ? navidromeList : webdavList);
  18089. if (remoteList.length > 0) {
  18090. // 将当前歌加入历史栈
  18091. if (this.currentSong) {
  18092. this.randomPlayHistory.unshift(this.currentSong);
  18093. if (this.randomPlayHistory.length > 50) {
  18094. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  18095. }
  18096. // 标记当前歌曲为已播放
  18097. markAsPlayed(this.currentSong.filePath);
  18098. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  18099. }
  18100. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  18101. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  18102. const totalCount = remoteList.length;
  18103. const playedCount = isNavidrome ? getPlayedCount() : 0;
  18104. Logger.info(TAG,
  18105. `randomPlay(网盘模式): source=${useFindRemoteQueue ? 'find-playlist' : (isNavidrome ? 'navidrome' : 'webdav')}, ` +
  18106. `总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  18107. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  18108. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  18109. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  18110. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  18111. if (loadSuccess) {
  18112. // 重新获取未播放数量
  18113. unplayedCount = getUnplayedCount();
  18114. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  18115. }
  18116. }
  18117. // 从未播放歌曲中随机选择
  18118. let candidates: VideoItem[];
  18119. if (isNavidrome) {
  18120. candidates = getUnplayedSongs();
  18121. // 如果全部播放完,重置已播放记录
  18122. if (candidates.length === 0) {
  18123. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  18124. clearPlayedHistory();
  18125. // 排除当前歌曲
  18126. const currentFilePath = this.currentSong?.filePath;
  18127. candidates = currentFilePath
  18128. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  18129. : getNavidromeVideoItems();
  18130. }
  18131. } else {
  18132. // WebDAV模式:简单排除当前歌曲
  18133. const currentFilePath = this.currentSong?.filePath;
  18134. candidates = currentFilePath
  18135. ? remoteList.filter(v => v.filePath !== currentFilePath)
  18136. : remoteList;
  18137. }
  18138. if (candidates.length > 0) {
  18139. const randomIndex = Math.floor(Math.random() * candidates.length);
  18140. const randomSong = candidates[randomIndex];
  18141. // 标记为已播放
  18142. if (isNavidrome) {
  18143. markAsPlayed(randomSong.filePath);
  18144. }
  18145. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  18146. // 将选中的歌曲加入播放列表(如果不存在)
  18147. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  18148. if (nextIndex < 0) {
  18149. this.songList = [...this.songList, randomSong];
  18150. this.sonDataSource.pushArrayData(this.songList);
  18151. nextIndex = this.songList.length - 1;
  18152. }
  18153. this.curIndex = nextIndex;
  18154. this.playedIndices.add(this.curIndex);
  18155. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18156. this.stop();
  18157. this.currentSong = randomSong;
  18158. const randomRemoteListLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18159. const randomRemoteListUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-list');
  18160. if (!randomRemoteListUrl) {
  18161. if (randomRemoteListLoading) {
  18162. this.hideLoadIng();
  18163. }
  18164. return;
  18165. }
  18166. this.videoUrl = randomRemoteListUrl;
  18167. this.name = this.currentSong.name;
  18168. this.artist = this.currentSong.artist;
  18169. this.changeImageAnimation();
  18170. return;
  18171. }
  18172. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  18173. }
  18174. }
  18175. if (this.currentSong) {
  18176. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  18177. this.randomPlayHistory.unshift(this.currentSong);
  18178. // 限制历史栈大小,避免无限增长
  18179. if (this.randomPlayHistory.length > 50) {
  18180. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  18181. }
  18182. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  18183. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  18184. const currentFilePath = this.currentSong.filePath;
  18185. if (isCurrentRemote) {
  18186. const remoteOptions: RandomSongQueryOptions = {
  18187. type: this.currentSong.type,
  18188. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18189. };
  18190. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  18191. if (randomRemoteSong) {
  18192. // 验证并修正webdav_account_id
  18193. if (randomRemoteSong.webdav_account_id) {
  18194. const manager = RemoteDriveManager.getInstance();
  18195. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  18196. if (!account) {
  18197. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  18198. // 获取所有账号,查找相同类型的账号
  18199. const allAccounts = manager.getAllWebDavAccounts();
  18200. let foundAccount: WebDavAccount | null = null;
  18201. for (let i = 0; i < allAccounts.length; i++) {
  18202. if (allAccounts[i].webType === randomRemoteSong.type) {
  18203. foundAccount = allAccounts[i];
  18204. break;
  18205. }
  18206. }
  18207. if (foundAccount && foundAccount.id) {
  18208. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  18209. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  18210. // 更新数据库记录
  18211. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  18212. } else {
  18213. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  18214. return;
  18215. }
  18216. }
  18217. }
  18218. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  18219. if (nextIndex < 0) {
  18220. this.songList = [...this.songList, randomRemoteSong];
  18221. this.sonDataSource.pushArrayData(this.songList);
  18222. nextIndex = this.songList.length - 1;
  18223. }
  18224. this.curIndex = nextIndex;
  18225. this.playedIndices.add(this.curIndex);
  18226. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18227. this.stop();
  18228. this.currentSong = randomRemoteSong;
  18229. const randomRemoteDbLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18230. const randomRemoteUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-db');
  18231. if (!randomRemoteUrl) {
  18232. if (randomRemoteDbLoading) {
  18233. this.hideLoadIng();
  18234. }
  18235. return;
  18236. }
  18237. this.videoUrl = randomRemoteUrl;
  18238. this.name = this.currentSong.name;
  18239. this.artist = this.currentSong.artist;
  18240. this.changeImageAnimation();
  18241. return;
  18242. }
  18243. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  18244. } else {
  18245. if (currentFilePath) {
  18246. this.playedLocalFilePaths.add(currentFilePath);
  18247. }
  18248. // 根据modeType构建不同的查询选项
  18249. const localOptions: RandomSongQueryOptions = {
  18250. type: CommonConstants.TYPE_LOCAL,
  18251. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  18252. };
  18253. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  18254. // modeType==0: 文件夹模式,添加parentPath过滤
  18255. if (this.modeType === 0 && this.currentPath) {
  18256. localOptions.parentPath = this.currentPath;
  18257. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  18258. }
  18259. // modeType==4: 歌单模式,添加playlistSongFilePaths
  18260. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18261. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18262. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  18263. } else if (this.modeType === 4) {
  18264. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  18265. }
  18266. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  18267. if (!randomLocalSong) {
  18268. this.playedLocalFilePaths.clear();
  18269. if (currentFilePath) {
  18270. this.playedLocalFilePaths.add(currentFilePath);
  18271. }
  18272. const fallbackLocalOptions: RandomSongQueryOptions = {
  18273. type: CommonConstants.TYPE_LOCAL,
  18274. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18275. };
  18276. // fallback时也要保持modeType的过滤条件
  18277. if (this.modeType === 0 && this.currentPath) {
  18278. fallbackLocalOptions.parentPath = this.currentPath;
  18279. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18280. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18281. }
  18282. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  18283. }
  18284. if (randomLocalSong !== null) {
  18285. const selectedLocalSong = randomLocalSong;
  18286. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  18287. if (nextIndex < 0) {
  18288. this.songList = [...this.songList, selectedLocalSong];
  18289. this.sonDataSource.pushArrayData(this.songList);
  18290. nextIndex = this.songList.length - 1;
  18291. }
  18292. this.curIndex = nextIndex;
  18293. this.playedIndices.add(this.curIndex);
  18294. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18295. this.stop();
  18296. this.currentSong = selectedLocalSong;
  18297. const randomLocalUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-local-db');
  18298. if (!randomLocalUrl) {
  18299. return;
  18300. }
  18301. this.videoUrl = randomLocalUrl;
  18302. this.name = this.currentSong.name;
  18303. this.artist = this.currentSong.artist;
  18304. this.changeImageAnimation();
  18305. return;
  18306. }
  18307. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  18308. }
  18309. }
  18310. if (ArrayUtil.isNotEmpty(this.songList)) {
  18311. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  18312. this.playedIndices.add(this.curIndex);
  18313. }
  18314. if (this.songList.length > 3) {
  18315. // 优先使用预缓存的随机索引(仅网盘播放时)
  18316. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  18317. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  18318. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  18319. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  18320. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  18321. this.curIndex = this.preloadNextRandomIndex;
  18322. this.playedIndices.add(this.curIndex);
  18323. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  18324. // 立即预缓存下一首,避免下次点击时没有预缓存
  18325. void this.preloadNextSongInternal();
  18326. } else {
  18327. // 如果没有预缓存索引,则正常随机选择
  18328. // 如果所有歌曲都播放过一次,清空已播放索引集合
  18329. if (this.playedIndices.size === this.songList.length) {
  18330. this.playedIndices.clear();
  18331. }
  18332. // 随机选择一个未播放的歌曲索引
  18333. let newIndex: number;
  18334. // 添加超时机制防止无限循环
  18335. let attempt = 0;
  18336. const maxAttempts = 100; // 根据需求调整
  18337. do {
  18338. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  18339. attempt++;
  18340. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  18341. if (attempt >= maxAttempts) {
  18342. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  18343. newIndex = Math.floor(Math.random() * this.songList.length);
  18344. }
  18345. this.curIndex = newIndex;
  18346. this.playedIndices.add(newIndex);
  18347. }
  18348. } else {
  18349. // 当歌曲数量小于或等于3时,直接播放下一首
  18350. if (this.curIndex == this.songList.length - 1) {
  18351. this.curIndex = 0;
  18352. } else {
  18353. this.curIndex++;
  18354. }
  18355. }
  18356. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18357. this.stop();
  18358. this.currentSong = this.songList[this.curIndex];
  18359. const randomFallbackLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18360. const randomFallbackUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-fallback');
  18361. if (!randomFallbackUrl) {
  18362. if (randomFallbackLoading) {
  18363. this.hideLoadIng();
  18364. }
  18365. return;
  18366. }
  18367. this.videoUrl = randomFallbackUrl;
  18368. this.name = this.songList[this.curIndex].name;
  18369. this.artist = this.songList[this.curIndex].artist
  18370. // this.cover = this.songList[this.curIndex].pixelMapPath
  18371. this.changeImageAnimation()
  18372. // 预缓存下一首(包括网盘和本地)
  18373. void this.preloadNextSongInternal();
  18374. }
  18375. }
  18376. private async playIndex(index: number) {
  18377. if (!this.debounce()) {
  18378. return;
  18379. }
  18380. if (ArrayUtil.isNotEmpty(this.songList)) {
  18381. this.curIndex = index;
  18382. this.currentSong = this.songList[index];
  18383. const playIndexLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18384. const playIndexUrl = await this.resolvePlaybackUrlForCurrentSong('playIndex');
  18385. if (!playIndexUrl) {
  18386. if (playIndexLoading) {
  18387. this.hideLoadIng();
  18388. }
  18389. return;
  18390. }
  18391. this.videoUrl = playIndexUrl;
  18392. this.name = this.currentSong.name
  18393. this.artist = this.currentSong.artist
  18394. // 如果是投播模式,需要为投播设备准备当前歌曲
  18395. if (this.castController && this.isCastPlaying) {
  18396. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  18397. this.initQueueItem();
  18398. await this.prepare();
  18399. if (playIndexLoading) {
  18400. this.hideLoadIng();
  18401. }
  18402. this.cover = this.currentSong.pixelMapPath;
  18403. return;
  18404. }
  18405. // 本地播放器模式,需要先stop
  18406. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18407. this.stop();
  18408. if (playIndexLoading) {
  18409. this.showLoadIng();
  18410. }
  18411. this.changeImageAnimation()
  18412. }
  18413. }
  18414. //上一个
  18415. private async playPrevious() {
  18416. if (!this.debounce()) {
  18417. return;
  18418. }
  18419. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  18420. this.randomModePlayFromHistory()
  18421. return;
  18422. }
  18423. if (this.curIndex == 0) {
  18424. this.curIndex = this.songList.length - 1;
  18425. } else {
  18426. this.curIndex--;
  18427. }
  18428. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  18429. this.currentSong = this.songList[this.curIndex];
  18430. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  18431. // 验证并修正webdav_account_id(针对远程类型歌曲)
  18432. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  18433. const manager = RemoteDriveManager.getInstance();
  18434. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  18435. if (!account) {
  18436. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  18437. // 获取所有账号,查找相同类型的账号
  18438. const allAccounts = manager.getAllWebDavAccounts();
  18439. let foundAccount: WebDavAccount | null = null;
  18440. for (let i = 0; i < allAccounts.length; i++) {
  18441. if (allAccounts[i].webType === this.currentSong.type) {
  18442. foundAccount = allAccounts[i];
  18443. break;
  18444. }
  18445. }
  18446. if (foundAccount && foundAccount.id) {
  18447. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  18448. this.currentSong.webdav_account_id = foundAccount.id.toString();
  18449. // 更新数据库记录
  18450. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  18451. } else {
  18452. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  18453. // 跳过无效账号的歌曲,继续查找上一首
  18454. if (this.curIndex == 0) {
  18455. this.curIndex = this.songList.length - 1;
  18456. } else {
  18457. this.curIndex--;
  18458. }
  18459. this.currentSong = this.songList[this.curIndex];
  18460. }
  18461. }
  18462. }
  18463. const previousLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18464. const previousUrl = await this.resolvePlaybackUrlForCurrentSong('playPrevious');
  18465. if (!previousUrl) {
  18466. if (previousLoading) {
  18467. this.hideLoadIng();
  18468. }
  18469. return;
  18470. }
  18471. this.videoUrl = previousUrl;
  18472. this.name = this.songList[this.curIndex].name
  18473. this.artist = this.songList[this.curIndex].artist
  18474. // 如果是投播模式,使用 CastController 切换上一首
  18475. if (this.castControllerWrapper) {
  18476. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  18477. try {
  18478. const prevDuration = this.getSongDurationMs(this.currentSong);
  18479. if (prevDuration > 0) {
  18480. this.duration = prevDuration;
  18481. this.durationTime = Math.floor(prevDuration / 1000);
  18482. this.durationStringTime = secondToTime(this.durationTime);
  18483. this.totalTime = this.stringForTime(prevDuration);
  18484. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  18485. }
  18486. this.updateCastProgress(0);
  18487. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  18488. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  18489. if (previousLoading) {
  18490. this.hideLoadIng();
  18491. }
  18492. } catch (error) {
  18493. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  18494. this.isCastPlaying = false;
  18495. }
  18496. this.cover = this.songList[this.curIndex].pixelMapPath;
  18497. return;
  18498. }
  18499. // 本地播放器模式,需要先stop
  18500. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18501. this.stop();
  18502. if (previousLoading) {
  18503. this.showLoadIng();
  18504. }
  18505. this.changeImageAnimation()
  18506. }
  18507. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  18508. private async randomModePlayFromHistory() {
  18509. if (this.randomPlayHistory.length >= 1) {
  18510. // 播放历史栈的第一首(刚刚播放过的)
  18511. const prevSong = this.randomPlayHistory[0];
  18512. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  18513. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  18514. this.randomPlayHistory.shift();
  18515. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  18516. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18517. this.stop();
  18518. // 验证并修正webdav_account_id(针对远程类型歌曲)
  18519. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  18520. const manager = RemoteDriveManager.getInstance();
  18521. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  18522. if (!account) {
  18523. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  18524. const allAccounts = manager.getAllWebDavAccounts();
  18525. let foundAccount: WebDavAccount | null = null;
  18526. for (let i = 0; i < allAccounts.length; i++) {
  18527. if (allAccounts[i].webType === prevSong.type) {
  18528. foundAccount = allAccounts[i];
  18529. break;
  18530. }
  18531. }
  18532. if (foundAccount && foundAccount.id) {
  18533. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  18534. prevSong.webdav_account_id = foundAccount.id.toString();
  18535. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  18536. } else {
  18537. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  18538. // 无法播放这首歌,继续尝试下一首历史记录
  18539. if (this.randomPlayHistory.length >= 1) {
  18540. this.randomModePlayFromHistory();
  18541. return;
  18542. } else {
  18543. // 历史记录为空,无法继续
  18544. ToastUtil.showToast('没有更多历史记录');
  18545. return;
  18546. }
  18547. }
  18548. }
  18549. }
  18550. this.currentSong = prevSong;
  18551. const historyLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18552. const historyUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-history');
  18553. if (!historyUrl) {
  18554. if (historyLoading) {
  18555. this.hideLoadIng();
  18556. }
  18557. return;
  18558. }
  18559. this.videoUrl = historyUrl;
  18560. this.cover = this.currentSong.pixelMapPath
  18561. this.artist = this.currentSong.artist
  18562. this.name = this.currentSong.name;
  18563. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  18564. this.startPlayOrResumePlay();
  18565. } else {
  18566. ToastUtil.showToast('随机播放模式暂无历史记录');
  18567. }
  18568. }
  18569. debounce() {
  18570. const delay = 600;
  18571. let cur = new Date().getTime();
  18572. if (cur - this.last > delay) {
  18573. this.last = cur;
  18574. return true;
  18575. }
  18576. return false;
  18577. }
  18578. /**
  18579. * Sets whether the screen is a constant based on the playback status.
  18580. */
  18581. watchStatus() {
  18582. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  18583. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  18584. this.windowClass.setWindowKeepScreenOn(true);
  18585. } else {
  18586. this.windowClass.setWindowKeepScreenOn(false);
  18587. }
  18588. }
  18589. /**
  18590. * Volume gesture method onActionStart.
  18591. *
  18592. * @param event Gesture event.
  18593. */
  18594. private customDialogComponentIdMM: number = 0
  18595. @Builder
  18596. customDialogComponentMM() {
  18597. Column() {
  18598. Row() {
  18599. Blank()
  18600. Text('验证密码')
  18601. .fontSize(22)
  18602. .fontColor($r('app.color.pri_bg'))
  18603. .margin({ top: 18 })
  18604. Blank()
  18605. Image($r('app.media.close'))
  18606. .fillColor(Color.White)
  18607. .margin({ top: 18, right: 18 })
  18608. .width(20)
  18609. .onClick(() => {
  18610. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18611. })
  18612. }
  18613. .width('100%') // 使Row占据整个宽度
  18614. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  18615. Verify({
  18616. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  18617. });
  18618. }.height('60%')
  18619. .backgroundColor($r('app.color.index_background'))
  18620. .justifyContent(FlexAlign.SpaceBetween)
  18621. }
  18622. private handleVerifyCompleted(isSuccess: boolean) {
  18623. if (isSuccess) {
  18624. console.log('验证成功');
  18625. // 在这里处理验证成功后的逻辑
  18626. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18627. this.currentPath = this.lockPath
  18628. this.getSortedFiles(this.currentPath)
  18629. } else {
  18630. // console.log('验证失败');
  18631. ToastUtil.showToast('验证失败')
  18632. }
  18633. }
  18634. private showVerifyDialog() {
  18635. promptAction.openCustomDialog({
  18636. transition: TransitionEffect.asymmetric(
  18637. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  18638. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18639. ,
  18640. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  18641. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18642. ),
  18643. builder: () => {
  18644. this.customDialogComponentMM()
  18645. },
  18646. isModal: true,
  18647. autoCancel: true,
  18648. maskColor: Color.Transparent,
  18649. alignment: DialogAlignment.Bottom,
  18650. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  18651. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  18652. console.log("dialog onWillDismiss")
  18653. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  18654. dismissDialogAction.dismiss()
  18655. }
  18656. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  18657. dismissDialogAction.dismiss()
  18658. }
  18659. }
  18660. }).then((dialogId: number) => {
  18661. this.customDialogComponentIdMM = dialogId
  18662. })
  18663. }
  18664. //左滑操作 移动文件 重命名 删除等操作
  18665. @Builder
  18666. DeleteButton(item: VideoItem, index: number, filePath: string) {
  18667. Row() {
  18668. //加入收藏
  18669. // Button() {
  18670. // Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  18671. // .fillColor(Color.White)
  18672. // .width(20)
  18673. // }
  18674. // .width(40)
  18675. // .height(40)
  18676. // .type(ButtonType.Circle)
  18677. // .backgroundColor(this.themeColor)
  18678. // .margin(5)
  18679. // .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18680. // .onClick(() => {
  18681. // if (item) {
  18682. // this.doFav(item)
  18683. // }
  18684. // })
  18685. //加入下一首播放
  18686. Button() {
  18687. Image($r('app.media.next_to_play'))
  18688. .fillColor(Color.White)
  18689. .width(20)
  18690. }
  18691. .width(40)
  18692. .height(40)
  18693. .type(ButtonType.Circle)
  18694. .backgroundColor(this.themeColor)
  18695. .margin(5)
  18696. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18697. .onClick(() => {
  18698. this.addToNextPlay(item);
  18699. })
  18700. //复制文件
  18701. Button() {
  18702. Image($r('app.media.copy'))
  18703. .fillColor(Color.White)
  18704. .width(20)
  18705. }
  18706. .width(40)
  18707. .height(40)
  18708. .type(ButtonType.Circle)
  18709. .backgroundColor(this.themeColor)
  18710. .margin(5)
  18711. .id(filePath + 'copy')
  18712. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18713. .onClick(() => {
  18714. this.showCopyDialog(false, item, index, filePath + 'copy');
  18715. })
  18716. //移动文件
  18717. Button() {
  18718. Image($r('app.media.cut'))
  18719. .fillColor(Color.White)
  18720. .width(20)
  18721. }
  18722. .width(40)
  18723. .height(40)
  18724. .type(ButtonType.Circle)
  18725. .backgroundColor(this.themeColor)
  18726. .margin(5)
  18727. .id(filePath)
  18728. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18729. .onClick(() => {
  18730. this.showCutDialog(false, item, index, filePath);
  18731. })
  18732. Button() {
  18733. Image($r('app.media.cut_current'))
  18734. .fillColor(Color.White)
  18735. .width(20)
  18736. }
  18737. .width(40)
  18738. .height(40)
  18739. .type(ButtonType.Circle)
  18740. .backgroundColor(this.themeColor)
  18741. .margin(5)
  18742. .id(filePath + 'current')
  18743. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  18744. (this.isHasDir ? Visibility.Visible : Visibility.None))
  18745. .onClick(() => {
  18746. this.showCutDialog(true, item, index, filePath + 'current');
  18747. })
  18748. //重命名
  18749. // Button() {
  18750. // Image($r('app.media.rename2'))
  18751. // .fillColor(Color.White)
  18752. // .width(20)
  18753. // }
  18754. // .width(40)
  18755. // .height(40)
  18756. // .type(ButtonType.Circle)
  18757. // .backgroundColor(this.themeColor)
  18758. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18759. // (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18760. // item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18761. // .margin(5)
  18762. // .onClick(() => {
  18763. // this.showReNameDialog(item, index + '', filePath)
  18764. //
  18765. // })
  18766. Button() {
  18767. Image($r('app.media.delete2'))
  18768. .fillColor(Color.White)
  18769. .width(20)
  18770. }
  18771. .width(40)
  18772. .height(40)
  18773. .type(ButtonType.Circle)
  18774. .backgroundColor(this.themeColor)
  18775. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18776. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18777. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18778. .margin({ left:5,top:5,bottom:5,right:20} )
  18779. .onClick(() => {
  18780. this.selectSingleItemForDelete(item)
  18781. this.showWarnIsDelete()
  18782. // this.showWarnIsDeleteFile(item, index + '', filePath)
  18783. })
  18784. // Button() {
  18785. // Image($r('app.media.share2'))
  18786. // .fillColor(Color.White)
  18787. // .width(20)
  18788. // }
  18789. // .width(40)
  18790. // .height(40)
  18791. // .type(ButtonType.Circle)
  18792. // .backgroundColor(this.themeColor)
  18793. // .margin(5)
  18794. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18795. // .onClick(() => {
  18796. // Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  18797. // })
  18798. }
  18799. }
  18800. /**
  18801. * 穿山甲banner广告
  18802. */
  18803. // private declare bannerAd: CSJNativeExpressAd;
  18804. // @State private status: string = "未加载"
  18805. // @State private isShowAd: boolean = false
  18806. // private declare mAdSlot: AdSlot;
  18807. // private mBiddingAdm = '' //服务端bidding才需要设置
  18808. // private expressLoadAdListener: NativeExpressAdListener = {
  18809. // /**
  18810. // * 加载失败的回调
  18811. // *
  18812. // * @param code
  18813. // * @param message
  18814. // */
  18815. // onError: (code: number, message: string) => {
  18816. // console.error("加载广告失败,code=" + code + ",message=" + message);
  18817. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  18818. // },
  18819. //
  18820. // /**
  18821. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  18822. // *
  18823. // * @param ads 返回的广告列表
  18824. // */
  18825. //
  18826. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  18827. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  18828. // if (ads && ads.length > 0) {
  18829. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  18830. // ad.setExpressInteractionListener({
  18831. // /**
  18832. // *广告的点击回调
  18833. // * @param type 广告的交互类型
  18834. // */
  18835. // onAdClicked: (type: number) => {
  18836. // console.log("BannerExpressAdPage==onAdClicked......");
  18837. // },
  18838. //
  18839. // /**
  18840. // * 广告的展示回调 每个广告仅回调一次
  18841. // * @param type 广告的交互类型
  18842. // */
  18843. // onAdShow: (type: number) => {
  18844. // console.log("BannerExpressAdPage==onAdShow......");
  18845. // },
  18846. //
  18847. // /**
  18848. // * 模板渲染失败
  18849. // */
  18850. // onRenderFail: (code: number, msg: string) => {
  18851. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  18852. // },
  18853. //
  18854. // /**
  18855. // * 模板渲染成功
  18856. // * @param width 返回view的宽 单位 vp
  18857. // * @param height 返回view的高 单位 vp
  18858. // */
  18859. // onRenderSuccess: (width: number, height: number) => {
  18860. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  18861. // this.bannerAd = ad;
  18862. // this.status = "广告加载完成待展示";
  18863. //
  18864. // this.showBannerAd()
  18865. // }
  18866. // })
  18867. // //渲染广告
  18868. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  18869. // this.setDislikeCallback(ad); //设置dislike
  18870. // ad.render(this.getUIContext())
  18871. // this.status = "广告加载中...";
  18872. // });
  18873. // }
  18874. // }
  18875. // }
  18876. //
  18877. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  18878. // ad.setDislikeCallback({
  18879. // /**
  18880. // * dislike show
  18881. // */
  18882. // onShow: () => {
  18883. // console.log("BannerExpressAdPage==dislike......show");
  18884. // },
  18885. //
  18886. // /**
  18887. // * @param position 选择的位置
  18888. // * @param value 选择的内容
  18889. // * @param enforceRemove 是否强制关闭广告
  18890. // */
  18891. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  18892. // this.isShowAd = false;
  18893. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  18894. // ",enforce=" + enforceRemove);
  18895. // },
  18896. //
  18897. // /**
  18898. // * 点击取消
  18899. // */
  18900. // onCancel: () => {
  18901. // console.log("BannerExpressAdPage==dislike......onCancel");
  18902. // }
  18903. //
  18904. // })
  18905. // }
  18906. /**
  18907. * 加载Banner广告
  18908. */
  18909. loadBannerAd(rit: string) {
  18910. // if (Utility.isNoble()) {
  18911. // return
  18912. // }
  18913. // if (!Utility.isPassInstallTime(2)) {
  18914. // return
  18915. // }
  18916. // this.isShowAd = false;
  18917. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  18918. // this.mAdSlot = new AdSlotBuilder()
  18919. // .setCodeId(rit)
  18920. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  18921. // .setAdCount(1)
  18922. // .setBidAdm(this.mBiddingAdm)
  18923. // .build()
  18924. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  18925. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  18926. // this.status = "广告加载中..."
  18927. }
  18928. /**
  18929. * 展示Banner广告
  18930. */
  18931. // showBannerAd() {
  18932. // if (!this.bannerAd) {
  18933. // return
  18934. // }
  18935. // this.isShowAd = true
  18936. // this.status = "已展示"
  18937. // }
  18938. /**
  18939. * 穿山甲广告代码结束
  18940. */
  18941. /**
  18942. * 处理歌单播放请求
  18943. */
  18944. private syncWebdavQueueWithoutRestart(): void {
  18945. try {
  18946. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  18947. return;
  18948. }
  18949. const webdavList = getWebdavVideoItems();
  18950. if (!ArrayUtil.isNotEmpty(webdavList)) {
  18951. return;
  18952. }
  18953. const currentPath = this.currentSong.filePath;
  18954. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  18955. if (targetIndex < 0) {
  18956. const memoryIndex = getWebdavCurrentPlayIndex();
  18957. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  18958. targetIndex = memoryIndex;
  18959. }
  18960. }
  18961. if (targetIndex < 0) {
  18962. targetIndex = 0;
  18963. }
  18964. this.songList = [...webdavList];
  18965. this.currentSongList = [...webdavList];
  18966. this.sonDataSource.pushArrayData(this.songList);
  18967. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  18968. this.curIndex = targetIndex;
  18969. PreferencesUtil.putSync('LastMusicList', this.songList);
  18970. this.skipNextPlaylistPersist = true
  18971. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  18972. } catch (error) {
  18973. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  18974. }
  18975. }
  18976. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  18977. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  18978. try {
  18979. const totalCount = songCount ?? songFilePaths.length;
  18980. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  18981. // 检查是否为WebDAV播放请求
  18982. if (playlistId === 'webdav-playlist') {
  18983. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  18984. // 从全局内存读取videoItems数据
  18985. const videoItems = getWebdavVideoItems();
  18986. const currentPlayIndex = getWebdavCurrentPlayIndex();
  18987. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  18988. if (videoItems && videoItems.length > 0) {
  18989. // 验证webdav_account_id设置情况
  18990. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  18991. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  18992. if(isJump){
  18993. this.setShowPlayTrue()//显示播放页
  18994. }
  18995. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18996. return
  18997. } else {
  18998. return
  18999. }
  19000. }
  19001. if (playlistId === 'navidrome-playlist') {
  19002. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  19003. const videoItems = getNavidromeVideoItems();
  19004. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  19005. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  19006. if (videoItems && videoItems.length > 0) {
  19007. if(isJump){
  19008. this.setShowPlayTrue()//显示播放页
  19009. }
  19010. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  19011. return;
  19012. } else {
  19013. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  19014. return;
  19015. }
  19016. }
  19017. if (playlistId === 'find-album-playlist' || playlistId.indexOf('find-') === 0) {
  19018. Logger.info(`heanup 检测到发现页播放请求,从内存读取videoItems`)
  19019. const videoItems = getFindVideoItems();
  19020. const currentPlayIndex = getFindCurrentPlayIndex();
  19021. const findPlaylistMeta = getFindPlaylistMeta();
  19022. Logger.info(`heanup 发现页歌曲列表长度: ${videoItems.length}, 索引: ${currentPlayIndex}`)
  19023. Logger.info(
  19024. TAG,
  19025. `[remote-debug] handlePlaylistPlayRequest find-memory playlist=${playlistId}, loaded=${videoItems.length}, ` +
  19026. `declaredTotal=${totalCount}, sample=${this.buildSongListDebugLog(videoItems)}`
  19027. )
  19028. if (videoItems && videoItems.length > 0) {
  19029. if (isJump) {
  19030. this.setShowPlayTrue()
  19031. }
  19032. // 只有“随心所欲分页随机”才读取分页元数据,其他发现页队列仍按原有歌单模式处理。
  19033. const findMeta = isFindLocalRandomPagedPlaylist(playlistId) && findPlaylistMeta.isPagedLocalQueue
  19034. ? findPlaylistMeta
  19035. : undefined;
  19036. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount, findMeta)
  19037. return
  19038. } else {
  19039. Logger.warn('heanup 发现页播放请求缺少歌曲数据')
  19040. return
  19041. }
  19042. }
  19043. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  19044. const songMap: Map<number, VideoItem> = new Map()
  19045. let completedQueries = 0
  19046. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  19047. // 遍历所有文件路径,使用索引记录位置
  19048. for (let i = 0; i < songFilePaths.length; i++) {
  19049. const filePath = songFilePaths[i]
  19050. const index = i
  19051. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  19052. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  19053. const queryPromise = this.table.queryVideoByFilePath(filePath)
  19054. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  19055. queryPromise.then((videoItem) => {
  19056. completedQueries++
  19057. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  19058. if (videoItem) {
  19059. // 使用索引作为key保存到Map中,保持原始顺序
  19060. songMap.set(index, videoItem)
  19061. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  19062. } else {
  19063. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  19064. }
  19065. // 检查是否所有歌曲都已加载完成
  19066. if (completedQueries === songFilePaths.length) {
  19067. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  19068. // 按照索引顺序重建歌曲数组
  19069. const songs: VideoItem[] = []
  19070. for (let j = 0; j < songFilePaths.length; j++) {
  19071. const song = songMap.get(j)
  19072. if (song) {
  19073. songs.push(song)
  19074. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  19075. }
  19076. }
  19077. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  19078. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  19079. }
  19080. }).catch((error: Error) => {
  19081. completedQueries++
  19082. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  19083. // 即使出错也要检查是否完成所有查询
  19084. if (completedQueries === songFilePaths.length) {
  19085. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  19086. // 按照索引顺序重建歌曲数组
  19087. const songs: VideoItem[] = []
  19088. for (let j = 0; j < songFilePaths.length; j++) {
  19089. const song = songMap.get(j)
  19090. if (song) {
  19091. songs.push(song)
  19092. }
  19093. }
  19094. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  19095. }
  19096. })
  19097. }
  19098. } catch (error) {
  19099. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  19100. ToastUtil.showToast('播放失败')
  19101. }
  19102. }
  19103. /**
  19104. * 完成歌单加载并开始播放
  19105. */
  19106. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number,
  19107. findMeta?: FindPlaylistMeta) {
  19108. if (songs.length === 0) {
  19109. Logger.error('heanup 没有找到任何可播放的歌曲')
  19110. ToastUtil.showToast('没有找到可播放的歌曲')
  19111. return
  19112. }
  19113. const isFindPagedLocalQueue = !!findMeta?.isPagedLocalQueue;
  19114. this.songList = songs
  19115. this.currentSongList = songs // 同步更新 currentSongList
  19116. this.sonDataSource.pushArrayData(songs)
  19117. this.curIndex = startIndex
  19118. const actualTotal = totalCount ?? songs.length;
  19119. if (isFindPagedLocalQueue) {
  19120. // 这类队列只保存当前页歌曲,总数和分页游标放到独立状态里继续滚动加载。
  19121. this.applyFindPagedLocalQueueState(findMeta, actualTotal);
  19122. this.currentPlaylistSongFilePaths = [];
  19123. } else {
  19124. this.resetFindPagedLocalQueueState();
  19125. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  19126. }
  19127. // 如果是网盘播放,保存服务端总数到全局存储
  19128. if (!isFindPagedLocalQueue && totalCount && totalCount > 0 && songs.length > 0) {
  19129. const firstSong = songs[0];
  19130. if (firstSong && (isNavidromeType(firstSong.type) ||
  19131. isJellyfinType(firstSong.type) ||
  19132. isEmbyType(firstSong.type) ||
  19133. isAudioStationType(firstSong.type) ||
  19134. isPlexType(firstSong.type) ||
  19135. isDaoLiYuType(firstSong.type))) {
  19136. setNavidromeTotalCount(totalCount);
  19137. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  19138. }
  19139. }
  19140. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  19141. Logger.info(
  19142. TAG,
  19143. `[remote-debug] finishLoadingPlaylist playlist=${playlistName}, loaded=${songs.length}, actualTotal=${actualTotal}, ` +
  19144. `startIndex=${startIndex}, sample=${this.buildSongListDebugLog(songs)}`
  19145. );
  19146. if (songs[startIndex]) {
  19147. // 确保当前播放的歌曲也更新到存储
  19148. AppStorage.setOrCreate('currentSong', songs[startIndex])
  19149. if (isFindPagedLocalQueue) {
  19150. // 不要把发现页分页随机队列降级成普通歌单,否则后面又会触发全量 hydrate。
  19151. this.preserveExistingQueueOnNextPlay = true
  19152. this.nextPlayQueueScope = 'find_paged_local'
  19153. this.doPlay(songs[startIndex], startIndex, false)
  19154. } else {
  19155. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  19156. this.doPlay(songs[startIndex], startIndex, true)
  19157. }
  19158. }
  19159. PreferencesUtil.putSync('LastMusicList', this.songList)
  19160. this.skipNextPlaylistPersist = true
  19161. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  19162. }
  19163. }
  19164. //视频气泡窗口的布局
  19165. @Builder
  19166. function customPopupBuilder(dataBu: BubbleBean) {
  19167. List() {
  19168. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  19169. ListItem() {
  19170. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19171. Row() {
  19172. Column() {
  19173. Image(dataBu.imageRes[index])
  19174. .height(28)
  19175. .fillColor(dataBu.color)
  19176. .alignSelf(ItemAlign.Center)
  19177. }
  19178. .width(32)
  19179. Text(item)
  19180. .padding({
  19181. top: 10,
  19182. bottom: 10,
  19183. right: 10,
  19184. left: 10
  19185. })
  19186. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  19187. .textAlign(TextAlign.Start)
  19188. .width("100%")
  19189. }
  19190. }
  19191. .backgroundColor($r('app.color.settings_background_main'))
  19192. .margin({ top: 6, bottom: 6 })
  19193. }
  19194. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  19195. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  19196. TransitionEffect.scale({ x: 0, y: 0 })))
  19197. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  19198. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  19199. .onClick(() => {
  19200. dataBu.onItemClick?.(index)
  19201. })
  19202. })
  19203. }
  19204. .scrollBar(BarState.Off)
  19205. .width(120)
  19206. .divider({
  19207. strokeWidth: 1,
  19208. color: "#22FFFFFF"
  19209. })
  19210. }
  19211. // Function to calculate a hash for the file list
  19212. function simpleHash(fileList: string[]): string {
  19213. let hash = 0;
  19214. const str = fileList.join(',');
  19215. for (let i = 0; i < str.length; i++) {
  19216. const char = str.charCodeAt(i);
  19217. hash = (hash << 5) - hash + char;
  19218. hash |= 0; // Convert to 32bit integer
  19219. }
  19220. return hash.toString();
  19221. }
  19222. interface MoreItem {
  19223. id: number;
  19224. image: Resource;
  19225. title: string;
  19226. }
  19227. //视频气泡窗口的布局
  19228. @Builder
  19229. function cutPopupBuilder(dataBu: BubbleBean) {
  19230. Column() {
  19231. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  19232. .padding({
  19233. top: 10,
  19234. bottom: 10,
  19235. right: 10,
  19236. left: 10
  19237. })
  19238. .textAlign(TextAlign.Start)
  19239. .width(160)
  19240. .fontWeight(666)
  19241. .fontSize(16)
  19242. List() {
  19243. ForEach(dataBu.data, (item: string, index: number) => {
  19244. ListItem() {
  19245. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19246. Row() {
  19247. Column() {
  19248. Image($r('app.media.music_group'))
  19249. .height(28)
  19250. .fillColor(dataBu.color)
  19251. .alignSelf(ItemAlign.Center)
  19252. }
  19253. .width(32)
  19254. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  19255. .padding({
  19256. top: 10,
  19257. bottom: 10,
  19258. right: 10,
  19259. left: 10
  19260. })
  19261. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  19262. .fontSize(15)
  19263. }
  19264. }
  19265. .backgroundColor(Color.Transparent)
  19266. .margin({ top: 7, bottom: 7 })
  19267. }
  19268. .onClick(() => {
  19269. dataBu.onItemClick?.(index)
  19270. })
  19271. })
  19272. }
  19273. .scrollBar(BarState.Off)
  19274. .width(150)
  19275. .divider({
  19276. strokeWidth: 1,
  19277. color: "#22FFFFFF"
  19278. })
  19279. }
  19280. .height(300)
  19281. .padding({
  19282. bottom: 30
  19283. })
  19284. }
  19285. @Concurrent
  19286. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  19287. const alphabetSet = new Set<string>()
  19288. for (const item of items) {
  19289. let text = isShowFileName ? (item.fileName || '') :
  19290. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  19291. if (sortType === 0 || sortType == 1) {
  19292. text = item.artist || ''
  19293. } else if (sortType === 2 || sortType == 3) {
  19294. text = item.album || ''
  19295. }
  19296. if (text && text.length > 0) {
  19297. const first = getFirstLetter(text)
  19298. if (!alphabetSet.has(first)) {
  19299. alphabetSet.add(first)
  19300. }
  19301. }
  19302. }
  19303. const sorted = Array.from(alphabetSet).sort((a, b) => {
  19304. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  19305. return a.localeCompare(b)
  19306. }
  19307. return b.localeCompare(a)
  19308. })
  19309. return sorted
  19310. }
  19311. function getFileDirName(filePath: string,rootPath:string): string{
  19312. if(filePath===rootPath){
  19313. return '首页'
  19314. }
  19315. let result = FileUtil.getFileName(filePath)
  19316. if(StrUtil.isEmpty(result))
  19317. return ''
  19318. if(result.startsWith('.'))
  19319. result = result.replace(/\./g, '')
  19320. return result
  19321. }
  19322. //只扫描当前目录下文件(不扫描子文件夹)的方法
  19323. @Concurrent
  19324. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  19325. const table: MediaTable = new MediaTable(context);
  19326. try {
  19327. // 直接获取当前目录下的文件列表
  19328. const files = FileUtil.listFileSync(dirPath);
  19329. await Promise.all(files.map(async (file) => {
  19330. const fPath = `${dirPath}/${file}`;
  19331. // 跳过目录,只处理文件
  19332. if (FileUtil.isDirectory(fPath)) {
  19333. return;
  19334. }
  19335. // 跳过特定格式文件
  19336. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  19337. return;
  19338. }
  19339. // 检查是否为媒体文件
  19340. if (Utility.isMeidaByExtension(fPath)) {
  19341. let mType = CommonConstants.TYPE_LOCAL;
  19342. if (fPath.includes(lockPath)) {
  19343. mType = CommonConstants.TYPE_LOCK;
  19344. }
  19345. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  19346. context, fPath, mType, true
  19347. );
  19348. table.insert(mediaItem, (id: number) => {
  19349. // 插入回调函数
  19350. }, cover_api);
  19351. }
  19352. }));
  19353. } catch (error) {
  19354. console.error(' 扫描当前目录失败:', error);
  19355. }
  19356. }
  19357. //内嵌标签后更新库
  19358. @Concurrent
  19359. async function updateInfoDb(
  19360. context: Context,
  19361. filePath: string,
  19362. titleStr: string,
  19363. artistStr: string,
  19364. albumStr: string,
  19365. lyricConStr: string,
  19366. yearStr: string,
  19367. genreStr: string,
  19368. trackStr: string,
  19369. albumArtistStr: string,
  19370. composerStr: string,
  19371. lyricistStr: string,
  19372. commentStr: string,
  19373. discStr: string,
  19374. ): Promise<boolean> {
  19375. const table: MediaTable = new MediaTable(context);
  19376. await new Promise<void>((resolve, reject) => {
  19377. table.getRdbStore(context, (err:Error) => {
  19378. err ? reject(err) : resolve();
  19379. });
  19380. });
  19381. return await new Promise<boolean>((resolve) => {
  19382. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  19383. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  19384. (success: boolean, error?: string) => {
  19385. if (success) {
  19386. console.log("onecold 编辑信息成功,数据库已同步");
  19387. } else {
  19388. console.error("onecold 编辑信息数据库失败原因: " + error);
  19389. }
  19390. resolve(success);
  19391. });
  19392. });
  19393. }
  19394. @Concurrent
  19395. async function replaceLocalMusicCoverTask(
  19396. context: Context,
  19397. filePath: string,
  19398. sandboxCoverPath: string
  19399. ): Promise<boolean> {
  19400. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  19401. if (!coverResult) {
  19402. return false;
  19403. }
  19404. const table: MediaTable = new MediaTable(context);
  19405. await new Promise<void>((resolve, reject) => {
  19406. table.getRdbStore(context, (err: Error) => {
  19407. err ? reject(err) : resolve();
  19408. });
  19409. });
  19410. return await new Promise<boolean>((resolve) => {
  19411. table.updateCustomCoverPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  19412. (success: boolean, _error?: string) => {
  19413. resolve(success);
  19414. });
  19415. });
  19416. }