LocalMusic.ets 766 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362
  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. if(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath)){
  5430. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5431. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5432. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5433. .fillColor(this.themeColor)// .fontSize(33)
  5434. .alt($r('app.media.music_group'))
  5435. .borderRadius(this.isCoverRectangle?9:'100%')
  5436. .clip(true)
  5437. .shadow({
  5438. radius: 2,
  5439. type: ShadowType.BLUR,
  5440. color: 'on_primary'
  5441. })
  5442. .sourceSize({width:38, height:38})
  5443. .margin({ left: 20, top: 8, bottom: 8 })
  5444. }else{
  5445. SymbolGlyph($r('sys.symbol.folder'))
  5446. .fontSize(this.twoFingerType==3?55:this.twoFingerType==2?50:45)
  5447. .fontColor([this.themeColor])
  5448. .alignSelf(ItemAlign.Center)
  5449. .margin({ left: 20 ,top:8,bottom:8})
  5450. }
  5451. Column() {
  5452. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5453. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5454. .maxLines(1)// .width('88%')
  5455. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  5456. .margin({ left: 10, right: 20 })
  5457. .fontColor($r('app.color.text_color'))
  5458. Row() {
  5459. Text(`${this.getArtistSongCount(item.name)}首`)
  5460. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5461. .padding({ top: 8 })
  5462. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  5463. .fontColor($r('app.color.text_color'))
  5464. .margin({ left: 10 })
  5465. Text(`${this.getAlbumSongCount(item.name)}首`)
  5466. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5467. .padding({ top: 8 })
  5468. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  5469. .fontColor($r('app.color.text_color'))
  5470. .margin({ left: 10 })
  5471. Blank()
  5472. }
  5473. }
  5474. .height('100%')
  5475. .width('100%')
  5476. .justifyContent(FlexAlign.Center)
  5477. .alignItems(HorizontalAlign.Start)
  5478. Blank()
  5479. Checkbox({ name: 'dir_checkbox' + (index ?? -1) })
  5480. .select(this.isLocalItemSelected(item))
  5481. .selectedColor(this.themeColor)
  5482. .shape(CheckBoxShape.CIRCLE)
  5483. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5484. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible : Visibility.None)
  5485. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5486. .margin({ left: 20, top: 8, bottom: 8, right: 18 })
  5487. .width(22)
  5488. .height(22)
  5489. Image($r('app.media.arrow_right'))
  5490. .height(25)
  5491. .alignSelf(ItemAlign.Center)
  5492. .id(item.filePath)
  5493. .visibility(this.isShowAlphaBet || (this.isMultiSelect && this.isSelectableLocalItem(item)) ?
  5494. Visibility.None : Visibility.Visible)
  5495. }
  5496. }
  5497. .backgroundColor(Color.Transparent)
  5498. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5499. .width('98%')
  5500. .reuseId('dir_item')
  5501. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  5502. .opacity(this.opacityItem) // 绑定透明度
  5503. .onTouch((event: TouchEvent) => {
  5504. this.handlePointLightTouch(this.getPointLightItemKey('list_dir', item, index), event)
  5505. })
  5506. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5507. ? new hdsEffect.HdsEffectBuilder()
  5508. .pointLight({
  5509. options: this.getPointLightOptions(this.getPointLightItemKey('list_dir', item, index)),
  5510. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5511. })
  5512. .buildEffect()
  5513. : undefined)
  5514. }
  5515. private refreshDirVisibilitySettings(): void {
  5516. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  5517. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  5518. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  5519. }
  5520. isShowDir(dirName: string) {
  5521. if (dirName === undefined) {
  5522. return true
  5523. }
  5524. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  5525. return this.isShowSimi
  5526. }
  5527. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  5528. return this.isShowFAV
  5529. }
  5530. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  5531. return this.isShowHistory
  5532. }
  5533. return true
  5534. }
  5535. private getPointLightItemKey(prefix: string, item: VideoItem, index?: number): string {
  5536. const itemPath = StrUtil.isNotEmpty(item.filePath) ? item.filePath : `${item.name}_${index ?? -1}`
  5537. return `${prefix}_${itemPath}`
  5538. }
  5539. private handlePointLightTouch(itemKey: string, event: TouchEvent): void {
  5540. if (deviceInfo.sdkApiVersion < 20) {
  5541. return
  5542. }
  5543. if (event.type === TouchType.Down) {
  5544. this.activePointLightItemKey = itemKey
  5545. this.pointLightOptions = {
  5546. color: this.themeColor,
  5547. intensity: 1,
  5548. height: 60
  5549. }
  5550. return
  5551. }
  5552. if ((event.type === TouchType.Up || event.type === TouchType.Cancel) && this.activePointLightItemKey === itemKey) {
  5553. this.activePointLightItemKey = ''
  5554. this.pointLightOptions = undefined
  5555. }
  5556. }
  5557. private getPointLightOptions(itemKey: string): hdsEffect.PointLightOptions | undefined {
  5558. if (this.activePointLightItemKey !== itemKey) {
  5559. return undefined
  5560. }
  5561. return this.pointLightOptions
  5562. }
  5563. @State opacityItem: number = 1; // 控制透明度的状态变量
  5564. @Builder
  5565. private MusicItem(item: VideoItem, index?: number) {
  5566. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5567. Row() {
  5568. Stack() {
  5569. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5570. .fillColor(this.themeColor)
  5571. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5572. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5573. .alt($r('app.media.alt'))
  5574. .borderRadius(this.isCoverRectangle?9:'100%')
  5575. .clip(true)
  5576. .draggable(false)
  5577. .sourceSize({width:38, height:38})
  5578. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5579. // .autoResize(true) // 重采样,可减少内存占用
  5580. .opacity(this.opacityItem)// 绑定透明度
  5581. .margin({ left: 20 })
  5582. .shadow({
  5583. radius: this.isScrolling ? 0 : 10,
  5584. type: ShadowType.BLUR,
  5585. color: 'on_primary'
  5586. })
  5587. .onClick(()=>{
  5588. if (this.isMultiSelect) {
  5589. const isChecked = this.isLocalItemSelected(item);
  5590. this.handleFileSelection(item, !isChecked);
  5591. } else {
  5592. this.doPlay(item,index)
  5593. this.setShowPlayTrue()
  5594. }
  5595. })
  5596. }
  5597. Column() {
  5598. Column() {
  5599. Text(this.isShowFileName?item.fileName :item.name)
  5600. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5601. .maxLines(1)
  5602. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5603. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5604. $r('app.color.text_color'))
  5605. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5606. .padding({right:25})
  5607. .bindPopup(this.longItemFilePath === item.filePath, {
  5608. builder: this.MenuBuilder(item,index,item.filePath),
  5609. placement: Placement.Top,
  5610. // autoCancel: true,
  5611. mask: {color:'#33000000'},
  5612. // popupColor: Color.Yellow,
  5613. enableArrow: false,//是否显示箭头
  5614. showInSubWindow: false,
  5615. onStateChange: (e) => {
  5616. if (!e.isVisible) {
  5617. this.longItemFilePath = ''
  5618. this.tempLyricContent = ''
  5619. }
  5620. }
  5621. })
  5622. Row() {
  5623. Column(){
  5624. Text(item.md5Str?.includes('Lossless')?
  5625. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5626. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5627. .padding({ top: 3,right:6,left:6,bottom:3 })
  5628. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5629. $r('app.color.text_color'))
  5630. .fontWeight(500)
  5631. .borderRadius(12)
  5632. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  5633. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5634. .backgroundColor('#FFC107')
  5635. }
  5636. .padding({ top: 8 })
  5637. Text(StrUtil.isEmpty(item.artist) ? item.duration
  5638. :this.twoFingerType==2? item.artist +' ' + item.duration
  5639. : item.artist + ' ' + item?.duration)
  5640. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5641. .padding({ top: 8 ,right:25})
  5642. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  5643. .maxLines(1)
  5644. .opacity(0.85)
  5645. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  5646. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5647. $r('app.color.text_color'))
  5648. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5649. Blank()
  5650. Text(this.isShowFileName?item.duration:item.size)
  5651. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5652. .padding({ top: 8 })
  5653. .maxLines(1)
  5654. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  5655. ? Visibility.Visible : Visibility.None)
  5656. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5657. Color.Gray)
  5658. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  5659. }
  5660. }
  5661. .height('100%')
  5662. .width('100%')
  5663. .margin({ right: 10 })
  5664. .justifyContent(FlexAlign.Center)
  5665. .alignItems(HorizontalAlign.Start)
  5666. }
  5667. .height('100%')
  5668. .margin({ left: 5 })
  5669. .layoutWeight(1)
  5670. Column() {
  5671. Checkbox({ name: 'checkbox' + index })
  5672. .select(this.isLocalItemSelected(item))
  5673. .selectedColor(this.themeColor)
  5674. .shape(CheckBoxShape.CIRCLE)
  5675. .opacity(this.isMultiSelect ? 1 : 0)
  5676. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  5677. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5678. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  5679. .width(22)
  5680. .height(22)
  5681. PlayingIndicator({
  5682. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  5683. indicatorSize: 18,
  5684. marginRight: 20,
  5685. marginTop: 8,
  5686. marginBottom: 8
  5687. })
  5688. }
  5689. }
  5690. }
  5691. .gesture(LongPressGesture()
  5692. .onAction(async () => {
  5693. //如果是专辑和艺术家的首页,不能长按
  5694. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5695. return
  5696. //如果是我的收藏 最近播放等也不能长按
  5697. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5698. item.name === LocalMusic.STR_HISTORY_MUSIC
  5699. )
  5700. return
  5701. this.longItemFilePath = item.filePath
  5702. this.tempLyricContent = this.supportsLocalAudioActions(item) ? await this.getLyricContent(item) : ''
  5703. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5704. })
  5705. .onActionEnd((event: GestureEvent) => {
  5706. }))
  5707. .backgroundColor(Color.Transparent)
  5708. .width('100%')
  5709. .reuseId('file_item')
  5710. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5711. .onTouch((event: TouchEvent) => {
  5712. this.handlePointLightTouch(this.getPointLightItemKey('list_music', item, index), event)
  5713. })
  5714. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5715. ? new hdsEffect.HdsEffectBuilder()
  5716. .pointLight({
  5717. options: this.getPointLightOptions(this.getPointLightItemKey('list_music', item, index)),
  5718. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5719. })
  5720. .buildEffect()
  5721. : undefined)
  5722. }
  5723. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5724. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5725. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5726. direction: Direction.Ltr,
  5727. buttonPadding:{top:12,bottom:12},
  5728. backgroundColor: Color.Transparent,
  5729. fontSize:14,
  5730. selectedFontSize:15,
  5731. selectedFontColor:Color.White,
  5732. selectedBackgroundColor: this.themeColor,
  5733. localizedTextPadding: {
  5734. end: LengthMetrics.vp(20),
  5735. start: LengthMetrics.vp(20)
  5736. }
  5737. })
  5738. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5739. //当胶囊按钮的选择发生变化时调用此函数
  5740. capsuleSelectedIndexesChanged() {
  5741. this.modeType = this.tabSelectedIndexes[0]
  5742. }
  5743. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5744. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5745. isShowCoverHeader() {
  5746. if (!this.isShowHeader) {
  5747. return false
  5748. }
  5749. if (this.modeType == 0) {
  5750. if (this.isHistory || this.isFavMusic) {
  5751. return true
  5752. }
  5753. if (this.currentPath != this.rootPath) {
  5754. return true
  5755. }
  5756. }
  5757. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5758. }
  5759. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5760. if (this.isCustomizeBg) {
  5761. return ('rgba(255,255,255,0.2)')
  5762. }
  5763. if (this.isDarkMode) {
  5764. return $r('app.color.user_center_card_background')
  5765. }
  5766. return this.currentTitleCover
  5767. }
  5768. // 第二步:popup构造器定义弹框内容
  5769. @Builder popupBuilder() {
  5770. Column({ space: 2 }) {
  5771. Text('友情提示:双指缩放可以放大缩小列表')
  5772. .fontSize(12)
  5773. .fontWeight(FontWeight.Regular)
  5774. .fontColor($r('app.color.text_color'))
  5775. }
  5776. .justifyContent(FlexAlign.SpaceAround)
  5777. .width(220)
  5778. .height(55)
  5779. .padding(15)
  5780. }
  5781. //搜索功能的实现
  5782. @State searchText: string = ''; // 用户输入内容
  5783. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5784. @State isSearchMode: boolean = false
  5785. @State searchHistoryItems: string[] = []
  5786. private readonly searchHistoryScope: string = 'local_music'
  5787. private loadSearchHistory(): void {
  5788. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope)
  5789. }
  5790. private saveSearchHistory(keyword: string): void {
  5791. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword)
  5792. }
  5793. private commitSearchHistory(keyword: string): void {
  5794. const normalized = keyword.trim()
  5795. if (normalized.length === 0) {
  5796. return
  5797. }
  5798. this.saveSearchHistory(normalized)
  5799. }
  5800. private applySearchHistory(keyword: string): void {
  5801. this.searchText = keyword
  5802. this.searchController.stopEditing()
  5803. void this.onSearchInput(keyword)
  5804. }
  5805. // 实时搜索逻辑(带防抖)
  5806. private async onSearchInput(value: string): Promise<void> {
  5807. this.searchText = value.trim();
  5808. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5809. // 歌单模式不走媒体库分页查询,直接在当前歌单中筛选,避免混入非歌单歌曲并打乱顺序。
  5810. if (this.modeType === 4) {
  5811. if (this.searchText === '') {
  5812. this.loadSearchHistory()
  5813. this.filteredList = []
  5814. this.updateListData(this.currentSongList, true, true)
  5815. Logger.info('heanup LocalMusic', `onSearchInput: restore playlist list, count=${this.currentSongList.length}`)
  5816. return
  5817. }
  5818. if (!this.isSearchMode) {
  5819. this.isSearchMode = true
  5820. }
  5821. const filteredSongs = filterPlaylistSongsByKeyword(this.currentSongList, this.searchText)
  5822. this.filteredList = filteredSongs
  5823. this.updateListData(filteredSongs, true, true)
  5824. Logger.info('heanup LocalMusic', `onSearchInput: playlist filter applied, keyword="${this.searchText}", count=${filteredSongs.length}`)
  5825. return
  5826. }
  5827. // 清空搜索文本时保持搜索态,只重置为不带关键词的结果列表
  5828. if (this.searchText === '') {
  5829. this.loadSearchHistory()
  5830. await this.resetAndLoadFirstPage();
  5831. return;
  5832. }
  5833. // 进入搜索模式
  5834. if (!this.isSearchMode) {
  5835. this.isSearchMode = true;
  5836. }
  5837. // 使用数据库分页查询(带搜索条件)
  5838. await this.resetAndLoadFirstPage();
  5839. }
  5840. @Builder
  5841. private SearchHistoryView(): void {
  5842. Column({ space: 10 }) {
  5843. Row() {
  5844. Text('搜索历史')
  5845. .fontSize(14)
  5846. .fontWeight(FontWeight.Medium)
  5847. .fontColor($r('app.color.text_color'))
  5848. Blank()
  5849. Button('清空')
  5850. .fontSize(12)
  5851. .fontColor(this.themeColor)
  5852. .backgroundColor(Color.Transparent)
  5853. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  5854. .onClick(() => {
  5855. SearchHistoryUtil.clear(this.searchHistoryScope)
  5856. this.searchHistoryItems = []
  5857. })
  5858. }
  5859. .width('100%')
  5860. Flex({ wrap: FlexWrap.Wrap }) {
  5861. ForEach(this.searchHistoryItems, (keyword: string) => {
  5862. Button(keyword)
  5863. .fontSize(12)
  5864. .fontColor($r('app.color.text_color'))
  5865. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  5866. .borderRadius(16)
  5867. .margin({ right: 8, bottom: 8 })
  5868. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  5869. .onClick(() => {
  5870. this.applySearchHistory(keyword)
  5871. })
  5872. })
  5873. }
  5874. .width('100%')
  5875. }
  5876. .width('100%')
  5877. .padding({ left: 16, right: 16, top: 10, bottom: 10 })
  5878. }
  5879. @State dragItem: number = -1
  5880. @State scaleItem: number = -1
  5881. @State neighborItem: number = -1
  5882. @State neighborScale: number = -1
  5883. @State offsetY: number = 0
  5884. private dragRefOffset: number = 0
  5885. private ITEM_INTV: number = 78
  5886. scaleSelect(item: number): number {
  5887. if (this.scaleItem === item) {
  5888. return 1.05
  5889. } else if (this.neighborItem === item) {
  5890. return this.neighborScale
  5891. } else {
  5892. return 1
  5893. }
  5894. }
  5895. itemMove(index: number, newIndex: number): void {
  5896. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5897. return;
  5898. }
  5899. let tmp = this.videoLocalList.splice(index, 1);
  5900. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5901. this.dataSource.pushArrayData(this.videoLocalList)
  5902. if(this.modeType==4&&this.playlistTable){
  5903. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5904. }
  5905. }
  5906. //瀑布流布局 支持双指缩放
  5907. @State columns: number = 2;
  5908. @State waterFlowScale: number = 1;
  5909. @State imageScale: number = 1;
  5910. @State waterFlowOpacity: number = 1;
  5911. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5912. private columnChanged: boolean = false;
  5913. private oldColumn: number = this.columns;
  5914. private pinchTime: number = 0;
  5915. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5916. changeColumns(scale: number): void {
  5917. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5918. this.columns--;
  5919. this.columnChanged = true;
  5920. } else if (scale < 1 && this.columns < 4) {
  5921. this.columns++;
  5922. this.columnChanged = true;
  5923. }
  5924. }
  5925. @Builder
  5926. getWaterView(){
  5927. Scroll(this.scroller) {
  5928. Column() {
  5929. Blank().height(this.topSafeHeight + 55)
  5930. WaterFlow({
  5931. scroller:this.waterScroller,
  5932. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5933. }) {
  5934. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5935. FlowItem() {
  5936. this.MusicWaterCardItem(item,index)
  5937. }
  5938. .width('100%')
  5939. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5940. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5941. {
  5942. preview: MenuPreviewMode.IMAGE
  5943. })
  5944. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5945. {
  5946. preview: MenuPreviewMode.IMAGE
  5947. })
  5948. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5949. }
  5950. // .columnsTemplate('repeat(auto-fit, 160)')
  5951. .id('waterflow') // 设置id用于截图
  5952. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5953. .columnsGap(12) // 列间距
  5954. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5955. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5956. .padding({bottom:this.bottomBarHeight+10})
  5957. .scrollBar(BarState.Off)
  5958. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5959. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5960. .edgeEffect(EdgeEffect.None)
  5961. .width('90%')
  5962. .height('100%')
  5963. .opacity(this.waterFlowOpacity)
  5964. .scale({
  5965. x: this.waterFlowScale,
  5966. y: this.waterFlowScale,
  5967. centerX: 0,
  5968. centerY: 0
  5969. })
  5970. .onReachEnd(() => {
  5971. if(this.modeType === 4 )
  5972. return;
  5973. // 触底加载下一页
  5974. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5975. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5976. return;
  5977. }
  5978. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5979. this.scheduleLoadNextPage();
  5980. }
  5981. })
  5982. .onAppear(() => {
  5983. this.scroller.scrollEdge(Edge.Top)
  5984. })
  5985. .nestedScroll({
  5986. scrollForward: NestedScrollMode.PARENT_FIRST,
  5987. scrollBackward: NestedScrollMode.SELF_FIRST
  5988. })
  5989. .priorityGesture(
  5990. PinchGesture()
  5991. .onActionStart((event: GestureEvent) => {
  5992. // 双指捏合手势识别成功时截图
  5993. this.pinchTime = event.timestamp;
  5994. this.columnChanged = false;
  5995. this.oldColumn = this.columns;
  5996. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5997. if (error) {
  5998. console.info('error:' + JSON.stringify(error));
  5999. return;
  6000. }
  6001. this.waterFlowSnapshot = pixmap;
  6002. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  6003. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  6004. if (this.oldColumn ===4) {
  6005. this.twoFingerType =3
  6006. this.isGridMusic = true
  6007. }else if (this.oldColumn ===1) {
  6008. this.twoFingerType =1
  6009. this.isGridMusic = false
  6010. }
  6011. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6012. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6013. return;
  6014. }
  6015. })
  6016. })
  6017. .onActionUpdate((event: GestureEvent) => {
  6018. // 手势更新:处理缩放逻辑和视觉效果
  6019. // 边界限制:防止超出列数范围时继续缩放
  6020. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  6021. return;
  6022. }
  6023. // 节流处理:避免过于频繁的更新,提升性能
  6024. if (event.timestamp - this.pinchTime < 10000000) {
  6025. return;
  6026. }
  6027. this.pinchTime = event.timestamp;
  6028. this.waterFlowScale = event.scale;
  6029. this.imageScale = event.scale;
  6030. // 根据缩放比例设置WaterFlow透明度
  6031. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  6032. this.waterFlowOpacity *= 3;
  6033. if (!this.columnChanged) {
  6034. this.changeColumns(event.scale);
  6035. }
  6036. // 列数改变后的缩放比例调整:避免出现空白区域
  6037. if (this.columnChanged) {
  6038. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  6039. // 限制缩放范围,确保视觉效果自然
  6040. if (event.scale < 1) {
  6041. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  6042. } else {
  6043. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  6044. }
  6045. }
  6046. })
  6047. .onActionEnd((event: GestureEvent) => {
  6048. // 手势结束:执行归位动画并保存状态
  6049. // 执行归位动画:平滑过渡到正常状态
  6050. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  6051. this.waterFlowScale = 1;
  6052. this.waterFlowOpacity = 1;
  6053. })
  6054. // 持久化保存当前列数:下次启动时恢复
  6055. PreferencesUtil.putSync('lastColumns', this.columns);
  6056. })
  6057. )
  6058. .onScrollFrameBegin((offset: number) => {
  6059. this.markGridWaterScrollingActive()
  6060. // 获取当前滚动偏移量
  6061. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  6062. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  6063. this.updateTitleBarByScrollOffset(currentOffsetY)
  6064. return { offsetRemain: offset };
  6065. })
  6066. }
  6067. }
  6068. .scrollBar(BarState.Off)
  6069. }
  6070. //瀑布流卡片布局
  6071. @Builder
  6072. private MusicWaterCardItem(item: VideoItem, index: number) {
  6073. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6074. Stack() {
  6075. Column() {
  6076. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  6077. .backgroundImageSize(ImageSize.Auto)
  6078. .borderRadius({
  6079. topLeft: 12,
  6080. topRight : 12,
  6081. bottomLeft: 0,
  6082. bottomRight: 0
  6083. })
  6084. .draggable(false)// 禁止长按手势拖动
  6085. .autoResize(true) // 重采样,可减少内存占用
  6086. .sourceSize({
  6087. width: this.getCoverThumbTargetSize(true),
  6088. height: this.getCoverThumbTargetSize(true)
  6089. })
  6090. .width('100%')
  6091. .height('auto')
  6092. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6093. .objectFit(ImageFit.Cover)
  6094. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6095. height: '99%' ,
  6096. dragBar: true,
  6097. onDisappear: () => {
  6098. this.longItemFilePath = '';
  6099. this.tempLyricContent = ''
  6100. },
  6101. showClose: true,
  6102. preferType: SheetType.CENTER ,
  6103. title: { title: '编辑标签' }
  6104. })
  6105. .draggable(false)
  6106. .opacity(this.opacityItem)// 绑定透明度
  6107. .margin({
  6108. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6109. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6110. })
  6111. Column() {
  6112. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6113. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  6114. .maxLines(1)
  6115. .fontWeight(FontWeight.Bold)
  6116. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6117. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6118. height: '95%',
  6119. dragBar: true,
  6120. showClose: true,
  6121. onDisappear: () => {
  6122. this.longItemFilePathDetail = '';
  6123. },
  6124. blurStyle:BlurStyle.Thin,
  6125. backgroundColor:Color.Transparent,
  6126. preferType: SheetType.CENTER ,
  6127. title: { title: '详情' }
  6128. })
  6129. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6130. $r('app.color.text_color'))
  6131. Column() {
  6132. Text(`${this.getArtistSongCount(item.name)}首`)
  6133. .fontSize(11)
  6134. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6135. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6136. .fontColor($r('app.color.text_color'))
  6137. Text(`${this.getAlbumSongCount(item.name)}首`)
  6138. .fontSize(11)
  6139. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6140. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6141. .fontColor($r('app.color.text_color'))
  6142. Row(){
  6143. Column(){
  6144. Text(item.md5Str?.includes('Lossless')?
  6145. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6146. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  6147. .padding({ top: 3,right:6,left:6,bottom:3 })
  6148. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6149. $r('app.color.text_color'))
  6150. .fontWeight(500)
  6151. .borderRadius(12)
  6152. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6153. .backgroundColor('#FFC107')
  6154. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6155. }
  6156. .margin({ top: 2 ,right:6})
  6157. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6158. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6159. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6160. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  6161. .maxLines(1)
  6162. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  6163. .margin({ top: 2})
  6164. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6165. || item.type == CommonConstants.TYPE_IS_ALBUM
  6166. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6167. .fontWeight(FontWeight.Medium)
  6168. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6169. $r('app.color.text_color'))
  6170. }
  6171. }
  6172. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6173. }
  6174. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  6175. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  6176. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  6177. .width('100%')
  6178. .justifyContent(FlexAlign.Center)
  6179. .margin({
  6180. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6181. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6182. })
  6183. }
  6184. .width('100%')
  6185. .borderRadius(12)
  6186. .backgroundColor($r('app.color.com_bg'))
  6187. Checkbox({ name: 'checkbox' + index })
  6188. .select(this.isLocalItemSelected(item))
  6189. .selectedColor(this.themeColor)
  6190. .shape(CheckBoxShape.CIRCLE)
  6191. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6192. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6193. Visibility.None)
  6194. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6195. .margin({ left: 20, top: 8, bottom: 8 })
  6196. .width(38)
  6197. .height(38)
  6198. }
  6199. }
  6200. .backgroundColor(Color.Transparent)
  6201. .width('100%')
  6202. .height('auto')
  6203. .padding({top:2})
  6204. .shadow({
  6205. radius: this.isScrolling ? 0 : 8,
  6206. type: ShadowType.BLUR,
  6207. color: 'on_primary'
  6208. })
  6209. .reuseId('card_item')
  6210. .onTouch((event: TouchEvent) => {
  6211. this.handlePointLightTouch(this.getPointLightItemKey('water_music', item, index), event)
  6212. })
  6213. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6214. ? new hdsEffect.HdsEffectBuilder()
  6215. .pointLight({
  6216. options: this.getPointLightOptions(this.getPointLightItemKey('water_music', item, index)),
  6217. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6218. })
  6219. .buildEffect()
  6220. : undefined)
  6221. .onClick(() => {
  6222. if (this.isMultiSelect) {
  6223. if (this.isSelectableLocalItem(item)) {
  6224. const isChecked = this.isLocalItemSelected(item);
  6225. this.handleFileSelection(item, !isChecked);
  6226. }
  6227. return
  6228. }
  6229. this.doPlay(item, index)
  6230. })
  6231. }
  6232. // Grid布局的开始
  6233. private dragRefOffSetX: number = 0;
  6234. private dragRefOffSetY: number = 0;
  6235. private FIX_VP_X: number = 180;
  6236. private FIX_VP_Y: number = 84;
  6237. isDraggable(index: number): boolean {
  6238. return index >= 0;
  6239. }
  6240. getRowEnd(item: number) {
  6241. if (item.toString() === '0') {
  6242. return 1;
  6243. } else {
  6244. return 0;
  6245. }
  6246. }
  6247. isInLeft(index: number) {
  6248. return index % 2 == 0;
  6249. }
  6250. down(index: number): void {
  6251. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  6252. return;
  6253. }
  6254. this.offsetY -= this.FIX_VP_Y;
  6255. this.dragRefOffSetY += this.FIX_VP_Y;
  6256. this.itemMove(index, index + 1);
  6257. }
  6258. up(index: number): void {
  6259. if (!this.isDraggable(index - 2)) {
  6260. return;
  6261. }
  6262. this.offsetY += this.FIX_VP_Y;
  6263. this.dragRefOffSetY -= this.FIX_VP_Y;
  6264. this.itemMove(index, index - 1);
  6265. }
  6266. left(index: number): void {
  6267. if (this.isInLeft(index)) {
  6268. return;
  6269. }
  6270. if (!this.isDraggable(index - 1)) {
  6271. return;
  6272. }
  6273. this.offsetX += this.FIX_VP_X;
  6274. this.dragRefOffSetX -= this.FIX_VP_X;
  6275. this.itemMove(index, index - 1)
  6276. }
  6277. right(index: number): void {
  6278. if (!this.isInLeft(index)) {
  6279. return;
  6280. }
  6281. if (!this.isDraggable(index + 1)) {
  6282. return;
  6283. }
  6284. this.offsetX -= this.FIX_VP_X;
  6285. this.dragRefOffSetX += this.FIX_VP_X;
  6286. this.itemMove(index, index + 1)
  6287. }
  6288. private scroller: Scroller = new Scroller();
  6289. private waterScroller: Scroller = new Scroller();
  6290. private startIndex: number = 0
  6291. private endIndex: number = 0
  6292. @State scaleValue: number = 1
  6293. @State pinchValue: number = 1
  6294. layoutOptionsForHeader: GridLayoutOptions = {
  6295. regularSize: [1, 1], // 只支持[1, 1]
  6296. irregularIndexes: [0], // 索引为0的GridItem占用一行
  6297. };
  6298. @Builder
  6299. getGridView() {
  6300. Grid(this.scroller, this.layoutOptionsForHeader) {
  6301. GridItem() {
  6302. Column(){
  6303. Blank().height(this.topSafeHeight + 45)
  6304. }
  6305. }
  6306. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6307. GridItem() {
  6308. Stack() {
  6309. this.MusicItemGrid(item, index)
  6310. }
  6311. }
  6312. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  6313. {
  6314. preview: MenuPreviewMode.IMAGE
  6315. })
  6316. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  6317. {
  6318. preview: MenuPreviewMode.IMAGE
  6319. })
  6320. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  6321. // TransitionEffect.scale({ x: 0, y: 0 })))
  6322. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6323. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  6324. .zIndex(this.dragItem === index ? 1 : 0)
  6325. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  6326. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6327. }
  6328. .width('94%')
  6329. .height('100%')
  6330. .editMode(true)
  6331. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  6332. .reuseId('grid_item')
  6333. .layoutWeight(1)
  6334. .scrollBar(BarState.Off)
  6335. .supportAnimation(false)
  6336. .onReachEnd(() => {
  6337. if(this.modeType === 4 )
  6338. return;
  6339. // 触底加载下一页
  6340. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6341. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6342. return;
  6343. }
  6344. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6345. this.scheduleLoadNextPage();
  6346. }
  6347. })
  6348. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  6349. .columnsTemplate(
  6350. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  6351. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  6352. )
  6353. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  6354. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  6355. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6356. .gesture(PinchGesture({ fingers: 2 })
  6357. .onActionEnd((event: GestureEvent) => {
  6358. this.setGridTwoFingers()
  6359. })
  6360. .onActionUpdate(e => {
  6361. this.scaleValue = this.pinchValue * e.scale
  6362. })
  6363. .onActionStart(e => {
  6364. }))
  6365. .enableScrollInteraction(true)
  6366. .onScrollIndex((start: number, end: number) => {
  6367. this.startIndex = start
  6368. this.endIndex = end
  6369. this.gridVisibleStart = start
  6370. this.gridVisibleEnd = end
  6371. this.lastVisibleEndIndex = end
  6372. this.warmupGridWaterVisibleThumbs(start, end, false)
  6373. const now = Date.now()
  6374. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  6375. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  6376. this.gridScrollPagingCheckAt = now
  6377. this.gridScrollLastPagingEnd = end
  6378. this.tryTriggerLoadNextPageByScroll(end)
  6379. }
  6380. })
  6381. .onScrollFrameBegin((offset: number) => {
  6382. this.markGridWaterScrollingActive()
  6383. const currentOffsetY = this.scroller.currentOffset().yOffset;
  6384. this.updateTitleBarByScrollOffset(currentOffsetY)
  6385. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6386. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6387. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6388. if (this.isScrollHide) {
  6389. this.setBarHeightHide2(offset)
  6390. } else {
  6391. this.setBarHeightNormal()
  6392. }
  6393. } else {
  6394. this.setBarHeightHide(offset)
  6395. }
  6396. return { offsetRemain: offset };
  6397. })
  6398. }
  6399. @State targetFile: string = '';
  6400. setGridTwoFingers() {
  6401. this.pinchValue = this.scaleValue;
  6402. Logger.info('this.pinchValue = ' + this.pinchValue);
  6403. if (this.pinchValue >= 1) {
  6404. this.twoFingerType++
  6405. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6406. if(this.twoFingerType >= 4){
  6407. this.twoFingerType = 4//切换成瀑布流
  6408. this.columns = 4
  6409. }
  6410. } else {
  6411. this.twoFingerType--
  6412. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6413. if (this.twoFingerType < 1) {
  6414. this.twoFingerType = 3
  6415. this.isGridMusic = false
  6416. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6417. }
  6418. }
  6419. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6420. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6421. this.pinchValue = 1;
  6422. this.scaleValue = 1;
  6423. }
  6424. @State longItemFilePath: string = ''
  6425. @State tempLyricContent: string = ''
  6426. @State editingItem: VideoItem | null = null
  6427. @Builder
  6428. private MusicItemGrid(item: VideoItem, index: number) {
  6429. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6430. Stack() {
  6431. Column() {
  6432. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  6433. .height(this.getGridHeight())
  6434. .width(this.getGridWight())
  6435. .draggable(false)
  6436. .autoResize(true) // 重采样,可减少内存占用
  6437. .sourceSize({
  6438. width: this.getCoverThumbTargetSize(false),
  6439. height: this.getCoverThumbTargetSize(false)
  6440. })
  6441. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6442. .clip(true)
  6443. .borderRadius({
  6444. topLeft: 12,
  6445. topRight: 12,
  6446. bottomLeft: 0,
  6447. bottomRight: 0
  6448. })
  6449. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6450. height: '99%' ,
  6451. dragBar: true,
  6452. onDisappear: () => {
  6453. this.longItemFilePath = '';
  6454. this.tempLyricContent = ''
  6455. },
  6456. showClose: true,
  6457. preferType: SheetType.CENTER ,
  6458. title: { title: '编辑标签' }
  6459. })
  6460. .draggable(false)
  6461. .opacity(this.opacityItem)// 绑定透明度
  6462. .margin({
  6463. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6464. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6465. })
  6466. Column() {
  6467. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  6468. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6469. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  6470. .maxLines(1)
  6471. .fontWeight(FontWeight.Bold)
  6472. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6473. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6474. height: '100%',
  6475. dragBar: true,
  6476. showClose: true,
  6477. onDisappear: () => {
  6478. this.longItemFilePathDetail = '';
  6479. },
  6480. blurStyle:BlurStyle.Thin,
  6481. backgroundColor:Color.Transparent,
  6482. preferType: SheetType.CENTER ,
  6483. title: { title: '详情' }
  6484. })
  6485. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6486. $r('app.color.text_color'))
  6487. Column() {
  6488. Text(`${this.getArtistSongCount(item.name)}首`)
  6489. .fontSize(11)
  6490. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6491. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6492. .fontColor($r('app.color.text_color'))
  6493. Text(`${this.getAlbumSongCount(item.name)}首`)
  6494. .fontSize(11)
  6495. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6496. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6497. .fontColor($r('app.color.text_color'))
  6498. Row(){
  6499. Column(){
  6500. Text(item.md5Str?.includes('Lossless')?
  6501. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6502. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  6503. .padding({ top: 3,right:6,left:6,bottom:3 })
  6504. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6505. $r('app.color.text_color'))
  6506. .fontWeight(500)
  6507. .borderRadius(12)
  6508. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6509. .backgroundColor('#FFC107')
  6510. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6511. }
  6512. .margin({ top: 2 ,right:6})
  6513. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6514. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6515. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6516. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  6517. .maxLines(1)
  6518. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  6519. .margin({ top: 2})
  6520. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6521. || item.type == CommonConstants.TYPE_IS_ALBUM
  6522. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6523. .fontWeight(FontWeight.Medium)
  6524. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6525. $r('app.color.text_color'))
  6526. }
  6527. }
  6528. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6529. }
  6530. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  6531. .width(this.getGridWight())
  6532. .justifyContent(FlexAlign.Center)
  6533. .margin({
  6534. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6535. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6536. })
  6537. }
  6538. .width(this.getGridWight())
  6539. .borderRadius(12)
  6540. .backgroundColor($r('app.color.com_bg'))
  6541. Checkbox({ name: 'checkbox' + index })
  6542. .select(this.isLocalItemSelected(item))
  6543. .selectedColor(this.themeColor)
  6544. .shape(CheckBoxShape.CIRCLE)
  6545. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6546. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6547. Visibility.None)
  6548. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6549. .margin({ left: 20, top: 8, bottom: 8 })
  6550. .width(38)
  6551. .height(38)
  6552. }
  6553. }
  6554. .backgroundColor(Color.Transparent)
  6555. .width('100%')
  6556. .padding({ top: 15 })
  6557. .height(this.getGridAllHeight())
  6558. .onTouch((event: TouchEvent) => {
  6559. this.handlePointLightTouch(this.getPointLightItemKey('grid_music', item, index), event)
  6560. })
  6561. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6562. ? new hdsEffect.HdsEffectBuilder()
  6563. .pointLight({
  6564. options: this.getPointLightOptions(this.getPointLightItemKey('grid_music', item, index)),
  6565. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6566. })
  6567. .buildEffect()
  6568. : undefined)
  6569. .onClick(() => {
  6570. if (this.isMultiSelect) {
  6571. if (this.isSelectableLocalItem(item)) {
  6572. const isChecked = this.isLocalItemSelected(item);
  6573. this.handleFileSelection(item, !isChecked);
  6574. }
  6575. return
  6576. }
  6577. this.doPlay(item, index)
  6578. })
  6579. }
  6580. getGridAllHeight() {
  6581. let heightG = 222
  6582. switch (this.twoFingerType) {
  6583. case 1:
  6584. heightG = 143
  6585. break;
  6586. case 2:
  6587. heightG = 178
  6588. break;
  6589. case 3:
  6590. heightG = 222
  6591. break;
  6592. }
  6593. return heightG
  6594. }
  6595. getGridHeight() {
  6596. let heightG = 150
  6597. switch (this.twoFingerType) {
  6598. case 1:
  6599. heightG = 80
  6600. break;
  6601. case 2:
  6602. heightG = 110
  6603. break;
  6604. case 3:
  6605. heightG = 150
  6606. break;
  6607. }
  6608. return heightG
  6609. }
  6610. getGridWight() {
  6611. let wightG = 158
  6612. switch (this.twoFingerType) {
  6613. case 1:
  6614. wightG = 80
  6615. break;
  6616. case 2:
  6617. wightG = 110
  6618. break;
  6619. case 3:
  6620. wightG = 158
  6621. break;
  6622. }
  6623. return wightG
  6624. }
  6625. @State isShowDetail:boolean = false
  6626. @State longItemFilePathDetail:string =''
  6627. @Builder
  6628. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  6629. if(
  6630. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  6631. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6632. item.name === LocalMusic.STR_HISTORY_MUSIC)
  6633. ){
  6634. //如果是专辑和艺术家的首页,不能长按
  6635. //如果是我的收藏 最近播放等也不能长按
  6636. }else{
  6637. Scroll() {
  6638. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  6639. Menu() {
  6640. MenuItem({
  6641. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  6642. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  6643. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  6644. })
  6645. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6646. .onClick(() => {
  6647. if (item) {
  6648. this.doFav(item)
  6649. }
  6650. this.longItemFilePath = ''
  6651. })
  6652. MenuItem({
  6653. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  6654. content: '下一首播放'
  6655. })
  6656. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6657. .onClick(() => {
  6658. this.addToNextPlay(item);
  6659. this.longItemFilePath = ''
  6660. })
  6661. MenuItem({
  6662. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6663. content: '添加到歌单'
  6664. })
  6665. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6666. .onClick(async () => {
  6667. this.longItemFilePath = ''
  6668. await this.openAddToPlaylistDialog(item)
  6669. })
  6670. MenuItem({
  6671. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  6672. content: '编辑标签'
  6673. })
  6674. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  6675. height: '99%',
  6676. dragBar: true,
  6677. showClose: true,
  6678. preferType: SheetType.CENTER ,
  6679. title: { title: '编辑标签' }
  6680. })
  6681. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6682. .onClick(async() => {
  6683. this.initEditFields(item)
  6684. this.tempLyricContent = await this.getLyricContent(item);
  6685. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  6686. this.lyricConStr = this.tempLyricContent
  6687. }
  6688. if(this.isGridMusic||this.twoFingerType==4){
  6689. this.longItemFilePath = item.filePath
  6690. }else{
  6691. this.isShowEdit = !this.isShowEdit;
  6692. }
  6693. })
  6694. MenuItem({
  6695. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  6696. content: $r('app.string.select_all')
  6697. })
  6698. .onClick(() => {
  6699. this.longItemFilePath = ''
  6700. this.enterLocalMultiSelect(item)
  6701. })
  6702. MenuItem({
  6703. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6704. content: '提取ISO文件'
  6705. })
  6706. .visibility(this.isIsoLocalFile(item) ? Visibility.Visible : Visibility.None)
  6707. .onClick(async () => {
  6708. this.longItemFilePath = ''
  6709. await this.openIsoArchiveDialog(item)
  6710. })
  6711. MenuItem({
  6712. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  6713. content: $r('app.string.edit_audio')
  6714. })
  6715. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  6716. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6717. })
  6718. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6719. .onClick(() => {
  6720. this.isEditAudio = !this.isEditAudio
  6721. })
  6722. MenuItem({
  6723. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  6724. content: $r('app.string.extract_accompaniment')
  6725. })
  6726. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  6727. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6728. })
  6729. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6730. .onClick(() => {
  6731. if (!Utility.isNoble()) {
  6732. this.showVipDialog()
  6733. return
  6734. }
  6735. this.isExtractAcc = !this.isExtractAcc
  6736. })
  6737. MenuItem({
  6738. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  6739. content: $r('app.string.converter_audio')
  6740. })
  6741. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  6742. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6743. })
  6744. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6745. .onClick(() => {
  6746. if (!Utility.isNoble()) {
  6747. this.showVipDialog()
  6748. return
  6749. }
  6750. this.isConverter = !this.isConverter
  6751. })
  6752. // MenuItem({
  6753. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  6754. // content: $r('app.string.vocal_separation')
  6755. // })
  6756. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  6757. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6758. // })
  6759. // .onClick(() => {
  6760. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  6761. // })
  6762. MenuItem({
  6763. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  6764. content: $r('app.string.change_tone')
  6765. })
  6766. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  6767. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6768. })
  6769. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6770. .onClick(() => {
  6771. this.isChangeTone = !this.isChangeTone
  6772. })
  6773. if(Utility.isVideoByExtension(item.filePath)){
  6774. MenuItem({
  6775. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  6776. content: $r('app.string.extract_audio')
  6777. })
  6778. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  6779. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6780. })
  6781. .onClick(() => {
  6782. this.isExtractAudio = !this.isExtractAudio
  6783. })
  6784. }
  6785. MenuItem({
  6786. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  6787. content: $r('app.string.set_ring')
  6788. })
  6789. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6790. .onClick(async () => {
  6791. await PermissionUtil.activatePermission(item.filePath)
  6792. // if(item.filePath.includes(this.packName)){
  6793. setRingTone(this.context, item.filePath,item.name)
  6794. // }else{
  6795. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  6796. // }
  6797. this.longItemFilePath = ''
  6798. })
  6799. MenuItem({
  6800. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  6801. content: $r('app.string.rename')
  6802. })
  6803. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6804. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6805. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6806. .onClick(() => {
  6807. this.showReNameDialog(item, index + '', filePath)
  6808. this.longItemFilePath = ''
  6809. })
  6810. MenuItem({
  6811. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  6812. content: $r('app.string.delete')
  6813. })
  6814. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6815. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6816. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6817. .onClick(() => {
  6818. this.selectSingleItemForDelete(item)
  6819. this.showWarnIsDelete()
  6820. this.longItemFilePath = ''
  6821. })
  6822. MenuItem({
  6823. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6824. content: $r('app.string.detail')
  6825. })
  6826. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6827. height:'100%',
  6828. dragBar: true,
  6829. showClose: true,
  6830. blurStyle:BlurStyle.Thin,
  6831. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6832. backgroundColor:Color.Transparent,
  6833. title: { title: '详情信息' }
  6834. })
  6835. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6836. .onClick(() => {
  6837. if(this.isGridMusic||this.twoFingerType==4){
  6838. this.longItemFilePathDetail = item.filePath
  6839. }else{
  6840. this.isShowDetail = !this.isShowDetail
  6841. }
  6842. })
  6843. MenuItem({
  6844. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6845. content: $r('app.string.share')
  6846. })
  6847. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6848. .onClick(() => {
  6849. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6850. this.longItemFilePath = ''
  6851. })
  6852. }
  6853. .font({ size: 14, weight: FontWeight.Normal })
  6854. }
  6855. .width(180)
  6856. }
  6857. .height('auto')
  6858. .enableScrollInteraction(true)
  6859. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6860. }
  6861. }
  6862. private listMaxScrollOffsetY: number = 0
  6863. private selectedIndex: number = -1
  6864. setlistTwoFingers() {
  6865. this.pinchValue = this.scaleValue;
  6866. Logger.info('this.pinchValue = ' + this.pinchValue);
  6867. if (this.pinchValue >= 1) {
  6868. this.twoFingerType++
  6869. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6870. if (this.twoFingerType > 3) {
  6871. this.twoFingerType = 1
  6872. this.isGridMusic = true
  6873. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6874. }
  6875. } else {
  6876. this.twoFingerType--
  6877. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6878. if (this.twoFingerType < 1) {
  6879. this.twoFingerType = 4
  6880. this.columns = 1
  6881. }
  6882. }
  6883. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6884. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6885. this.pinchValue = 1;
  6886. this.scaleValue = 1;
  6887. }
  6888. @Builder
  6889. getList(){
  6890. Stack() {
  6891. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6892. this.getListView()
  6893. }
  6894. .pullDownRatio(this.ratioL)
  6895. .pullToRefresh(true)
  6896. .refreshOffset(0)
  6897. .onOffsetChange((offset: number) => {
  6898. // 越接近最大距离,下拉跟手系数越小。
  6899. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6900. })
  6901. .onStateChange((refreshStatus: RefreshStatus) => {
  6902. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6903. })
  6904. .onRefreshing(async () => {
  6905. if(this.modeType==0){
  6906. this.getHistoryList(false)
  6907. this.asyncCurrentPathOnlyFile()
  6908. }else if(this.modeType == 1){
  6909. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6910. }else if(this.modeType == 2){
  6911. workerInstance.postMessage({ code: 3, data: this.context });
  6912. }else if(this.modeType == 3){
  6913. workerInstance.postMessage({ code: 4, data: this.context });
  6914. }else if(this.modeType == 4){
  6915. this.doSongListTask()
  6916. }
  6917. console.log('onRefreshing test');
  6918. })
  6919. if (this.isLoadingPage) {
  6920. Row() {
  6921. LoadingProgress()
  6922. .width(24)
  6923. .height(24)
  6924. .color(this.themeColor)
  6925. Text('加载中...')
  6926. .margin({ left: 8 })
  6927. .fontSize(13)
  6928. .fontColor($r('app.color.text_color'))
  6929. }
  6930. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6931. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6932. .borderRadius(16)
  6933. .align(Alignment.Bottom)
  6934. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6935. }
  6936. }
  6937. }
  6938. // 扫描当前目录下的文件,不扫描子目录
  6939. asyncCurrentPathOnlyFile(){
  6940. if(this.modeType==0){
  6941. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6942. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6943. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6944. if(this.modeType==0){
  6945. setTimeout(()=>{
  6946. this.isRefreshing =false
  6947. this.deleteCache(this.currentPath)
  6948. this.getSortedFiles(this.currentPath)
  6949. },500)
  6950. }
  6951. }).catch((e:object)=>{
  6952. this.isRefreshing =false
  6953. console.info("onecold task1 catch e: " + e);
  6954. })
  6955. }
  6956. }
  6957. @Builder
  6958. getListView() {
  6959. List({ scroller: this.listScroller }) {
  6960. // ListItemGroup({ header: this.coverHeader() }) {
  6961. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6962. ListItem() {
  6963. Column() {
  6964. if (item.type === CommonConstants.TYPE_IS_DIR
  6965. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6966. this.DirItem(item, index)
  6967. } else {
  6968. this.MusicItem(item, index)
  6969. }
  6970. }
  6971. }
  6972. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6973. .swipeAction((
  6974. ((this.isSwipe && !this.isScrolling) &&
  6975. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6976. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6977. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6978. edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6979. .onClick(() => {
  6980. if (this.isMultiSelect) {
  6981. if (this.isSelectableLocalItem(item)) {
  6982. const isChecked = this.isLocalItemSelected(item);
  6983. this.handleFileSelection(item, !isChecked);
  6984. }
  6985. return
  6986. }
  6987. this.doPlay(item, index)
  6988. })
  6989. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6990. }
  6991. .onScrollStart(() => {
  6992. this.isScrolling = true
  6993. this.listVisibleStart = -1
  6994. this.listVisibleEnd = -1
  6995. this.listScrollAlphaCheckAt = 0
  6996. this.listScrollPagingCheckAt = 0
  6997. this.listScrollLastAlphaStart = -1
  6998. this.listScrollLastPagingEnd = -1
  6999. if (this.alphaBetRebuildTimer) {
  7000. clearTimeout(this.alphaBetRebuildTimer)
  7001. this.alphaBetRebuildTimer = 0
  7002. }
  7003. this.showAlphabetIndex()
  7004. })
  7005. .onScrollIndex((start: number,center:number,end:number) => {
  7006. this.selectedIndex = start
  7007. this.listVisibleStart = start
  7008. this.listVisibleEnd = end
  7009. this.lastVisibleEndIndex = end
  7010. if (!this.isMediaLibraryWarmupWindow()) {
  7011. this.warmupListVisibleThumbs(start, end)
  7012. }
  7013. const now = Date.now()
  7014. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  7015. if (!this.isMediaLibraryWarmupWindow() &&
  7016. start >= 0 && start < this.videoLocalList.length &&
  7017. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  7018. this.listScrollAlphaCheckAt = now
  7019. this.listScrollLastAlphaStart = start
  7020. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  7021. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  7022. this.selectAlphaBetIndex = nextAlphaIndex
  7023. }
  7024. }
  7025. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  7026. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  7027. this.listScrollPagingCheckAt = now
  7028. this.listScrollLastPagingEnd = end
  7029. this.tryTriggerLoadNextPageByScroll(end)
  7030. }
  7031. })
  7032. .onScrollStop(() => {
  7033. if(this.isScrolling){
  7034. this.isScrolling = false
  7035. }
  7036. this.flushPendingCoverThumbRefresh()
  7037. if (this.alphaBetDirty) {
  7038. this.scheduleAlphaBetRebuild(0)
  7039. }
  7040. this.hideAlphabetIndexAfterDelay(1500)
  7041. })
  7042. .onReachEnd(() => {
  7043. if(this.modeType === 4 )//歌单不能加载下一页
  7044. return;
  7045. // 触底加载下一页
  7046. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  7047. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  7048. return;
  7049. }
  7050. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  7051. this.scheduleLoadNextPage();
  7052. }
  7053. })
  7054. .scrollBar(BarState.Off)
  7055. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7056. .gesture(PinchGesture({ fingers: 2 })
  7057. .onActionEnd((event: GestureEvent) => {
  7058. this.setlistTwoFingers()
  7059. })
  7060. .onActionUpdate(e => {
  7061. this.scaleValue = this.pinchValue * e.scale
  7062. })
  7063. .onActionStart(e => {
  7064. }))
  7065. .contentStartOffset(this.topSafeHeight + 55)
  7066. .scrollBar(BarState.Off)
  7067. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  7068. .cachedCount(this.modeType == 1 ? 4 : 8)
  7069. // .reuseId('list_item')
  7070. .borderRadius(20)
  7071. .layoutWeight(1)
  7072. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  7073. .lanes(
  7074. new BreakpointType<number>({
  7075. sm: 1,
  7076. md: 2,
  7077. lg: 2,
  7078. xl: 3,
  7079. xxl: 4
  7080. }).getValue(this.currentBreakpoint),
  7081. new BreakpointType<number>({
  7082. sm: 0,
  7083. md: 12,
  7084. lg: 12,
  7085. xl: 16,
  7086. xxl: 20
  7087. }).getValue(this.currentBreakpoint)
  7088. )
  7089. .onAreaChange((oldValue: Area, newValue: Area) => {
  7090. this.listArea = newValue
  7091. if (this.twoFingerType == 3) {
  7092. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  7093. } else if (this.twoFingerType == 2) {
  7094. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  7095. } else if (this.twoFingerType == 1) {
  7096. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  7097. }
  7098. })
  7099. .onScrollFrameBegin((offset: number) => {
  7100. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  7101. this.updateTitleBarByScrollOffset(currentOffsetY)
  7102. return { offsetRemain: offset };
  7103. })
  7104. }
  7105. setBarHeightNormal() {
  7106. this.hideDone = false;
  7107. this.getUIContext().animateTo({
  7108. duration: 300
  7109. }, () => {
  7110. this.bottomBarHeight = 68 + 0;
  7111. this.topBarHeight = 50 + 0;
  7112. this.barOpacity = 1;
  7113. this.barBottomOpacity = 1
  7114. this.currentYOffset = 0;
  7115. this.isHiding = false;
  7116. });
  7117. }
  7118. setBarHeightHide(offset: number) {
  7119. if (offset > 0 && !this.hideDone) {
  7120. this.currentYOffset += offset;
  7121. if (this.currentYOffset <= 100) {
  7122. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  7123. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7124. this.barOpacity = 1 - this.currentYOffset / 100;
  7125. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  7126. } else {
  7127. this.topBarHeight = 0;
  7128. this.bottomBarHeight = 0;
  7129. this.barBottomOpacity = 0
  7130. this.barOpacity = 0;
  7131. this.hideDone = true;
  7132. }
  7133. this.isHiding = true;
  7134. }
  7135. if (offset < 0 && this.isHiding) {
  7136. this.hideDone = false;
  7137. this.getUIContext().animateTo({
  7138. duration: 300
  7139. }, () => {
  7140. this.bottomBarHeight = 68 + 0;
  7141. this.topBarHeight = 50 + 0;
  7142. this.barOpacity = 1;
  7143. this.barBottomOpacity = 1
  7144. this.currentYOffset = 0;
  7145. this.isHiding = false;
  7146. });
  7147. }
  7148. }
  7149. //这个方法没隐藏bottomBar,只隐藏topbar
  7150. setBarHeightHide2(offset: number) {
  7151. if (offset > 0 && !this.hideDone) {
  7152. this.currentYOffset += offset;
  7153. if (this.currentYOffset <= 100) {
  7154. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7155. this.barOpacity = 1 - this.currentYOffset / 100;
  7156. } else {
  7157. this.topBarHeight = 0;
  7158. this.barOpacity = 0;
  7159. this.hideDone = true;
  7160. }
  7161. this.isHiding = true;
  7162. }
  7163. if (offset < 0 && this.isHiding) {
  7164. this.hideDone = false;
  7165. this.getUIContext().animateTo({
  7166. duration: 300
  7167. }, () => {
  7168. this.topBarHeight = 50 + 0;
  7169. this.barOpacity = 1;
  7170. this.currentYOffset = 0;
  7171. this.isHiding = false;
  7172. });
  7173. }
  7174. }
  7175. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  7176. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  7177. switch (item.type) {
  7178. case CommonConstants.TYPE_IS_DIR:
  7179. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  7180. let shouldScrollTopNow = true
  7181. let offsetB = 0
  7182. if(this.twoFingerType==4){
  7183. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7184. let cur = this.waterScroller.currentOffset()
  7185. if (cur && typeof cur.yOffset === 'number') {
  7186. offsetB = cur.yOffset
  7187. }
  7188. }
  7189. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  7190. }else
  7191. if (this.isGridMusic) {
  7192. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7193. let cur = this.scroller.currentOffset()
  7194. if (cur && typeof cur.yOffset === 'number') {
  7195. offsetB = cur.yOffset
  7196. }
  7197. }
  7198. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  7199. } else {
  7200. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7201. let cur = this.listScroller.currentOffset()
  7202. if (cur && typeof cur.yOffset === 'number') {
  7203. offsetB = cur.yOffset
  7204. }
  7205. }
  7206. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  7207. }
  7208. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  7209. this.showVerifyDialog()
  7210. this.currentTitleName = '私密音频'
  7211. this.currentTitleCover = $r('app.media.alt')
  7212. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  7213. this.titleName = '最近播放'
  7214. this.currentTitleCover = $r('app.media.alt')
  7215. this.currentTitleName = '最近播放'
  7216. //加载动画效果
  7217. this.updateListData(this.historyList, true)
  7218. // this.videoLocalList = this.historyList
  7219. if (ArrayUtil.isEmpty(this.historyList)) {
  7220. ToastUtil.showToast('最近播放记录空空如也')
  7221. } else {
  7222. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  7223. }
  7224. this.isHistory = true
  7225. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  7226. this.titleName = '我的收藏'
  7227. this.currentTitleName = '我的收藏'
  7228. this.currentTitleCover = $r('app.media.alt')
  7229. //加载动画效果
  7230. this.updateListData(this.favList, true)
  7231. if (ArrayUtil.isEmpty(this.favList)) {
  7232. ToastUtil.showToast('无音乐收藏记录')
  7233. } else {
  7234. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  7235. }
  7236. this.isFavMusic = true
  7237. } else {
  7238. this.currentTitleName = item.name
  7239. this.currentPath = item.filePath
  7240. this.currentTitleCover = $r('app.media.alt')
  7241. shouldScrollTopNow = false
  7242. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  7243. }
  7244. //进入歌单的时候的滚动位置在顶部
  7245. if (shouldScrollTopNow) {
  7246. if(this.twoFingerType==4){
  7247. setTimeout(() => {
  7248. this.waterScroller.scrollEdge(Edge.Top)
  7249. this.scroller.scrollEdge(Edge.Top)
  7250. }, 200)
  7251. }else{
  7252. if (this.isGridMusic) {
  7253. this.scroller.scrollToIndex(0,false)
  7254. }else{
  7255. this.listScroller.scrollToIndex(0,false)
  7256. }
  7257. }
  7258. }
  7259. this.rightTopImage = $r('sys.symbol.chevron_left')
  7260. break;
  7261. case CommonConstants.TYPE_IS_ARTIST:
  7262. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  7263. let offsetA = 0
  7264. if(this.twoFingerType==4){
  7265. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7266. let cur = this.waterScroller.currentOffset()
  7267. if (cur && typeof cur.yOffset === 'number') {
  7268. offsetA = cur.yOffset
  7269. }
  7270. }
  7271. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  7272. }else
  7273. if (this.isGridMusic) {
  7274. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7275. let cur = this.scroller.currentOffset()
  7276. if (cur && typeof cur.yOffset === 'number') {
  7277. offsetA = cur.yOffset
  7278. }
  7279. }
  7280. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  7281. } else {
  7282. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7283. let cur = this.listScroller.currentOffset()
  7284. if (cur && typeof cur.yOffset === 'number') {
  7285. offsetA = cur.yOffset
  7286. }
  7287. }
  7288. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  7289. }
  7290. // 进入艺术家详情页前,先加载详情页的排序类型
  7291. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7292. const artistOriginalIsCanBack = this.isCanBack;
  7293. this.isCanBack = true;
  7294. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  7295. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  7296. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  7297. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7298. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  7299. let mList = this.artistMap.get(artistCacheKey)
  7300. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  7301. // 使用详情页的排序类型查询
  7302. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  7303. if (ArrayUtil.isNotEmpty(mList)) {
  7304. this.artistMap.set(artistCacheKey, mList);
  7305. }
  7306. }
  7307. // 设置当前排序类型为详情页排序
  7308. this.sortType = artistDetailSortType;
  7309. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  7310. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  7311. const nextArtistCountMap = new Map(this.artistSongCountMap);
  7312. nextArtistCountMap.set(item.name, mList.length);
  7313. this.artistSongCountMap = nextArtistCountMap;
  7314. this.isCanBack = true
  7315. this.hasMoreData = false
  7316. this.isLoadingPage = false
  7317. this.pageCache.clear()
  7318. this.pageHasMoreCache.clear()
  7319. this.pageTotalCountCache.clear()
  7320. this.prefetchingPages.clear()
  7321. this.lastScrollTriggerPage = -1
  7322. this.lastVisibleEndIndex = -1
  7323. this.isPagingTransition = false
  7324. if (this.pagingScheduleTimer) {
  7325. clearTimeout(this.pagingScheduleTimer)
  7326. this.pagingScheduleTimer = 0
  7327. }
  7328. this.totalCount = mList.length
  7329. this.titleName = item.name
  7330. this.currentTitleName = '艺术家:' + item.name
  7331. if (item.pixelMapPath) {
  7332. this.currentTitleCover = item.pixelMapPath
  7333. }
  7334. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7335. } else {
  7336. ToastUtil.showToast('未找到该艺术家的歌曲');
  7337. return;
  7338. }
  7339. this.rightTopImage = $r('sys.symbol.chevron_left')
  7340. //进入歌单的时候的滚动位置在顶部
  7341. if(this.twoFingerType==4){
  7342. setTimeout(() => {
  7343. this.waterScroller.scrollEdge(Edge.Top)
  7344. this.scroller.scrollEdge(Edge.Top)
  7345. }, 380)
  7346. }else{
  7347. if (this.isGridMusic) {
  7348. this.scroller.scrollEdge(Edge.Top)
  7349. }else{
  7350. this.listScroller.scrollEdge(Edge.Top)
  7351. }
  7352. }
  7353. break;
  7354. case CommonConstants.TYPE_IS_ALBUM:
  7355. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  7356. let offset = 0
  7357. if(this.twoFingerType==4){
  7358. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7359. let cur = this.waterScroller.currentOffset()
  7360. if (cur && typeof cur.yOffset === 'number') {
  7361. offset = cur.yOffset
  7362. }
  7363. }
  7364. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  7365. }else
  7366. if (this.isGridMusic) {
  7367. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7368. let cur = this.scroller.currentOffset()
  7369. if (cur && typeof cur.yOffset === 'number') {
  7370. offset = cur.yOffset
  7371. }
  7372. }
  7373. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  7374. } else {
  7375. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7376. let cur = this.listScroller.currentOffset()
  7377. if (cur && typeof cur.yOffset === 'number') {
  7378. offset = cur.yOffset
  7379. }
  7380. }
  7381. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  7382. }
  7383. // 进入专辑详情页前,先加载详情页的排序类型
  7384. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7385. const albumOriginalIsCanBack = this.isCanBack;
  7386. this.isCanBack = true;
  7387. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  7388. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  7389. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  7390. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7391. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  7392. let albumList = this.albumMap.get(albumCacheKey)
  7393. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  7394. // 使用详情页的排序类型查询
  7395. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  7396. if (ArrayUtil.isNotEmpty(albumList)) {
  7397. this.albumMap.set(albumCacheKey, albumList);
  7398. }
  7399. }
  7400. // 设置当前排序类型为详情页排序
  7401. this.sortType = albumDetailSortType;
  7402. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  7403. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  7404. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  7405. nextAlbumCountMap.set(item.name, albumList.length);
  7406. this.albumSongCountMap = nextAlbumCountMap;
  7407. this.isCanBack = true
  7408. this.hasMoreData = false
  7409. this.isLoadingPage = false
  7410. this.pageCache.clear()
  7411. this.pageHasMoreCache.clear()
  7412. this.pageTotalCountCache.clear()
  7413. this.prefetchingPages.clear()
  7414. this.lastScrollTriggerPage = -1
  7415. this.lastVisibleEndIndex = -1
  7416. this.isPagingTransition = false
  7417. if (this.pagingScheduleTimer) {
  7418. clearTimeout(this.pagingScheduleTimer)
  7419. this.pagingScheduleTimer = 0
  7420. }
  7421. this.totalCount = albumList.length
  7422. this.titleName = item.name
  7423. this.currentTitleName = '专辑:' + item.name
  7424. if (item.pixelMapPath) {
  7425. this.currentTitleCover = item.pixelMapPath
  7426. }
  7427. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7428. this.mScrollMap.set(item.name, this.selectedIndex)
  7429. this.rightTopImage = $r('sys.symbol.chevron_left')
  7430. } else {
  7431. ToastUtil.showToast('未找到该专辑的歌曲');
  7432. return;
  7433. }
  7434. //进入歌单的时候的滚动位置在顶部
  7435. if(this.twoFingerType==4){
  7436. setTimeout(() => {
  7437. this.waterScroller.scrollEdge(Edge.Top)
  7438. this.scroller.scrollEdge(Edge.Top)
  7439. }, 380)
  7440. }else{
  7441. if (this.isGridMusic) {
  7442. this.scroller.scrollEdge(Edge.Top)
  7443. }else{
  7444. this.listScroller.scrollEdge(Edge.Top)
  7445. }
  7446. }
  7447. break;
  7448. case CommonConstants.TYPE_IS_CSJAD:
  7449. return
  7450. break;
  7451. case CommonConstants.TYPE_LOCAL:
  7452. if (this.isIsoLocalFile(item)) {
  7453. await this.openIsoArchiveDialog(item)
  7454. return
  7455. }
  7456. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  7457. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  7458. const cueTracks:CueTrack[] = cueinfo.tracks
  7459. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  7460. if(ArrayUtil.isNotEmpty(cueTracks)){
  7461. this.showCueDialog(cueTracks,cueinfo)
  7462. }
  7463. // this.showCueSheet = !this.showCueSheet
  7464. return
  7465. }
  7466. console.info('kkMusic doPlay this.CONTROL_PlayStatus ='+this.CONTROL_PlayStatus )
  7467. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7468. console.info('kkMusic doPlay stop =' )
  7469. this.stop();
  7470. }
  7471. const useExistingQueueForPlayback = this.preserveExistingQueueOnNextPlay;
  7472. const nextQueueScope = this.nextPlayQueueScope;
  7473. this.preserveExistingQueueOnNextPlay = false;
  7474. this.nextPlayQueueScope = 'view';
  7475. if (isOpen) {
  7476. this.resetFindPagedLocalQueueState();
  7477. this.currentSong = item
  7478. if (index !== undefined) {
  7479. this.curIndex = index
  7480. }
  7481. this.songList = []
  7482. this.songList.push(item)
  7483. this.sonDataSource.pushArrayData(this.songList)
  7484. this.playQueueScope = 'single'
  7485. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  7486. this.currentSong = item
  7487. if (index !== undefined) {
  7488. this.curIndex = index
  7489. }
  7490. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  7491. if (this.isFindPagedLocalQueueActive()) {
  7492. // 这类队列来自发现页分页随机,点击播放列表里的歌也要继续保持“分页队列”身份。
  7493. this.playQueueScope = 'find_paged_local'
  7494. this.currentPlaylistSongFilePaths = [];
  7495. } else {
  7496. this.resetFindPagedLocalQueueState();
  7497. this.playQueueScope = 'playlist'
  7498. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7499. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7500. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7501. }
  7502. }
  7503. }else if (useExistingQueueForPlayback) {
  7504. // 特殊分页队列初始化时,直接复用 finishLoadingPlaylist 准备好的当前页,不再按视图重建全量队列。
  7505. this.currentSong = item
  7506. if (index !== undefined) {
  7507. this.curIndex = index
  7508. }
  7509. this.playQueueScope = nextQueueScope
  7510. this.currentPlaylistSongFilePaths = [];
  7511. this.sonDataSource.pushArrayData(this.songList)
  7512. }else {
  7513. this.resetFindPagedLocalQueueState();
  7514. const globalVideoList = this.buildPlayQueueFromView();
  7515. this.curIndex = findSongIndexByFilePath(globalVideoList, item.filePath)
  7516. if (this.curIndex < 0) {
  7517. globalVideoList.push(item);
  7518. this.curIndex = globalVideoList.length - 1;
  7519. }
  7520. this.songList = globalVideoList
  7521. this.sonDataSource.pushArrayData(this.songList)
  7522. this.currentSong = this.songList[this.curIndex]
  7523. // 只在非歌单模式下清空歌单路径列表
  7524. if (this.modeType !== 4) {
  7525. this.currentPlaylistSongFilePaths = [];
  7526. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  7527. } else {
  7528. // 歌单模式:确保歌单路径列表已设置
  7529. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7530. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7531. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7532. } else {
  7533. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7534. }
  7535. }
  7536. }
  7537. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7538. try {
  7539. const localUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-local');
  7540. this.videoUrl = localUrl || this.currentSong.filePath
  7541. } catch (error) {
  7542. Logger.error(TAG, `本地歌曲构建播放地址失败: ${(error as Error).message}`);
  7543. this.videoUrl = this.currentSong.filePath
  7544. }
  7545. this.name = this.currentSong.name
  7546. this.cover = this.currentSong.pixelMapPath
  7547. this.artist = this.currentSong.artist
  7548. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  7549. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  7550. this.startPlayOrResumePlay()
  7551. break;
  7552. case CommonConstants.TYPE_WEBDAV:
  7553. case CommonConstants.TYPE_SMB:
  7554. case CommonConstants.TYPE_NAVIDROME:
  7555. case CommonConstants.TYPE_FTP:
  7556. case CommonConstants.TYPE_BAIDU:
  7557. case CommonConstants.TYPE_JELLYFIN:
  7558. case CommonConstants.TYPE_EMBY:
  7559. case CommonConstants.TYPE_AUDIOSTATION:
  7560. case CommonConstants.TYPE_PLEX:
  7561. case CommonConstants.TYPE_DAOLIYU:
  7562. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  7563. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  7564. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7565. this.stop();
  7566. }
  7567. this.resetFindPagedLocalQueueState();
  7568. this.preserveExistingQueueOnNextPlay = false;
  7569. this.nextPlayQueueScope = 'view';
  7570. if (isOpen) {
  7571. this.currentSong = item
  7572. if (index !== undefined) {
  7573. this.curIndex = index
  7574. }
  7575. this.songList = []
  7576. this.songList.push(item)
  7577. this.sonDataSource.pushArrayData(this.songList)
  7578. } else if (isFromSonPlayList) {
  7579. // 点击来自右下角的播放列表
  7580. this.currentSong = item
  7581. if (index !== undefined) {
  7582. this.curIndex = index
  7583. }
  7584. // 设置播放队列作用域为歌单
  7585. this.playQueueScope = 'playlist'
  7586. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7587. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  7588. } else {
  7589. // 从全局网络音频列表中查找
  7590. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  7591. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  7592. if (this.curIndex === -1 && index !== undefined) {
  7593. this.curIndex = index;
  7594. }
  7595. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  7596. this.currentSong = this.songList[this.curIndex];
  7597. this.sonDataSource.pushArrayData(this.songList)
  7598. }
  7599. await this.hydrateRemoteSongFromDb(this.currentSong);
  7600. await this.hydrateRemoteSongFromDb(this.currentSong);
  7601. AppStorage.setOrCreate('currentSong', this.currentSong);
  7602. const remotePlayLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  7603. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-remote');
  7604. if (!playbackUrl) {
  7605. if (remotePlayLoading) {
  7606. this.hideLoadIng();
  7607. }
  7608. return;
  7609. }
  7610. this.videoUrl = playbackUrl;
  7611. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  7612. this.name = this.currentSong.name
  7613. this.cover = this.currentSong.pixelMapPath
  7614. this.artist = this.currentSong.artist
  7615. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  7616. this.startPlayOrResumePlay()
  7617. break;
  7618. }
  7619. }
  7620. private async openIsoArchiveDialog(item: VideoItem): Promise<void> {
  7621. if (!item || StrUtil.isEmpty(item.filePath)) {
  7622. Logger.error(TAG, `heanup ISO open dialog invalid path=${item ? item.filePath : ''}`)
  7623. ToastUtil.showToast('ISO 文件无效')
  7624. return
  7625. }
  7626. if (this.isIsoExtracting) {
  7627. if (ArrayUtil.isNotEmpty(this.isoAudioEntries)) {
  7628. if (this.isoSourceFilePath !== item.filePath) {
  7629. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行,已打开提取进度窗口')
  7630. }
  7631. this.presentIsoArchiveDialog()
  7632. return
  7633. }
  7634. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行')
  7635. return
  7636. }
  7637. Logger.info(TAG, `heanup ISO open dialog path=${item.filePath}, name=${item.fileName || item.name}`)
  7638. this.closeIsoDialog()
  7639. this.isoSourceFilePath = item.filePath
  7640. this.isoSourceFileName = item.fileName || item.name
  7641. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  7642. progress: 0,
  7643. backCancel: false,
  7644. autoCancel: false,
  7645. loadColor: this.themeColor,
  7646. fontColor: this.themeColor
  7647. })
  7648. try {
  7649. const task = new taskpool.Task(listIsoAudioEntriesTask, item.filePath)
  7650. const entries = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoArchiveAudioEntry[]
  7651. this.isoAudioEntries = Array.isArray(entries) ? entries : []
  7652. Logger.info(TAG, `heanup ISO list entries done count=${this.isoAudioEntries.length}, path=${item.filePath}`)
  7653. if (ArrayUtil.isEmpty(this.isoAudioEntries)) {
  7654. Logger.error(TAG, `heanup ISO list entries empty path=${item.filePath}`)
  7655. ToastUtil.showToast('ISO 内未发现可提取的媒体文件')
  7656. this.closeIsoDialog()
  7657. return
  7658. }
  7659. this.selectedIsoAudioPaths = []
  7660. } catch (error) {
  7661. Logger.error(TAG, `heanup 解析 ISO 失败: ${(error as Error).message}`)
  7662. ToastUtil.showToast('解析 ISO 失败')
  7663. this.closeIsoDialog()
  7664. return
  7665. } finally {
  7666. if (this.loadingProgressDialogId) {
  7667. DialogHelper.closeDialog(this.loadingProgressDialogId)
  7668. this.loadingProgressDialogId = ''
  7669. }
  7670. }
  7671. this.presentIsoArchiveDialog()
  7672. }
  7673. private presentIsoArchiveDialog(): void {
  7674. if (this.isoComponentId > 0) {
  7675. return
  7676. }
  7677. this.getUIContext().getPromptAction().openCustomDialog({
  7678. builder: () => {
  7679. this.isoComptentBuilder()
  7680. },
  7681. isModal: true,
  7682. showInSubWindow: false,
  7683. maskColor: Color.Transparent,
  7684. dialogTransition: TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7685. .animation({ duration: 600, curve: Curve.Smooth }),
  7686. maskTransition: TransitionEffect.opacity(0.5)
  7687. .animation({ duration: 600, curve: Curve.Smooth })
  7688. }).then((dialogId: number) => {
  7689. this.isoComponentId = dialogId
  7690. }).catch((error: BusinessError) => {
  7691. Logger.error(TAG, `heanup 打开 ISO 弹窗失败: ${error.message}`)
  7692. this.closeIsoDialog()
  7693. })
  7694. }
  7695. private toggleIsoEntrySelection(path: string, checked: boolean): void {
  7696. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7697. if (checked) {
  7698. selectedPathSet.add(path)
  7699. } else {
  7700. selectedPathSet.delete(path)
  7701. }
  7702. this.selectedIsoAudioPaths = this.isoAudioEntries
  7703. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7704. .map((entry: IsoArchiveAudioEntry) => entry.path)
  7705. Logger.info(TAG,
  7706. `heanup ISO toggle selection path=${path}, checked=${checked}, total=${this.selectedIsoAudioPaths.length}`)
  7707. }
  7708. private toggleIsoEntrySelectAll(): void {
  7709. if (this.selectedIsoAudioPaths.length === this.isoAudioEntries.length) {
  7710. this.selectedIsoAudioPaths = []
  7711. Logger.info(TAG, 'heanup ISO toggle select all cleared')
  7712. return
  7713. }
  7714. this.selectedIsoAudioPaths = this.isoAudioEntries.map((entry: IsoArchiveAudioEntry) => entry.path)
  7715. Logger.info(TAG, `heanup ISO toggle select all count=${this.selectedIsoAudioPaths.length}`)
  7716. }
  7717. private startIsoExtractProgressWatcher(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): void {
  7718. this.stopIsoExtractProgressWatcher()
  7719. this.isoExtractExpectedOutputPaths = this.buildIsoExtractExpectedOutputPaths(entries, destinationDir)
  7720. this.isoExtractTotalBytes = entries.reduce((total: number, entry: IsoArchiveAudioEntry) => {
  7721. const size = entry && entry.size > 0 ? entry.size : 0
  7722. return total + size
  7723. }, 0)
  7724. this.isoExtractReceivedTaskProgress = false
  7725. this.isoExtractDisplayedProgress = 0
  7726. this.isoExtractLastActivityTime = Date.now()
  7727. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths)) {
  7728. return
  7729. }
  7730. this.isoExtractProgressTimer = setInterval(() => {
  7731. this.updateIsoExtractProgressFromFiles()
  7732. }, 500)
  7733. }
  7734. private stopIsoExtractProgressWatcher(): void {
  7735. if (this.isoExtractProgressTimer) {
  7736. clearInterval(this.isoExtractProgressTimer)
  7737. this.isoExtractProgressTimer = 0
  7738. }
  7739. this.isoExtractExpectedOutputPaths = []
  7740. this.isoExtractTotalBytes = 0
  7741. this.isoExtractReceivedTaskProgress = false
  7742. this.isoExtractLastActivityTime = 0
  7743. }
  7744. private markIsoExtractActivity(): void {
  7745. this.isoExtractLastActivityTime = Date.now()
  7746. }
  7747. private updateIsoExtractProgressFromFiles(): void {
  7748. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths) ||
  7749. this.isoExtractReceivedTaskProgress) {
  7750. return
  7751. }
  7752. let writtenBytes = 0
  7753. let existingCount = 0
  7754. for (let i = 0; i < this.isoExtractExpectedOutputPaths.length; i++) {
  7755. const outputPath = this.isoExtractExpectedOutputPaths[i]
  7756. if (!FileUtil.accessSync(outputPath)) {
  7757. continue
  7758. }
  7759. existingCount++
  7760. try {
  7761. const stat = fs.statSync(outputPath) as fs.Stat
  7762. if (typeof stat.size === 'number' && stat.size > 0) {
  7763. writtenBytes += stat.size
  7764. }
  7765. } catch (_error) {
  7766. }
  7767. }
  7768. let progress = 0
  7769. if (writtenBytes > 0) {
  7770. progress = Math.ceil((writtenBytes / this.isoExtractTotalBytes) * 100)
  7771. if (progress > 99) {
  7772. progress = 99
  7773. }
  7774. this.markIsoExtractActivity()
  7775. } else if (existingCount > 0) {
  7776. progress = 1
  7777. this.markIsoExtractActivity()
  7778. }
  7779. if (progress > 0) {
  7780. this.updateIsoExtractProgressState(progress,
  7781. `正在提取 ${progress}% (${existingCount}/${this.isoExtractExpectedOutputPaths.length})`)
  7782. return
  7783. }
  7784. if (this.isoExtractTask && this.isoExtractLastActivityTime > 0 &&
  7785. Date.now() - this.isoExtractLastActivityTime > this.isoExtractStallTimeoutMs) {
  7786. Logger.warn(TAG, `heanup ISO 提取进度长时间无变化: timeout=${this.isoExtractStallTimeoutMs}`)
  7787. this.markIsoExtractActivity()
  7788. this.updateIsoExtractProgressState(1, '准备提取 1%')
  7789. }
  7790. }
  7791. private updateIsoExtractProgressState(progress: number, message: string, currentName: string = '',
  7792. force: boolean = false): void {
  7793. let safeProgress = progress
  7794. if (safeProgress < 0) {
  7795. safeProgress = 0
  7796. }
  7797. if (safeProgress > 100) {
  7798. safeProgress = 100
  7799. }
  7800. if (!force && safeProgress < this.isoExtractDisplayedProgress) {
  7801. return
  7802. }
  7803. this.isoExtractDisplayedProgress = safeProgress
  7804. this.isoExtractProgress = safeProgress
  7805. this.isoExtractProgressText = message
  7806. if (force || StrUtil.isNotEmpty(currentName)) {
  7807. this.isoExtractCurrentEntryName = currentName
  7808. }
  7809. }
  7810. private resetIsoExtractProgressState(): void {
  7811. this.isoExtractProgress = 0
  7812. this.isoExtractProgressText = ''
  7813. this.isoExtractCurrentEntryName = ''
  7814. this.isoExtractDisplayedProgress = 0
  7815. }
  7816. private buildIsoExtractExpectedOutputPaths(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): Array<string> {
  7817. const outputPaths: Array<string> = []
  7818. const occupiedPaths: Set<string> = new Set<string>()
  7819. for (let i = 0; i < entries.length; i++) {
  7820. const entry = entries[i]
  7821. const fileName = entry.name || this.getIsoLastPathSegment(entry.path)
  7822. const outputPath = this.buildIsoExpectedOutputPath(destinationDir, fileName, occupiedPaths)
  7823. occupiedPaths.add(outputPath)
  7824. outputPaths.push(outputPath)
  7825. }
  7826. return outputPaths
  7827. }
  7828. private buildIsoExpectedOutputPath(destinationDir: string, fileName: string, occupiedPaths: Set<string>): string {
  7829. const cleanName = this.sanitizeIsoOutputFileName(fileName)
  7830. const extension = this.getIsoOutputFileExtension(cleanName)
  7831. const baseName = extension.length > 0 ? cleanName.substring(0, cleanName.length - extension.length) : cleanName
  7832. let candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${cleanName}`
  7833. let suffix = 0
  7834. while (occupiedPaths.has(candidatePath) || FileUtil.accessSync(candidatePath)) {
  7835. suffix++
  7836. candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${baseName} (${suffix})${extension}`
  7837. }
  7838. return candidatePath
  7839. }
  7840. private sanitizeIsoOutputFileName(fileName: string): string {
  7841. const lastSegment = this.getIsoLastPathSegment(fileName)
  7842. let sanitized = ''
  7843. for (let i = 0; i < lastSegment.length; i++) {
  7844. const char = lastSegment[i]
  7845. if (char === '/' || char === '\\' || char === ':' || char === '*' || char === '?' || char === '"' ||
  7846. char === '<' || char === '>' || char === '|') {
  7847. sanitized += '_'
  7848. } else {
  7849. sanitized += char
  7850. }
  7851. }
  7852. if (sanitized.trim().length === 0) {
  7853. return 'iso_audio.bin'
  7854. }
  7855. return sanitized
  7856. }
  7857. private getIsoLastPathSegment(path: string): string {
  7858. const normalizedPath = path.replace(/\\/g, '/')
  7859. const lastSeparator = normalizedPath.lastIndexOf('/')
  7860. if (lastSeparator < 0) {
  7861. return normalizedPath
  7862. }
  7863. return normalizedPath.substring(lastSeparator + 1)
  7864. }
  7865. private getIsoOutputFileExtension(fileName: string): string {
  7866. const lastDot = fileName.lastIndexOf('.')
  7867. if (lastDot < 0) {
  7868. return ''
  7869. }
  7870. return fileName.substring(lastDot)
  7871. }
  7872. private trimIsoOutputTrailingSeparator(path: string): string {
  7873. if (path.endsWith('/')) {
  7874. return path.substring(0, path.length - 1)
  7875. }
  7876. return path
  7877. }
  7878. private cancelIsoExtraction(reason?: string): void {
  7879. const currentTask = this.isoExtractTask
  7880. Logger.info(TAG,
  7881. `heanup ISO cancel request reason=${reason || ''}, hasTask=${currentTask ? 'true' : 'false'}`)
  7882. this.isoExtractCanceled = true
  7883. this.isoExtractCancelMessage = reason ? reason : ''
  7884. this.isoExtractTask = undefined
  7885. this.updateIsoExtractProgressState(this.isoExtractProgress, '正在停止提取...', this.isoExtractCurrentEntryName, true)
  7886. if (currentTask) {
  7887. try {
  7888. taskpool.terminateTask(currentTask)
  7889. } catch (error) {
  7890. Logger.error(TAG, `heanup 终止 ISO 提取任务失败: ${(error as Error).message}`)
  7891. }
  7892. }
  7893. }
  7894. private moveIsoExtractionToBackground(): void {
  7895. this.closeIsoDialog(false)
  7896. ToastUtil.showToast('ISO 提取已转入后台')
  7897. }
  7898. private async extractSelectedIsoAudioFiles(): Promise<void> {
  7899. if (this.isIsoExtracting) {
  7900. return
  7901. }
  7902. if (ArrayUtil.isEmpty(this.selectedIsoAudioPaths)) {
  7903. ToastUtil.showToast('请先选择要提取的文件')
  7904. return
  7905. }
  7906. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7907. const selectedEntries = this.isoAudioEntries
  7908. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7909. if (ArrayUtil.isEmpty(selectedEntries)) {
  7910. ToastUtil.showToast('未找到要提取的文件')
  7911. return
  7912. }
  7913. const hasSacdTrack: boolean = selectedEntries.some((entry: IsoArchiveAudioEntry) => entry.entryType === 'sacd_track')
  7914. const destinationDir: string = this.currentPath
  7915. this.isIsoExtracting = true
  7916. this.isoExtractCanceled = false
  7917. this.isoExtractCancelMessage = ''
  7918. this.isoExtractDestinationDir = destinationDir
  7919. Logger.info(TAG,
  7920. `heanup ISO extract start file=${this.isoSourceFilePath}, selected=${selectedEntries.length}, ` +
  7921. `hasSacd=${hasSacdTrack}, destinationDir=${destinationDir}`)
  7922. Logger.info(TAG,
  7923. `heanup ISO selected entries: ${selectedEntries.map((entry: IsoArchiveAudioEntry) => entry.path).join(', ')}`)
  7924. this.resetIsoExtractProgressState()
  7925. this.updateIsoExtractProgressState(1, '准备提取 1%', '', true)
  7926. this.startIsoExtractProgressWatcher(selectedEntries, destinationDir)
  7927. try {
  7928. const extractStartedAt = Date.now()
  7929. const outputPaths: string[] = this.buildIsoExtractExpectedOutputPaths(selectedEntries, destinationDir)
  7930. const payloadJson = JSON.stringify({
  7931. isoPath: this.isoSourceFilePath,
  7932. destinationDir,
  7933. entries: selectedEntries,
  7934. outputPaths
  7935. })
  7936. const task = new taskpool.Task(extractIsoAudioEntriesTask, payloadJson)
  7937. this.isoExtractTask = task
  7938. task.onReceiveData((progressData: IsoExtractProgressMessage) => {
  7939. this.markIsoExtractActivity()
  7940. const progress = typeof progressData.progress === 'number' ? Math.floor(progressData.progress) : 0
  7941. Logger.info(TAG,
  7942. `heanup ISO task receive stage=${progressData.stage || ''}, progress=${progress}, name=${progressData.name || ''}`)
  7943. if (progress > 1 && !this.isoExtractReceivedTaskProgress) {
  7944. this.isoExtractReceivedTaskProgress = true
  7945. if (this.isoExtractProgressTimer) {
  7946. clearInterval(this.isoExtractProgressTimer)
  7947. this.isoExtractProgressTimer = 0
  7948. }
  7949. Logger.info(TAG, `heanup ISO 提取切换为任务进度: progress=${progress}, stage=${progressData.stage || ''}`)
  7950. }
  7951. const stageText = progressData.stage === 'prepare' ? '准备提取' :
  7952. (progressData.stage === 'done' ? '提取完成' : (progressData.stage === 'error' ? '提取异常' : '正在提取'))
  7953. if (progress > this.isoExtractDisplayedProgress || progressData.stage !== 'extract') {
  7954. Logger.info(TAG,
  7955. `heanup ISO 提取任务进度: stage=${progressData.stage || ''}, progress=${progress}, ` +
  7956. `name=${progressData.name || ''}`)
  7957. }
  7958. this.updateIsoExtractProgressState(progress, `${stageText} ${progress}%`, progressData.name || '')
  7959. })
  7960. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoExtractTaskResult
  7961. const extractElapsedMs = Date.now() - extractStartedAt
  7962. this.isoExtractTask = undefined
  7963. Logger.info(TAG, `heanup ISO extract task completed canceled=${this.isoExtractCanceled}, elapsedMs=${extractElapsedMs}`)
  7964. if (this.isoExtractCanceled) {
  7965. return
  7966. }
  7967. const extractedPaths = result?.extractedPaths || []
  7968. const failedEntries = result?.failedEntries || []
  7969. const failureDetails = result?.failureDetails || []
  7970. Logger.info(TAG,
  7971. `heanup ISO extract result extracted=${extractedPaths.length}, failed=${failedEntries.length}, details=${failureDetails.length}`)
  7972. let importErrorMessage: string = ''
  7973. let importedCount: number = 0
  7974. if (ArrayUtil.isNotEmpty(extractedPaths)) {
  7975. const importStartedAt = Date.now()
  7976. try {
  7977. await this.postProcessExtractedIsoFiles(extractedPaths, selectedEntries, outputPaths)
  7978. importedCount = await this.importExtractedFilesToDirectory(extractedPaths, destinationDir)
  7979. Logger.info(TAG,
  7980. `heanup ISO import extracted files success elapsedMs=${Date.now() - importStartedAt}, ` +
  7981. `importedCount=${importedCount}`)
  7982. } catch (importError) {
  7983. importErrorMessage = (importError as Error).message || '导入媒体库失败'
  7984. Logger.error(TAG,
  7985. `heanup ISO import extracted files failed elapsedMs=${Date.now() - importStartedAt}, ` +
  7986. `message=${importErrorMessage}`)
  7987. }
  7988. }
  7989. if (extractedPaths.length > 0 && failedEntries.length > 0) {
  7990. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7991. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,导入失败`)
  7992. } else if (importedCount > 0) {
  7993. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,已入库 ${importedCount} 个音频文件`)
  7994. } else {
  7995. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个`)
  7996. }
  7997. } else if (extractedPaths.length > 0) {
  7998. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7999. ToastUtil.showToast(`提取完成,但导入媒体库失败: ${importErrorMessage}`)
  8000. } else if (importedCount > 0) {
  8001. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件,入库 ${importedCount} 个音频文件`)
  8002. } else {
  8003. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件`)
  8004. }
  8005. } else if (ArrayUtil.isNotEmpty(failureDetails)) {
  8006. const firstFailure: IsoExtractFailureDetail = failureDetails[0]
  8007. const reasonText = firstFailure.reason && firstFailure.reason.length > 0 ? firstFailure.reason : '提取失败'
  8008. ToastUtil.showToast(reasonText)
  8009. } else if (hasSacdTrack) {
  8010. ToastUtil.showToast('SACD ISO 轨道提取失败')
  8011. } else {
  8012. ToastUtil.showToast('提取失败')
  8013. }
  8014. } catch (error) {
  8015. this.isoExtractTask = undefined
  8016. if (this.isoExtractCanceled) {
  8017. return
  8018. }
  8019. Logger.error(TAG, `heanup 提取 ISO 文件失败: ${(error as Error).message}`)
  8020. ToastUtil.showToast('提取 ISO 文件失败')
  8021. } finally {
  8022. const shouldResetDialogState: boolean = this.isoComponentId <= 0
  8023. this.stopIsoExtractProgressWatcher()
  8024. this.isoExtractTask = undefined
  8025. this.isIsoExtracting = false
  8026. Logger.info(TAG,
  8027. `heanup ISO extract finally canceled=${this.isoExtractCanceled}, cancelMessage=${this.isoExtractCancelMessage}`)
  8028. if (this.isoExtractCanceled && this.isoExtractCancelMessage.length > 0) {
  8029. ToastUtil.showToast(this.isoExtractCancelMessage)
  8030. }
  8031. this.isoExtractCanceled = false
  8032. this.isoExtractCancelMessage = ''
  8033. if (shouldResetDialogState) {
  8034. this.resetIsoDialogState()
  8035. } else {
  8036. this.selectedIsoAudioPaths = []
  8037. this.resetIsoExtractProgressState()
  8038. }
  8039. }
  8040. }
  8041. private async postProcessExtractedIsoFiles(extractedPaths: Array<string>, selectedEntries: Array<IsoArchiveAudioEntry>,
  8042. outputPaths: Array<string>): Promise<void> {
  8043. if (ArrayUtil.isEmpty(extractedPaths) || ArrayUtil.isEmpty(selectedEntries) || ArrayUtil.isEmpty(outputPaths)) {
  8044. return
  8045. }
  8046. const entryByOutputPath: Map<string, IsoArchiveAudioEntry> = new Map<string, IsoArchiveAudioEntry>()
  8047. for (let i = 0; i < outputPaths.length && i < selectedEntries.length; i++) {
  8048. entryByOutputPath.set(outputPaths[i], selectedEntries[i])
  8049. }
  8050. for (let i = 0; i < extractedPaths.length; i++) {
  8051. const extractedPath = extractedPaths[i]
  8052. const entry = entryByOutputPath.get(extractedPath)
  8053. if (!entry) {
  8054. continue
  8055. }
  8056. await this.postProcessExtractedIsoEntry(extractedPath, entry)
  8057. }
  8058. }
  8059. private async postProcessExtractedIsoEntry(filePath: string, entry: IsoArchiveAudioEntry): Promise<void> {
  8060. if (!Utility.isMusicByExtension(filePath)) {
  8061. return
  8062. }
  8063. const hasEmbeddedMetadata: boolean = StrUtil.isNotEmpty(entry.title) || StrUtil.isNotEmpty(entry.album) ||
  8064. StrUtil.isNotEmpty(entry.artist) || StrUtil.isNotEmpty(entry.albumArtist) || StrUtil.isNotEmpty(entry.comment) ||
  8065. !!(entry.trackNumber && entry.trackNumber > 0)
  8066. if (entry.entryType !== 'sacd_track' && !hasEmbeddedMetadata) {
  8067. return
  8068. }
  8069. const tags: FFMpegTags = this.buildIsoExtractedMetadata(entry)
  8070. if (Object.keys(tags).length > 0) {
  8071. try {
  8072. const metadataResult = await repairAudioMetadata(filePath, '', tags, true, '')
  8073. Logger.info(TAG,
  8074. `heanup ISO metadata post-process path=${filePath}, success=${metadataResult}, type=${entry.entryType || ''}`)
  8075. } catch (error) {
  8076. Logger.error(TAG, `heanup ISO metadata post-process failed path=${filePath}, message=${(error as Error).message}`)
  8077. }
  8078. }
  8079. if (!filePath.toLowerCase().endsWith('.dsf')) {
  8080. return
  8081. }
  8082. const coverUrl = await this.resolveIsoExtractCoverUrl(entry)
  8083. if (StrUtil.isEmpty(coverUrl)) {
  8084. return
  8085. }
  8086. try {
  8087. const coverResult = await changeMusicCover(this.context, filePath, coverUrl, true, '')
  8088. Logger.info(TAG, `heanup ISO cover post-process path=${filePath}, success=${coverResult}`)
  8089. } catch (error) {
  8090. Logger.error(TAG, `heanup ISO cover post-process failed path=${filePath}, message=${(error as Error).message}`)
  8091. }
  8092. }
  8093. private buildIsoExtractedMetadata(entry: IsoArchiveAudioEntry): FFMpegTags {
  8094. const metadata: FFMpegTags = {}
  8095. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  8096. if (StrUtil.isNotEmpty(title)) {
  8097. metadata.title = title
  8098. metadata.TITLE = title
  8099. }
  8100. if (StrUtil.isNotEmpty(entry.artist)) {
  8101. metadata.artist = entry.artist
  8102. metadata.ARTIST = entry.artist
  8103. }
  8104. if (StrUtil.isNotEmpty(entry.album)) {
  8105. metadata.album = entry.album
  8106. metadata.ALBUM = entry.album
  8107. }
  8108. if (entry.trackNumber && entry.trackNumber > 0) {
  8109. metadata.track = `${entry.trackNumber}`
  8110. metadata.TRACK = `${entry.trackNumber}`
  8111. }
  8112. if (StrUtil.isNotEmpty(entry.albumArtist)) {
  8113. metadata.ALBUMARTIST = entry.albumArtist
  8114. metadata.album_artist = entry.albumArtist
  8115. metadata.TPE2 = entry.albumArtist
  8116. }
  8117. if (StrUtil.isNotEmpty(entry.comment)) {
  8118. metadata.comment = entry.comment
  8119. metadata.COMMENT = entry.comment
  8120. metadata.COMM = entry.comment
  8121. }
  8122. return metadata
  8123. }
  8124. private getIsoEntryBaseName(fileName: string): string {
  8125. const lastSegment = this.getIsoLastPathSegment(fileName)
  8126. const lastDot = lastSegment.lastIndexOf('.')
  8127. if (lastDot <= 0) {
  8128. return lastSegment
  8129. }
  8130. return lastSegment.substring(0, lastDot)
  8131. }
  8132. private async resolveIsoExtractCoverUrl(entry: IsoArchiveAudioEntry): Promise<string> {
  8133. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  8134. const artist = entry.artist || entry.albumArtist || ''
  8135. if (StrUtil.isEmpty(title) || PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8136. return ''
  8137. }
  8138. try {
  8139. const coverUrl = await NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', ''))
  8140. if (StrUtil.isNotEmpty(coverUrl) && coverUrl !== 'unknown') {
  8141. return coverUrl
  8142. }
  8143. } catch (error) {
  8144. Logger.error(TAG,
  8145. `heanup ISO resolve cover failed title=${title}, artist=${artist}, message=${(error as Error).message}`)
  8146. }
  8147. return ''
  8148. }
  8149. private async importExtractedFilesToDirectory(paths: Array<string>, destinationDir: string): Promise<number> {
  8150. if (ArrayUtil.isEmpty(paths)) {
  8151. return 0
  8152. }
  8153. let importedCount: number = 0
  8154. for (let i = 0; i < paths.length; i++) {
  8155. const filePath = paths[i]
  8156. if (destinationDir === this.lockPath || !Utility.isMeidaByExtension(filePath) ||
  8157. filePath.endsWith('.lrc') || filePath.endsWith('.srt') || Utility.isIsoByExtension(filePath)) {
  8158. continue
  8159. }
  8160. const mediaItem = await Utility.uriGetMusicAssetsFromFile(this.context, filePath,
  8161. CommonConstants.TYPE_LOCAL, this.autoParseMusicName)
  8162. await new Promise<void>((resolve) => {
  8163. this.table.insert(mediaItem, (_id: number) => resolve())
  8164. })
  8165. importedCount++
  8166. }
  8167. this.cache.delete(destinationDir)
  8168. if (this.currentPath === destinationDir) {
  8169. this.pageCache.clear()
  8170. this.pageHasMoreCache.clear()
  8171. this.pageTotalCountCache.clear()
  8172. if (destinationDir === this.lockPath) {
  8173. this.getSortedFiles(destinationDir, true)
  8174. } else {
  8175. await this.resetAndLoadFirstPage()
  8176. }
  8177. }
  8178. return importedCount
  8179. }
  8180. private resetIsoDialogState(): void {
  8181. this.isoAudioEntries = []
  8182. this.selectedIsoAudioPaths = []
  8183. this.isoSourceFileName = ''
  8184. this.isoSourceFilePath = ''
  8185. this.isoExtractDestinationDir = ''
  8186. this.isIsoExtracting = false
  8187. this.stopIsoExtractProgressWatcher()
  8188. this.isoExtractTask = undefined
  8189. this.resetIsoExtractProgressState()
  8190. }
  8191. private closeIsoDialog(reset: boolean = true): void {
  8192. if (this.isoComponentId > 0) {
  8193. try {
  8194. this.getUIContext().getPromptAction().closeCustomDialog(this.isoComponentId)
  8195. } catch (_error) {
  8196. }
  8197. this.isoComponentId = 0
  8198. }
  8199. if (!reset) {
  8200. return
  8201. }
  8202. this.resetIsoDialogState()
  8203. }
  8204. @Builder
  8205. isoComptentBuilder() {
  8206. IsoExtractComptent({
  8207. isoFileName: this.isoSourceFileName,
  8208. entries: this.isoAudioEntries,
  8209. selectedPaths: this.selectedIsoAudioPaths,
  8210. isLongNameRoLL: this.isLongNameRoLL,
  8211. isExtracting: this.isIsoExtracting,
  8212. extractProgress: this.isoExtractProgress,
  8213. extractProgressText: this.isoExtractProgressText,
  8214. extractCurrentName: this.isoExtractCurrentEntryName,
  8215. onToggleSelection: (path: string, checked: boolean) => {
  8216. this.toggleIsoEntrySelection(path, checked)
  8217. },
  8218. onToggleSelectAll: () => {
  8219. this.toggleIsoEntrySelectAll()
  8220. },
  8221. onExtract: async () => {
  8222. await this.extractSelectedIsoAudioFiles()
  8223. },
  8224. onRunInBackground: () => {
  8225. this.moveIsoExtractionToBackground()
  8226. },
  8227. onStopExtract: () => {
  8228. this.cancelIsoExtraction('已取消 ISO 提取')
  8229. },
  8230. onCancel: () => {
  8231. if (this.isIsoExtracting) {
  8232. this.moveIsoExtractionToBackground()
  8233. return
  8234. }
  8235. this.closeIsoDialog()
  8236. }
  8237. })
  8238. }
  8239. private cueComponentId: number = 0
  8240. private async handleCueTrackImport(cueinfo: CueInfo): Promise<void> {
  8241. try {
  8242. let sourceItem = Utility.getItemByFilePath(this.videoLocalList, cueinfo.filePath);
  8243. if (!sourceItem) {
  8244. sourceItem = await this.table.queryVideoByFilePath(cueinfo.filePath) || undefined;
  8245. }
  8246. const importedItems = await importCueTracks(this.context, this.table, cueinfo, sourceItem);
  8247. if (ArrayUtil.isEmpty(importedItems)) {
  8248. ToastUtil.showToast('未导入到任何分轨');
  8249. return;
  8250. }
  8251. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId);
  8252. await this.resetAndLoadFirstPage();
  8253. ToastUtil.showToast(`分轨完成,已入库 ${importedItems.length} 首`);
  8254. } catch (error) {
  8255. Logger.error(TAG, `CUE 分轨入库失败: ${(error as Error).message}`);
  8256. ToastUtil.showToast('分轨失败');
  8257. }
  8258. }
  8259. //显示cue分轨列表对话框
  8260. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  8261. this.getUIContext().getPromptAction().openCustomDialog({
  8262. builder: () => {
  8263. this.cueComptentBuilder(cueTracks,cueinfo)
  8264. },
  8265. isModal:true,
  8266. showInSubWindow:false,
  8267. maskColor: Color.Transparent,
  8268. dialogTransition: // 设置弹窗内容显示的过渡效果
  8269. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  8270. .animation({ duration: 600, curve: Curve.Smooth }),
  8271. maskTransition: // 设置蒙层显示的过渡效果
  8272. TransitionEffect.opacity(0.5)
  8273. .animation({ duration: 600, curve: Curve.Smooth })
  8274. }).then((dialogId: number) => {
  8275. this.cueComponentId = dialogId
  8276. })
  8277. .catch((error: BusinessError) => {
  8278. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  8279. })
  8280. }
  8281. @Builder
  8282. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  8283. CueComptent({
  8284. title:cueinfo.title,
  8285. cueTracks:cueTracks,
  8286. isLongNameRoLL:this.isLongNameRoLL,
  8287. onCancel:()=>{
  8288. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  8289. },
  8290. onSplitTracks: async ()=>{
  8291. await this.handleCueTrackImport(cueinfo)
  8292. },
  8293. onDoItemClick: async (item: CueTrack, index: number)=>{
  8294. //获取cueinfo对应的filePath
  8295. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  8296. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  8297. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  8298. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  8299. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  8300. if (this.currentSong){
  8301. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  8302. this.stop();//播放之前先停止之前播放。
  8303. }
  8304. this.songList = globalVideoList
  8305. this.sonDataSource.pushArrayData(this.songList)
  8306. if (this.currentSong) {
  8307. try {
  8308. const cueUrl = await this.resolvePlaybackUrlForCurrentSong('cue-track-play');
  8309. if (!cueUrl) {
  8310. return;
  8311. }
  8312. this.videoUrl = cueUrl;
  8313. } catch (error) {
  8314. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  8315. this.videoUrl = this.currentSong.filePath;
  8316. }
  8317. }
  8318. this.name = item.title||this.currentSong.name
  8319. this.cover = this.currentSong.pixelMapPath
  8320. this.artist = item.performer||this.currentSong.artist
  8321. this.currentSong.name = this.name
  8322. this.currentSong.artist = this.artist
  8323. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  8324. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  8325. }
  8326. }
  8327. })
  8328. }
  8329. @State isFrontWhite: boolean = false
  8330. private showCoverScaleGuideIfNeeded(): void {
  8331. const hasShown = PreferencesUtil.getBooleanSync(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, false)
  8332. if (hasShown) {
  8333. return
  8334. }
  8335. this.isShowCoverScaleGuide = true
  8336. setTimeout(() => {
  8337. if (this.isShowCoverScaleGuide) {
  8338. this.dismissCoverScaleGuide()
  8339. }
  8340. }, 9000)
  8341. }
  8342. private dismissCoverScaleGuide(): void {
  8343. this.isShowCoverScaleGuide = false
  8344. PreferencesUtil.put(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, true)
  8345. }
  8346. private resolveMiniBarDismissTarget() {
  8347. const viewportWidthVp = this.windowWidth > 0 ? px2vp(this.windowWidth) : 360
  8348. const viewportHeightVp = this.windowHeight > 0 ? px2vp(this.windowHeight) : 800
  8349. const useFixedBottomMargin = DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  8350. || this.curDisplayIsHiCar
  8351. return resolvePlayerDismissMorphTarget(viewportWidthVp, viewportHeightVp, this.bottomSafeHeight, useFixedBottomMargin)
  8352. }
  8353. private clearPlayDismissTimer(): void {
  8354. if (this.playDismissTimer >= 0) {
  8355. clearTimeout(this.playDismissTimer)
  8356. this.playDismissTimer = -1
  8357. }
  8358. }
  8359. private clearPlayOpenTimer(): void {
  8360. if (this.playOpenTimer >= 0) {
  8361. clearTimeout(this.playOpenTimer)
  8362. this.playOpenTimer = -1
  8363. }
  8364. }
  8365. private resetMusicPlayDismissState(): void {
  8366. this.clearPlayDismissTimer()
  8367. this.clearPlayOpenTimer()
  8368. this.playOpenFromMiniBarPending = false
  8369. this.translateY = 0
  8370. this.playDismissTranslateX = 0
  8371. this.playDismissScale = 1
  8372. this.playDismissScaleY = 1
  8373. this.playDismissOpacity = 1
  8374. this.playDismissBorderRadius = 0
  8375. this.playDismissProxySize = 0
  8376. this.playDismissProxyOpacity = 0
  8377. this.scaleValueImage = 1
  8378. this.scaleValueText = 1
  8379. this.playDragUiOpacity = 1
  8380. }
  8381. private preparePlayerViewOpenFromMiniBar(): void {
  8382. const target = this.resolveMiniBarDismissTarget()
  8383. this.playOpenFromMiniBarPending = true
  8384. this.translateY = target.translateY
  8385. this.playDismissTranslateX = 0
  8386. this.playDismissScale = 0.9
  8387. this.playDismissScaleY = 0.8
  8388. this.playDismissOpacity = 0
  8389. this.playDismissBorderRadius = 48
  8390. this.playDismissProxySize = 0
  8391. this.playDismissProxyOpacity = 0
  8392. this.playDragUiOpacity = 0
  8393. this.scaleValueImage = 0.82
  8394. this.scaleValueText = 0.88
  8395. }
  8396. private startPlayerViewOpenAnimationIfNeeded(): void {
  8397. if (!this.playOpenFromMiniBarPending) {
  8398. return
  8399. }
  8400. this.playOpenFromMiniBarPending = false
  8401. this.getUIContext()?.animateTo({
  8402. duration: this.playOpenExpandDuration,
  8403. curve: Curve.Friction
  8404. }, () => {
  8405. this.playDismissProxySize = 0
  8406. this.playDismissProxyOpacity = 0
  8407. this.translateY = 0
  8408. this.playDismissTranslateX = 0
  8409. this.playDismissScale = 1
  8410. this.playDismissScaleY = 1
  8411. this.playDismissOpacity = 1
  8412. this.playDismissBorderRadius = 0
  8413. this.playDragUiOpacity = 1
  8414. this.scaleValueImage = 1
  8415. this.scaleValueText = 1
  8416. })
  8417. }
  8418. setShowPlayTrue(){
  8419. this.getUIContext()?.animateTo({
  8420. duration: 500,
  8421. curve: Curve.Friction
  8422. }, () => {
  8423. this.isShowPlay = true;
  8424. this.showCoverScaleGuideIfNeeded()
  8425. });
  8426. }
  8427. setShowPlayFalse(){
  8428. this.getUIContext()?.animateTo({
  8429. duration: 500,
  8430. curve: Curve.Friction
  8431. }, () => {
  8432. this.isShowPlay = false;
  8433. });
  8434. this.isShowCoverScaleGuide = false
  8435. }
  8436. //打开播放页
  8437. showPlayerView() {
  8438. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  8439. if (ArrayUtil.isNotEmpty(this.songList)) {
  8440. // this.setShowPlayTrue()
  8441. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  8442. this.initLyric(lyricPath);
  8443. this.startAutoHide();
  8444. } else {
  8445. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  8446. }
  8447. }
  8448. //打开播放列表
  8449. openPlayList(){
  8450. if (ArrayUtil.isNotEmpty(this.songList)) {
  8451. this.isShowSheet = !this.isShowSheet;
  8452. this.isFrontWhite = false
  8453. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  8454. this.scrollIndex()
  8455. if (this.shouldHydrateFullMediaPlayListOnOpen()) {
  8456. void this.hydrateFullMediaPlayListIfNeeded();
  8457. }
  8458. } else {
  8459. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  8460. }
  8461. }
  8462. scrollIndex(){
  8463. try {
  8464. setTimeout(() => {
  8465. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8466. if(this.curIndex>60){
  8467. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  8468. }else{
  8469. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  8470. }
  8471. })
  8472. }, 123)
  8473. }catch (error) {
  8474. console.error(`onecold scrollIndex出错: ${error}`);
  8475. }
  8476. }
  8477. scrollIndexMain(dialogId?:string){
  8478. try {
  8479. setTimeout(() => {
  8480. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8481. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  8482. if(dialogId)
  8483. DialogHelper.closeDialog(dialogId)
  8484. let isAni:boolean = false
  8485. if(this.curIndex<50){
  8486. isAni = true
  8487. }
  8488. if(this.twoFingerType==4){
  8489. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8490. }else{
  8491. if(this.isGridMusic){
  8492. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8493. }else{
  8494. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8495. }
  8496. }
  8497. })
  8498. }, 123)
  8499. }catch (error) {
  8500. console.error(`onecold scrollIndexMain出错: ${error}`);
  8501. }
  8502. }
  8503. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  8504. async locateCurrentSong(): Promise<void> {
  8505. if (!this.currentSong) {
  8506. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  8507. return;
  8508. }
  8509. // 检查当前播放歌曲是否在已加载的列表中
  8510. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8511. if (targetIndex > 0) {
  8512. // 歌曲在当前列表中,直接滚动
  8513. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  8514. this.curIndex = targetIndex;
  8515. this.scrollIndexMain();
  8516. } else {
  8517. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  8518. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  8519. const dialogID = DialogHelper.showLoadingDialog()
  8520. await this.hydrateFullMediaPlayListIfNeeded(false);
  8521. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8522. this.scrollIndexMain(dialogID);
  8523. }
  8524. }
  8525. //播放列表布局
  8526. @Builder
  8527. PlayListSheet() {
  8528. Column() {
  8529. this.PlayList()
  8530. }
  8531. .width('100%')
  8532. .height('100%')
  8533. }
  8534. @State titleStr: string = ''
  8535. @State ablumStr: string = ''
  8536. @State artistStr: string = ''
  8537. @State lyricConStr: string = ''
  8538. @State currentEditItem: string = ''
  8539. @State yearStr: string = ''
  8540. @State trackStr: string = ''
  8541. @State genreStr: string = ''
  8542. @State imagePathStr: string = ''
  8543. @State albumArtistStr: string = ''
  8544. @State composerStr: string = ''
  8545. @State lyricistStr: string = ''
  8546. @State commentStr: string = ''
  8547. @State discStr: string = ''
  8548. doUpdateData() {
  8549. setTimeout(async () => {
  8550. if (this.modeType === 0) {
  8551. this.deleteCache(this.currentPath)
  8552. await this.resetAndLoadFirstPage();
  8553. }else if (this.modeType === 1){
  8554. await this.resetAndLoadFirstPage();
  8555. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8556. }
  8557. }, 500)
  8558. }
  8559. doAllUpdateData() {
  8560. setTimeout(async () => {
  8561. if (this.modeType === 0) {
  8562. this.deleteCache(this.currentPath)
  8563. await this.resetAndLoadFirstPage();
  8564. }else{
  8565. await this.resetAndLoadFirstPage();
  8566. }
  8567. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8568. workerInstance.postMessage({ code: 3, data: this.context });
  8569. workerInstance.postMessage({ code: 4, data: this.context });
  8570. }, 999)
  8571. }
  8572. private delayMs(ms: number): Promise<void> {
  8573. return new Promise(resolve => {
  8574. setTimeout(() => resolve(), ms);
  8575. });
  8576. }
  8577. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  8578. if (!items || items.length === 0) {
  8579. return;
  8580. }
  8581. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  8582. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  8583. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  8584. if (!this.isScrolling || items.length <= directAppendThreshold) {
  8585. this.videoLocalList.push(...items);
  8586. this.dataSource.appendArrayData(items);
  8587. return;
  8588. }
  8589. const chunkSize = isHeavyGridWaterMode
  8590. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  8591. : (isMediaLibraryListMode
  8592. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  8593. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  8594. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  8595. for (let index = 0; index < items.length; index += chunkSize) {
  8596. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  8597. this.videoLocalList.push(...chunk);
  8598. this.dataSource.appendArrayData(chunk);
  8599. if (index + chunkSize < items.length) {
  8600. await this.delayMs(chunkDelay);
  8601. }
  8602. }
  8603. }
  8604. /**
  8605. * 加载指定页的数据
  8606. */
  8607. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  8608. try {
  8609. // 1. 检查缓存
  8610. if (this.pageCache.has(pageIndex)) {
  8611. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  8612. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8613. const cachedData = this.pageCache.get(pageIndex)!;
  8614. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  8615. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  8616. if (cachedHasMore !== undefined) {
  8617. this.hasMoreData = cachedHasMore;
  8618. }
  8619. if (cachedTotal !== undefined) {
  8620. this.totalCount = cachedTotal;
  8621. if (this.modeType === 1) {
  8622. this.mediaKuCount = cachedTotal;
  8623. }
  8624. }
  8625. if (append) {
  8626. this.prefetchListThumbsFromItems(cachedData, 26);
  8627. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8628. await this.appendItemsSmoothly(cachedData);
  8629. } else {
  8630. this.videoLocalList = cachedData;
  8631. this.dataSource.pushArrayData(this.videoLocalList);
  8632. if (inMediaLibraryWarmup) {
  8633. this.prefetchListThumbsFromItems(cachedData, 8);
  8634. } else {
  8635. this.prefetchListThumbsFromItems(cachedData, 30);
  8636. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8637. }
  8638. }
  8639. this.setButtonStatus();
  8640. if (inMediaLibraryWarmup) {
  8641. this.scheduleAlphaBetRebuild(900);
  8642. } else {
  8643. this.markAlphaBetDirty();
  8644. }
  8645. if (this.hasMoreData) {
  8646. if (inMediaLibraryWarmup) {
  8647. if (this.mediaLibraryWarmupPrefetchTimer) {
  8648. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8649. }
  8650. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8651. this.mediaLibraryWarmupPrefetchTimer = 0;
  8652. if (this.modeType === 1 && !this.isCanBack) {
  8653. this.prefetchFollowingPages(pageIndex + 1);
  8654. }
  8655. }, 900) as number;
  8656. } else {
  8657. this.prefetchFollowingPages(pageIndex + 1);
  8658. }
  8659. }
  8660. return;
  8661. }
  8662. this.isLoadingPage = true;
  8663. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  8664. // 2. 构造查询参数
  8665. const options: PageQueryOptions = {
  8666. pageIndex: pageIndex,
  8667. pageSize: this.pageSize,
  8668. sortType: this.sortType,
  8669. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8670. isShowFileName: this.isShowFileName
  8671. };
  8672. // 根据 modeType 补充查询条件
  8673. if (this.modeType === 0) {
  8674. options.parentPath = this.currentPath;
  8675. }
  8676. // 3. 执行查询
  8677. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8678. switch (this.modeType) {
  8679. case 0:
  8680. result = await this.table.queryByParentPathPaged(options);
  8681. result.items = this.filterOutLocalIsoItems(result.items);
  8682. // modeType=0时,第一页需要添加文件夹列表
  8683. if (pageIndex === 0 && !this.isSearchMode) {
  8684. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  8685. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  8686. result.items = [...directories, ...isoItems, ...result.items];
  8687. result.totalCount += directories.length + isoItems.length;
  8688. }
  8689. break;
  8690. case 1:
  8691. result = await this.table.queryMediaLibraryPaged(options);
  8692. break;
  8693. case 2:
  8694. result = await this.table.queryArtistsPaged(options);
  8695. break;
  8696. case 3:
  8697. result = await this.table.queryAlbumsPaged(options);
  8698. break;
  8699. default:
  8700. result = await this.table.queryMediaLibraryPaged(options);
  8701. break;
  8702. }
  8703. if (!result || result.items.length === 0) {
  8704. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  8705. this.isLoadingPage = false;
  8706. this.hasMoreData = false;
  8707. // 仅首页为空时清空,后续页为空只终止继续分页
  8708. if (pageIndex === 0) {
  8709. this.totalCount = 0;
  8710. this.videoLocalList = [];
  8711. this.dataSource.pushArrayData(this.videoLocalList);
  8712. this.setButtonStatus();
  8713. this.markAlphaBetDirty();
  8714. }
  8715. return;
  8716. }
  8717. // 4. 更新状态和缓存
  8718. this.totalCount = result.totalCount;
  8719. this.hasMoreData = result.hasMore;
  8720. if (this.modeType === 1) {
  8721. this.mediaKuCount = result.totalCount;
  8722. }
  8723. if (this.modeType === 2 && result.countMap) {
  8724. this.mergeArtistCountMap(result.countMap);
  8725. } else if (this.modeType === 3 && result.countMap) {
  8726. this.mergeAlbumCountMap(result.countMap);
  8727. }
  8728. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  8729. // 缓存管理 - 只保留最近3页
  8730. this.pageCache.set(pageIndex, result.items);
  8731. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  8732. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  8733. this.cleanOldCache(pageIndex);
  8734. // 5. 更新显示列表
  8735. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8736. if (append) {
  8737. this.prefetchListThumbsFromItems(result.items, 26);
  8738. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8739. await this.appendItemsSmoothly(result.items);
  8740. } else {
  8741. this.videoLocalList = result.items;
  8742. this.dataSource.pushArrayData(this.videoLocalList);
  8743. if (inMediaLibraryWarmup) {
  8744. this.prefetchListThumbsFromItems(result.items, 8);
  8745. } else {
  8746. this.prefetchListThumbsFromItems(result.items, 30);
  8747. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8748. }
  8749. }
  8750. this.setButtonStatus();
  8751. if (inMediaLibraryWarmup) {
  8752. this.scheduleAlphaBetRebuild(900);
  8753. } else {
  8754. this.markAlphaBetDirty();
  8755. }
  8756. if (inMediaLibraryWarmup) {
  8757. if (this.mediaLibraryWarmupPrefetchTimer) {
  8758. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8759. }
  8760. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8761. this.mediaLibraryWarmupPrefetchTimer = 0;
  8762. if (this.modeType === 1 && !this.isCanBack) {
  8763. this.prefetchFollowingPages(pageIndex + 1);
  8764. }
  8765. }, 900) as number;
  8766. } else {
  8767. this.prefetchFollowingPages(pageIndex + 1);
  8768. }
  8769. this.isLoadingPage = false;
  8770. } catch (err) {
  8771. const error = err as Error;
  8772. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  8773. // ToastUtil.showToast('加载数据失败');
  8774. this.isLoadingPage = false;
  8775. this.hasMoreData = false;
  8776. }
  8777. }
  8778. /**
  8779. * 清理旧缓存 - 只保留当前页前后各1页
  8780. */
  8781. private cleanOldCache(currentPage: number): void {
  8782. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  8783. const keysToDelete: number[] = [];
  8784. this.pageCache.forEach((_, page) => {
  8785. if (!pagesToKeep.has(page)) {
  8786. keysToDelete.push(page);
  8787. }
  8788. });
  8789. keysToDelete.forEach(page => {
  8790. this.pageCache.delete(page);
  8791. this.pageHasMoreCache.delete(page);
  8792. this.pageTotalCountCache.delete(page);
  8793. });
  8794. if (keysToDelete.length > 0) {
  8795. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  8796. }
  8797. }
  8798. private async prefetchNextPage(nextPage: number): Promise<void> {
  8799. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8800. return;
  8801. }
  8802. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  8803. return;
  8804. }
  8805. const expectedModeType = this.modeType;
  8806. const expectedSortType = this.sortType;
  8807. const expectedIsShowFileName = this.isShowFileName;
  8808. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  8809. const expectedParentPath = this.currentPath;
  8810. this.prefetchingPages.add(nextPage);
  8811. try {
  8812. const options: PageQueryOptions = {
  8813. pageIndex: nextPage,
  8814. pageSize: this.pageSize,
  8815. sortType: this.sortType,
  8816. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8817. isShowFileName: this.isShowFileName
  8818. };
  8819. if (this.modeType === 0) {
  8820. options.parentPath = this.currentPath;
  8821. }
  8822. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8823. switch (this.modeType) {
  8824. case 0:
  8825. result = await this.table.queryByParentPathPaged(options);
  8826. result.items = this.filterOutLocalIsoItems(result.items);
  8827. break;
  8828. case 1:
  8829. result = await this.table.queryMediaLibraryPaged(options);
  8830. break;
  8831. case 2:
  8832. result = await this.table.queryArtistsPaged(options);
  8833. if (result.countMap) {
  8834. this.mergeArtistCountMap(result.countMap);
  8835. }
  8836. break;
  8837. case 3:
  8838. result = await this.table.queryAlbumsPaged(options);
  8839. if (result.countMap) {
  8840. this.mergeAlbumCountMap(result.countMap);
  8841. }
  8842. break;
  8843. default:
  8844. result = await this.table.queryMediaLibraryPaged(options);
  8845. break;
  8846. }
  8847. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  8848. if (expectedModeType !== this.modeType ||
  8849. expectedSortType !== this.sortType ||
  8850. expectedIsShowFileName !== this.isShowFileName ||
  8851. expectedSearchKeyword !== currentSearchKeyword ||
  8852. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  8853. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  8854. return;
  8855. }
  8856. this.pageHasMoreCache.set(nextPage, result.hasMore);
  8857. this.pageTotalCountCache.set(nextPage, result.totalCount);
  8858. if (result.items.length > 0) {
  8859. this.pageCache.set(nextPage, result.items);
  8860. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  8861. this.cleanOldCache(nextPage);
  8862. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  8863. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  8864. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  8865. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  8866. Logger.info('heanup LocalMusic',
  8867. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  8868. this.scheduleLoadNextPage(8);
  8869. }
  8870. }
  8871. }
  8872. } catch (err) {
  8873. const error = err as Error;
  8874. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  8875. } finally {
  8876. this.prefetchingPages.delete(nextPage);
  8877. }
  8878. }
  8879. private mergeArtistCountMap(countMap: Map<string, number>): void {
  8880. const nextMap = new Map(this.artistSongCountMap);
  8881. countMap.forEach((count, artist) => {
  8882. nextMap.set(artist, count);
  8883. });
  8884. this.artistSongCountMap = nextMap;
  8885. }
  8886. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  8887. const nextMap = new Map(this.albumSongCountMap);
  8888. countMap.forEach((count, album) => {
  8889. nextMap.set(album, count);
  8890. });
  8891. this.albumSongCountMap = nextMap;
  8892. }
  8893. private getArtistSongCount(artist: string): number {
  8894. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  8895. }
  8896. private getAlbumSongCount(album: string): number {
  8897. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  8898. }
  8899. /**
  8900. * 加载文件夹列表(仅用于modeType=0的首页模式)
  8901. */
  8902. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  8903. try {
  8904. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  8905. // 检查缓存
  8906. const cacheKey = curPath + "_dirList";
  8907. const cachedDirList = this.findCache(cacheKey);
  8908. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  8909. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  8910. return cachedDirList as VideoItem[];
  8911. }
  8912. // 从文件系统读取
  8913. const fileList = FileUtil.listFileSync(curPath);
  8914. const directories: VideoItem[] = [];
  8915. for (let i = 0; i < fileList.length; i++) {
  8916. const path = curPath + '/' + fileList[i];
  8917. if (FileUtil.isDirectory(path)) {
  8918. const item: VideoItem = new VideoItem(
  8919. fileList[i].toString(),
  8920. fileList[i].toString(),
  8921. path,
  8922. CommonConstants.TYPE_IS_DIR,
  8923. 0,
  8924. ''
  8925. );
  8926. if (this.isShowDir(item.name)) {
  8927. directories.push(item);
  8928. }
  8929. }
  8930. }
  8931. // 排序
  8932. Utility.doSortListAscending(directories);
  8933. // 缓存文件夹列表
  8934. if (curPath === this.rootPath) {
  8935. this.dirList = directories;
  8936. this.addCache(cacheKey, directories);
  8937. }
  8938. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  8939. return directories;
  8940. } catch (err) {
  8941. const error = err as Error;
  8942. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  8943. return [];
  8944. }
  8945. }
  8946. /**
  8947. * 构建播放队列(避免一次性加载全量)
  8948. */
  8949. private buildPlayQueueFromView(): Array<VideoItem> {
  8950. if (this.modeType === 4) {
  8951. this.playQueueScope = 'playlist';
  8952. return this.currentSongList;
  8953. }
  8954. if (this.isHistory) {
  8955. this.playQueueScope = 'history';
  8956. return this.historyList;
  8957. }
  8958. if (this.isFavMusic) {
  8959. this.playQueueScope = 'fav';
  8960. return this.favList;
  8961. }
  8962. this.playQueueScope = 'view';
  8963. return Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8964. }
  8965. private openSpecialLocalList(target: string): void {
  8966. this.mType = 0
  8967. this.isShowDrawer = false
  8968. this.offsetX = 0
  8969. this.isHistory = false
  8970. this.isFavMusic = false
  8971. if (target === 'recent') {
  8972. this.titleName = '最近播放'
  8973. this.currentTitleName = '最近播放'
  8974. this.currentTitleCover = $r('app.media.alt')
  8975. this.updateListData(this.historyList, true)
  8976. if (ArrayUtil.isNotEmpty(this.historyList)) {
  8977. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  8978. }
  8979. this.isHistory = true
  8980. return
  8981. }
  8982. if (target === 'favorite') {
  8983. this.titleName = '我的收藏'
  8984. this.currentTitleName = '我的收藏'
  8985. this.currentTitleCover = $r('app.media.alt')
  8986. this.updateListData(this.favList, true)
  8987. if (ArrayUtil.isNotEmpty(this.favList)) {
  8988. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  8989. }
  8990. this.isFavMusic = true
  8991. }
  8992. }
  8993. private async tryLoadNextPageForPlayback(): Promise<void> {
  8994. if (this.playQueueScope === 'find_paged_local') {
  8995. // 发现页的本地随机分页队列单独补页,不去动主媒体库列表状态。
  8996. await this.loadMoreFindPagedLocalSongs();
  8997. return;
  8998. }
  8999. if (this.playQueueScope !== 'view') {
  9000. return;
  9001. }
  9002. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  9003. return;
  9004. }
  9005. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9006. return;
  9007. }
  9008. await this.loadNextPage();
  9009. const nextList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  9010. if (nextList.length > this.songList.length) {
  9011. this.songList = nextList;
  9012. this.sonDataSource.pushArrayData(this.songList);
  9013. }
  9014. }
  9015. private async loadMoreFindPagedLocalSongs(): Promise<void> {
  9016. if (!this.findPagedLocalQueueHasMore || this.isLoadingFindPagedLocalQueue) {
  9017. return;
  9018. }
  9019. this.isLoadingFindPagedLocalQueue = true;
  9020. const nextPage = this.findPagedLocalQueuePageIndex + 1;
  9021. Logger.info(TAG,
  9022. `loadMoreFindPagedLocalSongs: page=${nextPage}, size=${this.findPagedLocalQueuePageSize}, ` +
  9023. `loaded=${this.songList.length}, total=${this.findPagedLocalQueueTotalCount}`);
  9024. try {
  9025. // 继续按发现页建立队列时的排序规则查询下一页,保证后续页和初始页顺序一致。
  9026. const result = await this.table.queryMediaLibraryPaged({
  9027. pageIndex: nextPage,
  9028. pageSize: this.findPagedLocalQueuePageSize,
  9029. sortType: this.findPagedLocalQueueSortType,
  9030. isShowFileName: this.isShowFileName
  9031. });
  9032. this.findPagedLocalQueuePageIndex = nextPage;
  9033. this.findPagedLocalQueueHasMore = result.hasMore;
  9034. if (result.totalCount > 0) {
  9035. this.findPagedLocalQueueTotalCount = result.totalCount;
  9036. this.totalCount = result.totalCount;
  9037. }
  9038. if (!result.items || result.items.length === 0) {
  9039. return;
  9040. }
  9041. const existingPaths = new Set(this.songList.map((item: VideoItem) => item.filePath));
  9042. // 随机播放过程中可能已经把“未加载页里的歌曲”临时插进队列,这里要去重后再追加。
  9043. const newItems = result.items.filter((item: VideoItem) => !existingPaths.has(item.filePath));
  9044. if (newItems.length === 0) {
  9045. return;
  9046. }
  9047. this.songList.push(...newItems);
  9048. this.currentSongList = this.songList;
  9049. this.sonDataSource.appendArrayData(newItems);
  9050. PreferencesUtil.putSync('LastMusicList', this.songList);
  9051. } catch (error) {
  9052. Logger.error(TAG, `loadMoreFindPagedLocalSongs failed: ${(error as Error).message}`);
  9053. } finally {
  9054. this.isLoadingFindPagedLocalQueue = false;
  9055. }
  9056. }
  9057. /**
  9058. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  9059. * 当播放列表弹窗滚动到底部时调用
  9060. */
  9061. private async loadMoreNavidromeSongs(): Promise<void> {
  9062. const beforeCount = this.songList.length;
  9063. const hasMore = hasMoreData();
  9064. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  9065. if (!hasMore) {
  9066. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  9067. return;
  9068. }
  9069. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  9070. const success = await triggerLoadMoreSongs(1);
  9071. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  9072. if (success) {
  9073. // 获取更新后的完整列表
  9074. const updatedList = getNavidromeVideoItems();
  9075. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  9076. if (updatedList.length > beforeCount) {
  9077. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  9078. this.songList = updatedList;
  9079. this.sonDataSource.pushArrayData(this.songList);
  9080. } else {
  9081. Logger.info('heanup', '列表长度未增加');
  9082. }
  9083. } else {
  9084. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  9085. }
  9086. }
  9087. /**
  9088. * 重置分页状态并加载首页
  9089. */
  9090. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  9091. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  9092. this.currentPage = 0;
  9093. if (clearExistingList) {
  9094. this.videoLocalList = [];
  9095. }
  9096. this.pageCache.clear();
  9097. this.pageHasMoreCache.clear();
  9098. this.pageTotalCountCache.clear();
  9099. this.prefetchingPages.clear();
  9100. this.hasMoreData = true;
  9101. this.totalCount = 0;
  9102. this.lastScrollTriggerPage = -1;
  9103. this.lastVisibleEndIndex = -1;
  9104. this.listScrollAlphaCheckAt = 0;
  9105. this.listScrollPagingCheckAt = 0;
  9106. this.listScrollLastAlphaStart = -1;
  9107. this.listScrollLastPagingEnd = -1;
  9108. this.gridScrollPagingCheckAt = 0;
  9109. this.gridScrollLastPagingEnd = -1;
  9110. this.waterScrollPagingCheckAt = 0;
  9111. this.waterScrollLastPagingEnd = -1;
  9112. this.listVisibleStart = -1;
  9113. this.listVisibleEnd = -1;
  9114. this.listThumbWarmupCheckAt = 0;
  9115. this.listThumbWarmupStart = -1;
  9116. this.listThumbWarmupEnd = -1;
  9117. this.gridThumbWarmupCheckAt = 0;
  9118. this.gridThumbWarmupStart = -1;
  9119. this.gridThumbWarmupEnd = -1;
  9120. this.waterThumbWarmupCheckAt = 0;
  9121. this.waterThumbWarmupStart = -1;
  9122. this.waterThumbWarmupEnd = -1;
  9123. this.gridVisibleStart = -1;
  9124. this.gridVisibleEnd = -1;
  9125. this.waterVisibleStart = -1;
  9126. this.waterVisibleEnd = -1;
  9127. this.gridWaterLastActiveTs = 0;
  9128. this.isPagingTransition = false;
  9129. if (this.pagingScheduleTimer) {
  9130. clearTimeout(this.pagingScheduleTimer);
  9131. this.pagingScheduleTimer = 0;
  9132. }
  9133. if (this.gridWaterScrollIdleTimer) {
  9134. clearTimeout(this.gridWaterScrollIdleTimer);
  9135. this.gridWaterScrollIdleTimer = 0;
  9136. }
  9137. this.coverThumbCache.clearPending();
  9138. this.pendingCoverThumbRefresh = false;
  9139. if (this.modeType === 2) {
  9140. this.artistSongCountMap = new Map();
  9141. } else if (this.modeType === 3) {
  9142. this.albumSongCountMap = new Map();
  9143. }
  9144. await this.loadPage(0, false);
  9145. }
  9146. private markGridWaterScrollingActive(): void {
  9147. if (!this.isScrolling) {
  9148. this.isScrolling = true;
  9149. }
  9150. const now = Date.now();
  9151. if (now - this.gridWaterLastActiveTs < 80) {
  9152. return;
  9153. }
  9154. this.gridWaterLastActiveTs = now;
  9155. if (this.gridWaterScrollIdleTimer) {
  9156. clearTimeout(this.gridWaterScrollIdleTimer);
  9157. }
  9158. this.gridWaterScrollIdleTimer = setTimeout(() => {
  9159. this.gridWaterScrollIdleTimer = 0;
  9160. if (this.isScrolling) {
  9161. this.isScrolling = false;
  9162. }
  9163. this.flushPendingCoverThumbRefresh();
  9164. }, 120);
  9165. }
  9166. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  9167. if (!this.autoHideTitle) {
  9168. return;
  9169. }
  9170. const now = Date.now();
  9171. if (now - this.titleBarLastCheckTs < 36) {
  9172. return;
  9173. }
  9174. this.titleBarLastCheckTs = now;
  9175. const delta = currentOffsetY - this.prevOffsetY;
  9176. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  9177. return;
  9178. }
  9179. if (delta > 0) {
  9180. if (this.isShowTitleBar) {
  9181. this.isShowTitleBar = false;
  9182. }
  9183. } else {
  9184. if (!this.isShowTitleBar) {
  9185. this.isShowTitleBar = true;
  9186. }
  9187. }
  9188. this.prevOffsetY = currentOffsetY;
  9189. }
  9190. private shouldPrefetchSecondPage(): boolean {
  9191. if (this.isMediaLibraryListMode()) {
  9192. return this.pageSize <= 120;
  9193. }
  9194. if (this.pageSize > 60) {
  9195. return false;
  9196. }
  9197. return this.isGridMusic || this.twoFingerType == 4;
  9198. }
  9199. private isMediaLibraryListMode(): boolean {
  9200. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  9201. }
  9202. private isMediaLibraryWarmupWindow(): boolean {
  9203. if (this.modeType !== 1 || this.isCanBack) {
  9204. return false;
  9205. }
  9206. if (this.mediaLibraryEnterTs <= 0) {
  9207. return false;
  9208. }
  9209. return Date.now() - this.mediaLibraryEnterTs < 1800;
  9210. }
  9211. private getDynamicPreloadStartRatio(): number {
  9212. if (this.twoFingerType == 4) {
  9213. return 0.10;
  9214. }
  9215. if (this.isGridMusic) {
  9216. return 0.14;
  9217. }
  9218. if (this.isMediaLibraryListMode()) {
  9219. return 0.12;
  9220. }
  9221. return this.preloadStartRatio;
  9222. }
  9223. private getDynamicAppendStartRatio(): number {
  9224. if (this.twoFingerType == 4) {
  9225. return 0.18;
  9226. }
  9227. if (this.isGridMusic) {
  9228. return 0.22;
  9229. }
  9230. if (this.isMediaLibraryListMode()) {
  9231. return 0.22;
  9232. }
  9233. return this.appendStartRatio;
  9234. }
  9235. private getDynamicEarlyAppendReserveCount(): number {
  9236. if (this.twoFingerType == 4) {
  9237. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9238. }
  9239. if (this.isGridMusic) {
  9240. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  9241. }
  9242. if (this.isMediaLibraryListMode()) {
  9243. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  9244. }
  9245. return this.earlyAppendReserveCount;
  9246. }
  9247. private prefetchFollowingPages(nextPage: number): void {
  9248. void this.prefetchNextPage(nextPage);
  9249. if (this.shouldPrefetchSecondPage()) {
  9250. void this.prefetchNextPage(nextPage + 1);
  9251. }
  9252. }
  9253. private scrollToTopForCurrentLayout(): void {
  9254. if (this.twoFingerType == 4) {
  9255. this.waterScroller.scrollEdge(Edge.Top);
  9256. this.scroller.scrollEdge(Edge.Top);
  9257. return;
  9258. }
  9259. if (this.isGridMusic) {
  9260. this.scroller.scrollEdge(Edge.Top);
  9261. return;
  9262. }
  9263. this.listScroller.scrollEdge(Edge.Top);
  9264. }
  9265. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  9266. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9267. if (coverVersion < -1) {
  9268. return fallback;
  9269. }
  9270. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9271. return fallback;
  9272. }
  9273. const sourceUri = item.pixelMapPath as string;
  9274. this.initCoverThumbCacheIfNeeded();
  9275. const targetSize = this.getListThumbTargetSize();
  9276. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9277. if (cachedThumb) {
  9278. return cachedThumb;
  9279. }
  9280. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9281. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  9282. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  9283. const isNearVisible = !hasRange ||
  9284. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  9285. if (isNearVisible) {
  9286. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9287. }
  9288. }
  9289. return sourceUri;
  9290. }
  9291. private getListThumbTargetSize(): number {
  9292. if (this.twoFingerType == 1) {
  9293. return 96;
  9294. }
  9295. if (this.twoFingerType == 2) {
  9296. return 112;
  9297. }
  9298. return 128;
  9299. }
  9300. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  9301. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  9302. return;
  9303. }
  9304. this.initCoverThumbCacheIfNeeded();
  9305. const targetSize = this.getListThumbTargetSize();
  9306. const maxCount = Math.min(limit, items.length);
  9307. for (let i = 0; i < maxCount; i++) {
  9308. const item = items[i];
  9309. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9310. continue;
  9311. }
  9312. const sourceUri = item.pixelMapPath as string;
  9313. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9314. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9315. }
  9316. }
  9317. }
  9318. private warmupListVisibleThumbs(start: number, end: number): void {
  9319. if (!this.isMediaLibraryListMode()) {
  9320. return;
  9321. }
  9322. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9323. return;
  9324. }
  9325. const now = Date.now();
  9326. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  9327. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  9328. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  9329. return;
  9330. }
  9331. this.listThumbWarmupCheckAt = now;
  9332. this.listThumbWarmupStart = start;
  9333. this.listThumbWarmupEnd = end;
  9334. this.initCoverThumbCacheIfNeeded();
  9335. const targetSize = this.getListThumbTargetSize();
  9336. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  9337. const begin = Math.max(0, start - 4);
  9338. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9339. for (let index = begin; index <= last; index++) {
  9340. const item = this.videoLocalList[index];
  9341. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9342. continue;
  9343. }
  9344. const sourceUri = item.pixelMapPath as string;
  9345. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9346. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9347. }
  9348. }
  9349. }
  9350. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  9351. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  9352. return;
  9353. }
  9354. this.initCoverThumbCacheIfNeeded();
  9355. const isWater = this.twoFingerType == 4;
  9356. const targetSize = this.getCoverThumbTargetSize(isWater);
  9357. const maxCount = Math.min(limit, items.length);
  9358. for (let i = 0; i < maxCount; i++) {
  9359. const item = items[i];
  9360. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9361. continue;
  9362. }
  9363. const sourceUri = item.pixelMapPath as string;
  9364. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9365. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9366. }
  9367. }
  9368. }
  9369. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  9370. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  9371. return;
  9372. }
  9373. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9374. return;
  9375. }
  9376. const now = Date.now();
  9377. let lastStart = -1;
  9378. let lastEnd = -1;
  9379. let lastCheckAt = 0;
  9380. if (isWater) {
  9381. lastStart = this.waterThumbWarmupStart;
  9382. lastEnd = this.waterThumbWarmupEnd;
  9383. lastCheckAt = this.waterThumbWarmupCheckAt;
  9384. } else {
  9385. lastStart = this.gridThumbWarmupStart;
  9386. lastEnd = this.gridThumbWarmupEnd;
  9387. lastCheckAt = this.gridThumbWarmupCheckAt;
  9388. }
  9389. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  9390. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  9391. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  9392. return;
  9393. }
  9394. if (isWater) {
  9395. this.waterThumbWarmupCheckAt = now;
  9396. this.waterThumbWarmupStart = start;
  9397. this.waterThumbWarmupEnd = end;
  9398. } else {
  9399. this.gridThumbWarmupCheckAt = now;
  9400. this.gridThumbWarmupStart = start;
  9401. this.gridThumbWarmupEnd = end;
  9402. }
  9403. this.initCoverThumbCacheIfNeeded();
  9404. const columns = isWater ? Math.max(this.columns, 1) :
  9405. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9406. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  9407. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  9408. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9409. const targetSize = this.getCoverThumbTargetSize(isWater);
  9410. for (let index = begin; index <= last; index++) {
  9411. const item = this.videoLocalList[index];
  9412. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9413. continue;
  9414. }
  9415. const sourceUri = item.pixelMapPath as string;
  9416. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9417. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9418. }
  9419. }
  9420. }
  9421. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  9422. coverVersion: number = 0): ResourceStr {
  9423. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9424. if (coverVersion < -1) {
  9425. return fallback;
  9426. }
  9427. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9428. return fallback;
  9429. }
  9430. const sourceUri = item.pixelMapPath as string;
  9431. this.initCoverThumbCacheIfNeeded();
  9432. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  9433. const targetSize = this.getCoverThumbTargetSize(isWater);
  9434. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9435. if (cachedThumb) {
  9436. return cachedThumb;
  9437. }
  9438. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  9439. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  9440. const columns = isWater ? Math.max(this.columns, 1) :
  9441. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9442. const preloadBuffer = Math.max(columns * 2, 8);
  9443. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  9444. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  9445. if (!isRemoteCover && isNearVisible) {
  9446. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9447. }
  9448. if (!this.isScrolling) {
  9449. return sourceUri;
  9450. }
  9451. if (isNearVisible) {
  9452. return sourceUri;
  9453. }
  9454. return fallback;
  9455. }
  9456. private flushPendingCoverThumbRefresh(): void {
  9457. if (!this.pendingCoverThumbRefresh) {
  9458. return;
  9459. }
  9460. this.pendingCoverThumbRefresh = false;
  9461. this.coverThumbVersion++;
  9462. }
  9463. private initCoverThumbCacheIfNeeded(): void {
  9464. if (this.coverThumbCacheReady) {
  9465. return;
  9466. }
  9467. this.coverThumbCache.setContext(this.context);
  9468. this.coverThumbCache.setOnThumbReady(() => {
  9469. if (this.isScrolling) {
  9470. this.pendingCoverThumbRefresh = true;
  9471. return;
  9472. }
  9473. this.coverThumbVersion++;
  9474. });
  9475. this.coverThumbCacheReady = true;
  9476. }
  9477. private getCoverThumbTargetSize(isWater: boolean): number {
  9478. if (isWater) {
  9479. if (this.columns >= 4) {
  9480. return 160;
  9481. }
  9482. if (this.columns == 3) {
  9483. return 200;
  9484. }
  9485. return 260;
  9486. }
  9487. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  9488. if (this.twoFingerType == 1) {
  9489. return baseSize;
  9490. }
  9491. if (this.twoFingerType == 2) {
  9492. return Math.floor(baseSize * 1.1);
  9493. }
  9494. return Math.floor(baseSize * 1.15);
  9495. }
  9496. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  9497. if (this.videoLocalList.length <= 0) {
  9498. return;
  9499. }
  9500. const columns = Math.max(this.columns, 1);
  9501. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  9502. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  9503. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  9504. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  9505. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  9506. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  9507. this.waterVisibleStart = startIndex;
  9508. this.waterVisibleEnd = estimatedEnd;
  9509. this.lastVisibleEndIndex = estimatedEnd;
  9510. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  9511. const now = Date.now();
  9512. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  9513. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  9514. this.waterScrollPagingCheckAt = now;
  9515. this.waterScrollLastPagingEnd = estimatedEnd;
  9516. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  9517. }
  9518. }
  9519. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  9520. if (this.modeType === 4) {
  9521. return;
  9522. }
  9523. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  9524. return;
  9525. }
  9526. if (this.isHistory || this.isFavMusic) {
  9527. return;
  9528. }
  9529. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9530. return;
  9531. }
  9532. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  9533. return;
  9534. }
  9535. const nextPage = this.currentPage + 1;
  9536. const next2Page = this.currentPage + 2;
  9537. const totalLoaded = this.videoLocalList.length;
  9538. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  9539. const remainCount = this.videoLocalList.length - endIndex - 1;
  9540. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  9541. const appendStartRatio = this.getDynamicAppendStartRatio();
  9542. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  9543. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  9544. if (seenRatio >= preloadStartRatio) {
  9545. if (!this.pageCache.has(nextPage)) {
  9546. void this.prefetchNextPage(nextPage);
  9547. }
  9548. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  9549. void this.prefetchNextPage(next2Page);
  9550. }
  9551. }
  9552. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  9553. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  9554. const shouldGapAppend = this.pageCache.has(nextPage) &&
  9555. seenRatio >= (appendStartRatio - 0.08) &&
  9556. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9557. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  9558. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  9559. return;
  9560. }
  9561. if (this.lastScrollTriggerPage === this.currentPage) {
  9562. return;
  9563. }
  9564. this.lastScrollTriggerPage = this.currentPage;
  9565. Logger.info('heanup LocalMusic',
  9566. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  9567. this.scheduleLoadNextPage(8);
  9568. }
  9569. private scheduleLoadNextPage(delayMs: number = 0): void {
  9570. if (this.pagingScheduleTimer) {
  9571. return;
  9572. }
  9573. this.pagingScheduleTimer = setTimeout(() => {
  9574. this.pagingScheduleTimer = 0;
  9575. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9576. return;
  9577. }
  9578. void this.loadNextPage();
  9579. }, delayMs);
  9580. }
  9581. /**
  9582. * 加载下一页
  9583. */
  9584. private async loadNextPage(): Promise<void> {
  9585. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9586. return;
  9587. }
  9588. this.isPagingTransition = true;
  9589. this.currentPage++;
  9590. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  9591. try {
  9592. await this.loadPage(this.currentPage, true);
  9593. } finally {
  9594. this.isPagingTransition = false;
  9595. }
  9596. }
  9597. //编辑信息
  9598. async doEdit(item: VideoItem) {
  9599. if (!item) {
  9600. return
  9601. }
  9602. if (StrUtil.isEmpty(this.titleStr)) {
  9603. ToastUtil.showToast('标题不能为空')
  9604. return
  9605. }
  9606. //内嵌音乐标签不能开启监听
  9607. // this.deletionWatcher?.stop();
  9608. this.loadingDialogId = DialogHelper.showLoadingDialog()
  9609. if (isRemoteCloudType(item.type)) {
  9610. await this.saveRemoteSongEdit(item);
  9611. return;
  9612. }
  9613. await PermissionUtil.activatePermission(item.filePath)
  9614. let tempOutPath = ''
  9615. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  9616. if(!item.filePath.toLowerCase().includes(this.packName)){
  9617. tempOutPath = this.currentPath + '/' + item.fileName
  9618. }
  9619. console.info('onecold tempOutPath ='+tempOutPath)
  9620. //用户更改了封面,那就内嵌下封面
  9621. if(StrUtil.isNotEmpty(this.imagePathStr)){
  9622. const resultCover:boolean = await changeMusicCover(this.context,
  9623. item.filePath,this.imagePathStr,true,tempOutPath);
  9624. this.imagePathStr = ''
  9625. if(resultCover){
  9626. ToastUtil.showToast('内嵌封面成功')
  9627. }
  9628. }
  9629. const metadata:FFMpegTags = {
  9630. title: this.titleStr,
  9631. artist: this.artistStr,
  9632. album: this.ablumStr,
  9633. TYER:this.yearStr,
  9634. genre:this.genreStr,
  9635. track:this.trackStr,
  9636. album_artist:this.albumArtistStr,
  9637. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  9638. COMPOSER:this.composerStr,
  9639. lyricist:this.lyricistStr,
  9640. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  9641. comment:this.commentStr,
  9642. disc:this.discStr,
  9643. };
  9644. let newInput = item.filePath
  9645. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  9646. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  9647. newInput = tempOutPath
  9648. tempOutPath = ''
  9649. }
  9650. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  9651. ||newInput.toLowerCase().endsWith('.ape')
  9652. ||newInput.toLowerCase().endsWith('.dsf')
  9653. ||newInput.toLowerCase().endsWith('.dff');
  9654. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  9655. const result:boolean = await repairAudioMetadata(
  9656. newInput,
  9657. this.lyricConStr,
  9658. metadata,
  9659. true,
  9660. tempOutPath
  9661. );
  9662. // ToastUtil.showToast('result ='+ result)
  9663. if (result||isWav) {
  9664. if(!item.filePath.includes(this.packName)){
  9665. //内嵌成功的歌路径如果不是包含包名,则要入库
  9666. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  9667. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  9668. this.table.insert(newItem, (id: number) => {
  9669. //加入数据库
  9670. if(this.modeType==0){
  9671. this.deleteCache(this.currentPath)
  9672. this.getSortedFiles(this.currentPath)
  9673. }
  9674. });
  9675. }
  9676. const task = new taskpool.Task(
  9677. updateInfoDb,
  9678. this.context,
  9679. item.filePath,
  9680. this.titleStr,
  9681. this.artistStr,
  9682. this.ablumStr,
  9683. this.lyricConStr,
  9684. this.yearStr,this.genreStr,
  9685. this.trackStr,this.albumArtistStr,
  9686. this.composerStr, this.lyricistStr,
  9687. this.commentStr,this.discStr
  9688. );
  9689. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  9690. if (result) {
  9691. console.log(" onecold 编辑信息成功,数据库已同步");
  9692. if(isWav){
  9693. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  9694. }else{
  9695. ToastUtil.showToast('内嵌音乐标签成功')
  9696. }
  9697. this.isShowMoreView = false
  9698. this.name = this.titleStr
  9699. this.syncEditedFields(item)
  9700. if (item.filePath == this.currentSong?.filePath) {
  9701. this.currentSong.name = this.titleStr
  9702. this.artist = this.artistStr
  9703. this.currentSong.artist = this.artistStr
  9704. this.currentSong.album = this.ablumStr
  9705. this.currentSong.year = this.yearStr
  9706. this.currentSong.genre = this.genreStr
  9707. this.currentSong.track = this.trackStr
  9708. this.currentSong.lyricContent = this.lyricConStr
  9709. this.currentSong.ALBUMARTIST = this.albumArtistStr
  9710. this.currentSong.COMPOSER = this.composerStr
  9711. this.currentSong.LYRICIST = this.lyricistStr
  9712. this.currentSong.COMMENT = this.commentStr
  9713. }
  9714. this.syncListsAfterEdit(item.filePath)
  9715. this.doUpateEditedFields(item)
  9716. //this.doUpdateData()
  9717. } else {
  9718. // ToastUtil.showToast('保存失败' + error?.toString())
  9719. console.error(" onecold 编辑信息数据库失败 ");
  9720. }
  9721. // 关闭进度条
  9722. DialogHelper.closeDialog(this.loadingDialogId)
  9723. }).catch((error: Error) => {
  9724. // 关闭进度条
  9725. DialogHelper.closeDialog(this.loadingDialogId)
  9726. console.error('onecold Subtitle sync failed:', error);
  9727. });
  9728. console.log(' onecold 元数据标签更新成功,');
  9729. } else {
  9730. // 关闭进度条
  9731. DialogHelper.closeDialog(this.loadingDialogId)
  9732. ToastUtil.showToast('内嵌音乐标签失败')
  9733. console.log('onecold 内嵌音乐标签失败');
  9734. }
  9735. this.longItemFilePath = ''
  9736. this.tempLyricContent = ''
  9737. this.isShowEdit = false
  9738. }
  9739. private normalizeEditedCoverPath(path: string): string {
  9740. if (StrUtil.isEmpty(path)) {
  9741. return '';
  9742. }
  9743. const lowerPath = path.toLowerCase();
  9744. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  9745. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  9746. return path;
  9747. }
  9748. return fileUri.getUriFromPath(path);
  9749. }
  9750. private emitRemoteMetadataUpdated(item: VideoItem): void {
  9751. if (!item || StrUtil.isEmpty(item.filePath)) {
  9752. return;
  9753. }
  9754. const payload: WebDavMetadataUpdatePayload = {
  9755. filePath: item.filePath,
  9756. pixelMapPath: item.pixelMapPath,
  9757. isCustomCover: item.isCustomCover,
  9758. md5Str: item.md5Str,
  9759. name: item.name,
  9760. artist: item.artist
  9761. };
  9762. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  9763. emitter.emit(eventUpdate, { data: [payload] });
  9764. }
  9765. private syncRemoteManagerSong(item: VideoItem): void {
  9766. if (!item || StrUtil.isEmpty(item.filePath)) {
  9767. return;
  9768. }
  9769. const remoteManager = RemoteDriveManager.getInstance();
  9770. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  9771. if (!target) {
  9772. return;
  9773. }
  9774. this.mergeVideoItemFromSource(target, item);
  9775. }
  9776. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  9777. try {
  9778. this.syncEditedFields(item);
  9779. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  9780. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  9781. item.isCustomCover = 1;
  9782. }
  9783. this.name = this.titleStr;
  9784. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  9785. this.syncEditedFields(this.currentSong);
  9786. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  9787. mergeCoverWithPriority(this.currentSong, item.pixelMapPath, item.isCustomCover ?? 0);
  9788. this.cover = this.currentSong.pixelMapPath || item.pixelMapPath;
  9789. }
  9790. this.artist = this.currentSong.artist ?? '';
  9791. this.currentSong = cloneVideoItem(this.currentSong);
  9792. AppStorage.setOrCreate('currentSong', this.currentSong);
  9793. }
  9794. this.syncListsAfterEdit(item.filePath);
  9795. this.syncRemoteManagerSong(item);
  9796. await this.persistRemoteMetadataToDb(item);
  9797. this.emitRemoteMetadataUpdated(item);
  9798. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  9799. } catch (error) {
  9800. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  9801. ToastUtil.showToast('网盘歌曲编辑失败');
  9802. } finally {
  9803. DialogHelper.closeDialog(this.loadingDialogId);
  9804. this.longItemFilePath = '';
  9805. this.tempLyricContent = '';
  9806. this.isShowEdit = false;
  9807. this.imagePathStr = '';
  9808. this.isShowMoreView = false;
  9809. }
  9810. }
  9811. // 内嵌标签更新当前内嵌的Item
  9812. async doUpateEditedFields(item: VideoItem) {
  9813. // 找到当前项在 videoLocalList 中的索引
  9814. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  9815. if (index !== -1) {
  9816. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  9817. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  9818. // 只有当查询结果不为 null 时才更新列表
  9819. if (updatedItem !== null) {
  9820. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  9821. this.videoLocalList = [
  9822. ...this.videoLocalList.slice(0, index),
  9823. updatedItem,
  9824. ...this.videoLocalList.slice(index + 1)
  9825. ];
  9826. // 同步更新 LazyDataSource
  9827. this.dataSource.pushArrayData(this.videoLocalList)
  9828. } else {
  9829. ToastUtil.showToast('未找到更新的数据');
  9830. }
  9831. }
  9832. DialogHelper.closeDialog(this.loadingDialogId)
  9833. }
  9834. @Builder
  9835. editSheet(item: VideoItem) {
  9836. Scroll() {
  9837. Column() {
  9838. this.editDetail(item)
  9839. }
  9840. }
  9841. .width('100%')
  9842. .height('100%')
  9843. }
  9844. @Builder
  9845. editDetail(item: VideoItem) {
  9846. Column() {
  9847. if (item) {
  9848. Row() {
  9849. Stack() {
  9850. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  9851. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  9852. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  9853. item.pixelMapPath)
  9854. .fillColor(this.themeColor)
  9855. .height(88)
  9856. .width(88)
  9857. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9858. .borderRadius(12)
  9859. .clip(true)
  9860. .opacity(this.opacityItem)// 绑定透明度
  9861. .margin({ left: 25 })
  9862. }
  9863. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9864. .onClick(async () => {
  9865. const imagePath:string | undefined = await this.goSelectImage(item);
  9866. if (imagePath) {
  9867. //用户更改过图片
  9868. this.imagePathStr = imagePath
  9869. }
  9870. })
  9871. .width('28%')
  9872. Row() {
  9873. Column() {
  9874. Text(item.name)
  9875. .fontSize(17)
  9876. .maxLines(1)
  9877. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9878. .animation({
  9879. duration: 555,
  9880. curve: 'Linear',
  9881. })
  9882. .fontColor(this.themeColor)
  9883. .margin({ left: 8 })
  9884. Row() {
  9885. Text(item.artist)
  9886. .fontSize(14)
  9887. .maxLines(1)
  9888. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9889. .padding({ top: 8 })
  9890. .fontColor(this.themeColor)
  9891. .margin({ left: 8 })
  9892. }
  9893. }
  9894. .height('100%')
  9895. .width(100)
  9896. .layoutWeight(1)
  9897. .justifyContent(FlexAlign.Center)
  9898. .alignItems(HorizontalAlign.Start)
  9899. Column() {
  9900. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9901. Row(){
  9902. SymbolGlyph($r('sys.symbol.picture'))
  9903. .fontSize(18)
  9904. .fontColor([Color.White])
  9905. Text('获取封面')
  9906. .margin({ left: 4 })
  9907. .fontSize(11)
  9908. .fontColor(Color.White)
  9909. .fontWeight(480)
  9910. .textAlign(TextAlign.Center)
  9911. }
  9912. .justifyContent(FlexAlign.Center)
  9913. }
  9914. .height(38)
  9915. .width(100)
  9916. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9917. .backgroundColor(this.themeColor)
  9918. .stateEffect(true)
  9919. .margin({ right: 35 })
  9920. .onClick(async () => {
  9921. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9922. this.showTipsDialog();
  9923. return; // Return empty string when no API is configured
  9924. }
  9925. const imagePath:string | undefined = await this.doSearchCover(item,
  9926. this.titleStr,this.artistStr);
  9927. console.info('onecold imagePath = '+imagePath)
  9928. if (StrUtil.isNotEmpty(imagePath)) {
  9929. //用户更改过图片
  9930. this.imagePathStr = imagePath
  9931. ToastUtil.showToast('获取封面成功')
  9932. }else{
  9933. ToastUtil.showToast('获取封面失败,请重试')
  9934. }
  9935. })
  9936. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9937. Row(){
  9938. SymbolGlyph($r('sys.symbol.input_mode'))
  9939. .fontSize(18)
  9940. .fontColor([Color.White])
  9941. Text('获取歌词')
  9942. .margin({ left: 4 })
  9943. .fontSize(11)
  9944. .fontColor(Color.White)
  9945. .fontWeight(480)
  9946. .textAlign(TextAlign.Center)
  9947. }
  9948. .justifyContent(FlexAlign.Center)
  9949. }
  9950. .height(38)
  9951. .width(100)
  9952. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9953. .backgroundColor(this.themeColor)
  9954. .stateEffect(true)
  9955. .margin({ top: 9, right: 35 })
  9956. .onClick(async () => {
  9957. //判断有没有设置api
  9958. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  9959. if (StrUtil.isEmpty(apiUrl)) {
  9960. this.isLyricSetting = false
  9961. this.showTipsDialog()
  9962. return
  9963. }
  9964. let res: string | undefined = await getApiLyric(apiUrl,
  9965. this.titleStr, this.artistStr, false);
  9966. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9967. this.lyricConStr = res;
  9968. ToastUtil.showToast('获取歌词成功')
  9969. }else{
  9970. ToastUtil.showToast('获取歌词失败,请重试')
  9971. }
  9972. })
  9973. }
  9974. .justifyContent(FlexAlign.Start)
  9975. }
  9976. .height('100%')
  9977. .justifyContent(FlexAlign.Start)
  9978. .layoutWeight(1)
  9979. }
  9980. .width('100%')
  9981. .height(98)
  9982. Row() {
  9983. Text('标题:')
  9984. .fontSize(14)
  9985. .fontColor($r('app.color.text_color'))
  9986. .margin({ left: 22 })
  9987. TextInput({ text: this.titleStr })
  9988. .height(40)
  9989. .maxLines(1)
  9990. .fontSize(14)
  9991. .layoutWeight(1)
  9992. .fontColor($r('app.color.text_color'))
  9993. .margin({ right: 15, left: 10 })
  9994. .onChange((val: string) => {
  9995. this.titleStr = val
  9996. })
  9997. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  9998. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9999. .backgroundColor(this.themeColor)
  10000. .fontSize(10)
  10001. .margin({ right: 20})
  10002. .onClick(async () => {
  10003. let hwTags = await extractHwMediaMetadata(item.filePath)
  10004. let artist = hwTags?.artist|| '';
  10005. let title = hwTags?.title|| '';
  10006. let album = hwTags?.album|| '';
  10007. console.info('onecold 乱码修正 artist='+artist);
  10008. console.info('onecold 乱码修正 title='+title);
  10009. console.info('onecold 乱码修正 album='+album);
  10010. this.titleStr = title;
  10011. this.artistStr = artist;
  10012. this.ablumStr = album;
  10013. })
  10014. }
  10015. .width('100%')
  10016. .margin({ top: 10, bottom: 10 })
  10017. .justifyContent(FlexAlign.Start)
  10018. Row() {
  10019. Text('艺术家:')
  10020. .fontSize(14)
  10021. .fontColor($r('app.color.text_color'))
  10022. .margin({ left: 22 })
  10023. TextInput({ text: this.artistStr })
  10024. .height(40)
  10025. .maxLines(1)
  10026. .fontSize(14)
  10027. .layoutWeight(1)
  10028. .fontColor($r('app.color.text_color'))
  10029. .margin({ right: 20, left: 10 })
  10030. .onChange((val: string) => {
  10031. this.artistStr = val
  10032. })
  10033. }
  10034. .width('100%')
  10035. .margin({ top: 10, bottom: 10 })
  10036. .justifyContent(FlexAlign.Start)
  10037. Row() {
  10038. Text('专辑名:')
  10039. .fontSize(14)
  10040. .fontColor($r('app.color.text_color'))
  10041. .margin({ left: 22 })
  10042. TextInput({ text: this.ablumStr})
  10043. .height(40)
  10044. .maxLines(1)
  10045. .fontSize(14)
  10046. .layoutWeight(1)
  10047. .fontColor($r('app.color.text_color'))
  10048. .margin({ right: 20, left: 10 })
  10049. .onChange((val: string) => {
  10050. this.ablumStr = val
  10051. })
  10052. }
  10053. .width('100%')
  10054. .margin({ top: 10, bottom: 10 })
  10055. .justifyContent(FlexAlign.Start)
  10056. Row() {
  10057. Column(){
  10058. Column(){
  10059. Text('歌词:')
  10060. .fontSize(14)
  10061. .fontColor($r('app.color.text_color'))
  10062. .margin({ top:9,left: 22 })
  10063. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10064. SymbolGlyph($r('sys.symbol.trash_fill'))
  10065. .fontSize(25)
  10066. .alignSelf(ItemAlign.Center)
  10067. .margin({ left: 22,top:25})
  10068. }
  10069. .backgroundColor(Color.Transparent)
  10070. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10071. Visibility.None:Visibility.Visible)
  10072. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10073. .onClick(()=>{
  10074. this.lyricConStr = ''
  10075. this.lyricContent = ''
  10076. this.tempLyricContent = ''
  10077. })
  10078. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10079. SymbolGlyph($r('sys.symbol.plus'))
  10080. .fontSize(25)
  10081. .alignSelf(ItemAlign.Center)
  10082. .margin({ left: 22,top:25})
  10083. }
  10084. .backgroundColor(Color.Transparent)
  10085. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10086. .onClick( ()=>{
  10087. this.callFilePickerSelectFileForLyric()
  10088. })
  10089. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10090. SymbolGlyph($r('sys.symbol.traditional_square'))
  10091. .fontSize(25)
  10092. .alignSelf(ItemAlign.Center)
  10093. .margin({ left: 22,top:25})
  10094. }
  10095. .backgroundColor(Color.Transparent)
  10096. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10097. Visibility.None:Visibility.Visible)
  10098. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10099. .onClick( ()=>{
  10100. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  10101. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  10102. })
  10103. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10104. Image($r('app.media.jianti'))
  10105. .height(25)
  10106. .fillColor($r('app.color.text_color'))
  10107. .alignSelf(ItemAlign.Center)
  10108. .margin({ left: 22,top:25})
  10109. }
  10110. .backgroundColor(Color.Transparent)
  10111. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10112. Visibility.None:Visibility.Visible)
  10113. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10114. .onClick( ()=>{
  10115. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  10116. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  10117. })
  10118. }
  10119. .layoutWeight(1)
  10120. }
  10121. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  10122. this.tempLyricContent })
  10123. .type(TextAreaType.NORMAL)
  10124. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  10125. .fontSize(14)
  10126. .layoutWeight(1)
  10127. .fontColor($r('app.color.text_color'))
  10128. .margin({ right: 20, left: 10 })
  10129. .onChange((val: string) => {
  10130. this.lyricConStr = val
  10131. })
  10132. }
  10133. .width('100%')
  10134. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  10135. .margin({ top: 10, bottom: 10 })
  10136. .justifyContent(FlexAlign.Start)
  10137. Row() {
  10138. Text('年份:')
  10139. .fontSize(14)
  10140. .fontColor($r('app.color.text_color'))
  10141. .margin({ left: 22 })
  10142. TextInput({ text: item.year })
  10143. .height(40)
  10144. .maxLines(1)
  10145. .fontSize(14)
  10146. .type(InputType.Number)
  10147. .layoutWeight(1)
  10148. .fontColor($r('app.color.text_color'))
  10149. .margin({ right: 20, left: 10 })
  10150. .onChange((val: string) => {
  10151. this.yearStr = val
  10152. })
  10153. }
  10154. .width('100%')
  10155. .margin({ top: 10, bottom: 10 })
  10156. .justifyContent(FlexAlign.Start)
  10157. Row() {
  10158. Text('音轨号:')
  10159. .fontSize(14)
  10160. .fontColor($r('app.color.text_color'))
  10161. .margin({ left: 22 })
  10162. TextInput({ text:item.track=='未知'?'': item.track })
  10163. .height(40)
  10164. .maxLines(1)
  10165. .fontSize(14)
  10166. .type(InputType.Number)
  10167. .layoutWeight(1)
  10168. .fontColor($r('app.color.text_color'))
  10169. .margin({ right: 20, left: 10 })
  10170. .onChange((val: string) => {
  10171. this.trackStr = val
  10172. })
  10173. }
  10174. .width('100%')
  10175. .margin({ top: 10, bottom: 10 })
  10176. .justifyContent(FlexAlign.Start)
  10177. Row() {
  10178. Text('碟号:')
  10179. .fontSize(14)
  10180. .fontColor($r('app.color.text_color'))
  10181. .margin({ left: 22 })
  10182. TextInput({ text:item.disc })
  10183. .height(40)
  10184. .maxLines(1)
  10185. .fontSize(14)
  10186. .type(InputType.Number)
  10187. .layoutWeight(1)
  10188. .fontColor($r('app.color.text_color'))
  10189. .margin({ right: 20, left: 10 })
  10190. .onChange((val: string) => {
  10191. this.discStr = val
  10192. })
  10193. }
  10194. .width('100%')
  10195. .margin({ top: 10, bottom: 10 })
  10196. .justifyContent(FlexAlign.Start)
  10197. Row() {
  10198. Text('风格:')
  10199. .fontSize(14)
  10200. .fontColor($r('app.color.text_color'))
  10201. .margin({ left: 22 })
  10202. TextInput({ text: item.genre })
  10203. .height(40)
  10204. .maxLines(1)
  10205. .fontSize(14)
  10206. .layoutWeight(1)
  10207. .fontColor($r('app.color.text_color'))
  10208. .margin({ right: 20, left: 10 })
  10209. .onChange((val: string) => {
  10210. this.genreStr = val
  10211. })
  10212. }
  10213. .width('100%')
  10214. .margin({ top: 10, bottom: 10 })
  10215. .justifyContent(FlexAlign.Start)
  10216. Row() {
  10217. Text('专辑艺术家:')
  10218. .fontSize(14)
  10219. .fontColor($r('app.color.text_color'))
  10220. .margin({ left: 22 })
  10221. TextInput({ text: item.ALBUMARTIST })
  10222. .height(40)
  10223. .maxLines(1)
  10224. .fontSize(14)
  10225. .layoutWeight(1)
  10226. .fontColor($r('app.color.text_color'))
  10227. .margin({ right: 20, left: 10 })
  10228. .onChange((val: string) => {
  10229. this.albumArtistStr = val
  10230. })
  10231. }
  10232. .width('100%')
  10233. .margin({ top: 10, bottom: 10 })
  10234. .justifyContent(FlexAlign.Start)
  10235. Row() {
  10236. Text('作曲:')
  10237. .fontSize(14)
  10238. .fontColor($r('app.color.text_color'))
  10239. .margin({ left: 22 })
  10240. TextInput({ text: item.COMPOSER })
  10241. .height(40)
  10242. .maxLines(1)
  10243. .fontSize(14)
  10244. .layoutWeight(1)
  10245. .fontColor($r('app.color.text_color'))
  10246. .margin({ right: 20, left: 10 })
  10247. .onChange((val: string) => {
  10248. this.composerStr = val
  10249. })
  10250. }
  10251. .width('100%')
  10252. .margin({ top: 10, bottom: 10 })
  10253. .justifyContent(FlexAlign.Start)
  10254. Row() {
  10255. Text('作词:')
  10256. .fontSize(14)
  10257. .fontColor($r('app.color.text_color'))
  10258. .margin({ left: 22 })
  10259. TextInput({ text: item.LYRICIST })
  10260. .height(40)
  10261. .maxLines(1)
  10262. .fontSize(14)
  10263. .layoutWeight(1)
  10264. .fontColor($r('app.color.text_color'))
  10265. .margin({ right: 20, left: 10 })
  10266. .onChange((val: string) => {
  10267. this.lyricistStr = val
  10268. })
  10269. }
  10270. .width('100%')
  10271. .margin({ top: 10, bottom: 10 })
  10272. .justifyContent(FlexAlign.Start)
  10273. Row() {
  10274. Text('注释:')
  10275. .fontSize(14)
  10276. .fontColor($r('app.color.text_color'))
  10277. .margin({ left: 22 })
  10278. TextInput({ text: item.COMMENT })
  10279. .height(40)
  10280. .maxLines(1)
  10281. .fontSize(14)
  10282. .layoutWeight(1)
  10283. .fontColor($r('app.color.text_color'))
  10284. .margin({ right: 20, left: 10 })
  10285. .onChange((val: string) => {
  10286. this.commentStr = val
  10287. })
  10288. }
  10289. .width('100%')
  10290. .margin({ top: 10, bottom: 10 })
  10291. .justifyContent(FlexAlign.Start)
  10292. Row() {
  10293. Button('保存')
  10294. .fontColor(Color.White)
  10295. .layoutWeight(1)
  10296. .height(50)
  10297. .width(100)
  10298. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10299. .backgroundColor(this.themeColor)
  10300. .stateEffect(true)
  10301. .margin({ right: 20, bottom: 20 })
  10302. .onClick(async () => {
  10303. this.doEdit(item)
  10304. })
  10305. Button('取消')
  10306. .fontColor(Color.White)
  10307. .layoutWeight(1)
  10308. .height(50)
  10309. .width(100)
  10310. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10311. .backgroundColor(this.themeColor)
  10312. .stateEffect(true)
  10313. .margin({ left: 20, bottom: 20 })
  10314. .onClick(async () => {
  10315. if(this.isGridMusic){
  10316. this.longItemFilePath =''
  10317. }else{
  10318. this.isShowEdit = false
  10319. }
  10320. this.setEditStrEmpty()
  10321. if(this.isShowPlay){
  10322. this.isShowEdit = false
  10323. }
  10324. })
  10325. }
  10326. .margin({
  10327. left: 38,
  10328. right: 38,
  10329. top: 10,
  10330. bottom: 10
  10331. })
  10332. .width(250)
  10333. .height(60)
  10334. }
  10335. }
  10336. .margin({ bottom: 20 })
  10337. }
  10338. setEditStrEmpty(){
  10339. this.imagePathStr = ''
  10340. this.lyricConStr = ''
  10341. this.artistStr = ''
  10342. this.titleStr = ''
  10343. this.ablumStr = ''
  10344. this.genreStr = ''
  10345. this.yearStr = ''
  10346. this.trackStr = ''
  10347. this.albumArtistStr = ''
  10348. this.composerStr = ''
  10349. this.lyricistStr = ''
  10350. this.commentStr = ''
  10351. this.discStr = ''
  10352. }
  10353. initEditFields(item?: VideoItem) {
  10354. if (!item) {
  10355. this.setEditStrEmpty()
  10356. return
  10357. }
  10358. this.imagePathStr = ''
  10359. this.titleStr = item.name ?? ''
  10360. this.artistStr = item.artist ?? ''
  10361. this.ablumStr = item.album ?? ''
  10362. this.genreStr = item.genre ?? ''
  10363. this.yearStr = item.year ?? ''
  10364. this.trackStr = item.track ?? ''
  10365. this.albumArtistStr = item.ALBUMARTIST ?? ''
  10366. this.composerStr = item.COMPOSER ?? ''
  10367. this.lyricistStr = item.LYRICIST ?? ''
  10368. this.commentStr = item.COMMENT ?? ''
  10369. this.discStr = item.disc ?? ''
  10370. this.lyricConStr = item.lyricContent ?? ''
  10371. }
  10372. private syncEditedFields(target?: VideoItem) {
  10373. if (!target) {
  10374. return
  10375. }
  10376. target.name = this.titleStr
  10377. target.artist = this.artistStr
  10378. target.album = this.ablumStr
  10379. target.lyricContent = this.lyricConStr
  10380. target.year = this.yearStr
  10381. target.genre = this.genreStr
  10382. target.track = this.trackStr
  10383. target.ALBUMARTIST = this.albumArtistStr
  10384. target.COMPOSER = this.composerStr
  10385. target.LYRICIST = this.lyricistStr
  10386. target.COMMENT = this.commentStr
  10387. target.disc = this.discStr
  10388. }
  10389. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  10390. apply?: (next: Array<VideoItem>) => void) {
  10391. if (!list || ArrayUtil.isEmpty(list)) {
  10392. return
  10393. }
  10394. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  10395. if (index < 0) {
  10396. return
  10397. }
  10398. const nextList = [...list]
  10399. this.syncEditedFields(nextList[index])
  10400. apply?.(nextList)
  10401. }
  10402. private syncListsAfterEdit(filePath: string) {
  10403. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  10404. this.videoLocalList = next
  10405. this.dataSource.pushArrayData(next)
  10406. })
  10407. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  10408. this.songList = next
  10409. this.sonDataSource.pushArrayData(next)
  10410. })
  10411. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  10412. this.favList = next
  10413. })
  10414. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  10415. this.historyList = next
  10416. })
  10417. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  10418. this.currentSongList = next
  10419. })
  10420. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  10421. this.mediaKuList = next
  10422. })
  10423. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  10424. this.filteredList = next
  10425. })
  10426. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  10427. this.artistList = next
  10428. })
  10429. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  10430. this.albumList = next
  10431. })
  10432. this.listRefreshKey++
  10433. }
  10434. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  10435. if (!mainListUpdated && !playlistUpdated) {
  10436. return;
  10437. }
  10438. this.listRefreshKey++;
  10439. if (mainListUpdated) {
  10440. this.dataSource.notifyDataReload();
  10441. }
  10442. if (playlistUpdated) {
  10443. this.sonDataSource.notifyDataReload();
  10444. }
  10445. }
  10446. @Builder
  10447. detailSheet(item:VideoItem) {
  10448. Scroll() {
  10449. Column() {
  10450. this.songDetail(item)
  10451. }
  10452. }
  10453. .width('100%')
  10454. .height('100%')
  10455. }
  10456. @Builder
  10457. songDetail(currentItem:VideoItem) {
  10458. Column() {
  10459. if (currentItem) {
  10460. Row() {
  10461. Stack() {
  10462. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  10463. currentItem.pixelMapPath)
  10464. .fillColor(this.themeColor)
  10465. .height(80)
  10466. .width(80)
  10467. .borderRadius(10)
  10468. .opacity(this.opacityItem)// 绑定透明度
  10469. .margin({ left: 22 })
  10470. }
  10471. Column() {
  10472. Column() {
  10473. Text(currentItem.name)
  10474. .fontSize(16)
  10475. .maxLines(1)
  10476. .animation({
  10477. duration: 555,
  10478. curve: 'Linear',
  10479. })
  10480. .fontColor($r('app.color.text_color'))
  10481. .margin({ left: 15 })
  10482. }
  10483. .height('100%')
  10484. .width('100%')
  10485. .justifyContent(FlexAlign.Center)
  10486. .alignItems(HorizontalAlign.Start)
  10487. }
  10488. .height('100%')
  10489. }
  10490. .width('100%')
  10491. .height(90)
  10492. .justifyContent(FlexAlign.SpaceBetween)
  10493. Row() {
  10494. Text('艺术家:')
  10495. .fontSize(14)
  10496. .fontColor($r('app.color.text_color'))
  10497. .margin({ left: 22 })
  10498. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  10499. .fontSize(14)
  10500. .fontColor($r('app.color.text_color'))
  10501. .margin({ left: 10 })
  10502. .layoutWeight(1)
  10503. }
  10504. .width('100%')
  10505. .margin({ top: 10, bottom: 10 })
  10506. .justifyContent(FlexAlign.Start)
  10507. Row() {
  10508. Text('专辑名:')
  10509. .fontSize(14)
  10510. .fontColor($r('app.color.text_color'))
  10511. .margin({ left: 22 })
  10512. Text(currentItem?.album ?currentItem.album : '未知专辑')
  10513. .fontSize(14)
  10514. .margin({ left: 10 })
  10515. .fontColor($r('app.color.text_color'))
  10516. .layoutWeight(1)
  10517. }
  10518. .width('100%')
  10519. .margin({ top: 10, bottom: 10 })
  10520. .justifyContent(FlexAlign.Start)
  10521. Row() {
  10522. Text('时长:')
  10523. .fontSize(14)
  10524. .fontColor($r('app.color.text_color'))
  10525. .margin({ left: 22 })
  10526. Text(StrUtil.isEmpty(currentItem.duration)?
  10527. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  10528. .fontSize(14)
  10529. .margin({ left: 10 })
  10530. .fontColor($r('app.color.text_color'))
  10531. .layoutWeight(1)
  10532. }
  10533. .width('100%')
  10534. .margin({ top: 10, bottom: 10 })
  10535. .justifyContent(FlexAlign.Start)
  10536. Row() {
  10537. Text('采样率:')
  10538. .fontSize(14)
  10539. .fontColor($r('app.color.text_color'))
  10540. .margin({ left: 22 })
  10541. Text(Utility.convertToKHz(currentItem.sampleRate))
  10542. .fontSize(14)
  10543. .margin({ left: 10 })
  10544. .fontColor($r('app.color.text_color'))
  10545. .layoutWeight(1)
  10546. }
  10547. .width('100%')
  10548. .margin({ top: 10, bottom: 10 })
  10549. .justifyContent(FlexAlign.Start)
  10550. Row() {
  10551. Text('比特率:')
  10552. .fontSize(14)
  10553. .fontColor($r('app.color.text_color'))
  10554. .margin({ left: 22 })
  10555. Text(currentItem.bit_rate)
  10556. .fontSize(14)
  10557. .margin({ left: 10 })
  10558. .fontColor($r('app.color.text_color'))
  10559. .layoutWeight(1)
  10560. }
  10561. .width('100%')
  10562. .margin({ top: 10, bottom: 10 })
  10563. .justifyContent(FlexAlign.Start)
  10564. Row() {
  10565. Text('位深:')
  10566. .fontSize(14)
  10567. .fontColor($r('app.color.text_color'))
  10568. .margin({ left: 22 })
  10569. Text(`${currentItem.bits_per_raw_sample} bits`)
  10570. .fontSize(14)
  10571. .margin({ left: 10 })
  10572. .fontColor($r('app.color.text_color'))
  10573. .layoutWeight(1)
  10574. }
  10575. .width('100%')
  10576. .margin({ top: 10, bottom: 10 })
  10577. .justifyContent(FlexAlign.Start)
  10578. Row() {
  10579. Text('声道:')
  10580. .fontSize(14)
  10581. .fontColor($r('app.color.text_color'))
  10582. .margin({ left: 22 })
  10583. Text(`${currentItem.channels}`)
  10584. .fontSize(14)
  10585. .margin({ left: 10 })
  10586. .fontColor($r('app.color.text_color'))
  10587. .layoutWeight(1)
  10588. }
  10589. .width('100%')
  10590. .margin({ top: 10, bottom: 10 })
  10591. .justifyContent(FlexAlign.Start)
  10592. Row() {
  10593. Text('声道布局:')
  10594. .fontSize(14)
  10595. .fontColor($r('app.color.text_color'))
  10596. .margin({ left: 22 })
  10597. Text(`${currentItem.channel_layout}`)
  10598. .fontSize(14)
  10599. .margin({ left: 10 })
  10600. .fontColor($r('app.color.text_color'))
  10601. .layoutWeight(1)
  10602. }
  10603. .width('100%')
  10604. .margin({ top: 10, bottom: 10 })
  10605. .justifyContent(FlexAlign.Start)
  10606. Row() {
  10607. Text('起始播放点:')
  10608. .fontSize(14)
  10609. .fontColor($r('app.color.text_color'))
  10610. .margin({ left: 22 })
  10611. Text(`${currentItem.start_time}`)
  10612. .fontSize(14)
  10613. .margin({ left: 10 })
  10614. .fontColor($r('app.color.text_color'))
  10615. .layoutWeight(1)
  10616. }
  10617. .width('100%')
  10618. .margin({ top: 10, bottom: 10 })
  10619. .justifyContent(FlexAlign.Start)
  10620. Row() {
  10621. Text('风格:')
  10622. .fontSize(14)
  10623. .fontColor($r('app.color.text_color'))
  10624. .margin({ left: 22 })
  10625. Text(currentItem.genre)
  10626. .fontSize(14)
  10627. .margin({ left: 10 })
  10628. .fontColor($r('app.color.text_color'))
  10629. .layoutWeight(1)
  10630. }
  10631. .width('100%')
  10632. .margin({ top: 10, bottom: 10 })
  10633. .justifyContent(FlexAlign.Start)
  10634. Row() {
  10635. Text('发行时间:')
  10636. .fontSize(14)
  10637. .fontColor($r('app.color.text_color'))
  10638. .margin({ left: 22 })
  10639. Text(currentItem.year)
  10640. .fontSize(14)
  10641. .margin({ left: 10 })
  10642. .fontColor($r('app.color.text_color'))
  10643. .layoutWeight(1)
  10644. }
  10645. .width('100%')
  10646. .margin({ top: 10, bottom: 10 })
  10647. .justifyContent(FlexAlign.Start)
  10648. Row() {
  10649. Text('质量评分:')
  10650. .fontSize(14)
  10651. .fontColor($r('app.color.text_color'))
  10652. .margin({ left: 22 })
  10653. Text(currentItem.probe_score+"")
  10654. .fontSize(14)
  10655. .margin({ left: 10 })
  10656. .fontColor($r('app.color.text_color'))
  10657. .layoutWeight(1)
  10658. }
  10659. .width('100%')
  10660. .margin({ top: 10, bottom: 10 })
  10661. .justifyContent(FlexAlign.Start)
  10662. Row() {
  10663. Text('音轨号:')
  10664. .fontSize(14)
  10665. .fontColor($r('app.color.text_color'))
  10666. .margin({ left: 22 })
  10667. Text(currentItem.track)
  10668. .fontSize(14)
  10669. .margin({ left: 10 })
  10670. .fontColor($r('app.color.text_color'))
  10671. .layoutWeight(1)
  10672. }
  10673. .width('100%')
  10674. .margin({ top: 10, bottom: 10 })
  10675. .justifyContent(FlexAlign.Start)
  10676. Row() {
  10677. Text('碟号:')
  10678. .fontSize(14)
  10679. .fontColor($r('app.color.text_color'))
  10680. .margin({ left: 22 })
  10681. Text(currentItem.disc)
  10682. .fontSize(14)
  10683. .margin({ left: 10 })
  10684. .fontColor($r('app.color.text_color'))
  10685. .layoutWeight(1)
  10686. }
  10687. .width('100%')
  10688. .margin({ top: 10, bottom: 10 })
  10689. .justifyContent(FlexAlign.Start)
  10690. Row() {
  10691. Text('专辑艺术家:')
  10692. .fontSize(14)
  10693. .fontColor($r('app.color.text_color'))
  10694. .margin({ left: 22 })
  10695. Text(currentItem.ALBUMARTIST)
  10696. .fontSize(14)
  10697. .margin({ left: 10 })
  10698. .fontColor($r('app.color.text_color'))
  10699. .layoutWeight(1)
  10700. }
  10701. .width('100%')
  10702. .margin({ top: 10, bottom: 10 })
  10703. .justifyContent(FlexAlign.Start)
  10704. Row() {
  10705. Text('作曲家:')
  10706. .fontSize(14)
  10707. .fontColor($r('app.color.text_color'))
  10708. .margin({ left: 22 })
  10709. Text(currentItem.COMPOSER)
  10710. .fontSize(14)
  10711. .margin({ left: 10 })
  10712. .fontColor($r('app.color.text_color'))
  10713. .layoutWeight(1)
  10714. }
  10715. .width('100%')
  10716. .margin({ top: 10, bottom: 10 })
  10717. .justifyContent(FlexAlign.Start)
  10718. Row() {
  10719. Text('作词家:')
  10720. .fontSize(14)
  10721. .fontColor($r('app.color.text_color'))
  10722. .margin({ left: 22 })
  10723. Text(currentItem.LYRICIST)
  10724. .fontSize(14)
  10725. .margin({ left: 10 })
  10726. .fontColor($r('app.color.text_color'))
  10727. .layoutWeight(1)
  10728. }
  10729. .width('100%')
  10730. .margin({ top: 10, bottom: 10 })
  10731. .justifyContent(FlexAlign.Start)
  10732. Row() {
  10733. Text('注释:')
  10734. .fontSize(14)
  10735. .fontColor($r('app.color.text_color'))
  10736. .margin({ left: 22 })
  10737. Text(currentItem.COMMENT)
  10738. .fontSize(14)
  10739. .margin({ left: 10 })
  10740. .fontColor($r('app.color.text_color'))
  10741. .layoutWeight(1)
  10742. }
  10743. .width('100%')
  10744. .margin({ top: 10, bottom: 10 })
  10745. .justifyContent(FlexAlign.Start)
  10746. Row() {
  10747. Text('格式:')
  10748. .fontSize(14)
  10749. .fontColor($r('app.color.text_color'))
  10750. .margin({ left: 22 })
  10751. Text(Utility.formatMimeType(currentItem.mimeType))
  10752. .fontSize(14)
  10753. .margin({ left: 10 })
  10754. .fontColor($r('app.color.text_color'))
  10755. .layoutWeight(1)
  10756. }
  10757. .width('100%')
  10758. .margin({ top: 10, bottom: 10 })
  10759. .justifyContent(FlexAlign.Start)
  10760. Row() {
  10761. Text('播放次数:')
  10762. .fontSize(14)
  10763. .fontColor($r('app.color.text_color'))
  10764. .margin({ left: 22 })
  10765. Text(currentItem.playCount?.toString())
  10766. .fontSize(14)
  10767. .margin({ left: 10 })
  10768. .fontColor($r('app.color.text_color'))
  10769. .layoutWeight(1)
  10770. }
  10771. .width('100%')
  10772. .margin({ top: 10, bottom: 10 })
  10773. .justifyContent(FlexAlign.Start)
  10774. Row() {
  10775. Text('流数量:')
  10776. .fontSize(14)
  10777. .fontColor($r('app.color.text_color'))
  10778. .margin({ left: 22 })
  10779. Text(currentItem.nb_streams?.toString())
  10780. .fontSize(14)
  10781. .margin({ left: 10 })
  10782. .fontColor($r('app.color.text_color'))
  10783. .layoutWeight(1)
  10784. }
  10785. .width('100%')
  10786. .margin({ top: 10, bottom: 10 })
  10787. .justifyContent(FlexAlign.Start)
  10788. Row() {
  10789. Text('文件大小:')
  10790. .fontSize(14)
  10791. .fontColor($r('app.color.text_color'))
  10792. .margin({ left: 22 })
  10793. Text(currentItem.size)
  10794. .fontSize(14)
  10795. .margin({ left: 10 })
  10796. .fontColor($r('app.color.text_color'))
  10797. .layoutWeight(1)
  10798. }
  10799. .width('100%')
  10800. .margin({ top: 10, bottom: 10 })
  10801. .justifyContent(FlexAlign.Start)
  10802. Row() {
  10803. Text('文件名:')
  10804. .fontSize(14)
  10805. .fontColor($r('app.color.text_color'))
  10806. .margin({ left: 22 })
  10807. Text(currentItem.fileName)
  10808. .fontSize(14)
  10809. .margin({ left: 10 })
  10810. .fontColor($r('app.color.text_color'))
  10811. .layoutWeight(1)
  10812. }
  10813. .width('100%')
  10814. .margin({ top: 10, bottom: 10 })
  10815. .justifyContent(FlexAlign.Start)
  10816. Row() {
  10817. Text('修改时间:')
  10818. .fontSize(14)
  10819. .fontColor($r('app.color.text_color'))
  10820. .margin({ left: 22 })
  10821. Text(currentItem.cTime)
  10822. .fontSize(14)
  10823. .margin({ left: 10 })
  10824. .fontColor($r('app.color.text_color'))
  10825. .layoutWeight(1)
  10826. }
  10827. .width('100%')
  10828. .margin({ top: 10, bottom: 10 })
  10829. .justifyContent(FlexAlign.Start)
  10830. Row() {
  10831. Text('存放目录:')
  10832. .fontSize(14)
  10833. .fontColor($r('app.color.text_color'))
  10834. .margin({ left: 22 })
  10835. Text(currentItem.filePath)
  10836. .fontSize(12)
  10837. .margin({ left: 10 })
  10838. .fontColor($r('app.color.text_color'))
  10839. .layoutWeight(1)
  10840. }
  10841. .margin({ top: 10, bottom: 10 })
  10842. .width('100%')
  10843. .justifyContent(FlexAlign.Start)
  10844. Row() {
  10845. Text('内嵌歌词:')
  10846. .fontSize(14)
  10847. .fontColor($r('app.color.text_color'))
  10848. .margin({ left: 22 })
  10849. Text(currentItem.lyricContent)
  10850. .fontSize(12)
  10851. .copyOption(CopyOptions.InApp)
  10852. .margin({ left: 10 })
  10853. .fontColor($r('app.color.text_color'))
  10854. .layoutWeight(1)
  10855. }
  10856. .margin({ top: 10, bottom: 10 })
  10857. .width('100%')
  10858. .justifyContent(FlexAlign.Start)
  10859. }
  10860. }
  10861. .margin({ bottom: 20 })
  10862. }
  10863. //定时关闭布局
  10864. @Builder
  10865. TimeCloseSheet() {
  10866. Scroll() {
  10867. Column() {
  10868. this.TimeClose()
  10869. }
  10870. }
  10871. .width('100%')
  10872. .height('100%')
  10873. }
  10874. //倒计时关闭音乐,退出App功能实现。
  10875. @State selectedMinutes: number = 0 // 0表示未开启
  10876. @State remainingSeconds: number = 0
  10877. // 预设时间选项
  10878. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  10879. private formatTime(seconds: number): string {
  10880. const mins = Math.floor(seconds / 60)
  10881. const secs = seconds % 60
  10882. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  10883. }
  10884. // 开始倒计时
  10885. private handleTimeSelect(minutes: number) {
  10886. if (minutes === this.selectedMinutes) {
  10887. this.stopCountdown();
  10888. this.selectedMinutes = 0;
  10889. return;
  10890. }
  10891. this.selectedMinutes = minutes;
  10892. this.remainingSeconds = minutes * 60;
  10893. this.startCountdown(); // 新增调用
  10894. }
  10895. @Builder
  10896. TimeClose() {
  10897. Column() {
  10898. // 倒计时显示区域
  10899. Text(this.selectedMinutes > 0 ?
  10900. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  10901. "定时关闭未开启")
  10902. .fontSize(17)
  10903. .fontColor($r('app.color.text_color'))
  10904. .margin({ top: 2, bottom: 8 });
  10905. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10906. ForEach(this.presetTimes, (minutes: number, index: number) => {
  10907. // 单行时间选项容器
  10908. Row() {
  10909. // 文字描述区域
  10910. Text(this.getDisplayText(minutes))
  10911. .fontSize(15)
  10912. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  10913. $r('app.color.text_color'))// 选中态颜色变化
  10914. .textAlign(TextAlign.Start)
  10915. .layoutWeight(1); // 占据剩余空间
  10916. // 复选框样式的选择器
  10917. Row() {
  10918. if (minutes === this.selectedMinutes) {
  10919. // 选中状态 - 带勾号的圆形复选框
  10920. Row() {
  10921. // 使用系统内置的勾号图标
  10922. Image($r('sys.media.ohos_ic_public_ok'))
  10923. .width(14)
  10924. .height(14)
  10925. .fillColor(Color.White)
  10926. }
  10927. .width(24)
  10928. .height(24)
  10929. .borderRadius(12)
  10930. .backgroundColor(this.themeColor)
  10931. .justifyContent(FlexAlign.Center)
  10932. .alignItems(VerticalAlign.Center)
  10933. } else {
  10934. // 未选中状态的圆形边框
  10935. Row()
  10936. .width(24)
  10937. .height(24)
  10938. .borderRadius(12)
  10939. .border({
  10940. width: 2,
  10941. color: $r('app.color.text_color'),
  10942. style: BorderStyle.Solid
  10943. })
  10944. .backgroundColor(Color.Transparent)
  10945. }
  10946. }
  10947. .width(24)
  10948. .height(24)
  10949. .margin({ left: 20 })
  10950. .justifyContent(FlexAlign.Center)
  10951. .alignItems(VerticalAlign.Center)
  10952. }
  10953. .width('100%')
  10954. .padding({
  10955. top: 18,
  10956. bottom: 18,
  10957. left: 18,
  10958. right: 18
  10959. })
  10960. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  10961. $r('app.color.bottom_control_background')) // 选中背景高亮
  10962. .borderRadius(12)
  10963. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10964. .margin({ bottom: 18 })
  10965. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  10966. });
  10967. }
  10968. .width('100%')
  10969. .padding(16)
  10970. }
  10971. }
  10972. // 获取显示文本
  10973. private getDisplayText(minutes: number): string {
  10974. if (minutes === -1) {
  10975. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  10976. }
  10977. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  10978. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  10979. }
  10980. // 处理选择事件
  10981. private handleSelect(minutes: number): void {
  10982. if (minutes === -1) { // 自定义
  10983. // 弹出自定义时间对话框
  10984. DialogHelper.showTextInputDialog({
  10985. title: '自定义时间',
  10986. maskColor: Color.Transparent,
  10987. inputType: InputType.Number,
  10988. text: '',
  10989. onChange: (text) => {
  10990. console.error("onChange: " + text);
  10991. },
  10992. onAction: (action, dialogId, content) => {
  10993. if (action == DialogAction.TWO) {
  10994. const customMinutes = Number(content);
  10995. if (customMinutes > 0) {
  10996. this.handleTimeSelect(customMinutes); // 设置自定义时间
  10997. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  10998. }
  10999. }
  11000. }
  11001. });
  11002. } else {
  11003. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  11004. }
  11005. }
  11006. // 添加定时器引用
  11007. private timerId: number = -1;
  11008. // 启动/重置倒计时
  11009. private startCountdown() {
  11010. // 清除旧定时器
  11011. if (this.timerId !== -1) {
  11012. clearInterval(this.timerId);
  11013. }
  11014. // 创建新定时器
  11015. if (this.selectedMinutes > 0) {
  11016. this.timerId = setInterval(() => {
  11017. if (this.remainingSeconds === 15) {
  11018. this.showConfirmationDialog();
  11019. }
  11020. if (this.remainingSeconds > 0) {
  11021. this.remainingSeconds -= 1;
  11022. } else {
  11023. this.stopCountdown();
  11024. this.handleTimeout();
  11025. }
  11026. }, 1000);
  11027. }
  11028. }
  11029. // 15倒计时后再次提示显示确认是否关闭App对话框
  11030. private showConfirmationDialog() {
  11031. DialogHelper.showAlertDialog({
  11032. backgroundColor: $r('app.color.btn_green'),
  11033. title: '确认关闭',
  11034. maskColor: Color.Transparent,
  11035. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  11036. borderStyle: BorderStyle.Dashed,
  11037. primaryButton: '暂不关闭',
  11038. secondaryButton: '确定',
  11039. onAction: (action) => {
  11040. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  11041. this.stopCountdown();
  11042. this.selectedMinutes = 0
  11043. } else if (action == DialogAction.TWO) {
  11044. }
  11045. }
  11046. })
  11047. }
  11048. // 停止倒计时
  11049. private stopCountdown() {
  11050. if (this.timerId !== -1) {
  11051. clearInterval(this.timerId);
  11052. this.timerId = -1;
  11053. }
  11054. }
  11055. // 超时处理
  11056. private handleTimeout() {
  11057. // 执行播放器关闭逻辑
  11058. this.selectedMinutes = 0;
  11059. ToastUtil.showToast(" 定时关闭已完成");
  11060. this.stop(); // 假设存在的播放器实例
  11061. //退出APP
  11062. const mContext = getContext(this) as common.UIAbilityContext
  11063. mContext.terminateSelf();
  11064. AvSessionController.getInstance(true).unregisterSessionListener()
  11065. }
  11066. //倒计时关闭音乐,退出App功能实现结束。
  11067. //播放列表的拖动List 重新排序
  11068. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  11069. //左滑操作 移动文件 重命名 删除等操作
  11070. @Builder
  11071. sonButton(item: VideoItem, index: number, filePath: string) {
  11072. Row() {
  11073. //加入下一首播放
  11074. Button() {
  11075. Image($r('app.media.next_to_play'))
  11076. .fillColor(Color.White)
  11077. .width(20)
  11078. }
  11079. .width(40)
  11080. .height(40)
  11081. .type(ButtonType.Circle)
  11082. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11083. .backgroundColor(this.themeColor)
  11084. .margin(5)
  11085. .onClick(() => {
  11086. this.addToNextPlay(item);
  11087. })
  11088. Button() {
  11089. Image($r('app.media.close'))
  11090. .fillColor(Color.White)
  11091. .width(20)
  11092. }
  11093. .width(40)
  11094. .height(40)
  11095. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11096. .type(ButtonType.Circle)
  11097. .backgroundColor(this.themeColor)
  11098. .margin(5)
  11099. .onClick(() => {
  11100. this.songList.splice(Number(index), 1)
  11101. this.sonDataSource.pushArrayData(this.songList)
  11102. })
  11103. Button() {
  11104. Image($r('app.media.share2'))
  11105. .fillColor(Color.White)
  11106. .width(20)
  11107. }
  11108. .width(40)
  11109. .height(40)
  11110. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11111. .type(ButtonType.Circle)
  11112. .backgroundColor(this.themeColor)
  11113. .margin(5)
  11114. .onClick(() => {
  11115. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11116. })
  11117. }
  11118. }
  11119. itemMoveSon(index: number, newIndex: number): void {
  11120. if (newIndex < 0 || newIndex >= this.songList.length) {
  11121. return;
  11122. }
  11123. let tmp = this.songList.splice(index, 1);
  11124. this.songList.splice(newIndex, 0, tmp[0]);
  11125. this.sonDataSource.pushArrayData(this.songList)
  11126. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  11127. if(this.modeType==4&&this.playlistTable){
  11128. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  11129. }
  11130. }
  11131. @Builder
  11132. PlayList() {
  11133. List({ scroller: this.playListScroller }) {
  11134. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  11135. ListItem() {
  11136. this.MusicItemSon(item, index)
  11137. }
  11138. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  11139. .animation({
  11140. duration: 666,
  11141. curve: 'ease-in-out' // 可选动画曲线
  11142. })
  11143. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  11144. // TransitionEffect.scale({ x: 0, y: 0 })))
  11145. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  11146. //拖动List关键代码开始
  11147. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  11148. .zIndex(this.dragItem === index ? 1 : 0)
  11149. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  11150. .gesture(
  11151. GestureGroup(GestureMode.Sequence,
  11152. LongPressGesture({ repeat: true })
  11153. .onAction((event?: GestureEvent) => {
  11154. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11155. this.scaleItem = index
  11156. })
  11157. })
  11158. .onActionEnd(() => {
  11159. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11160. this.scaleItem = -1
  11161. })
  11162. }),
  11163. PanGesture({ fingers: 1, direction: null, distance: 0 })
  11164. .onActionStart(() => {
  11165. this.dragItem = index // 记录当前拖动项索引
  11166. this.dragRefOffset = 0 // 重置偏移基准
  11167. })
  11168. .onActionUpdate((event: GestureEvent) => {
  11169. this.offsetY = event.offsetY - this.dragRefOffset;
  11170. this.neighborItem = -1;
  11171. let indexA = this.songList.indexOf(item);
  11172. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  11173. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  11174. let value: number = 0;
  11175. if (this.offsetY < 0) {
  11176. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  11177. this.neighborItem = indexA - 1;
  11178. this.neighborScale = 1 - value / 20;
  11179. } else if (this.offsetY > 0) {
  11180. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  11181. this.neighborItem = indexA + 1;
  11182. this.neighborScale = 1 - value / 20;
  11183. }
  11184. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  11185. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11186. this.offsetY -= this.ITEM_INTV;
  11187. this.dragRefOffset += this.ITEM_INTV;
  11188. this.itemMoveSon(indexA, indexA + 1);
  11189. });
  11190. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  11191. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11192. this.offsetY += this.ITEM_INTV;
  11193. this.dragRefOffset -= this.ITEM_INTV;
  11194. this.itemMoveSon(indexA, indexA - 1);
  11195. });
  11196. }
  11197. })
  11198. .onActionEnd((event: GestureEvent) => {
  11199. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11200. this.dragItem = -1
  11201. this.neighborItem = -1
  11202. })
  11203. animateTo({
  11204. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11205. }, () => {
  11206. this.scaleItem = -1
  11207. })
  11208. })
  11209. )
  11210. .onCancel(() => {
  11211. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11212. this.dragItem = -1
  11213. this.neighborItem = -1
  11214. })
  11215. animateTo({
  11216. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11217. }, () => {
  11218. this.scaleItem = -1
  11219. })
  11220. })
  11221. ) //拖动List关键代码结束
  11222. .onClick(() => {
  11223. this.doPlay(item, index, true)
  11224. })
  11225. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  11226. }
  11227. .width('100%')
  11228. .height('100%')
  11229. .onReachEnd(() => {
  11230. if(this.modeType === 4 && !this.isFindPagedLocalQueueActive())
  11231. return;
  11232. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  11233. const isStreamingSong = this.currentSong && (
  11234. isNavidromeType(this.currentSong.type) ||
  11235. isJellyfinType(this.currentSong.type) ||
  11236. isEmbyType(this.currentSong.type) ||
  11237. isAudioStationType(this.currentSong.type) ||
  11238. isPlexType(this.currentSong.type)
  11239. );
  11240. if (isStreamingSong && hasMoreData()) {
  11241. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  11242. void this.loadMoreNavidromeSongs();
  11243. } else {
  11244. void this.tryLoadNextPageForPlayback();
  11245. }
  11246. })
  11247. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11248. // .animation({ duration: 500, curve: Curve.Ease }))
  11249. .cachedCount(10)
  11250. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  11251. .gesture(PinchGesture({ fingers: 2 })
  11252. .onActionEnd((event: GestureEvent) => {
  11253. this.setSonListTwoFingers()
  11254. })
  11255. .onActionUpdate(e => {
  11256. this.scaleValue = this.pinchValue * e.scale
  11257. })
  11258. .onActionStart(e => {
  11259. }))
  11260. .padding({
  11261. bottom: 0
  11262. })
  11263. }
  11264. setSonListTwoFingers() {
  11265. this.pinchValue = this.scaleValue;
  11266. Logger.info('this.pinchValue = ' + this.pinchValue);
  11267. if (this.pinchValue >= 1) {
  11268. this.sonTwoFingerType++
  11269. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  11270. if (this.sonTwoFingerType > 3) {
  11271. this.sonTwoFingerType = 1
  11272. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  11273. }
  11274. } else {
  11275. this.sonTwoFingerType--
  11276. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  11277. if (this.sonTwoFingerType < 1) {
  11278. this.sonTwoFingerType = 1
  11279. }
  11280. }
  11281. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  11282. this.pinchValue = 1;
  11283. this.scaleValue = 1;
  11284. }
  11285. @State sonTwoFingerType:number = 3
  11286. @Builder
  11287. private MusicItemSon(item: VideoItem, index?: number) {
  11288. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11289. Row() {
  11290. Stack() {
  11291. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  11292. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11293. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11294. .alt($r('app.media.alt'))
  11295. .fillColor(this.themeColor)
  11296. .borderRadius(this.isCoverRectangle?11:'100%')
  11297. .clip(true)
  11298. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  11299. .draggable(false)// 禁止长按手势拖动
  11300. .autoResize(true) // 重采样,可减少内存占用
  11301. .margin({ left: 20 })
  11302. }
  11303. .width('15%')
  11304. Column() {
  11305. Column() {
  11306. Text(this.isShowFileName?item.fileName :item.name)
  11307. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  11308. .fontColor(this.curIndex === index ? this.themeColor :
  11309. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  11310. .maxLines(1)
  11311. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  11312. Row() {
  11313. Column(){
  11314. Text(item.md5Str?.includes('Lossless')?
  11315. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  11316. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  11317. .padding({ top: 3,right:6,left:6,bottom:3 })
  11318. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  11319. $r('app.color.text_color'))
  11320. .fontWeight(500)
  11321. .borderRadius(12)
  11322. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  11323. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  11324. .backgroundColor('#FFC107')
  11325. }
  11326. .padding({ top: 8 })
  11327. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  11328. item.artist + ' ' + item?.duration)
  11329. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11330. .padding({ top: 8 })
  11331. .maxLines(1)
  11332. .fontColor(this.curIndex === index ? this.themeColor :
  11333. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11334. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  11335. Blank()
  11336. Text(item.size)
  11337. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11338. .padding({ top: 8 })
  11339. .maxLines(1)
  11340. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  11341. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  11342. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11343. .margin({ left: 10 })
  11344. }
  11345. }
  11346. .height('100%')
  11347. .width('100%')
  11348. .justifyContent(FlexAlign.Center)
  11349. .alignItems(HorizontalAlign.Start)
  11350. }
  11351. .height('100%')
  11352. .width('65%')
  11353. Column() {
  11354. PlayingIndicator({
  11355. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  11356. indicatorSize: 18
  11357. })
  11358. }
  11359. .width('20%')
  11360. }
  11361. }
  11362. .backgroundColor(Color.Transparent)
  11363. .width('100%')
  11364. .reuseId('son_item')
  11365. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  11366. .shadow(this.scaleItem === index ? {
  11367. radius: 70,
  11368. color: '#15000000',
  11369. offsetX: 0,
  11370. offsetY: 0
  11371. } :
  11372. {
  11373. radius: 0,
  11374. color: '#15000000',
  11375. offsetX: 0,
  11376. offsetY: 0
  11377. })
  11378. .animation({ curve: Curve.Sharp, duration: 300 })
  11379. }
  11380. @Builder
  11381. private MusicPlayDismissProxyDot() {
  11382. Stack({ alignContent: Alignment.Center }) {
  11383. Image(StrUtil.isNotEmpty(this.cover) ? this.cover as string : $r('app.media.alt'))
  11384. .width('100%')
  11385. .height('100%')
  11386. .objectFit(ImageFit.Cover)
  11387. .alt($r('app.media.alt'))
  11388. }
  11389. .width(this.playDismissProxySize)
  11390. .height(this.playDismissProxySize)
  11391. .borderRadius(this.playDismissProxySize)
  11392. .clip(true)
  11393. .opacity(this.playDismissProxyOpacity)
  11394. .translate({ x: this.playDismissTranslateX, y: this.translateY })
  11395. .shadow({
  11396. radius: 18,
  11397. type: ShadowType.BLUR,
  11398. color: 'on_primary'
  11399. })
  11400. }
  11401. @Builder
  11402. MusicPlayBuilder() {
  11403. Column() {
  11404. this.IjkMusicPlayerView()
  11405. }
  11406. .transition(TransitionEffect.asymmetric(
  11407. TransitionEffect.opacity(1),
  11408. TransitionEffect.OPACITY
  11409. ))
  11410. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  11411. new hdsEffect.HdsEffectBuilder()
  11412. .shaderEffect({
  11413. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  11414. animation: {
  11415. duration: 10000,
  11416. iterations: -1,
  11417. autoPlay: true,
  11418. onFinish: ()=> {
  11419. console.info('Succeeded in finishing');
  11420. }
  11421. },
  11422. controller: this.bgController,
  11423. })
  11424. .buildEffect():null)
  11425. .height('100%')
  11426. .width('100%')
  11427. .onDisAppear(() => {
  11428. this.translateY = 0;
  11429. this.playDragUiOpacity = 1
  11430. })
  11431. .translate({ y: this.translateY })
  11432. .gesture(
  11433. PanGesture(this.panOption)
  11434. .onActionUpdate((event?: GestureEvent) => {
  11435. if (event) {
  11436. // 判断滑动方向
  11437. const offsetY = event.offsetY ?? 0;
  11438. const isSwipeUp = offsetY < 0;
  11439. if (isSwipeUp) {
  11440. // 向上滑动:不应用位移动画,保持 translateY = 0
  11441. this.translateY = 0;
  11442. this.scaleValueImage = 1
  11443. this.scaleValueText = 1
  11444. this.playDragUiOpacity = 1
  11445. } else {
  11446. if(this.isGeKongPlayNext){
  11447. return
  11448. }
  11449. // 向下滑动:应用位移动画
  11450. this.translateY = offsetY;
  11451. // 向下滑动时的缩放效果
  11452. this.getUIContext().animateTo({
  11453. duration: 500,
  11454. curve: Curve.Sharp
  11455. }, () => {
  11456. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - this.translateY / 880));
  11457. console.info('onecold scaleValueImage:', this.scaleValueImage)
  11458. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  11459. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  11460. })
  11461. }
  11462. }
  11463. })
  11464. .onActionEnd((event?: GestureEvent) => {
  11465. // 判断滑动方向
  11466. const offsetY = event?.offsetY ?? 0;
  11467. const isSwipeUp = offsetY < 0;
  11468. const minDistance = 300; // 最小滑动距离
  11469. const minVelocity = 500; // 最小滑动速度
  11470. const velocity = event?.velocityY ?? 0;
  11471. if (isSwipeUp) {
  11472. // 向上滑动:切换下一首
  11473. const shouldSwitch = this.isPlayPageSwipeNext &&
  11474. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  11475. if (shouldSwitch) {
  11476. // 直接切换下一首,无需动画(因为界面没有移动)
  11477. this.playNext().catch(() => {
  11478. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  11479. });
  11480. }
  11481. } else {
  11482. //这里加个变量,是否开启隔空手势播放下一首
  11483. if(this.isGeKongPlayNext){
  11484. this.playNext()
  11485. return
  11486. }
  11487. // 向下滑动:关闭播放页
  11488. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  11489. if (shouldClose) {
  11490. // 添加关闭动画
  11491. this.getUIContext().animateTo({
  11492. duration: 600,
  11493. curve: Curve.Friction
  11494. }, () => {
  11495. this.isShowPlay = false;
  11496. this.scaleValueImage = 1
  11497. this.scaleValueText = 1
  11498. this.playDragUiOpacity = 1
  11499. this.translateY = 0;
  11500. })
  11501. } else {
  11502. // 回弹动画
  11503. this.getUIContext().animateTo({
  11504. duration: 600,
  11505. curve: Curve.Friction
  11506. }, () => {
  11507. this.scaleValueImage = 1
  11508. this.scaleValueText = 1
  11509. this.playDragUiOpacity = 1
  11510. this.translateY = 0;
  11511. })
  11512. }
  11513. }
  11514. })
  11515. )
  11516. }
  11517. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  11518. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  11519. HeightBreakpoint.HEIGHT_LG;
  11520. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  11521. @State topBarHeight: number = 50
  11522. @State barOpacity: number = 1
  11523. @State barBottomOpacity: number = 1
  11524. private hideDone: boolean = false;
  11525. @State currentYOffset: number = 0;
  11526. @State bottomBarHeight: number = 68;
  11527. private isHiding: boolean = false;
  11528. //是否是Pura X外屏,或者小屏幕
  11529. isPuraWP() {
  11530. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  11531. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  11532. }
  11533. //是否是Pura X外屏,或者小屏幕,手机横屏
  11534. /**
  11535. * 是否是Pura X外屏,或者小屏幕,手机横屏
  11536. * @returns
  11537. */
  11538. isCoverOpacity() {
  11539. if (this.isPuraWP()) {
  11540. return true
  11541. }
  11542. if (this.isPhoneLan()) {
  11543. return true
  11544. }
  11545. if (deviceInfo.marketName.includes('Pura X')
  11546. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  11547. return true
  11548. }
  11549. return false
  11550. }
  11551. //是不是手机横屏
  11552. isPhoneLan() {
  11553. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  11554. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  11555. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  11556. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  11557. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  11558. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  11559. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  11560. if (this.isHiCarKuanBianPing()) {
  11561. return true
  11562. }
  11563. if (this.isHiCar()) {
  11564. return false
  11565. }
  11566. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11567. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  11568. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  11569. return true
  11570. }
  11571. return false
  11572. }
  11573. //是不是1920x720的hicar的屏幕分辨率
  11574. isHiCarKuanBianPing(){
  11575. // if(!this.isHiCar()){
  11576. // return false
  11577. // }
  11578. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11579. { ratio: 1920 / 720, name: "1920x720" },
  11580. ];
  11581. const currentRatio: number = this.windowWidth / this.windowHeight;
  11582. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11583. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  11584. for (const hiCarRatio of hiCarAspectRatios) {
  11585. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  11586. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11587. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11588. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11589. //宽扁平的尺寸设置列表展示
  11590. this.twoFingerType ==3
  11591. this.isGridMusic = false
  11592. return true;
  11593. }
  11594. }
  11595. return false;
  11596. }
  11597. //是不是hicar的屏幕分辨率
  11598. isHiCarSmall() {
  11599. if(!this.isHiCar()){
  11600. return false
  11601. }
  11602. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  11603. {
  11604. this.columns = 6
  11605. return false
  11606. }
  11607. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11608. { ratio: 800 / 480, name: "800x480" },
  11609. { ratio: 1280 / 720, name: "1280x720" },
  11610. { ratio: 1920 / 1080, name: "1920x1080" },
  11611. ];
  11612. const currentRatio: number = this.windowWidth / this.windowHeight;
  11613. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11614. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  11615. for (const hiCarRatio of hiCarAspectRatios) {
  11616. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  11617. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11618. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  11619. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11620. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11621. //宽扁平的尺寸设置列表展示
  11622. return true;
  11623. }
  11624. }
  11625. return false;
  11626. }
  11627. isHiCar(): boolean {
  11628. return this.curDisplayIsHiCar;
  11629. }
  11630. //是不是正常的手机竖屏
  11631. isPhonePortrait() {
  11632. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  11633. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  11634. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  11635. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11636. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  11637. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  11638. return true
  11639. }
  11640. return false
  11641. }
  11642. @State showSpeedDialog: boolean = false
  11643. @State longPressSpeed: number = 3 //长按默认倍数
  11644. @Builder
  11645. SpeedDialog() {
  11646. Stack() {
  11647. Column() {
  11648. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11649. .fontColor(Color.White)
  11650. .visibility(Visibility.Hidden)
  11651. }
  11652. .backgroundColor(Color.Black)
  11653. .borderRadius(20)
  11654. .padding({
  11655. top: 10,
  11656. right: 20,
  11657. left: 15,
  11658. bottom: 20
  11659. })
  11660. .opacity(0.6)
  11661. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11662. .fontColor(Color.White)
  11663. }
  11664. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  11665. .zIndex(5)
  11666. .margin({ top: 80 })
  11667. }
  11668. @Builder
  11669. IjkMusicPlayerView() {
  11670. Stack() {
  11671. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  11672. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  11673. HdsVisualComponent()
  11674. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  11675. console.info('Succeeded in finishing');
  11676. })
  11677. .width('100%')
  11678. .height('100%')
  11679. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  11680. }
  11681. Column() {
  11682. Column() {
  11683. //播放标题
  11684. Column() {
  11685. this.PlayTitle()
  11686. }
  11687. .opacity(this.playDragUiOpacity)
  11688. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 40 })
  11689. .width('100%')
  11690. .margin({ top: 0 })
  11691. .height(PlayConstants.HEIGHT)
  11692. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  11693. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  11694. if (this.showSpeedDialog) {
  11695. this.SpeedDialog()
  11696. }
  11697. Stack() {
  11698. //手势拖动快进
  11699. Column()
  11700. .width(CommonConstants.FULL_PERCENT)
  11701. .height('100%')
  11702. .gesture(
  11703. GestureGroup(GestureMode.Parallel,
  11704. // 长按屏幕倍数播放
  11705. LongPressGesture({ repeat: true })
  11706. .onAction(() => {
  11707. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11708. this.showSpeedDialog = true;
  11709. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  11710. }
  11711. })
  11712. .onActionEnd(() => {
  11713. this.showSpeedDialog = false;
  11714. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11715. }),
  11716. )
  11717. )
  11718. }
  11719. .height('65%')
  11720. Swiper() {
  11721. this.CoverInfo()
  11722. this.PlayerLyrics()
  11723. }
  11724. .onChange((index: number) => {
  11725. this.currentSwiperIndex = index
  11726. if (index === 1) {
  11727. this.syncLyricPositionNow()
  11728. }
  11729. })
  11730. .indicator(false)
  11731. .displayCount(this.getPlayerSwiperDisplayCount())
  11732. .clip(false)
  11733. .loop(false)
  11734. .autoPlay(false)
  11735. // .interval(8000)
  11736. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  11737. .height('100%')
  11738. .hitTestBehavior(HitTestMode.Transparent)
  11739. Image($r('app.media.icon_replay'))
  11740. .objectFit(ImageFit.Auto)
  11741. .width('120px')
  11742. .height('120px')
  11743. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  11744. .border({ width: 0 })
  11745. .visibility(Visibility.None)
  11746. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  11747. .onClick(() => {
  11748. console.info('onecold startPlayOrResumePlay 6744')
  11749. this.startPlayOrResumePlay();
  11750. })
  11751. }
  11752. .width(CommonConstants.FULL_PERCENT)
  11753. .height(CommonConstants.FULL_PERCENT)
  11754. .justifyContent(FlexAlign.End)
  11755. }
  11756. .justifyContent(FlexAlign.End)
  11757. .margin({ bottom: 5 })
  11758. }
  11759. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  11760. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  11761. .animation({
  11762. duration: 666,
  11763. curve: 'ease-in-out' // 可选动画曲线
  11764. })
  11765. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  11766. ? BlurStyle.NONE :
  11767. BlurStyle.BACKGROUND_ULTRA_THICK)
  11768. .hitTestBehavior(HitTestMode.Transparent)
  11769. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  11770. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  11771. .onClick(() => {
  11772. if(this.isHiCar())
  11773. return
  11774. if(this.is_auto_hide_progress){
  11775. this.is_auto_hide_progress = false
  11776. }
  11777. this.startAutoHide()
  11778. })
  11779. }
  11780. @Consume progressValue: number ;
  11781. @State currentTime: string = "00:00";
  11782. @State totalTime: string = "00:00";
  11783. @State loadingVisible: Visibility = Visibility.None;
  11784. @State replayVisible: Visibility = Visibility.None;
  11785. @State slideEnable: boolean = false;
  11786. @State aspRatio: number = 0.5;
  11787. @State mContext: object | undefined = undefined;
  11788. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  11789. @State mFirst: boolean = true;
  11790. @State mDestroyPage: boolean = false;
  11791. @State playSpeed: number = 1;
  11792. @State oldSeconds: number = 0;
  11793. @State isSeekTo: boolean = false;
  11794. @State isCurrentTime: boolean = false;
  11795. @State videoWidth: string = '100%';
  11796. @State videoHeight: string = '100%';
  11797. @State initAspectRatio: number = 1;
  11798. @State videoAspectRatio: number = this.initAspectRatio;
  11799. @State videoUrl: string = '';
  11800. private last: number = 0;
  11801. @State videoParentAspectRatio: number = this.initAspectRatio;
  11802. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  11803. @Consume CONTROL_PlayStatus: number ;
  11804. @State PROGRESS_MAX_VALUE: number = 100;
  11805. @State updateProgressTimer: number = 0;
  11806. private readonly progressUpdateIntervalMs: number = 120;
  11807. private readonly lyricUpdateMinDeltaMs: number = 24;
  11808. private lastLyricRenderPosition: number = Number.NaN;
  11809. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  11810. @State name: string = '';
  11811. // @State loop: boolean = false;
  11812. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  11813. @State multiple: string = '1.0X';
  11814. xcomponentController: XComponentController = new XComponentController()
  11815. private panOptionBright: PanGestureOptions =
  11816. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  11817. private panOptionVolume: PanGestureOptions =
  11818. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  11819. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  11820. //手势的音量控制和亮度控制
  11821. private positionX: number = PlayConstants.POSITION_X;
  11822. private positionY: number = PlayConstants.POSITION_Y;
  11823. private windowClass: window.Window = globalThis.windowClass
  11824. @State volume: number = 0.8;
  11825. @State volumeBoostPercent: number = 0
  11826. @State volumeSmall: boolean = false
  11827. @State autoParseMusicName: boolean = true
  11828. @State isShowFileName: boolean = false
  11829. @State isLongNameRoLL: boolean = true//长歌名滚动
  11830. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  11831. private readonly volumeBoostMaxPercent: number = 500;
  11832. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  11833. @State bright: number = PlayConstants.BRIGHT;
  11834. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  11835. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  11836. @State screenWidth: number = 0
  11837. @State screenHeight: number = 0
  11838. @State statusBarHeight: number = 0
  11839. @State isYesFull: boolean = false
  11840. private seekValue: number = 0
  11841. @State isVideoLock: boolean = false; // Whether the video playback is locked
  11842. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  11843. private playbackUrlRequestSerial: number = 0;
  11844. eventHub = getContext().eventHub;
  11845. private isAppForeground: boolean = true;
  11846. private lastBufferingLogTs: number = 0;
  11847. private readonly bufferingLogIntervalMs: number = 5000;
  11848. //投播组件
  11849. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  11850. // 新的投播控制器(封装了官方示例的逻辑)
  11851. private castControllerWrapper: CastController | undefined = undefined;
  11852. // 保留原始的 avCastController 引用(用于兼容旧代码)
  11853. private castController: avSession.AVCastController | undefined = undefined;
  11854. @State isCastPlaying: boolean = false;
  11855. @State currentTime2: number = 0;
  11856. @State currentStringTime: string = '00:00';
  11857. @State duration: number = 0;
  11858. @State isReady: boolean = false;
  11859. @State durationTime: number = 0;
  11860. @State durationStringTime: string = '00:00';
  11861. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  11862. // @State isPlaying: boolean = false;
  11863. private castSeek: boolean = false;
  11864. private castItem: avSession.AVQueueItem | undefined = undefined;
  11865. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  11866. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  11867. @State rotateAngle2: number = -9
  11868. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  11869. @Consume cover: string | undefined ;
  11870. @State artist: string | undefined = ''
  11871. // 1.初始化controller
  11872. private lyricController: LyricController = new LyricController()
  11873. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  11874. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  11875. private parser = new LyricParser()
  11876. @State randomShakenX: number = 0
  11877. @State randomShakenY: number = 0
  11878. @State lyricTextSize: number = 24
  11879. @State lyricContent: string = ''
  11880. @State isDebug: boolean = false
  11881. @State isHightLightCenter: boolean = true
  11882. private syncWordByWordLyricMode(): void {
  11883. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11884. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11885. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11886. }
  11887. private syncLyricLightTextMode(): void {
  11888. this.lyricController.setLightText(this.isLightText)
  11889. this.lyricControllerXF.setLightText(this.isLightText)
  11890. this.lyricControllerSingle.setLightText(this.isLightText)
  11891. }
  11892. /**
  11893. * 初始化歌词加载与展示逻辑
  11894. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  11895. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  11896. * @param isApi2 是否使用API2获取歌词(可选)
  11897. *
  11898. * 主要流程:
  11899. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  11900. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  11901. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  11902. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  11903. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  11904. * 6. 解析失败或读取失败时,清空歌词显示。
  11905. *
  11906. * 注意事项:
  11907. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  11908. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  11909. * - 歌词内容解析后通过lyricController驱动UI渲染。
  11910. */
  11911. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  11912. if (StrUtil.isEmpty(lyricPath)) {
  11913. return
  11914. }
  11915. this.syncWordByWordLyricMode()
  11916. this.syncLyricLightTextMode()
  11917. this.initPipLyricSetting()
  11918. this.lyricControllerSingle
  11919. .setTextSize(15)
  11920. .setCacheSize(4)
  11921. .setTextColor("#FFFFFF")
  11922. .setHighlightColor(this.currentHighLightLyricColor)
  11923. .setHighlightScale(1.2)
  11924. .setEmptyHint("")
  11925. .setLineSpace(1)
  11926. .setAlignMode('center')
  11927. .setAnimationDuration(500)
  11928. .setSingleLine(true)
  11929. this.lyricContent = ''
  11930. this.lyricController
  11931. .setTextSize(this.currentLyricSize)
  11932. .setCacheSize(4)
  11933. .setTextColor("#DDDDDD")
  11934. .setHighlightColor("#FFFFFF")
  11935. .setEmptyHint("")
  11936. .setAnimationDuration(1000)
  11937. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  11938. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  11939. this.setBlurDegree(this.blurDegree, false)
  11940. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  11941. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  11942. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  11943. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  11944. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  11945. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  11946. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  11947. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  11948. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  11949. this.lyricController.setTextWeight(this.lyricTextWeight)
  11950. this.showSingleLyric = false
  11951. // 加载已保存的歌词时间偏移
  11952. this.loadLyricTimeOffset()
  11953. this.lyricController.setLyric(null)
  11954. this.lyricControllerSingle.setLyric(null)
  11955. console.log("onecold lyricPath =" + lyricPath)
  11956. // 1. 检查内嵌歌词
  11957. let neiqianLrc = ''
  11958. let lyContent = this.currentSong?.lyricContent
  11959. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  11960. neiqianLrc = lyContent
  11961. }
  11962. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  11963. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  11964. // Navidrome JSON歌词转换
  11965. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  11966. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  11967. if (convertedLyric) {
  11968. neiqianLrc = convertedLyric;
  11969. console.log("onecold Navidrome歌词转换成功");
  11970. }
  11971. }
  11972. this.setLyricToControllers(neiqianLrc);
  11973. return
  11974. }
  11975. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  11976. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  11977. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  11978. song: this.currentSong,
  11979. playbackUrl: this.videoUrl,
  11980. manager: RemoteDriveManager.getInstance(),
  11981. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  11982. });
  11983. if (StrUtil.isNotEmpty(remoteLyric)) {
  11984. this.currentSong.lyricContent = remoteLyric;
  11985. this.setLyricToControllers(remoteLyric);
  11986. void this.persistRemoteMetadataToDb(this.currentSong);
  11987. return;
  11988. }
  11989. }
  11990. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  11991. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  11992. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  11993. || isPlexType(this.currentSong.type))) {
  11994. const manager = RemoteDriveManager.getInstance();
  11995. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  11996. // 将currentSong转换为SongData接口
  11997. const songData: SongData = {
  11998. webdav_account_id: this.currentSong.webdav_account_id,
  11999. artist: this.currentSong.artist,
  12000. name: this.currentSong.name,
  12001. webdav_id: this.currentSong.webdav_id,
  12002. lyricIndex: this.currentSong.lyricIndex,
  12003. type: this.currentSong.type
  12004. };
  12005. let serverLyric = '';
  12006. if (!serverLyric && isNavidromeType(songData.type)) {
  12007. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  12008. }
  12009. if (!serverLyric && isJellyfinType(songData.type)) {
  12010. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  12011. }
  12012. if (!serverLyric && isEmbyType(songData.type)) {
  12013. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  12014. }
  12015. if (!serverLyric && isAudioStationType(songData.type)) {
  12016. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  12017. }
  12018. if (!serverLyric && isPlexType(songData.type)) {
  12019. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  12020. }
  12021. if (serverLyric) {
  12022. this.setLyricToControllers(serverLyric, lyricPath);
  12023. return;
  12024. }
  12025. }
  12026. // 4. 尝试在线歌词API
  12027. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  12028. && !Utility.isVideoByExtension(this.videoUrl))) {
  12029. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  12030. return;
  12031. }
  12032. // 5. 从本地文件读取歌词
  12033. await this.loadLyricFromFile(lyricPath, isLocal || false);
  12034. }
  12035. /**
  12036. * 从本地文件加载歌词
  12037. */
  12038. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  12039. try {
  12040. let realLyricPath = lyricPath;
  12041. // 读取文件内容
  12042. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  12043. const stat = await fileIo.stat(file.fd);
  12044. const arrayBuffer = new ArrayBuffer(stat.size);
  12045. fs.read(file.fd, arrayBuffer)
  12046. .then((readLen: number) => {
  12047. console.info("read file data succeed");
  12048. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  12049. if (buf.length === 0) {
  12050. throw new Error("Buffer is empty after reading the file");
  12051. }
  12052. try {
  12053. // 检测文件编码
  12054. let detectedEncoding = this.detect(arrayBuffer);
  12055. console.info("onecoldT Detected encoding: " + detectedEncoding);
  12056. // 使用检测到的编码解码,解决中文乱码问题
  12057. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  12058. console.info("onecoldT Detected textDecoder: " + textDecoder);
  12059. let fileContent = textDecoder.decode(buf);
  12060. console.info(`onecoldT The content of file1: ${fileContent}`);
  12061. console.info(`onecold The content of file2: ${fileContent}`);
  12062. this.lyricContent = fileContent;
  12063. if(isLocal){
  12064. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  12065. this.lyricConStr = fileContent;
  12066. }
  12067. this.setLyricToControllers(fileContent);
  12068. console.info(`The content of file: ${fileContent}`);
  12069. } catch (chardetError) {
  12070. console.error("chardet.detect failed with error: " + chardetError.message);
  12071. this.clearLyricControllers();
  12072. }
  12073. })
  12074. .catch((err: BusinessError) => {
  12075. this.clearLyricControllers();
  12076. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  12077. })
  12078. .catch((err: Error) => {
  12079. this.clearLyricControllers();
  12080. console.error("read file 2 data failed with error message: " + err.message);
  12081. })
  12082. .finally(() => {
  12083. fs.closeSync(file);
  12084. });
  12085. } catch (error) {
  12086. this.clearLyricControllers();
  12087. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  12088. }
  12089. }
  12090. detect(data: ArrayBuffer): string {
  12091. //创建检测对象
  12092. let detector: UniversalDetector = new UniversalDetector();
  12093. // 限制检测数据大小,避免内存溢出
  12094. // 通常只需要检测文件前16KB就足够判断编码格式
  12095. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  12096. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  12097. // 传入检测数据并实时判断编码格式
  12098. detector.handleData(data, 0, detectSize);
  12099. // 标记检测数据 读取结束
  12100. detector.dataEnd();
  12101. // 获取检测结果
  12102. let detected: string = detector.getDetectedCharset();
  12103. // 释放资源
  12104. detector.reset();
  12105. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  12106. return detected;
  12107. }
  12108. /**
  12109. * 设置歌词到所有控制器
  12110. * @param lyricText 歌词文本
  12111. * @param savePath 可选,如果提供则保存到本地文件
  12112. */
  12113. private setLyricToControllers(lyricText: string, savePath?: string): void {
  12114. if (StrUtil.isEmpty(lyricText)) {
  12115. this.clearLyricControllers();
  12116. return;
  12117. }
  12118. this.lyricContent = lyricText;
  12119. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  12120. const lyric: Lyric = this.parser.parse(lines);
  12121. this.lyricController.setLyric(lyric);
  12122. this.lyricControllerXF.setLyric(lyric);
  12123. this.lyricControllerSingle.setLyric(lyric);
  12124. this.showSingleLyric = true;
  12125. // 如果提供了保存路径,保存歌词到本地
  12126. if (savePath) {
  12127. this.saveDataToFile(lyricText, savePath);
  12128. }
  12129. }
  12130. /**
  12131. * 清空所有歌词控制器
  12132. */
  12133. private clearLyricControllers(): void {
  12134. this.lyricController.setLyric(null);
  12135. this.lyricControllerXF.setLyric(null);
  12136. this.lyricControllerSingle.setLyric(null);
  12137. }
  12138. private extractLyricCopyLines(lyricText: string): string[] {
  12139. if (StrUtil.isEmpty(lyricText)) {
  12140. return [];
  12141. }
  12142. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  12143. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  12144. const lines = source.split('\n');
  12145. const result: string[] = [];
  12146. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  12147. for (let i = 0; i < lines.length; i++) {
  12148. const line = lines[i].trim();
  12149. if (!line || metaTagPattern.test(line)) {
  12150. continue;
  12151. }
  12152. const pureLine = line
  12153. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  12154. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  12155. .trim();
  12156. if (pureLine.length > 0) {
  12157. result.push(pureLine);
  12158. }
  12159. }
  12160. return result;
  12161. }
  12162. private openLyricCopySheet(): void {
  12163. const lines = this.extractLyricCopyLines(this.lyricContent);
  12164. if (ArrayUtil.isEmpty(lines)) {
  12165. ToastUtil.showToast('暂无可复制歌词');
  12166. return;
  12167. }
  12168. this.lyricCopyLines = lines;
  12169. this.lyricSelectedIndexes = [];
  12170. this.isShowLyricCopySheet = true;
  12171. }
  12172. private toggleLyricLineSelection(index: number): void {
  12173. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  12174. if (selectedIndex >= 0) {
  12175. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  12176. nextSelectedIndexes.splice(selectedIndex, 1);
  12177. this.lyricSelectedIndexes = nextSelectedIndexes;
  12178. return;
  12179. }
  12180. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  12181. }
  12182. private toggleLyricSelectAll(): void {
  12183. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  12184. this.lyricSelectedIndexes = [];
  12185. return;
  12186. }
  12187. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  12188. }
  12189. private copySelectedLyricLines(): void {
  12190. const selectedLines = this.getSelectedLyricLines();
  12191. if (ArrayUtil.isEmpty(selectedLines)) {
  12192. ToastUtil.showToast('暂无可复制歌词');
  12193. return;
  12194. }
  12195. Utility.copyText(selectedLines.join('\n'));
  12196. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  12197. }
  12198. private getSelectedLyricLines(): string[] {
  12199. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  12200. return [];
  12201. }
  12202. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  12203. const selectedLines: string[] = [];
  12204. for (let i = 0; i < selectedIndexes.length; i++) {
  12205. const index = selectedIndexes[i];
  12206. if (index >= 0 && index < this.lyricCopyLines.length) {
  12207. selectedLines.push(this.lyricCopyLines[index]);
  12208. }
  12209. }
  12210. return selectedLines;
  12211. }
  12212. private shareSelectedLyricLines(): void {
  12213. const selectedLines = this.getSelectedLyricLines();
  12214. if (ArrayUtil.isEmpty(selectedLines)) {
  12215. ToastUtil.showToast('暂无可分享歌词');
  12216. return;
  12217. }
  12218. const shareTitle = `${this.currentSong?.name ?? '歌词'}歌词`;
  12219. Utility.doShareText(selectedLines.join('\n'), this.context, shareTitle, '分享歌词');
  12220. }
  12221. /**
  12222. * 从在线API获取歌词
  12223. */
  12224. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  12225. if (!this.currentSong) {
  12226. this.clearLyricControllers();
  12227. if (isOnLineAndToast) {
  12228. ToastUtil.showShort('未获取到歌词!');
  12229. }
  12230. return;
  12231. }
  12232. let artist = this.currentSong.artist || '';
  12233. if (isApi2 === undefined) {
  12234. isApi2 = false;
  12235. }
  12236. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  12237. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  12238. this.setLyricToControllers(res, lyricPath);
  12239. } else {
  12240. this.clearLyricControllers();
  12241. if (isOnLineAndToast) {
  12242. ToastUtil.showShort('未获取到歌词!');
  12243. }
  12244. }
  12245. });
  12246. }
  12247. //初始化悬浮歌词的自定义设置
  12248. initPipLyricSetting() {
  12249. this.lyricControllerXF
  12250. .setTextSize(this.currentLyricSize)
  12251. .setCacheSize(4)
  12252. .setTextColor("#DDDDDD")
  12253. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  12254. .setEmptyHint("")
  12255. .setAnimationDuration(1000)
  12256. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  12257. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  12258. this.setBlurDegree(this.blurDegreePip, true)
  12259. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  12260. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  12261. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  12262. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  12263. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  12264. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  12265. this.lyricControllerXF.setHightLightCenter(true)
  12266. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  12267. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  12268. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  12269. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  12270. if (this.pipBgIndex === 0) {
  12271. if (this.cover) {
  12272. this.pipBg = this.cover
  12273. } else {
  12274. this.pipBg = this.imageColor
  12275. }
  12276. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  12277. }
  12278. }
  12279. //根据item返回歌词内容
  12280. async getLyricContent(item: VideoItem): Promise<string> {
  12281. let neiqianLrc = ''
  12282. let lyContent = item?.lyricContent
  12283. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  12284. neiqianLrc = lyContent
  12285. return neiqianLrc
  12286. }
  12287. try {
  12288. //取数据库里面的歌词lyContent
  12289. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  12290. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  12291. console.log("onecold Lyrics:", lyricContent);
  12292. neiqianLrc = lyricContent
  12293. return neiqianLrc
  12294. }
  12295. } catch (error) {
  12296. console.error("Error fetching lyrics:", error);
  12297. }
  12298. try {
  12299. let filePath = item.filePath;
  12300. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  12301. let realLyricPath = lyricPath;
  12302. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  12303. const stat = await fileIo.stat(file.fd);
  12304. const arrayBuffer = new ArrayBuffer(stat.size);
  12305. const readLen = await fs.read(file.fd, arrayBuffer);
  12306. console.info("read file data succeed");
  12307. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  12308. if (buf.length === 0) {
  12309. throw new Error("Buffer is empty after reading the file");
  12310. }
  12311. // let detectedEncoding = chardet.detect(buf);
  12312. let detectedEncoding = this.detect(arrayBuffer)
  12313. console.info("Detected encoding: " + detectedEncoding);
  12314. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  12315. let fileContent = textDecoder.decode(buf);
  12316. console.info(`onecold The content of file1: ${fileContent}`);
  12317. fs.closeSync(file);
  12318. return fileContent;
  12319. } catch (error) {
  12320. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  12321. return '';
  12322. }
  12323. }
  12324. async saveDataToFile(content: string, filePath: string) {
  12325. if (StrUtil.isEmpty(filePath)) {
  12326. return
  12327. }
  12328. try {
  12329. let lyricContent = ''
  12330. lyricContent = content
  12331. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  12332. // 清空文件内容
  12333. await fileIo.truncate(file.fd, 0);
  12334. await fileIo.write(file.fd, lyricContent);
  12335. await fileIo.close(file);
  12336. console.log('onecold lyric file Data saved successfully.');
  12337. } catch (error) {
  12338. console.error('onecold lyric file Failed to save data:', error);
  12339. }
  12340. }
  12341. // 定义开始旋转的方法
  12342. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  12343. @State timer: number = 0
  12344. @State rotateAngle: number = 0
  12345. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  12346. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  12347. // 页面可见性变化回调
  12348. onPageVisibilityChange() {
  12349. // 当页面可见性改变时,重新启动/停止旋转动画
  12350. this.animationRoFun()
  12351. }
  12352. //封面旋转动画
  12353. animationRoFun() {
  12354. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  12355. // 启动旋转动画
  12356. if (!this.isRotationRunning) {
  12357. this.isRotationRunning = true
  12358. this.startContinuousRotation()
  12359. }
  12360. this.startRotation()
  12361. } else {
  12362. // 停止旋转动画
  12363. this.isRotationRunning = false
  12364. clearInterval(this.timer)
  12365. this.stopRotation()
  12366. }
  12367. }
  12368. // 使用持续的动画进行旋转,避免频繁状态更新
  12369. private startContinuousRotation() {
  12370. clearInterval(this.timer)
  12371. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  12372. // 不使用 % 360 取模,让角度持续累加,避免反转
  12373. this.timer = setInterval(() => {
  12374. if (this.isRotationRunning) {
  12375. this.rotateAngle = this.rotateAngle + 36
  12376. }
  12377. }, 1000)
  12378. }
  12379. // 定义开始旋转的方法
  12380. startRotation() {
  12381. if (this.isPlaying) {
  12382. animateTo({
  12383. duration: 777,
  12384. iterations: 1,
  12385. curve: Curve.Linear
  12386. }, () => {
  12387. this.rotateAngle2 = -9
  12388. })
  12389. }
  12390. }
  12391. // 回调,暂停和播放按钮回调,下一首和上一首
  12392. playChange() {
  12393. // if(this.isCoverRectangle){
  12394. // return
  12395. // }
  12396. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12397. this.setIsPlaying(true)
  12398. this.animationState = AnimationStatus.Running
  12399. } else {
  12400. this.setIsPlaying(false)
  12401. this.animationState = AnimationStatus.Paused
  12402. }
  12403. AppStorage.setOrCreate('animationState', this.animationState);
  12404. }
  12405. // 定义停止旋转的方法
  12406. stopRotation() {
  12407. if (this.isCoverRectangle) {
  12408. this.rotateAngle = 0
  12409. } else {
  12410. //唱针以左上角为点选择逆时针40度
  12411. animateTo({
  12412. duration: 1000,
  12413. curve: Curve.Linear,
  12414. iterations: 1,
  12415. }, () => {
  12416. this.rotateAngle2 = -45;
  12417. });
  12418. }
  12419. }
  12420. @Builder
  12421. private LyricsTopItem() {
  12422. Row() {
  12423. Stack({ alignContent: Alignment.Center }) {
  12424. Image( StrUtil.isNotEmpty(this.cover)?
  12425. this.cover:$r('app.media.alt'))
  12426. .height(58)
  12427. .width(58)
  12428. .clip(true)
  12429. .sourceSize({width:38, height:38})
  12430. .alt($r('app.media.alt'))
  12431. .borderRadius(8)
  12432. .clickEffect({ level: ClickEffectLevel.HEAVY })
  12433. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  12434. .shadow({
  12435. radius: 22,
  12436. type: ShadowType.BLUR,
  12437. color: 'on_primary'
  12438. })
  12439. }
  12440. .width(62)
  12441. .height('100%')
  12442. Column() {
  12443. Column() {
  12444. Text(this.name)
  12445. .fontSize(16)
  12446. .maxLines(1)
  12447. .fontWeight(FontWeight.Bolder)
  12448. .fontColor(Color.White)
  12449. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12450. .margin({ left: 10 })
  12451. Row() {
  12452. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  12453. .fontSize(13)
  12454. .fontWeight(FontWeight.Bolder)
  12455. .padding({ top: 8 })
  12456. .fontColor(Color.White)
  12457. .margin({ left: 10 })
  12458. Blank()
  12459. }
  12460. }
  12461. .height('100%')
  12462. .width('100%')
  12463. .justifyContent(FlexAlign.Center)
  12464. .alignItems(HorizontalAlign.Start)
  12465. }
  12466. .height('100%')
  12467. .layoutWeight(1)
  12468. .margin({ right: 8 })
  12469. Column() {
  12470. PointLightDefaultButton({
  12471. isSysBol:false,
  12472. pointColor:Color.White,
  12473. imageResource:$r('app.media.lyric'),
  12474. isPx: false,
  12475. builderHeight: 23,
  12476. builderWidth: 23,
  12477. })
  12478. .onClick(() => {
  12479. this.isLyricSetting = !this.isLyricSetting;
  12480. })
  12481. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  12482. height: '99%',
  12483. dragBar: true,
  12484. preferType: SheetType.CENTER,
  12485. showClose: true,
  12486. blurStyle: BlurStyle.Thin,
  12487. backgroundColor: Color.Transparent,
  12488. title: { title: $r('app.string.lyric_setting') }
  12489. })
  12490. }
  12491. .width(44)
  12492. .height('100%')
  12493. .justifyContent(FlexAlign.Center)
  12494. .alignItems(HorizontalAlign.End)
  12495. }
  12496. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  12497. .padding({ left: 28, right: 28 })
  12498. .height(58)
  12499. .alignItems(VerticalAlign.Center)
  12500. }
  12501. //歌词显示
  12502. @Builder
  12503. PlayerLyrics() {
  12504. Column() {
  12505. Column() {
  12506. this.LyricsTopItem()
  12507. }
  12508. .height(this.isPuraWP() ? 15 : 58)
  12509. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  12510. Visibility.None : Visibility.Visible)
  12511. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  12512. .width("100%")
  12513. Column() {
  12514. LyricView2({
  12515. controller: this.lyricController,
  12516. enableSeek: true,
  12517. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12518. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12519. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12520. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  12521. if (!this.isPlaying) {
  12522. console.info('onecold startPlayOrResumePlay 7527')
  12523. this.startPlayOrResumePlay()
  12524. }
  12525. else {
  12526. this.isSeekTo = true;
  12527. this.mDestroyPage = false;
  12528. // 只有播放网盘歌曲时才显示转圈圈
  12529. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12530. this.showLoadIng();
  12531. }
  12532. this.seekTo(position + "");
  12533. }
  12534. return true
  12535. }
  12536. })
  12537. .width("100%")
  12538. .layoutWeight(1)
  12539. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  12540. .gesture(LongPressGesture()
  12541. .onAction(() => {
  12542. this.openLyricCopySheet();
  12543. }))
  12544. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  12545. height: '99%',
  12546. dragBar: true,
  12547. showClose: true,
  12548. preferType: SheetType.CENTER,
  12549. blurStyle: BlurStyle.Thin,
  12550. title: { title: '歌词' }
  12551. })
  12552. if (this.isPhoneLan()) {
  12553. Column() {
  12554. if (this.isShowSpectrum) {
  12555. this.InlineSpectrumView()
  12556. }
  12557. this.playProgressView()
  12558. }
  12559. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  12560. }
  12561. }
  12562. .position({
  12563. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  12564. (this.isPuraWP() ? 58 : 99)
  12565. })
  12566. .justifyContent(FlexAlign.Center)
  12567. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  12568. }
  12569. }
  12570. @Builder
  12571. LyricCopySheetBuilder() {
  12572. LyricCopySheet({
  12573. lyricCopyLines: this.lyricCopyLines,
  12574. lyricSelectedIndexes: this.lyricSelectedIndexes,
  12575. isDarkMode: this.isDarkMode,
  12576. themeColor: this.themeColor,
  12577. bottomSafeHeight: this.bottomSafeHeight,
  12578. onToggleLyricLine: (index: number) => {
  12579. this.toggleLyricLineSelection(index);
  12580. },
  12581. onToggleSelectAll: () => {
  12582. this.toggleLyricSelectAll();
  12583. },
  12584. onCopySelectedLines: () => {
  12585. this.copySelectedLyricLines();
  12586. },
  12587. onShareSelectedLines: () => {
  12588. this.shareSelectedLyricLines();
  12589. }
  12590. })
  12591. }
  12592. @Builder
  12593. SingleLyricView() {
  12594. Column() {
  12595. Column() {
  12596. LyricView2({
  12597. controller: this.lyricControllerSingle,
  12598. enableSeek: false,
  12599. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12600. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12601. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12602. })
  12603. .gesture(LongPressGesture()
  12604. .onAction(() => {
  12605. this.openLyricCopySheet();
  12606. }))
  12607. }
  12608. .height(82)
  12609. .margin({ bottom: 20 })
  12610. }
  12611. .opacity(this.playDragUiOpacity)
  12612. }
  12613. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  12614. @Builder
  12615. BottomControl() {
  12616. Column() {
  12617. if (this.isShowSpectrum) {
  12618. this.InlineSpectrumView()
  12619. }
  12620. this.TopPlayProgressView()
  12621. //播放 暂停,下一首,上一首
  12622. this.playCenterView()
  12623. if(!this.curDisplayIsHiCar){
  12624. //播放进度条
  12625. this.BottomView()
  12626. }
  12627. }
  12628. .justifyContent(FlexAlign.Center)
  12629. .alignItems(HorizontalAlign.Center)
  12630. .opacity(this.playDragUiOpacity)
  12631. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  12632. }
  12633. @Builder
  12634. playMenuBuilder(){
  12635. Image($r('app.media.menu'))
  12636. .width(24)
  12637. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12638. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  12639. height: '99%',
  12640. preferType:SheetType.CENTER,
  12641. dragBar: true,
  12642. showClose: true,
  12643. blurStyle: BlurStyle.Thin,
  12644. title: { title: $r('app.string.more') },
  12645. backgroundColor: Color.Transparent,
  12646. })
  12647. }
  12648. //播放控制上一首 下一首 暂停和播放
  12649. @Builder
  12650. playCenterView(){
  12651. Row() {
  12652. PointLightButton({
  12653. builder: () => {
  12654. this.playMenuBuilder()
  12655. },
  12656. isPx: false,
  12657. builderHeight: 26,
  12658. builderWidth: 26,
  12659. })
  12660. .onClick(async () =>{
  12661. this.isShowMoreView = !this.isShowMoreView;
  12662. })
  12663. PointLightButton({
  12664. builder: () => {
  12665. this.playPreviousBuilder()
  12666. },
  12667. isPx: false,
  12668. builderHeight: 26,
  12669. builderWidth: 26,
  12670. })
  12671. .onClick(async () =>{
  12672. await this.playPrevious()
  12673. })
  12674. PointLightButton({
  12675. builder: () => {
  12676. this.PlayOrPauseButton()
  12677. },
  12678. isPx: false,
  12679. builderHeight: this.isPhoneLan()?38:41,
  12680. builderWidth: this.isPhoneLan()?38:41,
  12681. })
  12682. .onClick(() =>{
  12683. this.playOrPause()
  12684. })
  12685. PointLightButton({
  12686. builder: () => {
  12687. this.playNextBuilder()
  12688. },
  12689. isPx: false,
  12690. builderHeight: 26,
  12691. builderWidth: 26,
  12692. })
  12693. .onClick(async () =>{
  12694. await this.playNext()
  12695. })
  12696. this.playModeButton()
  12697. }
  12698. .width('95%')
  12699. .margin({ bottom:this.isCoverOpacity()?0:15 })
  12700. .justifyContent(FlexAlign.SpaceEvenly)
  12701. }
  12702. @Builder
  12703. playPreviousBuilder(){
  12704. Image($r('app.media.ic_previous'))
  12705. .width(32)
  12706. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12707. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12708. }
  12709. @Builder
  12710. playNextBuilder(){
  12711. Image($r('app.media.ic_next'))
  12712. .width(32)
  12713. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12714. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12715. }
  12716. @Builder
  12717. PlayOrPauseButton(){
  12718. Stack() {
  12719. Column() {
  12720. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  12721. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  12722. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  12723. .width(this.isPhoneLan()?38:40)
  12724. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12725. .fillColor(Color.White)
  12726. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12727. }
  12728. // 加载进度圈
  12729. if (this.isPlayerLoading) {
  12730. Progress({value:0,total:100,type:ProgressType.Ring })
  12731. .width(this.isPhoneLan()?40:43)
  12732. .height(this.isPhoneLan()?40:43)
  12733. .color(Color.White)
  12734. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  12735. }
  12736. }
  12737. .width(this.isPhoneLan()?38:41)
  12738. .height(this.isPhoneLan()?38:41)
  12739. }
  12740. @Builder
  12741. TopPlayProgressView(){
  12742. Column() {
  12743. Row(){
  12744. Stack(){
  12745. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  12746. .fontColor([Color.White])
  12747. .fontSize(21)
  12748. .effectStrategy(1)
  12749. Text(this.fastForwardSeconds)
  12750. .fontColor(Color.White)
  12751. .fontSize(10)
  12752. .fontWeight(FontWeight.Bold)
  12753. }
  12754. .padding({left:12,bottom:6})
  12755. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12756. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12757. .onClick(()=>{
  12758. this.backForward()
  12759. })
  12760. Slider({
  12761. value: this.progressValue,
  12762. min: 0,
  12763. max: this.PROGRESS_MAX_VALUE,
  12764. step: 1,
  12765. style: SliderStyle.InSet
  12766. })
  12767. .height(20)
  12768. .blockColor('rgba(255,255,255,1)')
  12769. .trackColor('rgba(255,255,255,0.3)')
  12770. .selectedColor(Color.White)
  12771. .trackThickness(4)
  12772. .showSteps(false)
  12773. .showTips(true)
  12774. .layoutWeight(1)
  12775. .enabled(this.slideEnable)
  12776. .onChange((value: number, mode: SliderChangeMode) => {
  12777. if (mode !== 2) {
  12778. return
  12779. }
  12780. if(this.isSeekTo)
  12781. return
  12782. this.isSeekTo = true;
  12783. this.mDestroyPage = false;
  12784. // 只有播放网盘歌曲时才显示转圈圈
  12785. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12786. this.showLoadIng();
  12787. }
  12788. let seekValue = value * (this.getActiveDuration() / 100);
  12789. this.seekTo(seekValue + "", "top-progress-slider");
  12790. })
  12791. Stack(){
  12792. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  12793. .fontColor([Color.White])
  12794. .fontSize(21)
  12795. .effectStrategy(1)
  12796. Text(this.fastForwardSeconds)
  12797. .fontColor(Color.White)
  12798. .fontSize(10)
  12799. .fontWeight(FontWeight.Bold)
  12800. }
  12801. .padding({right:10,bottom:6})
  12802. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12803. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12804. .onClick(()=>{
  12805. this.fastForward()
  12806. })
  12807. }
  12808. .justifyContent(FlexAlign.Center)
  12809. .padding({left:20,right:20})
  12810. .width(this.isLandscape?'88%':'95%')
  12811. Row() {
  12812. Text(this.currentTime)
  12813. .fontSize(10)
  12814. .fontColor(Color.White)
  12815. .margin({left:25})
  12816. Blank()
  12817. Text(this.totalTime)
  12818. .fontSize(10)
  12819. .fontColor(Color.White)
  12820. .margin({right:25})
  12821. }
  12822. .width(this.isLandscape?'85%':'90%')
  12823. .height(10)
  12824. }
  12825. .width('100%')
  12826. .alignItems(HorizontalAlign.Center)
  12827. }
  12828. @Builder
  12829. playModeButton(){
  12830. PointLightButton({
  12831. builder: () => {
  12832. this.playModeBuilder()
  12833. },
  12834. isPx: false,
  12835. builderHeight: 26,
  12836. builderWidth: 26,
  12837. })
  12838. .onClick(async () =>{
  12839. this.setLoopMode()
  12840. })
  12841. }
  12842. @Builder
  12843. playModeBuilder(){
  12844. Column() {
  12845. if (this.playType === 0) {
  12846. Image($r('app.media.loop'))
  12847. .width(24)
  12848. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12849. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12850. } else if (this.playType === 1) {
  12851. Image($r('app.media.single'))
  12852. .width(24)
  12853. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12854. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12855. } else if (this.playType === 2) {
  12856. Image($r('app.media.normal_play'))
  12857. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12858. .width(24)
  12859. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12860. } else if (this.playType === 3) {
  12861. Image($r('app.media.random'))
  12862. .width(24)
  12863. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12864. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12865. } else if (this.playType === 4) {
  12866. Image($r('app.media.noloop'))
  12867. .width(24)
  12868. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12869. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12870. }
  12871. }
  12872. }
  12873. //播放进度条
  12874. @Builder
  12875. BottomView(){
  12876. Row() {
  12877. PointLightDefaultButton({
  12878. isSysBol:true,
  12879. pointColor:Color.White,
  12880. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12881. isPx: false,
  12882. builderHeight: 22,
  12883. builderWidth: 22,
  12884. })
  12885. .onClick(async () =>{
  12886. if (this.isLandscape) {
  12887. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12888. } else {
  12889. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12890. }
  12891. })
  12892. if(this.currentSong){
  12893. PointLightDefaultButton({
  12894. isSysBol:true,
  12895. pointColor:Color.White,
  12896. imageResource:$r('sys.symbol.rename'),
  12897. isPx: false,
  12898. builderHeight: 22,
  12899. builderWidth: 22,
  12900. })
  12901. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  12902. height: '99%',
  12903. dragBar: true,
  12904. showClose: true,
  12905. preferType: SheetType.BOTTOM,
  12906. title: { title: '编辑标签' }
  12907. })
  12908. .onClick(async () => {
  12909. this.initEditFields(this.currentSong)
  12910. this.tempLyricContent = this.lyricContent
  12911. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  12912. this.lyricConStr = this.tempLyricContent
  12913. }
  12914. this.isShowEdit = !this.isShowEdit;
  12915. })
  12916. }
  12917. PointLightDefaultButton({
  12918. isSysBol:true,
  12919. pointColor:Color.White,
  12920. imageResource:$r('sys.symbol.slider_vertical_3'),
  12921. isPx: false,
  12922. builderHeight: 22,
  12923. builderWidth: 22,
  12924. })
  12925. .onClick(async () => {
  12926. this.isEqualizerSheet = !this.isEqualizerSheet;
  12927. })
  12928. PointLightDefaultButton({
  12929. isSysBol:true,
  12930. pointColor:Color.White,
  12931. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  12932. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  12933. isPx: false,
  12934. builderHeight: 22,
  12935. builderWidth: 22,
  12936. })
  12937. .onClick(async () => {
  12938. if(this.currentSong){
  12939. this.doFav(this.currentSong)
  12940. }
  12941. })
  12942. this.playListBuilder()
  12943. }
  12944. .width(this.isLandscape?'88%':'95%')
  12945. .justifyContent(FlexAlign.SpaceAround)
  12946. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  12947. .height(30)
  12948. .animation({
  12949. duration: 666,
  12950. curve: 'ease-in-out' // 可选动画曲线
  12951. })
  12952. }
  12953. @Builder
  12954. fullButton(){
  12955. Column() {
  12956. Image($r('app.media.full_4'))
  12957. .width(25)
  12958. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12959. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12960. }
  12961. }
  12962. @Builder
  12963. playListBuilder(){
  12964. PointLightDefaultButton({
  12965. isSysBol:true,
  12966. pointColor:Color.White,
  12967. imageResource:$r('sys.symbol.music_note_list'),
  12968. isPx: false,
  12969. builderHeight: 26,
  12970. builderWidth: 26,
  12971. })
  12972. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  12973. height: '95%',
  12974. dragBar: true,
  12975. showClose: true,
  12976. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12977. blurStyle: BlurStyle.Thin,
  12978. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  12979. title: {
  12980. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12981. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12982. + `(${this.getPlayListDisplayCount()}首)`
  12983. }
  12984. })
  12985. .onClick(() => {
  12986. this.isShowSheetView = !this.isShowSheetView;
  12987. if(this.isPlayListBgGrass){
  12988. this.isFrontWhite = true
  12989. }else{
  12990. this.isFrontWhite = false
  12991. }
  12992. this.scrollIndex()
  12993. if (this.shouldHydrateFullMediaPlayListOnOpen()) {
  12994. void this.hydrateFullMediaPlayListIfNeeded();
  12995. }
  12996. })
  12997. }
  12998. //旧版本播放进度条(现在是手机横屏的播放条)
  12999. @Builder
  13000. playProgressView() {
  13001. Row() {
  13002. Column(){
  13003. PointLightDefaultButton({
  13004. isSysBol:true,
  13005. pointColor:Color.White,
  13006. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  13007. isPx: false,
  13008. builderHeight: 26,
  13009. builderWidth: 26,
  13010. })
  13011. .onClick(async () =>{
  13012. if (this.isLandscape) {
  13013. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  13014. } else {
  13015. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  13016. }
  13017. })
  13018. }
  13019. .margin({ right: 10,bottom:6})
  13020. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  13021. .animation({
  13022. duration: 666,
  13023. curve: 'ease-in-out' // 可选动画曲线
  13024. })
  13025. Text(this.currentTime)
  13026. .fontSize($r('app.float.slider_font_size'))
  13027. .fontColor(Color.White)
  13028. .margin(3)
  13029. Slider({
  13030. value: this.progressValue,
  13031. min: 0,
  13032. max: this.PROGRESS_MAX_VALUE,
  13033. step: 1,
  13034. style: SliderStyle.InSet
  13035. })
  13036. .width('600px')
  13037. .blockColor('rgba(255,255,255,1)')
  13038. .trackColor('rgba(255,255,255,0.3)')
  13039. .selectedColor(Color.White)
  13040. .trackThickness(5)
  13041. .layoutWeight(1)
  13042. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  13043. .showSteps(false)
  13044. .showTips(true)
  13045. .enabled(this.slideEnable)
  13046. .onChange((value: number, mode: SliderChangeMode) => {
  13047. if (mode !== 2) {
  13048. return
  13049. }
  13050. this.isSeekTo = true;
  13051. this.mDestroyPage = false;
  13052. // 只有播放网盘歌曲时才显示转圈圈
  13053. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  13054. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  13055. this.showLoadIng();
  13056. }
  13057. let seekValue = value * (this.getActiveDuration() / 100);
  13058. this.seekTo(seekValue + "", "landscape-progress-slider");
  13059. })
  13060. Text(this.totalTime)
  13061. .fontSize($r('app.float.slider_font_size'))
  13062. .fontColor(Color.White)
  13063. .margin(3)
  13064. //播放列表
  13065. Column(){
  13066. this.playListBuilder()
  13067. }
  13068. .margin({ left: 10,bottom:6})
  13069. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  13070. .animation({
  13071. duration: 666,
  13072. curve: 'ease-in-out' // 可选动画曲线
  13073. })
  13074. }
  13075. //x5的竖屏模式需要99%
  13076. .width(this.isPhonePortrait() ? '93.4%'
  13077. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  13078. .height(this.isPhoneLan() ? 25 : 33)
  13079. .alignItems(VerticalAlign.Bottom)
  13080. .animation({
  13081. duration: 666,
  13082. curve: 'ease-in-out' // 可选动画曲线
  13083. })
  13084. }
  13085. isBigScreen() {
  13086. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  13087. return true
  13088. }
  13089. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  13090. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  13091. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  13092. return false
  13093. } else {
  13094. return true
  13095. }
  13096. return false
  13097. }
  13098. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  13099. // 添加控制缩放的状态变量
  13100. @State scaleValueImage: number = 1
  13101. @State scaleValueText: number = 1
  13102. @State playDragUiOpacity: number = 1
  13103. @Builder
  13104. private CoverScaleGuideOverlay() {
  13105. Stack() {
  13106. Column({ space: 10 }) {
  13107. SymbolGlyph($r('sys.symbol.arrow_up_left_and_arrow_down_right'))
  13108. .fontSize(34)
  13109. .fontColor([Color.White])
  13110. Text('双指缩放封面')
  13111. .fontSize(16)
  13112. .fontWeight(FontWeight.Bold)
  13113. .fontColor(Color.White)
  13114. Text('在封面区域双指捏合,可调整封面大小')
  13115. .fontSize(12)
  13116. .fontColor(Color.White)
  13117. .opacity(0.88)
  13118. .textAlign(TextAlign.Center)
  13119. }
  13120. .padding({ left: 18, right: 18, top: 16, bottom: 16 })
  13121. .backgroundColor('#A6000000')
  13122. .borderRadius(18)
  13123. .width(this.isPhoneLan() ? 230 : 240)
  13124. }
  13125. .width('100%')
  13126. .height(this.isPhoneLan() ? 260 : 360)
  13127. .align(Alignment.Center)
  13128. .zIndex(10)
  13129. .visibility(this.isShowCoverScaleGuide ? Visibility.Visible : Visibility.None)
  13130. .onClick(() => {
  13131. this.dismissCoverScaleGuide()
  13132. })
  13133. }
  13134. @Builder
  13135. CoverInfo() {
  13136. Column() {
  13137. Stack() {
  13138. Column() {
  13139. //方形封面布局
  13140. if (this.isCoverRectangle) {
  13141. this.RectangleCoverView()
  13142. } else {
  13143. //圆形封面布局
  13144. this.CicleCoverView()
  13145. }
  13146. this.musicNameInfo(false)
  13147. if (this.isPhoneLan()) {
  13148. Text(this.name+"--"+this.artist)
  13149. .fontSize(18)
  13150. .fontWeight(FontWeight.Bold)
  13151. .margin({ top: 13 })
  13152. .textOverflow({ overflow: TextOverflow.Ellipsis })
  13153. .maxLines(1)
  13154. .width('99%')
  13155. .textAlign(TextAlign.Center)
  13156. .fontColor(Color.White)
  13157. }
  13158. }
  13159. .width('100%')
  13160. Column({ space: 8 }) {
  13161. Text(this.name)
  13162. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  13163. .fontWeight(FontWeight.Bold)
  13164. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13165. .maxLines(1)
  13166. .width('85%')
  13167. .textAlign(TextAlign.Center)
  13168. .fontColor(Color.White)
  13169. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13170. Text(this.artist)
  13171. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  13172. .fontColor(Color.White)
  13173. .fontWeight(FontWeight.Bold)
  13174. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13175. }
  13176. .justifyContent(FlexAlign.Start)
  13177. .zIndex(1)
  13178. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  13179. this.CoverScaleGuideOverlay()
  13180. }
  13181. .margin({
  13182. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  13183. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  13184. top: this.isCoverOpacity() ? 0 : 20
  13185. })
  13186. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  13187. this.SingleLyricView()
  13188. }
  13189. if (this.isPhoneLan()) {
  13190. Column() {
  13191. this.playCenterView()
  13192. }
  13193. .position({ left: 28, bottom: 35 })
  13194. } else {
  13195. this.BottomControl()
  13196. }
  13197. }
  13198. .width(CommonConstants.FULL_PERCENT)
  13199. .clip(true)
  13200. }
  13201. //方形封面布局
  13202. @Builder
  13203. RectangleCoverView(){
  13204. Stack({alignContent:Alignment.Center}){
  13205. Image( StrUtil.isNotEmpty(this.cover)?
  13206. this.cover:$r('app.media.alt'))
  13207. .height(this.getRectangleCoverHeight())
  13208. .width(this.getRectangleCoverWidth())
  13209. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13210. .alt($r('app.media.alt'))
  13211. .margin({ right: 8, left: 8, top: 5 })
  13212. .aspectRatio(1)
  13213. .opacity(this.opacityValueImage)
  13214. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13215. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  13216. {
  13217. preview: MenuPreviewMode.IMAGE,
  13218. previewAnimationOptions: { scale: [0.8, 1.0] },
  13219. })
  13220. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  13221. {
  13222. preview: MenuPreviewMode.IMAGE,
  13223. previewAnimationOptions: { scale: [0.8, 1.0] },
  13224. })
  13225. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13226. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13227. .clip(true)
  13228. .animation({
  13229. duration: 1000, // 与 setInterval 同步
  13230. curve: Curve.Linear,
  13231. iterations: 1
  13232. })
  13233. .shadow({
  13234. radius: 22,
  13235. type: ShadowType.BLUR,
  13236. color: 'on_primary'
  13237. })
  13238. .onClick(() => {
  13239. this.isMusicBGCover = !this.isMusicBGCover
  13240. })
  13241. .gesture(PinchGesture({ fingers: 2 })
  13242. .onActionUpdate((event: GestureEvent) => {
  13243. this.updateRectangleCoverScaleByPinch(event.scale)
  13244. })
  13245. .onActionEnd(() => {
  13246. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13247. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13248. }))
  13249. }
  13250. .scale({ x: this.scaleValueImage, y: this.scaleValueImage})
  13251. }
  13252. private getRectangleCoverWidth(): string | number {
  13253. if (this.isHiCar() || this.isCoverOpacity()) {
  13254. return 'auto'
  13255. }
  13256. const baseWidth = this.isBigScreen() ? 72 : this.isCoverTopBig ? 100 : 88
  13257. return `${Math.min(100, Math.max(48, baseWidth * this.rectangleCoverScale))}%`
  13258. }
  13259. private getRectangleCoverHeight(): string | number {
  13260. if (this.isHiCar()) {
  13261. return px2vp(this.windowHeight) * 0.4 * this.rectangleCoverScale
  13262. }
  13263. if (this.isCoverOpacity()) {
  13264. return px2vp(this.windowHeight) * 0.54 * this.rectangleCoverScale
  13265. }
  13266. return 'auto'
  13267. }
  13268. private updateCoverScaleByPinch(scale: number): void {
  13269. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * scale))
  13270. }
  13271. private updateRectangleCoverScaleByPinch(scale: number): void {
  13272. const dampedScale = 1 + (scale - 1) * 0.45
  13273. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * dampedScale))
  13274. }
  13275. private persistCoverScaleAfterPinch(): void {
  13276. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13277. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13278. }
  13279. @Builder
  13280. CicleCoverView() {
  13281. //圆形封面布局
  13282. Stack({alignContent:Alignment.Center}) {
  13283. Image($r('app.media.ic_music_disc'))
  13284. .width(245)
  13285. .height(245)
  13286. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  13287. .aspectRatio(1)
  13288. .opacity(this.isCoverOpacity() ? 0 : 1)
  13289. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  13290. .borderRadius('100%')
  13291. .align(Alignment.Center)
  13292. .clip(true)
  13293. .rotate({
  13294. angle: this.rotateAngle,
  13295. centerX: "50%",
  13296. centerY: "50%",
  13297. })
  13298. .animation({
  13299. duration: 1000, // 改为 1000ms 与 setInterval 同步
  13300. curve: Curve.Linear,
  13301. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  13302. })
  13303. .shadow({
  13304. radius: 22,
  13305. type: ShadowType.BLUR,
  13306. color: 'on_primary'
  13307. })
  13308. Image( StrUtil.isNotEmpty(this.cover)?
  13309. this.cover:$r('app.media.alt'))
  13310. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  13311. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  13312. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13313. .alt($r('app.media.alt'))
  13314. .margin({ right: 20, left: 20,
  13315. top:this.isCoverRectangle||this.isLandscape?0:50})
  13316. .aspectRatio(1)
  13317. .opacity(this.opacityValueImage)
  13318. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13319. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13320. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13321. .align(Alignment.Center)//
  13322. .clip(true)
  13323. .shadow({
  13324. radius: 22,
  13325. type: ShadowType.BLUR,
  13326. color: 'on_primary'
  13327. })
  13328. .rotate({
  13329. x: 0,
  13330. y: 0,
  13331. z: 1,
  13332. angle: this.rotateAngle
  13333. })
  13334. .animation({
  13335. duration: 1000, // 与 setInterval 同步
  13336. curve: Curve.Linear,
  13337. iterations: 1
  13338. })
  13339. .onClick(() => {
  13340. this.isMusicBGCover = !this.isMusicBGCover
  13341. })
  13342. // 唱针以左上角为点选择逆时针40度
  13343. Image($r('app.media.ic_music_cover_hand'))
  13344. .height(130)
  13345. .margin({ bottom: 200, top: 0 })
  13346. // .position({ x: this.windowWidth/2, y: 0 })
  13347. .align(Alignment.Top)
  13348. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  13349. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  13350. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  13351. }
  13352. .scale({ x: this.scaleValueImage * this.rectangleCoverScale, y: this.scaleValueImage * this.rectangleCoverScale,
  13353. centerX: '50%',
  13354. centerY: '50%' })
  13355. .priorityGesture(PinchGesture({ fingers: 2 })
  13356. .onActionStart(() => {
  13357. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13358. })
  13359. .onActionUpdate((event: GestureEvent) => {
  13360. this.updateCoverScaleByPinch(event.scale)
  13361. })
  13362. .onActionEnd(() => {
  13363. this.persistCoverScaleAfterPinch()
  13364. }))
  13365. }
  13366. @Builder
  13367. MenuImageBuilder(cover: string|undefined) {
  13368. Menu(){
  13369. MenuItem({
  13370. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  13371. content: '查看封面'
  13372. })
  13373. .onClick(async() => {
  13374. if (StrUtil.isEmpty(cover)) {
  13375. ToastUtil.showToast('当前没有可用封面')
  13376. return;
  13377. }
  13378. this.getUIContext().getRouter().pushUrl({
  13379. url: 'pages/WallpaperPreviewPage',
  13380. params: {
  13381. imageUri: cover
  13382. }
  13383. })
  13384. })
  13385. MenuItem({
  13386. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  13387. content: '更换封面'
  13388. })
  13389. .onClick(async() => {
  13390. await this.replaceCurrentSongCoverByAlbum();
  13391. })
  13392. }
  13393. }
  13394. @Builder
  13395. private musicNameInfo(isHidden: boolean) {
  13396. Row(){
  13397. Column({ space: 8 }) {
  13398. Text(this.name)
  13399. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  13400. .fontWeight(FontWeight.Bold)
  13401. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13402. .maxLines(1)
  13403. .width('99%')
  13404. .textAlign(TextAlign.Start)
  13405. .fontColor(Color.White)
  13406. Text(this.artist + ' ' + this.currentSong?.album)
  13407. .fontSize(this.isCoverOpacity() ? 12 : 15)
  13408. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13409. .fontColor(Color.White)
  13410. .textAlign(TextAlign.Start)
  13411. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  13412. .width('99%')
  13413. .maxLines(1)
  13414. }
  13415. .zIndex(1)
  13416. .layoutWeight(1)
  13417. .margin({ left: 15 })
  13418. Blank()
  13419. Row(){
  13420. PointLightDefaultButton({
  13421. isSysBol:true,
  13422. pointColor:Color.White,
  13423. imageResource:this.showSimple?
  13424. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  13425. isPx: false,
  13426. builderHeight: 26,
  13427. builderWidth: 26,
  13428. })
  13429. .onClick(async () => {
  13430. this.showSimple = !this.showSimple
  13431. PreferencesUtil.put('showSimple', this.showSimple)
  13432. })
  13433. }
  13434. .margin({ left: 8,right:8 })
  13435. }
  13436. .width(this.isLandscape?'83%':'90%')
  13437. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  13438. .opacity(this.playDragUiOpacity)
  13439. .margin({ top:this.isCoverRectangle?15: 0 })
  13440. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  13441. }
  13442. @Builder
  13443. private PlayTitle() {
  13444. Row() {
  13445. Row() {
  13446. PointLightDefaultButton({
  13447. isSysBol: true,
  13448. pointColor: Color.White,
  13449. imageResource: $r('sys.symbol.chevron_down'),
  13450. isPx: false,
  13451. builderHeight: 26,
  13452. builderWidth: 26,
  13453. })
  13454. .onClick(() => {
  13455. this.setShowPlayFalse()
  13456. })
  13457. }
  13458. .width('100%')
  13459. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  13460. }
  13461. .width(PlayConstants.ROW_WIDTH)
  13462. }
  13463. @Builder
  13464. lyricSettingSheet(isPip: boolean) {
  13465. Scroll() {
  13466. this.lyricSetting(isPip)
  13467. }
  13468. .width('100%')
  13469. .height('100%')
  13470. }
  13471. @Builder
  13472. lyricSetting(isPip: boolean) {
  13473. Column() {
  13474. // 时间调节模块
  13475. if (!isPip) {
  13476. this.BuildTimeControls()
  13477. }
  13478. // 字号控制模块
  13479. this.BuildFontControls(isPip)
  13480. }
  13481. }
  13482. // 歌词时间偏移状态
  13483. @State timeOffset: number = 0.0
  13484. @State currentLyricColor: string = '#FFFFFF'
  13485. @State currentLyricColorPip: string = '#FFFFFF'
  13486. @State currentHighLightLyricColor: string = '#FF4081'
  13487. @State currentHighLightLyricColorPip: string = '#FF4081'
  13488. // 歌词字号状态
  13489. @State currentLyricSize: number = 20
  13490. @State currentLyricSizePip: number = 20
  13491. // 高亮歌词放大倍数
  13492. @State currentHightLyricSize: number = 1.2
  13493. @State currentHightLyricSizePip: number = 1.2
  13494. @State currentLyricLineSpace: number = 10
  13495. @State currentLyricLineSpacePip: number = 10
  13496. @State currentLyricAlignMode: number = 1
  13497. @State currentLyricAlignModePip: number = 1
  13498. @State blurDegree: number = 2
  13499. @State blurDegreePip: number = 2
  13500. @State isShowSelectColor: boolean = false
  13501. @State isShowHLSelectColor: boolean = false
  13502. @State isShowPipBgSelectColor: boolean = false
  13503. @State pipLyWidth: number = 330
  13504. @State pipLyHeight: number = 120
  13505. // 构建颜色选择器
  13506. @Builder
  13507. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  13508. Row({ space: 10 }) {
  13509. HSBColorPicker({
  13510. color: '#FFFFFF',
  13511. radius: 8,
  13512. layout: HSBColorPickerLayout.COLUMN,
  13513. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  13514. '#fa7105'],
  13515. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  13516. this.changeLyricColor(value, isPip, isBGPip)
  13517. })
  13518. .height(250)
  13519. .layoutWeight(1)
  13520. .padding(25)
  13521. }
  13522. .width('66%')
  13523. }
  13524. @State isOpenPip: boolean = false
  13525. @State pipBgIndex: number = 0
  13526. // 构建字号控制器
  13527. @Builder
  13528. BuildFontControls(isPip: boolean) {
  13529. Column() {
  13530. if (isPip) {
  13531. Column() {
  13532. Row() {
  13533. Text('悬浮歌词')
  13534. .margin({ left: 18 })
  13535. .fontSize(15)
  13536. .fontColor(Color.White)
  13537. .fontWeight(480)
  13538. .layoutWeight(1)
  13539. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  13540. .selectedColor(this.themeColor)
  13541. .switchPointColor(Color.White)
  13542. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13543. .margin({ right: 18 })
  13544. .onChange((checked: boolean) => {
  13545. this.isOpenPip = checked;
  13546. if (this.isOpenPip) {
  13547. this.startPip()
  13548. } else {
  13549. this.stopPip()
  13550. }
  13551. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  13552. })
  13553. .width(50)
  13554. .height(30);
  13555. }
  13556. .height(55)
  13557. }
  13558. .backgroundColor(Color.Transparent)
  13559. .borderRadius(15)
  13560. .margin({
  13561. left: 30,
  13562. right: 30,
  13563. top: 0,
  13564. bottom: 20
  13565. })
  13566. .padding(0)
  13567. .border({
  13568. color: Color.White,
  13569. width: 1.8
  13570. })
  13571. }else{
  13572. Row() {
  13573. Row() {
  13574. Text(`迷你歌词:`)
  13575. .fontSize(14)
  13576. .fontColor(Color.White)
  13577. .width(88)
  13578. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  13579. .selectedColor(this.themeColor)
  13580. .switchPointColor(Color.White)
  13581. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13582. .onChange((checked: boolean) => {
  13583. this.isShowSingleLineLyric = checked;
  13584. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  13585. })
  13586. .width(50)
  13587. .height(30)
  13588. .alignSelf(ItemAlign.Start)
  13589. .margin({ left: 12 })
  13590. Blank()
  13591. }
  13592. .layoutWeight(1)
  13593. Row() {
  13594. Text(`逐字歌词:`)
  13595. .fontSize(14)
  13596. .fontColor(Color.White)
  13597. .width(88)
  13598. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  13599. .selectedColor(this.themeColor)
  13600. .switchPointColor(Color.White)
  13601. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13602. .onChange((checked: boolean) => {
  13603. this.isEnableWordByWordLyric = checked;
  13604. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  13605. this.syncWordByWordLyricMode()
  13606. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13607. })
  13608. .width(50)
  13609. .height(30)
  13610. .alignSelf(ItemAlign.Start)
  13611. .margin({ left: 12 })
  13612. Blank()
  13613. }
  13614. .layoutWeight(1)
  13615. }
  13616. .width('100%')
  13617. .margin({
  13618. left: 20,
  13619. right: 15,
  13620. top: 10,
  13621. bottom: 10
  13622. })
  13623. }
  13624. if (!isPip) {
  13625. Row() {
  13626. Row() {
  13627. Text(`歌词发光:`)
  13628. .fontSize(14)
  13629. .fontColor(Color.White)
  13630. .width(88)
  13631. Toggle({ type: ToggleType.Switch, isOn: this.isLightText })
  13632. .selectedColor(this.themeColor)
  13633. .switchPointColor(Color.White)
  13634. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13635. .onChange((checked: boolean) => {
  13636. this.isLightText = checked;
  13637. PreferencesUtil.putSync(SettingPage.IS_LIGHT_TEXT, this.isLightText)
  13638. this.syncLyricLightTextMode()
  13639. })
  13640. .width(50)
  13641. .height(30)
  13642. .alignSelf(ItemAlign.Start)
  13643. .margin({ left: 12 })
  13644. Blank()
  13645. }
  13646. .layoutWeight(1)
  13647. Row() {
  13648. Text(`高亮居中:`)
  13649. .fontSize(14)
  13650. .fontColor(Color.White)
  13651. .width(88)
  13652. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  13653. .selectedColor(this.themeColor)
  13654. .switchPointColor(Color.White)
  13655. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13656. .onChange((checked: boolean) => {
  13657. this.isHightLightCenter = checked;
  13658. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  13659. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  13660. })
  13661. .width(50)
  13662. .height(30)
  13663. .alignSelf(ItemAlign.Start)
  13664. .margin({ left: 12 })
  13665. Blank()
  13666. }
  13667. .layoutWeight(1)
  13668. }
  13669. .width('100%')
  13670. .margin({
  13671. left: 20,
  13672. right: 15,
  13673. top: 10,
  13674. bottom: 10
  13675. })
  13676. }
  13677. Row() {
  13678. Text(`歌词居中:`)
  13679. .fontSize(14)
  13680. .fontColor(Color.White)
  13681. Row() {
  13682. ForEach(['居中', '居左'], (size: string, index: number) => {
  13683. Button(size)
  13684. .width(60)
  13685. .height(28)
  13686. .fontSize(12)
  13687. .fontColor('#FFFFFF')
  13688. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  13689. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  13690. .border({
  13691. color: (!isPip && this.currentLyricAlignMode === index) ||
  13692. (isPip && this.currentLyricAlignModePip === index) ?
  13693. '#007DFF' : '#DDDDDD',
  13694. width: 1.8
  13695. })
  13696. .onClick(() => {
  13697. this.setLyricAlignMode(index, isPip)
  13698. })
  13699. .margin({ left: 10, right: 8 })
  13700. })
  13701. }
  13702. .layoutWeight(1)
  13703. Blank()
  13704. }
  13705. .width('100%')
  13706. .margin({
  13707. top: 10,
  13708. bottom: 10,
  13709. right: 15,
  13710. left: 20
  13711. })
  13712. if (isPip) {
  13713. Row() {
  13714. Text(`悬浮背景:`)
  13715. .fontSize(14)
  13716. .fontColor(Color.White)
  13717. Select([
  13718. { value: CommonConstants.PIP_LYRIC_BG[0] },
  13719. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  13720. .font({ size: 13, weight: FontWeight.Medium })
  13721. .fontColor(Color.White)
  13722. .margin({ left: 10 })
  13723. .selected(this.pipBgIndex)
  13724. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  13725. .onSelect(async (_index: number, text?: string | undefined) => {
  13726. this.pipBgIndex = _index
  13727. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  13728. if (this.pipBgIndex === 0) {
  13729. if (this.cover) {
  13730. this.pipBg = this.cover
  13731. } else {
  13732. this.pipBg = this.imageColor
  13733. }
  13734. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13735. } else {
  13736. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  13737. }
  13738. })
  13739. Column() {
  13740. }
  13741. .backgroundColor(this.pipBg)
  13742. .margin({ left: 10, right: 10 })
  13743. .borderRadius(20)
  13744. .height(28)
  13745. .width(28)
  13746. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13747. Row() {
  13748. SymbolGlyph($r('sys.symbol.paintbrush'))
  13749. .fontColor([Color.White])
  13750. .effectStrategy(1)
  13751. Text(`选择颜色`)
  13752. .fontSize(13)
  13753. .margin({ left: 10 })
  13754. .fontColor(Color.White)
  13755. }
  13756. }
  13757. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  13758. .backgroundColor(Color.Transparent)
  13759. .border({
  13760. color: '#FFFFFF',
  13761. radius: 20,
  13762. width: 1.8
  13763. })
  13764. .height(36)
  13765. .width(110)
  13766. .onClick(() => {
  13767. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  13768. })
  13769. .bindPopup(this.isShowPipBgSelectColor, {
  13770. builder: this.SelectColor(false, isPip, true),
  13771. placement: Placement.Top,
  13772. mask: { color: '#33000000' },
  13773. enableArrow: false, //是否显示箭头
  13774. showInSubWindow: false,
  13775. onStateChange: (e) => {
  13776. if (!e.isVisible) {
  13777. this.isShowPipBgSelectColor = false
  13778. }
  13779. }
  13780. })
  13781. }
  13782. .width('100%')
  13783. .margin({ bottom: 5, right: 15, left: 20 })
  13784. }
  13785. Row() {
  13786. Text(`歌词颜色:`)
  13787. .fontSize(14)
  13788. .fontColor(Color.White)
  13789. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13790. .fontSize(15)
  13791. .fontColor(Color.White)
  13792. .margin({ left: 6, right: 6 })
  13793. Column() {
  13794. }
  13795. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13796. .margin({ right: 12 })
  13797. .borderRadius(20)
  13798. .height(28)
  13799. .width(28)
  13800. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13801. Row() {
  13802. SymbolGlyph($r('sys.symbol.paintbrush'))
  13803. .fontColor([Color.White])
  13804. .effectStrategy(1)
  13805. Text(`选择颜色`)
  13806. .fontSize(13)
  13807. .margin({ left: 10 })
  13808. .fontColor(Color.White)
  13809. }
  13810. }
  13811. .backgroundColor(Color.Transparent)
  13812. .border({
  13813. color: '#FFFFFF',
  13814. radius: 20,
  13815. width: 1.8
  13816. })
  13817. .height(36)
  13818. .width(110)
  13819. .onClick(() => {
  13820. this.isShowSelectColor = !this.isShowSelectColor
  13821. })
  13822. .bindPopup(this.isShowSelectColor, {
  13823. builder: this.SelectColor(false, isPip),
  13824. placement: Placement.Top,
  13825. mask: { color: '#33000000' },
  13826. enableArrow: false, //是否显示箭头
  13827. showInSubWindow: false,
  13828. onStateChange: (e) => {
  13829. if (!e.isVisible) {
  13830. this.isShowSelectColor = false
  13831. }
  13832. }
  13833. })
  13834. }
  13835. .width('100%')
  13836. .margin({
  13837. top: 10,
  13838. bottom: 10,
  13839. right: 15,
  13840. left: 20
  13841. })
  13842. Row() {
  13843. Text(`高亮颜色:`)
  13844. .fontSize(14)
  13845. .fontColor(Color.White)
  13846. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13847. .fontSize(15)
  13848. .fontColor(Color.White)
  13849. .margin({ left: 6, right: 6 })
  13850. Column() {
  13851. }
  13852. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13853. .margin({ right: 12 })
  13854. .borderRadius(20)
  13855. .height(28)
  13856. .width(28)
  13857. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13858. Row() {
  13859. SymbolGlyph($r('sys.symbol.paintbrush'))
  13860. .fontColor([Color.White])
  13861. .effectStrategy(1)
  13862. Text(`选择颜色`)
  13863. .fontSize(13)
  13864. .margin({ left: 10 })
  13865. .fontColor(Color.White)
  13866. }
  13867. }
  13868. .backgroundColor(Color.Transparent)
  13869. .border({
  13870. color: '#FFFFFF',
  13871. radius: 20,
  13872. width: 1.8
  13873. })
  13874. .height(36)
  13875. .width(110)
  13876. .onClick(() => {
  13877. this.isShowHLSelectColor = !this.isShowHLSelectColor
  13878. })
  13879. .bindPopup(this.isShowHLSelectColor, {
  13880. builder: this.SelectColor(true, isPip),
  13881. placement: Placement.Top,
  13882. mask: { color: '#33000000' },
  13883. enableArrow: false, //是否显示箭头
  13884. showInSubWindow: false,
  13885. onStateChange: (e) => {
  13886. if (!e.isVisible) {
  13887. this.isShowHLSelectColor = false
  13888. }
  13889. }
  13890. })
  13891. }
  13892. .width('100%')
  13893. .margin({
  13894. top: 10,
  13895. bottom: 10,
  13896. right: 15,
  13897. left: 20
  13898. })
  13899. if (isPip) {
  13900. Row() {
  13901. Text(`显示宽度:`)
  13902. .fontSize(14)
  13903. .fontColor(Color.White)
  13904. Slider({
  13905. value: this.pipLyWidth,
  13906. min: 10,
  13907. max: 800,
  13908. step: 1,
  13909. style: SliderStyle.OutSet
  13910. })
  13911. .blockColor(this.themeColor)
  13912. .trackColor($r('app.color.speed_text_color'))
  13913. .selectedColor(Color.White)
  13914. .trackThickness(6)
  13915. .onChange((value: number) => {
  13916. this.pipLyWidth = value
  13917. if (this.pipController) {
  13918. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13919. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  13920. }
  13921. })
  13922. .layoutWeight(1)
  13923. }
  13924. .justifyContent(FlexAlign.Start)
  13925. .margin({
  13926. left: 20,
  13927. right: 15,
  13928. top: 5,
  13929. bottom: 5
  13930. })
  13931. Row() {
  13932. Text(`显示高度:`)
  13933. .fontSize(14)
  13934. .fontColor(Color.White)
  13935. Slider({
  13936. value: this.pipLyHeight,
  13937. min: 10,
  13938. max: 1000,
  13939. step: 1,
  13940. style: SliderStyle.OutSet
  13941. })
  13942. .blockColor(this.themeColor)
  13943. .trackColor($r('app.color.speed_text_color'))
  13944. .selectedColor(Color.White)
  13945. .trackThickness(6)
  13946. .onChange((value: number) => {
  13947. this.pipLyHeight = value
  13948. if (this.pipController) {
  13949. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13950. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  13951. }
  13952. })
  13953. .layoutWeight(1)
  13954. }
  13955. .justifyContent(FlexAlign.Start)
  13956. .margin({
  13957. left: 20,
  13958. right: 15,
  13959. top: 5,
  13960. bottom: 5
  13961. })
  13962. }
  13963. Row() {
  13964. Text(`歌词字号:`)
  13965. .fontSize(14)
  13966. .fontColor(Color.White)
  13967. Slider({
  13968. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  13969. min: 12,
  13970. max: 30,
  13971. step: 0.1,
  13972. style: SliderStyle.OutSet
  13973. })
  13974. .blockColor(this.themeColor)
  13975. .trackColor($r('app.color.speed_text_color'))
  13976. .selectedColor(Color.White)
  13977. .trackThickness(6)
  13978. .onChange((value: number) => {
  13979. this.setLyricTextSize(value, isPip)
  13980. })
  13981. .layoutWeight(1)
  13982. .margin({ right: 3 })
  13983. Text(this.getLyricSizeDisplayValue(isPip))
  13984. .fontSize(13)
  13985. .fontColor(Color.White)
  13986. .textAlign(TextAlign.Start)
  13987. }
  13988. .width('100%')
  13989. .margin({
  13990. left: 20,
  13991. right: 15,
  13992. top: 5,
  13993. bottom: 5
  13994. })
  13995. Row() {
  13996. Text(`高亮倍数:`)
  13997. .fontSize(14)
  13998. .fontColor(Color.White)
  13999. Slider({
  14000. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  14001. min: 1,
  14002. max: 2,
  14003. step: 0.1,
  14004. style: SliderStyle.OutSet
  14005. })
  14006. .blockColor(this.themeColor)
  14007. .trackColor($r('app.color.speed_text_color'))
  14008. .selectedColor(Color.White)
  14009. .trackThickness(6)
  14010. .onChange((value: number) => {
  14011. this.setHighLyricTextSize(value, isPip)
  14012. })
  14013. .layoutWeight(1)
  14014. .margin({ right: 3 })
  14015. Text(this.getHighLyricSizeDisplayValue(isPip))
  14016. .fontSize(13)
  14017. .fontColor(Color.White)
  14018. .textAlign(TextAlign.Start)
  14019. }
  14020. .width('100%')
  14021. .margin({
  14022. left: 20,
  14023. right: 15,
  14024. top: 5,
  14025. bottom: 5
  14026. })
  14027. Row() {
  14028. Text(`歌词间隙:`)
  14029. .fontSize(14)
  14030. .fontColor(Color.White)
  14031. Slider({
  14032. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  14033. min: 0,
  14034. max: 100,
  14035. step: 1,
  14036. style: SliderStyle.OutSet
  14037. })
  14038. .blockColor(this.themeColor)
  14039. .trackColor($r('app.color.speed_text_color'))
  14040. .selectedColor(Color.White)
  14041. .trackThickness(6)
  14042. .onChange((value: number) => {
  14043. this.setLyricLineSpace(value, isPip)
  14044. })
  14045. .layoutWeight(1)
  14046. .margin({ right: 3 })
  14047. Text(this.getLyricLineSpaceDisplayValue(isPip))
  14048. .fontSize(13)
  14049. .fontColor(Color.White)
  14050. .textAlign(TextAlign.Start)
  14051. }
  14052. .width('100%')
  14053. .margin({
  14054. left: 20,
  14055. right: 15,
  14056. top: 5,
  14057. bottom: 5
  14058. })
  14059. //取值间隔为100,默认为400,取值越大,字体越粗
  14060. Row() {
  14061. Text(`歌词字重:`)
  14062. .fontSize(14)
  14063. .fontColor(Color.White)
  14064. Slider({
  14065. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  14066. min: 100,
  14067. max: 900,
  14068. step: 100,
  14069. style: SliderStyle.OutSet
  14070. })
  14071. .blockColor(this.themeColor)
  14072. .trackColor($r('app.color.speed_text_color'))
  14073. .selectedColor(Color.White)
  14074. .trackThickness(6)
  14075. .onChange((value: number) => {
  14076. if (isPip) {
  14077. this.lyricTextWeightPip = value
  14078. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  14079. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  14080. } else {
  14081. this.lyricTextWeight = value
  14082. this.lyricController.setTextWeight(this.lyricTextWeight)
  14083. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  14084. }
  14085. })
  14086. .layoutWeight(1)
  14087. .margin({ right: 3 })
  14088. Text(this.getLyricTextWeightDisplayValue(isPip))
  14089. .fontSize(13)
  14090. .fontColor(Color.White)
  14091. .textAlign(TextAlign.Start)
  14092. }
  14093. .width('100%')
  14094. .margin({
  14095. left: 20,
  14096. right: 15,
  14097. top: 5,
  14098. bottom: 5
  14099. })
  14100. Row() {
  14101. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  14102. this.pushLyricButton($r('app.media.share2'), 2, '分享歌词')
  14103. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  14104. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  14105. }
  14106. .justifyContent(FlexAlign.Center)
  14107. .margin({ top: 3, bottom: 10 })
  14108. }
  14109. .width('88%')
  14110. }
  14111. private getLyricSizeDisplayValue(isPip: boolean): string {
  14112. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  14113. return lyricSize.toFixed(1);
  14114. }
  14115. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  14116. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  14117. return highLyricSize.toFixed(1);
  14118. }
  14119. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  14120. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  14121. return Math.round(lyricLineSpace).toString();
  14122. }
  14123. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  14124. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  14125. return Math.round(lyricTextWeightValue).toString();
  14126. }
  14127. private setBlurDegree(index: number, isPip: boolean) {
  14128. if (isPip) {
  14129. this.blurDegreePip = index
  14130. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  14131. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  14132. } else {
  14133. this.blurDegree = index
  14134. this.lyricController.setBlurDegree(this.blurDegree)
  14135. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  14136. }
  14137. }
  14138. private setLyricAlignMode(index: number, isPip: boolean) {
  14139. if (isPip) {
  14140. this.currentLyricAlignModePip = index
  14141. if (this.currentLyricAlignModePip === 1) {
  14142. this.lyricControllerXF.setAlignMode("left")
  14143. } else {
  14144. this.lyricControllerXF.setAlignMode("center")
  14145. }
  14146. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  14147. } else {
  14148. this.currentLyricAlignMode = index
  14149. if (this.currentLyricAlignMode === 1) {
  14150. this.lyricController.setAlignMode("left")
  14151. } else {
  14152. this.lyricController.setAlignMode("center")
  14153. }
  14154. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  14155. }
  14156. }
  14157. private setLyricTextSize(index: number, isPip: boolean) {
  14158. if (isPip) {
  14159. this.currentLyricSizePip = index
  14160. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  14161. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  14162. } else {
  14163. this.currentLyricSize = index
  14164. this.lyricController.setTextSize(this.currentLyricSize)
  14165. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  14166. }
  14167. }
  14168. private setHighLyricTextSize(scale: number, isPip: boolean) {
  14169. if (isPip) {
  14170. this.currentHightLyricSizePip = scale
  14171. this.lyricControllerXF
  14172. .setHighlightScale(this.currentHightLyricSizePip)
  14173. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  14174. } else {
  14175. this.currentHightLyricSize = scale
  14176. this.lyricController
  14177. .setHighlightScale(this.currentHightLyricSize)
  14178. PreferencesUtil.putSync('HighLyricTextSize', scale)
  14179. }
  14180. }
  14181. private setLyricLineSpace(index: number, isPip: boolean) {
  14182. if (isPip) {
  14183. this.currentLyricLineSpacePip = index
  14184. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  14185. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  14186. } else {
  14187. this.currentLyricLineSpace = index
  14188. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  14189. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  14190. }
  14191. }
  14192. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  14193. LogUtil.info('onecold isBG = ' + isBG)
  14194. if (isBG) { //如果是设置悬浮背景
  14195. this.pipBg = color
  14196. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  14197. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  14198. return
  14199. }
  14200. if (isPip) {
  14201. this.currentLyricColorPip = color
  14202. this.lyricControllerXF
  14203. .setTextColor(this.currentLyricColorPip)
  14204. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  14205. } else {
  14206. this.currentLyricColor = color
  14207. this.lyricController
  14208. .setTextColor(this.currentLyricColor)
  14209. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  14210. }
  14211. }
  14212. private changeLyricHightLightColor(color: string, isPip: boolean) {
  14213. if (isPip) {
  14214. this.currentHighLightLyricColorPip = color
  14215. this.lyricControllerXF
  14216. .setHighlightColor(this.currentHighLightLyricColorPip)
  14217. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  14218. } else {
  14219. this.currentHighLightLyricColor = color
  14220. this.lyricController
  14221. .setHighlightColor(this.currentHighLightLyricColor)
  14222. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  14223. }
  14224. }
  14225. // 构建时间控制器
  14226. @Builder
  14227. BuildTimeControls() {
  14228. Column() {
  14229. // 时间显示
  14230. Text(this.getTimeText())
  14231. .fontSize(18)
  14232. .fontColor(Color.White)
  14233. .margin({ bottom: 10 })
  14234. Row() {
  14235. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  14236. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  14237. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  14238. }
  14239. .justifyContent(FlexAlign.Center)
  14240. }
  14241. .margin({ top: 12, bottom: 8 })
  14242. }
  14243. // 精度按钮组件
  14244. @Builder
  14245. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  14246. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14247. Column() {
  14248. Image(icon)
  14249. .width(28)
  14250. .margin({ bottom: 5 })
  14251. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  14252. Text(label)
  14253. .fontSize(12)
  14254. .fontColor('#FFFFFF')
  14255. }
  14256. }
  14257. .backgroundColor(Color.Transparent)
  14258. .enabled(!this.isButtonDisabled(step))
  14259. .onClick(() => this.handlePrecisionAdjust(step))
  14260. .padding(5)
  14261. .width(66)
  14262. .height(66)
  14263. .margin({ left: 18, right: 18 })
  14264. .border({
  14265. color: '#FFFFFF',
  14266. width: 1.8
  14267. })
  14268. }
  14269. private handlePrecisionAdjust(step: number) {
  14270. if (step === 0) {
  14271. this.timeOffset = 0
  14272. this.saveLyricTimeOffset()
  14273. return
  14274. }
  14275. // 精度处理:保留1位小数
  14276. const newOffset = Number((this.timeOffset + step).toFixed(5))
  14277. // 边界保护(±15.0秒)
  14278. if (newOffset < -30.0 || newOffset > 30.0) {
  14279. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  14280. return
  14281. }
  14282. // 状态更新
  14283. this.timeOffset = newOffset
  14284. // 保存歌词时间偏移
  14285. this.saveLyricTimeOffset()
  14286. }
  14287. // 按钮禁用逻辑
  14288. private isButtonDisabled(step: number): boolean {
  14289. const futureOffset = this.timeOffset + step
  14290. return (futureOffset < -30.0) || (futureOffset > 30.0)
  14291. }
  14292. // 时间显示文本升级
  14293. private getTimeText(): string {
  14294. const absValue = Math.abs(this.timeOffset)
  14295. return this.timeOffset === 0
  14296. ? '歌词时间已重置'
  14297. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  14298. }
  14299. /**
  14300. * 获取当前歌曲的唯一标识key
  14301. * 使用歌曲的filePath作为唯一标识
  14302. */
  14303. private getLyricOffsetKey(): string {
  14304. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  14305. // 使用MD5对filePath进行加密,作为存储key
  14306. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  14307. }
  14308. return ''
  14309. }
  14310. /**
  14311. * 保存当前歌曲的歌词时间偏移
  14312. */
  14313. private saveLyricTimeOffset(): void {
  14314. try {
  14315. const key = this.getLyricOffsetKey()
  14316. if (StrUtil.isEmpty(key)) {
  14317. console.warn('heanup saveLyricTimeOffset: key is empty')
  14318. return
  14319. }
  14320. PreferencesUtil.putSync(key, this.timeOffset)
  14321. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  14322. } catch (e) {
  14323. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  14324. }
  14325. }
  14326. /**
  14327. * 加载当前歌曲的歌词时间偏移
  14328. */
  14329. private loadLyricTimeOffset(): void {
  14330. try {
  14331. const key = this.getLyricOffsetKey()
  14332. if (StrUtil.isEmpty(key)) {
  14333. console.warn('heanup loadLyricTimeOffset: key is empty')
  14334. return
  14335. }
  14336. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  14337. if (savedOffset !== 0) {
  14338. this.timeOffset = savedOffset
  14339. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  14340. }else{
  14341. this.timeOffset = 0
  14342. }
  14343. } catch (e) {
  14344. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  14345. }
  14346. }
  14347. // 导入 本地歌词 搜索歌词
  14348. @Builder
  14349. pushLyricButton(icon: Resource, step: number, label: string) {
  14350. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14351. Row() {
  14352. Image(icon)
  14353. .width(14)
  14354. .margin({ left: 13 })
  14355. Text(label)
  14356. .fontSize(12)
  14357. .margin({ left: 6 })
  14358. .fontColor('#FFFFFF')
  14359. }
  14360. }
  14361. .onClick(() => {
  14362. switch (step) {
  14363. case 0:
  14364. this.callFilePickerSelectFileForLyric()
  14365. break;
  14366. case 1:
  14367. //判断有没有设置api
  14368. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  14369. this.isLyricSetting = false
  14370. this.showTipsDialog()
  14371. return
  14372. }
  14373. if (StrUtil.isNotEmpty(this.videoUrl)) {
  14374. ToastUtil.showToast('正在获取')
  14375. this.isLyricSetting = false
  14376. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  14377. this.initLyric(lyricPath, true);
  14378. }
  14379. break;
  14380. case 2:
  14381. this.isLyricSetting = false
  14382. this.openLyricCopySheet()
  14383. break;
  14384. }
  14385. })
  14386. .padding(5)
  14387. .layoutWeight(1)
  14388. .backgroundColor(Color.Transparent)
  14389. .height(40)
  14390. .margin({ left: 4, right: 4 })
  14391. .border({
  14392. color: '#FFFFFF',
  14393. radius: 20,
  14394. width: 1.8
  14395. })
  14396. }
  14397. showVipDialog() {
  14398. DialogHelper.showCustomContentDialog({
  14399. dialogId: 'vip',
  14400. title: "友情提示",
  14401. autoCancel: false, //点击遮障层时,不关闭弹窗
  14402. backCancel: true, //点击返回键,不关闭弹窗
  14403. contentBuilder: () => {
  14404. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  14405. },
  14406. buttons: [],
  14407. })
  14408. }
  14409. //去赞助的自定义内容
  14410. @Builder
  14411. customVipBuilder(content: string) {
  14412. Column() {
  14413. Text(content)
  14414. .fontColor(Color.Gray)
  14415. .fontSize(16)
  14416. .alignSelf(ItemAlign.Start)
  14417. .margin({ bottom: 15 })
  14418. .fontSize(16)
  14419. Row() {
  14420. Button('取消')
  14421. .fontColor(Color.White)
  14422. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14423. .height(50)
  14424. .layoutWeight(1)
  14425. .stateEffect(true)
  14426. .margin({ right: 6 })
  14427. .onClick(() => {
  14428. DialogHelper.closeDialog('vip'); //关闭弹框
  14429. })
  14430. Button('开通')
  14431. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14432. .layoutWeight(1)
  14433. .height(50)
  14434. .backgroundColor(this.themeColor)
  14435. .stateEffect(true)
  14436. .margin({ left: 6 })
  14437. .onClick(() => {
  14438. DialogHelper.closeDialog('vip'); //关闭弹框
  14439. this.isShowPlay = false
  14440. this.mType = 1 //跳转到用户中心
  14441. // router.pushUrl({
  14442. // url: 'pages/VipPage'
  14443. // }, router.RouterMode.Single);
  14444. })
  14445. }
  14446. }
  14447. .width("100%")
  14448. .padding(10)
  14449. }
  14450. showTipsDialog() {
  14451. DialogHelper.showCustomContentDialog({
  14452. dialogId: 'tips',
  14453. title: "友情提示",
  14454. autoCancel: false, //点击遮障层时,不关闭弹窗
  14455. backCancel: true, //点击返回键,不关闭弹窗
  14456. contentBuilder: () => {
  14457. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  14458. },
  14459. buttons: [],
  14460. })
  14461. }
  14462. @Builder
  14463. customTipsBuilder(content: string) {
  14464. Column() {
  14465. Text(content)
  14466. .fontColor(Color.Gray)
  14467. .fontSize(16)
  14468. .alignSelf(ItemAlign.Start)
  14469. .margin({ bottom: 15 })
  14470. .fontSize(16)
  14471. Row() {
  14472. Button('取消')
  14473. .fontColor(Color.White)
  14474. .backgroundColor(this.themeColor)
  14475. .height(50)
  14476. .layoutWeight(1)
  14477. .stateEffect(true)
  14478. .margin({ right: 6 })
  14479. .onClick(() => {
  14480. DialogHelper.closeDialog('tips'); //关闭弹框
  14481. })
  14482. Button('跳转')
  14483. .fontColor(Color.White)//
  14484. .layoutWeight(1)
  14485. .height(50)
  14486. .backgroundColor(this.themeColor)
  14487. .stateEffect(true)
  14488. .margin({ left: 6 })
  14489. .onClick(() => {
  14490. DialogHelper.closeDialog('tips'); //关闭弹框
  14491. this.isShowEdit = false
  14492. this.longItemFilePath = ''
  14493. // if(this.isGridMusic&&!this.isShowPlay){
  14494. // this.longItemFilePath== ''
  14495. // }else{
  14496. // this.isShowEdit = false
  14497. // }
  14498. this.isShowMoreView = false;
  14499. this.isShowPlay = false
  14500. this.mType = 4
  14501. // router.pushUrl({
  14502. // url: 'pages/SettingPage'
  14503. // }, router.RouterMode.Single);
  14504. })
  14505. }
  14506. }
  14507. .width("100%")
  14508. .padding(10)
  14509. }
  14510. @Builder
  14511. PlayMoreSheet() {
  14512. Column() {
  14513. this.MoreList()
  14514. }
  14515. .width('100%')
  14516. .height('100%')
  14517. }
  14518. @Builder
  14519. MoreList() {
  14520. Scroll() {
  14521. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  14522. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  14523. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14524. Row() {
  14525. if (more.id === 3&&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. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  14534. height: '99%',
  14535. dragBar: true,
  14536. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14537. showClose: true,
  14538. blurStyle: BlurStyle.Thin,
  14539. backgroundColor: Color.Transparent,
  14540. title: { title: '歌曲信息' }
  14541. })
  14542. } else if (more.id === 15 && this.currentSong) { //编辑标签
  14543. Image(more.image)
  14544. .width(24)
  14545. .height(24)
  14546. .margin({ left: 10, right: 10 })
  14547. Text(more.title)
  14548. .fontSize(16)
  14549. .fontColor(Color.White)
  14550. } else if (more.id === 5) { //定时关闭
  14551. Image(more.image)
  14552. .width(24)
  14553. .height(24)
  14554. .margin({ left: 10, right: 10 })
  14555. Text(more.title)
  14556. .fontSize(16)
  14557. .fontColor(Color.White)
  14558. .onClick(() => {
  14559. this.doMore(more.id)
  14560. })
  14561. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  14562. height: this.isCoverOpacity() ? '95%' : '95%',
  14563. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14564. dragBar: true,
  14565. showClose: true,
  14566. title: { title: $r('app.string.time_close') }
  14567. })
  14568. } else if (more.id === 2) { //歌词设置
  14569. Image(more.image)
  14570. .width(24)
  14571. .height(24)
  14572. .margin({ left: 10, right: 10 })
  14573. Text(more.title)
  14574. .fontSize(16)
  14575. .fontColor(Color.White)
  14576. } else if (more.id === 16) { //悬浮歌词设置
  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.showPipLyric, this.lyricSettingSheet(true), {
  14585. height: '99%',
  14586. dragBar: true,
  14587. preferType: SheetType.CENTER,
  14588. showClose: true,
  14589. blurStyle: BlurStyle.Thin,
  14590. backgroundColor: Color.Transparent,
  14591. title: { title: '悬浮歌词' }
  14592. })
  14593. } else if (more.id === 11) {
  14594. Image(more.image)
  14595. .width(24)
  14596. .height(24)
  14597. .margin({ left: 10, right: 10 })
  14598. Text(more.title)
  14599. .fontSize(16)
  14600. .fontColor(Color.White)
  14601. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  14602. height: this.isCoverOpacity() ? '95%' : '60%',
  14603. dragBar: true,
  14604. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14605. showClose: true,
  14606. blurStyle: BlurStyle.Thin,
  14607. backgroundColor: Color.Transparent,
  14608. title: { title: '跳过头尾' }
  14609. })
  14610. } else if (more.id === 12) { //投播
  14611. AVCastPicker({
  14612. customPicker: (): void => this.TPImageBuilder(more),
  14613. onStateChange: (state) => {
  14614. if (state == AVCastPickerState.STATE_APPEARING) {
  14615. console.log(' The picker starts showing.');
  14616. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14617. console.log(' The picker finishes presenting.');
  14618. }
  14619. },
  14620. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  14621. sessionType: 'video'
  14622. })
  14623. .id('AVCastPicker')
  14624. } else {
  14625. if(more.id >= 22){
  14626. SymbolGlyph(more.image)
  14627. .fontSize(24)
  14628. .fontColor([Color.White])
  14629. .alignSelf(ItemAlign.Center)
  14630. .margin({ left: 10, right: 10,bottom:5})
  14631. // .padding({bottom:4})
  14632. .onClick(() => {
  14633. this.doMore(more.id)
  14634. })
  14635. }else{
  14636. Image(more.image)
  14637. .width(24)
  14638. .height(24)
  14639. .fillColor(Color.White)
  14640. .margin({ left: 10, right: 10 })
  14641. .onClick(() => {
  14642. this.doMore(more.id)
  14643. })
  14644. }
  14645. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  14646. .fontSize(16)
  14647. .margin({top:more.id >= 22?3:0})
  14648. .fontColor(Color.White)
  14649. .onClick(() => {
  14650. this.doMore(more.id)
  14651. })
  14652. Select([//倍速
  14653. { value: '0.25x' },
  14654. { value: '0.5x' },
  14655. { value: '0.75x' },
  14656. { value: '1x' },
  14657. { value: '1.25x' },
  14658. { value: '1.5x' },
  14659. { value: '1.75x' },
  14660. { value: '2x' },
  14661. { value: '3x' }])
  14662. .font({ size: 16, weight: FontWeight.Medium })
  14663. .fontColor($r('sys.color.white'))
  14664. .margin({ left: 25 })
  14665. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  14666. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  14667. .value(Utility.optimizedFormat(this.playSpeed))
  14668. .onSelect(async (_index: number, text?: string | undefined) => {
  14669. let speed = parseFloat(text?.replace('x', '') || '1');
  14670. if (!CommonConstants.video_speed_list.includes(speed)) {
  14671. speed = 1;
  14672. }
  14673. this.playSpeed = speed
  14674. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14675. })
  14676. Slider({
  14677. value: this.volume,
  14678. min: 0,
  14679. max: 1,
  14680. step: 0.1,
  14681. style: SliderStyle.OutSet
  14682. })
  14683. .margin({ left: 18, right: 8 })
  14684. .blockColor(this.themeColor)
  14685. .trackColor($r('app.color.speed_text_color'))
  14686. .selectedColor(Color.White)
  14687. .trackThickness(9)
  14688. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14689. .onChange((value: number) => {
  14690. this.volume = value;
  14691. this.applyCurrentVolume();
  14692. PreferencesUtil.putSync('DefalutVolume',this.volume)
  14693. })
  14694. .layoutWeight(1)
  14695. Slider({
  14696. value: this.volumeBoostPercent,
  14697. min: 0,
  14698. max: this.volumeBoostMaxPercent,
  14699. step: 1,
  14700. style: SliderStyle.OutSet
  14701. })
  14702. .margin({ left: 18, right: 8 })
  14703. .blockColor(this.themeColor)
  14704. .trackColor($r('app.color.speed_text_color'))
  14705. .selectedColor(Color.White)
  14706. .trackThickness(9)
  14707. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14708. .onChange((value: number) => {
  14709. this.volumeBoostPercent = Math.round(value);
  14710. this.applyCurrentVolume();
  14711. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  14712. })
  14713. .layoutWeight(1)
  14714. Text(`${Math.round(this.volumeBoostPercent)}%`)
  14715. .fontSize(13)
  14716. .fontColor(Color.White)
  14717. .margin({ left: 8, right: 8 })
  14718. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14719. Text(`${Math.round(this.volume*100)}%`)
  14720. .fontSize(13)
  14721. .fontColor(Color.White)
  14722. .margin({ left: 8, right: 8 })
  14723. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14724. Blank()
  14725. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  14726. .selectedColor(this.themeColor)
  14727. .switchPointColor(Color.White)
  14728. .margin({ right: 15 })
  14729. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14730. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  14731. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14732. if (more.id == 6) {
  14733. this.isMusicMemoryPlay = checked;
  14734. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  14735. if (this.isMusicMemoryPlay) {
  14736. ToastUtil.showToast('记忆播放已开启')
  14737. } else {
  14738. ToastUtil.showToast('记忆播放已关闭')
  14739. }
  14740. }
  14741. })
  14742. .width(48)
  14743. .height(24);
  14744. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  14745. .selectedColor(this.themeColor)
  14746. .switchPointColor(Color.White)
  14747. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14748. .margin({ right: 15 })
  14749. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  14750. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14751. if (more.id == 7) {
  14752. this.isMusicBGCover = checked;
  14753. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  14754. if (this.isMusicBGCover) {
  14755. ToastUtil.showToast('播放背景随音乐封面已开启')
  14756. } else {
  14757. ToastUtil.showToast('播放背景随音乐封面已关闭')
  14758. }
  14759. }
  14760. })
  14761. .width(48)
  14762. .height(24);
  14763. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  14764. .selectedColor(this.themeColor)
  14765. .switchPointColor(Color.White)
  14766. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14767. .margin({ right: 15 })
  14768. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  14769. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14770. if (more.id == 8) {
  14771. this.isSavePlayMode = checked;
  14772. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  14773. if (this.isSavePlayMode) {
  14774. ToastUtil.showToast('保存播放模式已开启')
  14775. } else {
  14776. ToastUtil.showToast('保存播放模式已关闭')
  14777. }
  14778. }
  14779. })
  14780. .width(48)
  14781. .height(24);
  14782. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  14783. .selectedColor(this.themeColor)
  14784. .switchPointColor(Color.White)
  14785. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14786. .margin({ right: 15 })
  14787. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  14788. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14789. if (more.id == 13) {
  14790. this.isCoverRectangle = checked;
  14791. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  14792. if (this.isCoverRectangle) {
  14793. ToastUtil.showToast('封面方形已开启,双指缩放封面可以调整封面大小')
  14794. this.animationRoFun()
  14795. } else {
  14796. ToastUtil.showToast('封面圆形已开启,双指缩放封面可以调整封面大小')
  14797. this.animationRoFun()
  14798. }
  14799. }
  14800. })
  14801. .width(48)
  14802. .height(24);
  14803. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  14804. .selectedColor(this.themeColor)
  14805. .switchPointColor(Color.White)
  14806. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14807. .margin({ right: 15 })
  14808. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  14809. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14810. if (more.id == 25) {
  14811. this.isShowSpectrum = checked;
  14812. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  14813. }
  14814. })
  14815. .width(48)
  14816. .height(24);
  14817. // 频谱特效类型选择器
  14818. Select([
  14819. { value: '柱状' },
  14820. { value: '波形' },
  14821. { value: '水波纹' },
  14822. { value: '圆形' },
  14823. { value: '粒子' },
  14824. { value: '脉冲' },
  14825. { value: '镜像柱' },
  14826. { value: '影子柱' },
  14827. { value: '轨道线' },
  14828. { value: '点阵' },
  14829. { value: '星爆' },
  14830. { value: '心电图' },
  14831. { value: '特效' }
  14832. ])
  14833. .font({ size: 14, weight: FontWeight.Medium })
  14834. .fontColor(Color.White)
  14835. .margin({ left: 25 })
  14836. .margin({top:more.id >= 22?3:0})
  14837. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  14838. .selected(this.spectrumModeIndex)
  14839. .value(['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'][this.spectrumModeIndex])
  14840. .onSelect((index: number, _text?: string) => {
  14841. this.spectrumModeIndex = index;
  14842. // 使用同步方法保存,确保立即生效
  14843. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  14844. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  14845. const modeNames = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  14846. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  14847. });
  14848. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  14849. .selectedColor(this.themeColor)
  14850. .switchPointColor(Color.White)
  14851. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14852. .margin({ right: 15 })
  14853. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  14854. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14855. if (more.id == 22) {
  14856. this.showSimple = checked;
  14857. PreferencesUtil.put('showSimple', this.showSimple)
  14858. }
  14859. })
  14860. .width(48)
  14861. .height(24);
  14862. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  14863. .selectedColor(this.themeColor)
  14864. .switchPointColor(Color.White)
  14865. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14866. .margin({ right: 15 })
  14867. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  14868. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14869. if (more.id == 23) {
  14870. this.enablePointLight = checked;
  14871. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  14872. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  14873. }
  14874. })
  14875. .width(48)
  14876. .height(24);
  14877. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  14878. .selectedColor(this.themeColor)
  14879. .switchPointColor(Color.White)
  14880. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14881. .margin({ right: 15 })
  14882. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  14883. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14884. if (more.id == 27) {
  14885. this.isGeKongPlayNext = checked;
  14886. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  14887. }
  14888. })
  14889. .width(48)
  14890. .height(24);
  14891. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  14892. .selectedColor(this.themeColor)
  14893. .switchPointColor(Color.White)
  14894. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14895. .margin({ right: 15 })
  14896. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  14897. .onChange((checked: boolean) => { // 是否开启背景流光效果
  14898. if (more.id == 21) {
  14899. this.isShowBgLiuGUANG = checked;
  14900. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  14901. }
  14902. })
  14903. .width(48)
  14904. .height(24);
  14905. }
  14906. }
  14907. .width('100%')
  14908. .height(45)
  14909. .padding(15)
  14910. .backgroundColor(Color.Transparent)
  14911. .borderRadius(12)
  14912. .margin({ bottom: 6 })
  14913. }
  14914. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  14915. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  14916. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  14917. .backgroundColor(Color.Transparent)
  14918. .onClick(() => {
  14919. this.doMore(more.id)
  14920. })
  14921. });
  14922. }
  14923. .width('100%')
  14924. .padding(16)
  14925. }.margin({ bottom: 18 })
  14926. }
  14927. @Builder
  14928. TPImageBuilder(more: MoreItem): void {
  14929. Row() {
  14930. Image($r('app.media.tuoping'))
  14931. .width(22)
  14932. .height(22)
  14933. .margin({ left: 10, right: 10 })
  14934. Text(more.title)
  14935. .fontSize(16)
  14936. .fontColor(Color.White)
  14937. }
  14938. .width('100%')
  14939. .layoutWeight(1)
  14940. .alignItems(VerticalAlign.Center)
  14941. .justifyContent(FlexAlign.Start)
  14942. }
  14943. private moreItems: MoreItem[] = [
  14944. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  14945. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  14946. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  14947. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  14948. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  14949. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  14950. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  14951. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  14952. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  14953. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  14954. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  14955. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  14956. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  14957. { id: 4, image: $r('app.media.share2'), title: '分享' },
  14958. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  14959. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  14960. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  14961. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  14962. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  14963. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  14964. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  14965. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  14966. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  14967. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  14968. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  14969. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  14970. ];
  14971. @State isShowBgLiuGUANG: boolean = false;
  14972. @State isShowMoreView: boolean = false;
  14973. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  14974. @State isShowTimeCloseMore: boolean = false
  14975. @State isShowDetailMore: boolean = false
  14976. @State isMusicBGCover: boolean = true
  14977. @State isSavePlayMode: boolean = true
  14978. @State isLyricSetting: boolean = false
  14979. @State isJumpSetting: boolean = false
  14980. @State isShowEdit: boolean = false
  14981. @State showPipLyric: boolean = false
  14982. @State isShowSpectrum: boolean = false//是否显示频谱
  14983. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  14984. private getEqualizerVolumeBoostRisk(): number {
  14985. const equalizerManager = EqualizerManager.getInstance();
  14986. if (!equalizerManager.enabled) {
  14987. return 0;
  14988. }
  14989. const gainStats = equalizerManager.getCurrentGainStats();
  14990. if (gainStats.maxPositiveGain <= 0 || gainStats.positiveGainSum <= 0) {
  14991. return 0;
  14992. }
  14993. const peakRisk = (gainStats.maxPositiveGain / 12) * 0.65;
  14994. const spreadRisk = (gainStats.positiveGainSum / 24) * 0.35;
  14995. return Math.max(0, Math.min(peakRisk + spreadRisk, 1));
  14996. }
  14997. private getSafeBoostPercent(): number {
  14998. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  14999. let compressedBoostPercent = rawBoostPercent;
  15000. if (rawBoostPercent <= 150) {
  15001. compressedBoostPercent = rawBoostPercent;
  15002. } else if (rawBoostPercent <= 300) {
  15003. compressedBoostPercent = 150 + (rawBoostPercent - 150) * 0.45;
  15004. } else {
  15005. compressedBoostPercent = 217.5 + (rawBoostPercent - 300) * 0.15;
  15006. }
  15007. const equalizerRisk = this.getEqualizerVolumeBoostRisk();
  15008. if (equalizerRisk <= 0) {
  15009. return compressedBoostPercent;
  15010. }
  15011. const protectedBoostPercent = compressedBoostPercent * (1 - equalizerRisk * 0.45);
  15012. const cappedBoostPercent = 220 - equalizerRisk * 140;
  15013. return Math.max(0, Math.min(protectedBoostPercent, cappedBoostPercent));
  15014. }
  15015. private getVolumeBoostFactor(): number {
  15016. return 1 + this.getSafeBoostPercent() / 100;
  15017. }
  15018. private getCurrentOutputVolume(): number {
  15019. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  15020. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  15021. const maxOutputVolume = this.getVolumeBoostFactor();
  15022. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  15023. }
  15024. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  15025. if (!this.mIjkMediaPlayer) {
  15026. return;
  15027. }
  15028. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  15029. this.mIjkMediaPlayer.setVolume('1', '1');
  15030. return;
  15031. }
  15032. const outputVolume = this.getCurrentOutputVolume();
  15033. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  15034. }
  15035. async setRingTone() {
  15036. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  15037. return
  15038. }
  15039. // 确定后的逻辑
  15040. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  15041. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  15042. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  15043. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  15044. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  15045. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  15046. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  15047. , this.videoUrl, this.name).then(res => {
  15048. LogUtil.info('onecold setFlag :' + res);
  15049. });
  15050. }
  15051. doMore(moreId: number) {
  15052. switch (moreId) {
  15053. case 30: //歌词
  15054. this.isLyricSetting = !this.isLyricSetting;
  15055. this.isShowMoreView = false
  15056. break;
  15057. case 3: //详情
  15058. this.isShowDetailMore = !this.isShowDetailMore;
  15059. break;
  15060. case 4: //分享
  15061. if (this.currentSong !== undefined) {
  15062. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  15063. }
  15064. this.isShowMoreView = false
  15065. break;
  15066. case 5: //定时关闭
  15067. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  15068. break;
  15069. case 10: //设为铃声
  15070. this.setRingTone()
  15071. this.isShowMoreView = false
  15072. break;
  15073. case 11: //跳过头尾
  15074. this.isJumpSetting = !this.isJumpSetting;
  15075. break;
  15076. case 13: //倍速
  15077. break;
  15078. case 14: //搜索封面
  15079. if (this.currentSong !== undefined) {
  15080. this.doSearchCover(this.currentSong)
  15081. }
  15082. this.isShowMoreView = false
  15083. break;
  15084. case 15: //编辑标签
  15085. this.initEditFields(this.currentSong)
  15086. this.tempLyricContent = this.lyricContent
  15087. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  15088. this.lyricConStr = this.tempLyricContent
  15089. }
  15090. this.isShowEdit = !this.isShowEdit;
  15091. break;
  15092. case 16: //悬浮歌词
  15093. this.showPipLyric = !this.showPipLyric;
  15094. break;
  15095. case 17: //横屏模式
  15096. if (this.isLandscape) {
  15097. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  15098. } else {
  15099. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  15100. }
  15101. this.isShowMoreView = false
  15102. break;
  15103. case 20://AB循环
  15104. this.isABSheet = !this.isABSheet
  15105. break;
  15106. case 24://均衡器
  15107. this.isEqualizerSheet = !this.isEqualizerSheet
  15108. break;
  15109. }
  15110. }
  15111. //AB循环
  15112. @State isOpenAB:boolean = false
  15113. @State jumpATime:number = 0
  15114. @State jumpBTime:number = 0
  15115. @State isABSheet:boolean = false
  15116. @State isEqualizerSheet: boolean = false
  15117. @State eqApplying: boolean = false
  15118. @State eqAppliedAt: number = 0
  15119. @State eqCurrentPresetName: string = '正常'
  15120. @State eqCurrentEnabled: boolean = false
  15121. @Builder
  15122. ABLoopSheet() {
  15123. ABLoopComptent({
  15124. jumpATime:this.jumpATime,
  15125. jumpBTime:this.jumpBTime,
  15126. onClickAItem: async ()=>{
  15127. if(this.mIjkMediaPlayer){
  15128. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  15129. }
  15130. },
  15131. onClickBItem: async ()=>{
  15132. if(this.mIjkMediaPlayer){
  15133. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  15134. if(this.jumpBTime<=this.jumpATime){
  15135. ToastUtil.showToast('设置B点时间不能小于A点时间')
  15136. this.jumpBTime = 0
  15137. }
  15138. }
  15139. },
  15140. onCancleButtonClick: async ()=>{
  15141. this.isOpenAB = false
  15142. this.isABSheet = false
  15143. },
  15144. onStartButtonClick: async ()=>{
  15145. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  15146. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  15147. return
  15148. }
  15149. this.isABSheet = false
  15150. this.startABLoop()
  15151. },
  15152. })
  15153. }
  15154. private syncEqualizerUi(): void {
  15155. const equalizerManager = EqualizerManager.getInstance();
  15156. this.eqCurrentEnabled = equalizerManager.enabled;
  15157. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15158. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  15159. this.eqAppliedAt = 0;
  15160. }
  15161. }
  15162. private markEqualizerApplied(): void {
  15163. const equalizerManager = EqualizerManager.getInstance();
  15164. this.eqCurrentEnabled = equalizerManager.enabled;
  15165. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15166. this.eqAppliedAt = Date.now();
  15167. this.eqApplying = false;
  15168. }
  15169. private applyEqualizerToCurrentPlayback(): void {
  15170. if (this.eqApplying) {
  15171. return;
  15172. }
  15173. if (this.castControllerWrapper && this.isCastPlaying) {
  15174. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  15175. return;
  15176. }
  15177. if (!this.currentSong || !this.mIjkMediaPlayer) {
  15178. ToastUtil.showToast('暂无可应用的播放');
  15179. return;
  15180. }
  15181. this.eqApplying = true;
  15182. try {
  15183. const equalizerManager = EqualizerManager.getInstance();
  15184. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15185. this.applyCurrentVolume();
  15186. this.markEqualizerApplied();
  15187. ToastUtil.showToast('均衡器已实时生效');
  15188. } catch (error) {
  15189. this.eqApplying = false;
  15190. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  15191. }
  15192. }
  15193. @Builder
  15194. private EqualizerApplyStatusBar(): void {
  15195. Row() {
  15196. Column() {
  15197. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  15198. .fontSize(12)
  15199. .fontColor($r('app.color.text_color'))
  15200. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  15201. .fontSize(10)
  15202. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  15203. }
  15204. .alignItems(HorizontalAlign.Start)
  15205. Blank()
  15206. Button('重新应用')
  15207. .fontSize(12)
  15208. .fontColor(Color.White)
  15209. .backgroundColor('#666666')
  15210. .height(28)
  15211. .padding({ left: 14, right: 14 })
  15212. .borderRadius(14)
  15213. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  15214. .onClick(() => {
  15215. this.applyEqualizerToCurrentPlayback();
  15216. })
  15217. }
  15218. .width('100%')
  15219. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  15220. .backgroundColor($r('app.color.settings_background_main'))
  15221. .borderRadius(12)
  15222. }
  15223. @Builder
  15224. EqualizerSheet() {
  15225. Column() {
  15226. Column() {
  15227. EqualizerViewWithCallback({
  15228. onEqualizerChanged: () => {
  15229. this.syncEqualizerUi();
  15230. if (this.mIjkMediaPlayer) {
  15231. const equalizerManager = EqualizerManager.getInstance();
  15232. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15233. this.applyCurrentVolume();
  15234. this.markEqualizerApplied();
  15235. }
  15236. }
  15237. })
  15238. }
  15239. .margin({ top: 8 })
  15240. Column() {
  15241. this.EqualizerApplyStatusBar()
  15242. }
  15243. .margin({ top: 8 })
  15244. }
  15245. .padding({ left: 12, right: 12, bottom: 20 })
  15246. .width('100%')
  15247. }
  15248. //开始AB循环
  15249. startABLoop(){
  15250. if(this.mIjkMediaPlayer){
  15251. this.seekTo(this.jumpATime+'')
  15252. this.isOpenAB = true
  15253. }
  15254. }
  15255. /**
  15256. * 切换横竖屏
  15257. *
  15258. */
  15259. setOrientation(orientation: number) {
  15260. this.windowClass.setPreferredOrientation(orientation).then(() => {
  15261. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  15262. }).catch((err: BusinessError) => {
  15263. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  15264. });
  15265. }
  15266. /**
  15267. * 画中画功能(悬浮歌词功能)
  15268. *
  15269. */
  15270. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  15271. pipController?: PiPWindow.PiPController;
  15272. navigationId: string = '';
  15273. @State curState: string = '';
  15274. @State curError: ResourceStr = '';
  15275. @State pipBg: string = '#E8E8E8'
  15276. @State buttonAction: string = '';
  15277. //开启画中画功能
  15278. async startPip() {
  15279. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  15280. if (!this.pipController) {
  15281. await this.createPipController();
  15282. }
  15283. if (!this.pipController) {
  15284. Logger.info(`[${TAG}] pipController create error`);
  15285. return;
  15286. }
  15287. await this.pipController.startPiP();
  15288. }
  15289. async stopPip() {
  15290. if (!this.pipController) {
  15291. Logger.info(`[${TAG}] pipController is not exist`);
  15292. return;
  15293. }
  15294. this.isOpenPip = false
  15295. await this.pipController.stopPiP();
  15296. }
  15297. async createPipController() {
  15298. this.pipController = await PiPWindow.create({
  15299. context: getContext(this),
  15300. componentController: this.xcomponentController,
  15301. navigationId: this.navigationId,
  15302. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  15303. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  15304. customUIController: this.nodeController,
  15305. });
  15306. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  15307. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  15308. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  15309. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  15310. this.onStateChange(state, reason);
  15311. });
  15312. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  15313. this.onActionEvent(event, status);
  15314. });
  15315. }
  15316. destroyPipController() {
  15317. if (!this.pipController) {
  15318. return;
  15319. }
  15320. this.pipController.off('stateChange');
  15321. this.pipController.off('controlPanelActionEvent');
  15322. this.pipController = undefined;
  15323. }
  15324. onStateChange(state: PiPWindow.PiPState, reason: string) {
  15325. switch (state) {
  15326. case PiPWindow.PiPState.ABOUT_TO_START:
  15327. this.curState = 'ABOUT_TO_START';
  15328. this.curError = $r('app.string.current_error_hint');
  15329. break;
  15330. case PiPWindow.PiPState.STARTED:
  15331. this.curState = 'STARTED';
  15332. this.curError = $r('app.string.current_error_hint');
  15333. break;
  15334. case PiPWindow.PiPState.ABOUT_TO_STOP:
  15335. this.curState = 'ABOUT_TO_STOP';
  15336. this.curError = $r('app.string.current_error_hint');
  15337. break;
  15338. case PiPWindow.PiPState.STOPPED:
  15339. this.curState = 'STOPPED';
  15340. this.curError = $r('app.string.current_error_hint');
  15341. this.stopPip()
  15342. this.destroyPipController()
  15343. break;
  15344. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  15345. this.curState = 'ABOUT_TO_RESTORE';
  15346. this.curError = $r('app.string.current_error_hint');
  15347. break;
  15348. case PiPWindow.PiPState.ERROR:
  15349. this.curState = 'ERROR';
  15350. this.curError = reason;
  15351. break;
  15352. default:
  15353. break;
  15354. }
  15355. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  15356. }
  15357. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  15358. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  15359. switch (event) {
  15360. case 'playbackStateChanged':
  15361. if (status === 0) {
  15362. this.pause();
  15363. } else {
  15364. console.info('onecold startPlayOrResumePlay 9869')
  15365. this.startPlayOrResumePlay();
  15366. }
  15367. break;
  15368. case 'nextVideo':
  15369. // 切换到下一个视频
  15370. this.playNext().catch(() => {
  15371. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  15372. });
  15373. break;
  15374. case 'previousVideo':
  15375. // 切换到上一个视频
  15376. this.playPrevious().catch(() => {
  15377. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  15378. });
  15379. break;
  15380. case 'previousVideo':
  15381. // 切换到上一个视频
  15382. this.playPrevious().catch(() => {
  15383. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  15384. });
  15385. break;
  15386. default:
  15387. }
  15388. this.buttonAction = event + `-status:${status}`;
  15389. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  15390. }
  15391. /**
  15392. * 画中画功能(悬浮歌词功能)结束
  15393. *
  15394. */
  15395. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  15396. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  15397. this.isShowMoreView = false;
  15398. this.showTipsDialog();
  15399. return ''; // Return empty string when no API is configured
  15400. }
  15401. if (!item) {
  15402. return ''; // Return empty string if item is undefined
  15403. }
  15404. const titleS = title||item?.name || '';
  15405. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  15406. return this.searchCover(item, titleS, artistS, true); // Await is not needed here as we return the promise directly
  15407. }
  15408. /**
  15409. *api搜索封面
  15410. *item,根据title和artist
  15411. */
  15412. searchCover(item: VideoItem, title: string, artist: string, markAsCustomCover: boolean = false): Promise<string> {
  15413. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  15414. LogUtil.debug("onecold res =" + res);
  15415. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  15416. if (item.filePath == this.currentSong?.filePath) {
  15417. if (this.currentSong) {
  15418. mergeCoverWithPriority(this.currentSong, res, markAsCustomCover ? 1 : 0);
  15419. this.cover = this.currentSong.pixelMapPath || res;
  15420. }
  15421. }
  15422. if (isRemoteCloudType(item.type)) {
  15423. mergeCoverWithPriority(item, res, markAsCustomCover ? 1 : 0);
  15424. this.syncRemoteManagerSong(item);
  15425. try {
  15426. await this.persistRemoteMetadataToDb(item);
  15427. this.emitRemoteMetadataUpdated(item);
  15428. } catch (error) {
  15429. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  15430. }
  15431. } else {
  15432. // Update pixel map path but always return res regardless of success
  15433. if (markAsCustomCover) {
  15434. item.isCustomCover = 1;
  15435. this.table.updateCustomCoverPath(item.filePath, res, (success: boolean, error?: string) => {
  15436. if (success) {
  15437. this.doUpdateData();
  15438. console.log("onecold 更新音乐封面成功,数据库已同步");
  15439. } else {
  15440. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15441. }
  15442. });
  15443. } else {
  15444. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  15445. if (success) {
  15446. this.doUpdateData();
  15447. console.log("onecold 更新音乐封面成功,数据库已同步");
  15448. } else {
  15449. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15450. }
  15451. });
  15452. }
  15453. }
  15454. LogUtil.debug("onecold this.cover =" + this.cover);
  15455. }
  15456. return res; // Always return res regardless of updatePixelMapPath result
  15457. });
  15458. }
  15459. @State jumpTopTime: number = 0
  15460. @State jumpEndTime: number = 0
  15461. @State isOpenJump: boolean = false
  15462. @Builder
  15463. JumpTopEndSheet() {
  15464. Scroll() {
  15465. Column() {
  15466. Column() {
  15467. Text('仅对本播放列表有效')
  15468. .fontSize(16)
  15469. .fontColor($r('app.color.text_color'))
  15470. // 跳过头尾
  15471. Column() {
  15472. Row() {
  15473. Text('跳过片头:')
  15474. .fontSize(16)
  15475. .fontColor($r('app.color.text_color'))
  15476. Text(this.jumpTopTime + 's')
  15477. .fontSize(16)
  15478. .fontColor($r('app.color.text_color'))
  15479. }
  15480. .margin({ bottom: 5 })
  15481. Row() {
  15482. Slider({
  15483. value: this.jumpTopTime,
  15484. min: 0,
  15485. max: 120,
  15486. step: 1,
  15487. style: SliderStyle.OutSet
  15488. })
  15489. .blockColor(this.themeColor)
  15490. .trackColor($r('app.color.speed_text_color'))
  15491. .selectedColor(Color.White)
  15492. .trackThickness(8)
  15493. .onChange((value: number) => {
  15494. this.jumpTopTime = value;
  15495. })
  15496. .width('85%')
  15497. }
  15498. .alignItems(VerticalAlign.Top)
  15499. }
  15500. .margin({ top: 10, bottom: 10 })
  15501. // 跳过头尾
  15502. Column() {
  15503. Row() {
  15504. Text('跳过片尾:')
  15505. .fontSize(16)
  15506. .fontColor($r('app.color.text_color'))
  15507. Text(this.jumpEndTime + 's')
  15508. .fontSize(16)
  15509. .fontColor($r('app.color.text_color'))
  15510. }
  15511. .margin({ bottom: 5 })
  15512. Row() {
  15513. Slider({
  15514. value: this.jumpEndTime,
  15515. min: 0,
  15516. max: 120,
  15517. step: 1,
  15518. style: SliderStyle.OutSet
  15519. })
  15520. .blockColor(this.themeColor)
  15521. .trackColor($r('app.color.speed_text_color'))
  15522. .selectedColor(Color.White)
  15523. .trackThickness(8)
  15524. .onChange((value: number) => {
  15525. this.jumpEndTime = value;
  15526. })
  15527. .width('85%')
  15528. }
  15529. .alignItems(VerticalAlign.Top)
  15530. }
  15531. .margin({ top: 10, bottom: 10 })
  15532. Row() {
  15533. Button('保存设置')
  15534. .fontColor(Color.White)
  15535. .layoutWeight(1)
  15536. .height(40)
  15537. .width(80)
  15538. .backgroundColor(this.themeColor)
  15539. .stateEffect(true)
  15540. .margin({ left: 0, bottom: 20 })
  15541. .onClick(async () => {
  15542. if (!Utility.isNoble()) {
  15543. this.isJumpSetting = false
  15544. this.isShowMoreView = false
  15545. this.showVipDialog()
  15546. return
  15547. }
  15548. if (this.currentSong === undefined) {
  15549. return
  15550. }
  15551. if (this.modeType === 0) {
  15552. let parentPath = FileUtil.getParentPath(this.videoUrl)
  15553. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  15554. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  15555. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  15556. } else if (this.modeType === 1) { //媒体库
  15557. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  15558. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  15559. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  15560. } else if (this.modeType === 2) { //艺术家
  15561. if (this.currentSong?.artist) {
  15562. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  15563. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  15564. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  15565. }
  15566. } else if (this.modeType === 3) { //专辑
  15567. if (this.currentSong?.album) {
  15568. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  15569. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  15570. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  15571. }
  15572. }
  15573. ToastUtil.showShort("保存成功")
  15574. this.isJumpSetting = false
  15575. })
  15576. }
  15577. .margin({
  15578. left: 38,
  15579. right: 38,
  15580. top: 10,
  15581. bottom: 10
  15582. })
  15583. .width(120)
  15584. .height(50)
  15585. }
  15586. }
  15587. }
  15588. .width('100%')
  15589. .height('100%')
  15590. }
  15591. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  15592. private onStateVastChange(state: AVCastPickerState) {
  15593. if (state == AVCastPickerState.STATE_APPEARING) {
  15594. console.log('The picker starts showing.');
  15595. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  15596. console.log('The picker finishes presenting.');
  15597. }
  15598. }
  15599. private showSelectLyric() {
  15600. DialogHelper.showActionSheetDialog({
  15601. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  15602. // sheets: ["本地歌词", "搜索歌词"],
  15603. sheets: [
  15604. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  15605. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  15606. ],
  15607. maskColor: Color.Transparent,
  15608. backgroundColor: $r('app.color.bg_card'),
  15609. transition: AnimationHelper.transitionInDown(666),
  15610. onAction: (index) => {
  15611. switch (index) {
  15612. case 0:
  15613. this.callFilePickerSelectFileForLyric()
  15614. break;
  15615. case 1:
  15616. if (StrUtil.isNotEmpty(this.videoUrl)) {
  15617. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15618. this.initLyric(lyricPath);
  15619. }
  15620. break;
  15621. }
  15622. }
  15623. })
  15624. }
  15625. // 拉起picker选择文件管理器
  15626. async callFilePickerSelectFileForLyric(): Promise<void> {
  15627. try {
  15628. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  15629. DocumentSelectOptions.maxSelectNumber = 1
  15630. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  15631. let documentPicker = new picker.DocumentViewPicker();
  15632. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  15633. Logger.info(TAG,
  15634. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  15635. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  15636. this.saveVideoDatasLyric(DocumentSelectResult)
  15637. }
  15638. }).catch((err: BusinessError) => {
  15639. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  15640. });
  15641. } catch (err) {
  15642. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  15643. }
  15644. }
  15645. async saveVideoDatasLyric(uris: string[]) {
  15646. if (ArrayUtil.isEmpty(uris)) {
  15647. return
  15648. }
  15649. let newUris: string[] = [];
  15650. for (let i = 0; i < uris.length; i++) {
  15651. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  15652. Logger.info(TAG, 'filePath uri: ' + filePath);
  15653. newUris.push(filePath)
  15654. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  15655. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  15656. fileIo.copyFileSync(file.fd, file2.fd)
  15657. fileIo.closeSync(file);
  15658. fileIo.closeSync(file2);
  15659. this.initLyric(filePath,false,false,true)
  15660. }
  15661. }
  15662. private initDelayPlay(context: object) {
  15663. this.mContext = context;
  15664. }
  15665. startPipLyric() {
  15666. if (this.pipController) {
  15667. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15668. PiPWindow.PiPControlStatus.PLAY);
  15669. }
  15670. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  15671. if (this.isOpenPip) {
  15672. this.startPip()
  15673. } else {
  15674. this.stopPip()
  15675. }
  15676. }
  15677. //startOffset 从cue分轨时间开始播
  15678. private startPlayOrResumePlay(startOffset?:number) {
  15679. let finalStartOffset = startOffset
  15680. if ((finalStartOffset === undefined || finalStartOffset === null) && this.currentSong && isCueSplitItem(this.currentSong)) {
  15681. finalStartOffset = 0
  15682. }
  15683. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  15684. //针对dsf文件高采样率,统一转wav播放
  15685. // const sampleRate = this.currentSong?.sampleRate||0
  15686. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  15687. // console.info('onecold 采样率 ='+sampleRate)
  15688. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  15689. // console.info('onecold newDsfPath ='+newDsfPath)
  15690. // if(!FileUtil.accessSync(newDsfPath)){
  15691. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  15692. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  15693. // this.videoUrl = newDsfPath
  15694. // this.startPlay(startOffset)
  15695. // }).catch((e:object)=>{
  15696. // console.info("task1 catch e: " + e);
  15697. // })
  15698. // }else{
  15699. // this.videoUrl = newDsfPath
  15700. // this.startPlay(startOffset)
  15701. // }
  15702. //
  15703. // }else{
  15704. // this.startPlay(startOffset)
  15705. // }
  15706. this.startPlay(finalStartOffset)
  15707. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  15708. // 排除用户拖动进度条的情况
  15709. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  15710. void this.preloadNextSongInternal();
  15711. }
  15712. }
  15713. startPlay(startOffset?:number) {
  15714. this.startPipLyric()
  15715. this.mDestroyPage = false;
  15716. this.animationState = AnimationStatus.Running
  15717. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  15718. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  15719. this.stopProgressTask();
  15720. this.startProgressTask();
  15721. this.clearInitialSeekGuardTimer();
  15722. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  15723. this.remoteRestoreSeekToken++;
  15724. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  15725. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  15726. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  15727. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  15728. this.videoUrl.includes('://');
  15729. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  15730. // 网盘歌曲起播阶段统一显示加载圈,prepared/首帧后再收起
  15731. this.isPlayerLoading = !!isRemoteStreamSong;
  15732. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15733. Logger.info(
  15734. TAG,
  15735. `[remote-play] startPlay type=${this.currentSong.type}, memory=${this.pendingMemorySeekPosition}, ` +
  15736. `waitInitial=${this.waitInitialSeekBeforeStart}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15737. );
  15738. }
  15739. this.play(this.videoUrl.toString(),startOffset);
  15740. }
  15741. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  15742. this.mIjkMediaPlayer.start();
  15743. this.setProgress()
  15744. this.CONTROL_PlayStatus = PlayStatus.PLAY
  15745. }
  15746. this.setIsPlaying(true)
  15747. this.updateSessionPlayState(true)
  15748. this.watchStatus();
  15749. this.updateLastPlayTimeStr(this.videoUrl)
  15750. }
  15751. updateLastPlayTimeStr(filePath: string) {
  15752. const activeSong = this.currentSong;
  15753. let targetFilePath = this.currentSong?.filePath || filePath;
  15754. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15755. const remoteStoragePath = this.resolveRemoteStoragePath(activeSong);
  15756. if (remoteStoragePath) {
  15757. targetFilePath = remoteStoragePath;
  15758. }
  15759. Logger.info(`heanup 检测到网络音频播放,改为更新远程歌曲最近播放: ${targetFilePath}`)
  15760. }
  15761. if (!targetFilePath) {
  15762. Logger.warn(TAG, `更新最近播放时间失败,目标路径为空: ${filePath}`);
  15763. return;
  15764. }
  15765. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  15766. const applyHistoryUpdate = (): void => {
  15767. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (success: boolean, error?: string) => {
  15768. if (success) {
  15769. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15770. this.currentSong.lastPlayedStr = lastPlayTime
  15771. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15772. }
  15773. this.getHistoryList(false)
  15774. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  15775. return;
  15776. }
  15777. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15778. Logger.warn(TAG, `远程歌曲最近播放更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  15779. this.persistRemoteMetadataToDb(activeSong)
  15780. .then(() => {
  15781. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (retrySuccess: boolean,
  15782. retryError?: string) => {
  15783. if (retrySuccess) {
  15784. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15785. this.currentSong.lastPlayedStr = lastPlayTime
  15786. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15787. }
  15788. this.getHistoryList(false)
  15789. Logger.info(TAG, `远程歌曲最近播放补入库后更新成功: ${targetFilePath}`);
  15790. } else {
  15791. Logger.error(TAG,
  15792. `远程歌曲最近播放补入库后仍更新失败: ${targetFilePath}, error=${retryError}`);
  15793. }
  15794. });
  15795. })
  15796. .catch((persistError: Error) => {
  15797. Logger.error(TAG,
  15798. `远程歌曲最近播放补入库失败: ${targetFilePath}, error=${persistError.message}`);
  15799. });
  15800. return;
  15801. }
  15802. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  15803. });
  15804. };
  15805. applyHistoryUpdate();
  15806. }
  15807. private completionNum(num: number): string | number {
  15808. if (num < 10) {
  15809. return '0' + num;
  15810. } else {
  15811. return num;
  15812. }
  15813. }
  15814. private parseDurationToMs(duration?: string): number {
  15815. if (!duration) {
  15816. return 0;
  15817. }
  15818. const parts = duration.split(':').map((item) => Number(item));
  15819. if (parts.some((item) => Number.isNaN(item))) {
  15820. return 0;
  15821. }
  15822. if (parts.length === 2) {
  15823. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  15824. }
  15825. if (parts.length === 3) {
  15826. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  15827. }
  15828. return 0;
  15829. }
  15830. private sanitizePlaybackUrl(url?: string): string {
  15831. if (!url) {
  15832. return '';
  15833. }
  15834. let sanitized = url.replace(/(access_token=)[^&]+/ig, '$1***');
  15835. sanitized = sanitized.replace(/(refresh_token=)[^&]+/ig, '$1***');
  15836. sanitized = sanitized.replace(/(Authorization=)[^&]+/ig, '$1***');
  15837. if (sanitized.length > 220) {
  15838. return `${sanitized.substring(0, 220)}...`;
  15839. }
  15840. return sanitized;
  15841. }
  15842. private sanitizePlaylistDebugPath(path?: string): string {
  15843. if (!path) {
  15844. return '';
  15845. }
  15846. return path.length > 48 ? `...${path.substring(path.length - 48)}` : path;
  15847. }
  15848. private buildSongDebugItem(item?: VideoItem): string {
  15849. if (!item) {
  15850. return 'unknown';
  15851. }
  15852. const title = item.name || item.fileName || '未知歌曲';
  15853. return `${title}|type=${item.type}|acc=${item.webdav_account_id || ''}|path=${this.sanitizePlaylistDebugPath(item.filePath)}`;
  15854. }
  15855. private buildSongListDebugLog(items: VideoItem[], limit: number = 5): string {
  15856. if (!items || items.length === 0) {
  15857. return '[]';
  15858. }
  15859. const parts: string[] = [];
  15860. const maxCount = Math.min(limit, items.length);
  15861. for (let i = 0; i < maxCount; i++) {
  15862. parts.push(this.buildSongDebugItem(items[i]));
  15863. }
  15864. return `[${parts.join('; ')}](${items.length})`;
  15865. }
  15866. private buildPathListDebugLog(paths: string[], limit: number = 5): string {
  15867. if (!paths || paths.length === 0) {
  15868. return '[]';
  15869. }
  15870. const parts: string[] = [];
  15871. const maxCount = Math.min(limit, paths.length);
  15872. for (let i = 0; i < maxCount; i++) {
  15873. parts.push(this.sanitizePlaylistDebugPath(paths[i]));
  15874. }
  15875. return `[${parts.join('; ')}](${paths.length})`;
  15876. }
  15877. private async dispatchPlaylistPlayRequest(playlistData: PlaylistPlayRequest): Promise<void> {
  15878. clearPendingPlaylistPlay();
  15879. Logger.info(
  15880. TAG,
  15881. `[remote-debug] dispatchPlaylistPlayRequest id=${playlistData.playlistId}, name=${playlistData.playlistName}, ` +
  15882. `songCount=${playlistData.songCount}, startIndex=${playlistData.startIndex}, playType=${playlistData.playType ?? -1}, ` +
  15883. `paths=${this.buildPathListDebugLog(playlistData.songFilePaths)}`
  15884. );
  15885. if (playlistData.playType !== undefined) {
  15886. this.applyRequestedPlayType(playlistData.playType);
  15887. }
  15888. await this.handlePlaylistPlayRequest(
  15889. playlistData.playlistId,
  15890. playlistData.playlistName,
  15891. playlistData.songFilePaths,
  15892. playlistData.startIndex,
  15893. playlistData.isJump ?? false,
  15894. playlistData.songCount
  15895. );
  15896. }
  15897. private async resolvePlaybackUrlForCurrentSong(source: string): Promise<string | null> {
  15898. const song = this.currentSong;
  15899. if (!song) {
  15900. Logger.warn(TAG, `[play-url] skip source=${source}, currentSong is null`);
  15901. return null;
  15902. }
  15903. const expectedFilePath = song.filePath || '';
  15904. const requestSerial = ++this.playbackUrlRequestSerial;
  15905. Logger.info(
  15906. TAG,
  15907. `[play-url] begin serial=${requestSerial}, source=${source}, song=${song.name}, path=${expectedFilePath}`
  15908. );
  15909. const resolvedUrl = await setVideoUrlForSong(song, {
  15910. context: this.context,
  15911. autoParseMusicName: this.autoParseMusicName
  15912. });
  15913. const currentFilePath = this.currentSong?.filePath || '';
  15914. if (requestSerial !== this.playbackUrlRequestSerial || currentFilePath !== expectedFilePath) {
  15915. Logger.warn(
  15916. TAG,
  15917. `[play-url] stale serial=${requestSerial}, source=${source}, expected=${expectedFilePath}, ` +
  15918. `current=${currentFilePath}, drop=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15919. );
  15920. return null;
  15921. }
  15922. Logger.info(
  15923. TAG,
  15924. `[play-url] apply serial=${requestSerial}, source=${source}, song=${song.name}, ` +
  15925. `url=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15926. );
  15927. return resolvedUrl;
  15928. }
  15929. private beginSeekTrace(source: string, requestMs: number): void {
  15930. this.lastSeekSource = source;
  15931. this.lastSeekRequestMs = requestMs;
  15932. this.seekTraceUntilTs = Date.now() + this.seekTraceLogWindowMs;
  15933. this.lastSeekTraceLogTs = 0;
  15934. }
  15935. private isSeekTraceActive(): boolean {
  15936. return this.seekTraceUntilTs > 0 && Date.now() <= this.seekTraceUntilTs;
  15937. }
  15938. private logSeekTrace(stage: string, position?: number, playerDuration?: number, force: boolean = false): void {
  15939. if (!force && !this.isSeekTraceActive()) {
  15940. return;
  15941. }
  15942. const now = Date.now();
  15943. if (!force && now - this.lastSeekTraceLogTs < this.seekTraceLogIntervalMs) {
  15944. return;
  15945. }
  15946. this.lastSeekTraceLogTs = now;
  15947. const currentPosition = typeof position === 'number' ? position : this.mIjkMediaPlayer.getCurrentPosition();
  15948. const resolvedPlayerDuration = typeof playerDuration === 'number' ? playerDuration : this.mIjkMediaPlayer.getDuration();
  15949. Logger.info(
  15950. TAG,
  15951. `[seek-trace] stage=${stage}, source=${this.lastSeekSource || 'unknown'}, req=${this.lastSeekRequestMs}, ` +
  15952. `current=${currentPosition}, playerDuration=${resolvedPlayerDuration}, uiDuration=${this.duration}, ` +
  15953. `activeDuration=${this.getActiveDuration()}, isPlaying=${this.mIjkMediaPlayer.isPlaying()}, ` +
  15954. `isSeekTo=${this.isSeekTo}, waitInitial=${this.waitInitialSeekBeforeStart}, ` +
  15955. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15956. );
  15957. }
  15958. private shouldShowSeekBlockedToast(source: string): boolean {
  15959. return source === 'top-progress-slider' ||
  15960. source === 'landscape-progress-slider' ||
  15961. source === 'fast-forward-button' ||
  15962. source === 'rewind-button' ||
  15963. source === 'session-fast-forward' ||
  15964. source === 'session-rewind' ||
  15965. source === 'session-seek';
  15966. }
  15967. private handleBlockedSeek(seekPos: number, source: string): boolean {
  15968. const decision = resolveSeekGuardDecision(this.videoUrl, seekPos);
  15969. if (decision.allow) {
  15970. return false;
  15971. }
  15972. Logger.warn(
  15973. TAG,
  15974. `[seek] blocked source=${source}, target=${seekPos}, reason=${decision.reason}, ` +
  15975. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15976. );
  15977. if (this.shouldShowSeekBlockedToast(source) && StrUtil.isNotEmpty(decision.toastMessage)) {
  15978. ToastUtil.showToast(decision.toastMessage);
  15979. }
  15980. if (this.waitInitialSeekBeforeStart) {
  15981. this.finishInitialSeekWait(`blocked-${decision.reason}`, true);
  15982. } else {
  15983. this.hideLoadIng();
  15984. }
  15985. this.isSeekTo = false;
  15986. this.logSeekTrace(`seek-blocked-${decision.reason}`, undefined, undefined, true);
  15987. return true;
  15988. }
  15989. private stringForTime(timeMs: number): string {
  15990. let totalSeconds: number | string = (timeMs / 1000);
  15991. let newSeconds: number | string = totalSeconds % 60;
  15992. let minutes: number | string = (totalSeconds / 60) % 60;
  15993. let hours: number | string = totalSeconds / 3600;
  15994. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  15995. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  15996. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  15997. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  15998. if (this.isCurrentTime) {
  15999. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  16000. this.oldSeconds = newSeconds
  16001. } else {
  16002. newSeconds = this.oldSeconds
  16003. }
  16004. }
  16005. newSeconds = this.completionNum(newSeconds);
  16006. if (hours > 0) {
  16007. return hours + ":" + minutes + ":" + newSeconds;
  16008. } else {
  16009. return minutes + ":" + newSeconds;
  16010. }
  16011. }
  16012. private getPlayerSwiperDisplayCount(): number {
  16013. return new BreakpointType<number>({
  16014. sm: 1,
  16015. md: 2,
  16016. lg: 2,
  16017. xl: 2,
  16018. xxl: 2
  16019. }).getValue(this.currentBreakpoint) ?? 1
  16020. }
  16021. private shouldUpdateMainLyricPanel(): boolean {
  16022. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  16023. }
  16024. private getActivePlaybackPositionMs(): number {
  16025. if (this.castControllerWrapper && this.isCastPlaying) {
  16026. return this.currentTime2 * 1000
  16027. }
  16028. return this.mIjkMediaPlayer.getCurrentPosition()
  16029. }
  16030. private syncLyricPositionNow(): void {
  16031. const position = this.getActivePlaybackPositionMs()
  16032. if (position < 0) {
  16033. return
  16034. }
  16035. this.updateLyricPosition(position + this.timeOffset * 1000)
  16036. }
  16037. private updateLyricPosition(lyricPosition: number): void {
  16038. if (!this.isAppForeground || !this.isPageVisible) {
  16039. return;
  16040. }
  16041. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  16042. const shouldUpdatePipLyric = this.showPipLyric
  16043. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  16044. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  16045. return
  16046. }
  16047. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  16048. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  16049. return;
  16050. }
  16051. this.lastLyricRenderPosition = lyricPosition;
  16052. if (shouldUpdateMainLyric) {
  16053. this.lyricController.updatePosition(lyricPosition);
  16054. }
  16055. if (shouldUpdatePipLyric) {
  16056. this.lyricControllerXF.updatePosition(lyricPosition);
  16057. }
  16058. if (shouldUpdateSingleLineLyric) {
  16059. this.lyricControllerSingle.updatePosition(lyricPosition);
  16060. }
  16061. }
  16062. private setProgress() {
  16063. if (this.castControllerWrapper && this.isCastPlaying) {
  16064. return;
  16065. }
  16066. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  16067. const rawPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16068. const rawDuration = this.mIjkMediaPlayer.getDuration();
  16069. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  16070. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  16071. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  16072. const cueTrackDuration = cueTrackItem ? getCueTrackDuration(cueTrackItem) : 0;
  16073. let position = rawPosition;
  16074. let duration = rawDuration;
  16075. if (cueTrackItem) {
  16076. position = Math.max(0, rawPosition - cueTrackStartOffset);
  16077. if (cueTrackDuration > 0) {
  16078. duration = cueTrackDuration;
  16079. } else if (cueTrackEndOffset > cueTrackStartOffset) {
  16080. duration = cueTrackEndOffset - cueTrackStartOffset;
  16081. } else if (rawDuration > cueTrackStartOffset) {
  16082. duration = rawDuration - cueTrackStartOffset;
  16083. }
  16084. if (duration > 0 && position > duration) {
  16085. position = duration;
  16086. }
  16087. }
  16088. if (duration <= 0 && this.duration > 0) {
  16089. duration = this.duration;
  16090. }
  16091. let pos = 0;
  16092. if (duration > 0) {
  16093. this.slideEnable = true;
  16094. let curPercent = position / duration;
  16095. pos = curPercent * 100;
  16096. if (shouldRefreshUi) {
  16097. if (pos > this.PROGRESS_MAX_VALUE) {
  16098. this.progressValue = this.PROGRESS_MAX_VALUE
  16099. } else {
  16100. this.progressValue = pos;
  16101. }
  16102. }
  16103. }
  16104. this.logSeekTrace('progress-tick', position, duration);
  16105. // LogUtils.getInstance()
  16106. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  16107. if (shouldRefreshUi) {
  16108. this.totalTime = this.stringForTime(duration);
  16109. }
  16110. if (position > duration) {
  16111. position = duration;
  16112. }
  16113. if (shouldRefreshUi) {
  16114. const lyricPosition = (cueTrackItem ? rawPosition : position) + this.timeOffset * 1000;
  16115. this.isCurrentTime = true;
  16116. this.updateLyricPosition(lyricPosition);
  16117. // 蓝牙歌词更新逻辑
  16118. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  16119. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  16120. // 仅在歌词行变化时更新,避免频繁调用
  16121. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  16122. this.lastBluetoothLyricLine = currentLyricLine;
  16123. this.avSessionController.updateBluetoothLyric(
  16124. currentLyricLine,
  16125. this.currentSong.name || '',
  16126. this.currentSong.artist || '',
  16127. this.bluetoothLyricMode
  16128. );
  16129. }
  16130. }
  16131. this.currentTime = this.stringForTime(position);
  16132. this.isCurrentTime = false
  16133. }
  16134. if (this.mIjkMediaPlayer.isPlaying()) {
  16135. const isCueTrackCompleted = cueTrackItem &&
  16136. cueTrackEndOffset > cueTrackStartOffset &&
  16137. rawPosition >= cueTrackEndOffset;
  16138. //如果是开启AB循环
  16139. if(this.isOpenAB){
  16140. if(position >=this.jumpBTime){
  16141. this.seekTo(this.jumpATime+'')
  16142. return
  16143. }
  16144. }
  16145. // 判断是否播放到结束时间
  16146. if ((this.isOpenJump && duration > this.jumpEndTime * 1000 &&
  16147. position >= duration - this.jumpEndTime * 1000) || isCueTrackCompleted) {
  16148. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  16149. this.CONTROL_PlayStatus = PlayStatus.INIT
  16150. this.startPlayOrResumePlay();
  16151. }else if (this.playType == 2) { //2:正常播放,单片播完
  16152. this.showRePlay();
  16153. this.currentTime = this.stringForTime(duration);
  16154. this.progressValue = this.PROGRESS_MAX_VALUE;
  16155. this.slideEnable = false;
  16156. this.stop();
  16157. // ToastUtil.showToast('开始重新播放')
  16158. }else if (this.playType == 4) { //4:连续播放不循环
  16159. // 检查是否是最后一首
  16160. if (this.curIndex >= this.songList.length - 1) {
  16161. // 已经是最后一首,停止播放
  16162. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  16163. ToastUtil.showToast('已经是最后一首了');
  16164. this.showRePlay();
  16165. this.currentTime = this.stringForTime(duration);
  16166. this.progressValue = this.PROGRESS_MAX_VALUE;
  16167. this.slideEnable = false;
  16168. this.stop();
  16169. } else {
  16170. // 不是最后一首,继续播放下一首
  16171. this.playNext().catch(() => {
  16172. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  16173. });
  16174. }
  16175. }else{
  16176. this.playNext().catch(() => {
  16177. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  16178. });
  16179. }
  16180. }
  16181. }
  16182. }
  16183. private startProgressTask() {
  16184. let that = this;
  16185. if (this.updateProgressTimer) {
  16186. clearInterval(this.updateProgressTimer);
  16187. this.updateProgressTimer = 0;
  16188. }
  16189. this.updateProgressTimer = setInterval(() => {
  16190. //LogUtils.getInstance().LOGI("startProgressTask");
  16191. if (!that.mDestroyPage) {
  16192. that.setProgress();
  16193. }
  16194. }, this.progressUpdateIntervalMs);
  16195. }
  16196. private stopProgressTask() {
  16197. LogUtils.getInstance().LOGI("stopProgressTask");
  16198. clearInterval(this.updateProgressTimer);
  16199. this.updateProgressTimer = 0;
  16200. }
  16201. private showLoadIng() {
  16202. this.isPlayerLoading = true;
  16203. this.loadingVisible = Visibility.Visible;
  16204. this.replayVisible = Visibility.None;
  16205. }
  16206. private hideLoadIng() {
  16207. this.isPlayerLoading = false;
  16208. this.loadingVisible = Visibility.None;
  16209. this.replayVisible = Visibility.None;
  16210. }
  16211. private showRePlay() {
  16212. this.isPlayerLoading = false;
  16213. this.loadingVisible = Visibility.None;
  16214. this.replayVisible = Visibility.Visible;
  16215. }
  16216. private beginRemoteSongSwitchLoading(song?: VideoItem): boolean {
  16217. const shouldShow = !!song && isRemoteCloudType(song.type);
  16218. if (shouldShow) {
  16219. this.showLoadIng();
  16220. }
  16221. return shouldShow;
  16222. }
  16223. private clearInitialSeekGuardTimer(): void {
  16224. if (this.initialSeekGuardTimer) {
  16225. clearTimeout(this.initialSeekGuardTimer);
  16226. this.initialSeekGuardTimer = 0;
  16227. }
  16228. }
  16229. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  16230. try {
  16231. if (!this.mIjkMediaPlayer.isPlaying()) {
  16232. this.mIjkMediaPlayer.start();
  16233. }
  16234. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16235. this.setIsPlaying(true);
  16236. this.updateSessionPlayState(true);
  16237. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  16238. } catch (error) {
  16239. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  16240. }
  16241. }
  16242. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  16243. this.clearInitialSeekGuardTimer();
  16244. const wasWaiting = this.waitInitialSeekBeforeStart;
  16245. this.waitInitialSeekBeforeStart = false;
  16246. this.pendingMemorySeekPosition = 0;
  16247. this.isPlayerLoading = false;
  16248. this.hideLoadIng();
  16249. if (wasWaiting) {
  16250. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  16251. }
  16252. if (shouldStart) {
  16253. this.ensurePlayerStartedAfterInitialSeek(reason);
  16254. }
  16255. }
  16256. private startInitialSeekGuardTimer(scene: string): void {
  16257. this.clearInitialSeekGuardTimer();
  16258. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  16259. return;
  16260. }
  16261. const token = this.remoteRestoreSeekToken;
  16262. this.initialSeekGuardTimer = setTimeout(() => {
  16263. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  16264. return;
  16265. }
  16266. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  16267. this.finishInitialSeekWait('seek-timeout', true);
  16268. }, this.initialSeekGuardTimeoutMs);
  16269. }
  16270. private async play(url: string,startOffset?:number) {
  16271. this.lyricController.setLyric(null)
  16272. this.lyricControllerSingle.setLyric(null)
  16273. this.lastLyricRenderPosition = Number.NaN;
  16274. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  16275. console.info('onecold this.url 1= '+url)
  16276. if(!url.toLowerCase().startsWith('http')){
  16277. let hasPermission = await PermissionUtil.activatePermission(url)
  16278. console.info('onecold this.hasPermission 1= '+hasPermission)
  16279. if(!url.includes(this.packName)){
  16280. const file = fs.openSync(url)
  16281. this.videoUrl = file.path
  16282. url= this.videoUrl
  16283. }
  16284. console.info('onecold this.hasPermission 1= '+hasPermission)
  16285. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  16286. }
  16287. let that = this;
  16288. const isBaiduStreamingPlayback = isBaiduStreamingPlaybackUrl(url);
  16289. if (this.waitInitialSeekBeforeStart) {
  16290. that.showLoadIng();
  16291. } else {
  16292. that.hideLoadIng();
  16293. }
  16294. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  16295. this.isOpenAB = false
  16296. //设置XComponent回调的context
  16297. if (!!this.mContext) {
  16298. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  16299. }
  16300. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  16301. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  16302. try {
  16303. this.mIjkMediaPlayer.reset();
  16304. Logger.info(TAG, 'IjkPlayer reset 成功');
  16305. } catch (error) {
  16306. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  16307. }
  16308. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16309. //设置debug模式(用于EQ日志采集)
  16310. this.mIjkMediaPlayer.setDebug(true);
  16311. //初始化配置
  16312. this.mIjkMediaPlayer.native_setup();
  16313. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  16314. this.applyCurrentVolume(true);
  16315. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  16316. const headers = new Map<string, string>();
  16317. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  16318. headers.set("Accept", "*/*");
  16319. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  16320. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  16321. //如果封面为空,则搜索封面
  16322. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  16323. }
  16324. // 仅对确实需要额外认证头的远程类型补充请求头。
  16325. // Navidrome/Plex/AudioStation/DaoLiYu 等类型的播放链接已自带认证参数,这里不要再误走 WebDAV 认证分支。
  16326. if (this.currentSong
  16327. && (isWebDavType(this.currentSong.type) || isJellyfinType(this.currentSong.type) || isEmbyType(this.currentSong.type))) {
  16328. Logger.info(`heanup 远程歌曲认证头构建 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  16329. if (this.currentSong.webdav_account_id) {
  16330. try {
  16331. const webdavManager = RemoteDriveManager.getInstance();
  16332. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16333. if (webDavHeaders && webDavHeaders.size > 0) {
  16334. webDavHeaders.forEach((value, key) => headers.set(key, value));
  16335. Logger.info(`heanup 成功通过webdav_account_id获取并合并远程认证头`);
  16336. } else {
  16337. Logger.warn(`heanup 通过webdav_account_id未获取到额外认证头`);
  16338. }
  16339. } catch (error) {
  16340. const err = error as Error;
  16341. Logger.error(`heanup 获取远程认证头时出错: ${err.message}`);
  16342. }
  16343. } else {
  16344. Logger.error(`heanup 远程歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法构建认证头`);
  16345. }
  16346. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  16347. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  16348. }
  16349. // 统一设置带认证的请求头
  16350. // 百度类型也需要特殊请求头
  16351. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  16352. try {
  16353. const webdavManager = RemoteDriveManager.getInstance();
  16354. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16355. baiduHeaders.forEach((value, key) => headers.set(key, value));
  16356. const headerSnapshot: Record<string, string> = {};
  16357. headers.forEach((value, key) => headerSnapshot[key] = value);
  16358. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  16359. } catch (error) {
  16360. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  16361. }
  16362. }
  16363. //设置视频源(先准备好认证头,再设置数据源)
  16364. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  16365. this.mIjkMediaPlayer.setDataSource(url);
  16366. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  16367. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  16368. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  16369. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  16370. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  16371. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  16372. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  16373. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  16374. // 缓冲和播放优化设置
  16375. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  16376. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  16377. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  16378. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  16379. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  16380. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  16381. // 网络相关设置
  16382. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  16383. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  16384. // 重连设置
  16385. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  16386. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  16387. } else if ((this.currentSong && isBaiduType(this.currentSong.type)) || isBaiduStreamingPlayback) {
  16388. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  16389. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  16390. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  16391. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  16392. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  16393. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  16394. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  16395. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  16396. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  16397. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  16398. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  16399. }
  16400. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  16401. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  16402. // }
  16403. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  16404. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  16405. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  16406. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  16407. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  16408. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  16409. //停止预读的最小帧数
  16410. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  16411. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  16412. // 设置其他缓冲相关选项
  16413. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  16414. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  16415. //启动预加载
  16416. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  16417. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  16418. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  16419. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  16420. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  16421. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  16422. // 因此需要播放器丢包,才不会累积延时
  16423. // 这个和第三个参数packet-buffering无关。
  16424. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  16425. // 无限制收流
  16426. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  16427. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  16428. // 屏幕常亮
  16429. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  16430. // 开启hls起播优化 默认是关闭的
  16431. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  16432. // 设置超时
  16433. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  16434. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  16435. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  16436. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  16437. // 变速播放
  16438. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  16439. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  16440. let Speed = this.mIjkMediaPlayer.getSpeed()
  16441. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  16442. //是否开启循环播放
  16443. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  16444. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  16445. (width: number, height: number, sar_num: number, sar_den: number) => {
  16446. if (height === 0) {
  16447. return;
  16448. }
  16449. const va = width / height;
  16450. const vpa = that.videoParentAspectRatio;
  16451. if (vpa > va) {
  16452. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  16453. } else {
  16454. that.videoWidth = '100%';
  16455. }
  16456. if (width && height) {
  16457. that.videoAspectRatio = width / height;
  16458. }
  16459. LogUtils.getInstance()
  16460. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  16461. if (!that.waitInitialSeekBeforeStart) {
  16462. that.hideLoadIng();
  16463. }
  16464. }
  16465. );
  16466. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  16467. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  16468. async () => {
  16469. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  16470. Logger.info(
  16471. TAG,
  16472. `[seek] prepared enter, waitInitial=${this.waitInitialSeekBeforeStart}, pendingMemory=${this.pendingMemorySeekPosition}, ` +
  16473. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16474. );
  16475. if (!this.waitInitialSeekBeforeStart) {
  16476. // 无记忆seek时,prepared后可直接隐藏加载
  16477. this.isPlayerLoading = false;
  16478. }
  16479. try {
  16480. //保存碰一碰分享的当前的歌曲
  16481. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  16482. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  16483. await this.initLyric(lyricPath);
  16484. const applyDuration = (durationMs: number): void => {
  16485. const cueTrackDuration = this.currentSong && isCueSplitItem(this.currentSong)
  16486. ? getCueTrackDuration(this.currentSong)
  16487. : 0;
  16488. const effectiveDuration = cueTrackDuration > 0 ? cueTrackDuration : durationMs;
  16489. if (effectiveDuration <= 0) {
  16490. return;
  16491. }
  16492. this.duration = effectiveDuration;
  16493. this.durationTime = Math.floor(effectiveDuration / 1000);
  16494. this.durationStringTime = secondToTime(this.durationTime);
  16495. this.totalTime = this.stringForTime(effectiveDuration);
  16496. if (this.currentSong) {
  16497. this.currentSong.duration = this.totalTime;
  16498. try {
  16499. this.avSessionController.setAVMetadataMusic(this.currentSong, effectiveDuration, this.lyricContent);
  16500. } catch (metaError) {
  16501. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  16502. }
  16503. }
  16504. };
  16505. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  16506. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  16507. return 0;
  16508. }
  16509. const httpRequest = http.createHttp();
  16510. try {
  16511. const response = await httpRequest.request(url, {
  16512. method: http.RequestMethod.GET,
  16513. connectTimeout: 8000,
  16514. readTimeout: 8000,
  16515. expectDataType: http.HttpDataType.STRING,
  16516. header: {
  16517. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  16518. 'Host': 'pan.baidu.com',
  16519. 'Referer': 'https://pan.baidu.com/disk/home',
  16520. 'Accept-Encoding': 'identity'
  16521. }
  16522. });
  16523. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  16524. return 0;
  16525. }
  16526. const text = response.result;
  16527. if (text.indexOf('#EXTM3U') < 0) {
  16528. return 0;
  16529. }
  16530. const lines = text.split('\n');
  16531. let totalSeconds = 0;
  16532. for (let i = 0; i < lines.length; i++) {
  16533. const line = lines[i].trim();
  16534. if (line.startsWith('#EXTINF:')) {
  16535. const colonIndex = line.indexOf(':');
  16536. if (colonIndex < 0) {
  16537. continue;
  16538. }
  16539. const content = line.substring(colonIndex + 1);
  16540. const commaIndex = content.indexOf(',');
  16541. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  16542. const seconds = Number(numberPart);
  16543. if (!Number.isNaN(seconds) && seconds > 0) {
  16544. totalSeconds += seconds;
  16545. }
  16546. }
  16547. }
  16548. if (totalSeconds > 0) {
  16549. return Math.floor(totalSeconds * 1000);
  16550. }
  16551. return 0;
  16552. } catch (fetchError) {
  16553. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  16554. return 0;
  16555. } finally {
  16556. httpRequest.destroy();
  16557. }
  16558. };
  16559. const fetchDurationFallback = async (): Promise<void> => {
  16560. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16561. if (durationMs > 0) {
  16562. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  16563. applyDuration(durationMs);
  16564. return;
  16565. }
  16566. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  16567. };
  16568. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  16569. Logger.info(
  16570. TAG,
  16571. `[seek] prepared duration snapshot, playerDuration=${preparedDuration}, metaDuration=${this.currentSong?.duration ?? ''}, ` +
  16572. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16573. );
  16574. if (preparedDuration > 0) {
  16575. applyDuration(preparedDuration);
  16576. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  16577. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16578. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  16579. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  16580. applyDuration(durationMs);
  16581. }
  16582. }
  16583. } else {
  16584. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  16585. if (metaDurationMs > 0) {
  16586. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  16587. applyDuration(metaDurationMs);
  16588. } else {
  16589. fetchDurationFallback();
  16590. }
  16591. }
  16592. setTimeout(() => {
  16593. this.avSessionController.initAvSession(false);
  16594. if (this.duration > 0) {
  16595. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  16596. }
  16597. this.setAvSessionListener();
  16598. this.updateSessionPlayState(true)
  16599. this.setCurrentPlayMode()
  16600. const cueTrackStartOffset = this.currentSong && isCueSplitItem(this.currentSong)
  16601. ? getCueTrackStartOffset(this.currentSong)
  16602. : 0;
  16603. if ((startOffset && startOffset > 0) || cueTrackStartOffset > 0) {//cue分轨播放
  16604. const cueSeekValue = cueTrackStartOffset > 0 && (!startOffset || startOffset <= 0) ? 0 : startOffset;
  16605. this.seekTo((cueSeekValue || 0) + "");
  16606. this.saveLastPlayList()
  16607. return
  16608. }
  16609. }, 500)
  16610. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16611. let timeoutPlay = 0
  16612. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16613. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  16614. timeoutPlay = 400
  16615. }
  16616. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  16617. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  16618. timeoutPlay = Math.max(timeoutPlay,
  16619. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  16620. }
  16621. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  16622. if (this.modeType === 0) { //文件夹
  16623. let parentPath = FileUtil.getParentPath(this.videoUrl)
  16624. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  16625. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  16626. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  16627. } else if (this.modeType === 1) { //媒体库
  16628. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  16629. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  16630. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  16631. } else if (this.modeType === 2) { //艺术家
  16632. if (this.currentSong?.artist) {
  16633. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  16634. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  16635. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  16636. }
  16637. } else if (this.modeType === 3) { //专辑
  16638. if (this.currentSong?.album) {
  16639. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  16640. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  16641. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  16642. }
  16643. }
  16644. const playerDuration = this.mIjkMediaPlayer.getDuration()
  16645. if (playerDuration > 0 && (!this.currentSong || !isCueSplitItem(this.currentSong))) {
  16646. this.duration = playerDuration
  16647. }
  16648. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  16649. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  16650. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  16651. let targetSeekPosition = memoryPosition;
  16652. if (this.isOpenJump) {
  16653. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  16654. }
  16655. this.pendingMemorySeekPosition = targetSeekPosition;
  16656. this.startInitialSeekGuardTimer('prepared-memory-seek');
  16657. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  16658. setTimeout(() => {
  16659. if (!this.waitInitialSeekBeforeStart) {
  16660. return;
  16661. }
  16662. this.restorePlaybackPosition();
  16663. }, timeoutPlay);
  16664. this.isFirstStartPlay = false
  16665. this.saveLastPlayList()
  16666. return
  16667. }
  16668. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  16669. if (this.mIjkMediaPlayer != null) {
  16670. let jumpTopTimeMs = this.jumpTopTime*1000;
  16671. if (jumpTopTimeMs <= this.duration) {
  16672. // 调用 seekTo 方法,跳到指定时间
  16673. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16674. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16675. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  16676. }
  16677. }, timeoutPlay)
  16678. } else {
  16679. // 提示用户无法跳过
  16680. ToastUtil.showToast('跳过时间超过视频时长');
  16681. }
  16682. }
  16683. } else {
  16684. this.jumpTopTime = 0
  16685. this.jumpEndTime = 0
  16686. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  16687. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  16688. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  16689. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  16690. //记忆播放(每一首都会记忆播放)
  16691. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16692. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16693. if (this.pendingMemorySeekPosition > 0 ||
  16694. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  16695. this.restorePlaybackPosition() //读取播放记忆功能
  16696. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  16697. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  16698. this.restorePlaybackPosition() //读取播放记忆功能
  16699. }
  16700. this.isFirstStartPlay = false
  16701. }, timeoutPlay)
  16702. } else {
  16703. this.isFirstStartPlay = false
  16704. }
  16705. }
  16706. this.saveLastPlayList()
  16707. } catch (error) {
  16708. let err: BusinessError = error as BusinessError;
  16709. console.error('onecold failed with err: ' + JSON.stringify(err));
  16710. if (this.waitInitialSeekBeforeStart) {
  16711. this.finishInitialSeekWait('prepared-exception', true);
  16712. }
  16713. }
  16714. }
  16715. );
  16716. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  16717. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  16718. (text: string) => {
  16719. }
  16720. );
  16721. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  16722. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  16723. () => {
  16724. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  16725. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  16726. // 异步调用playNext
  16727. this.playNext().catch(() => {
  16728. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16729. });
  16730. } else if (this.playType == 1) { //1:单片重复播放
  16731. this.CONTROL_PlayStatus = PlayStatus.INIT
  16732. that.startPlayOrResumePlay();
  16733. } else if (this.playType == 2) { //2:正常播放,单曲播完
  16734. that.showRePlay();
  16735. that.currentTime = that.stringForTime(that.getActiveDuration());
  16736. that.progressValue = this.PROGRESS_MAX_VALUE;
  16737. that.slideEnable = false;
  16738. that.stop();
  16739. // ToastUtil.showToast('开始重新播放')
  16740. } else if (this.playType == 3) { //3:随机播放
  16741. // 异步调用randomPlay
  16742. this.randomPlay().catch(() => {
  16743. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  16744. });
  16745. } else if (this.playType == 4) { //4:连续播放不循环
  16746. // 异步调用playNext
  16747. this.playNext().catch(() => {
  16748. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16749. });
  16750. }
  16751. }
  16752. );
  16753. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  16754. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  16755. (percent: number) => {
  16756. if (this.isDebug) {
  16757. const now = Date.now();
  16758. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  16759. this.lastBufferingLogTs = now;
  16760. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  16761. }
  16762. }
  16763. }
  16764. );
  16765. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  16766. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  16767. () => {
  16768. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  16769. that.logSeekTrace('seek-complete', undefined, undefined, true);
  16770. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  16771. setTimeout(() => {
  16772. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  16773. that.isSeekTo = false;
  16774. if (waitingInitialSeek) {
  16775. that.finishInitialSeekWait('seek-complete', true);
  16776. } else {
  16777. that.hideLoadIng();
  16778. }
  16779. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  16780. }
  16781. );
  16782. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  16783. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  16784. (what: number, extra: number) => {
  16785. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  16786. if (that.isSeekTraceActive()) {
  16787. Logger.info(
  16788. TAG,
  16789. `[seek] onInfo what=${what}, extra=${extra}, source=${that.lastSeekSource || 'unknown'}, ` +
  16790. `req=${that.lastSeekRequestMs}, url=${that.sanitizePlaybackUrl(that.videoUrl)}`
  16791. );
  16792. that.logSeekTrace(`info-${what}`, undefined, undefined, true);
  16793. }
  16794. if (!that.waitInitialSeekBeforeStart) {
  16795. that.hideLoadIng();
  16796. }
  16797. }
  16798. );
  16799. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  16800. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  16801. (what: number, extra: number) => {
  16802. this.finishInitialSeekWait('player-error', false);
  16803. this.stopProgressTask();
  16804. this.logSeekTrace(`error-${what}-${extra}`, undefined, undefined, true);
  16805. Logger.error(
  16806. TAG,
  16807. `[seek] onError what=${what}, extra=${extra}, url=${this.sanitizePlaybackUrl(this.videoUrl)}, ` +
  16808. `song=${JSON.stringify(this.currentSong)}`
  16809. );
  16810. // 检查是否为WebDAV播放错误
  16811. let isWebDavError = false;
  16812. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  16813. try {
  16814. const globalContext = GlobalContext.getContext();
  16815. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  16816. if (webDavAuthInfo) {
  16817. isWebDavError = true;
  16818. }
  16819. } catch (error) {
  16820. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  16821. }
  16822. }
  16823. if (isWebDavError) {
  16824. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  16825. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  16826. // this.currentWebDavAuthInfo = null;
  16827. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  16828. // 根据错误代码提供更具体的错误信息
  16829. let errorMessage = "WebDAV播放失败";
  16830. if (what === -1) { // 网络错误
  16831. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  16832. } else if (what === -1004) { // HTTP 404
  16833. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  16834. } else if (what === -1001) { // 超时
  16835. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  16836. } else if (what === -1003) { // 无法解析主机
  16837. errorMessage = "无法连接到WebDAV服务器";
  16838. }
  16839. ToastUtil.showToast(errorMessage);
  16840. } else {
  16841. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16842. !this.videoUrl.startsWith('http') &&
  16843. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  16844. !FileUtil.accessSync(this.videoUrl)) {
  16845. console.info('heanup 播放.文件不存在');
  16846. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  16847. }
  16848. }
  16849. that.hideLoadIng();
  16850. }
  16851. );
  16852. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  16853. this.mIjkMediaPlayer.setMessageListener();
  16854. // 应用均衡器设置
  16855. try {
  16856. const equalizerManager = EqualizerManager.getInstance();
  16857. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  16858. Logger.info(TAG, 'heanup 均衡器设置已应用');
  16859. this.markEqualizerApplied();
  16860. } catch (eqError) {
  16861. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  16862. this.eqApplying = false;
  16863. }
  16864. this.mIjkMediaPlayer.prepareAsync();
  16865. this.mIjkMediaPlayer.start();
  16866. }
  16867. //保存最后播放的那首歌和已经对应的播放列表
  16868. saveLastPlayList() {
  16869. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  16870. // 新队列刚刚完成落盘时,首帧 prepared 会立刻再进一次这里,跳过这次重复写入即可。
  16871. if (this.skipNextPlaylistPersist) {
  16872. this.skipNextPlaylistPersist = false
  16873. } else {
  16874. PreferencesUtil.putSync('LastMusicList', this.songList)
  16875. }
  16876. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  16877. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  16878. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  16879. }
  16880. // 清空播放记录
  16881. clearVideoHistory() {
  16882. this.table.clearPlayHistory((success: boolean, error?: string) => {
  16883. if (success) {
  16884. this.historyList = [];
  16885. this.updateListData(this.historyList)
  16886. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  16887. ToastUtil.showToast('清空播放记录成功')
  16888. } else {
  16889. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  16890. }
  16891. });
  16892. }
  16893. public async setAvSessionListener() {
  16894. if (!this.avSessionController) {
  16895. return;
  16896. }
  16897. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  16898. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  16899. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  16900. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  16901. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  16902. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  16903. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  16904. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  16905. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  16906. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  16907. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  16908. }
  16909. setLoopMode() {
  16910. let itype = this.playType + 1
  16911. if (itype >= 5) {
  16912. this.playType = 0
  16913. ToastUtil.showToast('连续循环播放')
  16914. } else if (itype === 1) {
  16915. this.playType = 1
  16916. ToastUtil.showToast('单曲循环')
  16917. } else if (itype === 2) {
  16918. this.playType = 2
  16919. ToastUtil.showToast('单曲播完')
  16920. } else if (itype === 3) {
  16921. this.playType = 3
  16922. ToastUtil.showToast('随机播放')
  16923. } else if (itype === 4) {
  16924. this.playType = 4
  16925. ToastUtil.showToast('连续播放不循环')
  16926. } else if (itype === 0) {
  16927. this.playType = 0
  16928. ToastUtil.showToast('连续循环播放')
  16929. }
  16930. PreferencesUtil.putSync('musicPlayType', this.playType)
  16931. this.setCurrentPlayMode()
  16932. }
  16933. private sessionSetLoopModeCallback = (mode: number) => {
  16934. if (this.mIjkMediaPlayer != null) {
  16935. ToastUtil.showToast('当前播放模式:' + mode)
  16936. Logger.info('onecold 当前播放模式= ' + mode)
  16937. let hmPlayMode = mode + 1
  16938. if (hmPlayMode >= 4) {
  16939. hmPlayMode = 0
  16940. }
  16941. if (hmPlayMode === 1) {
  16942. this.playType = 1
  16943. ToastUtil.showToast('单曲循环')
  16944. } else if (hmPlayMode === 0) {
  16945. this.playType = 2
  16946. ToastUtil.showToast('单曲播完')
  16947. } else if (hmPlayMode === 3) {
  16948. this.playType = 3
  16949. ToastUtil.showToast('随机播放')
  16950. } else if (hmPlayMode === 2) {
  16951. this.playType = 0
  16952. ToastUtil.showToast('连续循环播放')
  16953. } else if (hmPlayMode === 4) {
  16954. this.playType = 4
  16955. ToastUtil.showToast('连续播放不循环')
  16956. }
  16957. PreferencesUtil.putSync('musicPlayType', this.playType)
  16958. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  16959. let playBackState: avSession.AVPlaybackState = {
  16960. loopMode: hmPlayMode,
  16961. };
  16962. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  16963. console.info(`set setLoopMode AVPlaybackState successfully`);
  16964. }).catch((err: BusinessError) => {
  16965. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16966. });
  16967. }
  16968. }
  16969. setCurrentPlayMode() {
  16970. if (!this.avSessionController) {
  16971. return;
  16972. }
  16973. let mLoopMode = 0
  16974. switch (this.playType) {
  16975. case 0:
  16976. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  16977. break;
  16978. case 1:
  16979. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  16980. break;
  16981. case 2:
  16982. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  16983. break;
  16984. case 3:
  16985. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  16986. break;
  16987. case 4:
  16988. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  16989. break;
  16990. }
  16991. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  16992. let playBState: avSession.AVPlaybackState = {
  16993. loopMode: mLoopMode,
  16994. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  16995. };
  16996. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  16997. console.info(`set setLoopMode AVPlaybackState successfully`);
  16998. }).catch((err: BusinessError) => {
  16999. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  17000. });
  17001. }
  17002. private applyRequestedPlayType(playType: number): void {
  17003. if (playType < 0 || playType > 4 || this.playType === playType) {
  17004. return
  17005. }
  17006. this.playType = playType
  17007. PreferencesUtil.putSync('musicPlayType', this.playType)
  17008. this.setCurrentPlayMode()
  17009. }
  17010. private sessionToggleFavoriteCallback = (assetId: string) => {
  17011. if (this.mIjkMediaPlayer != null && this.currentSong) {
  17012. console.info(`on toggleFavorite `);
  17013. // 应用收到收藏命令,进行收藏处理。
  17014. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  17015. this.doFav(this.currentSong)
  17016. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  17017. let playbackState: avSession.AVPlaybackState = {
  17018. isFavorite: !this.isFac,
  17019. };
  17020. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  17021. console.info(`SetAVPlaybackState successfully`);
  17022. }).catch((err: BusinessError) => {
  17023. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  17024. });
  17025. }
  17026. }
  17027. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  17028. device: avSession.OutputDeviceInfo) => {
  17029. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  17030. // 将 connectState 转换为可读的字符串
  17031. let stateName = 'UNKNOWN';
  17032. switch (connectState) {
  17033. case avSession.ConnectionState.STATE_CONNECTED:
  17034. stateName = 'CONNECTED(1)';
  17035. break;
  17036. case avSession.ConnectionState.STATE_DISCONNECTED:
  17037. stateName = 'DISCONNECTED(2)';
  17038. break;
  17039. case avSession.ConnectionState.STATE_CONNECTING:
  17040. stateName = 'CONNECTING(3)';
  17041. break;
  17042. default:
  17043. stateName = `OTHER(${connectState})`;
  17044. }
  17045. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  17046. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  17047. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  17048. await this.startCasting();
  17049. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  17050. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  17051. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  17052. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  17053. if (device) {
  17054. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  17055. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  17056. this.endCasting();
  17057. }
  17058. }
  17059. };
  17060. private async startCasting() {
  17061. try {
  17062. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  17063. // 获取原始的 AVCastController
  17064. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  17065. if (!avCastCtrl) {
  17066. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  17067. return;
  17068. }
  17069. this.castController = avCastCtrl;
  17070. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  17071. // 创建新的 CastController 封装器
  17072. this.castControllerWrapper = new CastController(avCastCtrl);
  17073. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  17074. // 设置回调函数
  17075. let callbacks: CastControllerCallbacks = {
  17076. onPlayNext: () => {
  17077. Logger.info('heanup CastController', '收到 playNext 回调');
  17078. this.playNext();
  17079. },
  17080. onPlayPrevious: () => {
  17081. Logger.info('heanup CastController', '收到 playPrevious 回调');
  17082. this.playPrevious();
  17083. },
  17084. onPositionChanged: (position: number) => {
  17085. this.positionChange(position);
  17086. },
  17087. onDurationChanged: (duration: number) => {
  17088. this.playDurationChange(duration);
  17089. }
  17090. };
  17091. this.castControllerWrapper.setCallbacks(callbacks);
  17092. Logger.info('heanup startCasting', '✅ 设置回调成功');
  17093. // 暂停本地播放
  17094. this.pause();
  17095. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  17096. // 初始化投播会话
  17097. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  17098. await this.castControllerWrapper.initAVCast(
  17099. this.songList,
  17100. this.curIndex,
  17101. this.mIjkMediaPlayer.getCurrentPosition(),
  17102. this.videoUrl,
  17103. this.getActiveDuration()
  17104. );
  17105. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  17106. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  17107. refToIsCasting?.set(true);
  17108. this.castSeek = true;
  17109. // 从 CastController 获取投播状态
  17110. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17111. if (this.isCastPlaying) {
  17112. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  17113. this.setIsPlaying(true);
  17114. this.updateSessionPlayState(true);
  17115. }
  17116. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  17117. } catch (error) {
  17118. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  17119. }
  17120. }
  17121. async changeCasting() {
  17122. Logger.info('heanup changeCasting', '切换投播');
  17123. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  17124. this.initQueueItem();
  17125. await this.prepare();
  17126. this.setPlaybackStateChangeListener();
  17127. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  17128. this.castSeek = true;
  17129. }
  17130. public endCasting() {
  17131. Logger.info('heanup endCasting', 'endCasting被调用');
  17132. this.avSessionController.getAvSession()?.stopCasting();
  17133. this.stopCast();
  17134. // 关闭文件描述符
  17135. if (this.castFile) {
  17136. try {
  17137. fs.closeSync(this.castFile);
  17138. this.castFile = undefined;
  17139. Logger.info('heanup endCasting', '关闭投播文件描述符');
  17140. } catch (error) {
  17141. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  17142. }
  17143. }
  17144. this.isCastPlaying = false;
  17145. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  17146. refToIsCasting?.set(false);
  17147. this.pause();
  17148. this.setIsPlaying(false);
  17149. // if (this.curIndex === this.curSource.index) {
  17150. // this.play
  17151. // this.seek(this.currentTime * 1000);
  17152. // this.setIsPlaying(true);
  17153. // } else {
  17154. // this.pauseVideo();
  17155. // this.setIsPlaying(false);
  17156. // }
  17157. }
  17158. public setIsPlaying(isPlayer: boolean) {
  17159. this.isPlaying = isPlayer;
  17160. // 发送播放状态变化事件给歌单详情页面
  17161. try {
  17162. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  17163. const currentFilePath = this.currentSong?.filePath || ''
  17164. const eventData: emitter.EventData = {
  17165. data: {
  17166. isPlaying: this.isPlaying,
  17167. curIndex: this.curIndex,
  17168. currentFilePath: currentFilePath
  17169. }
  17170. };
  17171. emitter.emit(eventPlaybackStatus, eventData)
  17172. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  17173. } catch (error) {
  17174. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  17175. }
  17176. }
  17177. private setPlaybackStateChangeListener(): void {
  17178. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  17179. // 我们需要通过其他方式来判断播放状态
  17180. // 1. 监听位置变化
  17181. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  17182. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  17183. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  17184. this.positionChange(playbackState.position.elapsedTime);
  17185. }
  17186. });
  17187. // 2. 监听时长变化
  17188. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  17189. const duration = playbackState?.extras?.duration;
  17190. if (typeof duration === 'number') {
  17191. this.playDurationChange(duration);
  17192. }
  17193. });
  17194. // 3. 监听所有状态变化(用于调试和状态判断)
  17195. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  17196. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  17197. // 检查是否有 state 字段(某些设备可能返回)
  17198. if (playbackState.state !== undefined) {
  17199. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  17200. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  17201. this.isCastPlaying = true;
  17202. }
  17203. }
  17204. });
  17205. // 4. 监听播放完成事件
  17206. this.castController?.on('endOfStream', this.playNextCallback);
  17207. this.castController?.on('playNext', this.playNextCallback);
  17208. this.castController?.on('playPrevious', this.playPreviousCallback);
  17209. // 5. 监听错误事件
  17210. this.castController?.on('error', (error: BusinessError) => {
  17211. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  17212. this.isCastPlaying = false;
  17213. });
  17214. }
  17215. private updateSessionPlayState(isPlay: boolean): void {
  17216. // if(!this.isBgPlayOpen)
  17217. // return
  17218. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  17219. : this.mIjkMediaPlayer.getCurrentPosition();
  17220. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  17221. this.setAVSessionPlayState({
  17222. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  17223. position: {
  17224. elapsedTime: elapsedTime,
  17225. updateTime: new Date().getTime()
  17226. }
  17227. });
  17228. }
  17229. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  17230. this.avSessionController.setAvSessionPlayState(playbackState)
  17231. }
  17232. private positionChange(position: number) {
  17233. this.currentTime2 = position / 1000;
  17234. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  17235. if (this.castControllerWrapper && this.isCastPlaying) {
  17236. this.updateCastProgress(position);
  17237. if (this.isSeekTo) {
  17238. this.isSeekTo = false;
  17239. }
  17240. }
  17241. }
  17242. private playDurationChange(duration: number) {
  17243. this.duration = duration;
  17244. this.durationTime = Math.floor(this.duration / 1000);
  17245. this.durationStringTime = secondToTime((this.durationTime));
  17246. if (this.castControllerWrapper && this.isCastPlaying) {
  17247. this.totalTime = this.stringForTime(this.duration);
  17248. }
  17249. }
  17250. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  17251. private reloadCasting = async () => {
  17252. Logger.info('heanup reloadCasting', '重新加载投播');
  17253. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  17254. this.initQueueItem();
  17255. await this.prepare();
  17256. };
  17257. public playNextCallback = (): void => {
  17258. this.playNext().catch(() => {
  17259. Logger.error('heanup playNextCallback', `播放下一首失败`);
  17260. });
  17261. };
  17262. public playPreviousCallback = (): void => {
  17263. this.playPrevious().catch(() => {
  17264. Logger.error('heanup playNextCallback', `播放上一首失败`);
  17265. });
  17266. };
  17267. async prepare() {
  17268. try {
  17269. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  17270. await this.castController?.prepare(this.castItem);
  17271. Logger.info('heanup prepare', '投播prepare成功');
  17272. await this.castController?.start(this.castItem);
  17273. Logger.info('heanup prepare', '投播start成功');
  17274. // 投播启动成功,设置为投播状态
  17275. this.isCastPlaying = true;
  17276. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  17277. } catch (error) {
  17278. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  17279. this.isCastPlaying = false;
  17280. }
  17281. }
  17282. public initQueueItem() {
  17283. let item = this.songList[this.curIndex];
  17284. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  17285. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  17286. let isStreaming = this.isUrl(this.videoUrl);
  17287. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  17288. // 关闭之前的文件描述符
  17289. if (this.castFile) {
  17290. try {
  17291. fs.closeSync(this.castFile);
  17292. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  17293. } catch (error) {
  17294. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  17295. }
  17296. }
  17297. let description: avSession.AVMediaDescription = {
  17298. assetId: 'AUDIO-' + item.filePath,
  17299. title: item.name,
  17300. artist: item.artist || '',
  17301. // 该字段大写,音频'AUDIO',视频'VIDEO'
  17302. mediaType: 'AUDIO',
  17303. mediaSize: item.videoSize,
  17304. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  17305. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  17306. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  17307. duration: this.duration,
  17308. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  17309. appName: this.appName,
  17310. lyricContent: item.lyricContent,
  17311. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  17312. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  17313. };
  17314. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  17315. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  17316. if (isStreaming) {
  17317. // 流媒体地址使用 mediaUri
  17318. description.mediaUri = this.videoUrl;
  17319. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  17320. } else {
  17321. // 本地文件使用 fdSrc
  17322. const localPath = this.videoUrl || item.filePath;
  17323. let uri = fileUri.getUriFromPath(localPath);
  17324. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  17325. let fdSrc: media.AVFileDescriptor = {
  17326. fd: this.castFile.fd
  17327. };
  17328. description.fdSrc = fdSrc;
  17329. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  17330. }
  17331. this.castItem = {
  17332. itemId: this.curIndex,
  17333. description: description
  17334. };
  17335. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  17336. title: description.title,
  17337. mediaType: description.mediaType,
  17338. hasMediaUri: !!description.mediaUri,
  17339. hasFdSrc: !!description.fdSrc,
  17340. duration: description.duration
  17341. })}`);
  17342. }
  17343. // 判断是否是 URL 或流媒体地址
  17344. private isUrl(str: string): boolean {
  17345. if (!str) {
  17346. return false;
  17347. }
  17348. // 检查常见的流媒体协议
  17349. if (str.startsWith('http://') || str.startsWith('https://') ||
  17350. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  17351. str.startsWith('rtp://') || str.startsWith('mms://')) {
  17352. return true;
  17353. }
  17354. // 扩展的URL正则表达式,支持多种协议
  17355. const urlPattern = new RegExp(
  17356. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  17357. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  17358. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  17359. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  17360. 'localhost)' + // 或localhost
  17361. '(\\:\\d+)?' + // 端口号(可选)
  17362. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  17363. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  17364. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  17365. 'i' // 不区分大小写
  17366. );
  17367. return urlPattern.test(str);
  17368. }
  17369. async stopCast() {
  17370. try {
  17371. // 使用 CastController 释放资源
  17372. if (this.castControllerWrapper) {
  17373. await this.castControllerWrapper.releaseAVCast();
  17374. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  17375. }
  17376. // 清空引用
  17377. this.castControllerWrapper = undefined;
  17378. this.castController = undefined;
  17379. this.castItem = undefined;
  17380. this.castFile = undefined;
  17381. } catch (error) {
  17382. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  17383. }
  17384. }
  17385. private sessionPlayCallback = (): void => {
  17386. this.playOrPause()
  17387. };
  17388. private sessionPauseCallback = (): void => {
  17389. this.pause()
  17390. };
  17391. private async playOrPause() {
  17392. if (!this.debounce()) {
  17393. return;
  17394. }
  17395. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17396. await this.pause();
  17397. } else {
  17398. // 如果是投播模式,使用 CastController 的 play 方法
  17399. if (this.castControllerWrapper && this.isCastPlaying) {
  17400. try {
  17401. Logger.info('heanup playOrPause', '投播模式播放');
  17402. await this.castControllerWrapper.setPlaying();
  17403. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  17404. this.setIsPlaying(true);
  17405. this.updateSessionPlayState(true);
  17406. Logger.info('heanup playOrPause', '投播播放成功');
  17407. this.playChange();
  17408. } catch (error) {
  17409. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  17410. }
  17411. } else {
  17412. console.info('onecold startPlayOrResumePlay 11064')
  17413. this.startPlayOrResumePlay();
  17414. this.playChange()
  17415. }
  17416. }
  17417. }
  17418. private sessionPlayNextCallback = (): void => {
  17419. this.playNext().catch(() => {
  17420. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  17421. });
  17422. };
  17423. private sessionPlayPreviousCallback = (): void => {
  17424. this.playPrevious().catch(() => {
  17425. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  17426. });
  17427. };
  17428. private sessionStopCallback = (): void => {
  17429. this.stop()
  17430. };
  17431. private sessionFastForwardCallback = async (time?: number) => {
  17432. if (!time) {
  17433. return;
  17434. }
  17435. let curPosition: number;
  17436. if (this.castController && this.isCastPlaying) {
  17437. // 投播模式,使用UI显示的时间
  17438. curPosition = this.currentTime2 * 1000;
  17439. } else if (this.mIjkMediaPlayer != null) {
  17440. // 本地播放器模式
  17441. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17442. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17443. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17444. }
  17445. } else {
  17446. return;
  17447. }
  17448. let seeTime = curPosition + time * 1000;
  17449. // 限制 seekValue 在合法范围内
  17450. if (seeTime < 0) {
  17451. seeTime = 0;
  17452. } else if (seeTime > this.duration) {
  17453. seeTime = this.duration;
  17454. }
  17455. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  17456. this.setSeekToActionProgress(seeTime);
  17457. await this.seekTo(seeTime + "", 'session-fast-forward');
  17458. };
  17459. private getActiveDuration(): number {
  17460. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17461. const cueDuration = getCueTrackDuration(this.currentSong);
  17462. if (cueDuration > 0) {
  17463. return cueDuration;
  17464. }
  17465. }
  17466. let duration = this.mIjkMediaPlayer.getDuration();
  17467. if (this.castControllerWrapper && this.isCastPlaying) {
  17468. return this.duration > 0 ? this.duration : duration;
  17469. }
  17470. if (duration <= 0 && this.duration > 0) {
  17471. duration = this.duration;
  17472. }
  17473. return duration;
  17474. }
  17475. @Builder
  17476. InlineSpectrumView() {
  17477. SpectrumView({
  17478. isVisible: this.currentSwiperIndex === 0,
  17479. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  17480. })
  17481. .width( '83%')
  17482. .height(this.isCoverOpacity() ? 80 : 100)
  17483. .margin({bottom: 3 })
  17484. .clip(true)
  17485. .zIndex(-2)
  17486. .onClick(()=>{
  17487. this.cycleSpectrumMode();
  17488. })
  17489. }
  17490. private cycleSpectrumMode(): void {
  17491. const modeNames: string[] = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  17492. if (modeNames.length <= 0) {
  17493. return;
  17494. }
  17495. const nextIndex: number = (this.spectrumModeIndex + 1) % modeNames.length;
  17496. this.spectrumModeIndex = nextIndex;
  17497. PreferencesUtil.putSync('spectrumModeIndex', nextIndex);
  17498. AppStorage.setOrCreate<number>('spectrumMode', nextIndex);
  17499. Logger.info('heanup-LocalMusic', `频谱特效已顺序切换为: ${modeNames[nextIndex]}`);
  17500. }
  17501. private getSongDurationMs(song?: VideoItem): number {
  17502. if (!song || !song.duration) {
  17503. return 0;
  17504. }
  17505. const raw = song.duration.trim();
  17506. if (!raw) {
  17507. return 0;
  17508. }
  17509. const parts = raw.split(':').map((part) => Number(part));
  17510. if (parts.some((part) => Number.isNaN(part))) {
  17511. return 0;
  17512. }
  17513. let seconds = 0;
  17514. if (parts.length === 3) {
  17515. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  17516. } else if (parts.length === 2) {
  17517. seconds = parts[0] * 60 + parts[1];
  17518. } else if (parts.length === 1) {
  17519. seconds = parts[0];
  17520. }
  17521. return seconds > 0 ? seconds * 1000 : 0;
  17522. }
  17523. private updateCastProgress(position: number): void {
  17524. const duration = this.getActiveDuration();
  17525. if (duration <= 0) {
  17526. return;
  17527. }
  17528. this.slideEnable = true;
  17529. let pos = (position / duration) * 100;
  17530. if (pos > this.PROGRESS_MAX_VALUE) {
  17531. this.progressValue = this.PROGRESS_MAX_VALUE;
  17532. } else if (pos < 0) {
  17533. this.progressValue = 0;
  17534. } else {
  17535. this.progressValue = pos;
  17536. }
  17537. this.totalTime = this.stringForTime(duration);
  17538. if (position > duration) {
  17539. position = duration;
  17540. }
  17541. this.isCurrentTime = true;
  17542. this.currentTime = this.stringForTime(position);
  17543. this.isCurrentTime = false;
  17544. const lyricPosition = position + this.timeOffset * 1000;
  17545. this.updateLyricPosition(lyricPosition);
  17546. }
  17547. /**
  17548. * Gesture method onActionUpdate.
  17549. *
  17550. * @param event Gesture event.手势拖动设置快进和后退
  17551. */
  17552. private setSeekToActionProgress(position: number) {
  17553. // 投播模式使用this.duration,本地模式使用播放器获取
  17554. let duration = this.getActiveDuration();
  17555. let pos = 0;
  17556. if (duration > 0) {
  17557. this.slideEnable = true;
  17558. let curPercent = position / duration;
  17559. pos = curPercent * 100;
  17560. if (pos > this.PROGRESS_MAX_VALUE) {
  17561. this.progressValue = this.PROGRESS_MAX_VALUE
  17562. } else {
  17563. this.progressValue = pos;
  17564. }
  17565. }
  17566. // LogUtils.getInstance()
  17567. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  17568. this.totalTime = this.stringForTime(duration);
  17569. if (position > duration) {
  17570. position = duration;
  17571. }
  17572. this.isCurrentTime = true;
  17573. this.currentTime = this.stringForTime(position);
  17574. this.isCurrentTime = false
  17575. }
  17576. private sessionRewindCallback = async (time?: number) => {
  17577. if (!time) {
  17578. return;
  17579. }
  17580. let curPosition: number;
  17581. if (this.castController && this.isCastPlaying) {
  17582. // 投播模式,使用UI显示的时间
  17583. curPosition = this.currentTime2 * 1000;
  17584. } else if (this.mIjkMediaPlayer != null) {
  17585. // 本地播放器模式
  17586. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17587. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17588. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17589. }
  17590. } else {
  17591. return;
  17592. }
  17593. let seeTime = curPosition - time * 1000;
  17594. // 限制 seekValue 在合法范围内
  17595. if (seeTime < 0) {
  17596. seeTime = 0;
  17597. } else if (seeTime > this.duration) {
  17598. seeTime = this.duration;
  17599. }
  17600. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  17601. this.setSeekToActionProgress(seeTime);
  17602. await this.seekTo(seeTime + "", 'session-rewind');
  17603. };
  17604. private sessionSeekCallback = async (seekTime: number) => {
  17605. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  17606. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  17607. await this.seekTo(seekTime + "", 'session-seek');
  17608. };
  17609. private async getFileSize(filePath: string): Promise<number> {
  17610. try {
  17611. const stat = await fs.stat(filePath);
  17612. return stat.size;
  17613. } catch (err) {
  17614. console.error('Failed to get file size: ' + err.message);
  17615. return 0;
  17616. }
  17617. }
  17618. private async pause(clearInterruptResumeFlag: boolean = true) {
  17619. if (clearInterruptResumeFlag) {
  17620. this.audioInterruptResumePending = false;
  17621. }
  17622. // 如果是投播模式,使用 CastController 的 pause 方法
  17623. if (this.castControllerWrapper && this.isCastPlaying) {
  17624. try {
  17625. Logger.info('heanup pause', '投播模式暂停');
  17626. await this.castControllerWrapper.setPause();
  17627. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17628. this.setIsPlaying(false);
  17629. this.updateSessionPlayState(false);
  17630. Logger.info('heanup pause', '投播暂停成功');
  17631. } catch (error) {
  17632. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  17633. }
  17634. } else if (this.mIjkMediaPlayer.isPlaying() || this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17635. // 本地播放器模式
  17636. this.savePlaybackPosition();
  17637. if (this.mIjkMediaPlayer.isPlaying()) {
  17638. this.mIjkMediaPlayer.pause();
  17639. this.setProgress();
  17640. }
  17641. this.mDestroyPage = true;
  17642. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17643. this.updateSessionPlayState(false)
  17644. this.playChange()
  17645. if (this.pipController) {
  17646. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  17647. PiPWindow.PiPControlStatus.PAUSE);
  17648. }
  17649. }
  17650. }
  17651. private stop() {
  17652. this.audioInterruptResumePending = false;
  17653. this.savePlaybackPosition();
  17654. this.clearInitialSeekGuardTimer();
  17655. this.waitInitialSeekBeforeStart = false;
  17656. this.pendingMemorySeekPosition = 0;
  17657. this.isPlayerLoading = false;
  17658. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17659. this.mIjkMediaPlayer.stop();
  17660. this.mIjkMediaPlayer.release();
  17661. console.info('kkMusic stop ..this.CONTROL_PlayStatus '+this.CONTROL_PlayStatus )
  17662. this.stopProgressTask();
  17663. this.updateSessionPlayState(false)
  17664. this.playChange()
  17665. this.watchStatus();
  17666. }
  17667. //保持记忆播放功能
  17668. private savePlaybackPosition() {
  17669. if (this.mIjkMediaPlayer != null) {
  17670. let position = this.mIjkMediaPlayer.getCurrentPosition();
  17671. // ToastUtil.showToast('保存记忆播放 = ' + position)
  17672. let duration = this.mIjkMediaPlayer.getDuration();
  17673. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17674. position = Math.max(0, position - getCueTrackStartOffset(this.currentSong));
  17675. const cueDuration = getCueTrackDuration(this.currentSong);
  17676. if (cueDuration > 0) {
  17677. duration = cueDuration;
  17678. }
  17679. }
  17680. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  17681. // 如果播放位置接近视频末尾,则保存 position 为 0
  17682. const playbackPosition = (duration - position < threshold) ? 0 : position;
  17683. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  17684. PreferencesUtil.putSync(memoryKey, playbackPosition);
  17685. }
  17686. }
  17687. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  17688. if (song && isRemoteCloudType(song.type)) {
  17689. const accountId = song.webdav_account_id || 'unknown';
  17690. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  17691. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  17692. }
  17693. if (song && isCueSplitItem(song)) {
  17694. return `memory_play_local_cue:${song.filePath}`;
  17695. }
  17696. return playbackUrl || '';
  17697. }
  17698. private getPlaybackMemoryKey(): string {
  17699. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  17700. }
  17701. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  17702. if (token !== this.remoteRestoreSeekToken) {
  17703. return;
  17704. }
  17705. if (!this.mIjkMediaPlayer || position <= 0) {
  17706. if (this.waitInitialSeekBeforeStart) {
  17707. this.finishInitialSeekWait('invalid-memory-position', true);
  17708. }
  17709. return;
  17710. }
  17711. const duration = this.getActiveDuration();
  17712. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  17713. let safePosition = position;
  17714. if (duration > 0) {
  17715. safePosition = Math.max(0, Math.min(position, duration - 500));
  17716. } else {
  17717. safePosition = Math.max(0, position);
  17718. }
  17719. if (safePosition <= 0) {
  17720. if (this.waitInitialSeekBeforeStart) {
  17721. this.finishInitialSeekWait('memory-position-too-small', true);
  17722. }
  17723. return;
  17724. }
  17725. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  17726. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  17727. }
  17728. this.seekTo(safePosition + "", retryCount === 0 ? 'remote-memory-restore' : 'remote-memory-retry');
  17729. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  17730. return;
  17731. }
  17732. setTimeout(() => {
  17733. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  17734. return;
  17735. }
  17736. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  17737. if (Math.abs(latestPos - safePosition) <= 1500) {
  17738. return;
  17739. }
  17740. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  17741. }, this.remoteMemorySeekRetryIntervalMs);
  17742. }
  17743. //获取记忆播放功能
  17744. private restorePlaybackPosition() {
  17745. const position: number = this.pendingMemorySeekPosition > 0 ?
  17746. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  17747. if (!this.mIjkMediaPlayer || position <= 0) {
  17748. if (this.waitInitialSeekBeforeStart) {
  17749. this.finishInitialSeekWait('no-memory-position', true);
  17750. }
  17751. return;
  17752. }
  17753. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17754. if (isRemoteSong && this.videoUrl.includes('://')) {
  17755. const token = this.remoteRestoreSeekToken;
  17756. this.restoreRemotePlaybackPositionSafely(position, token);
  17757. return;
  17758. }
  17759. const duration = this.getActiveDuration();
  17760. let safePosition = position;
  17761. if (duration > 0) {
  17762. safePosition = Math.max(0, Math.min(position, duration - 500));
  17763. } else {
  17764. safePosition = Math.max(0, position);
  17765. }
  17766. if (safePosition <= 0) {
  17767. if (this.waitInitialSeekBeforeStart) {
  17768. this.finishInitialSeekWait('memory-position-too-small', true);
  17769. }
  17770. return;
  17771. }
  17772. this.seekTo(safePosition + "", isRemoteSong ? 'remote-memory-restore' : 'memory-restore');
  17773. }
  17774. private async seekTo(value: string, source: string = 'internal') {
  17775. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  17776. // ToastUtil.showToast('wma格式不支持拖动快进。')
  17777. // return
  17778. // }
  17779. // 如果是投播模式,使用 CastController 的 seek 方法
  17780. if (this.castControllerWrapper && this.isCastPlaying) {
  17781. try {
  17782. let seekPos = Number.parseInt(value);
  17783. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17784. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17785. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17786. const duration = this.getActiveDuration();
  17787. if (duration > 0) {
  17788. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17789. }
  17790. if (cueTrackItem) {
  17791. seekPos += cueTrackStartOffset;
  17792. if (cueTrackEndOffset > cueTrackStartOffset) {
  17793. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17794. }
  17795. }
  17796. this.beginSeekTrace(source, seekPos);
  17797. this.isSeekTo = true;
  17798. Logger.info(
  17799. TAG,
  17800. `[seek] cast dispatch, source=${source}, target=${seekPos}, duration=${duration}, ` +
  17801. `uiDuration=${this.duration}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17802. );
  17803. // 检查是否接近末尾
  17804. if (this.duration > 0 && seekPos >= this.duration - 500) {
  17805. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  17806. }
  17807. await this.castControllerWrapper.seek(seekPos);
  17808. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  17809. } catch (error) {
  17810. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  17811. }
  17812. } else {
  17813. // 本地播放器模式
  17814. let seekPos = Number.parseInt(value);
  17815. if (Number.isNaN(seekPos)) {
  17816. return;
  17817. }
  17818. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17819. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17820. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17821. const duration = this.getActiveDuration();
  17822. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17823. if (duration > 0) {
  17824. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17825. } else if (seekPos < 0) {
  17826. seekPos = 0;
  17827. }
  17828. if (cueTrackItem) {
  17829. seekPos += cueTrackStartOffset;
  17830. if (cueTrackEndOffset > cueTrackStartOffset) {
  17831. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17832. }
  17833. }
  17834. if (isRemoteSong && duration <= 0 && seekPos > 0) {
  17835. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${seekPos}ms`);
  17836. return;
  17837. }
  17838. if (isRemoteSong && duration <= 0) {
  17839. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  17840. }
  17841. if (source !== 'internal') {
  17842. this.beginSeekTrace(source, seekPos);
  17843. }
  17844. if (this.handleBlockedSeek(seekPos, source)) {
  17845. return;
  17846. }
  17847. this.isSeekTo = true
  17848. try {
  17849. if (isRemoteSong || source !== 'internal' || this.isSeekTraceActive()) {
  17850. Logger.info(
  17851. TAG,
  17852. `[seek] player dispatch, source=${source}, target=${seekPos}, activeDuration=${duration}, ` +
  17853. `playerDuration=${this.mIjkMediaPlayer.getDuration()}, current=${this.mIjkMediaPlayer.getCurrentPosition()}, ` +
  17854. `isPlaying=${this.mIjkMediaPlayer.isPlaying()}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17855. );
  17856. }
  17857. this.mIjkMediaPlayer.seekTo(seekPos + "");
  17858. this.logSeekTrace('seek-dispatched', this.mIjkMediaPlayer.getCurrentPosition(), this.mIjkMediaPlayer.getDuration(), true);
  17859. this.setProgress()
  17860. } catch (error) {
  17861. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  17862. this.logSeekTrace('seek-dispatch-error', undefined, undefined, true);
  17863. } finally {
  17864. this.isSeekTo = false
  17865. }
  17866. }
  17867. }
  17868. // 添加到下一首播放
  17869. private addToNextPlay(song: VideoItem) {
  17870. if (!this.debounce()) {
  17871. return;
  17872. }
  17873. if (this.currentSong) {
  17874. if (this.currentSong === song) {
  17875. ToastUtil.showToast('当前已经在播放这首歌了!')
  17876. return
  17877. }
  17878. }
  17879. // 如果未开始播放或队列为空
  17880. if (this.curIndex === -1 || this.songList.length === 0) {
  17881. this.songList = [song];
  17882. this.curIndex = 0;
  17883. this.doPlay(song)
  17884. return;
  17885. }
  17886. // 插入到当前索引+1的位置
  17887. const insertPos = this.curIndex + 1;
  17888. this.songList.splice(insertPos, 0, song);
  17889. this.songList = [...this.songList]; // 触发状态更新
  17890. this.sonDataSource.pushArrayData(this.songList)
  17891. ToastUtil.showToast('已添加至下一首播放')
  17892. }
  17893. //后退10s,可再设置设置默认几秒
  17894. async backForward() {
  17895. // 如果是投播模式,从currentTime2获取当前位置
  17896. let pos: number;
  17897. if (this.castController && this.isCastPlaying) {
  17898. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17899. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  17900. } else if (this.mIjkMediaPlayer) {
  17901. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17902. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17903. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17904. }
  17905. } else {
  17906. return;
  17907. }
  17908. let value = pos - Number(this.fastForwardSeconds) * 1000;
  17909. if (value < 0) {
  17910. value = 0;
  17911. }
  17912. await this.seekTo(value + "", 'rewind-button');
  17913. }
  17914. //快进10s,可再设置设置默认几秒
  17915. async fastForward() {
  17916. // 如果是投播模式,从currentTime2获取当前位置
  17917. let pos: number;
  17918. if (this.castController && this.isCastPlaying) {
  17919. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17920. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  17921. } else if (this.mIjkMediaPlayer) {
  17922. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17923. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17924. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17925. }
  17926. } else {
  17927. return;
  17928. }
  17929. let value = pos + Number(this.fastForwardSeconds) * 1000;
  17930. // 限制不超过总时长
  17931. if (this.duration > 0 && value > this.duration) {
  17932. value = this.duration;
  17933. }
  17934. await this.seekTo(value + "", 'fast-forward-button');
  17935. }
  17936. //下一个
  17937. private async playNext() {
  17938. this.lyricController.setLyric(null)
  17939. this.lyricControllerXF.setLyric(null)
  17940. this.lyricControllerSingle.setLyric(null)
  17941. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  17942. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  17943. if (!this.debounce()) {
  17944. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  17945. return;
  17946. }
  17947. Logger.info('heanup playNext', `playType=${this.playType}`);
  17948. if (this.playType == 3) { //3:随机播放
  17949. Logger.info('heanup playNext', '随机播放模式');
  17950. await this.randomPlay()
  17951. return;
  17952. }
  17953. if (ArrayUtil.isNotEmpty(this.songList)) {
  17954. if (this.curIndex >= this.songList.length - 1) {
  17955. // playType=0 或 3: 尝试加载更多或循环
  17956. // playType=4: 不循环,检查是否是最后一首
  17957. if (this.playType == 4) {
  17958. // 连续播放不循环模式:到达最后一首时停止播放
  17959. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  17960. ToastUtil.showToast('已经是最后一首了');
  17961. this.showRePlay();
  17962. this.currentTime = this.stringForTime(this.getActiveDuration());
  17963. this.progressValue = this.PROGRESS_MAX_VALUE;
  17964. this.slideEnable = false;
  17965. this.stop();
  17966. return;
  17967. }
  17968. await this.tryLoadNextPageForPlayback();
  17969. }
  17970. if (this.curIndex >= this.songList.length - 1) {
  17971. // playType=4 不应该执行到这里,因为上面已经return了
  17972. this.curIndex = 0;
  17973. } else {
  17974. this.curIndex++;
  17975. }
  17976. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17977. this.currentSong = this.songList[this.curIndex];
  17978. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17979. const nextLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17980. const nextUrl = await this.resolvePlaybackUrlForCurrentSong('playNext');
  17981. if (!nextUrl) {
  17982. if (nextLoading) {
  17983. this.hideLoadIng();
  17984. }
  17985. return;
  17986. }
  17987. this.videoUrl = nextUrl;
  17988. this.artist = this.songList[this.curIndex].artist
  17989. this.name = this.songList[this.curIndex].name
  17990. //this.cover = this.songList[this.curIndex].pixelMapPath
  17991. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  17992. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  17993. // 如果是投播模式,使用 CastController 播放下一首
  17994. if (this.castControllerWrapper) {
  17995. console.info('heanup playNext', '使用 CastController 播放下一首');
  17996. try {
  17997. const nextDuration = this.getSongDurationMs(this.currentSong);
  17998. if (nextDuration > 0) {
  17999. this.duration = nextDuration;
  18000. this.durationTime = Math.floor(nextDuration / 1000);
  18001. this.durationStringTime = secondToTime(this.durationTime);
  18002. this.totalTime = this.stringForTime(nextDuration);
  18003. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  18004. }
  18005. this.updateCastProgress(0);
  18006. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  18007. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  18008. if (nextLoading) {
  18009. this.hideLoadIng();
  18010. }
  18011. console.info('heanup playNext', 'CastController 播放下一首成功');
  18012. return;
  18013. } catch (error) {
  18014. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  18015. // 如果投播失败,回退到本地播放
  18016. this.isCastPlaying = false;
  18017. }
  18018. }
  18019. // 本地播放器模式,需要先stop
  18020. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18021. this.stop();
  18022. if (nextLoading) {
  18023. this.showLoadIng();
  18024. }
  18025. this.changeImageAnimation()
  18026. }
  18027. }
  18028. changeImageAnimation() {
  18029. if(this.openSkipSongAnimate){
  18030. // 第一步:淡出动画
  18031. this.getUIContext()?.animateTo({
  18032. duration: 500,
  18033. curve: Curve.EaseOut,
  18034. }, () => {
  18035. this.opacityValueImage = 0.1;
  18036. if(this.isCoverRectangle){
  18037. this.scaleValueImage = 0.88
  18038. }
  18039. });
  18040. // 第二步:切换图片后淡入
  18041. setTimeout(() => {
  18042. this.cover = this.songList[this.curIndex].pixelMapPath
  18043. this.getUIContext()?.animateTo({
  18044. duration: 500,
  18045. curve: Curve.EaseIn,
  18046. }, () => {
  18047. this.opacityValueImage = 1;
  18048. this.scaleValueImage = 1 // 图标恢复到原始大小
  18049. this.startPlayOrResumePlay()
  18050. });
  18051. }, 500);
  18052. }else{
  18053. this.cover = this.songList[this.curIndex].pixelMapPath
  18054. this.startPlayOrResumePlay()
  18055. }
  18056. }
  18057. // 内部方法:提前缓存下一首
  18058. private async preloadNextSongInternal(): Promise<void> {
  18059. // 随机模式下传递已播放索引集合
  18060. if (this.playType === 3) {
  18061. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  18062. this.songList,
  18063. this.curIndex,
  18064. this.playType,
  18065. this.playedIndices
  18066. );
  18067. } else {
  18068. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  18069. this.songList,
  18070. this.curIndex,
  18071. this.playType
  18072. );
  18073. }
  18074. }
  18075. // 存储已播放的歌曲索引
  18076. private playedIndices: Set<number> = new Set();
  18077. // 存储已播放的本地歌曲路径(随机播放去重用)
  18078. private playedLocalFilePaths: Set<string> = new Set();
  18079. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  18080. private randomPlayHistory: VideoItem[] = [];
  18081. //随机播放
  18082. private async randomPlay() {
  18083. // if (!this.debounce()) {
  18084. // return;
  18085. // }
  18086. // 网盘模式: 渐进式扩展播放库的随机播放
  18087. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  18088. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  18089. if (isCloudSong) {
  18090. const findRemoteQueue = getFindVideoItems();
  18091. const isSameFindQueue = this.songList.length === findRemoteQueue.length &&
  18092. this.songList.every((item: VideoItem, index: number) => item.filePath === findRemoteQueue[index]?.filePath);
  18093. const useFindRemoteQueue = this.playQueueScope === 'playlist' &&
  18094. findRemoteQueue.length > 0 &&
  18095. isSameFindQueue &&
  18096. findRemoteQueue.every((item: VideoItem) => isRemoteCloudType(item.type)) &&
  18097. findRemoteQueue.some((item: VideoItem) => item.filePath === this.currentSong?.filePath);
  18098. // 阈值常量
  18099. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  18100. const LOAD_MORE_PAGES = 3; // 每次加载页数
  18101. // 获取网盘播放列表
  18102. const navidromeList = useFindRemoteQueue ? [] : getNavidromeVideoItems();
  18103. const webdavList = useFindRemoteQueue ? [] : getWebdavVideoItems();
  18104. const isNavidrome = !useFindRemoteQueue && navidromeList.length > 0;
  18105. const remoteList = useFindRemoteQueue ? findRemoteQueue : (isNavidrome ? navidromeList : webdavList);
  18106. if (remoteList.length > 0) {
  18107. // 将当前歌加入历史栈
  18108. if (this.currentSong) {
  18109. this.randomPlayHistory.unshift(this.currentSong);
  18110. if (this.randomPlayHistory.length > 50) {
  18111. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  18112. }
  18113. // 标记当前歌曲为已播放
  18114. markAsPlayed(this.currentSong.filePath);
  18115. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  18116. }
  18117. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  18118. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  18119. const totalCount = remoteList.length;
  18120. const playedCount = isNavidrome ? getPlayedCount() : 0;
  18121. Logger.info(TAG,
  18122. `randomPlay(网盘模式): source=${useFindRemoteQueue ? 'find-playlist' : (isNavidrome ? 'navidrome' : 'webdav')}, ` +
  18123. `总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  18124. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  18125. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  18126. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  18127. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  18128. if (loadSuccess) {
  18129. // 重新获取未播放数量
  18130. unplayedCount = getUnplayedCount();
  18131. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  18132. }
  18133. }
  18134. // 从未播放歌曲中随机选择
  18135. let candidates: VideoItem[];
  18136. if (isNavidrome) {
  18137. candidates = getUnplayedSongs();
  18138. // 如果全部播放完,重置已播放记录
  18139. if (candidates.length === 0) {
  18140. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  18141. clearPlayedHistory();
  18142. // 排除当前歌曲
  18143. const currentFilePath = this.currentSong?.filePath;
  18144. candidates = currentFilePath
  18145. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  18146. : getNavidromeVideoItems();
  18147. }
  18148. } else {
  18149. // WebDAV模式:简单排除当前歌曲
  18150. const currentFilePath = this.currentSong?.filePath;
  18151. candidates = currentFilePath
  18152. ? remoteList.filter(v => v.filePath !== currentFilePath)
  18153. : remoteList;
  18154. }
  18155. if (candidates.length > 0) {
  18156. const randomIndex = Math.floor(Math.random() * candidates.length);
  18157. const randomSong = candidates[randomIndex];
  18158. // 标记为已播放
  18159. if (isNavidrome) {
  18160. markAsPlayed(randomSong.filePath);
  18161. }
  18162. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  18163. // 将选中的歌曲加入播放列表(如果不存在)
  18164. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  18165. if (nextIndex < 0) {
  18166. this.songList = [...this.songList, randomSong];
  18167. this.sonDataSource.pushArrayData(this.songList);
  18168. nextIndex = this.songList.length - 1;
  18169. }
  18170. this.curIndex = nextIndex;
  18171. this.playedIndices.add(this.curIndex);
  18172. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18173. this.stop();
  18174. this.currentSong = randomSong;
  18175. const randomRemoteListLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18176. const randomRemoteListUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-list');
  18177. if (!randomRemoteListUrl) {
  18178. if (randomRemoteListLoading) {
  18179. this.hideLoadIng();
  18180. }
  18181. return;
  18182. }
  18183. this.videoUrl = randomRemoteListUrl;
  18184. this.name = this.currentSong.name;
  18185. this.artist = this.currentSong.artist;
  18186. this.changeImageAnimation();
  18187. return;
  18188. }
  18189. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  18190. }
  18191. }
  18192. if (this.currentSong) {
  18193. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  18194. this.randomPlayHistory.unshift(this.currentSong);
  18195. // 限制历史栈大小,避免无限增长
  18196. if (this.randomPlayHistory.length > 50) {
  18197. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  18198. }
  18199. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  18200. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  18201. const currentFilePath = this.currentSong.filePath;
  18202. if (isCurrentRemote) {
  18203. const remoteOptions: RandomSongQueryOptions = {
  18204. type: this.currentSong.type,
  18205. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18206. };
  18207. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  18208. if (randomRemoteSong) {
  18209. // 验证并修正webdav_account_id
  18210. if (randomRemoteSong.webdav_account_id) {
  18211. const manager = RemoteDriveManager.getInstance();
  18212. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  18213. if (!account) {
  18214. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  18215. // 获取所有账号,查找相同类型的账号
  18216. const allAccounts = manager.getAllWebDavAccounts();
  18217. let foundAccount: WebDavAccount | null = null;
  18218. for (let i = 0; i < allAccounts.length; i++) {
  18219. if (allAccounts[i].webType === randomRemoteSong.type) {
  18220. foundAccount = allAccounts[i];
  18221. break;
  18222. }
  18223. }
  18224. if (foundAccount && foundAccount.id) {
  18225. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  18226. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  18227. // 更新数据库记录
  18228. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  18229. } else {
  18230. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  18231. return;
  18232. }
  18233. }
  18234. }
  18235. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  18236. if (nextIndex < 0) {
  18237. this.songList = [...this.songList, randomRemoteSong];
  18238. this.sonDataSource.pushArrayData(this.songList);
  18239. nextIndex = this.songList.length - 1;
  18240. }
  18241. this.curIndex = nextIndex;
  18242. this.playedIndices.add(this.curIndex);
  18243. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18244. this.stop();
  18245. this.currentSong = randomRemoteSong;
  18246. const randomRemoteDbLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18247. const randomRemoteUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-db');
  18248. if (!randomRemoteUrl) {
  18249. if (randomRemoteDbLoading) {
  18250. this.hideLoadIng();
  18251. }
  18252. return;
  18253. }
  18254. this.videoUrl = randomRemoteUrl;
  18255. this.name = this.currentSong.name;
  18256. this.artist = this.currentSong.artist;
  18257. this.changeImageAnimation();
  18258. return;
  18259. }
  18260. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  18261. } else {
  18262. if (currentFilePath) {
  18263. this.playedLocalFilePaths.add(currentFilePath);
  18264. }
  18265. // 根据modeType构建不同的查询选项
  18266. const localOptions: RandomSongQueryOptions = {
  18267. type: CommonConstants.TYPE_LOCAL,
  18268. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  18269. };
  18270. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  18271. // modeType==0: 文件夹模式,添加parentPath过滤
  18272. if (this.modeType === 0 && this.currentPath) {
  18273. localOptions.parentPath = this.currentPath;
  18274. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  18275. }
  18276. // modeType==4: 歌单模式,添加playlistSongFilePaths
  18277. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18278. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18279. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  18280. } else if (this.modeType === 4) {
  18281. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  18282. }
  18283. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  18284. if (!randomLocalSong) {
  18285. this.playedLocalFilePaths.clear();
  18286. if (currentFilePath) {
  18287. this.playedLocalFilePaths.add(currentFilePath);
  18288. }
  18289. const fallbackLocalOptions: RandomSongQueryOptions = {
  18290. type: CommonConstants.TYPE_LOCAL,
  18291. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18292. };
  18293. // fallback时也要保持modeType的过滤条件
  18294. if (this.modeType === 0 && this.currentPath) {
  18295. fallbackLocalOptions.parentPath = this.currentPath;
  18296. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18297. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18298. }
  18299. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  18300. }
  18301. if (randomLocalSong !== null) {
  18302. const selectedLocalSong = randomLocalSong;
  18303. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  18304. if (nextIndex < 0) {
  18305. this.songList = [...this.songList, selectedLocalSong];
  18306. this.sonDataSource.pushArrayData(this.songList);
  18307. nextIndex = this.songList.length - 1;
  18308. }
  18309. this.curIndex = nextIndex;
  18310. this.playedIndices.add(this.curIndex);
  18311. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18312. this.stop();
  18313. this.currentSong = selectedLocalSong;
  18314. const randomLocalUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-local-db');
  18315. if (!randomLocalUrl) {
  18316. return;
  18317. }
  18318. this.videoUrl = randomLocalUrl;
  18319. this.name = this.currentSong.name;
  18320. this.artist = this.currentSong.artist;
  18321. this.changeImageAnimation();
  18322. return;
  18323. }
  18324. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  18325. }
  18326. }
  18327. if (ArrayUtil.isNotEmpty(this.songList)) {
  18328. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  18329. this.playedIndices.add(this.curIndex);
  18330. }
  18331. if (this.songList.length > 3) {
  18332. // 优先使用预缓存的随机索引(仅网盘播放时)
  18333. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  18334. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  18335. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  18336. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  18337. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  18338. this.curIndex = this.preloadNextRandomIndex;
  18339. this.playedIndices.add(this.curIndex);
  18340. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  18341. // 立即预缓存下一首,避免下次点击时没有预缓存
  18342. void this.preloadNextSongInternal();
  18343. } else {
  18344. // 如果没有预缓存索引,则正常随机选择
  18345. // 如果所有歌曲都播放过一次,清空已播放索引集合
  18346. if (this.playedIndices.size === this.songList.length) {
  18347. this.playedIndices.clear();
  18348. }
  18349. // 随机选择一个未播放的歌曲索引
  18350. let newIndex: number;
  18351. // 添加超时机制防止无限循环
  18352. let attempt = 0;
  18353. const maxAttempts = 100; // 根据需求调整
  18354. do {
  18355. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  18356. attempt++;
  18357. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  18358. if (attempt >= maxAttempts) {
  18359. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  18360. newIndex = Math.floor(Math.random() * this.songList.length);
  18361. }
  18362. this.curIndex = newIndex;
  18363. this.playedIndices.add(newIndex);
  18364. }
  18365. } else {
  18366. // 当歌曲数量小于或等于3时,直接播放下一首
  18367. if (this.curIndex == this.songList.length - 1) {
  18368. this.curIndex = 0;
  18369. } else {
  18370. this.curIndex++;
  18371. }
  18372. }
  18373. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18374. this.stop();
  18375. this.currentSong = this.songList[this.curIndex];
  18376. const randomFallbackLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18377. const randomFallbackUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-fallback');
  18378. if (!randomFallbackUrl) {
  18379. if (randomFallbackLoading) {
  18380. this.hideLoadIng();
  18381. }
  18382. return;
  18383. }
  18384. this.videoUrl = randomFallbackUrl;
  18385. this.name = this.songList[this.curIndex].name;
  18386. this.artist = this.songList[this.curIndex].artist
  18387. // this.cover = this.songList[this.curIndex].pixelMapPath
  18388. this.changeImageAnimation()
  18389. // 预缓存下一首(包括网盘和本地)
  18390. void this.preloadNextSongInternal();
  18391. }
  18392. }
  18393. private async playIndex(index: number) {
  18394. if (!this.debounce()) {
  18395. return;
  18396. }
  18397. if (ArrayUtil.isNotEmpty(this.songList)) {
  18398. this.curIndex = index;
  18399. this.currentSong = this.songList[index];
  18400. const playIndexLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18401. const playIndexUrl = await this.resolvePlaybackUrlForCurrentSong('playIndex');
  18402. if (!playIndexUrl) {
  18403. if (playIndexLoading) {
  18404. this.hideLoadIng();
  18405. }
  18406. return;
  18407. }
  18408. this.videoUrl = playIndexUrl;
  18409. this.name = this.currentSong.name
  18410. this.artist = this.currentSong.artist
  18411. // 如果是投播模式,需要为投播设备准备当前歌曲
  18412. if (this.castController && this.isCastPlaying) {
  18413. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  18414. this.initQueueItem();
  18415. await this.prepare();
  18416. if (playIndexLoading) {
  18417. this.hideLoadIng();
  18418. }
  18419. this.cover = this.currentSong.pixelMapPath;
  18420. return;
  18421. }
  18422. // 本地播放器模式,需要先stop
  18423. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18424. this.stop();
  18425. if (playIndexLoading) {
  18426. this.showLoadIng();
  18427. }
  18428. this.changeImageAnimation()
  18429. }
  18430. }
  18431. //上一个
  18432. private async playPrevious() {
  18433. if (!this.debounce()) {
  18434. return;
  18435. }
  18436. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  18437. this.randomModePlayFromHistory()
  18438. return;
  18439. }
  18440. if (this.curIndex == 0) {
  18441. this.curIndex = this.songList.length - 1;
  18442. } else {
  18443. this.curIndex--;
  18444. }
  18445. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  18446. this.currentSong = this.songList[this.curIndex];
  18447. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  18448. // 验证并修正webdav_account_id(针对远程类型歌曲)
  18449. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  18450. const manager = RemoteDriveManager.getInstance();
  18451. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  18452. if (!account) {
  18453. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  18454. // 获取所有账号,查找相同类型的账号
  18455. const allAccounts = manager.getAllWebDavAccounts();
  18456. let foundAccount: WebDavAccount | null = null;
  18457. for (let i = 0; i < allAccounts.length; i++) {
  18458. if (allAccounts[i].webType === this.currentSong.type) {
  18459. foundAccount = allAccounts[i];
  18460. break;
  18461. }
  18462. }
  18463. if (foundAccount && foundAccount.id) {
  18464. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  18465. this.currentSong.webdav_account_id = foundAccount.id.toString();
  18466. // 更新数据库记录
  18467. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  18468. } else {
  18469. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  18470. // 跳过无效账号的歌曲,继续查找上一首
  18471. if (this.curIndex == 0) {
  18472. this.curIndex = this.songList.length - 1;
  18473. } else {
  18474. this.curIndex--;
  18475. }
  18476. this.currentSong = this.songList[this.curIndex];
  18477. }
  18478. }
  18479. }
  18480. const previousLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18481. const previousUrl = await this.resolvePlaybackUrlForCurrentSong('playPrevious');
  18482. if (!previousUrl) {
  18483. if (previousLoading) {
  18484. this.hideLoadIng();
  18485. }
  18486. return;
  18487. }
  18488. this.videoUrl = previousUrl;
  18489. this.name = this.songList[this.curIndex].name
  18490. this.artist = this.songList[this.curIndex].artist
  18491. // 如果是投播模式,使用 CastController 切换上一首
  18492. if (this.castControllerWrapper) {
  18493. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  18494. try {
  18495. const prevDuration = this.getSongDurationMs(this.currentSong);
  18496. if (prevDuration > 0) {
  18497. this.duration = prevDuration;
  18498. this.durationTime = Math.floor(prevDuration / 1000);
  18499. this.durationStringTime = secondToTime(this.durationTime);
  18500. this.totalTime = this.stringForTime(prevDuration);
  18501. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  18502. }
  18503. this.updateCastProgress(0);
  18504. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  18505. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  18506. if (previousLoading) {
  18507. this.hideLoadIng();
  18508. }
  18509. } catch (error) {
  18510. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  18511. this.isCastPlaying = false;
  18512. }
  18513. this.cover = this.songList[this.curIndex].pixelMapPath;
  18514. return;
  18515. }
  18516. // 本地播放器模式,需要先stop
  18517. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18518. this.stop();
  18519. if (previousLoading) {
  18520. this.showLoadIng();
  18521. }
  18522. this.changeImageAnimation()
  18523. }
  18524. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  18525. private async randomModePlayFromHistory() {
  18526. if (this.randomPlayHistory.length >= 1) {
  18527. // 播放历史栈的第一首(刚刚播放过的)
  18528. const prevSong = this.randomPlayHistory[0];
  18529. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  18530. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  18531. this.randomPlayHistory.shift();
  18532. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  18533. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18534. this.stop();
  18535. // 验证并修正webdav_account_id(针对远程类型歌曲)
  18536. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  18537. const manager = RemoteDriveManager.getInstance();
  18538. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  18539. if (!account) {
  18540. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  18541. const allAccounts = manager.getAllWebDavAccounts();
  18542. let foundAccount: WebDavAccount | null = null;
  18543. for (let i = 0; i < allAccounts.length; i++) {
  18544. if (allAccounts[i].webType === prevSong.type) {
  18545. foundAccount = allAccounts[i];
  18546. break;
  18547. }
  18548. }
  18549. if (foundAccount && foundAccount.id) {
  18550. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  18551. prevSong.webdav_account_id = foundAccount.id.toString();
  18552. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  18553. } else {
  18554. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  18555. // 无法播放这首歌,继续尝试下一首历史记录
  18556. if (this.randomPlayHistory.length >= 1) {
  18557. this.randomModePlayFromHistory();
  18558. return;
  18559. } else {
  18560. // 历史记录为空,无法继续
  18561. ToastUtil.showToast('没有更多历史记录');
  18562. return;
  18563. }
  18564. }
  18565. }
  18566. }
  18567. this.currentSong = prevSong;
  18568. const historyLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18569. const historyUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-history');
  18570. if (!historyUrl) {
  18571. if (historyLoading) {
  18572. this.hideLoadIng();
  18573. }
  18574. return;
  18575. }
  18576. this.videoUrl = historyUrl;
  18577. this.cover = this.currentSong.pixelMapPath
  18578. this.artist = this.currentSong.artist
  18579. this.name = this.currentSong.name;
  18580. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  18581. this.startPlayOrResumePlay();
  18582. } else {
  18583. ToastUtil.showToast('随机播放模式暂无历史记录');
  18584. }
  18585. }
  18586. debounce() {
  18587. const delay = 600;
  18588. let cur = new Date().getTime();
  18589. if (cur - this.last > delay) {
  18590. this.last = cur;
  18591. return true;
  18592. }
  18593. return false;
  18594. }
  18595. /**
  18596. * Sets whether the screen is a constant based on the playback status.
  18597. */
  18598. watchStatus() {
  18599. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  18600. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  18601. this.windowClass.setWindowKeepScreenOn(true);
  18602. } else {
  18603. this.windowClass.setWindowKeepScreenOn(false);
  18604. }
  18605. }
  18606. /**
  18607. * Volume gesture method onActionStart.
  18608. *
  18609. * @param event Gesture event.
  18610. */
  18611. private customDialogComponentIdMM: number = 0
  18612. @Builder
  18613. customDialogComponentMM() {
  18614. Column() {
  18615. Row() {
  18616. Blank()
  18617. Text('验证密码')
  18618. .fontSize(22)
  18619. .fontColor($r('app.color.pri_bg'))
  18620. .margin({ top: 18 })
  18621. Blank()
  18622. Image($r('app.media.close'))
  18623. .fillColor(Color.White)
  18624. .margin({ top: 18, right: 18 })
  18625. .width(20)
  18626. .onClick(() => {
  18627. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18628. })
  18629. }
  18630. .width('100%') // 使Row占据整个宽度
  18631. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  18632. Verify({
  18633. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  18634. });
  18635. }.height('60%')
  18636. .backgroundColor($r('app.color.index_background'))
  18637. .justifyContent(FlexAlign.SpaceBetween)
  18638. }
  18639. private handleVerifyCompleted(isSuccess: boolean) {
  18640. if (isSuccess) {
  18641. console.log('验证成功');
  18642. // 在这里处理验证成功后的逻辑
  18643. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18644. this.currentPath = this.lockPath
  18645. this.getSortedFiles(this.currentPath)
  18646. } else {
  18647. // console.log('验证失败');
  18648. ToastUtil.showToast('验证失败')
  18649. }
  18650. }
  18651. private showVerifyDialog() {
  18652. promptAction.openCustomDialog({
  18653. transition: TransitionEffect.asymmetric(
  18654. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  18655. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18656. ,
  18657. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  18658. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18659. ),
  18660. builder: () => {
  18661. this.customDialogComponentMM()
  18662. },
  18663. isModal: true,
  18664. autoCancel: true,
  18665. maskColor: Color.Transparent,
  18666. alignment: DialogAlignment.Bottom,
  18667. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  18668. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  18669. console.log("dialog onWillDismiss")
  18670. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  18671. dismissDialogAction.dismiss()
  18672. }
  18673. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  18674. dismissDialogAction.dismiss()
  18675. }
  18676. }
  18677. }).then((dialogId: number) => {
  18678. this.customDialogComponentIdMM = dialogId
  18679. })
  18680. }
  18681. //左滑操作 移动文件 重命名 删除等操作
  18682. @Builder
  18683. DeleteButton(item: VideoItem, index: number, filePath: string) {
  18684. Row() {
  18685. //加入收藏
  18686. // Button() {
  18687. // Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  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. // if (item) {
  18699. // this.doFav(item)
  18700. // }
  18701. // })
  18702. //加入下一首播放
  18703. Button() {
  18704. Image($r('app.media.next_to_play'))
  18705. .fillColor(Color.White)
  18706. .width(20)
  18707. }
  18708. .width(40)
  18709. .height(40)
  18710. .type(ButtonType.Circle)
  18711. .backgroundColor(this.themeColor)
  18712. .margin(5)
  18713. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18714. .onClick(() => {
  18715. this.addToNextPlay(item);
  18716. })
  18717. //复制文件
  18718. Button() {
  18719. Image($r('app.media.copy'))
  18720. .fillColor(Color.White)
  18721. .width(20)
  18722. }
  18723. .width(40)
  18724. .height(40)
  18725. .type(ButtonType.Circle)
  18726. .backgroundColor(this.themeColor)
  18727. .margin(5)
  18728. .id(filePath + 'copy')
  18729. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18730. .onClick(() => {
  18731. this.showCopyDialog(false, item, index, filePath + 'copy');
  18732. })
  18733. //移动文件
  18734. Button() {
  18735. Image($r('app.media.cut'))
  18736. .fillColor(Color.White)
  18737. .width(20)
  18738. }
  18739. .width(40)
  18740. .height(40)
  18741. .type(ButtonType.Circle)
  18742. .backgroundColor(this.themeColor)
  18743. .margin(5)
  18744. .id(filePath)
  18745. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18746. .onClick(() => {
  18747. this.showCutDialog(false, item, index, filePath);
  18748. })
  18749. Button() {
  18750. Image($r('app.media.cut_current'))
  18751. .fillColor(Color.White)
  18752. .width(20)
  18753. }
  18754. .width(40)
  18755. .height(40)
  18756. .type(ButtonType.Circle)
  18757. .backgroundColor(this.themeColor)
  18758. .margin(5)
  18759. .id(filePath + 'current')
  18760. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  18761. (this.isHasDir ? Visibility.Visible : Visibility.None))
  18762. .onClick(() => {
  18763. this.showCutDialog(true, item, index, filePath + 'current');
  18764. })
  18765. //重命名
  18766. // Button() {
  18767. // Image($r('app.media.rename2'))
  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(5)
  18779. // .onClick(() => {
  18780. // this.showReNameDialog(item, index + '', filePath)
  18781. //
  18782. // })
  18783. Button() {
  18784. Image($r('app.media.delete2'))
  18785. .fillColor(Color.White)
  18786. .width(20)
  18787. }
  18788. .width(40)
  18789. .height(40)
  18790. .type(ButtonType.Circle)
  18791. .backgroundColor(this.themeColor)
  18792. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18793. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18794. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18795. .margin({ left:5,top:5,bottom:5,right:20} )
  18796. .onClick(() => {
  18797. this.selectSingleItemForDelete(item)
  18798. this.showWarnIsDelete()
  18799. // this.showWarnIsDeleteFile(item, index + '', filePath)
  18800. })
  18801. // Button() {
  18802. // Image($r('app.media.share2'))
  18803. // .fillColor(Color.White)
  18804. // .width(20)
  18805. // }
  18806. // .width(40)
  18807. // .height(40)
  18808. // .type(ButtonType.Circle)
  18809. // .backgroundColor(this.themeColor)
  18810. // .margin(5)
  18811. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18812. // .onClick(() => {
  18813. // Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  18814. // })
  18815. }
  18816. }
  18817. /**
  18818. * 穿山甲banner广告
  18819. */
  18820. // private declare bannerAd: CSJNativeExpressAd;
  18821. // @State private status: string = "未加载"
  18822. // @State private isShowAd: boolean = false
  18823. // private declare mAdSlot: AdSlot;
  18824. // private mBiddingAdm = '' //服务端bidding才需要设置
  18825. // private expressLoadAdListener: NativeExpressAdListener = {
  18826. // /**
  18827. // * 加载失败的回调
  18828. // *
  18829. // * @param code
  18830. // * @param message
  18831. // */
  18832. // onError: (code: number, message: string) => {
  18833. // console.error("加载广告失败,code=" + code + ",message=" + message);
  18834. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  18835. // },
  18836. //
  18837. // /**
  18838. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  18839. // *
  18840. // * @param ads 返回的广告列表
  18841. // */
  18842. //
  18843. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  18844. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  18845. // if (ads && ads.length > 0) {
  18846. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  18847. // ad.setExpressInteractionListener({
  18848. // /**
  18849. // *广告的点击回调
  18850. // * @param type 广告的交互类型
  18851. // */
  18852. // onAdClicked: (type: number) => {
  18853. // console.log("BannerExpressAdPage==onAdClicked......");
  18854. // },
  18855. //
  18856. // /**
  18857. // * 广告的展示回调 每个广告仅回调一次
  18858. // * @param type 广告的交互类型
  18859. // */
  18860. // onAdShow: (type: number) => {
  18861. // console.log("BannerExpressAdPage==onAdShow......");
  18862. // },
  18863. //
  18864. // /**
  18865. // * 模板渲染失败
  18866. // */
  18867. // onRenderFail: (code: number, msg: string) => {
  18868. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  18869. // },
  18870. //
  18871. // /**
  18872. // * 模板渲染成功
  18873. // * @param width 返回view的宽 单位 vp
  18874. // * @param height 返回view的高 单位 vp
  18875. // */
  18876. // onRenderSuccess: (width: number, height: number) => {
  18877. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  18878. // this.bannerAd = ad;
  18879. // this.status = "广告加载完成待展示";
  18880. //
  18881. // this.showBannerAd()
  18882. // }
  18883. // })
  18884. // //渲染广告
  18885. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  18886. // this.setDislikeCallback(ad); //设置dislike
  18887. // ad.render(this.getUIContext())
  18888. // this.status = "广告加载中...";
  18889. // });
  18890. // }
  18891. // }
  18892. // }
  18893. //
  18894. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  18895. // ad.setDislikeCallback({
  18896. // /**
  18897. // * dislike show
  18898. // */
  18899. // onShow: () => {
  18900. // console.log("BannerExpressAdPage==dislike......show");
  18901. // },
  18902. //
  18903. // /**
  18904. // * @param position 选择的位置
  18905. // * @param value 选择的内容
  18906. // * @param enforceRemove 是否强制关闭广告
  18907. // */
  18908. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  18909. // this.isShowAd = false;
  18910. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  18911. // ",enforce=" + enforceRemove);
  18912. // },
  18913. //
  18914. // /**
  18915. // * 点击取消
  18916. // */
  18917. // onCancel: () => {
  18918. // console.log("BannerExpressAdPage==dislike......onCancel");
  18919. // }
  18920. //
  18921. // })
  18922. // }
  18923. /**
  18924. * 加载Banner广告
  18925. */
  18926. loadBannerAd(rit: string) {
  18927. // if (Utility.isNoble()) {
  18928. // return
  18929. // }
  18930. // if (!Utility.isPassInstallTime(2)) {
  18931. // return
  18932. // }
  18933. // this.isShowAd = false;
  18934. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  18935. // this.mAdSlot = new AdSlotBuilder()
  18936. // .setCodeId(rit)
  18937. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  18938. // .setAdCount(1)
  18939. // .setBidAdm(this.mBiddingAdm)
  18940. // .build()
  18941. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  18942. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  18943. // this.status = "广告加载中..."
  18944. }
  18945. /**
  18946. * 展示Banner广告
  18947. */
  18948. // showBannerAd() {
  18949. // if (!this.bannerAd) {
  18950. // return
  18951. // }
  18952. // this.isShowAd = true
  18953. // this.status = "已展示"
  18954. // }
  18955. /**
  18956. * 穿山甲广告代码结束
  18957. */
  18958. /**
  18959. * 处理歌单播放请求
  18960. */
  18961. private syncWebdavQueueWithoutRestart(): void {
  18962. try {
  18963. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  18964. return;
  18965. }
  18966. const webdavList = getWebdavVideoItems();
  18967. if (!ArrayUtil.isNotEmpty(webdavList)) {
  18968. return;
  18969. }
  18970. const currentPath = this.currentSong.filePath;
  18971. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  18972. if (targetIndex < 0) {
  18973. const memoryIndex = getWebdavCurrentPlayIndex();
  18974. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  18975. targetIndex = memoryIndex;
  18976. }
  18977. }
  18978. if (targetIndex < 0) {
  18979. targetIndex = 0;
  18980. }
  18981. this.songList = [...webdavList];
  18982. this.currentSongList = [...webdavList];
  18983. this.sonDataSource.pushArrayData(this.songList);
  18984. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  18985. this.curIndex = targetIndex;
  18986. PreferencesUtil.putSync('LastMusicList', this.songList);
  18987. this.skipNextPlaylistPersist = true
  18988. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  18989. } catch (error) {
  18990. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  18991. }
  18992. }
  18993. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  18994. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  18995. try {
  18996. const totalCount = songCount ?? songFilePaths.length;
  18997. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  18998. // 检查是否为WebDAV播放请求
  18999. if (playlistId === 'webdav-playlist') {
  19000. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  19001. // 从全局内存读取videoItems数据
  19002. const videoItems = getWebdavVideoItems();
  19003. const currentPlayIndex = getWebdavCurrentPlayIndex();
  19004. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  19005. if (videoItems && videoItems.length > 0) {
  19006. // 验证webdav_account_id设置情况
  19007. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  19008. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  19009. if(isJump){
  19010. this.setShowPlayTrue()//显示播放页
  19011. }
  19012. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  19013. return
  19014. } else {
  19015. return
  19016. }
  19017. }
  19018. if (playlistId === 'navidrome-playlist') {
  19019. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  19020. const videoItems = getNavidromeVideoItems();
  19021. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  19022. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  19023. if (videoItems && videoItems.length > 0) {
  19024. if(isJump){
  19025. this.setShowPlayTrue()//显示播放页
  19026. }
  19027. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  19028. return;
  19029. } else {
  19030. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  19031. return;
  19032. }
  19033. }
  19034. if (playlistId === 'find-album-playlist' || playlistId.indexOf('find-') === 0) {
  19035. Logger.info(`heanup 检测到发现页播放请求,从内存读取videoItems`)
  19036. const videoItems = getFindVideoItems();
  19037. const currentPlayIndex = getFindCurrentPlayIndex();
  19038. const findPlaylistMeta = getFindPlaylistMeta();
  19039. Logger.info(`heanup 发现页歌曲列表长度: ${videoItems.length}, 索引: ${currentPlayIndex}`)
  19040. Logger.info(
  19041. TAG,
  19042. `[remote-debug] handlePlaylistPlayRequest find-memory playlist=${playlistId}, loaded=${videoItems.length}, ` +
  19043. `declaredTotal=${totalCount}, sample=${this.buildSongListDebugLog(videoItems)}`
  19044. )
  19045. if (videoItems && videoItems.length > 0) {
  19046. if (isJump) {
  19047. this.setShowPlayTrue()
  19048. }
  19049. // 只有“随心所欲分页随机”才读取分页元数据,其他发现页队列仍按原有歌单模式处理。
  19050. const findMeta = isFindLocalRandomPagedPlaylist(playlistId) && findPlaylistMeta.isPagedLocalQueue
  19051. ? findPlaylistMeta
  19052. : undefined;
  19053. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount, findMeta)
  19054. return
  19055. } else {
  19056. Logger.warn('heanup 发现页播放请求缺少歌曲数据')
  19057. return
  19058. }
  19059. }
  19060. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  19061. const songMap: Map<number, VideoItem> = new Map()
  19062. let completedQueries = 0
  19063. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  19064. // 遍历所有文件路径,使用索引记录位置
  19065. for (let i = 0; i < songFilePaths.length; i++) {
  19066. const filePath = songFilePaths[i]
  19067. const index = i
  19068. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  19069. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  19070. const queryPromise = this.table.queryVideoByFilePath(filePath)
  19071. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  19072. queryPromise.then((videoItem) => {
  19073. completedQueries++
  19074. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  19075. if (videoItem) {
  19076. // 使用索引作为key保存到Map中,保持原始顺序
  19077. songMap.set(index, videoItem)
  19078. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  19079. } else {
  19080. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  19081. }
  19082. // 检查是否所有歌曲都已加载完成
  19083. if (completedQueries === songFilePaths.length) {
  19084. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  19085. // 按照索引顺序重建歌曲数组
  19086. const songs: VideoItem[] = []
  19087. for (let j = 0; j < songFilePaths.length; j++) {
  19088. const song = songMap.get(j)
  19089. if (song) {
  19090. songs.push(song)
  19091. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  19092. }
  19093. }
  19094. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  19095. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  19096. }
  19097. }).catch((error: Error) => {
  19098. completedQueries++
  19099. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  19100. // 即使出错也要检查是否完成所有查询
  19101. if (completedQueries === songFilePaths.length) {
  19102. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  19103. // 按照索引顺序重建歌曲数组
  19104. const songs: VideoItem[] = []
  19105. for (let j = 0; j < songFilePaths.length; j++) {
  19106. const song = songMap.get(j)
  19107. if (song) {
  19108. songs.push(song)
  19109. }
  19110. }
  19111. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  19112. }
  19113. })
  19114. }
  19115. } catch (error) {
  19116. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  19117. ToastUtil.showToast('播放失败')
  19118. }
  19119. }
  19120. /**
  19121. * 完成歌单加载并开始播放
  19122. */
  19123. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number,
  19124. findMeta?: FindPlaylistMeta) {
  19125. if (songs.length === 0) {
  19126. Logger.error('heanup 没有找到任何可播放的歌曲')
  19127. ToastUtil.showToast('没有找到可播放的歌曲')
  19128. return
  19129. }
  19130. const isFindPagedLocalQueue = !!findMeta?.isPagedLocalQueue;
  19131. this.songList = songs
  19132. this.currentSongList = songs // 同步更新 currentSongList
  19133. this.sonDataSource.pushArrayData(songs)
  19134. this.curIndex = startIndex
  19135. const actualTotal = totalCount ?? songs.length;
  19136. if (isFindPagedLocalQueue) {
  19137. // 这类队列只保存当前页歌曲,总数和分页游标放到独立状态里继续滚动加载。
  19138. this.applyFindPagedLocalQueueState(findMeta, actualTotal);
  19139. this.currentPlaylistSongFilePaths = [];
  19140. } else {
  19141. this.resetFindPagedLocalQueueState();
  19142. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  19143. }
  19144. // 如果是网盘播放,保存服务端总数到全局存储
  19145. if (!isFindPagedLocalQueue && totalCount && totalCount > 0 && songs.length > 0) {
  19146. const firstSong = songs[0];
  19147. if (firstSong && (isNavidromeType(firstSong.type) ||
  19148. isJellyfinType(firstSong.type) ||
  19149. isEmbyType(firstSong.type) ||
  19150. isAudioStationType(firstSong.type) ||
  19151. isPlexType(firstSong.type) ||
  19152. isDaoLiYuType(firstSong.type))) {
  19153. setNavidromeTotalCount(totalCount);
  19154. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  19155. }
  19156. }
  19157. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  19158. Logger.info(
  19159. TAG,
  19160. `[remote-debug] finishLoadingPlaylist playlist=${playlistName}, loaded=${songs.length}, actualTotal=${actualTotal}, ` +
  19161. `startIndex=${startIndex}, sample=${this.buildSongListDebugLog(songs)}`
  19162. );
  19163. if (songs[startIndex]) {
  19164. // 确保当前播放的歌曲也更新到存储
  19165. AppStorage.setOrCreate('currentSong', songs[startIndex])
  19166. if (isFindPagedLocalQueue) {
  19167. // 不要把发现页分页随机队列降级成普通歌单,否则后面又会触发全量 hydrate。
  19168. this.preserveExistingQueueOnNextPlay = true
  19169. this.nextPlayQueueScope = 'find_paged_local'
  19170. this.doPlay(songs[startIndex], startIndex, false)
  19171. } else {
  19172. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  19173. this.doPlay(songs[startIndex], startIndex, true)
  19174. }
  19175. }
  19176. PreferencesUtil.putSync('LastMusicList', this.songList)
  19177. this.skipNextPlaylistPersist = true
  19178. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  19179. }
  19180. }
  19181. //视频气泡窗口的布局
  19182. @Builder
  19183. function customPopupBuilder(dataBu: BubbleBean) {
  19184. List() {
  19185. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  19186. ListItem() {
  19187. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19188. Row() {
  19189. Column() {
  19190. Image(dataBu.imageRes[index])
  19191. .height(28)
  19192. .fillColor(dataBu.color)
  19193. .alignSelf(ItemAlign.Center)
  19194. }
  19195. .width(32)
  19196. Text(item)
  19197. .padding({
  19198. top: 10,
  19199. bottom: 10,
  19200. right: 10,
  19201. left: 10
  19202. })
  19203. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  19204. .textAlign(TextAlign.Start)
  19205. .width("100%")
  19206. }
  19207. }
  19208. .backgroundColor($r('app.color.settings_background_main'))
  19209. .margin({ top: 6, bottom: 6 })
  19210. }
  19211. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  19212. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  19213. TransitionEffect.scale({ x: 0, y: 0 })))
  19214. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  19215. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  19216. .onClick(() => {
  19217. dataBu.onItemClick?.(index)
  19218. })
  19219. })
  19220. }
  19221. .scrollBar(BarState.Off)
  19222. .width(120)
  19223. .divider({
  19224. strokeWidth: 1,
  19225. color: "#22FFFFFF"
  19226. })
  19227. }
  19228. // Function to calculate a hash for the file list
  19229. function simpleHash(fileList: string[]): string {
  19230. let hash = 0;
  19231. const str = fileList.join(',');
  19232. for (let i = 0; i < str.length; i++) {
  19233. const char = str.charCodeAt(i);
  19234. hash = (hash << 5) - hash + char;
  19235. hash |= 0; // Convert to 32bit integer
  19236. }
  19237. return hash.toString();
  19238. }
  19239. interface MoreItem {
  19240. id: number;
  19241. image: Resource;
  19242. title: string;
  19243. }
  19244. //视频气泡窗口的布局
  19245. @Builder
  19246. function cutPopupBuilder(dataBu: BubbleBean) {
  19247. Column() {
  19248. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  19249. .padding({
  19250. top: 10,
  19251. bottom: 10,
  19252. right: 10,
  19253. left: 10
  19254. })
  19255. .textAlign(TextAlign.Start)
  19256. .width(160)
  19257. .fontWeight(666)
  19258. .fontSize(16)
  19259. List() {
  19260. ForEach(dataBu.data, (item: string, index: number) => {
  19261. ListItem() {
  19262. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19263. Row() {
  19264. Column() {
  19265. Image($r('app.media.music_group'))
  19266. .height(28)
  19267. .fillColor(dataBu.color)
  19268. .alignSelf(ItemAlign.Center)
  19269. }
  19270. .width(32)
  19271. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  19272. .padding({
  19273. top: 10,
  19274. bottom: 10,
  19275. right: 10,
  19276. left: 10
  19277. })
  19278. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  19279. .fontSize(15)
  19280. }
  19281. }
  19282. .backgroundColor(Color.Transparent)
  19283. .margin({ top: 7, bottom: 7 })
  19284. }
  19285. .onClick(() => {
  19286. dataBu.onItemClick?.(index)
  19287. })
  19288. })
  19289. }
  19290. .scrollBar(BarState.Off)
  19291. .width(150)
  19292. .divider({
  19293. strokeWidth: 1,
  19294. color: "#22FFFFFF"
  19295. })
  19296. }
  19297. .height(300)
  19298. .padding({
  19299. bottom: 30
  19300. })
  19301. }
  19302. @Concurrent
  19303. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  19304. const alphabetSet = new Set<string>()
  19305. for (const item of items) {
  19306. let text = isShowFileName ? (item.fileName || '') :
  19307. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  19308. if (sortType === 0 || sortType == 1) {
  19309. text = item.artist || ''
  19310. } else if (sortType === 2 || sortType == 3) {
  19311. text = item.album || ''
  19312. }
  19313. if (text && text.length > 0) {
  19314. const first = getFirstLetter(text)
  19315. if (!alphabetSet.has(first)) {
  19316. alphabetSet.add(first)
  19317. }
  19318. }
  19319. }
  19320. const sorted = Array.from(alphabetSet).sort((a, b) => {
  19321. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  19322. return a.localeCompare(b)
  19323. }
  19324. return b.localeCompare(a)
  19325. })
  19326. return sorted
  19327. }
  19328. function getFileDirName(filePath: string,rootPath:string): string{
  19329. if(filePath===rootPath){
  19330. return '首页'
  19331. }
  19332. let result = FileUtil.getFileName(filePath)
  19333. if(StrUtil.isEmpty(result))
  19334. return ''
  19335. if(result.startsWith('.'))
  19336. result = result.replace(/\./g, '')
  19337. return result
  19338. }
  19339. //只扫描当前目录下文件(不扫描子文件夹)的方法
  19340. @Concurrent
  19341. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  19342. const table: MediaTable = new MediaTable(context);
  19343. try {
  19344. // 直接获取当前目录下的文件列表
  19345. const files = FileUtil.listFileSync(dirPath);
  19346. await Promise.all(files.map(async (file) => {
  19347. const fPath = `${dirPath}/${file}`;
  19348. // 跳过目录,只处理文件
  19349. if (FileUtil.isDirectory(fPath)) {
  19350. return;
  19351. }
  19352. // 跳过特定格式文件
  19353. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  19354. return;
  19355. }
  19356. // 检查是否为媒体文件
  19357. if (Utility.isMeidaByExtension(fPath)) {
  19358. let mType = CommonConstants.TYPE_LOCAL;
  19359. if (fPath.includes(lockPath)) {
  19360. mType = CommonConstants.TYPE_LOCK;
  19361. }
  19362. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  19363. context, fPath, mType, true
  19364. );
  19365. table.insert(mediaItem, (id: number) => {
  19366. // 插入回调函数
  19367. }, cover_api);
  19368. }
  19369. }));
  19370. } catch (error) {
  19371. console.error(' 扫描当前目录失败:', error);
  19372. }
  19373. }
  19374. //内嵌标签后更新库
  19375. @Concurrent
  19376. async function updateInfoDb(
  19377. context: Context,
  19378. filePath: string,
  19379. titleStr: string,
  19380. artistStr: string,
  19381. albumStr: string,
  19382. lyricConStr: string,
  19383. yearStr: string,
  19384. genreStr: string,
  19385. trackStr: string,
  19386. albumArtistStr: string,
  19387. composerStr: string,
  19388. lyricistStr: string,
  19389. commentStr: string,
  19390. discStr: string,
  19391. ): Promise<boolean> {
  19392. const table: MediaTable = new MediaTable(context);
  19393. await new Promise<void>((resolve, reject) => {
  19394. table.getRdbStore(context, (err:Error) => {
  19395. err ? reject(err) : resolve();
  19396. });
  19397. });
  19398. return await new Promise<boolean>((resolve) => {
  19399. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  19400. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  19401. (success: boolean, error?: string) => {
  19402. if (success) {
  19403. console.log("onecold 编辑信息成功,数据库已同步");
  19404. } else {
  19405. console.error("onecold 编辑信息数据库失败原因: " + error);
  19406. }
  19407. resolve(success);
  19408. });
  19409. });
  19410. }
  19411. @Concurrent
  19412. async function replaceLocalMusicCoverTask(
  19413. context: Context,
  19414. filePath: string,
  19415. sandboxCoverPath: string
  19416. ): Promise<boolean> {
  19417. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  19418. if (!coverResult) {
  19419. return false;
  19420. }
  19421. const table: MediaTable = new MediaTable(context);
  19422. await new Promise<void>((resolve, reject) => {
  19423. table.getRdbStore(context, (err: Error) => {
  19424. err ? reject(err) : resolve();
  19425. });
  19426. });
  19427. return await new Promise<boolean>((resolve) => {
  19428. table.updateCustomCoverPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  19429. (success: boolean, _error?: string) => {
  19430. resolve(success);
  19431. });
  19432. });
  19433. }