LocalMusic.ets 765 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372
  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 {
  18. FindPlaylistMeta,
  19. getFindVideoItems,
  20. getFindCurrentPlayIndex,
  21. getFindPlaylistMeta,
  22. resolveFindPagedLocalQueueMetaForPlayback
  23. } from '../common/util/FindPlaylistStore';
  24. import { triggerLoadMoreSongs, hasMoreData } from '../common/util/NavidromeRandomLoader';
  25. import {
  26. DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE,
  27. isFindLocalRandomPagedPlaylist
  28. } from '../common/util/LocalRandomPagedQueueHelper';
  29. import {
  30. ImplOnBufferingUpdateListener,
  31. ImplOnCompletionListener,
  32. ImplOnErrorListener,
  33. ImplOnInfoListener,
  34. ImplOnPreparedListener,
  35. ImplOnSeekCompleteListener,
  36. ImplOnTimedTextListener,
  37. ImplOnVideoSizeChangedListener
  38. } from '../common/IjkPlayerListenerImpls';
  39. import {
  40. ImageFancyModifier,
  41. } from '../common/util/AttributeModifierUtil'
  42. import {
  43. AppUtil,
  44. ArrayUtil,
  45. Base64Util,
  46. DateUtil,
  47. DeviceUtil,
  48. FileUtil,
  49. GlobalContext,
  50. LogUtil,
  51. MD5,
  52. PreferencesUtil,
  53. RandomUtil,
  54. StrUtil,
  55. ToastUtil
  56. } from '@pura/harmony-utils';
  57. import { imagePathToPixelMap } from '../common/util/CommUtils';
  58. import LyricUtil from '../common/util/LyricUtil';
  59. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  60. import { CommonConstants } from '../common/constants/CommonConstants';
  61. import { BaiduConstants } from '../common/constants/BaiduConstants';
  62. import { EventConstants } from '../common/constants/EventConstants';
  63. import Logger from '../common/util/Logger';
  64. import { filterPlaylistSongsByKeyword, findSongIndexByFilePath } from '../common/util/PlaylistSearchHelper';
  65. import { http } from '@kit.NetworkKit';
  66. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  67. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  68. import { BubbleBean } from '../viewmodel/BubbleBean';
  69. import { PopupPosition, XPopup } from '@chinalike/popup';
  70. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  71. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  72. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  73. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  74. import { Verify } from './Verify';
  75. import { taskpool } from '@kit.ArkTS';
  76. import { RotatingCover } from './RotatingCover';
  77. import { SpectrumView } from './spectrum/SpectrumView';
  78. import { PlayingIndicator } from './PlayingIndicator';
  79. import { PointLightButton } from './PointLight/PointLightButton';
  80. import { TitleBarPointLightButton } from './PointLight/TitleBarPointLightButton'
  81. import { PlayConstants } from '../common/constants/PlayConstants';
  82. import { MusicCardActionConstants } from '../common/player/MusicCardActionConstants';
  83. import { MusicCardManager, MusicCardPlaybackStateOptions } from '../common/player/MusicCardManager'
  84. import { effectKit } from '@kit.ArkGraphics2D';
  85. import { ColorConversion } from '../common/util/ColorConversion';
  86. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  87. import { AvSessionController } from '../controller/AvSessionController';
  88. import { EqualizerManager } from '../common/util/EqualizerManager';
  89. import { EqualizerViewWithCallback } from './EqualizerView';
  90. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  91. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  92. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  93. import { TagsContentCover } from '../view/TagsContentCover';
  94. import {
  95. DeviceChangeReason,
  96. IjkMediaPlayer,
  97. InterruptEvent,
  98. InterruptHintType,
  99. LogUtils,
  100. OnBufferingUpdateListener,
  101. OnCompletionListener,
  102. OnErrorListener,
  103. OnInfoListener,
  104. OnPreparedListener,
  105. OnSeekCompleteListener,
  106. OnTimedTextListener,
  107. OnVideoSizeChangedListener
  108. } from '@ohos/ijkplayer';
  109. import { PlayStatus } from '../common/PlayStatus';
  110. import fs from '@ohos.file.fs';
  111. import { image } from '@kit.ImageKit';
  112. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  113. import { media } from '@kit.MediaKit';
  114. import { UniversalDetector } from '@ohos/juniversalchardet';
  115. import { SettingPage } from '../pages/SettingPage';
  116. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  117. import { CommonConstants2 } from '../common/util/CommonConstants2';
  118. import { hilog } from '@kit.PerformanceAnalysisKit';
  119. import { LazyDataSource } from '../common/util/LazyDataSource';
  120. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  121. import { requestPlaybackPlayerOpen, setPlaybackRuntimeReady } from '../playback/PlaybackHostState';
  122. import { BackgroundAudioPlaybackHost } from '../playback/BackgroundAudioPlaybackHost'
  123. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  124. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  125. import { ringtone } from '@kit.RingtoneKit';
  126. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  127. import { resourceManager } from '@kit.LocalizationKit';
  128. import { deviceInfo } from '@kit.BasicServicesKit';
  129. import '../common/network/RemoteCacheRegistry';
  130. import { shouldWrapLocalMusicMenuInScroll } from '../common/util/LocalMusicMenuScrollHelper';
  131. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  132. import { MusicPlaybackController } from '../controller/MusicPlaybackController';
  133. import { PlaybackRuntime } from '../controller/PlaybackCoordinator'
  134. import { PlaybackSnapshot as PlaybackStateBridgeSnapshot, PlaybackStateBridge } from '../controller/PlaybackStateBridge'
  135. import { clearRegisteredPlaybackRuntime, registerPlaybackRuntime } from '../playback/PlaybackRuntimeRegistry';
  136. import { consumePendingPlaybackActivation } from '../playback/PlaybackActivationStore';
  137. import { PlaybackSnapshotStore } from '../playback/PlaybackSnapshotStore'
  138. import { resolvePlaybackSnapshotProgressValue } from '../playback/model/PlaybackSnapshot'
  139. import { lyricService, SongData } from '../common/service/LyricService';
  140. import { shouldResolveRemoteLyricOnPlay, tryResolveRemotePlaybackLyric } from '../common/util/RemotePlaybackLyricUtil';
  141. import { resolvePlayerDismissMorphTarget } from '../common/util/PlayerDismissHelper';
  142. import { isBaiduStreamingPlaybackUrl, resolveSeekGuardDecision } from '../common/util/PlaybackSeekGuard';
  143. import {
  144. cloneVideoItem,
  145. preloadNextSongIfNeeded,
  146. setVideoUrlForSong,
  147. getTypeOrder,
  148. isWebDavType,
  149. isSmbType,
  150. isNavidromeType,
  151. isFtpType,
  152. isBaiduType,
  153. isJellyfinType,
  154. isEmbyType,
  155. isAudioStationType,
  156. isPlexType,
  157. isRemoteCloudType,
  158. mergeCoverWithPriority,
  159. WorkerEditMusicResult,
  160. WebDavMetadataUpdatePayload,
  161. isDaoLiYuType
  162. } from '../common/util/RemotePlayerUtil';
  163. import {
  164. PlaylistPlayRequest,
  165. clearPendingPlaylistPlay
  166. } from '../common/util/PlaylistPlayRequestStore';
  167. import { resolvePlaylistDisplayCount } from '../common/util/PlaylistPlayDispatchHelper'
  168. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  169. import app from '@system.app';
  170. import { TextNodeController } from './PipLyricTextBuilder';
  171. import { IndexerView } from './IndexerView';
  172. import { KeyCode } from '@kit.InputKit';
  173. import { KnockController } from '../controller/KnockController';
  174. import { DeleteComptent } from '../view/DeleteComptent';
  175. import { ABLoopComptent } from '../view/ABLoopComptent';
  176. import { FixMessyView } from '../view/FixMessyView';
  177. import {
  178. parseCueFile,
  179. CueTrack,
  180. CueInfo,
  181. getCueTrackDuration,
  182. getCueTrackEndOffset,
  183. getCueTrackStartOffset,
  184. importCueTracks,
  185. isCueSplitItem
  186. } from '../common/util/CueUtils';
  187. import { CueComptent } from '../view/CueComptent';
  188. import { SearchHistoryUtil } from '../common/util/SearchHistoryUtil';
  189. import { IsoExtractComptent } from '../view/IsoExtractComptent';
  190. import PlaylistTable from '../common/util/PlaylistTable';
  191. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  192. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  193. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  194. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  195. import { Song } from '../viewmodel/Song';
  196. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  197. import { SongType } from '../common/enums/SongType';
  198. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  199. buildHttpHeadersWithWebDav,
  200. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  201. import PermissionUtil from '../common/util/PermissionUtil'
  202. import { EditAudio, setRingTone } from './EditAudio';
  203. import { ExtractAccompaniment } from './ExtractAccompaniment';
  204. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  205. import { AudioFormatConverter } from './AudioFormatConverter';
  206. import { MergeAudio } from './MergeAudio';
  207. import { AIVoiceSeparation } from './AIVoiceSeparation';
  208. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  209. import { ChangeTone } from './ChangeTone';
  210. import {
  211. hdsEffect,
  212. HdsVisualComponent,
  213. HdsSceneController,
  214. HdsSceneType,
  215. HdsVisualComponentAttribute,
  216. } from '@kit.UIDesignKit';
  217. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  218. import { getFirstLetter } from '../Constants';
  219. import { audio } from '@kit.AudioKit';
  220. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  221. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  222. import { LyricCopySheet } from './LyricCopySheet';
  223. import {
  224. IsoArchiveAudioEntry,
  225. IsoExtractFailureDetail,
  226. IsoExtractProgressMessage,
  227. IsoExtractTaskResult,
  228. listIsoAudioEntriesTask,
  229. extractIsoAudioEntriesTask
  230. } from '../common/util/IsoArchiveUtil';
  231. const TAG = 'LocalMusic';
  232. const HICAR_LOG_TAG = 'HiCarWindow';
  233. const PREF_PLAY_COVER_SCALE_GUIDE_SHOWN = 'play_cover_scale_guide_show';
  234. function logHiCarWindow(message: string): void {
  235. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  236. }
  237. export interface WorkerMetadataPayload {
  238. originFilePath: string;
  239. originId?: string;
  240. bit_rate?: string;
  241. duration?: string;
  242. sampleRate?: string;
  243. mimeType?: string;
  244. md5Str?: string;
  245. videoSize?: number;
  246. size?: string;
  247. pixelMapPath?: string;
  248. artist?: string;
  249. album?: string;
  250. name?: string;
  251. lyricContent?: string;
  252. bits_per_raw_sample?: string;
  253. channels?: string;
  254. channel_layout?: string;
  255. start_time?: string;
  256. genre?: string;
  257. year?: string;
  258. probe_score?: number;
  259. track?: string;
  260. disc?: string;
  261. ALBUMARTIST?: string;
  262. COMPOSER?: string;
  263. COMMENT?: string;
  264. LYRICIST?: string;
  265. nb_streams?: number;
  266. nb_programs?: number;
  267. error?: string;
  268. }
  269. interface WorkerMessageScanDone {
  270. code: 101;
  271. data: WorkerMessageScanDoneData;
  272. }
  273. interface WorkerMessageScanDoneData {
  274. }
  275. interface WorkerMessageMediaList {
  276. code: 102;
  277. data: Array<VideoItem>;
  278. totalCount: number;
  279. }
  280. interface WorkerMessageArtistList {
  281. code: 103;
  282. data1: Map<string, Array<VideoItem>>;
  283. data2: Array<VideoItem>;
  284. totalCount: number;
  285. }
  286. interface WorkerMessageAlbumList {
  287. code: 104;
  288. data1: Map<string, Array<VideoItem>>;
  289. data2: Array<VideoItem>;
  290. totalCount: number;
  291. }
  292. interface WorkerMessageMetadata {
  293. code: 105;
  294. data: WorkerMetadataPayload;
  295. }
  296. interface WorkerMessageEditResult {
  297. code: 106;
  298. data: WorkerEditMusicResult;
  299. }
  300. interface AlphaTaskItem {
  301. type: number;
  302. name?: string;
  303. pyStr?: string;
  304. fileName?: string;
  305. artist?: string;
  306. album?: string;
  307. }
  308. interface SongPlaybackPreparationResult {
  309. success: boolean;
  310. loadingShown: boolean;
  311. }
  312. interface OpenLocalSpecialListEventData {
  313. target?: string;
  314. }
  315. type LocalMusicWorkerMessage =
  316. WorkerMessageScanDone
  317. | WorkerMessageMediaList
  318. | WorkerMessageArtistList
  319. | WorkerMessageAlbumList
  320. | WorkerMessageMetadata
  321. | WorkerMessageEditResult;
  322. const DEFAULT_INDEX =
  323. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  324. 'X', 'Y', 'Z']
  325. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  326. // 元数据提取状态追踪
  327. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  328. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  329. // 定义接口
  330. interface HiCarAspectRatio {
  331. ratio: number;
  332. name: string;
  333. }
  334. interface GeneratedObjectLiteralInterface_1 {
  335. assetId: string;
  336. title: string;
  337. artist: string;
  338. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  339. mediaUri: string;
  340. // 该字段大写,音频'AUDIO',视频'VIDEO'
  341. mediaType: string;
  342. mediaSize: number;
  343. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  344. startPosition: number;
  345. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  346. duration: number;
  347. albumCoverUri: string;
  348. albumTitle: string;
  349. appName: string;
  350. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  351. drmScheme: string;
  352. }
  353. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  354. const ITEM_HEIGHT: number = 65; // 列表项中高度
  355. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  356. /**
  357. * 排序模式枚举
  358. * 定义各种排序方式的升序基准值
  359. */
  360. export enum SortMode {
  361. ByArtist = 0, // 按艺术家升序
  362. ByAlbum = 2, // 按专辑升序
  363. ByName = 4, // 按名称升序
  364. ByTime = 6, // 按时间升序
  365. ByAddTime = 7, // 按添加时间(只有降序)
  366. ByCount = 8, // 按数量升序
  367. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  368. }
  369. //功能强大的音乐播放器
  370. @Preview
  371. @Component
  372. export struct LocalMusic {
  373. @State default_layout:number = 0
  374. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  375. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  376. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  377. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  378. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  379. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  380. private audioRoutingManager?: audio.AudioRoutingManager
  381. private outputDeviceChangeCallback?: Callback<audio.DeviceChangeAction>
  382. private audioInterruptResumePending: boolean = false
  383. @State showFindLocation: boolean = true
  384. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  385. @State showSimple: boolean = true//开启沉浸模式
  386. @State isPaging: boolean = true;//是否分页加载机制
  387. @State isCoverRectangle: boolean = true;
  388. @State showZMIndex: boolean = false //是否右侧显示字母索引
  389. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  390. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  391. // 字母表
  392. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  393. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  394. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  395. @State selectAlphaBetIndex: number = 0
  396. @State isShowAlphaBet: boolean = false
  397. @State isScrolling: boolean = false
  398. @State isTouchingAlphaBet: boolean = false
  399. @State alphabetHeight: number = 0
  400. public enableShowAlphabet: boolean = true // 是否显示字母表
  401. private alphaBetHideTimer: number = 0
  402. private alphaBetRebuildTimer: number = 0
  403. private alphaBetDirty: boolean = false
  404. private alphaBetCacheKey: string = ''
  405. private alphaBetBuildVersion: number = 0
  406. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  407. //背景两侧流光控制器
  408. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  409. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  410. new HdsSceneController()
  411. .setSceneParams({
  412. backgroundMaskColors: [Color.Green, Color.Red],
  413. firstEdgeFlowLight: {
  414. startPos: 0,
  415. endPos: 0.5,
  416. color: Color.Red
  417. },
  418. secondEdgeFlowLight: {
  419. startPos: 0,
  420. endPos: -0.5,
  421. color: Color.Green
  422. }
  423. }) : undefined;
  424. //背景流光控制器
  425. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  426. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  427. new hdsEffect.ShaderEffectController():undefined;
  428. @State showAddSheet:boolean = false
  429. private loadingDialogId: string = ''
  430. private loadingProgressDialogId: string = ''
  431. @State isoAudioEntries: IsoArchiveAudioEntry[] = []
  432. @State selectedIsoAudioPaths: string[] = []
  433. @State isoSourceFileName: string = ''
  434. @State isIsoExtracting: boolean = false
  435. @State isoExtractProgress: number = 0
  436. @State isoExtractProgressText: string = ''
  437. @State isoExtractCurrentEntryName: string = ''
  438. private isoSourceFilePath: string = ''
  439. private isoExtractDestinationDir: string = ''
  440. private isoComponentId: number = 0
  441. private isoExtractProgressTimer: number = 0
  442. private isoExtractExpectedOutputPaths: Array<string> = []
  443. private isoExtractTotalBytes: number = 0
  444. private isoExtractDisplayedProgress: number = 0
  445. private isoExtractReceivedTaskProgress: boolean = false
  446. private isoExtractTask: taskpool.Task | undefined = undefined
  447. private isoExtractLastActivityTime: number = 0
  448. private readonly isoExtractStallTimeoutMs: number = 15000
  449. private isoExtractCanceled: boolean = false
  450. private isoExtractCancelMessage: string = ''
  451. searchController: SearchController = new SearchController()
  452. @State rightTopImage:Resource = $r('sys.symbol.sort')
  453. @State isEditAudio:boolean = false
  454. @State isExtractAcc:boolean = false
  455. @State isConverter:boolean = false
  456. @State isAIVoiceSeparation:boolean = false
  457. @State isExtractAudio:boolean = false
  458. @State isMergeAudio:boolean = false
  459. @State isCopyFileToDownLoad: boolean = false
  460. @State isChangeTone:boolean = false
  461. @State offHeight: number = 75
  462. @State currentSongList: Array<VideoItem> = []//当前歌单
  463. @Consume currentSongListName:string //当前歌单名称
  464. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  465. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  466. @State isRefreshing: boolean = false;
  467. @State maxRefreshingHeight: number = 100.0;
  468. @State isPlayerLoading: boolean = false; // 播放器加载状态
  469. private contentNode?: ComponentContent<Object> = undefined;
  470. private skipNextPlaylistPersist: boolean = false
  471. private playbackController: MusicPlaybackController = MusicPlaybackController.getInstance()
  472. private playbackStateBridge: PlaybackStateBridge = PlaybackStateBridge.getInstance()
  473. private playbackSnapshotStore: PlaybackSnapshotStore = new PlaybackSnapshotStore()
  474. private pendingInternalLoopModeReport: number = -1
  475. private playbackRuntime: PlaybackRuntime = {
  476. playQueue: async (queue: VideoItem[], startIndex: number, source: string, playType?: number) => {
  477. const safeIndex = queue.length <= 0 ? -1 : Math.max(0, Math.min(startIndex, queue.length - 1))
  478. if (safeIndex < 0) {
  479. return
  480. }
  481. const findPagedLocalMeta = resolveFindPagedLocalQueueMetaForPlayback(queue, safeIndex)
  482. if (playType !== undefined) {
  483. this.applyRequestedPlayType(playType)
  484. }
  485. if (findPagedLocalMeta?.isPagedLocalQueue) {
  486. this.playQueueScope = 'find_paged_local'
  487. this.applyFindPagedLocalQueueState(findPagedLocalMeta, findPagedLocalMeta.totalCount)
  488. this.currentPlaylistSongFilePaths = []
  489. } else {
  490. this.resetFindPagedLocalQueueState()
  491. }
  492. this.songList = [...queue]
  493. this.currentSongList = [...queue]
  494. this.sonDataSource.pushArrayData(this.songList)
  495. this.curIndex = safeIndex
  496. this.currentSong = queue[safeIndex]
  497. AppStorage.setOrCreate('currentSong', this.currentSong)
  498. if (source === 'controller-open') {
  499. requestPlaybackPlayerOpen()
  500. }
  501. await this.doPlay(queue[safeIndex], safeIndex, true)
  502. this.playbackStateBridge.replaceQueue(this.songList, this.curIndex)
  503. this.playbackStateBridge.updatePlaybackState(
  504. this.CONTROL_PlayStatus === PlayStatus.PLAY,
  505. this.mIjkMediaPlayer.getCurrentPosition(),
  506. this.getActiveDuration()
  507. )
  508. },
  509. playOrPause: async () => {
  510. await this.playOrPause()
  511. },
  512. playNext: async () => {
  513. await this.playNext()
  514. },
  515. playPrevious: async () => {
  516. await this.playPrevious()
  517. },
  518. seekTo: async (value: string, source?: string) => {
  519. await this.seekTo(value, source ?? 'coordinator')
  520. }
  521. }
  522. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  523. @State ratioL: number = 1;
  524. @State mediaKuCount: number = 0;
  525. @State albumCount: number = 0;
  526. @State artistCount: number = 0;
  527. @State fastForwardSeconds: string = '10'
  528. @State isShowBackFast: boolean = true//快进快退按钮
  529. @State isCanAuto:boolean = true
  530. @State opacityValueImage: number = 1;
  531. @State tipPopup:boolean = false
  532. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  533. @Consume mType: number;
  534. @StorageProp('themeColor') themeColor: string =
  535. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  536. themeMode: number = 0;
  537. @State titleName: string = '文件夹'//首页就是文件夹
  538. @State textStr: string = ''
  539. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  540. // private download_path: string = '';
  541. @Consume rootPath: string //音频根目录
  542. @Consume currentPath: string
  543. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  544. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  545. @State lockPath: string = ''
  546. @State favPath: string = ''
  547. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  548. @State historyPath: string = ''
  549. @State historyList: Array<VideoItem> = []
  550. @Consume isHistory: boolean
  551. static readonly HISTORY_MUSIC: string = 'music_historyList';
  552. private table: MediaTable = new MediaTable(getContext(this))
  553. private playlistTable: PlaylistTable | null = null
  554. private deletionWatcher: FileDeletionWatcher | null = null
  555. @State allPlaylists: Playlist[] = []
  556. @State isZero: boolean = false
  557. @State fileList: Array<string> = []
  558. @State dirList: Array<VideoItem> = []
  559. @Consume videoLocalList:VideoItem[]
  560. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  561. @State listRefreshKey: number = 0
  562. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  563. @State artistList: Array<VideoItem> = []; //艺术家文件
  564. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  565. @State artistSongCountMap: Map<string, number> = new Map();
  566. @State albumList: Array<VideoItem> = []; //专辑文件
  567. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  568. @State albumSongCountMap: Map<string, number> = new Map();
  569. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  570. @State imageOpacities: number[] = [];
  571. @Consume isCanBack: boolean
  572. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  573. @State showSingleLyric: boolean = false
  574. @State sortType: number = 4 //默认排序方式
  575. @State isShowSimi: boolean = false //是否显示私密音频
  576. @State isShowFAV: boolean = true //是否显示我的收藏
  577. @State isShowTitleBar: boolean = true //是否显示分类导航条
  578. @State isShowAllBar: boolean = true //是否显示播放全部条
  579. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  580. @State isEnableWordByWordLyric: boolean = true //是否开启逐字歌词
  581. @State isShowHistory: boolean = true //是否显示最近播放
  582. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  583. @State isHomeBgFollowMusicCover: boolean = true //主页背景随当前播放封面
  584. @State isGridMusic: boolean = false //是否网格布局
  585. @State isCircleBtn: boolean = false //是否圆形播放按钮
  586. @State twoFingerType: number = 3 //双支放大缩小的类型
  587. @State isScrollHide: boolean = false //是否滚动隐藏
  588. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  589. @State isStartAutoPlay: boolean = false //启动后自动播放
  590. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  591. @State isShowHeader: boolean = true
  592. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  593. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  594. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  595. @State rectangleCoverScale: number = 1
  596. @State rectangleCoverPinchValue: number = 1
  597. @State isSwipe: boolean = false //listItem的左滑开关
  598. @State openSkipSongAnimate: boolean = true//切歌动画效果
  599. @State isPlayPageSwipeNext: boolean = true // 播放页上滑切歌
  600. @State isLightText: boolean = true //是否开启歌词发光
  601. @State customizeBgPath: string | undefined = '';
  602. @StorageProp('customizeMusicBgPath') customizeMusicBgPath: string = '';
  603. @State isDarkMode: boolean = false
  604. @State lyricTextWeight: number = 400
  605. @State lyricTextWeightPip: number = 400
  606. @State currentSwiperIndex: number = 0
  607. @StorageLink('playbackHostOpenRequestToken') @Watch('onPlaybackHostOpenRequestChange')
  608. playbackHostOpenRequestToken: number = 0
  609. @StorageLink('playbackHostPlaylistRequestToken') @Watch('onPlaybackHostPlaylistRequestChange')
  610. playbackHostPlaylistRequestToken: number = 0
  611. @State blurValue: number = 0 //背景模糊
  612. @State bgBrightness: number = 0 //背景亮度
  613. private listScroller: ListScroller = new ListScroller()
  614. private playListScroller: Scroller = new Scroller()
  615. @State isOneKeyTags:boolean = false
  616. @State isFixMessy:boolean = false
  617. // 分页相关状态
  618. @State private currentPage: number = 0 // 当前页码
  619. @State private pageSize: number = 53 // 每页数量
  620. @State private totalCount: number = 0 // 总记录数
  621. @State private hasMoreData: boolean = true // 是否还有更多数据
  622. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  623. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  624. private pageHasMoreCache: Map<number, boolean> = new Map()
  625. private pageTotalCountCache: Map<number, number> = new Map()
  626. private prefetchingPages: Set<number> = new Set()
  627. private preloadStartRatio: number = 0.18
  628. private appendStartRatio: number = 0.30
  629. private earlyAppendReserveCount: number = 28
  630. private lastScrollTriggerPage: number = -1
  631. private lastVisibleEndIndex: number = -1
  632. private isPagingTransition: boolean = false
  633. private pagingScheduleTimer: number = 0
  634. private listScrollAlphaCheckAt: number = 0
  635. private listScrollPagingCheckAt: number = 0
  636. private listScrollLastAlphaStart: number = -1
  637. private listScrollLastPagingEnd: number = -1
  638. private gridScrollPagingCheckAt: number = 0
  639. private gridScrollLastPagingEnd: number = -1
  640. private waterScrollPagingCheckAt: number = 0
  641. private waterScrollLastPagingEnd: number = -1
  642. private gridWaterScrollIdleTimer: number = 0
  643. private gridWaterLastActiveTs: number = 0
  644. private listUpdateTimer: number = 0
  645. private listUpdateVersion: number = 0
  646. private detailBackTransitioning: boolean = false
  647. private mediaLibraryEnterTs: number = 0
  648. private mediaLibraryWarmupPrefetchTimer: number = 0
  649. private listVisibleStart: number = -1
  650. private listVisibleEnd: number = -1
  651. private listThumbWarmupCheckAt: number = 0
  652. private listThumbWarmupStart: number = -1
  653. private listThumbWarmupEnd: number = -1
  654. private gridThumbWarmupCheckAt: number = 0
  655. private gridThumbWarmupStart: number = -1
  656. private gridThumbWarmupEnd: number = -1
  657. private waterThumbWarmupCheckAt: number = 0
  658. private waterThumbWarmupStart: number = -1
  659. private waterThumbWarmupEnd: number = -1
  660. private gridVisibleStart: number = -1
  661. private gridVisibleEnd: number = -1
  662. private waterVisibleStart: number = -1
  663. private waterVisibleEnd: number = -1
  664. private lastHandledPlaybackHostOpenRequestToken: number = 0
  665. private lastHandledPlaybackHostPlaylistRequestToken: number = 0
  666. private titleBarToggleMinDelta: number = 12
  667. private titleBarLastCheckTs: number = 0
  668. @State private coverThumbVersion: number = 0
  669. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  670. private coverThumbCacheReady: boolean = false
  671. private pendingCoverThumbRefresh: boolean = false
  672. private playbackSnapshotHydrated: boolean = false
  673. private isHostSnapshotDisplayOnly: boolean = false
  674. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' | 'find_paged_local' = 'view'
  675. private isHydratingPlayList: boolean = false
  676. private preserveExistingQueueOnNextPlay: boolean = false
  677. private nextPlayQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' | 'find_paged_local' = 'view'
  678. private findPagedLocalQueuePageIndex: number = 0
  679. private findPagedLocalQueuePageSize: number = DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE
  680. private findPagedLocalQueueTotalCount: number = 0
  681. private findPagedLocalQueueHasMore: boolean = false
  682. private findPagedLocalQueueSortType: number = 4
  683. private isLoadingFindPagedLocalQueue: boolean = false
  684. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  685. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  686. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  687. @StorageProp('windowWidth') windowWidth: number = 0;
  688. @StorageProp('windowHeight') windowHeight: number = 0;
  689. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  690. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  691. private UNKONWN:string = '';
  692. private listArea: Area = {
  693. width: 0,
  694. height: 0,
  695. position: {},
  696. globalPosition: {}
  697. }
  698. @State private pointLightOptions: hdsEffect.PointLightOptions | undefined = undefined
  699. @State private activePointLightItemKey: string = ''
  700. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  701. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  702. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  703. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  704. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  705. private activePlaybackMemoryKey: string = '';
  706. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  707. private remoteRestoreSeekToken: number = 0;
  708. // 本次是否需要先seek到记忆点再开始播放
  709. private waitInitialSeekBeforeStart: boolean = false;
  710. // 本次播放记忆点(毫秒)
  711. private pendingMemorySeekPosition: number = 0;
  712. // 记忆播放seek兜底,避免一直转圈
  713. private initialSeekGuardTimer: number = 0;
  714. private readonly initialSeekGuardTimeoutMs: number = 2000;
  715. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  716. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  717. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  718. private lastSeekRequestMs: number = -1;
  719. private lastSeekSource: string = '';
  720. private seekTraceUntilTs: number = 0;
  721. private lastSeekTraceLogTs: number = 0;
  722. private readonly seekTraceLogWindowMs: number = 4000;
  723. private readonly seekTraceLogIntervalMs: number = 400;
  724. //瀑布流的列数横竖屏动态切换
  725. onIsLandscapeChange() {
  726. if(this.isLandscape){
  727. this.columns = 4
  728. }else{
  729. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  730. }
  731. }
  732. onColorModeChange() {
  733. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  734. }
  735. //点击某个歌单id发生变化的时候回调
  736. onIDChange(){
  737. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  738. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  739. if(this.modeType==4){
  740. this.titleName = this.currentSongListName
  741. this.rightTopImage = $r('sys.symbol.sort')
  742. //获取缓存
  743. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  744. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  745. if(StrUtil.isNotEmpty(cacheSongs)){
  746. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  747. this.updateListData(this.currentSongList, true)
  748. }
  749. this.doSongListTask()//获取歌单信息
  750. }
  751. }
  752. async doSongListTask() {
  753. // 初始化歌单数据库
  754. const playlistTable = new PlaylistTable(this.context);
  755. // 查询歌单中的所有歌曲
  756. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  757. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  758. if (ArrayUtil.isEmpty(playlistSongs)) {
  759. this.updateListData([], true)
  760. // 清空歌单路径列表
  761. this.currentPlaylistSongFilePaths = [];
  762. } else {
  763. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  764. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  765. this.updateListData(this.currentSongList, true)
  766. // 保存歌单的歌曲路径列表,用于随机播放
  767. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  768. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  769. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  770. // 只保存前100条记录到缓存中
  771. let canceList = this.currentSongList.slice(0, 100);
  772. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  773. JSON.stringify(canceList))
  774. } else {
  775. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  776. }
  777. }
  778. this.isRefreshing = false
  779. }
  780. async onModeChange(preserveList: boolean = false): Promise<void> {
  781. this.isFavMusic = false
  782. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  783. this.refreshDirVisibilitySettings()
  784. if (this.mediaLibraryWarmupPrefetchTimer) {
  785. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  786. this.mediaLibraryWarmupPrefetchTimer = 0
  787. }
  788. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  789. switch (this.modeType) {
  790. case 0:
  791. // 首页模式已在 resetAndLoadFirstPage 中处理
  792. // 切换模式时加载对应的排序类型
  793. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  794. this.sortType = this.loadSortTypeForCurrentMode()
  795. this.mediaLibraryEnterTs = 0
  796. break
  797. case 1:
  798. this.rightTopImage = $r('sys.symbol.sort')
  799. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  800. // 切换模式时加载对应的排序类型
  801. this.sortType = this.loadSortTypeForCurrentMode()
  802. this.mediaLibraryEnterTs = Date.now()
  803. break
  804. case 2:
  805. this.rightTopImage = $r('sys.symbol.sort')
  806. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  807. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  808. this.sortType = this.loadSortTypeForCurrentMode()
  809. this.mediaLibraryEnterTs = 0
  810. break
  811. case 3:
  812. this.rightTopImage = $r('sys.symbol.sort')
  813. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  814. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  815. this.sortType = this.loadSortTypeForCurrentMode()
  816. this.mediaLibraryEnterTs = 0
  817. break
  818. }
  819. // 模式切换时重置分页状态并加载第一页
  820. await this.resetAndLoadFirstPage(!preserveList);
  821. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  822. }
  823. // @Consume currentSong: VideoItem | undefined;
  824. @StorageLink('currentSong') @Watch('onHomeBgCurrentSongChange') currentSong: VideoItem | undefined = undefined;
  825. // @StorageLink('isPlay') isPlay: boolean = false;
  826. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  827. @State isShowCoverScaleGuide: boolean = false
  828. @StorageLink('songList') songList: Array<VideoItem> = [];
  829. @State translateY: number = 0;
  830. @State playDismissScale: number = 1;
  831. @State playDismissScaleY: number = 1;
  832. @State playDismissOpacity: number = 1;
  833. @State playDismissTranslateX: number = 0;
  834. @State playDismissBorderRadius: number = 0;
  835. @State playDismissProxySize: number = 0;
  836. @State playDismissProxyOpacity: number = 0;
  837. @State isShowSheet: boolean = false;
  838. @State isShowSheetView: boolean = false;
  839. @State isShowLyricCopySheet: boolean = false;
  840. @State lyricCopyLines: string[] = [];
  841. @State lyricSelectedIndexes: number[] = [];
  842. @State isShowTimeCloseView: boolean = false;
  843. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  844. private playDismissTimer: number = -1;
  845. private readonly playDismissContentDuration: number = 260;
  846. private readonly playDismissDotDuration: number = 160;
  847. private playOpenFromMiniBarPending: boolean = false;
  848. private playOpenTimer: number = -1;
  849. private readonly playOpenDotDuration: number = 120;
  850. private readonly playOpenExpandDuration: number = 320;
  851. @StorageLink('currIndex') curIndex: number = 0;
  852. @Consume isShowDrawer: boolean;
  853. @Consume offsetX: number;
  854. @State isFac: boolean = false;
  855. @State favList: Array<VideoItem> = []
  856. @Consume isFavMusic: boolean
  857. @State isClickedPLayAll: boolean = false;
  858. private scrollerForlist: ListScroller = new ListScroller();
  859. private knockController: KnockController | undefined = undefined;
  860. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  861. // 缓存机制
  862. private cache: Map<string, Array<VideoItem>> = new Map();
  863. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  864. // 持久化缓存
  865. private async saveCacheToStorage() {
  866. const cacheArray = Array.from(this.cache.entries());
  867. const stringCacheArray = Array.from(this.stringCache.entries());
  868. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  869. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  870. }
  871. // 载入缓存
  872. private async loadCacheFromStorage() {
  873. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  874. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  875. if (cacheString) {
  876. const parsedCache: Object | null = JSON.parse(cacheString);
  877. if (parsedCache && Array.isArray(parsedCache)) {
  878. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  879. this.cache = new Map(cacheArray);
  880. }
  881. }
  882. if (stringCacheString) {
  883. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  884. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  885. const stringCacheArray: [string, string][] = parsedStringCache;
  886. this.stringCache = new Map(stringCacheArray);
  887. }
  888. }
  889. }
  890. // 查找缓存
  891. private findCache(key: string): Array<VideoItem> | undefined {
  892. return this.cache.get(key);
  893. }
  894. // 查找字符串缓存
  895. private findStringCache(key: string): string | undefined {
  896. return this.stringCache.get(key);
  897. }
  898. // 添加缓存
  899. private addCache(key: string, value: Array<VideoItem>) {
  900. this.cache.set(key, value);
  901. }
  902. // 添加字符串缓存
  903. private addStringCache(key: string, value: string) {
  904. this.stringCache.set(key, value);
  905. }
  906. // 删除缓存
  907. private deleteCache(key: string) {
  908. this.cache.delete(key);
  909. this.saveCacheToStorage()
  910. }
  911. // 删除字符串缓存
  912. private deleteStringCache(key: string) {
  913. this.stringCache.delete(key);
  914. }
  915. // 多选机制
  916. @State selectedFiles: Array<VideoItem> = [];
  917. @Consume isMultiSelect: boolean;
  918. @State isAllSelected: boolean = false;
  919. @State appName: string = ''
  920. @State isHasDir: boolean = false
  921. @State packName: string = ''
  922. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  923. doSwipBack() {
  924. if(this.isSearchMode){
  925. console.info('onecold doSwipBack = ' +this.isSearchMode)
  926. this.isSearchMode = false
  927. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  928. this.searchText = ''
  929. this.getSortedFiles(this.currentPath)
  930. return
  931. }
  932. this.onSearchInput('')
  933. return
  934. }
  935. this.isZero = false
  936. if (this.modeType !== 0 && this.isCanBack) {
  937. if (this.detailBackTransitioning) {
  938. return
  939. }
  940. this.detailBackTransitioning = true
  941. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  942. this.isCanBack = false
  943. this.rightTopImage = $r('sys.symbol.sort')
  944. if (this.modeType == 2) {
  945. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  946. if (ArrayUtil.isNotEmpty(this.artistList)) {
  947. this.updateListData(this.artistList, true, true)
  948. }
  949. } else if (this.modeType == 3) {
  950. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  951. if (ArrayUtil.isNotEmpty(this.albumList)) {
  952. this.updateListData(this.albumList, true, true)
  953. }
  954. }
  955. // 返回列表页时保留当前列表,避免先清空导致闪现
  956. void this.onModeChange(true).then(() => {
  957. if (this.modeType == 2) {
  958. if (this.isGridMusic||this.twoFingerType==4) {
  959. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  960. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  961. if(this.twoFingerType==4){
  962. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  963. }else{
  964. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  965. }
  966. } else {
  967. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  968. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  969. }
  970. } else if (this.modeType == 3) {
  971. if (this.isGridMusic||this.twoFingerType==4) {
  972. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  973. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  974. if(this.twoFingerType==4){
  975. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  976. }else{
  977. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  978. }
  979. } else {
  980. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  981. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  982. }
  983. }
  984. this.detailBackTransitioning = false
  985. }).catch((error: Error) => {
  986. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  987. this.detailBackTransitioning = false
  988. })
  989. return
  990. }
  991. this.mediaLibraryEnterTs = 0
  992. if (this.isHistory || this.isFavMusic) {
  993. this.isHistory = false
  994. this.getSortedFiles(this.currentPath)
  995. return
  996. }
  997. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  998. animateTo({ duration: 555 }, () => {
  999. // 动画闭包内控制Image组件的出现和消失
  1000. this.isShowDrawer = !this.isShowDrawer
  1001. this.offsetX = 0
  1002. })
  1003. return
  1004. }
  1005. //返回上一级歌单的滚动位置
  1006. setTimeout(() => {
  1007. if (this.modeType == 0) {
  1008. if (this.isGridMusic||this.twoFingerType==4) {
  1009. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  1010. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  1011. if(this.twoFingerType==4){
  1012. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  1013. }else{
  1014. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1015. }
  1016. } else {
  1017. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  1018. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  1019. }
  1020. }
  1021. }, 100)
  1022. this.currentPath = Utility.getParentDirectory(this.currentPath)
  1023. Logger.info('this.currentPath2 = ' + this.currentPath)
  1024. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  1025. }
  1026. private triggerSwipeBackWithAnimation(): void {
  1027. animateTo({ duration: 555 }, () => {
  1028. this.doSwipBack()
  1029. })
  1030. }
  1031. private onPlaybackHostOpenRequestChange(): void {
  1032. if (this.playbackHostOpenRequestToken === this.lastHandledPlaybackHostOpenRequestToken) {
  1033. return
  1034. }
  1035. this.lastHandledPlaybackHostOpenRequestToken = this.playbackHostOpenRequestToken
  1036. if (!this.isShowPlay) {
  1037. this.setShowPlayTrue()
  1038. }
  1039. this.showPlayerView()
  1040. }
  1041. private onPlaybackHostPlaylistRequestChange(): void {
  1042. if (this.playbackHostPlaylistRequestToken === this.lastHandledPlaybackHostPlaylistRequestToken) {
  1043. return
  1044. }
  1045. this.lastHandledPlaybackHostPlaylistRequestToken = this.playbackHostPlaylistRequestToken
  1046. this.openPlayList()
  1047. }
  1048. private consumePendingPlaybackActivationAfterRestore(): void {
  1049. const activation = consumePendingPlaybackActivation()
  1050. if (!activation) {
  1051. return
  1052. }
  1053. if (activation.actionType === 'resume_play') {
  1054. void this.playbackController.playOrPause()
  1055. return
  1056. }
  1057. if (activation.actionType === 'play_previous') {
  1058. void this.playbackController.playPrevious()
  1059. return
  1060. }
  1061. if (activation.actionType === 'play_next') {
  1062. void this.playbackController.playNext()
  1063. return
  1064. }
  1065. if (activation.actionType === 'open_player') {
  1066. requestPlaybackPlayerOpen()
  1067. }
  1068. }
  1069. // 组件生命周期
  1070. aboutToAppear() {
  1071. registerPlaybackRuntime(this.playbackRuntime)
  1072. setPlaybackRuntimeReady(true)
  1073. this.playbackSnapshotHydrated = this.hydrateFromPlaybackSnapshot()
  1074. this.onPlaybackHostOpenRequestChange()
  1075. this.onPlaybackHostPlaylistRequestChange()
  1076. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  1077. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  1078. this.updateListData(this.videoLocalList)
  1079. }
  1080. // 初始化 PlaylistTable
  1081. this.playlistTable = new PlaylistTable(getContext(this))
  1082. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  1083. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  1084. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  1085. this.tipPopup = !this.tipPopup
  1086. PreferencesUtil.putSync('isFirstTiped',false)
  1087. }
  1088. this.loadSearchHistory()
  1089. this.initSetting()
  1090. this.syncEqualizerUi();
  1091. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  1092. Utility.getAppName(getContext(this)).then((appName: string) => {
  1093. this.appName = appName
  1094. })
  1095. this.packName = AppUtil.getBundleName()
  1096. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  1097. this.loadCacheFromStorage(); // 加载文件夹缓存
  1098. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  1099. this.initLoadCache()
  1100. this.mkDownLoadDir()
  1101. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  1102. // 监听广播事件(打开其他应用处理)
  1103. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  1104. this.saveVideoDatas([eventData.data?.message], true)
  1105. });
  1106. //侧滑广播接收时间
  1107. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  1108. // 监听广播事件(手势返回处理)
  1109. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  1110. this.triggerSwipeBackWithAnimation()
  1111. });
  1112. //ScanFilePage广播接收时间
  1113. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  1114. // 监听ScanFilePage广播事件(更新数据库)
  1115. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  1116. this.doUpdateData()
  1117. });
  1118. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  1119. emitter.on(eventEqualizerChanged, () => {
  1120. this.syncEqualizerUi();
  1121. if (this.mIjkMediaPlayer) {
  1122. const equalizerManager = EqualizerManager.getInstance();
  1123. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  1124. this.markEqualizerApplied();
  1125. }
  1126. });
  1127. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1128. // 监听广播事件(通用设置配置更新)
  1129. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1130. if(this.modeType ==4){
  1131. this.doSongListTask()//获取歌单信息
  1132. }
  1133. });
  1134. let eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  1135. emitter.on(eventQueueRefresh, () => {
  1136. this.syncWebdavQueueWithoutRestart();
  1137. });
  1138. let eventOpenLocalSpecialList: emitter.InnerEvent = { eventId: EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST }
  1139. emitter.on(eventOpenLocalSpecialList, (eventData: emitter.EventData) => {
  1140. const data = eventData.data as OpenLocalSpecialListEventData | undefined
  1141. const target = data?.target ?? ''
  1142. this.openSpecialLocalList(target)
  1143. });
  1144. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1145. // 监听广播事件(通用设置配置更新)
  1146. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1147. this.initSetting()
  1148. });
  1149. // 监听 WebDAV 元数据更新事件
  1150. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  1151. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  1152. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  1153. if (!payloads || payloads.length === 0) {
  1154. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  1155. return;
  1156. }
  1157. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  1158. // 处理每个元数据更新
  1159. for (let i = 0; i < payloads.length; i++) {
  1160. const payload = payloads[i];
  1161. if (!payload || !payload.filePath) {
  1162. continue;
  1163. }
  1164. // 重要:只更新当前正在播放的歌曲
  1165. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  1166. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  1167. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  1168. if (payload.name && payload.name.length > 0) {
  1169. this.name = payload.name;
  1170. if (this.currentSong) {
  1171. this.currentSong.name = payload.name;
  1172. }
  1173. }
  1174. if (payload.artist && payload.artist.length > 0) {
  1175. this.artist = payload.artist;
  1176. if (this.currentSong) {
  1177. this.currentSong.artist = payload.artist;
  1178. }
  1179. }
  1180. if (this.currentSong) {
  1181. const coverMutated = mergeCoverWithPriority(this.currentSong, payload.pixelMapPath,
  1182. payload.isCustomCover ?? 0);
  1183. if (coverMutated && this.currentSong.pixelMapPath) {
  1184. this.cover = this.currentSong.pixelMapPath;
  1185. Logger.info(TAG, `LocalMusic: 封面已更新: ${this.currentSong.pixelMapPath}`);
  1186. }
  1187. if (payload.md5Str && payload.md5Str.length > 0) {
  1188. this.currentSong.md5Str = payload.md5Str;
  1189. }
  1190. }
  1191. // 同步更新 AppStorage
  1192. AppStorage.setOrCreate('currentSong', this.currentSong);
  1193. } else {
  1194. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  1195. }
  1196. }
  1197. });
  1198. // 监听广播事件(通用设置配置更新)
  1199. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1200. this.doChangeSetting()
  1201. });
  1202. this.mIjkMediaPlayer.on('audioInterrupt', (event: InterruptEvent) => {
  1203. this.handleAudioInterrupt(event)
  1204. });
  1205. this.mIjkMediaPlayer.on('deviceChange', (event: InterruptEvent) => {
  1206. this.handlePlayerDeviceChange(event)
  1207. });
  1208. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1209. // 监听广播事件(hicar断开暂停播放)
  1210. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1211. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1212. this.audioInterruptResumePending = false
  1213. this.pause();
  1214. });
  1215. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1216. this.audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1217. this.outputDeviceChangeCallback = (deviceChanged: audio.DeviceChangeAction) => {
  1218. this.handleOutputDeviceChange(deviceChanged)
  1219. }
  1220. this.audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, this.outputDeviceChangeCallback);
  1221. this.makeWorker()
  1222. //折叠屏的屏幕显示模式变化
  1223. display.on('foldDisplayModeChange', (data) => {
  1224. this.doChangeBarHeight()
  1225. });
  1226. display.on('foldStatusChange', (data) => {
  1227. Logger.info('onecold foldStatusChange ')
  1228. });
  1229. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1230. this.rectangleCoverScale = PreferencesUtil.getNumberSync(SettingPage.RECTANGLE_COVER_SCALE, 1)
  1231. if (this.rectangleCoverScale < 0.7 || this.rectangleCoverScale > 1.4) {
  1232. this.rectangleCoverScale = 1
  1233. }
  1234. // 读取 themeMode 并同步 currentColorMode
  1235. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1236. this.applyThemeMode(this.themeMode)
  1237. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1238. AppStorage.setOrCreate('themeColor', themeColor);
  1239. this.themeColor = themeColor;
  1240. this.doChangeSetting()
  1241. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1242. LogUtil.info('onecold windowSizeChange')
  1243. this.doChangeBarHeight()
  1244. let viewWidth = px2vp(size.width);
  1245. let viewHeight = px2vp(size.height);
  1246. if(this.isPhoneLan()){
  1247. this.is_auto_hide_progress = false
  1248. if(this.isHiCar()){
  1249. return
  1250. }
  1251. setTimeout(() => {
  1252. this.is_auto_hide_progress = true
  1253. }, 6000)
  1254. }else{
  1255. this.startAutoHide()
  1256. }
  1257. });
  1258. this.eventHub.on('onStateChange', (fg: boolean) => {
  1259. this.isAppForeground = fg;
  1260. if (fg && this.curState === 'STARTED') {
  1261. this.stopPip();
  1262. this.syncLyricPositionNow();
  1263. }
  1264. });
  1265. }
  1266. //载入媒体库,艺术家,专辑等缓存
  1267. initLoadCache(){
  1268. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1269. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1270. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1271. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1272. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1273. if(ArrayUtil.isNotEmpty(cachedList)){
  1274. this.mediaKuList = cachedList
  1275. if(this.modeType==1){
  1276. this.updateListData(this.mediaKuList)
  1277. }
  1278. }
  1279. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1280. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1281. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1282. this.artistList = artistCachedList
  1283. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1284. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1285. this.artistMap = new Map(parsedArray);
  1286. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1287. if(this.modeType==2){
  1288. this.updateListData(this.artistList)
  1289. }
  1290. }
  1291. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1292. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1293. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1294. this.albumList = albumCachedList
  1295. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1296. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1297. this.albumMap = new Map(parsedArray);
  1298. if(this.modeType==3){
  1299. this.updateListData(this.albumList)
  1300. }
  1301. }
  1302. }
  1303. startAutoHide() {
  1304. if(this.isHiCar()){
  1305. return
  1306. }
  1307. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1308. console.info('onecold startAutoHide')
  1309. this.is_auto_hide_progress = false
  1310. setTimeout(() => {
  1311. this.is_auto_hide_progress = true
  1312. }, 6000)
  1313. }
  1314. }
  1315. applyThemeMode(mode: number) {
  1316. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1317. if (mode === 1) {
  1318. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1319. } else if (mode === 2) {
  1320. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1321. }
  1322. AppStorage.setOrCreate('currentColorMode', colorMode)
  1323. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1324. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1325. AppStorage.setOrCreate('themeMode', mode)
  1326. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1327. // 只有强制浅色/深色时才主动设置
  1328. const context = getContext(this) as common.UIAbilityContext
  1329. context.getApplicationContext().setColorMode(colorMode)
  1330. }
  1331. private isAudioPlaybackActive(): boolean {
  1332. return this.CONTROL_PlayStatus === PlayStatus.PLAY
  1333. || this.mIjkMediaPlayer.isPlaying()
  1334. || (!!this.castControllerWrapper && this.isCastPlaying)
  1335. }
  1336. private isBluetoothOutputDeviceType(deviceType: audio.DeviceType): boolean {
  1337. return deviceType === audio.DeviceType.BLUETOOTH_A2DP || deviceType === audio.DeviceType.BLUETOOTH_SCO
  1338. }
  1339. private isWiredOutputDeviceType(deviceType: audio.DeviceType): boolean {
  1340. return deviceType === audio.DeviceType.WIRED_HEADSET
  1341. || deviceType === audio.DeviceType.WIRED_HEADPHONES
  1342. || deviceType === audio.DeviceType.USB_HEADSET
  1343. }
  1344. private handleAudioInterrupt(event: InterruptEvent): void {
  1345. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1346. if (this.isSameTimePlay) {
  1347. Logger.info(TAG, `音频中断已忽略,当前为混音模式: ${JSON.stringify(event)}`)
  1348. return
  1349. }
  1350. const wasPlayingBeforeInterrupt = this.isAudioPlaybackActive()
  1351. switch (event.hintType) {
  1352. case InterruptHintType.INTERRUPT_HINT_PAUSE:
  1353. this.audioInterruptResumePending = wasPlayingBeforeInterrupt
  1354. if (wasPlayingBeforeInterrupt) {
  1355. this.pause(false)
  1356. }
  1357. break
  1358. case InterruptHintType.INTERRUPT_HINT_RESUME:
  1359. if (this.audioInterruptResumePending && this.CONTROL_PlayStatus === PlayStatus.PAUSE) {
  1360. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1361. this.audioInterruptResumePending = false
  1362. this.resumePlaybackAfterAudioInterrupt()
  1363. }
  1364. break
  1365. case InterruptHintType.INTERRUPT_HINT_STOP:
  1366. Logger.info(TAG, `收到音频中断 STOP,改为暂停等待用户手动恢复: ${JSON.stringify(event)}`)
  1367. this.audioInterruptResumePending = false
  1368. if (wasPlayingBeforeInterrupt) {
  1369. this.pause(false)
  1370. }
  1371. break
  1372. default:
  1373. Logger.info(TAG, `忽略未处理的音频中断类型: ${JSON.stringify(event)}`)
  1374. break
  1375. }
  1376. }
  1377. private resumePlaybackAfterAudioInterrupt(): void {
  1378. if (this.castControllerWrapper && this.isCastPlaying) {
  1379. this.castControllerWrapper.setPlaying().then(() => {
  1380. this.CONTROL_PlayStatus = PlayStatus.PLAY
  1381. this.setIsPlaying(true)
  1382. this.updateSessionPlayState(true)
  1383. this.playChange()
  1384. }).catch((error: BusinessError | Error) => {
  1385. Logger.error(TAG, `音频中断后恢复投播失败: ${error}`)
  1386. })
  1387. return
  1388. }
  1389. this.startPlayOrResumePlay()
  1390. }
  1391. private handlePlayerDeviceChange(event: InterruptEvent): void {
  1392. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1393. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) {
  1394. Logger.info(TAG, 'ijk deviceChange 检测到新设备接入,交由 AudioRoutingManager 处理')
  1395. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) {
  1396. Logger.info(TAG, 'ijk deviceChange 检测到旧设备移除,等待 AudioRoutingManager 精确判断是否暂停')
  1397. }
  1398. }
  1399. private handleOutputDeviceChange(deviceChanged: audio.DeviceChangeAction): void {
  1400. const descriptors = deviceChanged?.deviceDescriptors ?? []
  1401. if (descriptors.length <= 0) {
  1402. Logger.warn(TAG, `音频输出设备变化缺少描述信息: ${JSON.stringify(deviceChanged)}`)
  1403. return
  1404. }
  1405. Logger.info(TAG, `音频输出设备变化: type=${deviceChanged.type}, count=${descriptors.length}`)
  1406. const outputDescriptors = descriptors.filter((descriptor) => descriptor.deviceRole === audio.DeviceRole.OUTPUT_DEVICE)
  1407. if (outputDescriptors.length <= 0) {
  1408. Logger.info(TAG, `忽略非输出设备变化: ${JSON.stringify(deviceChanged)}`)
  1409. return
  1410. }
  1411. const hasBluetoothOutput = outputDescriptors.some((descriptor) =>
  1412. this.isBluetoothOutputDeviceType(descriptor.deviceType))
  1413. const hasWiredOutput = outputDescriptors.some((descriptor) =>
  1414. this.isWiredOutputDeviceType(descriptor.deviceType))
  1415. if (deviceChanged.type === audio.DeviceChangeType.CONNECT) {
  1416. if (hasBluetoothOutput) {
  1417. this.isBluetoothConnected = true
  1418. console.info('onecold 蓝牙设备已连接')
  1419. }
  1420. return
  1421. }
  1422. if (deviceChanged.type !== audio.DeviceChangeType.DISCONNECT) {
  1423. return
  1424. }
  1425. if (hasBluetoothOutput) {
  1426. this.isBluetoothConnected = false
  1427. this.lastBluetoothLyricLine = ''
  1428. console.info('onecold 蓝牙设备已断开')
  1429. if (this.currentSong) {
  1430. this.avSessionController.restoreOriginalMetadata(
  1431. this.currentSong.name || '',
  1432. this.currentSong.artist || ''
  1433. )
  1434. }
  1435. if (this.bluetoothDisconnectPause && this.isAudioPlaybackActive()) {
  1436. this.audioInterruptResumePending = false
  1437. console.info('heanup onecold 蓝牙音响断开, 暂停播放')
  1438. this.pause()
  1439. }
  1440. return
  1441. }
  1442. if (hasWiredOutput && this.isAudioPlaybackActive()) {
  1443. this.audioInterruptResumePending = false
  1444. console.info('heanup onecold 有线/USB耳机断开, 暂停播放')
  1445. this.pause()
  1446. }
  1447. }
  1448. initSetting() {
  1449. this.default_layout = PreferencesUtil.getNumberSync('default_layout', 0)
  1450. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1451. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1452. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1453. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1454. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1455. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1456. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1457. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1458. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1459. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1460. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1461. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1462. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1463. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1464. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1465. this.isHomeBgFollowMusicCover = PreferencesUtil.getBooleanSync(SettingPage.IS_HOME_BG_FOLLOW_MUSIC_COVER, true)
  1466. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1467. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  1468. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1469. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1470. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1471. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1472. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1473. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1474. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1475. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1476. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1477. this.syncCustomizeMusicBgPath()
  1478. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  1479. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1480. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, false)
  1481. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1482. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1483. this.isEnableWordByWordLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, true)
  1484. this.isLightText = PreferencesUtil.getBooleanSync(SettingPage.IS_LIGHT_TEXT, true)
  1485. this.syncWordByWordLyricMode()
  1486. this.syncLyricLightTextMode()
  1487. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1488. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1489. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1490. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1491. const volumeBoostPercent = PreferencesUtil.getNumberSync(this.volumeBoostPreferenceKey, 0)
  1492. this.volumeBoostPercent = Math.max(0, Math.min(volumeBoostPercent, this.volumeBoostMaxPercent))
  1493. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1494. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1495. this.isPlayPageSwipeNext = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYPAGE_SWIPE_NEXT, true)
  1496. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1497. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1498. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1499. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1500. this.refreshDirVisibilitySettings()
  1501. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1502. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1503. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1504. let audioManager = audio.getAudioManager();
  1505. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1506. if(this.isSameTimePlay){
  1507. //与其他应用同时播放,关键代码
  1508. let strategy: audio.AudioSessionStrategy = {
  1509. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1510. };
  1511. audioSessionManager.activateAudioSession(strategy).then(() => {
  1512. console.info('onecold Succeeded in doing activateAudioSession.');
  1513. }).catch((err: BusinessError) => {
  1514. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1515. });
  1516. }else{
  1517. let isActivated = audioSessionManager.isAudioSessionActivated();
  1518. if(isActivated){
  1519. audioSessionManager.deactivateAudioSession().then(() => {
  1520. console.info('Succeeded in doing deactivateAudioSession.');
  1521. }).catch((err: BusinessError) => {
  1522. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1523. });
  1524. }
  1525. }
  1526. //如果是hicar连接状态,这些都是false
  1527. if(this.isHiCar()){
  1528. this.autoHideTitle = false
  1529. this.isCoverRectangle= true
  1530. this.columns=4
  1531. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1532. {
  1533. this.isGridMusic= false//用list不用网格
  1534. this.isCoverTopBig = false
  1535. }
  1536. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1537. }
  1538. if (this.isSavePlayMode) {
  1539. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1540. }
  1541. }
  1542. private onHomeBgCurrentSongChange(): void {
  1543. this.syncCustomizeMusicBgPath()
  1544. }
  1545. private syncCustomizeMusicBgPath(): void {
  1546. if (!this.isHomeBgFollowMusicCover) {
  1547. return
  1548. }
  1549. const coverPath: string = this.currentSong?.pixelMapPath ?? ''
  1550. AppStorage.setOrCreate('customizeMusicBgPath', coverPath)
  1551. }
  1552. private isMusicCoverHomeBackgroundActive(): boolean {
  1553. return this.isHomeBgFollowMusicCover && this.customizeMusicBgPath.length > 0
  1554. }
  1555. doChangeSetting() {
  1556. this.initSetting()
  1557. this.deleteCache(this.currentPath)
  1558. if (this.modeType === 0) {
  1559. this.getSortedFiles(this.currentPath)
  1560. }
  1561. }
  1562. doChangeBarHeight() {
  1563. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1564. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1565. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1566. this.setBarHeightNormal()
  1567. }
  1568. }
  1569. onPageShow() {
  1570. this.knockController?.immersiveListening();
  1571. app.setImageCacheCount(100);
  1572. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1573. app.setImageRawDataCacheSize(104857600);
  1574. this.refreshDirVisibilitySettings();
  1575. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1576. }
  1577. //开启线程查看各个数据库
  1578. makeWorker() {
  1579. setTimeout(() => {
  1580. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1581. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1582. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1583. // workerInstance.postMessage({
  1584. // code: 1,
  1585. // data1: this.context,
  1586. // data2: this.rootPath,
  1587. // data3: this.lockPath,
  1588. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1589. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1590. // });
  1591. PreferencesUtil.putSync('isFirstApp', false)
  1592. } else {
  1593. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1594. workerInstance.postMessage({ code: 3, data: this.context });
  1595. workerInstance.postMessage({ code: 4, data: this.context });
  1596. this.getHistoryList(false)
  1597. }
  1598. }, 1000)
  1599. workerInstance.onmessage = (e: MessageEvents): void => {
  1600. const message = e.data as LocalMusicWorkerMessage;
  1601. switch (message.code) {
  1602. case 101: //第一次扫描文件夹入库
  1603. ToastUtil.showToast('刷新同步数据库成功!')
  1604. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1605. this.doAllUpdateData()
  1606. break;
  1607. case 102: //查询媒体库列表
  1608. this.isRefreshing = false
  1609. this.mediaKuList = message.data // 只包含前100条
  1610. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1611. this.mediaKuCount = mediaTotalCount;
  1612. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1613. Utility.doSortListAscending(this.mediaKuList)
  1614. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1615. // 媒体库模式下重新加载第一页(分页查询)
  1616. if (this.modeType === 1) {
  1617. this.resetAndLoadFirstPage();
  1618. }
  1619. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1620. // 只保存前100条记录到缓存中
  1621. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1622. break;
  1623. case 103: //收到查询艺术家列表
  1624. this.isRefreshing = false
  1625. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1626. this.artistList = message.data2; // 只包含前100个艺术家
  1627. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1628. this.artistCount = artistTotalCount;
  1629. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1630. this.artistMap.forEach((songs, artist) => {
  1631. nextArtistCountMap.set(artist, songs.length);
  1632. });
  1633. this.artistSongCountMap = nextArtistCountMap;
  1634. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1635. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1636. // 艺术家模式下重新加载第一页(分页查询)
  1637. if (this.modeType === 2) {
  1638. this.resetAndLoadFirstPage();
  1639. }
  1640. // 保存前100条艺术家列表
  1641. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1642. // 保存前60条艺术家的歌曲Map
  1643. const sortedEntries = Array.from(this.artistMap.entries());
  1644. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1645. break;
  1646. case 104: //收到查询专辑列表
  1647. this.isRefreshing = false
  1648. this.albumMap = message.data1;
  1649. this.albumList = message.data2
  1650. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1651. this.albumCount = albumTotalCount;
  1652. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1653. this.albumMap.forEach((songs, album) => {
  1654. nextAlbumCountMap.set(album, songs.length);
  1655. });
  1656. this.albumSongCountMap = nextAlbumCountMap;
  1657. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1658. // 专辑模式下重新加载第一页(分页查询)
  1659. if (this.modeType === 3) {
  1660. this.resetAndLoadFirstPage();
  1661. }
  1662. //查询完毕在启动是否自动播放
  1663. if (this.isStartAutoPlay&&this.isCanAuto) {
  1664. this.isCanAuto = false
  1665. console.info('onecold startPlayOrResumePlay 757')
  1666. this.startPlayOrResumePlay()
  1667. }
  1668. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1669. // 保存前100条专辑列表(Worker已经只发送了100条)
  1670. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1671. // 保存前60条专辑Map(Worker已经只发送了60条)
  1672. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1673. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1674. break;
  1675. case 105: // 缓存完成后返回的元数据
  1676. this.handleWorkerMetadataPayload(message.data);
  1677. break;
  1678. case 106: // 编辑音乐元数据和封面完成
  1679. this.handleEditMusicResult(message.data);
  1680. break;
  1681. }
  1682. };
  1683. // 在调用terminate后,执行onexit
  1684. workerInstance.onexit = (code) => {
  1685. metadataExtractionInFlight.clear();
  1686. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1687. }
  1688. workerInstance.onerror = (err: ErrorEvent) => {
  1689. metadataExtractionInFlight.clear();
  1690. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1691. }
  1692. }
  1693. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1694. if (!payload || !payload.originFilePath) {
  1695. return;
  1696. }
  1697. metadataExtractionInFlight.delete(payload.originFilePath);
  1698. if (payload.error) {
  1699. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1700. return;
  1701. }
  1702. this.applyMetadataToCollections(payload.originFilePath, payload);
  1703. }
  1704. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1705. const targets: Array<VideoItem> = [];
  1706. let mainListUpdated = false;
  1707. let playlistUpdated = false;
  1708. if (this.currentSong && this.currentSong.filePath === filePath) {
  1709. targets.push(this.currentSong);
  1710. }
  1711. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1712. if (!list || list.length === 0) {
  1713. return;
  1714. }
  1715. const found = Utility.getItemByFilePath(list, filePath);
  1716. if (found) {
  1717. markUpdated?.();
  1718. targets.push(found);
  1719. }
  1720. };
  1721. collectFromList(this.videoLocalList, () => {
  1722. mainListUpdated = true;
  1723. });
  1724. collectFromList(this.songList, () => {
  1725. playlistUpdated = true;
  1726. });
  1727. collectFromList(this.historyList);
  1728. collectFromList(this.favList);
  1729. const remoteManager = RemoteDriveManager.getInstance();
  1730. collectFromList(remoteManager.webDavSongs);
  1731. const updated = new Set<VideoItem>();
  1732. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1733. for (let i = 0; i < targets.length; i++) {
  1734. const target = targets[i];
  1735. if (!target || updated.has(target)) {
  1736. continue;
  1737. }
  1738. updated.add(target);
  1739. this.mergeVideoItemWithPayload(target, payload);
  1740. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1741. remoteMetadataUpdates.set(target.filePath, {
  1742. filePath: target.filePath,
  1743. pixelMapPath: target.pixelMapPath,
  1744. isCustomCover: target.isCustomCover,
  1745. md5Str: target.md5Str,
  1746. name: target.name,
  1747. artist: target.artist
  1748. });
  1749. }
  1750. }
  1751. if (this.currentSong && this.currentSong.filePath === filePath) {
  1752. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1753. if (payload.name) {
  1754. this.name = payload.name;
  1755. }
  1756. if (payload.artist) {
  1757. this.artist = payload.artist;
  1758. }
  1759. if (payload.pixelMapPath && this.currentSong?.pixelMapPath) {
  1760. this.cover = this.currentSong.pixelMapPath;
  1761. }
  1762. if (payload.lyricContent) {
  1763. this.applyInlineLyricContent(payload.lyricContent);
  1764. }
  1765. let avSessionDurationMs: number = this.duration;
  1766. if (payload.duration) {
  1767. const durationSeconds = Number(payload.duration);
  1768. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1769. avSessionDurationMs = durationSeconds * 1000;
  1770. this.duration = avSessionDurationMs;
  1771. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1772. this.durationStringTime = secondToTime(this.durationTime);
  1773. }
  1774. }
  1775. if (avSessionDurationMs > 0) {
  1776. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1777. }
  1778. this.currentSong = cloneVideoItem(this.currentSong);
  1779. AppStorage.setOrCreate('currentSong', this.currentSong);
  1780. }
  1781. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1782. if (primaryTarget) {
  1783. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1784. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1785. });
  1786. }
  1787. if (remoteMetadataUpdates.size > 0) {
  1788. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1789. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1790. }
  1791. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1792. }
  1793. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1794. // 关闭进度条
  1795. DialogHelper.closeDialog(this.loadingDialogId)
  1796. if (result.success) {
  1797. console.log("heanup 编辑信息成功,数据库已同步");
  1798. if (result.coverResult) {
  1799. ToastUtil.showToast('内嵌封面成功');
  1800. }
  1801. ToastUtil.showToast('内嵌音乐标签成功');
  1802. this.isShowMoreView = false;
  1803. this.name = this.titleStr;
  1804. // 同步当前播放的歌曲信息
  1805. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1806. this.currentSong.name = this.titleStr;
  1807. this.artist = this.artistStr;
  1808. this.currentSong.artist = this.artistStr;
  1809. this.currentSong.album = this.ablumStr;
  1810. this.currentSong.year = this.yearStr;
  1811. this.currentSong.genre = this.genreStr;
  1812. this.currentSong.track = this.trackStr;
  1813. this.currentSong.lyricContent = this.lyricConStr;
  1814. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1815. this.currentSong.COMPOSER = this.composerStr;
  1816. this.currentSong.LYRICIST = this.lyricistStr;
  1817. this.currentSong.COMMENT = this.commentStr;
  1818. }
  1819. // if (result.needRefreshList && this.modeType == 0) {
  1820. // this.deleteCache(this.currentPath);
  1821. // this.getSortedFiles(this.currentPath);
  1822. // }
  1823. // 同步编辑字段到本地列表
  1824. if (this.editingItem) {
  1825. this.syncEditedFields(this.editingItem);
  1826. this.syncListsAfterEdit(this.editingItem.filePath);
  1827. this.doUpateEditedFields(this.editingItem);
  1828. }
  1829. // 清理临时变量
  1830. this.longItemFilePath = '';
  1831. this.tempLyricContent = '';
  1832. this.isShowEdit = false;
  1833. this.imagePathStr = '';
  1834. } else {
  1835. console.error("heanup 编辑信息失败: " + result.error);
  1836. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1837. // 清理临时变量
  1838. this.longItemFilePath = '';
  1839. this.tempLyricContent = '';
  1840. this.isShowEdit = false;
  1841. this.imagePathStr = '';
  1842. }
  1843. }
  1844. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1845. if (value === undefined || value === null) {
  1846. return;
  1847. }
  1848. const text = value.toString();
  1849. if (!allowEmpty && text.trim().length === 0) {
  1850. return;
  1851. }
  1852. Reflect.set(target, key as string, value);
  1853. }
  1854. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1855. if (value === undefined || value === null || Number.isNaN(value)) {
  1856. return;
  1857. }
  1858. Reflect.set(target, key as string, value);
  1859. }
  1860. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1861. if (!target || !payload) {
  1862. return;
  1863. }
  1864. this.assignStringMetadata(target, 'name', payload.name);
  1865. this.assignStringMetadata(target, 'artist', payload.artist);
  1866. this.assignStringMetadata(target, 'album', payload.album);
  1867. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1868. this.assignStringMetadata(target, 'duration', payload.duration);
  1869. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1870. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1871. this.assignStringMetadata(target, 'md5Str', payload.md5Str);
  1872. this.assignStringMetadata(target, 'size', payload.size);
  1873. mergeCoverWithPriority(target, payload.pixelMapPath);
  1874. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1875. this.assignStringMetadata(target, 'genre', payload.genre);
  1876. this.assignStringMetadata(target, 'track', payload.track);
  1877. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1878. this.assignStringMetadata(target, 'channels', payload.channels);
  1879. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1880. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1881. this.assignStringMetadata(target, 'year', payload.year);
  1882. this.assignStringMetadata(target, 'disc', payload.disc);
  1883. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1884. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1885. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1886. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1887. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1888. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1889. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1890. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1891. }
  1892. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1893. if (!target || !source) {
  1894. return;
  1895. }
  1896. this.assignStringMetadata(target, 'name', source.name);
  1897. this.assignStringMetadata(target, 'artist', source.artist);
  1898. this.assignStringMetadata(target, 'album', source.album);
  1899. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1900. this.assignStringMetadata(target, 'duration', source.duration);
  1901. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1902. this.assignStringMetadata(target, 'md5Str', source.md5Str);
  1903. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1904. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1905. this.assignStringMetadata(target, 'size', source.size);
  1906. mergeCoverWithPriority(target, source.pixelMapPath, source.isCustomCover ?? 0);
  1907. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1908. this.assignStringMetadata(target, 'genre', source.genre);
  1909. this.assignStringMetadata(target, 'track', source.track);
  1910. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1911. this.assignStringMetadata(target, 'channels', source.channels);
  1912. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1913. this.assignStringMetadata(target, 'start_time', source.start_time);
  1914. this.assignStringMetadata(target, 'year', source.year);
  1915. this.assignStringMetadata(target, 'disc', source.disc);
  1916. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1917. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1918. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1919. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1920. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1921. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1922. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1923. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1924. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1925. target.remote_rel_path = source.remote_rel_path;
  1926. }
  1927. }
  1928. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1929. if (!item || !isRemoteCloudType(item.type)) {
  1930. return;
  1931. }
  1932. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1933. if (!storagePath) {
  1934. return;
  1935. }
  1936. try {
  1937. const cached = await this.table.queryVideoByFilePath(storagePath);
  1938. if (!cached) {
  1939. return;
  1940. }
  1941. this.mergeVideoItemFromSource(item, cached);
  1942. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1943. item.remote_rel_path = storagePath;
  1944. }
  1945. if (item === this.currentSong) {
  1946. if (StrUtil.isNotEmpty(item.name)) {
  1947. this.name = item.name;
  1948. }
  1949. if (StrUtil.isNotEmpty(item.artist)) {
  1950. this.artist = item.artist!;
  1951. }
  1952. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1953. this.cover = item.pixelMapPath!;
  1954. }
  1955. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1956. this.applyInlineLyricContent(item.lyricContent as string);
  1957. }
  1958. }
  1959. } catch (error) {
  1960. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1961. }
  1962. }
  1963. private applyInlineLyricContent(content: string): void {
  1964. if (StrUtil.isEmpty(content)) {
  1965. return;
  1966. }
  1967. this.lyricContent = content;
  1968. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1969. const lyric: Lyric = this.parser.parse(lines);
  1970. this.lyricController.setLyric(lyric);
  1971. this.lyricControllerXF.setLyric(lyric);
  1972. this.lyricControllerSingle.setLyric(lyric);
  1973. }
  1974. private extractParentPathFromStoragePath(path: string): string {
  1975. if (!path) {
  1976. return '';
  1977. }
  1978. const lastSlash = path.lastIndexOf('/');
  1979. if (lastSlash <= 0) {
  1980. return '';
  1981. }
  1982. return path.substring(0, lastSlash);
  1983. }
  1984. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1985. if (!target || !isRemoteCloudType(target.type)) {
  1986. return null;
  1987. }
  1988. if (isWebDavType(target.type)) {
  1989. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1990. if (storagePath) {
  1991. target.remote_rel_path = storagePath;
  1992. return storagePath;
  1993. }
  1994. return null;
  1995. }
  1996. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1997. return target.remote_rel_path;
  1998. }
  1999. return null;
  2000. }
  2001. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  2002. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  2003. return;
  2004. }
  2005. const storagePath = this.resolveRemoteStoragePath(target);
  2006. if (!storagePath) {
  2007. return;
  2008. }
  2009. const table = new MediaTable(this.context);
  2010. await new Promise<void>((resolve) => {
  2011. table.getRdbStore(this.context as Context, () => resolve());
  2012. });
  2013. const cloneItem = cloneVideoItem(target);
  2014. cloneItem.filePath = storagePath;
  2015. cloneItem.remote_rel_path = storagePath;
  2016. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  2017. await table.saveOrUpdateWebDavItem(cloneItem);
  2018. }
  2019. onPageHide() {
  2020. this.knockController?.immersiveDisableListening();
  2021. }
  2022. @State isFirstStartPlay: boolean = false
  2023. private async startFileDeletionWatcher(): Promise<void> {
  2024. if (!this.rootPath) {
  2025. return;
  2026. }
  2027. if (!this.deletionWatcher) {
  2028. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  2029. }
  2030. try {
  2031. await this.deletionWatcher.watchDirectories([
  2032. this.rootPath,
  2033. this.lockPath,
  2034. this.favPath,
  2035. this.historyPath
  2036. ]);
  2037. } catch (error) {
  2038. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  2039. }
  2040. }
  2041. //获取download_path
  2042. async mkDownLoadDir() {
  2043. const documentViewPicker = new picker.DocumentViewPicker()
  2044. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  2045. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  2046. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  2047. this.currentPath = this.rootPath
  2048. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  2049. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  2050. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  2051. Logger.info('onecold rootPath = ' + this.rootPath)
  2052. if (!FileUtil.accessSync(this.favPath)) {
  2053. FileUtil.mkdirSync(this.favPath)
  2054. }
  2055. if (!FileUtil.accessSync(this.historyPath)) {
  2056. FileUtil.mkdirSync(this.historyPath)
  2057. }
  2058. // await this.startFileDeletionWatcher();
  2059. this.getSortedFiles(this.rootPath).then(async () => {
  2060. this.isFavMusic = false
  2061. //穿山甲
  2062. // this.loadBannerAd(CSJUtil.getBannerID())
  2063. this.restoreLastPlayContext();
  2064. const hydratedFromSnapshot = this.playbackSnapshotHydrated || this.hydrateFromPlaybackSnapshot()
  2065. if (!hydratedFromSnapshot) {
  2066. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  2067. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  2068. if (ArrayUtil.isEmpty(this.songList)) {
  2069. this.songList = this.videoLocalList.filter(item =>
  2070. item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2071. } else if (this.currentSong !== undefined) {
  2072. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  2073. } else {
  2074. this.curIndex = 0
  2075. }
  2076. if (ArrayUtil.isNotEmpty(this.songList)) {
  2077. this.isFirstStartPlay = true
  2078. this.sonDataSource.pushArrayData(this.songList)
  2079. if (this.currentSong === undefined) {
  2080. this.isFirstStartPlay = false
  2081. this.currentSong = this.songList[0]
  2082. }
  2083. const restoredUrl = await this.resolvePlaybackUrlForCurrentSong('restore-last-song');
  2084. if (!restoredUrl) {
  2085. return;
  2086. }
  2087. this.videoUrl = restoredUrl;
  2088. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  2089. this.name = this.currentSong.name
  2090. this.cover = this.currentSong.pixelMapPath
  2091. this.playbackStateBridge.replaceQueue(this.songList, this.curIndex)
  2092. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  2093. this.consumePendingPlaybackActivationAfterRestore()
  2094. } else {
  2095. this.name = '空空如也'
  2096. }
  2097. }
  2098. })
  2099. this.getFavList(false)
  2100. }
  2101. getFavList(isFavRefresh: boolean) {
  2102. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  2103. this.favList = result
  2104. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  2105. this.videoLocalList = this.favList
  2106. this.updateListData(this.videoLocalList, true)
  2107. }
  2108. })
  2109. }
  2110. getHistoryList(isRefresh: boolean) {
  2111. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  2112. this.historyList = result
  2113. // for (let i = 0; i < this.historyList.length; i++) {
  2114. //
  2115. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  2116. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  2117. // }
  2118. if (isRefresh) {
  2119. this.videoLocalList = this.historyList
  2120. this.updateListData(this.videoLocalList, true)
  2121. }
  2122. })
  2123. }
  2124. // 组件消失生命周期
  2125. aboutToDisappear() {
  2126. console.info('LifeCycleComponent aboutToDisappear');
  2127. clearRegisteredPlaybackRuntime(this.playbackRuntime)
  2128. setPlaybackRuntimeReady(false)
  2129. this.playbackSnapshotHydrated = false
  2130. this.pendingInternalLoopModeReport = -1
  2131. if (this.alphaBetHideTimer) {
  2132. clearTimeout(this.alphaBetHideTimer);
  2133. this.alphaBetHideTimer = 0;
  2134. }
  2135. if (this.alphaBetRebuildTimer) {
  2136. clearTimeout(this.alphaBetRebuildTimer);
  2137. this.alphaBetRebuildTimer = 0;
  2138. }
  2139. if (this.pagingScheduleTimer) {
  2140. clearTimeout(this.pagingScheduleTimer);
  2141. this.pagingScheduleTimer = 0;
  2142. }
  2143. if (this.gridWaterScrollIdleTimer) {
  2144. clearTimeout(this.gridWaterScrollIdleTimer);
  2145. this.gridWaterScrollIdleTimer = 0;
  2146. }
  2147. if (this.listUpdateTimer) {
  2148. clearTimeout(this.listUpdateTimer);
  2149. this.listUpdateTimer = 0;
  2150. }
  2151. if (this.mediaLibraryWarmupPrefetchTimer) {
  2152. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  2153. this.mediaLibraryWarmupPrefetchTimer = 0;
  2154. }
  2155. this.clearInitialSeekGuardTimer();
  2156. this.alphaBetBuildVersion++;
  2157. this.gridWaterLastActiveTs = 0;
  2158. this.coverThumbCache.dispose();
  2159. this.coverThumbCacheReady = false;
  2160. this.pendingCoverThumbRefresh = false;
  2161. this.deletionWatcher?.stop();
  2162. this.knockController?.immersiveDisableListening();
  2163. this.curIndex = 0
  2164. this.isAppForeground = false;
  2165. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  2166. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  2167. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  2168. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  2169. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  2170. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  2171. emitter.off(EventConstants.EVENT_PLAYLIST_REFRESH_SORT);
  2172. emitter.off(EventConstants.EVENT_PLAY_QUEUE_REFRESH);
  2173. emitter.off(EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST);
  2174. emitter.off(EventConstants.EVENT_PLAY_PAUSE);
  2175. this.mDestroyPage = true;
  2176. this.audioInterruptResumePending = false;
  2177. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  2178. if (this.CONTROL_PlayStatus != PlayStatus.INIT && !this.isHostSnapshotDisplayOnly) {
  2179. this.stop();
  2180. }
  2181. this.isHostSnapshotDisplayOnly = false;
  2182. this.mIjkMediaPlayer.off('audioInterrupt');
  2183. this.mIjkMediaPlayer.off('deviceChange');
  2184. if (this.audioRoutingManager && this.outputDeviceChangeCallback) {
  2185. try {
  2186. this.audioRoutingManager.off('deviceChange', this.outputDeviceChangeCallback);
  2187. } catch (error) {
  2188. Logger.warn(TAG, `注销音频输出设备监听失败: ${(error as BusinessError).message ?? error}`);
  2189. }
  2190. }
  2191. this.outputDeviceChangeCallback = undefined;
  2192. this.audioRoutingManager = undefined;
  2193. if (workerInstance) {
  2194. workerInstance.terminate();
  2195. }
  2196. this.stopPip();
  2197. this.destroyPipController()
  2198. this.eventHub.off('onStateChange');
  2199. }
  2200. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  2201. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  2202. this.isFavMusic = false
  2203. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2204. if (isWorkerPost) {
  2205. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2206. }
  2207. if (this.modeType !== 0) {
  2208. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  2209. if (isOpen && destPath) {
  2210. this.openMusic(true, destPath, openItem)
  2211. }
  2212. return
  2213. }
  2214. console.info('onecold getSortedFiles 2')
  2215. this.isCanBack = false
  2216. this.currentPath = curPath
  2217. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2218. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2219. if (curPath === this.rootPath) {
  2220. this.rightTopImage = $r('sys.symbol.sort')
  2221. } else {
  2222. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2223. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2224. this.rightTopImage = $r('sys.symbol.chevron_left')
  2225. }
  2226. }
  2227. // Get the current file list and calculate its hash
  2228. this.fileList = FileUtil.listFileSync(curPath);
  2229. const currentHash = simpleHash(this.fileList);
  2230. // Check cache
  2231. const cachedValue = this.findCache(curPath);
  2232. Logger.info('onecold cachedValue = ' + cachedValue)
  2233. const cachedHash = this.findStringCache(curPath + '_hash');
  2234. const cachedDirList = this.findCache(curPath + "_dirList");
  2235. if (cachedValue !== undefined&&!this.isRefreshing) {
  2236. // this.videoLocalList = cachedValue;
  2237. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2238. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2239. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2240. }
  2241. this.isRefreshing = false
  2242. this.updateListData(cachedValue, undefined, immediateListUpdate)
  2243. if (scrollTopAfterUpdate) {
  2244. this.scrollToTopForCurrentLayout()
  2245. }
  2246. }
  2247. if (cachedDirList !== undefined) {
  2248. this.dirList = cachedDirList
  2249. }
  2250. //通过当前hash值和缓存hash判断list有没有变化
  2251. if (cachedValue && cachedHash === currentHash) {
  2252. return;
  2253. }
  2254. // this.fileList = FileUtil.listFileSync(curPath)
  2255. let directories: Array<VideoItem> = [];
  2256. let isoFiles: Array<VideoItem> = this.getLocalIsoItems(curPath, this.fileList);
  2257. let files: Array<VideoItem> = [];
  2258. for (let i = 0; i < this.fileList.length; i++) {
  2259. // console.info(`The name of file: ${this.fileList[i]}`);
  2260. let path = curPath + '/' + this.fileList[i]
  2261. if (FileUtil.isDirectory(path)) {
  2262. let item: VideoItem =
  2263. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2264. '')
  2265. if (this.isShowDir(item.name)) {
  2266. directories.push(item);
  2267. }
  2268. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2269. // Utility.doSortListAscending(directories)
  2270. } else {
  2271. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2272. let item: VideoItem =
  2273. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2274. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2275. files.push(item);
  2276. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2277. // this.doSortListAscending(files)
  2278. }
  2279. }
  2280. }
  2281. }
  2282. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2283. if (this.currentPath !== this.lockPath) {
  2284. files = result.filter(item => !this.isIsoLocalFile(item));
  2285. }
  2286. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2287. Utility.doSortListAscending(files)
  2288. Utility.doSortListAscending(isoFiles)
  2289. if (this.currentPath === this.rootPath) {
  2290. this.dirList = directories
  2291. this.addCache(curPath + "_dirList", this.dirList);
  2292. }
  2293. //插入广告先注释掉
  2294. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2295. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2296. // directories.push(adItem)
  2297. // }
  2298. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2299. this.videoLocalList = directories.concat(isoFiles).concat(files);
  2300. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2301. if (scrollTopAfterUpdate) {
  2302. this.scrollToTopForCurrentLayout()
  2303. }
  2304. if (ArrayUtil.isNotEmpty(files)) {
  2305. if (this.currentPath != this.rootPath) {
  2306. if (files) {
  2307. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2308. }
  2309. }
  2310. }
  2311. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2312. this.addCache(curPath, this.videoLocalList);
  2313. await this.saveCacheToStorage();
  2314. this.addStringCache(curPath + '_hash', currentHash);
  2315. }
  2316. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2317. for (let i = 0; i < this.videoLocalList.length; i++) {
  2318. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2319. }
  2320. // this.setButtonStatus()
  2321. this.openMusic(isOpen, destPath,openItem)
  2322. this.isRefreshing = false
  2323. });
  2324. }
  2325. //第三方app打开天天静听导入音乐后播放
  2326. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2327. if (isOpen&&destPath) {
  2328. if (destPath === undefined) {
  2329. // 处理 destPath 为 undefined 的情况
  2330. return
  2331. }
  2332. if (destPath.endsWith('.lrc')) {
  2333. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2334. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2335. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2336. this.initLyric(lyricPath);
  2337. }
  2338. return
  2339. }
  2340. if(openItem){
  2341. this.doPlay(openItem,0,false,true)
  2342. // this.isShowPlay = true
  2343. this.setShowPlayTrue()
  2344. }
  2345. }
  2346. }
  2347. //扫描文件夹入库
  2348. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2349. const files = FileUtil.listFileSync(curPath);
  2350. let mediaItems: VideoItem[] = [];
  2351. Logger.info('onecold scanDirectory start ')
  2352. for (const file of files) {
  2353. const fPath = `${curPath}/${file}`;
  2354. if (fPath === this.lockPath) {
  2355. Logger.info(`Skipping locked path: ${fPath}`);
  2356. continue;
  2357. }
  2358. if (FileUtil.isDirectory(fPath)) {
  2359. // Recursively scan subdirectories
  2360. const subDirItems = await this.scanDirectory(fPath);
  2361. mediaItems = mediaItems.concat(subDirItems);
  2362. } else {
  2363. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2364. // Process media files
  2365. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2366. let mediaItem: VideoItem =
  2367. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2368. mediaItems.push(mediaItem);
  2369. this.table.insert(mediaItem, (id: number) => {
  2370. });
  2371. }
  2372. }
  2373. }
  2374. return mediaItems;
  2375. }
  2376. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2377. this.isShowTitleBar = true
  2378. const shouldAnimate = !immediate
  2379. if (this.listUpdateTimer) {
  2380. clearTimeout(this.listUpdateTimer)
  2381. this.listUpdateTimer = 0
  2382. }
  2383. const updateVersion = ++this.listUpdateVersion
  2384. if (shouldAnimate) {
  2385. this.getUIContext().animateTo({ duration: 666 }, () => {
  2386. this.opacityItem = 0.5;
  2387. });
  2388. }
  2389. const applyListData = () => {
  2390. if (updateVersion !== this.listUpdateVersion) {
  2391. return
  2392. }
  2393. this.videoLocalList = mList;
  2394. if (!noSort) {
  2395. if (this.modeType === 0 || this.modeType === 1) {
  2396. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2397. this.doSortType(this.sortType)
  2398. }
  2399. }
  2400. this.dataSource.pushArrayData(this.videoLocalList)
  2401. if (shouldAnimate) {
  2402. this.getUIContext().animateTo({ duration: 666 }, () => {
  2403. this.opacityItem = 1;
  2404. });
  2405. } else {
  2406. this.opacityItem = 1;
  2407. }
  2408. this.setButtonStatus()
  2409. //添加到字母索引表
  2410. this.markAlphaBetDirty()
  2411. };
  2412. if (immediate) {
  2413. applyListData();
  2414. return;
  2415. }
  2416. this.listUpdateTimer = setTimeout(() => {
  2417. this.listUpdateTimer = 0
  2418. applyListData();
  2419. }, 200);
  2420. }
  2421. getCurFileList(): Array<VideoItem> {
  2422. const source = this.isSearchMode ? this.filteredList : this.videoLocalList
  2423. let files: Array<VideoItem> = [];
  2424. if (ArrayUtil.isNotEmpty(source)) {
  2425. for (let i = 0; i < source.length; i++) {
  2426. if (this.isSelectableLocalItem(source[i])) {
  2427. files.push(source[i]);
  2428. }
  2429. }
  2430. }
  2431. return files
  2432. }
  2433. private isProtectedLocalDirectory(item: VideoItem): boolean {
  2434. return item.type === CommonConstants.TYPE_IS_DIR &&
  2435. (item.name === LocalMusic.STR_LOCK_VIDEO ||
  2436. item.name === LocalMusic.STR_FAC_VIDEO ||
  2437. item.name === LocalMusic.STR_HISTORY_MUSIC)
  2438. }
  2439. private isIsoLocalFile(item?: VideoItem | null): boolean {
  2440. if (!item || item.type !== CommonConstants.TYPE_LOCAL) {
  2441. return false
  2442. }
  2443. return Utility.isIsoByExtension(item.filePath || item.fileName || item.name || '')
  2444. }
  2445. private supportsLocalAudioActions(item: VideoItem): boolean {
  2446. return !!item && item.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(item)
  2447. }
  2448. private buildLocalIsoItem(filePath: string, fileName?: string): VideoItem {
  2449. const displayName = fileName || FileUtil.getFileName(filePath) || filePath
  2450. let fileSize = 0
  2451. try {
  2452. const stat = fs.statSync(filePath) as fs.Stat
  2453. if (typeof stat.size === 'number') {
  2454. fileSize = stat.size
  2455. }
  2456. } catch (_error) {
  2457. }
  2458. const item = new VideoItem(
  2459. displayName,
  2460. filePath,
  2461. filePath,
  2462. CommonConstants.TYPE_LOCAL,
  2463. fileSize,
  2464. Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
  2465. Utility.formatFSize(fileSize),
  2466. '',
  2467. 'ISO 镜像',
  2468. '可提取音频',
  2469. displayName
  2470. )
  2471. item.mimeType = 'application/x-iso9660-image'
  2472. item.duration = ''
  2473. return item
  2474. }
  2475. private getLocalIsoItems(curPath: string, fileNames?: Array<string>): Array<VideoItem> {
  2476. let sourceNames: Array<string> = []
  2477. if (fileNames !== undefined && fileNames.length > 0) {
  2478. sourceNames = fileNames
  2479. } else {
  2480. const listedNames = FileUtil.listFileSync(curPath)
  2481. sourceNames = listedNames ? listedNames : []
  2482. }
  2483. const isoItems: Array<VideoItem> = []
  2484. for (let i = 0; i < sourceNames.length; i++) {
  2485. const name = sourceNames[i]
  2486. const fullPath = `${curPath}/${name}`
  2487. if (FileUtil.isDirectory(fullPath) || !Utility.isIsoByExtension(fullPath)) {
  2488. continue
  2489. }
  2490. isoItems.push(this.buildLocalIsoItem(fullPath, name))
  2491. }
  2492. Utility.doSortListAscending(isoItems)
  2493. return isoItems
  2494. }
  2495. private filterOutLocalIsoItems(items: Array<VideoItem>): Array<VideoItem> {
  2496. return items.filter(item => !this.isIsoLocalFile(item))
  2497. }
  2498. private isSelectableLocalItem(item: VideoItem): boolean {
  2499. if (!item) {
  2500. return false
  2501. }
  2502. if (item.type === CommonConstants.TYPE_LOCAL) {
  2503. return true
  2504. }
  2505. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2506. return !this.isProtectedLocalDirectory(item)
  2507. }
  2508. return false
  2509. }
  2510. private isLocalItemSelected(item: VideoItem): boolean {
  2511. return this.selectedFiles.some(x => x.filePath === item.filePath)
  2512. }
  2513. private hasSelectedDirectories(): boolean {
  2514. return this.selectedFiles.some(item => item.type === CommonConstants.TYPE_IS_DIR)
  2515. }
  2516. private getSelectedPlayableFiles(): Array<VideoItem> {
  2517. return this.selectedFiles.filter(item => item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2518. }
  2519. private syncLocalSelectionState(): void {
  2520. const selectableItems = this.getCurFileList()
  2521. const selectableKeys: Set<string> = new Set(selectableItems.map(item => item.filePath))
  2522. const nextSelected = this.selectedFiles.filter(item => selectableKeys.has(item.filePath))
  2523. if (nextSelected.length !== this.selectedFiles.length) {
  2524. this.selectedFiles = [...nextSelected]
  2525. }
  2526. this.isAllSelected = nextSelected.length > 0 && nextSelected.length === selectableItems.length
  2527. }
  2528. private enterLocalMultiSelect(item: VideoItem): void {
  2529. if (!this.isSelectableLocalItem(item)) {
  2530. return
  2531. }
  2532. if (!this.isMultiSelect) {
  2533. this.isMultiSelect = true
  2534. }
  2535. if (!this.isLocalItemSelected(item)) {
  2536. this.selectedFiles = [...this.selectedFiles, item]
  2537. }
  2538. this.syncLocalSelectionState()
  2539. }
  2540. private selectSingleItemForDelete(item: VideoItem): void {
  2541. if (!this.isSelectableLocalItem(item)) {
  2542. return
  2543. }
  2544. this.selectedFiles = [item]
  2545. this.isAllSelected = false
  2546. }
  2547. setButtonStatus() {
  2548. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2549. this.isZero = false
  2550. } else {
  2551. this.isZero = true
  2552. }
  2553. if (this.currentPath !== this.rootPath &&
  2554. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2555. this.isHasDir = true //不为空,说明有子文件夹
  2556. } else {
  2557. this.isHasDir = false
  2558. }
  2559. }
  2560. private getPlayListDisplayCount(): number {
  2561. if (this.playQueueScope === 'history') {
  2562. return this.historyList.length;
  2563. }
  2564. if (this.playQueueScope === 'fav') {
  2565. return this.favList.length;
  2566. }
  2567. if (this.playQueueScope === 'find_paged_local') {
  2568. const pagedCount = this.findPagedLocalQueueTotalCount > 0 ? this.findPagedLocalQueueTotalCount : this.totalCount;
  2569. if (pagedCount > 0) {
  2570. return pagedCount;
  2571. }
  2572. }
  2573. if (this.playQueueScope === 'playlist') {
  2574. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2575. // 如果是,优先返回服务端总数
  2576. const navidromeTotalCount = getNavidromeTotalCount();
  2577. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2578. if (navidromeTotalCount > 0 && this.currentSong && (
  2579. isNavidromeType(this.currentSong.type) ||
  2580. isJellyfinType(this.currentSong.type) ||
  2581. isEmbyType(this.currentSong.type) ||
  2582. isAudioStationType(this.currentSong.type) ||
  2583. isPlexType(this.currentSong.type) ||
  2584. isDaoLiYuType(this.currentSong.type)
  2585. )) {
  2586. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2587. return navidromeTotalCount;
  2588. }
  2589. const displayCount = resolvePlaylistDisplayCount(this.currentSongList.length, this.songList.length);
  2590. Logger.info('heanup getPlayListDisplayCount',
  2591. `返回歌单数量: currentSongList=${this.currentSongList.length}, songList=${this.songList.length}, display=${displayCount}`);
  2592. return displayCount;
  2593. }
  2594. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2595. return this.totalCount;
  2596. }
  2597. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2598. return this.songList.length;
  2599. }
  2600. private restoreLastPlayContext(): void {
  2601. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2602. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single' ||
  2603. scope === 'find_paged_local') {
  2604. this.playQueueScope = scope;
  2605. } else {
  2606. this.playQueueScope = 'view';
  2607. }
  2608. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2609. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2610. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2611. this.totalCount = lastTotalCount;
  2612. }
  2613. if (this.playQueueScope === 'find_paged_local' && lastTotalCount > 0) {
  2614. this.findPagedLocalQueueTotalCount = lastTotalCount;
  2615. this.findPagedLocalQueueHasMore = this.songList.length < lastTotalCount;
  2616. }
  2617. }
  2618. private hydrateFromPlaybackSnapshot(): boolean {
  2619. if (this.playbackSnapshotHydrated) {
  2620. return true
  2621. }
  2622. const snapshot = this.playbackSnapshotStore.read()
  2623. if (!snapshot) {
  2624. return false
  2625. }
  2626. const recovered = this.playbackSnapshotStore.recoverQueueState(snapshot)
  2627. if (ArrayUtil.isEmpty(recovered.queue) || recovered.currentSong === undefined) {
  2628. return false
  2629. }
  2630. this.songList = recovered.queue
  2631. this.currentSongList = [...recovered.queue]
  2632. this.curIndex = recovered.currentIndex
  2633. this.currentSong = recovered.currentSong
  2634. if (snapshot.cover && StrUtil.isEmpty(this.currentSong.pixelMapPath)) {
  2635. this.currentSong.pixelMapPath = snapshot.cover
  2636. }
  2637. this.playType = snapshot.playType
  2638. this.isFirstStartPlay = true
  2639. this.videoUrl = this.currentSong.filePath
  2640. this.name = snapshot.currentSongName !== '' ? snapshot.currentSongName : this.currentSong.name
  2641. this.artist = snapshot.currentArtist ?? this.currentSong.artist ?? ''
  2642. this.cover = snapshot.cover ?? this.currentSong.pixelMapPath
  2643. this.CONTROL_PlayStatus = snapshot.isPlaying ? PlayStatus.PLAY : PlayStatus.PAUSE
  2644. this.progressValue = resolvePlaybackSnapshotProgressValue(
  2645. snapshot.positionMs,
  2646. snapshot.durationMs,
  2647. this.PROGRESS_MAX_VALUE
  2648. )
  2649. this.slideEnable = snapshot.durationMs > 0
  2650. this.currentTime = this.stringForTime(snapshot.positionMs)
  2651. this.totalTime = this.stringForTime(snapshot.durationMs)
  2652. this.duration = snapshot.durationMs
  2653. this.durationTime = Math.floor(snapshot.durationMs / 1000)
  2654. this.sonDataSource.pushArrayData(this.songList)
  2655. const bridgeSnapshot: PlaybackStateBridgeSnapshot = {
  2656. queue: this.songList,
  2657. currentIndex: this.curIndex,
  2658. currentSong: this.currentSong,
  2659. isPlaying: snapshot.isPlaying,
  2660. positionMs: snapshot.positionMs,
  2661. durationMs: snapshot.durationMs
  2662. }
  2663. this.playbackStateBridge.restoreSnapshot(bridgeSnapshot)
  2664. AppStorage.setOrCreate('songList', this.songList)
  2665. AppStorage.setOrCreate('currIndex', this.curIndex)
  2666. AppStorage.setOrCreate('currentSong', this.currentSong)
  2667. AppStorage.setOrCreate('CONTROL_PlayStatus', this.CONTROL_PlayStatus)
  2668. AppStorage.setOrCreate('progressValue', this.progressValue)
  2669. AppStorage.setOrCreate('cover', this.cover ?? '')
  2670. this.playbackSnapshotHydrated = true
  2671. this.isHostSnapshotDisplayOnly = true
  2672. Logger.info(TAG,
  2673. `从后台宿主快照恢复页面状态 song=${this.currentSong.name}, index=${this.curIndex}, ` +
  2674. `isPlaying=${snapshot.isPlaying}, position=${snapshot.positionMs}`)
  2675. return true
  2676. }
  2677. private resetFindPagedLocalQueueState(): void {
  2678. // 退出“随心所欲”分页队列时,避免旧分页状态污染后续普通播放队列。
  2679. this.findPagedLocalQueuePageIndex = 0;
  2680. this.findPagedLocalQueuePageSize = DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE;
  2681. this.findPagedLocalQueueTotalCount = 0;
  2682. this.findPagedLocalQueueHasMore = false;
  2683. this.findPagedLocalQueueSortType = 4;
  2684. this.isLoadingFindPagedLocalQueue = false;
  2685. }
  2686. private applyFindPagedLocalQueueState(meta?: FindPlaylistMeta, totalCount?: number): void {
  2687. // 播放器只持有当前页数据,但总数、页码和排序要单独记住,后面才能继续按页补队列。
  2688. this.findPagedLocalQueuePageIndex = meta?.pageIndex ?? 0;
  2689. this.findPagedLocalQueuePageSize = meta?.pageSize && meta.pageSize > 0
  2690. ? Math.max(1, Math.floor(meta.pageSize))
  2691. : DEFAULT_LOCAL_RANDOM_QUEUE_PAGE_SIZE;
  2692. this.findPagedLocalQueueSortType = meta?.sortType !== undefined ? meta.sortType : 4;
  2693. const actualTotalCount = meta?.totalCount && meta.totalCount > 0
  2694. ? meta.totalCount
  2695. : (totalCount ?? 0);
  2696. this.findPagedLocalQueueTotalCount = actualTotalCount;
  2697. this.findPagedLocalQueueHasMore =
  2698. (this.findPagedLocalQueuePageIndex + 1) * this.findPagedLocalQueuePageSize < actualTotalCount;
  2699. if (actualTotalCount > 0) {
  2700. this.totalCount = actualTotalCount;
  2701. }
  2702. }
  2703. private isFindPagedLocalQueueActive(): boolean {
  2704. return this.playQueueScope === 'find_paged_local';
  2705. }
  2706. private shouldHydrateFullMediaPlayListOnOpen(): boolean {
  2707. // 特殊分页队列禁止打开播放列表时自动补全全量歌曲,否则会回到 3000+ 首卡顿问题。
  2708. return !!this.currentSong &&
  2709. this.currentSong.type === CommonConstants.TYPE_LOCAL &&
  2710. !this.isFindPagedLocalQueueActive();
  2711. }
  2712. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2713. if (this.isHydratingPlayList) {
  2714. return;
  2715. }
  2716. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2717. return;
  2718. }
  2719. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2720. return;
  2721. }
  2722. this.isHydratingPlayList = true;
  2723. try {
  2724. const fullList: VideoItem[] = [];
  2725. let pageIndex = 0;
  2726. let hasMore = true;
  2727. while (hasMore) {
  2728. const result = await this.table.queryMediaLibraryPaged({
  2729. pageIndex,
  2730. pageSize: this.pageSize,
  2731. sortType: this.sortType,
  2732. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2733. isShowFileName: this.isShowFileName
  2734. });
  2735. if (result.items.length === 0) {
  2736. break;
  2737. }
  2738. fullList.push(...result.items);
  2739. hasMore = result.hasMore;
  2740. pageIndex += 1;
  2741. if (fullList.length >= result.totalCount) {
  2742. hasMore = false;
  2743. }
  2744. }
  2745. if (fullList.length > 0) {
  2746. if(isSonList){
  2747. this.songList = fullList;
  2748. this.sonDataSource.pushArrayData(this.songList);
  2749. }else{
  2750. this.videoLocalList = fullList;
  2751. this.dataSource.pushArrayData(this.videoLocalList);
  2752. }
  2753. }
  2754. } finally {
  2755. this.isHydratingPlayList = false;
  2756. }
  2757. }
  2758. @Builder
  2759. SortMenuBuilder() {
  2760. Menu() {
  2761. MenuItem({
  2762. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2763. content: "按艺术家",
  2764. builder: this.SubSortBuilder(SortMode.ByArtist),
  2765. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2766. })
  2767. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByArtist)))
  2768. MenuItem({
  2769. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2770. content: "按专辑",
  2771. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2772. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2773. })
  2774. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByAlbum)))
  2775. MenuItem({
  2776. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2777. content: "按名称",
  2778. builder: this.SubSortBuilder(SortMode.ByName),
  2779. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2780. })
  2781. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2782. MenuItem({
  2783. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2784. content: $r('app.string.sort_by_time'),
  2785. builder: this.SubSortBuilder(SortMode.ByTime),
  2786. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2787. })
  2788. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByTime)))
  2789. MenuItem({
  2790. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2791. content: '按碟片音轨号',
  2792. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2793. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2794. })
  2795. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByDiscTrack)))
  2796. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2797. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2798. }.attributeModifier(new MenuModifier())
  2799. }
  2800. @Builder
  2801. SortMenuForArtistAblumBuilder() {
  2802. Menu() {
  2803. MenuItem({
  2804. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2805. content: "按名称",
  2806. builder: this.SubSortBuilder(SortMode.ByName),
  2807. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2808. })
  2809. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2810. MenuItem({
  2811. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2812. content: '按数量',
  2813. builder: this.SubSortBuilder(SortMode.ByCount),
  2814. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2815. })
  2816. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByCount)))
  2817. }.attributeModifier(new MenuModifier())
  2818. }
  2819. @Builder SubSortBuilder(sortType: number){
  2820. Menu(){
  2821. MenuItem({
  2822. content: "升序",
  2823. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2824. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2825. })
  2826. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType, true))
  2827. .onClick(async () => {
  2828. await this.doSortType(sortType)
  2829. })
  2830. MenuItem({
  2831. content: "降序",
  2832. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2833. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2834. })
  2835. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType + 1, false))
  2836. .onClick(async () => {
  2837. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2838. })
  2839. }
  2840. }
  2841. async doSortType(index: number): Promise<void> {
  2842. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2843. this.sortType = index;
  2844. this.saveSortTypeForCurrentMode(index);
  2845. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2846. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2847. await this.reloadCurrentDetailSongs();
  2848. } else {
  2849. // 分页模式下,排序需要重新从数据库查询
  2850. await this.resetAndLoadFirstPage();
  2851. }
  2852. }
  2853. /**
  2854. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2855. * 用于详情页切换排序方式时重新查询并排序
  2856. */
  2857. private async reloadCurrentDetailSongs(): Promise<void> {
  2858. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2859. try {
  2860. if (this.modeType === 2) {
  2861. // 艺术家详情页: 重新查询该艺术家的歌曲
  2862. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2863. if (ArrayUtil.isNotEmpty(mList)) {
  2864. // 使用带排序类型的缓存键
  2865. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2866. this.artistMap.set(cacheKey, mList);
  2867. this.totalCount = mList.length;
  2868. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2869. this.updateListData(mList, true);
  2870. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2871. }
  2872. } else if (this.modeType === 3) {
  2873. // 专辑详情页: 重新查询该专辑的歌曲
  2874. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2875. if (ArrayUtil.isNotEmpty(albumList)) {
  2876. // 使用带排序类型的缓存键
  2877. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2878. this.albumMap.set(cacheKey, albumList);
  2879. this.totalCount = albumList.length;
  2880. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2881. this.updateListData(albumList, true);
  2882. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2883. }
  2884. }
  2885. } catch (err) {
  2886. const error = err as Error;
  2887. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2888. ToastUtil.showToast('重新加载数据失败');
  2889. }
  2890. }
  2891. /**
  2892. * 根据当前模式保存排序类型到不同的存储键
  2893. * 区分列表页和详情页的排序设置
  2894. */
  2895. private saveSortTypeForCurrentMode(sortType: number): void {
  2896. let storageKey = SettingPage.SORT_TYPE;
  2897. if (this.modeType === 2) {
  2898. // 艺术家模式
  2899. if (this.isCanBack) {
  2900. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2901. } else {
  2902. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2903. }
  2904. } else if (this.modeType === 3) {
  2905. // 专辑模式
  2906. if (this.isCanBack) {
  2907. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2908. } else {
  2909. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2910. }
  2911. } else {
  2912. storageKey = SettingPage.SORT_TYPE;
  2913. }
  2914. PreferencesUtil.putSync(storageKey, sortType);
  2915. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2916. }
  2917. /**
  2918. * 根据当前模式加载排序类型
  2919. * 区分列表页和详情页的排序设置
  2920. */
  2921. private loadSortTypeForCurrentMode(): number {
  2922. let storageKey = SettingPage.SORT_TYPE;
  2923. let defaultSortType = 4;
  2924. if (this.modeType === 2) {
  2925. // 艺术家模式
  2926. if (this.isCanBack) {
  2927. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2928. defaultSortType = 4; // 详情页默认按名称升序
  2929. } else {
  2930. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2931. defaultSortType = 9; // 列表页默认按数量降序
  2932. }
  2933. } else if (this.modeType === 3) {
  2934. // 专辑模式
  2935. if (this.isCanBack) {
  2936. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2937. defaultSortType = 4; // 详情页默认按名称升序
  2938. } else {
  2939. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2940. defaultSortType = 9; // 列表页默认按数量降序
  2941. }
  2942. }
  2943. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2944. }
  2945. /**
  2946. * 检查当前sortType是否在指定排序类型的范围内
  2947. * 用于判断是否显示打勾图标
  2948. * @param baseSortType 基础排序类型(升序的值)
  2949. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2950. */
  2951. private isSortTypeInRange(baseSortType: number): boolean {
  2952. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2953. }
  2954. private getSortModeItemBackground(isSelected: boolean): ResourceColor {
  2955. if (!isSelected) {
  2956. return Color.Transparent;
  2957. }
  2958. return this.isDarkMode ? '#334967' : '#EAF2FF';
  2959. }
  2960. private getSortOrderItemBackground(isSelected: boolean, isAsc: boolean): ResourceColor {
  2961. if (!isSelected) {
  2962. return Color.Transparent;
  2963. }
  2964. if (isAsc) {
  2965. return this.isDarkMode ? '#295B8A' : '#DCEEFF';
  2966. }
  2967. return this.isDarkMode ? '#7A4D22' : '#FFE9D5';
  2968. }
  2969. showSheelDialog() {
  2970. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2971. // this.showTips()
  2972. // return
  2973. // }
  2974. this.showAddDialog()
  2975. }
  2976. showAddDialog() {
  2977. if (this.modeType === 2 || this.modeType === 3) {
  2978. return
  2979. }
  2980. DialogHelper.showActionSheetDialog({
  2981. title: "请选择添加方式(建议歌词文件一起导入)",
  2982. sheets: [
  2983. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2984. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2985. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2986. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2987. ],
  2988. maskColor: Color.Transparent,
  2989. backgroundColor: $r('app.color.bg_card'),
  2990. transition: AnimationHelper.transitionInDown(555),
  2991. onAction: (index) => {
  2992. switch (index) {
  2993. case 0:
  2994. if (this.modeType === 0) {
  2995. this.showMkDialog()
  2996. } else {
  2997. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2998. }
  2999. break;
  3000. case 1:
  3001. this.callFilePickerSelectFile()
  3002. break;
  3003. case 2:
  3004. this.showTips()
  3005. break;
  3006. case 3:
  3007. this.goSelectMusic()
  3008. break;
  3009. }
  3010. }
  3011. })
  3012. }
  3013. //拉起音频
  3014. goSelectMusic() {
  3015. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  3016. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  3017. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  3018. ) {
  3019. ToastUtil.showToast('暂时不支持该设备')
  3020. return
  3021. }
  3022. try {
  3023. let documentSelectOptions = new picker.DocumentSelectOptions();
  3024. documentSelectOptions.authMode = true
  3025. documentSelectOptions.multiAuthMode = true
  3026. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  3027. documentSelectOptions.maxSelectNumber = 20000
  3028. }
  3029. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  3030. let documentPicker = new picker.DocumentViewPicker(this.context);
  3031. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  3032. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  3033. this.saveVideoDatas(documentSelectResult)
  3034. }
  3035. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  3036. JSON.stringify(documentSelectResult));
  3037. }).catch((err: BusinessError) => {
  3038. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  3039. });
  3040. } catch (error) {
  3041. let err: BusinessError = error as BusinessError;
  3042. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  3043. }
  3044. }
  3045. async showTips() {
  3046. try {
  3047. this.getUIContext().getPromptAction().showDialog({
  3048. title: '导入指南',
  3049. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  3050. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  3051. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  3052. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  3053. buttons: [
  3054. {
  3055. text: '知道了',
  3056. color: '#000000'
  3057. },
  3058. ]
  3059. }, (err, data) => {
  3060. if (err) {
  3061. console.error('showDialog err: ' + err);
  3062. return;
  3063. }
  3064. console.info('showDialog success callback, click button: ' + data.index);
  3065. });
  3066. } catch (error) {
  3067. let message = (error as BusinessError).message;
  3068. let code = (error as BusinessError).code;
  3069. console.error(`showDialog args error code is ${code}, message is ${message}`);
  3070. };
  3071. }
  3072. showMkDialog() {
  3073. DialogHelper.showTextInputDialog({
  3074. title: '新建歌单',
  3075. maskColor: Color.Transparent,
  3076. text: '',
  3077. transition: AnimationHelper.transitionInDown(666),
  3078. onChange: (text) => {
  3079. console.error("onChange: " + text);
  3080. },
  3081. onAction: (action, dialogId, content) => {
  3082. // ToastUtil.showToast('content = ' +content)
  3083. if (action == DialogAction.TWO) {
  3084. const newName = content
  3085. const newPath = this.currentPath + '/' + newName
  3086. FileUtil.mkdir(newPath, true).then(() => {
  3087. this.cache.delete(this.currentPath); // 删除目标路径缓存
  3088. this.getSortedFiles(this.currentPath)
  3089. }).catch((error: BusinessError) => {
  3090. console.error(error.message);
  3091. });
  3092. }
  3093. }
  3094. })
  3095. }
  3096. @State progress: number = 0;
  3097. async saveVideoDatas(uris:string[],isOpen?:boolean){
  3098. if (ArrayUtil.isEmpty(uris)) {
  3099. return;
  3100. }
  3101. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  3102. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  3103. this.saveVideoDatasToDownLoad(uris,isOpen)
  3104. return
  3105. }
  3106. // 初始化进度条
  3107. this.progress = 0;
  3108. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  3109. progress: this.progress,
  3110. backCancel: false,
  3111. autoCancel: false,
  3112. loadColor: $r('app.color.title_bar_bg'),
  3113. fontColor: $r('app.color.title_bar_bg')
  3114. });
  3115. // 计算处理总数用于进度计算
  3116. const totalItems = uris.length;
  3117. let processedItems = 0;
  3118. for (let i = 0; i < uris.length; i++) {
  3119. let filePath = uris[i];
  3120. try {
  3121. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  3122. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  3123. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  3124. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3125. console.info('onecold saveVideoDatas filePath = ' + filePath)
  3126. if (!filePath.includes(this.rootPath)) {
  3127. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  3128. mediaItem.parentPath = this.currentPath;
  3129. }
  3130. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  3131. this.table.insert(mediaItem, (id: number) => {
  3132. // 插入完成回调
  3133. });
  3134. }
  3135. }
  3136. // 更新进度
  3137. processedItems++;
  3138. this.progress = Math.floor((processedItems / totalItems) * 100);
  3139. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  3140. } catch (error) {
  3141. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  3142. // 即使出错也更新进度
  3143. processedItems++;
  3144. this.progress = Math.floor((processedItems / totalItems) * 100);
  3145. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  3146. }
  3147. }
  3148. // 关闭进度条
  3149. DialogHelper.closeDialog(this.loadingProgressDialogId)
  3150. this.isZero = false
  3151. // 删除目标路径缓存
  3152. setTimeout(() => {
  3153. this.cache.delete(this.currentPath);
  3154. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  3155. this.setButtonStatus()
  3156. }, 500);
  3157. }
  3158. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  3159. if (ArrayUtil.isEmpty(uris)) {
  3160. return;
  3161. }
  3162. let newUris: string[] = [];
  3163. this.progress = 0
  3164. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  3165. progress: this.progress,
  3166. backCancel: false,
  3167. autoCancel: false,
  3168. loadColor: this.themeColor,
  3169. fontColor: this.themeColor
  3170. });
  3171. // 计算所有文件的总大小
  3172. let totalSize = 0;
  3173. for (let uri of uris) {
  3174. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  3175. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  3176. await fileIo.close(sourceFile.fd);
  3177. }
  3178. let totalRead = 0;
  3179. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  3180. Logger.info(TAG, 'destPath uri: ' + destPath);
  3181. for (let i = 0; i < uris.length; i++) {
  3182. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  3183. Logger.info(TAG, 'filePath uri: ' + filePath);
  3184. newUris.push(filePath);
  3185. try {
  3186. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  3187. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  3188. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  3189. const buffer = new ArrayBuffer(buffSize);
  3190. let len = await fileIo.read(sourceFile.fd, buffer);
  3191. while (len > 0) {
  3192. await fileIo.write(destFile.fd, buffer.slice(0, len));
  3193. totalRead += len;
  3194. // 计算总进度
  3195. this.progress = Math.floor((totalRead / totalSize) * 100);
  3196. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  3197. len = await fileIo.read(sourceFile.fd, buffer);
  3198. }
  3199. await fileIo.close(sourceFile.fd);
  3200. await fileIo.close(destFile.fd);
  3201. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  3202. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  3203. let mediaItem: VideoItem =
  3204. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3205. this.table.insert(mediaItem, (id: number) => {
  3206. // 删除目标路径缓存
  3207. this.cache.delete(this.currentPath);
  3208. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  3209. });
  3210. }
  3211. }
  3212. } catch (error) {
  3213. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  3214. }
  3215. }
  3216. DialogHelper.closeDialog(this.loadingProgressDialogId);
  3217. this.isZero = false
  3218. Logger.info(TAG, 'scan select video result:' + newUris)
  3219. }
  3220. //拉起音频
  3221. // goSelectMusic(){
  3222. //
  3223. // try {
  3224. // let audioSelectOptions = new picker.AudioSelectOptions();
  3225. // let audioPicker = new picker.AudioViewPicker(this.context);
  3226. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  3227. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  3228. // this.saveVideoDatas(audioSelectResult)
  3229. // }
  3230. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  3231. // }).catch((err: BusinessError) => {
  3232. //
  3233. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  3234. // });
  3235. // } catch (error) {
  3236. // let err: BusinessError = error as BusinessError;
  3237. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  3238. // }
  3239. //
  3240. //
  3241. //
  3242. // }
  3243. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  3244. if (!item) {
  3245. return undefined;
  3246. }
  3247. try {
  3248. let selectUris: Array<string> = [];
  3249. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  3250. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  3251. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  3252. photoSelectOptions.maxSelectNumber = 1;
  3253. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  3254. selectUris = photoSelectResult.photoUris;
  3255. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  3256. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  3257. console.info('file fd: ' + file.fd);
  3258. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  3259. let imagePath = this.context.filesDir + FileUtil.separator + name
  3260. imagePath = fileUri.getUriFromPath(imagePath)
  3261. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  3262. fileIo.copyFileSync(file.fd, file2.fd)
  3263. fileIo.closeSync(file);
  3264. fileIo.closeSync(file2);
  3265. if (item.filePath == this.currentSong?.filePath) {
  3266. this.cover = imagePath
  3267. if (this.currentSong) {
  3268. this.currentSong.isCustomCover = 1;
  3269. }
  3270. }
  3271. if (item) {
  3272. item.pixelMapPath = imagePath
  3273. item.isCustomCover = 1;
  3274. }
  3275. if (isRemoteCloudType(item.type)) {
  3276. return FileUtil.getFilePath(imagePath);
  3277. }
  3278. this.table.updateCustomCoverPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  3279. if (success) {
  3280. this.doUpdateData()
  3281. console.log("onecold 更新音乐封面成功,数据库已同步");
  3282. } else {
  3283. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  3284. }
  3285. });
  3286. LogUtil.debug("onecold this.cover =" + this.cover)
  3287. return FileUtil.getFilePath(imagePath); // Return the image path here
  3288. } catch (err) {
  3289. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  3290. return undefined;
  3291. }
  3292. }
  3293. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  3294. try {
  3295. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  3296. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  3297. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  3298. photoSelectOptions.maxSelectNumber = 1;
  3299. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  3300. const selectUris = photoSelectResult.photoUris;
  3301. if (!selectUris || selectUris.length === 0) {
  3302. return undefined;
  3303. }
  3304. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  3305. if (!FileUtil.accessSync(coverDir)) {
  3306. FileUtil.mkdirSync(coverDir);
  3307. }
  3308. const sourceUri = selectUris[0];
  3309. const sourceName = FileUtil.getFileName(sourceUri) || '';
  3310. let suffix = '.jpg';
  3311. const dotIndex = sourceName.lastIndexOf('.');
  3312. if (dotIndex >= 0) {
  3313. suffix = sourceName.substring(dotIndex);
  3314. }
  3315. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  3316. const targetPath = coverDir + FileUtil.separator + targetName;
  3317. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  3318. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  3319. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  3320. fileIo.closeSync(sourceFile.fd);
  3321. fileIo.closeSync(targetFile.fd);
  3322. return fileUri.getUriFromPath(targetPath);
  3323. } catch (error) {
  3324. const err = error as BusinessError;
  3325. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  3326. return undefined;
  3327. }
  3328. }
  3329. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  3330. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  3331. ToastUtil.showToast('当前歌曲无效');
  3332. return;
  3333. }
  3334. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  3335. if (StrUtil.isEmpty(sandboxCoverUri)) {
  3336. return;
  3337. }
  3338. const coverUri = sandboxCoverUri as string;
  3339. this.loadingDialogId = DialogHelper.showLoadingDialog();
  3340. try {
  3341. if (isRemoteCloudType(this.currentSong.type)) {
  3342. this.cover = coverUri;
  3343. this.currentSong.pixelMapPath = coverUri;
  3344. this.currentSong.isCustomCover = 1;
  3345. this.syncRemoteManagerSong(this.currentSong);
  3346. await this.persistRemoteMetadataToDb(this.currentSong);
  3347. this.emitRemoteMetadataUpdated(this.currentSong);
  3348. this.currentSong = cloneVideoItem(this.currentSong);
  3349. AppStorage.setOrCreate('currentSong', this.currentSong);
  3350. ToastUtil.showToast('更换封面成功');
  3351. return;
  3352. }
  3353. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  3354. ToastUtil.showToast('当前歌曲类型暂不支持更换封面');
  3355. return;
  3356. }
  3357. const task = new taskpool.Task(
  3358. replaceLocalMusicCoverTask,
  3359. this.context,
  3360. this.currentSong.filePath,
  3361. FileUtil.getFilePath(coverUri)
  3362. );
  3363. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  3364. if (!result) {
  3365. ToastUtil.showToast('更换封面失败');
  3366. return;
  3367. }
  3368. this.cover = coverUri;
  3369. this.currentSong.pixelMapPath = coverUri;
  3370. this.currentSong.isCustomCover = 1;
  3371. await this.doUpateEditedFields(this.currentSong);
  3372. ToastUtil.showToast('更换封面成功');
  3373. } catch (error) {
  3374. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  3375. ToastUtil.showToast('更换封面失败');
  3376. } finally {
  3377. DialogHelper.closeDialog(this.loadingDialogId);
  3378. }
  3379. }
  3380. // 拉起picker选择文件管理器
  3381. async callFilePickerSelectFile(): Promise<void> {
  3382. try {
  3383. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  3384. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  3385. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  3386. } else {
  3387. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  3388. }
  3389. let documentPicker = new picker.DocumentViewPicker();
  3390. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  3391. Logger.info(TAG,
  3392. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  3393. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  3394. this.saveVideoDatas(DocumentSelectResult)
  3395. }
  3396. }).catch((err: BusinessError) => {
  3397. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  3398. });
  3399. } catch (err) {
  3400. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  3401. }
  3402. }
  3403. //重命名的对话框
  3404. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  3405. if(!item.filePath.includes(this.packName)){
  3406. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  3407. return
  3408. }
  3409. DialogHelper.showTextInputDialog({
  3410. title: '重命名',
  3411. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : (item.fileName || item.name),
  3412. maskColor: Color.Transparent,
  3413. backgroundColor: Color.Grey,
  3414. transition: AnimationHelper.transitionInDown(666),
  3415. onChange: (text) => {
  3416. console.error("onChange: " + text);
  3417. },
  3418. onAction: (action, dialogId, content) => {
  3419. // ToastUtil.showToast('content = ' +content)
  3420. if (action == DialogAction.TWO) {
  3421. const newName = content
  3422. const newPath = this.currentPath + '/' + newName
  3423. console.log("onecold item = " + item.type);
  3424. this.doReName(index, newName, filePath, newPath, item)
  3425. }
  3426. }
  3427. })
  3428. }
  3429. //剪切 移动到另个文件夹的对话框
  3430. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3431. Logger.info('onecold showCutDialog')
  3432. let mList: Array<string> = []
  3433. let rPath = this.rootPath
  3434. if (isCurrent) {
  3435. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3436. rPath = this.currentPath
  3437. } else {
  3438. mList = Utility.getNameList(this.dirList);
  3439. rPath = this.rootPath
  3440. }
  3441. let dataBean = new BubbleBean()
  3442. dataBean.data = mList
  3443. dataBean.color = this.themeColor
  3444. dataBean.onItemClick = (i) => {
  3445. const targetName = item.fileName || item.name
  3446. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3447. Logger.info('newPath = ' + newPath)
  3448. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3449. ToastUtil.showToast('移动成功')
  3450. this.table.deleteData(item, () => {
  3451. });
  3452. if (!Utility.isIsoByExtension(newPath)) {
  3453. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3454. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3455. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3456. this.table.insert(newItem, (id: number) => {
  3457. //加入数据库
  3458. });
  3459. }
  3460. }
  3461. this.cache.delete(this.currentPath); // 删除原路径缓存
  3462. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3463. this.getSortedFiles(this.currentPath, true)
  3464. }).catch((error: BusinessError) => {
  3465. console.error(error.message);
  3466. });
  3467. XPopup.dismissTop()
  3468. }
  3469. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3470. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3471. popupPosition = PopupPosition.TOP
  3472. }
  3473. if (index <= 3) {
  3474. popupPosition = PopupPosition.BOTTOM
  3475. }
  3476. let pup: XPopup
  3477. if (this.isDarkMode) {
  3478. pup = XPopup.Builder()
  3479. .setPopupPosition(popupPosition)
  3480. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  3481. .setBackgroundColor(Color.Black)
  3482. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3483. .show()
  3484. } else {
  3485. pup = XPopup.Builder()
  3486. .setPopupPosition(popupPosition)
  3487. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  3488. .setBackgroundColor(Color.White)
  3489. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3490. .show()
  3491. }
  3492. }
  3493. //复制 到另个文件夹的对话框
  3494. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3495. Logger.info('onecoldv showCopyDialog')
  3496. let mList: Array<string> = []
  3497. let rPath = this.rootPath
  3498. if (isCurrent) {
  3499. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3500. rPath = this.currentPath
  3501. } else {
  3502. mList = Utility.getNameList(this.dirList);
  3503. rPath = this.rootPath
  3504. }
  3505. let dataBean = new BubbleBean()
  3506. dataBean.data = mList
  3507. dataBean.isCopy = true
  3508. dataBean.color = this.themeColor
  3509. dataBean.onItemClick = (i) => {
  3510. const targetName = item.fileName || item.name
  3511. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3512. Logger.info('newPath = ' + newPath)
  3513. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3514. ToastUtil.showToast('复制成功')
  3515. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3516. this.getSortedFiles(this.currentPath)
  3517. if (!Utility.isIsoByExtension(newPath)) {
  3518. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3519. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3520. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3521. this.table.insert(newItem, (id: number) => {
  3522. //加入数据库
  3523. });
  3524. }
  3525. }
  3526. }).catch((error: BusinessError) => {
  3527. console.error(error.message);
  3528. });
  3529. XPopup.dismissTop()
  3530. }
  3531. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3532. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3533. popupPosition = PopupPosition.TOP
  3534. }
  3535. if (index <= 3) {
  3536. popupPosition = PopupPosition.BOTTOM
  3537. }
  3538. let pup: XPopup
  3539. if (this.isDarkMode) {
  3540. pup = XPopup.Builder()
  3541. .setPopupPosition(popupPosition)
  3542. .atView(id)
  3543. .setMaxHeight('60%')
  3544. .setBackgroundColor(Color.Black)
  3545. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3546. .show();
  3547. } else {
  3548. pup = XPopup.Builder()
  3549. .setPopupPosition(popupPosition)
  3550. .atView(id)
  3551. .setMaxHeight('60%')
  3552. .setBackgroundColor(Color.White)
  3553. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3554. .show();
  3555. }
  3556. }
  3557. //重命名索引index的视频
  3558. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3559. FileUtil.rename(oldPath, newPath).then(async () => {
  3560. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3561. let refreshedItem: VideoItem = info
  3562. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3563. //如果是文件夹先删除源数据,再添加新数据
  3564. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3565. if (success) {
  3566. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3567. } else {
  3568. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3569. }
  3570. });
  3571. this.scanDirectory(newPath)
  3572. refreshedItem = new VideoItem(newName, newName, newPath, CommonConstants.TYPE_IS_DIR, 0, '')
  3573. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3574. if (Utility.isIsoByExtension(oldPath) || Utility.isIsoByExtension(newPath)) {
  3575. refreshedItem = this.buildLocalIsoItem(newPath, newName)
  3576. } else {
  3577. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3578. if (success) {
  3579. console.log(" onecold 重命名成功,数据库已同步");
  3580. } else {
  3581. console.error(" onecold 重命名数据库失败原因: " + error);
  3582. }
  3583. });
  3584. refreshedItem =
  3585. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3586. }
  3587. } else {
  3588. return
  3589. }
  3590. this.videoLocalList[index] = refreshedItem;
  3591. }
  3592. this.cache.delete(this.currentPath)
  3593. this.cache.delete(oldPath)
  3594. this.cache.delete(newPath)
  3595. this.getSortedFiles(this.currentPath, true)
  3596. }).catch((error: BusinessError) => {
  3597. console.error(error.message);
  3598. });
  3599. }
  3600. build() {
  3601. Stack() {
  3602. this.ContentBuild()
  3603. Stack() {
  3604. Column()
  3605. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3606. height: '95%',
  3607. dragBar: true,
  3608. showClose: true,
  3609. blurStyle: BlurStyle.Thin,
  3610. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3611. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3612. title: {
  3613. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3614. + `(${this.getPlayListDisplayCount()}首)`
  3615. }
  3616. })
  3617. }
  3618. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3619. modalTransition: ModalTransition.DEFAULT,
  3620. onWillDisappear: () => {
  3621. this.setShowPlayFalse()
  3622. },
  3623. })
  3624. }
  3625. .alignContent(Alignment.Bottom)
  3626. .width('100%')
  3627. .height('100%')
  3628. }
  3629. @Builder
  3630. ContentBuild() {
  3631. Scroll() {
  3632. Column() {
  3633. Stack() {
  3634. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3635. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3636. controller: this.xcomponentController })
  3637. .onLoad(async (event?: object) => {
  3638. })
  3639. .focusable(true)
  3640. .height(0)
  3641. .focusOnTouch(true)
  3642. .defaultFocus(true) // 自动获取键盘焦点
  3643. .onKeyEvent((event?: KeyEvent) => {
  3644. console.info('onecold点击 onKeyEvent')
  3645. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3646. if (!event || event.type !== KeyType.Down) {
  3647. return;
  3648. }
  3649. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3650. //空格键 Space key controls pause/play
  3651. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3652. this.playbackController.playOrPause()
  3653. }
  3654. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3655. void this.playbackController.playPrevious()
  3656. }
  3657. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3658. void this.playbackController.playNext()
  3659. }
  3660. // Right-click to fast forward
  3661. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3662. this.fastForward()
  3663. }
  3664. // Left-click to rewind
  3665. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3666. this.backForward()
  3667. }
  3668. })
  3669. Column() {
  3670. XComponent({
  3671. id: 'xcomponentId',
  3672. type: 'surface',
  3673. libraryname: 'ijkplayer_napi',
  3674. controller: this.xcomponentController
  3675. })
  3676. .onLoad((event?: object) => {
  3677. if (!!event) {
  3678. this.initDelayPlay(event);
  3679. }
  3680. })
  3681. .onDestroy(() => {
  3682. })
  3683. .width('100%')// .width(this.videoWidth)
  3684. .aspectRatio(this.videoAspectRatio)
  3685. }
  3686. .aspectRatio(this.videoAspectRatio)
  3687. .justifyContent(FlexAlign.Center)
  3688. .backgroundColor(Color.Transparent)
  3689. .visibility(Visibility.Hidden)
  3690. .height(CommonConstants.FULL_PERCENT)
  3691. .width(CommonConstants.FULL_PERCENT)
  3692. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3693. height:this.isLandscape?'80%': '43%',
  3694. dragBar: true,
  3695. showClose: true,
  3696. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3697. blurStyle:BlurStyle.Thin,
  3698. backgroundColor:Color.Transparent,
  3699. title: { title: 'AB循环' }
  3700. })
  3701. Stack() {
  3702. Column() {
  3703. if(this.twoFingerType==4){
  3704. this.getWaterView()
  3705. }else{
  3706. if(this.isGridMusic){
  3707. this.getGridView()
  3708. }else {
  3709. this.getListView()
  3710. }
  3711. }
  3712. if (this.modeType ==0||this.modeType==4) {
  3713. Column() {
  3714. emptyView(this.themeColor)
  3715. }
  3716. .padding({ right:6 })
  3717. .onClick(()=>{
  3718. this.asyncCurrentPathOnlyFile()
  3719. })
  3720. .alignItems(HorizontalAlign.Center)
  3721. .position({ top: 200 })
  3722. .justifyContent(FlexAlign.Center)
  3723. .opacity(this.isZero ? 1 : 0)
  3724. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3725. ? Visibility.Visible : Visibility.None)
  3726. .animation({
  3727. duration: 500,
  3728. curve: Curve.Friction // 可选动画曲线
  3729. })
  3730. .width('100%')
  3731. }
  3732. }
  3733. .layoutWeight(1)
  3734. .height('100%')
  3735. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3736. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3737. .onDrop((event?: DragEvent) => {
  3738. try {
  3739. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3740. if (dragData !== undefined) {
  3741. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3742. if (records.length > 0) {
  3743. for (let i = 0; i < records.length; i++) {
  3744. let types = records[i].getTypes();
  3745. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3746. const fileUriUds =
  3747. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3748. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3749. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3750. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3751. this.targetFile = fileUriUds.oriUri;
  3752. this.saveVideoDatas([this.targetFile])
  3753. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3754. }
  3755. }
  3756. }
  3757. } else {
  3758. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3759. }
  3760. } else {
  3761. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3762. }
  3763. } catch (error) {
  3764. const err = error as BusinessError;
  3765. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3766. }
  3767. })
  3768. // 右侧居中的字母表索引
  3769. this.indexBuilder()
  3770. this.topTitleBar()
  3771. }
  3772. .alignContent(Alignment.Top)
  3773. .layoutWeight(1)
  3774. .height('100%')
  3775. Row() {
  3776. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3777. .width(45)
  3778. .height(45)
  3779. .fontSize(10)
  3780. .margin({ top: 10, bottom: 10, right: 6 })
  3781. .backgroundColor(this.themeColor)
  3782. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3783. .onClick(() => {
  3784. if (this.isAllSelected) {
  3785. // 全不选
  3786. this.selectedFiles = [];
  3787. } else {
  3788. // 全选
  3789. this.selectedFiles = [...this.getCurFileList()];
  3790. }
  3791. this.syncLocalSelectionState();
  3792. })
  3793. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3794. .width(72)
  3795. .height(45)
  3796. .fontSize(10)
  3797. .margin({ top: 10, bottom: 10, right: 6 })
  3798. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3799. .backgroundColor(this.themeColor)
  3800. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3801. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3802. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3803. })
  3804. .onClick(() => {
  3805. if (this.hasSelectedDirectories()) {
  3806. ToastUtil.showToast('文件夹不支持批量内嵌标签')
  3807. return
  3808. }
  3809. this.isOneKeyTags = !this.isOneKeyTags
  3810. })
  3811. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3812. .width(45)
  3813. .height(45)
  3814. .fontSize(10)
  3815. .margin({ top: 10, bottom: 10, right: 6 })
  3816. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3817. .backgroundColor(this.themeColor)
  3818. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3819. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3820. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3821. })
  3822. .onClick(() => {
  3823. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3824. if (this.hasSelectedDirectories()) {
  3825. ToastUtil.showToast('文件夹不支持合并')
  3826. return
  3827. }
  3828. if(ArrayUtil.isNotEmpty(selectedMediaFiles)&&Utility.isMerge(selectedMediaFiles,this.packName)){
  3829. this.isMergeAudio = !this.isMergeAudio
  3830. }else{
  3831. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3832. }
  3833. })
  3834. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3835. .width(45)
  3836. .height(45)
  3837. .fontSize(10)
  3838. .margin({ top: 10, bottom: 10, right: 6 })
  3839. .backgroundColor(this.themeColor)
  3840. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3841. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3842. .onClick(async () => {
  3843. this.longItemFilePath = ''
  3844. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3845. if (ArrayUtil.isEmpty(selectedMediaFiles)) {
  3846. ToastUtil.showToast('请先选择音频文件')
  3847. return
  3848. }
  3849. await this.openAddToPlaylistDialog(selectedMediaFiles)
  3850. })
  3851. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3852. // .width(45)
  3853. // .height(45)
  3854. // .fontSize(10)
  3855. // .margin({ top: 10, bottom: 10, right: 6 })
  3856. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3857. // .backgroundColor(this.themeColor)
  3858. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3859. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3860. // })
  3861. // .onClick(() => {
  3862. // this.isFixMessy = !this.isFixMessy
  3863. // })
  3864. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3865. // .width('35%')
  3866. // .height(60)
  3867. // .id('music_cut')
  3868. // .margin({ top: 10, bottom: 10, right: 6 })
  3869. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3870. // .backgroundColor(this.themeColor)
  3871. // .onClick(() => {
  3872. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3873. // })
  3874. //
  3875. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3876. // .width('35%')
  3877. // .height(60)
  3878. // .id('music_cut_current')
  3879. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3880. // .margin({ top: 10, bottom: 10, right: 6 })
  3881. // .backgroundColor(this.themeColor)
  3882. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3883. // .onClick(() => {
  3884. //
  3885. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3886. // })
  3887. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3888. // .width('35%')
  3889. // .height(60)
  3890. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3891. // .margin({ top: 10, bottom: 10, right: 6 })
  3892. // .backgroundColor(this.themeColor)
  3893. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3894. // .onClick(() => {
  3895. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3896. // })
  3897. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3898. .width(45)
  3899. .height(45)
  3900. .fontSize(10)
  3901. .margin({ top: 10, bottom: 10, right: 6 })
  3902. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3903. .backgroundColor(this.themeColor)
  3904. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3905. .onClick(() => {
  3906. this.showWarnIsDelete()
  3907. })
  3908. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3909. .width(45)
  3910. .height(45)
  3911. .fontSize(10)
  3912. .margin({ top: 10, bottom: 10, right: 6 })
  3913. .backgroundColor(this.themeColor)
  3914. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3915. .onClick(() => {
  3916. this.selectedFiles = [];
  3917. this.isAllSelected = false
  3918. this.isMultiSelect = false
  3919. })
  3920. }
  3921. .width('100%')
  3922. .justifyContent(FlexAlign.Center)
  3923. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3924. .opacity(this.isMultiSelect ? 1 : 0)
  3925. .animation({
  3926. duration: 666,
  3927. curve: 'ease-in-out' // 可选动画曲线
  3928. })
  3929. .position({ bottom: 20 }) // 将 Row 固定在底部
  3930. }
  3931. .width('100%')
  3932. .height('100%')
  3933. .alignContent(Alignment.Top)
  3934. }
  3935. .width('100%')
  3936. .height('100%')
  3937. .backgroundImage(this.isMusicCoverHomeBackgroundActive()
  3938. ? this.customizeMusicBgPath
  3939. : (this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background')))
  3940. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3941. .backgroundImagePosition(Alignment.Center)
  3942. .backdropBlur(this.blurValue)
  3943. .backgroundBrightness({ rate: this.isMusicCoverHomeBackgroundActive() || this.isCustomizeBg ? 0.1 : 0,
  3944. lightUpDegree: this.bgBrightness })
  3945. .backgroundBlurStyle(this.isMusicCoverHomeBackgroundActive()
  3946. ? BlurStyle.BACKGROUND_ULTRA_THICK :
  3947. BlurStyle.NONE)
  3948. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3949. }
  3950. }
  3951. //字母表索引
  3952. @Builder
  3953. indexBuilder(){
  3954. Column({space: 5}){
  3955. if(this.showZMIndex&&this.enableShowAlphabet){
  3956. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3957. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3958. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3959. .attributeModifier(this.alphaBetStyle)
  3960. .usingPopup(this.isTouchingAlphaBet)
  3961. .onAreaChange((old_value,new_value)=>{
  3962. this.alphabetHeight = new_value.height as number
  3963. })
  3964. .popupPosition({
  3965. x: 40,
  3966. y: this.alphabetHeight / 2
  3967. })
  3968. .onSelect((index: number) => {
  3969. void this.onSelectIndexItem(this.alphaBet[index])
  3970. })
  3971. .onTouch((event: TouchEvent) =>{
  3972. this.showAlphabetIndex()
  3973. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3974. this.isTouchingAlphaBet = false
  3975. this.hideAlphabetIndexAfterDelay(1500)
  3976. }else{
  3977. this.isTouchingAlphaBet = true
  3978. }
  3979. })
  3980. .transition(
  3981. TransitionEffect.translate({x: 10})
  3982. .combine(TransitionEffect.opacity(0.1))
  3983. .animation({
  3984. duration: 150,
  3985. curve: Curve.EaseInOut,
  3986. })
  3987. )
  3988. }
  3989. }
  3990. if(this.showFindLocation){
  3991. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3992. Blank()
  3993. .layoutWeight(1)
  3994. }
  3995. PointLightDefaultButton({
  3996. isSysBol:true,
  3997. pointColor:Color.Gray,
  3998. imageResource:$r('sys.symbol.local_fill'),
  3999. isPx: false,
  4000. builderHeight: 30,
  4001. builderWidth: 30,
  4002. })
  4003. .onClick(() =>{
  4004. void this.locateCurrentSong();
  4005. })
  4006. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  4007. .margin({
  4008. bottom: this.bottomSafeHeight+100,right:10
  4009. })
  4010. }
  4011. }
  4012. .padding({
  4013. bottom: 0
  4014. })
  4015. .margin({right:5})
  4016. .position({x:'92%'})
  4017. .height('100%')
  4018. .justifyContent(FlexAlign.Center)
  4019. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  4020. height: '100%',
  4021. dragBar: true,
  4022. showClose: true,
  4023. preferType: SheetType.CENTER ,
  4024. blurStyle: BlurStyle.Thin,
  4025. title: { title: '均衡器' },
  4026. onDisappear: () => {
  4027. this.isEqualizerSheet = false
  4028. }
  4029. })
  4030. }
  4031. async onSelectIndexItem(letter: string) {
  4032. await this.ensureFullListForAlphabetIndex();
  4033. const findTargetIndex = (): number => {
  4034. const songs = this.videoLocalList;
  4035. for (let i = 0; i < songs.length; i++) {
  4036. const song = songs[i];
  4037. let text = this.isShowFileName ? song.fileName :
  4038. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  4039. if (this.sortType === 0 || this.sortType == 1) {
  4040. text = song.artist;
  4041. } else if (this.sortType === 2 || this.sortType == 3) {
  4042. text = song.album;
  4043. }
  4044. if (text) {
  4045. const firstPinyin = getFirstLetter(text);
  4046. if (firstPinyin && firstPinyin === letter) {
  4047. return i;
  4048. }
  4049. }
  4050. }
  4051. return -1;
  4052. };
  4053. const targetIndex = findTargetIndex();
  4054. if (targetIndex !== -1) {
  4055. if (this.isGridMusic || this.twoFingerType == 4) {
  4056. this.scroller.scrollToIndex(targetIndex, false);
  4057. } else {
  4058. this.listScroller.scrollToIndex(targetIndex);
  4059. }
  4060. }
  4061. }
  4062. private showAlphabetIndex(): void {
  4063. this.isShowAlphaBet = true;
  4064. if (this.alphaBetHideTimer) {
  4065. clearTimeout(this.alphaBetHideTimer);
  4066. this.alphaBetHideTimer = 0;
  4067. }
  4068. }
  4069. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  4070. if (this.alphaBetHideTimer) {
  4071. clearTimeout(this.alphaBetHideTimer);
  4072. }
  4073. this.alphaBetHideTimer = setTimeout(() => {
  4074. if (!this.isTouchingAlphaBet) {
  4075. this.isShowAlphaBet = false;
  4076. }
  4077. this.alphaBetHideTimer = 0;
  4078. }, delayMs) as number;
  4079. }
  4080. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  4081. if (!this.showZMIndex) {
  4082. return;
  4083. }
  4084. if (this.alphaBetRebuildTimer) {
  4085. clearTimeout(this.alphaBetRebuildTimer);
  4086. }
  4087. this.alphaBetRebuildTimer = setTimeout(() => {
  4088. this.alphaBetRebuildTimer = 0;
  4089. if (this.isScrolling) {
  4090. this.alphaBetDirty = true;
  4091. return;
  4092. }
  4093. this.alphaBetDirty = false;
  4094. void this.setAlphaBet();
  4095. }, delayMs) as number;
  4096. }
  4097. private markAlphaBetDirty(): void {
  4098. if (!this.showZMIndex) {
  4099. return;
  4100. }
  4101. if (this.isMediaLibraryWarmupWindow()) {
  4102. this.alphaBetDirty = true;
  4103. this.scheduleAlphaBetRebuild(900);
  4104. return;
  4105. }
  4106. this.alphaBetDirty = true;
  4107. if (!this.isScrolling) {
  4108. this.scheduleAlphaBetRebuild(80);
  4109. }
  4110. }
  4111. private async ensureFullListForAlphabetIndex(): Promise<void> {
  4112. if (this.isLoadingPage) {
  4113. return;
  4114. }
  4115. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  4116. return;
  4117. }
  4118. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  4119. return;
  4120. }
  4121. if (this.modeType !== 0 && this.modeType !== 1) {
  4122. return;
  4123. }
  4124. this.isLoadingPage = true;
  4125. try {
  4126. const options: PageQueryOptions = {
  4127. pageIndex: 0,
  4128. pageSize: this.totalCount,
  4129. sortType: this.sortType,
  4130. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  4131. isShowFileName: this.isShowFileName
  4132. };
  4133. if (this.modeType === 0) {
  4134. options.parentPath = this.currentPath;
  4135. }
  4136. let result: PageQueryResult;
  4137. if (this.modeType === 0) {
  4138. result = await this.table.queryByParentPathPaged(options);
  4139. const dbItems = this.filterOutLocalIsoItems(result.items);
  4140. if (!this.isSearchMode) {
  4141. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  4142. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  4143. result.items = [...directories, ...isoItems, ...dbItems];
  4144. } else {
  4145. result.items = dbItems;
  4146. }
  4147. } else {
  4148. result = await this.table.queryMediaLibraryPaged(options);
  4149. }
  4150. this.videoLocalList = result.items;
  4151. this.dataSource.pushArrayData(this.videoLocalList);
  4152. this.pageCache.clear();
  4153. this.pageHasMoreCache.clear();
  4154. this.pageTotalCountCache.clear();
  4155. this.prefetchingPages.clear();
  4156. this.currentPage = 0;
  4157. this.totalCount = this.modeType === 0 ? result.items.length : result.totalCount;
  4158. this.hasMoreData = false;
  4159. this.lastScrollTriggerPage = -1;
  4160. this.lastVisibleEndIndex = -1;
  4161. this.isPagingTransition = false;
  4162. if (this.pagingScheduleTimer) {
  4163. clearTimeout(this.pagingScheduleTimer);
  4164. this.pagingScheduleTimer = 0;
  4165. }
  4166. if (this.modeType === 1) {
  4167. this.mediaKuCount = result.totalCount;
  4168. }
  4169. this.setButtonStatus();
  4170. this.markAlphaBetDirty();
  4171. } catch (err) {
  4172. const error = err as Error;
  4173. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  4174. } finally {
  4175. this.isLoadingPage = false;
  4176. }
  4177. }
  4178. // 找到对应字母表的索引
  4179. findAlphaBetIndex(song: VideoItem):number{
  4180. let text = this.isShowFileName?song.fileName:
  4181. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  4182. if(this.sortType === 0||this.sortType==1){
  4183. text = song.artist
  4184. }else if(this.sortType === 2||this.sortType==3){
  4185. text = song.album
  4186. }
  4187. if(text){
  4188. let firstLetter = getFirstLetter(text)
  4189. for(let i=0;i<this.alphaBet.length;i++){
  4190. if(this.alphaBet[i] === firstLetter){
  4191. return i
  4192. }
  4193. }
  4194. }
  4195. return 0
  4196. }
  4197. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  4198. const items: Array<AlphaTaskItem> = []
  4199. for (const song of songs) {
  4200. items.push({
  4201. type: song.type,
  4202. name: song.name,
  4203. pyStr: song.pyStr,
  4204. fileName: song.fileName,
  4205. artist: song.artist,
  4206. album: song.album
  4207. })
  4208. }
  4209. return items
  4210. }
  4211. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  4212. const taskItems = this.buildAlphaTaskItems(songs)
  4213. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  4214. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  4215. if (version !== this.alphaBetBuildVersion) {
  4216. return
  4217. }
  4218. this.alphaBet = result
  4219. if (this.videoLocalList.length > 0) {
  4220. this.selectAlphaBetIndex = 0
  4221. }
  4222. }
  4223. async setAlphaBet(){
  4224. if(!this.showZMIndex){
  4225. return
  4226. }
  4227. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  4228. await this.refreshAlphaBetFromMediaLibrary()
  4229. return
  4230. }
  4231. try {
  4232. const songs = this.videoLocalList
  4233. if (songs.length > 40000) {
  4234. this.alphaBet = []
  4235. return
  4236. }
  4237. const version = ++this.alphaBetBuildVersion
  4238. await this.buildAlphaBetByTask(songs, version)
  4239. } catch (e) {
  4240. console.error('testTag','排序字母表出错',JSON.stringify(e))
  4241. }
  4242. }
  4243. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  4244. if (this.totalCount <= 0) {
  4245. return
  4246. }
  4247. if (this.totalCount > 40000) {
  4248. this.alphaBet = []
  4249. return
  4250. }
  4251. const keyword = this.isSearchMode ? this.searchText : ''
  4252. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  4253. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  4254. return
  4255. }
  4256. const result = await this.table.queryMediaLibraryPaged({
  4257. pageIndex: 0,
  4258. pageSize: this.totalCount,
  4259. sortType: this.sortType,
  4260. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  4261. isShowFileName: this.isShowFileName
  4262. })
  4263. const version = ++this.alphaBetBuildVersion
  4264. await this.buildAlphaBetByTask(result.items, version)
  4265. this.alphaBetCacheKey = cacheKey
  4266. }
  4267. @Builder
  4268. topTitleBar(){
  4269. Column() {
  4270. Row({ space: 15 }) {
  4271. if (!this.isSearchMode ) {
  4272. //左侧滑动按钮
  4273. TitleBarPointLightButton({
  4274. iconResource: this.rightTopImage,
  4275. iconSize: 25,
  4276. pointColor: this.themeColor,
  4277. clickScale: 0.6,
  4278. clickHandler: () => {
  4279. this.triggerSwipeBackWithAnimation()
  4280. }
  4281. })
  4282. }else{
  4283. //左侧搜索返回按钮
  4284. TitleBarPointLightButton({
  4285. iconResource: $r('sys.symbol.chevron_left'),
  4286. iconSize: 25,
  4287. pointColor: this.themeColor,
  4288. clickScale: 0.6,
  4289. clickHandler: () => {
  4290. this.isSearchMode = false
  4291. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  4292. this.searchText = ''
  4293. this.getSortedFiles(this.currentPath)
  4294. return
  4295. }
  4296. this.onSearchInput('')
  4297. }
  4298. })
  4299. .margin({bottom:5})
  4300. }
  4301. if (!this.isSearchMode) {
  4302. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  4303. .margin({left:3,right:10})
  4304. .fontColor($r('app.color.text_color'))
  4305. .fontSize(this.twoFingerType==3?17:16)
  4306. .maxLines(1)
  4307. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4308. .layoutWeight(1)
  4309. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4310. }
  4311. //搜索框
  4312. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  4313. .searchButton('搜索',{fontColor:this.themeColor})
  4314. .searchIcon({
  4315. src: $r('sys.media.ohos_ic_public_search_filled')
  4316. })
  4317. .cancelButton({
  4318. style: CancelButtonStyle.CONSTANT,
  4319. icon: {
  4320. src: $r('sys.media.ohos_ic_public_cancel_filled')
  4321. }
  4322. })
  4323. .layoutWeight(1)
  4324. .height(40)
  4325. .maxLength(20)
  4326. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  4327. .placeholderColor(Color.Grey)
  4328. .placeholderFont({ size: 14, weight: 400 })
  4329. .textFont({ size: 14, weight: 400 })
  4330. .onSubmit((value: string) => {
  4331. console.log('onecold onSubmit ='+value)
  4332. this.searchController.stopEditing()
  4333. if(this.modeType==0){
  4334. this.modeType =1//如果是首页 切换到媒体库搜索
  4335. }
  4336. this.commitSearchHistory(value)
  4337. this.onSearchInput(this.searchText);
  4338. })
  4339. .onChange((value: string) => {
  4340. console.log('onecold onChange ='+value)
  4341. if(this.modeType==0){
  4342. this.modeType =1//如果是首页 切换到媒体库搜索
  4343. }
  4344. this.onSearchInput(value);
  4345. })
  4346. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  4347. .animation({ duration: 300, curve: Curve.Ease })
  4348. //搜索按钮
  4349. if (!this.isSearchMode) {
  4350. TitleBarPointLightButton({
  4351. iconResource: $r('sys.symbol.magnifyingglass'),
  4352. iconSize: 25,
  4353. pointColor: this.themeColor,
  4354. clickScale: 0.6,
  4355. clickHandler: () => {
  4356. this.isSearchMode = true
  4357. this.loadSearchHistory()
  4358. }
  4359. })
  4360. //排序按钮
  4361. TitleBarPointLightButton({
  4362. iconResource: $r('sys.symbol.list_number'),
  4363. iconSize: 25,
  4364. pointColor: this.themeColor,
  4365. clickScale: 0.6,
  4366. menuBuilder: () => {
  4367. if ((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)) {
  4368. this.SortMenuForArtistAblumBuilder()
  4369. return
  4370. }
  4371. this.SortMenuBuilder()
  4372. }
  4373. })
  4374. //添加按钮
  4375. TitleBarPointLightButton({
  4376. iconResource: $r('sys.symbol.plus'),
  4377. iconSize: 25,
  4378. pointColor: this.themeColor,
  4379. clickScale: 0.6,
  4380. clickHandler: () => {
  4381. this.showAddSheet = !this.showAddSheet;
  4382. }
  4383. })
  4384. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  4385. .bindSheet($$this.showAddSheet, this.addSheet(), {
  4386. height: SheetSize.FIT_CONTENT,
  4387. dragBar: true,
  4388. showClose: true,
  4389. preferType: SheetType.CENTER ,
  4390. title: {
  4391. title: '导入音乐'
  4392. }
  4393. })
  4394. }
  4395. }
  4396. }
  4397. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  4398. .width('100%')
  4399. .translate({
  4400. x: 0,
  4401. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  4402. })
  4403. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  4404. .animation({
  4405. duration: 240,
  4406. curve: Curve.EaseInOut
  4407. })
  4408. }
  4409. @Builder
  4410. addSheet() {
  4411. Scroll() {
  4412. Column() {
  4413. Column() {
  4414. Row() {
  4415. SymbolGlyph($r('sys.symbol.info_circle'))
  4416. .fontSize(22)
  4417. .fontColor([this.themeColor])
  4418. .alignSelf(ItemAlign.Center)
  4419. .margin({ left: 8 })
  4420. Text('导入音乐复制到DownLoad目录')
  4421. .margin({ left: 8 })
  4422. .fontSize(14)
  4423. .fontColor($r('app.color.text_color'))
  4424. .fontWeight(480)
  4425. .layoutWeight(1)
  4426. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  4427. .selectedColor(this.themeColor)
  4428. .switchPointColor(Color.White)
  4429. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4430. .margin({ right: 2 })
  4431. .onChange((checked: boolean) => {
  4432. this.isCopyFileToDownLoad = checked;
  4433. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  4434. })
  4435. .width(50)
  4436. .height(30);
  4437. }
  4438. .height(72)
  4439. .padding({ left:8,right:8 })
  4440. }
  4441. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4442. .backgroundColor($r('app.color.start_window_background'))
  4443. .borderRadius(15)
  4444. .width('85%')
  4445. .margin({
  4446. top: 10,
  4447. bottom: 10
  4448. })
  4449. .padding(0)
  4450. .border({
  4451. color: Color.White,
  4452. width: 1.8
  4453. })
  4454. Menu() {
  4455. MenuItem({
  4456. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  4457. content: "新建文件夹"
  4458. })
  4459. .backgroundColor($r('app.color.silvery'))
  4460. .border({
  4461. width: { bottom: 1 },
  4462. color: '#12ec5c87'
  4463. })
  4464. .margin(10)
  4465. .height(60)
  4466. .padding({left:15,right:15})
  4467. .onClick(async () => {
  4468. this.showMkDialog()
  4469. this.showAddSheet = !this.showAddSheet
  4470. })
  4471. MenuItem({
  4472. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  4473. content: $r('app.string.import_from_files')
  4474. })
  4475. .padding({left:15,right:15})
  4476. .backgroundColor($r('app.color.silvery'))
  4477. .border({
  4478. width: { bottom: 1 },
  4479. color: '#12ec5c87'
  4480. })
  4481. .margin(10)
  4482. .height(60)
  4483. .onClick(async () => {
  4484. this.callFilePickerSelectFile()
  4485. this.showAddSheet = !this.showAddSheet
  4486. })
  4487. MenuItem({
  4488. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  4489. content: '全选导入'
  4490. // content: '从下载文件夹导入(路径:Download/' +
  4491. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  4492. })
  4493. .padding({left:15,right:15})
  4494. .backgroundColor($r('app.color.silvery'))
  4495. .border({
  4496. width: { bottom: 1 },
  4497. color: '#12ec5c87'
  4498. })
  4499. .margin(10)
  4500. .height(60)
  4501. .onClick(async () => {
  4502. this.goSelectMusic()
  4503. this.showAddSheet = !this.showAddSheet
  4504. })
  4505. MenuItem({
  4506. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  4507. content: '自动导入教程'
  4508. })
  4509. .padding({left:15,right:15})
  4510. .backgroundColor($r('app.color.silvery'))
  4511. .border({
  4512. width: { bottom: 1 },
  4513. color: '#12ec5c87'
  4514. })
  4515. .margin(10)
  4516. .height(60)
  4517. .onClick(async () => {
  4518. this.showTips()
  4519. this.showAddSheet = !this.showAddSheet
  4520. })
  4521. MenuItem({
  4522. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  4523. content: '导入疑问'
  4524. })
  4525. .height(60)
  4526. .padding({left:15,right:15})
  4527. .backgroundColor($r('app.color.silvery'))
  4528. .border({
  4529. width: { bottom: 1 },
  4530. color: '#12ec5c87'
  4531. })
  4532. .margin(10)
  4533. .onClick(async () => {
  4534. this.showProblomTips()
  4535. this.showAddSheet = !this.showAddSheet
  4536. })
  4537. }.attributeModifier(new MenuModifier())
  4538. .margin({bottom:30})
  4539. .width('90%')
  4540. .borderRadius(15)
  4541. }
  4542. .layoutWeight(1)
  4543. }
  4544. }
  4545. async showProblomTips() {
  4546. try {
  4547. this.getUIContext().getPromptAction().showDialog({
  4548. title: '导入疑问',
  4549. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  4550. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  4551. buttons: [
  4552. {
  4553. text: '知道了',
  4554. color: '#000000'
  4555. },
  4556. ]
  4557. }, (err, data) => {
  4558. if (err) {
  4559. console.error('showDialog err: ' + err);
  4560. return;
  4561. }
  4562. console.info('showDialog success callback, click button: ' + data.index);
  4563. });
  4564. } catch (error) {
  4565. let message = (error as BusinessError).message;
  4566. let code = (error as BusinessError).code;
  4567. console.error(`showDialog args error code is ${code}, message is ${message}`);
  4568. };
  4569. }
  4570. @Builder
  4571. TagsContentCoverBuilder() {
  4572. Scroll() {
  4573. Column() {
  4574. TagsContentCover(
  4575. {
  4576. selectedFiles:this.selectedFiles,
  4577. isOneKeyTags:this.isOneKeyTags,
  4578. onSeePath:(path:string)=>{
  4579. this.modeType = 0
  4580. this.deleteCache(path)
  4581. this.getSortedFiles(path)
  4582. },
  4583. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4584. this.isMultiSelect = false
  4585. if(result){//如果嵌入成功,更新数据
  4586. this.listRefreshKey++
  4587. setTimeout(()=>{
  4588. this.doUpdateData()
  4589. },500)
  4590. }
  4591. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4592. if(deleteCache_path){
  4593. this.deleteCache(deleteCache_path)
  4594. }
  4595. }
  4596. }
  4597. )
  4598. }
  4599. }
  4600. .width('100%')
  4601. .height('100%')
  4602. }
  4603. @Builder
  4604. FixMessyViewBuilder() {
  4605. Scroll() {
  4606. Column() {
  4607. FixMessyView(
  4608. {
  4609. selectedFiles:this.selectedFiles,
  4610. isFixMessy:this.isFixMessy,
  4611. onFixResult:(result: boolean)=>{
  4612. this.isMultiSelect = false
  4613. if(result){//如果嵌入成功,更新数据
  4614. this.deleteCache(this.currentPath)
  4615. this.doUpdateData()
  4616. }
  4617. }
  4618. }
  4619. )
  4620. }
  4621. }
  4622. .width('100%')
  4623. .height('100%')
  4624. }
  4625. //剪辑音频
  4626. @Builder
  4627. EditAudioBuilder(item:VideoItem) {
  4628. Scroll() {
  4629. Column() {
  4630. EditAudio(
  4631. {
  4632. mVideoItem:item,
  4633. currentPath:this.currentPath,
  4634. videoUrl:this.videoUrl,
  4635. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4636. currentTime:this.currentTime,
  4637. progressValue:this.progressValue,
  4638. onBack:()=>{
  4639. this.isEditAudio = !this.isEditAudio
  4640. },
  4641. onSeeOutputPath:(outPutPath:string)=>{
  4642. this.isEditAudio = !this.isEditAudio
  4643. this.longItemFilePath = ''
  4644. this.modeType = 0
  4645. this.isShowFileName = true
  4646. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4647. },
  4648. onPlayOrPause:()=>{
  4649. this.dispatchTogglePlayForItem(item)
  4650. },
  4651. onSliderChange:(value:number)=>{
  4652. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4653. const seekValue = MusicPlaybackController.resolveSeekValueFromPercent(value, this.getActiveDuration())
  4654. this.dispatchSeekFromEditorSlider(value, item.filePath)
  4655. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4656. },
  4657. onResult:(result: boolean,outPath:string)=>{
  4658. if(result){//如果剪辑成功,更新数据
  4659. this.doUpdateData()
  4660. }else{
  4661. ToastUtil.showToast('剪辑失败')
  4662. }
  4663. }
  4664. }
  4665. )
  4666. }
  4667. }
  4668. .width('100%')
  4669. .height('100%')
  4670. }
  4671. //提取伴奏
  4672. @Builder
  4673. ConverterBuilder(item:VideoItem) {
  4674. Scroll() {
  4675. Column() {
  4676. AudioFormatConverter(
  4677. {
  4678. mVideoItem:item,
  4679. videoUrl:this.videoUrl,
  4680. currentPath:this.currentPath,
  4681. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4682. currentTime:this.currentTime,
  4683. progressValue:this.progressValue,
  4684. onBack:()=>{
  4685. this.isConverter = !this.isConverter
  4686. this.longItemFilePath = ''
  4687. },
  4688. onPlayOrPause:()=>{
  4689. this.dispatchTogglePlayForItem(item)
  4690. },
  4691. onSeeOutputPath:(outPutPath:string)=>{
  4692. this.isConverter = !this.isConverter
  4693. this.longItemFilePath = ''
  4694. this.modeType = 0
  4695. this.isShowFileName = true
  4696. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4697. },
  4698. onSliderChange:(value:number)=>{
  4699. this.dispatchSeekFromEditorSlider(value, item.filePath)
  4700. },
  4701. onResult:(result: boolean,outPath:string)=>{
  4702. if(result){//如果成功,更新数据
  4703. this.doUpdateData()
  4704. }else{
  4705. ToastUtil.showToast('格式转化失败')
  4706. }
  4707. }
  4708. }
  4709. )
  4710. }
  4711. }
  4712. .width('100%')
  4713. .height('100%')
  4714. }
  4715. //提取伴奏
  4716. @Builder
  4717. ExtractAccBuilder(item:VideoItem) {
  4718. Scroll() {
  4719. Column() {
  4720. ExtractAccompaniment(
  4721. {
  4722. mVideoItem:item,
  4723. currentPath:this.currentPath,
  4724. videoUrl:this.videoUrl,
  4725. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4726. currentTime:this.currentTime,
  4727. progressValue:this.progressValue,
  4728. onBack:()=>{
  4729. this.isExtractAcc = !this.isExtractAcc
  4730. this.longItemFilePath = ''
  4731. },
  4732. onPlayOrPause:()=>{
  4733. this.dispatchTogglePlayForItem(item)
  4734. },
  4735. onSeeOutputPath:(outPutPath:string)=>{
  4736. this.isExtractAcc = !this.isExtractAcc
  4737. this.longItemFilePath = ''
  4738. this.modeType = 0
  4739. this.isShowFileName = true
  4740. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4741. },
  4742. onSliderChange:(value:number)=>{
  4743. this.dispatchSeekFromEditorSlider(value, item.filePath)
  4744. },
  4745. onResult:(result: boolean,outPath:string)=>{
  4746. if(result){//如果成功,更新数据
  4747. this.doUpdateData()
  4748. }else{
  4749. ToastUtil.showToast('提取伴奏失败')
  4750. }
  4751. }
  4752. }
  4753. )
  4754. }
  4755. }
  4756. .width('100%')
  4757. .height('100%')
  4758. }
  4759. //AI人声分离
  4760. @Builder
  4761. AiBuilder(item:VideoItem) {
  4762. Scroll() {
  4763. Column() {
  4764. AIVoiceSeparation(
  4765. {
  4766. mVideoItem:item,
  4767. videoUrl:this.videoUrl,
  4768. currentPath:this.currentPath,
  4769. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4770. currentTime:this.currentTime,
  4771. progressValue:this.progressValue,
  4772. onBack:()=>{
  4773. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4774. this.longItemFilePath = ''
  4775. },
  4776. onPlayOrPause:()=>{
  4777. this.dispatchTogglePlayForItem(item, true)
  4778. },
  4779. onPlayPath:(path:string)=>{
  4780. this.videoUrl==path
  4781. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4782. if(itemP)
  4783. this.doPlay(itemP,0,false,true)
  4784. },
  4785. onSeeOutputPath:(outPutPath:string)=>{
  4786. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4787. this.longItemFilePath = ''
  4788. this.modeType = 0
  4789. this.isShowFileName = true
  4790. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4791. },
  4792. onSliderChange:(value:number)=>{
  4793. this.dispatchSeekFromEditorSlider(value, item.filePath)
  4794. },
  4795. onResult:(result: boolean,outPath:string)=>{
  4796. if(result){//如果成功,更新数据
  4797. this.doUpdateData()
  4798. }else{
  4799. ToastUtil.showToast('Ai人声分离失败')
  4800. }
  4801. }
  4802. }
  4803. )
  4804. }
  4805. }
  4806. .width('100%')
  4807. .height('100%')
  4808. }
  4809. //变速变调
  4810. @Builder
  4811. ChangeToneBuilder(item:VideoItem) {
  4812. Scroll() {
  4813. Column() {
  4814. ChangeTone(
  4815. {
  4816. mVideoItem:item,
  4817. currentPath:this.currentPath,
  4818. videoUrl:this.videoUrl,
  4819. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4820. currentTime:this.currentTime,
  4821. progressValue:this.progressValue,
  4822. onBack:()=>{
  4823. this.isChangeTone = !this.isChangeTone
  4824. this.longItemFilePath = ''
  4825. },
  4826. onPlayOrPause:()=>{
  4827. this.dispatchTogglePlayForItem(item)
  4828. },
  4829. onSeeOutputPath:(outPutPath:string)=>{
  4830. this.isChangeTone = !this.isChangeTone
  4831. this.longItemFilePath = ''
  4832. this.modeType = 0
  4833. this.isShowFileName = true
  4834. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4835. },
  4836. onSliderChange:(value:number)=>{
  4837. this.dispatchSeekFromEditorSlider(value, item.filePath)
  4838. },
  4839. onResult:(result: boolean,outPath:string)=>{
  4840. if(result){//如果成功,更新数据
  4841. this.doUpdateData()
  4842. }else{
  4843. ToastUtil.showToast('变速变调失败')
  4844. }
  4845. }
  4846. }
  4847. )
  4848. }
  4849. }
  4850. .width('100%')
  4851. .height('100%')
  4852. }
  4853. //提取视频中的音频
  4854. @Builder
  4855. extractAudioFromVideoBuilder(item:VideoItem) {
  4856. Scroll() {
  4857. Column() {
  4858. ExtractAudioFromVideo(
  4859. {
  4860. mVideoItem:item,
  4861. currentPath:this.currentPath,
  4862. videoUrl:this.videoUrl,
  4863. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4864. currentTime:this.currentTime,
  4865. progressValue:this.progressValue,
  4866. onBack:()=>{
  4867. this.isExtractAudio = !this.isExtractAudio
  4868. this.longItemFilePath = ''
  4869. },
  4870. onPlayOrPause:()=>{
  4871. this.dispatchTogglePlayForItem(item)
  4872. },
  4873. onSeeOutputPath:(outPutPath:string)=>{
  4874. this.isExtractAudio = !this.isExtractAudio
  4875. this.longItemFilePath = ''
  4876. this.modeType = 0
  4877. this.isShowFileName = true
  4878. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4879. },
  4880. onSliderChange:(value:number)=>{
  4881. this.dispatchSeekFromEditorSlider(value, item.filePath)
  4882. },
  4883. onResult:(result: boolean,outPath:string)=>{
  4884. if(result){//如果成功,更新数据
  4885. this.doUpdateData()
  4886. }else{
  4887. ToastUtil.showToast('提取音频失败')
  4888. }
  4889. }
  4890. }
  4891. )
  4892. }
  4893. }
  4894. .width('100%')
  4895. .height('100%')
  4896. }
  4897. //合并音频
  4898. @Builder
  4899. MergeAudioBuilder() {
  4900. Scroll() {
  4901. Column() {
  4902. MergeAudio(
  4903. {
  4904. videoUrl:this.videoUrl,
  4905. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4906. currentPath:this.currentPath,
  4907. selectedFiles:this.selectedFiles,
  4908. currentTime:this.currentTime,
  4909. progressValue:this.progressValue,
  4910. onBack:()=>{
  4911. this.isMergeAudio = !this.isMergeAudio
  4912. this.longItemFilePath = ''
  4913. },
  4914. // onPlayPath:(path:string)=>{
  4915. // if(this.videoUrl==item.filePath){
  4916. // this.playOrPause()
  4917. // }else{//如果不是当前播放的,则播放该文件
  4918. // this.videoUrl==item.filePath
  4919. // this.doPlay(item,0,false,true)
  4920. // }
  4921. //
  4922. // },
  4923. onSeeOutputPath:(outPutPath:string)=>{
  4924. this.isMergeAudio = !this.isMergeAudio
  4925. this.longItemFilePath = ''
  4926. this.modeType = 0
  4927. this.isShowFileName = true
  4928. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4929. },
  4930. onResult:(result: boolean,outPath:string)=>{
  4931. if(result){//如果成功,更新数据
  4932. this.doUpdateData()
  4933. }else{
  4934. if(this.selectedFiles.length>=3){
  4935. ToastUtil.showToast('合并数量太多导致失败')
  4936. }else{
  4937. ToastUtil.showToast('合并失败')
  4938. }
  4939. }
  4940. }
  4941. }
  4942. )
  4943. }
  4944. }
  4945. .width('100%')
  4946. .height('100%')
  4947. }
  4948. asyncCurrentPathData() {
  4949. if (this.modeType == 0) {
  4950. workerInstance.postMessage({
  4951. code: 1,
  4952. data1: this.context,
  4953. data2: this.currentPath,
  4954. data3: this.lockPath,
  4955. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4956. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4957. });
  4958. }
  4959. }
  4960. // 处理文件选择的函数
  4961. handleFileSelection(item: VideoItem, checked: boolean) {
  4962. if (!this.isSelectableLocalItem(item)) {
  4963. return
  4964. }
  4965. const exists = this.isLocalItemSelected(item)
  4966. if (checked) {
  4967. if (!exists) {
  4968. this.selectedFiles = [...this.selectedFiles, item];
  4969. }
  4970. } else if (exists) {
  4971. this.selectedFiles = this.selectedFiles.filter(selected => selected.filePath !== item.filePath);
  4972. if (this.selectedFiles.length === 0) {
  4973. this.isAllSelected = false
  4974. }
  4975. }
  4976. this.syncLocalSelectionState()
  4977. }
  4978. private deleteComponentId: number = 0
  4979. private closeDeleteDialog(afterClose?: () => void): void {
  4980. if (this.deleteComponentId > 0) {
  4981. try {
  4982. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4983. } catch (_error) {
  4984. }
  4985. this.deleteComponentId = 0
  4986. }
  4987. if (afterClose) {
  4988. setTimeout(() => {
  4989. afterClose()
  4990. }, 16)
  4991. }
  4992. }
  4993. private resetDeleteSelectionState(): void {
  4994. this.isMultiSelect = false
  4995. this.selectedFiles = []
  4996. this.isAllSelected = false
  4997. }
  4998. private removeDisplayedLocalItemsByKeys(deletedKeys: Set<string>): void {
  4999. for (let index = this.dataSource.dataArray.length - 1; index >= 0; index--) {
  5000. const item = this.dataSource.dataArray[index]
  5001. if (item && deletedKeys.has(item.filePath)) {
  5002. this.dataSource.deleteData(index)
  5003. }
  5004. }
  5005. }
  5006. private async removeDeletedLocalItemsLocally(deletedItems: Array<VideoItem>): Promise<void> {
  5007. if (ArrayUtil.isEmpty(deletedItems) || this.modeType !== 0) {
  5008. return
  5009. }
  5010. const deletedKeys: Set<string> = new Set<string>()
  5011. for (let i = 0; i < deletedItems.length; i++) {
  5012. const item = deletedItems[i]
  5013. if (StrUtil.isNotEmpty(item?.filePath)) {
  5014. deletedKeys.add(item.filePath)
  5015. }
  5016. }
  5017. if (deletedKeys.size <= 0) {
  5018. return
  5019. }
  5020. const nextVideoLocalList = this.videoLocalList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  5021. const nextDirList = this.dirList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  5022. const nextFilteredList = this.filteredList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  5023. const removedCount = this.videoLocalList.length - nextVideoLocalList.length
  5024. this.videoLocalList = nextVideoLocalList
  5025. this.dirList = nextDirList
  5026. this.filteredList = nextFilteredList
  5027. this.removeDisplayedLocalItemsByKeys(deletedKeys)
  5028. if (removedCount > 0 && this.totalCount > 0) {
  5029. this.totalCount = Math.max(0, this.totalCount - removedCount)
  5030. }
  5031. this.pageCache.clear()
  5032. this.pageHasMoreCache.clear()
  5033. this.pageTotalCountCache.clear()
  5034. this.setButtonStatus()
  5035. this.markAlphaBetDirty()
  5036. this.syncLocalSelectionState()
  5037. this.addCache(this.currentPath, nextVideoLocalList)
  5038. if (this.currentPath === this.rootPath) {
  5039. this.addCache(this.currentPath + '_dirList', nextDirList)
  5040. }
  5041. this.deleteStringCache(this.currentPath + '_hash')
  5042. await this.saveCacheToStorage()
  5043. }
  5044. //多选删除文件
  5045. showWarnIsDelete(){
  5046. this.getUIContext().getPromptAction().openCustomDialog({
  5047. builder: () => {
  5048. this.deleteComptentBuilder()
  5049. },
  5050. isModal:true,
  5051. showInSubWindow:false,
  5052. maskColor: Color.Transparent,
  5053. dialogTransition: // 设置弹窗内容显示的过渡效果
  5054. TransitionEffect.translate({ x: 0, y: 120, z: 0 })
  5055. .combine(TransitionEffect.opacity(0.01))
  5056. .animation({ duration: 260, curve: Curve.EaseOut }),
  5057. maskTransition: // 设置蒙层显示的过渡效果
  5058. TransitionEffect.opacity(0)
  5059. .animation({ duration: 220, curve: Curve.EaseOut })
  5060. }).then((dialogId: number) => {
  5061. this.deleteComponentId = dialogId
  5062. })
  5063. .catch((error: BusinessError) => {
  5064. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  5065. })
  5066. }
  5067. @Builder
  5068. deleteComptentBuilder(){
  5069. DeleteComptent({
  5070. selectedFiles:this.selectedFiles,
  5071. isPlaylistMode: this.modeType == 4,
  5072. playlistId: this.currentSongListID,
  5073. onCancel:()=>{
  5074. this.closeDeleteDialog(() => {
  5075. this.resetDeleteSelectionState()
  5076. })
  5077. },
  5078. onDeleteResult:(result: boolean)=>{
  5079. const deletedItems = [...this.selectedFiles]
  5080. this.closeDeleteDialog(() => {
  5081. this.resetDeleteSelectionState()
  5082. if(result){//如果删除成功,更新数据
  5083. if (this.modeType == 4) {
  5084. this.doSongListTask()
  5085. } else {
  5086. void this.removeDeletedLocalItemsLocally(deletedItems)
  5087. }
  5088. }
  5089. })
  5090. }
  5091. })
  5092. }
  5093. //多选移动文件
  5094. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5095. Logger.info('onecold showCutDialogForMultipleFiles')
  5096. let mList: Array<string> = []
  5097. let rPath = this.rootPath
  5098. if (isCurrent) {
  5099. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5100. rPath = this.currentPath
  5101. } else {
  5102. mList = Utility.getNameList(this.dirList);
  5103. rPath = this.rootPath
  5104. }
  5105. let dataBean = new BubbleBean();
  5106. dataBean.data = mList;
  5107. dataBean.color = this.themeColor
  5108. dataBean.onItemClick = (i) => {
  5109. const newDirPath = rPath + '/' + mList[i];
  5110. // Logger.info('newDirPath = ' + newDirPath)
  5111. this.selectedFiles.forEach((item) => {
  5112. const targetName = item.fileName || item.name;
  5113. const newPath = newDirPath + '/' + targetName;
  5114. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  5115. ToastUtil.showToast('移动成功');
  5116. this.table.deleteData(item, () => {
  5117. this.cache.delete(this.currentPath); // 删除原路径缓存
  5118. this.cache.delete(newDirPath); // 删除目标路径缓存
  5119. this.getSortedFiles(this.currentPath, true);
  5120. });
  5121. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5122. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5123. if (!Utility.isIsoByExtension(newPath)) {
  5124. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5125. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5126. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5127. this.table.insert(newItem, (id: number) => {
  5128. //加入数据库
  5129. });
  5130. }
  5131. }
  5132. }).catch((error: Error) => {
  5133. console.error(error.message);
  5134. });
  5135. });
  5136. this.isMultiSelect = false
  5137. this.selectedFiles = [];
  5138. this.isAllSelected = false
  5139. XPopup.dismissTop();
  5140. };
  5141. let pup: XPopup
  5142. if (this.isDarkMode) {
  5143. pup = XPopup.Builder()
  5144. .setPopupPosition(PopupPosition.TOP)
  5145. .atView(viewId)
  5146. .setBackgroundColor(Color.Black)
  5147. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5148. .show();
  5149. } else {
  5150. pup = XPopup.Builder()
  5151. .setPopupPosition(PopupPosition.TOP)
  5152. .atView(viewId)
  5153. .setBackgroundColor(Color.White)
  5154. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5155. .show();
  5156. }
  5157. }
  5158. /**
  5159. * 加载所有歌单
  5160. */
  5161. async loadAllPlaylists() {
  5162. try {
  5163. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  5164. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  5165. } catch (error) {
  5166. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  5167. }
  5168. }
  5169. /**
  5170. * 显示添加到歌单对话框
  5171. */
  5172. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  5173. const songs = Array.isArray(items) ? items : [items]
  5174. const musicItems = songs.filter(song =>
  5175. song.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(song))
  5176. if (musicItems.length === 0) {
  5177. ToastUtil.showToast('请选择要添加的歌曲')
  5178. return
  5179. }
  5180. // 加载最新的歌单列表
  5181. await this.loadAllPlaylists()
  5182. showAddToPlaylistDialog(
  5183. musicItems,
  5184. this.allPlaylists,
  5185. async (playlistId: string) => {
  5186. // 添加歌曲到歌单
  5187. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  5188. musicItems.map(song => song.filePath))
  5189. if (success) {
  5190. const count = musicItems.length
  5191. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  5192. // 重新加载歌单列表
  5193. await this.loadAllPlaylists()
  5194. } else {
  5195. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  5196. }
  5197. this.longItemFilePath = ''
  5198. if (this.isMultiSelect) {
  5199. this.isMultiSelect = false
  5200. this.isAllSelected = false
  5201. this.selectedFiles = []
  5202. }
  5203. },
  5204. () => {
  5205. LogUtil.info('取消添加到歌单')
  5206. },
  5207. () => {
  5208. // 创建新歌单
  5209. showCreatePlaylistDialog(
  5210. async (name: string, description: string, coverPath?: string) => {
  5211. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  5212. if (success) {
  5213. ToastUtil.showToast('歌单创建成功')
  5214. // 重新加载歌单列表并打开添加对话框
  5215. await this.loadAllPlaylists()
  5216. await this.openAddToPlaylistDialog(musicItems)
  5217. } else {
  5218. ToastUtil.showToast('歌单创建失败')
  5219. }
  5220. },
  5221. () => {
  5222. // 取消创建歌单
  5223. }
  5224. )
  5225. }
  5226. )
  5227. }
  5228. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  5229. const nextFavList = [...this.favList];
  5230. const itemFavKey = Utility.getFavMatchKey(item);
  5231. const favIndex = nextFavList.findIndex((favItem: VideoItem) => Utility.getFavMatchKey(favItem) === itemFavKey);
  5232. if (isFav === 1) {
  5233. if (favIndex >= 0) {
  5234. nextFavList[favIndex].isFav = 1;
  5235. } else {
  5236. const favItem = cloneVideoItem(item);
  5237. favItem.isFav = 1;
  5238. nextFavList.push(favItem);
  5239. }
  5240. } else if (favIndex >= 0) {
  5241. nextFavList.splice(favIndex, 1);
  5242. }
  5243. this.favList = nextFavList;
  5244. item.isFav = isFav;
  5245. if (this.currentSong && Utility.getFavMatchKey(this.currentSong) === itemFavKey) {
  5246. this.currentSong.isFav = isFav;
  5247. this.isFac = isFav === 1;
  5248. }
  5249. }
  5250. private syncFavoriteStateForPlainList(list: Array<VideoItem> | undefined, targetKey: string, isFav: number): boolean {
  5251. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5252. return false;
  5253. }
  5254. let changed = false;
  5255. for (let index = 0; index < list.length; index += 1) {
  5256. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5257. continue;
  5258. }
  5259. list[index].isFav = isFav;
  5260. changed = true;
  5261. }
  5262. return changed;
  5263. }
  5264. private syncFavoriteStateForVisibleList(list: Array<VideoItem> | undefined, dataSource: LazyDataSource<VideoItem>,
  5265. targetKey: string, isFav: number, removeOnCancel: boolean): boolean {
  5266. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5267. return false;
  5268. }
  5269. let changed = false;
  5270. for (let index = list.length - 1; index >= 0; index -= 1) {
  5271. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5272. continue;
  5273. }
  5274. changed = true;
  5275. if (removeOnCancel) {
  5276. list.splice(index, 1);
  5277. if (index < dataSource.dataArray.length) {
  5278. dataSource.deleteData(index);
  5279. }
  5280. } else {
  5281. list[index].isFav = isFav;
  5282. if (index < dataSource.dataArray.length) {
  5283. dataSource.dataArray[index].isFav = isFav;
  5284. dataSource.notifyDataChange(index);
  5285. }
  5286. }
  5287. }
  5288. return changed;
  5289. }
  5290. private syncFavoriteStateInCaches(targetKey: string, isFav: number): void {
  5291. if (StrUtil.isEmpty(targetKey) || this.cache.size === 0) {
  5292. return;
  5293. }
  5294. let changed = false;
  5295. this.cache.forEach((items: Array<VideoItem>) => {
  5296. for (let index = 0; index < items.length; index += 1) {
  5297. if (Utility.getFavMatchKey(items[index]) !== targetKey) {
  5298. continue;
  5299. }
  5300. items[index].isFav = isFav;
  5301. changed = true;
  5302. }
  5303. });
  5304. if (changed) {
  5305. void this.saveCacheToStorage();
  5306. }
  5307. }
  5308. private syncFavoriteStateAcrossCollections(item: VideoItem, isFav: number): void {
  5309. const targetKey = Utility.getFavMatchKey(item);
  5310. if (StrUtil.isEmpty(targetKey)) {
  5311. return;
  5312. }
  5313. const removeFromCurrentView = this.isFavMusic && isFav === 0;
  5314. const currentViewChanged = this.syncFavoriteStateForVisibleList(this.videoLocalList, this.dataSource, targetKey, isFav,
  5315. removeFromCurrentView);
  5316. this.syncFavoriteStateForVisibleList(this.songList, this.sonDataSource, targetKey, isFav, false);
  5317. this.syncFavoriteStateForPlainList(this.currentSongList, targetKey, isFav);
  5318. this.syncFavoriteStateForPlainList(this.historyList, targetKey, isFav);
  5319. this.syncFavoriteStateForPlainList(this.mediaKuList, targetKey, isFav);
  5320. this.syncFavoriteStateForPlainList(this.artistList, targetKey, isFav);
  5321. this.syncFavoriteStateForPlainList(this.albumList, targetKey, isFav);
  5322. this.syncFavoriteStateForPlainList(this.filteredList, targetKey, isFav);
  5323. this.syncFavoriteStateInCaches(targetKey, isFav);
  5324. if (this.isFavMusic) {
  5325. this.currentTitleCover = ArrayUtil.isNotEmpty(this.favList) ? Utility.getFirstCoverFromList(this.favList) :
  5326. $r('app.media.alt');
  5327. }
  5328. if (currentViewChanged) {
  5329. this.setButtonStatus();
  5330. if (removeFromCurrentView) {
  5331. this.markAlphaBetDirty();
  5332. }
  5333. }
  5334. }
  5335. private syncRemoteFavoriteState(item: VideoItem, isFav: number): void {
  5336. if (!item || !isRemoteCloudType(item.type) || StrUtil.isEmpty(item.filePath)) {
  5337. return;
  5338. }
  5339. const remoteManager = RemoteDriveManager.getInstance();
  5340. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  5341. if (target) {
  5342. target.isFav = isFav;
  5343. }
  5344. }
  5345. doFav(item: VideoItem) {
  5346. LogUtil.info('onecold doFav isFav=' + item.isFav)
  5347. let isFav = 0
  5348. if (Utility.getIsFav(this.favList, item)) {
  5349. isFav = 0
  5350. } else {
  5351. isFav = 1
  5352. }
  5353. const targetFilePath = isRemoteCloudType(item.type) ? (this.resolveRemoteStoragePath(item) || item.filePath) :
  5354. item.filePath;
  5355. const onUpdateSuccess = (): void => {
  5356. this.syncFavStateLocal(item, isFav);
  5357. this.syncRemoteFavoriteState(item, isFav);
  5358. this.syncFavoriteStateAcrossCollections(item, isFav);
  5359. if (isFav === 1) {
  5360. ToastUtil.showToast('收藏成功');
  5361. } else {
  5362. ToastUtil.showToast('取消收藏成功');
  5363. }
  5364. };
  5365. const updateFavorite = (): void => {
  5366. this.table.updateIsFavByFilePath(targetFilePath, isFav, async (result: boolean, error?: string) => {
  5367. if (result) {
  5368. onUpdateSuccess();
  5369. return;
  5370. }
  5371. if (isRemoteCloudType(item.type)) {
  5372. Logger.warn(TAG, `远程歌曲收藏更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  5373. try {
  5374. await this.persistRemoteMetadataToDb(item);
  5375. this.table.updateIsFavByFilePath(targetFilePath, isFav, (retryResult: boolean, retryError?: string) => {
  5376. if (retryResult) {
  5377. onUpdateSuccess();
  5378. } else {
  5379. Logger.error(TAG, `远程歌曲收藏补入库后仍失败: ${targetFilePath}, error=${retryError}`);
  5380. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5381. }
  5382. });
  5383. } catch (persistError) {
  5384. Logger.error(TAG,
  5385. `远程歌曲收藏补入库失败: ${targetFilePath}, error=${(persistError as Error).message}`);
  5386. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5387. }
  5388. return;
  5389. }
  5390. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5391. })
  5392. };
  5393. updateFavorite()
  5394. }
  5395. //多选复制文件
  5396. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5397. console.log('onecold showCopyDialogForMultipleFiles');
  5398. let mList: Array<string> = []
  5399. let rPath = this.rootPath
  5400. if (isCurrent) {
  5401. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5402. rPath = this.currentPath
  5403. } else {
  5404. mList = Utility.getNameList(this.dirList);
  5405. rPath = this.rootPath
  5406. }
  5407. let dataBean = new BubbleBean();
  5408. dataBean.data = mList;
  5409. dataBean.isCopy = true
  5410. dataBean.color = this.themeColor
  5411. dataBean.onItemClick = (i) => {
  5412. const newDirPath = rPath + '/' + mList[i];
  5413. // Logger.info('newDirPath = ' + newDirPath)
  5414. this.selectedFiles.forEach((item) => {
  5415. const targetName = item.fileName || item.name;
  5416. const newPath = newDirPath + '/' + targetName;
  5417. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  5418. ToastUtil.showToast('复制成功');
  5419. this.cache.delete(newDirPath); // 删除目标路径缓存
  5420. this.getSortedFiles(this.currentPath);
  5421. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5422. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5423. if (!Utility.isIsoByExtension(newPath)) {
  5424. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5425. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5426. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5427. this.table.insert(newItem, (id: number) => {
  5428. //加入数据库
  5429. });
  5430. }
  5431. }
  5432. }).catch((error: Error) => {
  5433. console.error(error.message);
  5434. });
  5435. });
  5436. this.isMultiSelect = false
  5437. this.selectedFiles = [];
  5438. this.isAllSelected = false
  5439. XPopup.dismissTop();
  5440. };
  5441. let pup: XPopup
  5442. if (this.isDarkMode) {
  5443. pup = XPopup.Builder()
  5444. .setPopupPosition(PopupPosition.TOP)
  5445. .atView(viewId)
  5446. .setBackgroundColor(Color.Black)
  5447. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5448. .show();
  5449. } else {
  5450. pup = XPopup.Builder()
  5451. .setPopupPosition(PopupPosition.TOP)
  5452. .atView(viewId)
  5453. .setBackgroundColor(Color.White)
  5454. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5455. .show();
  5456. }
  5457. }
  5458. @Builder
  5459. private DirItem(item: VideoItem, index?: number) {
  5460. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5461. Row() {
  5462. if(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath)){
  5463. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5464. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5465. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5466. .fillColor(this.themeColor)// .fontSize(33)
  5467. .alt($r('app.media.music_group'))
  5468. .borderRadius(this.isCoverRectangle?9:'100%')
  5469. .clip(true)
  5470. .shadow({
  5471. radius: 2,
  5472. type: ShadowType.BLUR,
  5473. color: 'on_primary'
  5474. })
  5475. .sourceSize({width:38, height:38})
  5476. .margin({ left: 20, top: 8, bottom: 8 })
  5477. }else{
  5478. SymbolGlyph($r('sys.symbol.folder'))
  5479. .fontSize(this.twoFingerType==3?55:this.twoFingerType==2?50:45)
  5480. .fontColor([this.themeColor])
  5481. .alignSelf(ItemAlign.Center)
  5482. .margin({ left: 20 ,top:8,bottom:8})
  5483. }
  5484. Column() {
  5485. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5486. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5487. .maxLines(1)// .width('88%')
  5488. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  5489. .margin({ left: 10, right: 20 })
  5490. .fontColor($r('app.color.text_color'))
  5491. Row() {
  5492. Text(`${this.getArtistSongCount(item.name)}首`)
  5493. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5494. .padding({ top: 8 })
  5495. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  5496. .fontColor($r('app.color.text_color'))
  5497. .margin({ left: 10 })
  5498. Text(`${this.getAlbumSongCount(item.name)}首`)
  5499. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5500. .padding({ top: 8 })
  5501. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  5502. .fontColor($r('app.color.text_color'))
  5503. .margin({ left: 10 })
  5504. Blank()
  5505. }
  5506. }
  5507. .height('100%')
  5508. .width('100%')
  5509. .justifyContent(FlexAlign.Center)
  5510. .alignItems(HorizontalAlign.Start)
  5511. Blank()
  5512. Checkbox({ name: 'dir_checkbox' + (index ?? -1) })
  5513. .select(this.isLocalItemSelected(item))
  5514. .selectedColor(this.themeColor)
  5515. .shape(CheckBoxShape.CIRCLE)
  5516. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5517. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible : Visibility.None)
  5518. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5519. .margin({ left: 20, top: 8, bottom: 8, right: 18 })
  5520. .width(22)
  5521. .height(22)
  5522. Image($r('app.media.arrow_right'))
  5523. .height(25)
  5524. .alignSelf(ItemAlign.Center)
  5525. .id(item.filePath)
  5526. .visibility(this.isShowAlphaBet || (this.isMultiSelect && this.isSelectableLocalItem(item)) ?
  5527. Visibility.None : Visibility.Visible)
  5528. }
  5529. }
  5530. .backgroundColor(Color.Transparent)
  5531. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5532. .width('98%')
  5533. .reuseId('dir_item')
  5534. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  5535. .opacity(this.opacityItem) // 绑定透明度
  5536. .onTouch((event: TouchEvent) => {
  5537. this.handlePointLightTouch(this.getPointLightItemKey('list_dir', item, index), event)
  5538. })
  5539. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5540. ? new hdsEffect.HdsEffectBuilder()
  5541. .pointLight({
  5542. options: this.getPointLightOptions(this.getPointLightItemKey('list_dir', item, index)),
  5543. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5544. })
  5545. .buildEffect()
  5546. : undefined)
  5547. }
  5548. private refreshDirVisibilitySettings(): void {
  5549. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  5550. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  5551. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  5552. }
  5553. isShowDir(dirName: string) {
  5554. if (dirName === undefined) {
  5555. return true
  5556. }
  5557. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  5558. return this.isShowSimi
  5559. }
  5560. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  5561. return this.isShowFAV
  5562. }
  5563. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  5564. return this.isShowHistory
  5565. }
  5566. return true
  5567. }
  5568. private getPointLightItemKey(prefix: string, item: VideoItem, index?: number): string {
  5569. const itemPath = StrUtil.isNotEmpty(item.filePath) ? item.filePath : `${item.name}_${index ?? -1}`
  5570. return `${prefix}_${itemPath}`
  5571. }
  5572. private handlePointLightTouch(itemKey: string, event: TouchEvent): void {
  5573. if (deviceInfo.sdkApiVersion < 20) {
  5574. return
  5575. }
  5576. if (event.type === TouchType.Down) {
  5577. this.activePointLightItemKey = itemKey
  5578. this.pointLightOptions = {
  5579. color: this.themeColor,
  5580. intensity: 1,
  5581. height: 60
  5582. }
  5583. return
  5584. }
  5585. if ((event.type === TouchType.Up || event.type === TouchType.Cancel) && this.activePointLightItemKey === itemKey) {
  5586. this.activePointLightItemKey = ''
  5587. this.pointLightOptions = undefined
  5588. }
  5589. }
  5590. private getPointLightOptions(itemKey: string): hdsEffect.PointLightOptions | undefined {
  5591. if (this.activePointLightItemKey !== itemKey) {
  5592. return undefined
  5593. }
  5594. return this.pointLightOptions
  5595. }
  5596. @State opacityItem: number = 1; // 控制透明度的状态变量
  5597. @Builder
  5598. private MusicItem(item: VideoItem, index?: number) {
  5599. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5600. Row() {
  5601. Stack() {
  5602. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5603. .fillColor(this.themeColor)
  5604. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5605. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5606. .alt($r('app.media.alt'))
  5607. .borderRadius(this.isCoverRectangle?9:'100%')
  5608. .clip(true)
  5609. .draggable(false)
  5610. .sourceSize({width:38, height:38})
  5611. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5612. // .autoResize(true) // 重采样,可减少内存占用
  5613. .opacity(this.opacityItem)// 绑定透明度
  5614. .margin({ left: 20 })
  5615. .shadow({
  5616. radius: this.isScrolling ? 0 : 10,
  5617. type: ShadowType.BLUR,
  5618. color: 'on_primary'
  5619. })
  5620. .onClick(()=>{
  5621. if (this.isMultiSelect) {
  5622. const isChecked = this.isLocalItemSelected(item);
  5623. this.handleFileSelection(item, !isChecked);
  5624. } else {
  5625. this.doPlay(item,index)
  5626. this.setShowPlayTrue()
  5627. }
  5628. })
  5629. }
  5630. Column() {
  5631. Column() {
  5632. Text(this.isShowFileName?item.fileName :item.name)
  5633. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5634. .maxLines(1)
  5635. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5636. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5637. $r('app.color.text_color'))
  5638. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5639. .padding({right:25})
  5640. .bindPopup(this.longItemFilePath === item.filePath, {
  5641. builder: this.MenuBuilder(item,index,item.filePath),
  5642. placement: Placement.Top,
  5643. // autoCancel: true,
  5644. mask: {color:'#33000000'},
  5645. // popupColor: Color.Yellow,
  5646. enableArrow: false,//是否显示箭头
  5647. showInSubWindow: false,
  5648. onStateChange: (e) => {
  5649. if (!e.isVisible) {
  5650. this.longItemFilePath = ''
  5651. this.tempLyricContent = ''
  5652. }
  5653. }
  5654. })
  5655. Row() {
  5656. Column(){
  5657. Text(item.md5Str?.includes('Lossless')?
  5658. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5659. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5660. .padding({ top: 3,right:6,left:6,bottom:3 })
  5661. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5662. $r('app.color.text_color'))
  5663. .fontWeight(500)
  5664. .borderRadius(12)
  5665. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  5666. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5667. .backgroundColor('#FFC107')
  5668. }
  5669. .padding({ top: 8 })
  5670. Text(StrUtil.isEmpty(item.artist) ? item.duration
  5671. :this.twoFingerType==2? item.artist +' ' + item.duration
  5672. : item.artist + ' ' + item?.duration)
  5673. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5674. .padding({ top: 8 ,right:25})
  5675. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  5676. .maxLines(1)
  5677. .opacity(0.85)
  5678. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  5679. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5680. $r('app.color.text_color'))
  5681. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5682. Blank()
  5683. Text(this.isShowFileName?item.duration:item.size)
  5684. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5685. .padding({ top: 8 })
  5686. .maxLines(1)
  5687. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  5688. ? Visibility.Visible : Visibility.None)
  5689. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5690. Color.Gray)
  5691. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  5692. }
  5693. }
  5694. .height('100%')
  5695. .width('100%')
  5696. .margin({ right: 10 })
  5697. .justifyContent(FlexAlign.Center)
  5698. .alignItems(HorizontalAlign.Start)
  5699. }
  5700. .height('100%')
  5701. .margin({ left: 5 })
  5702. .layoutWeight(1)
  5703. Column() {
  5704. Checkbox({ name: 'checkbox' + index })
  5705. .select(this.isLocalItemSelected(item))
  5706. .selectedColor(this.themeColor)
  5707. .shape(CheckBoxShape.CIRCLE)
  5708. .opacity(this.isMultiSelect ? 1 : 0)
  5709. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  5710. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5711. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  5712. .width(22)
  5713. .height(22)
  5714. PlayingIndicator({
  5715. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  5716. indicatorSize: 18,
  5717. marginRight: 20,
  5718. marginTop: 8,
  5719. marginBottom: 8
  5720. })
  5721. }
  5722. }
  5723. }
  5724. .gesture(LongPressGesture()
  5725. .onAction(async () => {
  5726. //如果是专辑和艺术家的首页,不能长按
  5727. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5728. return
  5729. //如果是我的收藏 最近播放等也不能长按
  5730. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5731. item.name === LocalMusic.STR_HISTORY_MUSIC
  5732. )
  5733. return
  5734. this.longItemFilePath = item.filePath
  5735. this.tempLyricContent = this.supportsLocalAudioActions(item) ? await this.getLyricContent(item) : ''
  5736. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5737. })
  5738. .onActionEnd((event: GestureEvent) => {
  5739. }))
  5740. .backgroundColor(Color.Transparent)
  5741. .width('100%')
  5742. .reuseId('file_item')
  5743. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5744. .onTouch((event: TouchEvent) => {
  5745. this.handlePointLightTouch(this.getPointLightItemKey('list_music', item, index), event)
  5746. })
  5747. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5748. ? new hdsEffect.HdsEffectBuilder()
  5749. .pointLight({
  5750. options: this.getPointLightOptions(this.getPointLightItemKey('list_music', item, index)),
  5751. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5752. })
  5753. .buildEffect()
  5754. : undefined)
  5755. }
  5756. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5757. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5758. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5759. direction: Direction.Ltr,
  5760. buttonPadding:{top:12,bottom:12},
  5761. backgroundColor: Color.Transparent,
  5762. fontSize:14,
  5763. selectedFontSize:15,
  5764. selectedFontColor:Color.White,
  5765. selectedBackgroundColor: this.themeColor,
  5766. localizedTextPadding: {
  5767. end: LengthMetrics.vp(20),
  5768. start: LengthMetrics.vp(20)
  5769. }
  5770. })
  5771. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5772. //当胶囊按钮的选择发生变化时调用此函数
  5773. capsuleSelectedIndexesChanged() {
  5774. this.modeType = this.tabSelectedIndexes[0]
  5775. }
  5776. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5777. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5778. isShowCoverHeader() {
  5779. if (!this.isShowHeader) {
  5780. return false
  5781. }
  5782. if (this.modeType == 0) {
  5783. if (this.isHistory || this.isFavMusic) {
  5784. return true
  5785. }
  5786. if (this.currentPath != this.rootPath) {
  5787. return true
  5788. }
  5789. }
  5790. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5791. }
  5792. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5793. if (this.isCustomizeBg) {
  5794. return ('rgba(255,255,255,0.2)')
  5795. }
  5796. if (this.isDarkMode) {
  5797. return $r('app.color.user_center_card_background')
  5798. }
  5799. return this.currentTitleCover
  5800. }
  5801. // 第二步:popup构造器定义弹框内容
  5802. @Builder popupBuilder() {
  5803. Column({ space: 2 }) {
  5804. Text('友情提示:双指缩放可以放大缩小列表')
  5805. .fontSize(12)
  5806. .fontWeight(FontWeight.Regular)
  5807. .fontColor($r('app.color.text_color'))
  5808. }
  5809. .justifyContent(FlexAlign.SpaceAround)
  5810. .width(220)
  5811. .height(55)
  5812. .padding(15)
  5813. }
  5814. //搜索功能的实现
  5815. @State searchText: string = ''; // 用户输入内容
  5816. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5817. @State isSearchMode: boolean = false
  5818. @State searchHistoryItems: string[] = []
  5819. private readonly searchHistoryScope: string = 'local_music'
  5820. private loadSearchHistory(): void {
  5821. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope)
  5822. }
  5823. private saveSearchHistory(keyword: string): void {
  5824. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword)
  5825. }
  5826. private commitSearchHistory(keyword: string): void {
  5827. const normalized = keyword.trim()
  5828. if (normalized.length === 0) {
  5829. return
  5830. }
  5831. this.saveSearchHistory(normalized)
  5832. }
  5833. private applySearchHistory(keyword: string): void {
  5834. this.searchText = keyword
  5835. this.searchController.stopEditing()
  5836. void this.onSearchInput(keyword)
  5837. }
  5838. // 实时搜索逻辑(带防抖)
  5839. private async onSearchInput(value: string): Promise<void> {
  5840. this.searchText = value.trim();
  5841. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5842. // 歌单模式不走媒体库分页查询,直接在当前歌单中筛选,避免混入非歌单歌曲并打乱顺序。
  5843. if (this.modeType === 4) {
  5844. if (this.searchText === '') {
  5845. this.loadSearchHistory()
  5846. this.filteredList = []
  5847. this.updateListData(this.currentSongList, true, true)
  5848. Logger.info('heanup LocalMusic', `onSearchInput: restore playlist list, count=${this.currentSongList.length}`)
  5849. return
  5850. }
  5851. if (!this.isSearchMode) {
  5852. this.isSearchMode = true
  5853. }
  5854. const filteredSongs = filterPlaylistSongsByKeyword(this.currentSongList, this.searchText)
  5855. this.filteredList = filteredSongs
  5856. this.updateListData(filteredSongs, true, true)
  5857. Logger.info('heanup LocalMusic', `onSearchInput: playlist filter applied, keyword="${this.searchText}", count=${filteredSongs.length}`)
  5858. return
  5859. }
  5860. // 清空搜索文本时保持搜索态,只重置为不带关键词的结果列表
  5861. if (this.searchText === '') {
  5862. this.loadSearchHistory()
  5863. await this.resetAndLoadFirstPage();
  5864. return;
  5865. }
  5866. // 进入搜索模式
  5867. if (!this.isSearchMode) {
  5868. this.isSearchMode = true;
  5869. }
  5870. // 使用数据库分页查询(带搜索条件)
  5871. await this.resetAndLoadFirstPage();
  5872. }
  5873. @Builder
  5874. private SearchHistoryView(): void {
  5875. Column({ space: 10 }) {
  5876. Row() {
  5877. Text('搜索历史')
  5878. .fontSize(14)
  5879. .fontWeight(FontWeight.Medium)
  5880. .fontColor($r('app.color.text_color'))
  5881. Blank()
  5882. Button('清空')
  5883. .fontSize(12)
  5884. .fontColor(this.themeColor)
  5885. .backgroundColor(Color.Transparent)
  5886. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  5887. .onClick(() => {
  5888. SearchHistoryUtil.clear(this.searchHistoryScope)
  5889. this.searchHistoryItems = []
  5890. })
  5891. }
  5892. .width('100%')
  5893. Flex({ wrap: FlexWrap.Wrap }) {
  5894. ForEach(this.searchHistoryItems, (keyword: string) => {
  5895. Button(keyword)
  5896. .fontSize(12)
  5897. .fontColor($r('app.color.text_color'))
  5898. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  5899. .borderRadius(16)
  5900. .margin({ right: 8, bottom: 8 })
  5901. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  5902. .onClick(() => {
  5903. this.applySearchHistory(keyword)
  5904. })
  5905. })
  5906. }
  5907. .width('100%')
  5908. }
  5909. .width('100%')
  5910. .padding({ left: 16, right: 16, top: 10, bottom: 10 })
  5911. }
  5912. @State dragItem: number = -1
  5913. @State scaleItem: number = -1
  5914. @State neighborItem: number = -1
  5915. @State neighborScale: number = -1
  5916. @State offsetY: number = 0
  5917. private dragRefOffset: number = 0
  5918. private ITEM_INTV: number = 78
  5919. scaleSelect(item: number): number {
  5920. if (this.scaleItem === item) {
  5921. return 1.05
  5922. } else if (this.neighborItem === item) {
  5923. return this.neighborScale
  5924. } else {
  5925. return 1
  5926. }
  5927. }
  5928. itemMove(index: number, newIndex: number): void {
  5929. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5930. return;
  5931. }
  5932. let tmp = this.videoLocalList.splice(index, 1);
  5933. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5934. this.dataSource.pushArrayData(this.videoLocalList)
  5935. if(this.modeType==4&&this.playlistTable){
  5936. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5937. }
  5938. }
  5939. //瀑布流布局 支持双指缩放
  5940. @State columns: number = 2;
  5941. @State waterFlowScale: number = 1;
  5942. @State imageScale: number = 1;
  5943. @State waterFlowOpacity: number = 1;
  5944. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5945. private columnChanged: boolean = false;
  5946. private oldColumn: number = this.columns;
  5947. private pinchTime: number = 0;
  5948. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5949. changeColumns(scale: number): void {
  5950. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5951. this.columns--;
  5952. this.columnChanged = true;
  5953. } else if (scale < 1 && this.columns < 4) {
  5954. this.columns++;
  5955. this.columnChanged = true;
  5956. }
  5957. }
  5958. @Builder
  5959. getWaterView(){
  5960. Scroll(this.scroller) {
  5961. Column() {
  5962. Blank().height(this.topSafeHeight + 55)
  5963. WaterFlow({
  5964. scroller:this.waterScroller,
  5965. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5966. }) {
  5967. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5968. FlowItem() {
  5969. this.MusicWaterCardItem(item,index)
  5970. }
  5971. .width('100%')
  5972. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5973. .bindContextMenu(this.ContextMenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5974. {
  5975. preview: MenuPreviewMode.IMAGE
  5976. })
  5977. .bindContextMenu(this.ContextMenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5978. {
  5979. preview: MenuPreviewMode.IMAGE
  5980. })
  5981. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5982. }
  5983. // .columnsTemplate('repeat(auto-fit, 160)')
  5984. .id('waterflow') // 设置id用于截图
  5985. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5986. .columnsGap(12) // 列间距
  5987. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5988. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5989. // .padding({bottom:this.bottomBarHeight+10})
  5990. .scrollBar(BarState.Off)
  5991. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5992. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5993. .edgeEffect(EdgeEffect.None)
  5994. .width('90%')
  5995. .height('100%')
  5996. .opacity(this.waterFlowOpacity)
  5997. .scale({
  5998. x: this.waterFlowScale,
  5999. y: this.waterFlowScale,
  6000. centerX: 0,
  6001. centerY: 0
  6002. })
  6003. .onReachEnd(() => {
  6004. if(this.modeType === 4 )
  6005. return;
  6006. // 触底加载下一页
  6007. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6008. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6009. return;
  6010. }
  6011. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6012. this.scheduleLoadNextPage();
  6013. }
  6014. })
  6015. .onAppear(() => {
  6016. this.scroller.scrollEdge(Edge.Top)
  6017. })
  6018. .nestedScroll({
  6019. scrollForward: NestedScrollMode.PARENT_FIRST,
  6020. scrollBackward: NestedScrollMode.SELF_FIRST
  6021. })
  6022. .priorityGesture(
  6023. PinchGesture()
  6024. .onActionStart((event: GestureEvent) => {
  6025. // 双指捏合手势识别成功时截图
  6026. this.pinchTime = event.timestamp;
  6027. this.columnChanged = false;
  6028. this.oldColumn = this.columns;
  6029. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  6030. if (error) {
  6031. console.info('error:' + JSON.stringify(error));
  6032. return;
  6033. }
  6034. this.waterFlowSnapshot = pixmap;
  6035. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  6036. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  6037. if (this.oldColumn ===4) {
  6038. this.twoFingerType =3
  6039. this.isGridMusic = true
  6040. }else if (this.oldColumn ===1) {
  6041. this.twoFingerType =1
  6042. this.isGridMusic = false
  6043. }
  6044. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6045. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6046. return;
  6047. }
  6048. })
  6049. })
  6050. .onActionUpdate((event: GestureEvent) => {
  6051. // 手势更新:处理缩放逻辑和视觉效果
  6052. // 边界限制:防止超出列数范围时继续缩放
  6053. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  6054. return;
  6055. }
  6056. // 节流处理:避免过于频繁的更新,提升性能
  6057. if (event.timestamp - this.pinchTime < 10000000) {
  6058. return;
  6059. }
  6060. this.pinchTime = event.timestamp;
  6061. this.waterFlowScale = event.scale;
  6062. this.imageScale = event.scale;
  6063. // 根据缩放比例设置WaterFlow透明度
  6064. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  6065. this.waterFlowOpacity *= 3;
  6066. if (!this.columnChanged) {
  6067. this.changeColumns(event.scale);
  6068. }
  6069. // 列数改变后的缩放比例调整:避免出现空白区域
  6070. if (this.columnChanged) {
  6071. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  6072. // 限制缩放范围,确保视觉效果自然
  6073. if (event.scale < 1) {
  6074. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  6075. } else {
  6076. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  6077. }
  6078. }
  6079. })
  6080. .onActionEnd((event: GestureEvent) => {
  6081. // 手势结束:执行归位动画并保存状态
  6082. // 执行归位动画:平滑过渡到正常状态
  6083. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  6084. this.waterFlowScale = 1;
  6085. this.waterFlowOpacity = 1;
  6086. })
  6087. // 持久化保存当前列数:下次启动时恢复
  6088. PreferencesUtil.putSync('lastColumns', this.columns);
  6089. })
  6090. )
  6091. .onScrollFrameBegin((offset: number) => {
  6092. this.markGridWaterScrollingActive()
  6093. // 获取当前滚动偏移量
  6094. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  6095. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  6096. this.updateTitleBarByScrollOffset(currentOffsetY)
  6097. return { offsetRemain: offset };
  6098. })
  6099. }
  6100. }
  6101. .scrollBar(BarState.Off)
  6102. }
  6103. //瀑布流卡片布局
  6104. @Builder
  6105. private MusicWaterCardItem(item: VideoItem, index: number) {
  6106. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6107. Stack() {
  6108. Column() {
  6109. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  6110. .backgroundImageSize(ImageSize.Auto)
  6111. .borderRadius({
  6112. topLeft: 12,
  6113. topRight : 12,
  6114. bottomLeft: 0,
  6115. bottomRight: 0
  6116. })
  6117. .draggable(false)// 禁止长按手势拖动
  6118. .autoResize(true) // 重采样,可减少内存占用
  6119. .sourceSize({
  6120. width: this.getCoverThumbTargetSize(true),
  6121. height: this.getCoverThumbTargetSize(true)
  6122. })
  6123. .width('100%')
  6124. .height('auto')
  6125. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6126. .objectFit(ImageFit.Cover)
  6127. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6128. height: '99%' ,
  6129. dragBar: true,
  6130. onDisappear: () => {
  6131. this.longItemFilePath = '';
  6132. this.tempLyricContent = ''
  6133. },
  6134. showClose: true,
  6135. preferType: SheetType.CENTER ,
  6136. title: { title: '编辑标签' }
  6137. })
  6138. .draggable(false)
  6139. .opacity(this.opacityItem)// 绑定透明度
  6140. .margin({
  6141. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6142. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6143. })
  6144. Column() {
  6145. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6146. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  6147. .maxLines(1)
  6148. .fontWeight(FontWeight.Bold)
  6149. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6150. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6151. height: '95%',
  6152. dragBar: true,
  6153. showClose: true,
  6154. onDisappear: () => {
  6155. this.longItemFilePathDetail = '';
  6156. },
  6157. blurStyle:BlurStyle.Thin,
  6158. backgroundColor:Color.Transparent,
  6159. preferType: SheetType.CENTER ,
  6160. title: { title: '详情' }
  6161. })
  6162. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6163. $r('app.color.text_color'))
  6164. Column() {
  6165. Text(`${this.getArtistSongCount(item.name)}首`)
  6166. .fontSize(11)
  6167. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6168. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6169. .fontColor($r('app.color.text_color'))
  6170. Text(`${this.getAlbumSongCount(item.name)}首`)
  6171. .fontSize(11)
  6172. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6173. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6174. .fontColor($r('app.color.text_color'))
  6175. Row(){
  6176. Column(){
  6177. Text(item.md5Str?.includes('Lossless')?
  6178. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6179. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  6180. .padding({ top: 3,right:6,left:6,bottom:3 })
  6181. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6182. $r('app.color.text_color'))
  6183. .fontWeight(500)
  6184. .borderRadius(12)
  6185. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6186. .backgroundColor('#FFC107')
  6187. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6188. }
  6189. .margin({ top: 2 ,right:6})
  6190. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6191. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6192. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6193. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  6194. .maxLines(1)
  6195. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  6196. .margin({ top: 2})
  6197. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6198. || item.type == CommonConstants.TYPE_IS_ALBUM
  6199. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6200. .fontWeight(FontWeight.Medium)
  6201. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6202. $r('app.color.text_color'))
  6203. }
  6204. }
  6205. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6206. }
  6207. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  6208. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  6209. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  6210. .width('100%')
  6211. .justifyContent(FlexAlign.Center)
  6212. .margin({
  6213. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6214. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6215. })
  6216. }
  6217. .width('100%')
  6218. .borderRadius(12)
  6219. .backgroundColor($r('app.color.com_bg'))
  6220. Checkbox({ name: 'checkbox' + index })
  6221. .select(this.isLocalItemSelected(item))
  6222. .selectedColor(this.themeColor)
  6223. .shape(CheckBoxShape.CIRCLE)
  6224. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6225. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6226. Visibility.None)
  6227. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6228. .margin({ left: 20, top: 8, bottom: 8 })
  6229. .width(38)
  6230. .height(38)
  6231. }
  6232. }
  6233. .backgroundColor(Color.Transparent)
  6234. .width('100%')
  6235. .height('auto')
  6236. .padding({top:2})
  6237. .shadow({
  6238. radius: this.isScrolling ? 0 : 8,
  6239. type: ShadowType.BLUR,
  6240. color: 'on_primary'
  6241. })
  6242. .reuseId('card_item')
  6243. .onTouch((event: TouchEvent) => {
  6244. this.handlePointLightTouch(this.getPointLightItemKey('water_music', item, index), event)
  6245. })
  6246. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6247. ? new hdsEffect.HdsEffectBuilder()
  6248. .pointLight({
  6249. options: this.getPointLightOptions(this.getPointLightItemKey('water_music', item, index)),
  6250. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6251. })
  6252. .buildEffect()
  6253. : undefined)
  6254. .onClick(() => {
  6255. if (this.isMultiSelect) {
  6256. if (this.isSelectableLocalItem(item)) {
  6257. const isChecked = this.isLocalItemSelected(item);
  6258. this.handleFileSelection(item, !isChecked);
  6259. }
  6260. return
  6261. }
  6262. this.doPlay(item, index)
  6263. })
  6264. }
  6265. // Grid布局的开始
  6266. private dragRefOffSetX: number = 0;
  6267. private dragRefOffSetY: number = 0;
  6268. private FIX_VP_X: number = 180;
  6269. private FIX_VP_Y: number = 84;
  6270. isDraggable(index: number): boolean {
  6271. return index >= 0;
  6272. }
  6273. getRowEnd(item: number) {
  6274. if (item.toString() === '0') {
  6275. return 1;
  6276. } else {
  6277. return 0;
  6278. }
  6279. }
  6280. isInLeft(index: number) {
  6281. return index % 2 == 0;
  6282. }
  6283. down(index: number): void {
  6284. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  6285. return;
  6286. }
  6287. this.offsetY -= this.FIX_VP_Y;
  6288. this.dragRefOffSetY += this.FIX_VP_Y;
  6289. this.itemMove(index, index + 1);
  6290. }
  6291. up(index: number): void {
  6292. if (!this.isDraggable(index - 2)) {
  6293. return;
  6294. }
  6295. this.offsetY += this.FIX_VP_Y;
  6296. this.dragRefOffSetY -= this.FIX_VP_Y;
  6297. this.itemMove(index, index - 1);
  6298. }
  6299. left(index: number): void {
  6300. if (this.isInLeft(index)) {
  6301. return;
  6302. }
  6303. if (!this.isDraggable(index - 1)) {
  6304. return;
  6305. }
  6306. this.offsetX += this.FIX_VP_X;
  6307. this.dragRefOffSetX -= this.FIX_VP_X;
  6308. this.itemMove(index, index - 1)
  6309. }
  6310. right(index: number): void {
  6311. if (!this.isInLeft(index)) {
  6312. return;
  6313. }
  6314. if (!this.isDraggable(index + 1)) {
  6315. return;
  6316. }
  6317. this.offsetX -= this.FIX_VP_X;
  6318. this.dragRefOffSetX += this.FIX_VP_X;
  6319. this.itemMove(index, index + 1)
  6320. }
  6321. private scroller: Scroller = new Scroller();
  6322. private waterScroller: Scroller = new Scroller();
  6323. private startIndex: number = 0
  6324. private endIndex: number = 0
  6325. @State scaleValue: number = 1
  6326. @State pinchValue: number = 1
  6327. layoutOptionsForHeader: GridLayoutOptions = {
  6328. regularSize: [1, 1], // 只支持[1, 1]
  6329. irregularIndexes: [0], // 索引为0的GridItem占用一行
  6330. };
  6331. @Builder
  6332. getGridView() {
  6333. Grid(this.scroller, this.layoutOptionsForHeader) {
  6334. GridItem() {
  6335. Column(){
  6336. Blank().height(this.topSafeHeight + 45)
  6337. }
  6338. }
  6339. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6340. GridItem() {
  6341. Stack() {
  6342. this.MusicItemGrid(item, index)
  6343. }
  6344. }
  6345. .bindContextMenu(this.ContextMenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  6346. {
  6347. preview: MenuPreviewMode.IMAGE
  6348. })
  6349. .bindContextMenu(this.ContextMenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  6350. {
  6351. preview: MenuPreviewMode.IMAGE
  6352. })
  6353. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  6354. // TransitionEffect.scale({ x: 0, y: 0 })))
  6355. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6356. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  6357. .zIndex(this.dragItem === index ? 1 : 0)
  6358. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  6359. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6360. }
  6361. .width('94%')
  6362. .height('100%')
  6363. .editMode(true)
  6364. .padding({bottom:this.bottomSafeHeight+10})
  6365. .reuseId('grid_item')
  6366. .layoutWeight(1)
  6367. .scrollBar(BarState.Off)
  6368. .supportAnimation(false)
  6369. .onReachEnd(() => {
  6370. if(this.modeType === 4 )
  6371. return;
  6372. // 触底加载下一页
  6373. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6374. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6375. return;
  6376. }
  6377. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6378. this.scheduleLoadNextPage();
  6379. }
  6380. })
  6381. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  6382. .columnsTemplate(
  6383. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  6384. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  6385. )
  6386. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  6387. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  6388. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6389. .gesture(PinchGesture({ fingers: 2 })
  6390. .onActionEnd((event: GestureEvent) => {
  6391. this.setGridTwoFingers()
  6392. })
  6393. .onActionUpdate(e => {
  6394. this.scaleValue = this.pinchValue * e.scale
  6395. })
  6396. .onActionStart(e => {
  6397. }))
  6398. .enableScrollInteraction(true)
  6399. .onScrollIndex((start: number, end: number) => {
  6400. this.startIndex = start
  6401. this.endIndex = end
  6402. this.gridVisibleStart = start
  6403. this.gridVisibleEnd = end
  6404. this.lastVisibleEndIndex = end
  6405. this.warmupGridWaterVisibleThumbs(start, end, false)
  6406. const now = Date.now()
  6407. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  6408. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  6409. this.gridScrollPagingCheckAt = now
  6410. this.gridScrollLastPagingEnd = end
  6411. this.tryTriggerLoadNextPageByScroll(end)
  6412. }
  6413. })
  6414. .onScrollFrameBegin((offset: number) => {
  6415. this.markGridWaterScrollingActive()
  6416. const currentOffsetY = this.scroller.currentOffset().yOffset;
  6417. this.updateTitleBarByScrollOffset(currentOffsetY)
  6418. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6419. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6420. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6421. if (this.isScrollHide) {
  6422. this.setBarHeightHide2(offset)
  6423. } else {
  6424. this.setBarHeightNormal()
  6425. }
  6426. } else {
  6427. this.setBarHeightHide(offset)
  6428. }
  6429. return { offsetRemain: offset };
  6430. })
  6431. }
  6432. @State targetFile: string = '';
  6433. setGridTwoFingers() {
  6434. this.pinchValue = this.scaleValue;
  6435. Logger.info('this.pinchValue = ' + this.pinchValue);
  6436. if (this.pinchValue >= 1) {
  6437. this.twoFingerType++
  6438. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6439. if(this.twoFingerType >= 4){
  6440. this.twoFingerType = 4//切换成瀑布流
  6441. this.columns = 4
  6442. }
  6443. } else {
  6444. this.twoFingerType--
  6445. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6446. if (this.twoFingerType < 1) {
  6447. this.twoFingerType = 3
  6448. this.isGridMusic = false
  6449. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6450. }
  6451. }
  6452. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6453. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6454. this.pinchValue = 1;
  6455. this.scaleValue = 1;
  6456. }
  6457. @State longItemFilePath: string = ''
  6458. @State tempLyricContent: string = ''
  6459. @State editingItem: VideoItem | null = null
  6460. @Builder
  6461. private MusicItemGrid(item: VideoItem, index: number) {
  6462. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6463. Stack() {
  6464. Column() {
  6465. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  6466. .height(this.getGridHeight())
  6467. .width(this.getGridWight())
  6468. .draggable(false)
  6469. .autoResize(true) // 重采样,可减少内存占用
  6470. .sourceSize({
  6471. width: this.getCoverThumbTargetSize(false),
  6472. height: this.getCoverThumbTargetSize(false)
  6473. })
  6474. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6475. .clip(true)
  6476. .borderRadius({
  6477. topLeft: 12,
  6478. topRight: 12,
  6479. bottomLeft: 0,
  6480. bottomRight: 0
  6481. })
  6482. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6483. height: '99%' ,
  6484. dragBar: true,
  6485. onDisappear: () => {
  6486. this.longItemFilePath = '';
  6487. this.tempLyricContent = ''
  6488. },
  6489. showClose: true,
  6490. preferType: SheetType.CENTER ,
  6491. title: { title: '编辑标签' }
  6492. })
  6493. .draggable(false)
  6494. .opacity(this.opacityItem)// 绑定透明度
  6495. .margin({
  6496. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6497. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6498. })
  6499. Column() {
  6500. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  6501. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6502. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  6503. .maxLines(1)
  6504. .fontWeight(FontWeight.Bold)
  6505. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6506. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6507. height: '100%',
  6508. dragBar: true,
  6509. showClose: true,
  6510. onDisappear: () => {
  6511. this.longItemFilePathDetail = '';
  6512. },
  6513. blurStyle:BlurStyle.Thin,
  6514. backgroundColor:Color.Transparent,
  6515. preferType: SheetType.CENTER ,
  6516. title: { title: '详情' }
  6517. })
  6518. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6519. $r('app.color.text_color'))
  6520. Column() {
  6521. Text(`${this.getArtistSongCount(item.name)}首`)
  6522. .fontSize(11)
  6523. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6524. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6525. .fontColor($r('app.color.text_color'))
  6526. Text(`${this.getAlbumSongCount(item.name)}首`)
  6527. .fontSize(11)
  6528. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6529. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6530. .fontColor($r('app.color.text_color'))
  6531. Row(){
  6532. Column(){
  6533. Text(item.md5Str?.includes('Lossless')?
  6534. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6535. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  6536. .padding({ top: 3,right:6,left:6,bottom:3 })
  6537. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6538. $r('app.color.text_color'))
  6539. .fontWeight(500)
  6540. .borderRadius(12)
  6541. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6542. .backgroundColor('#FFC107')
  6543. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6544. }
  6545. .margin({ top: 2 ,right:6})
  6546. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6547. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6548. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6549. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  6550. .maxLines(1)
  6551. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  6552. .margin({ top: 2})
  6553. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6554. || item.type == CommonConstants.TYPE_IS_ALBUM
  6555. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6556. .fontWeight(FontWeight.Medium)
  6557. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6558. $r('app.color.text_color'))
  6559. }
  6560. }
  6561. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6562. }
  6563. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  6564. .width(this.getGridWight())
  6565. .justifyContent(FlexAlign.Center)
  6566. .margin({
  6567. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6568. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6569. })
  6570. }
  6571. .width(this.getGridWight())
  6572. .borderRadius(12)
  6573. .backgroundColor($r('app.color.com_bg'))
  6574. Checkbox({ name: 'checkbox' + index })
  6575. .select(this.isLocalItemSelected(item))
  6576. .selectedColor(this.themeColor)
  6577. .shape(CheckBoxShape.CIRCLE)
  6578. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6579. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6580. Visibility.None)
  6581. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6582. .margin({ left: 20, top: 8, bottom: 8 })
  6583. .width(38)
  6584. .height(38)
  6585. }
  6586. }
  6587. .backgroundColor(Color.Transparent)
  6588. .width('100%')
  6589. .padding({ top: 15 })
  6590. .height(this.getGridAllHeight())
  6591. .onTouch((event: TouchEvent) => {
  6592. this.handlePointLightTouch(this.getPointLightItemKey('grid_music', item, index), event)
  6593. })
  6594. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6595. ? new hdsEffect.HdsEffectBuilder()
  6596. .pointLight({
  6597. options: this.getPointLightOptions(this.getPointLightItemKey('grid_music', item, index)),
  6598. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6599. })
  6600. .buildEffect()
  6601. : undefined)
  6602. .onClick(() => {
  6603. if (this.isMultiSelect) {
  6604. if (this.isSelectableLocalItem(item)) {
  6605. const isChecked = this.isLocalItemSelected(item);
  6606. this.handleFileSelection(item, !isChecked);
  6607. }
  6608. return
  6609. }
  6610. this.doPlay(item, index)
  6611. })
  6612. }
  6613. getGridAllHeight() {
  6614. let heightG = 222
  6615. switch (this.twoFingerType) {
  6616. case 1:
  6617. heightG = 143
  6618. break;
  6619. case 2:
  6620. heightG = 178
  6621. break;
  6622. case 3:
  6623. heightG = 222
  6624. break;
  6625. }
  6626. return heightG
  6627. }
  6628. getGridHeight() {
  6629. let heightG = 150
  6630. switch (this.twoFingerType) {
  6631. case 1:
  6632. heightG = 80
  6633. break;
  6634. case 2:
  6635. heightG = 110
  6636. break;
  6637. case 3:
  6638. heightG = 150
  6639. break;
  6640. }
  6641. return heightG
  6642. }
  6643. getGridWight() {
  6644. let wightG = 158
  6645. switch (this.twoFingerType) {
  6646. case 1:
  6647. wightG = 80
  6648. break;
  6649. case 2:
  6650. wightG = 110
  6651. break;
  6652. case 3:
  6653. wightG = 158
  6654. break;
  6655. }
  6656. return wightG
  6657. }
  6658. @State isShowDetail:boolean = false
  6659. @State longItemFilePathDetail:string =''
  6660. private canShowItemContextMenu(item: VideoItem): boolean {
  6661. return !(((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  6662. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6663. item.name === LocalMusic.STR_HISTORY_MUSIC))
  6664. }
  6665. @Builder
  6666. private LocalMusicMenuContent(item: VideoItem, index: number, filePath: string) {
  6667. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  6668. Menu() {
  6669. MenuItem({
  6670. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  6671. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  6672. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  6673. })
  6674. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6675. .onClick(() => {
  6676. if (item) {
  6677. this.doFav(item)
  6678. }
  6679. this.longItemFilePath = ''
  6680. })
  6681. MenuItem({
  6682. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  6683. content: '下一首播放'
  6684. })
  6685. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6686. .onClick(() => {
  6687. this.addToNextPlay(item);
  6688. this.longItemFilePath = ''
  6689. })
  6690. MenuItem({
  6691. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6692. content: '添加到歌单'
  6693. })
  6694. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6695. .onClick(async () => {
  6696. this.longItemFilePath = ''
  6697. await this.openAddToPlaylistDialog(item)
  6698. })
  6699. MenuItem({
  6700. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  6701. content: '编辑标签'
  6702. })
  6703. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  6704. height: '99%',
  6705. dragBar: true,
  6706. showClose: true,
  6707. preferType: SheetType.CENTER ,
  6708. title: { title: '编辑标签' }
  6709. })
  6710. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6711. .onClick(async() => {
  6712. this.initEditFields(item)
  6713. this.tempLyricContent = await this.getLyricContent(item);
  6714. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  6715. this.lyricConStr = this.tempLyricContent
  6716. }
  6717. if(this.isGridMusic||this.twoFingerType==4){
  6718. this.longItemFilePath = item.filePath
  6719. }else{
  6720. this.isShowEdit = !this.isShowEdit;
  6721. }
  6722. })
  6723. MenuItem({
  6724. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  6725. content: $r('app.string.select_all')
  6726. })
  6727. .onClick(() => {
  6728. this.longItemFilePath = ''
  6729. this.enterLocalMultiSelect(item)
  6730. })
  6731. MenuItem({
  6732. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6733. content: '提取ISO文件'
  6734. })
  6735. .visibility(this.isIsoLocalFile(item) ? Visibility.Visible : Visibility.None)
  6736. .onClick(async () => {
  6737. this.longItemFilePath = ''
  6738. await this.openIsoArchiveDialog(item)
  6739. })
  6740. MenuItem({
  6741. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  6742. content: $r('app.string.edit_audio')
  6743. })
  6744. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  6745. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6746. })
  6747. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6748. .onClick(() => {
  6749. this.isEditAudio = !this.isEditAudio
  6750. })
  6751. MenuItem({
  6752. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  6753. content: $r('app.string.extract_accompaniment')
  6754. })
  6755. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  6756. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6757. })
  6758. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6759. .onClick(() => {
  6760. if (!Utility.isNoble()) {
  6761. this.showVipDialog()
  6762. return
  6763. }
  6764. this.isExtractAcc = !this.isExtractAcc
  6765. })
  6766. MenuItem({
  6767. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  6768. content: $r('app.string.converter_audio')
  6769. })
  6770. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  6771. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6772. })
  6773. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6774. .onClick(() => {
  6775. if (!Utility.isNoble()) {
  6776. this.showVipDialog()
  6777. return
  6778. }
  6779. this.isConverter = !this.isConverter
  6780. })
  6781. // MenuItem({
  6782. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  6783. // content: $r('app.string.vocal_separation')
  6784. // })
  6785. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  6786. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6787. // })
  6788. // .onClick(() => {
  6789. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  6790. // })
  6791. MenuItem({
  6792. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  6793. content: $r('app.string.change_tone')
  6794. })
  6795. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  6796. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6797. })
  6798. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6799. .onClick(() => {
  6800. this.isChangeTone = !this.isChangeTone
  6801. })
  6802. if(Utility.isVideoByExtension(item.filePath)){
  6803. MenuItem({
  6804. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  6805. content: $r('app.string.extract_audio')
  6806. })
  6807. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  6808. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6809. })
  6810. .onClick(() => {
  6811. this.isExtractAudio = !this.isExtractAudio
  6812. })
  6813. }
  6814. MenuItem({
  6815. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  6816. content: $r('app.string.set_ring')
  6817. })
  6818. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6819. .onClick(async () => {
  6820. await PermissionUtil.activatePermission(item.filePath)
  6821. // if(item.filePath.includes(this.packName)){
  6822. setRingTone(this.context, item.filePath,item.name)
  6823. // }else{
  6824. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  6825. // }
  6826. this.longItemFilePath = ''
  6827. })
  6828. MenuItem({
  6829. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  6830. content: $r('app.string.rename')
  6831. })
  6832. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6833. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6834. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6835. .onClick(() => {
  6836. this.showReNameDialog(item, index + '', filePath)
  6837. this.longItemFilePath = ''
  6838. })
  6839. MenuItem({
  6840. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  6841. content: $r('app.string.delete')
  6842. })
  6843. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6844. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6845. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6846. .onClick(() => {
  6847. this.selectSingleItemForDelete(item)
  6848. this.showWarnIsDelete()
  6849. this.longItemFilePath = ''
  6850. })
  6851. MenuItem({
  6852. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6853. content: $r('app.string.detail')
  6854. })
  6855. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6856. height:'100%',
  6857. dragBar: true,
  6858. showClose: true,
  6859. blurStyle:BlurStyle.Thin,
  6860. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6861. backgroundColor:Color.Transparent,
  6862. title: { title: '详情信息' }
  6863. })
  6864. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6865. .onClick(() => {
  6866. if(this.isGridMusic||this.twoFingerType==4){
  6867. this.longItemFilePathDetail = item.filePath
  6868. }else{
  6869. this.isShowDetail = !this.isShowDetail
  6870. }
  6871. })
  6872. MenuItem({
  6873. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6874. content: $r('app.string.share')
  6875. })
  6876. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6877. .onClick(() => {
  6878. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6879. this.longItemFilePath = ''
  6880. })
  6881. }
  6882. .font({ size: 14, weight: FontWeight.Normal })
  6883. }
  6884. .width(180)
  6885. }
  6886. @Builder
  6887. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  6888. if (this.canShowItemContextMenu(item)) {
  6889. if (shouldWrapLocalMusicMenuInScroll(false)) {
  6890. Scroll() {
  6891. this.LocalMusicMenuContent(item, index, filePath)
  6892. }
  6893. .height('auto')
  6894. .enableScrollInteraction(true)
  6895. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6896. } else {
  6897. this.LocalMusicMenuContent(item, index, filePath)
  6898. }
  6899. }
  6900. }
  6901. @Builder
  6902. ContextMenuBuilder(item: VideoItem, index: number, filePath: string) {
  6903. if (this.canShowItemContextMenu(item)) {
  6904. if (shouldWrapLocalMusicMenuInScroll(true)) {
  6905. Scroll() {
  6906. this.LocalMusicMenuContent(item, index, filePath)
  6907. }
  6908. .height('auto')
  6909. .enableScrollInteraction(true)
  6910. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6911. } else {
  6912. this.LocalMusicMenuContent(item, index, filePath)
  6913. }
  6914. }
  6915. }
  6916. private listMaxScrollOffsetY: number = 0
  6917. private selectedIndex: number = -1
  6918. setlistTwoFingers() {
  6919. this.pinchValue = this.scaleValue;
  6920. Logger.info('this.pinchValue = ' + this.pinchValue);
  6921. if (this.pinchValue >= 1) {
  6922. this.twoFingerType++
  6923. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6924. if (this.twoFingerType > 3) {
  6925. this.twoFingerType = 1
  6926. this.isGridMusic = true
  6927. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6928. }
  6929. } else {
  6930. this.twoFingerType--
  6931. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6932. if (this.twoFingerType < 1) {
  6933. this.twoFingerType = 4
  6934. this.columns = 1
  6935. }
  6936. }
  6937. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6938. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6939. this.pinchValue = 1;
  6940. this.scaleValue = 1;
  6941. }
  6942. @Builder
  6943. getList(){
  6944. Stack() {
  6945. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6946. this.getListView()
  6947. }
  6948. .pullDownRatio(this.ratioL)
  6949. .pullToRefresh(true)
  6950. .refreshOffset(0)
  6951. .onOffsetChange((offset: number) => {
  6952. // 越接近最大距离,下拉跟手系数越小。
  6953. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6954. })
  6955. .onStateChange((refreshStatus: RefreshStatus) => {
  6956. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6957. })
  6958. .onRefreshing(async () => {
  6959. if(this.modeType==0){
  6960. this.getHistoryList(false)
  6961. this.asyncCurrentPathOnlyFile()
  6962. }else if(this.modeType == 1){
  6963. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6964. }else if(this.modeType == 2){
  6965. workerInstance.postMessage({ code: 3, data: this.context });
  6966. }else if(this.modeType == 3){
  6967. workerInstance.postMessage({ code: 4, data: this.context });
  6968. }else if(this.modeType == 4){
  6969. this.doSongListTask()
  6970. }
  6971. console.log('onRefreshing test');
  6972. })
  6973. if (this.isLoadingPage) {
  6974. Row() {
  6975. LoadingProgress()
  6976. .width(24)
  6977. .height(24)
  6978. .color(this.themeColor)
  6979. Text('加载中...')
  6980. .margin({ left: 8 })
  6981. .fontSize(13)
  6982. .fontColor($r('app.color.text_color'))
  6983. }
  6984. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6985. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6986. .borderRadius(16)
  6987. .align(Alignment.Bottom)
  6988. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6989. }
  6990. }
  6991. }
  6992. // 扫描当前目录下的文件,不扫描子目录
  6993. asyncCurrentPathOnlyFile(){
  6994. if(this.modeType==0){
  6995. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6996. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6997. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6998. if(this.modeType==0){
  6999. setTimeout(()=>{
  7000. this.isRefreshing =false
  7001. this.deleteCache(this.currentPath)
  7002. this.getSortedFiles(this.currentPath)
  7003. },500)
  7004. }
  7005. }).catch((e:object)=>{
  7006. this.isRefreshing =false
  7007. console.info("onecold task1 catch e: " + e);
  7008. })
  7009. }
  7010. }
  7011. @Builder
  7012. getListView() {
  7013. List({ scroller: this.listScroller }) {
  7014. // ListItemGroup({ header: this.coverHeader() }) {
  7015. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  7016. ListItem() {
  7017. Column() {
  7018. if (item.type === CommonConstants.TYPE_IS_DIR
  7019. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  7020. this.DirItem(item, index)
  7021. } else {
  7022. this.MusicItem(item, index)
  7023. }
  7024. }
  7025. }
  7026. .clickEffect({ level: ClickEffectLevel.LIGHT })
  7027. .swipeAction((
  7028. ((this.isSwipe && !this.isScrolling) &&
  7029. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  7030. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  7031. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  7032. edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  7033. .onClick(() => {
  7034. if (this.isMultiSelect) {
  7035. if (this.isSelectableLocalItem(item)) {
  7036. const isChecked = this.isLocalItemSelected(item);
  7037. this.handleFileSelection(item, !isChecked);
  7038. }
  7039. return
  7040. }
  7041. this.doPlay(item, index)
  7042. })
  7043. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  7044. }
  7045. .onScrollStart(() => {
  7046. this.isScrolling = true
  7047. this.listVisibleStart = -1
  7048. this.listVisibleEnd = -1
  7049. this.listScrollAlphaCheckAt = 0
  7050. this.listScrollPagingCheckAt = 0
  7051. this.listScrollLastAlphaStart = -1
  7052. this.listScrollLastPagingEnd = -1
  7053. if (this.alphaBetRebuildTimer) {
  7054. clearTimeout(this.alphaBetRebuildTimer)
  7055. this.alphaBetRebuildTimer = 0
  7056. }
  7057. this.showAlphabetIndex()
  7058. })
  7059. .onScrollIndex((start: number,center:number,end:number) => {
  7060. this.selectedIndex = start
  7061. this.listVisibleStart = start
  7062. this.listVisibleEnd = end
  7063. this.lastVisibleEndIndex = end
  7064. if (!this.isMediaLibraryWarmupWindow()) {
  7065. this.warmupListVisibleThumbs(start, end)
  7066. }
  7067. const now = Date.now()
  7068. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  7069. if (!this.isMediaLibraryWarmupWindow() &&
  7070. start >= 0 && start < this.videoLocalList.length &&
  7071. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  7072. this.listScrollAlphaCheckAt = now
  7073. this.listScrollLastAlphaStart = start
  7074. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  7075. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  7076. this.selectAlphaBetIndex = nextAlphaIndex
  7077. }
  7078. }
  7079. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  7080. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  7081. this.listScrollPagingCheckAt = now
  7082. this.listScrollLastPagingEnd = end
  7083. this.tryTriggerLoadNextPageByScroll(end)
  7084. }
  7085. })
  7086. .onScrollStop(() => {
  7087. if(this.isScrolling){
  7088. this.isScrolling = false
  7089. }
  7090. this.flushPendingCoverThumbRefresh()
  7091. if (this.alphaBetDirty) {
  7092. this.scheduleAlphaBetRebuild(0)
  7093. }
  7094. this.hideAlphabetIndexAfterDelay(1500)
  7095. })
  7096. .onReachEnd(() => {
  7097. if(this.modeType === 4 )//歌单不能加载下一页
  7098. return;
  7099. // 触底加载下一页
  7100. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  7101. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  7102. return;
  7103. }
  7104. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  7105. this.scheduleLoadNextPage();
  7106. }
  7107. })
  7108. .scrollBar(BarState.Off)
  7109. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  7110. .gesture(PinchGesture({ fingers: 2 })
  7111. .onActionEnd((event: GestureEvent) => {
  7112. this.setlistTwoFingers()
  7113. })
  7114. .onActionUpdate(e => {
  7115. this.scaleValue = this.pinchValue * e.scale
  7116. })
  7117. .onActionStart(e => {
  7118. }))
  7119. .contentStartOffset(this.topSafeHeight + 55)
  7120. .scrollBar(BarState.Off)
  7121. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  7122. .cachedCount(this.modeType == 1 ? 4 : 8)
  7123. // .reuseId('list_item')
  7124. .borderRadius(20)
  7125. .layoutWeight(1)
  7126. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  7127. .lanes(
  7128. new BreakpointType<number>({
  7129. sm: 1,
  7130. md: 2,
  7131. lg: 2,
  7132. xl: 3,
  7133. xxl: 4
  7134. }).getValue(this.currentBreakpoint),
  7135. new BreakpointType<number>({
  7136. sm: 0,
  7137. md: 12,
  7138. lg: 12,
  7139. xl: 16,
  7140. xxl: 20
  7141. }).getValue(this.currentBreakpoint)
  7142. )
  7143. .onAreaChange((oldValue: Area, newValue: Area) => {
  7144. this.listArea = newValue
  7145. if (this.twoFingerType == 3) {
  7146. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  7147. } else if (this.twoFingerType == 2) {
  7148. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  7149. } else if (this.twoFingerType == 1) {
  7150. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  7151. }
  7152. })
  7153. .onScrollFrameBegin((offset: number) => {
  7154. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  7155. this.updateTitleBarByScrollOffset(currentOffsetY)
  7156. return { offsetRemain: offset };
  7157. })
  7158. }
  7159. setBarHeightNormal() {
  7160. this.hideDone = false;
  7161. this.getUIContext().animateTo({
  7162. duration: 300
  7163. }, () => {
  7164. this.bottomBarHeight = 68 + 0;
  7165. this.topBarHeight = 50 + 0;
  7166. this.barOpacity = 1;
  7167. this.barBottomOpacity = 1
  7168. this.currentYOffset = 0;
  7169. this.isHiding = false;
  7170. });
  7171. }
  7172. setBarHeightHide(offset: number) {
  7173. if (offset > 0 && !this.hideDone) {
  7174. this.currentYOffset += offset;
  7175. if (this.currentYOffset <= 100) {
  7176. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  7177. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7178. this.barOpacity = 1 - this.currentYOffset / 100;
  7179. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  7180. } else {
  7181. this.topBarHeight = 0;
  7182. this.bottomBarHeight = 0;
  7183. this.barBottomOpacity = 0
  7184. this.barOpacity = 0;
  7185. this.hideDone = true;
  7186. }
  7187. this.isHiding = true;
  7188. }
  7189. if (offset < 0 && this.isHiding) {
  7190. this.hideDone = false;
  7191. this.getUIContext().animateTo({
  7192. duration: 300
  7193. }, () => {
  7194. this.bottomBarHeight = 68 + 0;
  7195. this.topBarHeight = 50 + 0;
  7196. this.barOpacity = 1;
  7197. this.barBottomOpacity = 1
  7198. this.currentYOffset = 0;
  7199. this.isHiding = false;
  7200. });
  7201. }
  7202. }
  7203. //这个方法没隐藏bottomBar,只隐藏topbar
  7204. setBarHeightHide2(offset: number) {
  7205. if (offset > 0 && !this.hideDone) {
  7206. this.currentYOffset += offset;
  7207. if (this.currentYOffset <= 100) {
  7208. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7209. this.barOpacity = 1 - this.currentYOffset / 100;
  7210. } else {
  7211. this.topBarHeight = 0;
  7212. this.barOpacity = 0;
  7213. this.hideDone = true;
  7214. }
  7215. this.isHiding = true;
  7216. }
  7217. if (offset < 0 && this.isHiding) {
  7218. this.hideDone = false;
  7219. this.getUIContext().animateTo({
  7220. duration: 300
  7221. }, () => {
  7222. this.topBarHeight = 50 + 0;
  7223. this.barOpacity = 1;
  7224. this.currentYOffset = 0;
  7225. this.isHiding = false;
  7226. });
  7227. }
  7228. }
  7229. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  7230. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  7231. switch (item.type) {
  7232. case CommonConstants.TYPE_IS_DIR:
  7233. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  7234. let shouldScrollTopNow = true
  7235. let offsetB = 0
  7236. if(this.twoFingerType==4){
  7237. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7238. let cur = this.waterScroller.currentOffset()
  7239. if (cur && typeof cur.yOffset === 'number') {
  7240. offsetB = cur.yOffset
  7241. }
  7242. }
  7243. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  7244. }else
  7245. if (this.isGridMusic) {
  7246. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7247. let cur = this.scroller.currentOffset()
  7248. if (cur && typeof cur.yOffset === 'number') {
  7249. offsetB = cur.yOffset
  7250. }
  7251. }
  7252. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  7253. } else {
  7254. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7255. let cur = this.listScroller.currentOffset()
  7256. if (cur && typeof cur.yOffset === 'number') {
  7257. offsetB = cur.yOffset
  7258. }
  7259. }
  7260. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  7261. }
  7262. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  7263. this.showVerifyDialog()
  7264. this.currentTitleName = '私密音频'
  7265. this.currentTitleCover = $r('app.media.alt')
  7266. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  7267. this.titleName = '最近播放'
  7268. this.currentTitleCover = $r('app.media.alt')
  7269. this.currentTitleName = '最近播放'
  7270. //加载动画效果
  7271. this.updateListData(this.historyList, true)
  7272. // this.videoLocalList = this.historyList
  7273. if (ArrayUtil.isEmpty(this.historyList)) {
  7274. ToastUtil.showToast('最近播放记录空空如也')
  7275. } else {
  7276. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  7277. }
  7278. this.isHistory = true
  7279. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  7280. this.titleName = '我的收藏'
  7281. this.currentTitleName = '我的收藏'
  7282. this.currentTitleCover = $r('app.media.alt')
  7283. //加载动画效果
  7284. this.updateListData(this.favList, true)
  7285. if (ArrayUtil.isEmpty(this.favList)) {
  7286. ToastUtil.showToast('无音乐收藏记录')
  7287. } else {
  7288. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  7289. }
  7290. this.isFavMusic = true
  7291. } else {
  7292. this.currentTitleName = item.name
  7293. this.currentPath = item.filePath
  7294. this.currentTitleCover = $r('app.media.alt')
  7295. shouldScrollTopNow = false
  7296. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  7297. }
  7298. //进入歌单的时候的滚动位置在顶部
  7299. if (shouldScrollTopNow) {
  7300. if(this.twoFingerType==4){
  7301. setTimeout(() => {
  7302. this.waterScroller.scrollEdge(Edge.Top)
  7303. this.scroller.scrollEdge(Edge.Top)
  7304. }, 200)
  7305. }else{
  7306. if (this.isGridMusic) {
  7307. this.scroller.scrollToIndex(0,false)
  7308. }else{
  7309. this.listScroller.scrollToIndex(0,false)
  7310. }
  7311. }
  7312. }
  7313. this.rightTopImage = $r('sys.symbol.chevron_left')
  7314. break;
  7315. case CommonConstants.TYPE_IS_ARTIST:
  7316. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  7317. let offsetA = 0
  7318. if(this.twoFingerType==4){
  7319. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7320. let cur = this.waterScroller.currentOffset()
  7321. if (cur && typeof cur.yOffset === 'number') {
  7322. offsetA = cur.yOffset
  7323. }
  7324. }
  7325. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  7326. }else
  7327. if (this.isGridMusic) {
  7328. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7329. let cur = this.scroller.currentOffset()
  7330. if (cur && typeof cur.yOffset === 'number') {
  7331. offsetA = cur.yOffset
  7332. }
  7333. }
  7334. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  7335. } else {
  7336. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7337. let cur = this.listScroller.currentOffset()
  7338. if (cur && typeof cur.yOffset === 'number') {
  7339. offsetA = cur.yOffset
  7340. }
  7341. }
  7342. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  7343. }
  7344. // 进入艺术家详情页前,先加载详情页的排序类型
  7345. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7346. const artistOriginalIsCanBack = this.isCanBack;
  7347. this.isCanBack = true;
  7348. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  7349. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  7350. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  7351. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7352. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  7353. let mList = this.artistMap.get(artistCacheKey)
  7354. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  7355. // 使用详情页的排序类型查询
  7356. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  7357. if (ArrayUtil.isNotEmpty(mList)) {
  7358. this.artistMap.set(artistCacheKey, mList);
  7359. }
  7360. }
  7361. // 设置当前排序类型为详情页排序
  7362. this.sortType = artistDetailSortType;
  7363. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  7364. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  7365. const nextArtistCountMap = new Map(this.artistSongCountMap);
  7366. nextArtistCountMap.set(item.name, mList.length);
  7367. this.artistSongCountMap = nextArtistCountMap;
  7368. this.isCanBack = true
  7369. this.hasMoreData = false
  7370. this.isLoadingPage = false
  7371. this.pageCache.clear()
  7372. this.pageHasMoreCache.clear()
  7373. this.pageTotalCountCache.clear()
  7374. this.prefetchingPages.clear()
  7375. this.lastScrollTriggerPage = -1
  7376. this.lastVisibleEndIndex = -1
  7377. this.isPagingTransition = false
  7378. if (this.pagingScheduleTimer) {
  7379. clearTimeout(this.pagingScheduleTimer)
  7380. this.pagingScheduleTimer = 0
  7381. }
  7382. this.totalCount = mList.length
  7383. this.titleName = item.name
  7384. this.currentTitleName = '艺术家:' + item.name
  7385. if (item.pixelMapPath) {
  7386. this.currentTitleCover = item.pixelMapPath
  7387. }
  7388. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7389. } else {
  7390. ToastUtil.showToast('未找到该艺术家的歌曲');
  7391. return;
  7392. }
  7393. this.rightTopImage = $r('sys.symbol.chevron_left')
  7394. //进入歌单的时候的滚动位置在顶部
  7395. if(this.twoFingerType==4){
  7396. setTimeout(() => {
  7397. this.waterScroller.scrollEdge(Edge.Top)
  7398. this.scroller.scrollEdge(Edge.Top)
  7399. }, 380)
  7400. }else{
  7401. if (this.isGridMusic) {
  7402. this.scroller.scrollEdge(Edge.Top)
  7403. }else{
  7404. this.listScroller.scrollEdge(Edge.Top)
  7405. }
  7406. }
  7407. break;
  7408. case CommonConstants.TYPE_IS_ALBUM:
  7409. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  7410. let offset = 0
  7411. if(this.twoFingerType==4){
  7412. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7413. let cur = this.waterScroller.currentOffset()
  7414. if (cur && typeof cur.yOffset === 'number') {
  7415. offset = cur.yOffset
  7416. }
  7417. }
  7418. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  7419. }else
  7420. if (this.isGridMusic) {
  7421. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7422. let cur = this.scroller.currentOffset()
  7423. if (cur && typeof cur.yOffset === 'number') {
  7424. offset = cur.yOffset
  7425. }
  7426. }
  7427. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  7428. } else {
  7429. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7430. let cur = this.listScroller.currentOffset()
  7431. if (cur && typeof cur.yOffset === 'number') {
  7432. offset = cur.yOffset
  7433. }
  7434. }
  7435. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  7436. }
  7437. // 进入专辑详情页前,先加载详情页的排序类型
  7438. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7439. const albumOriginalIsCanBack = this.isCanBack;
  7440. this.isCanBack = true;
  7441. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  7442. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  7443. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  7444. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7445. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  7446. let albumList = this.albumMap.get(albumCacheKey)
  7447. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  7448. // 使用详情页的排序类型查询
  7449. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  7450. if (ArrayUtil.isNotEmpty(albumList)) {
  7451. this.albumMap.set(albumCacheKey, albumList);
  7452. }
  7453. }
  7454. // 设置当前排序类型为详情页排序
  7455. this.sortType = albumDetailSortType;
  7456. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  7457. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  7458. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  7459. nextAlbumCountMap.set(item.name, albumList.length);
  7460. this.albumSongCountMap = nextAlbumCountMap;
  7461. this.isCanBack = true
  7462. this.hasMoreData = false
  7463. this.isLoadingPage = false
  7464. this.pageCache.clear()
  7465. this.pageHasMoreCache.clear()
  7466. this.pageTotalCountCache.clear()
  7467. this.prefetchingPages.clear()
  7468. this.lastScrollTriggerPage = -1
  7469. this.lastVisibleEndIndex = -1
  7470. this.isPagingTransition = false
  7471. if (this.pagingScheduleTimer) {
  7472. clearTimeout(this.pagingScheduleTimer)
  7473. this.pagingScheduleTimer = 0
  7474. }
  7475. this.totalCount = albumList.length
  7476. this.titleName = item.name
  7477. this.currentTitleName = '专辑:' + item.name
  7478. if (item.pixelMapPath) {
  7479. this.currentTitleCover = item.pixelMapPath
  7480. }
  7481. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7482. this.mScrollMap.set(item.name, this.selectedIndex)
  7483. this.rightTopImage = $r('sys.symbol.chevron_left')
  7484. } else {
  7485. ToastUtil.showToast('未找到该专辑的歌曲');
  7486. return;
  7487. }
  7488. //进入歌单的时候的滚动位置在顶部
  7489. if(this.twoFingerType==4){
  7490. setTimeout(() => {
  7491. this.waterScroller.scrollEdge(Edge.Top)
  7492. this.scroller.scrollEdge(Edge.Top)
  7493. }, 380)
  7494. }else{
  7495. if (this.isGridMusic) {
  7496. this.scroller.scrollEdge(Edge.Top)
  7497. }else{
  7498. this.listScroller.scrollEdge(Edge.Top)
  7499. }
  7500. }
  7501. break;
  7502. case CommonConstants.TYPE_IS_CSJAD:
  7503. return
  7504. break;
  7505. case CommonConstants.TYPE_LOCAL:
  7506. if (this.isIsoLocalFile(item)) {
  7507. await this.openIsoArchiveDialog(item)
  7508. return
  7509. }
  7510. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  7511. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  7512. const cueTracks:CueTrack[] = cueinfo.tracks
  7513. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  7514. if(ArrayUtil.isNotEmpty(cueTracks)){
  7515. this.showCueDialog(cueTracks,cueinfo)
  7516. }
  7517. // this.showCueSheet = !this.showCueSheet
  7518. return
  7519. }
  7520. console.info('kkMusic doPlay this.CONTROL_PlayStatus ='+this.CONTROL_PlayStatus )
  7521. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7522. console.info('kkMusic doPlay stop =' )
  7523. this.stop();
  7524. }
  7525. const useExistingQueueForPlayback = this.preserveExistingQueueOnNextPlay;
  7526. const nextQueueScope = this.nextPlayQueueScope;
  7527. this.preserveExistingQueueOnNextPlay = false;
  7528. this.nextPlayQueueScope = 'view';
  7529. if (isOpen) {
  7530. this.resetFindPagedLocalQueueState();
  7531. this.currentSong = item
  7532. if (index !== undefined) {
  7533. this.curIndex = index
  7534. }
  7535. this.songList = []
  7536. this.songList.push(item)
  7537. this.sonDataSource.pushArrayData(this.songList)
  7538. this.playQueueScope = 'single'
  7539. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  7540. this.currentSong = item
  7541. if (index !== undefined) {
  7542. this.curIndex = index
  7543. }
  7544. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  7545. if (this.isFindPagedLocalQueueActive()) {
  7546. // 这类队列来自发现页分页随机,点击播放列表里的歌也要继续保持“分页队列”身份。
  7547. this.playQueueScope = 'find_paged_local'
  7548. this.currentPlaylistSongFilePaths = [];
  7549. } else {
  7550. this.resetFindPagedLocalQueueState();
  7551. this.playQueueScope = 'playlist'
  7552. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7553. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7554. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7555. }
  7556. }
  7557. }else if (useExistingQueueForPlayback) {
  7558. // 特殊分页队列初始化时,直接复用 finishLoadingPlaylist 准备好的当前页,不再按视图重建全量队列。
  7559. this.currentSong = item
  7560. if (index !== undefined) {
  7561. this.curIndex = index
  7562. }
  7563. this.playQueueScope = nextQueueScope
  7564. this.currentPlaylistSongFilePaths = [];
  7565. this.sonDataSource.pushArrayData(this.songList)
  7566. }else {
  7567. this.resetFindPagedLocalQueueState();
  7568. const globalVideoList = this.buildPlayQueueFromView();
  7569. this.curIndex = findSongIndexByFilePath(globalVideoList, item.filePath)
  7570. if (this.curIndex < 0) {
  7571. globalVideoList.push(item);
  7572. this.curIndex = globalVideoList.length - 1;
  7573. }
  7574. this.songList = globalVideoList
  7575. this.sonDataSource.pushArrayData(this.songList)
  7576. this.currentSong = this.songList[this.curIndex]
  7577. // 只在非歌单模式下清空歌单路径列表
  7578. if (this.modeType !== 4) {
  7579. this.currentPlaylistSongFilePaths = [];
  7580. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  7581. } else {
  7582. // 歌单模式:确保歌单路径列表已设置
  7583. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7584. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7585. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7586. } else {
  7587. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7588. }
  7589. }
  7590. }
  7591. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7592. try {
  7593. const localUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-local');
  7594. this.videoUrl = localUrl || this.currentSong.filePath
  7595. } catch (error) {
  7596. Logger.error(TAG, `本地歌曲构建播放地址失败: ${(error as Error).message}`);
  7597. this.videoUrl = this.currentSong.filePath
  7598. }
  7599. this.name = this.currentSong.name
  7600. this.cover = this.currentSong.pixelMapPath
  7601. this.artist = this.currentSong.artist
  7602. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  7603. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  7604. this.startPlayOrResumePlay()
  7605. break;
  7606. case CommonConstants.TYPE_WEBDAV:
  7607. case CommonConstants.TYPE_SMB:
  7608. case CommonConstants.TYPE_NAVIDROME:
  7609. case CommonConstants.TYPE_FTP:
  7610. case CommonConstants.TYPE_BAIDU:
  7611. case CommonConstants.TYPE_JELLYFIN:
  7612. case CommonConstants.TYPE_EMBY:
  7613. case CommonConstants.TYPE_AUDIOSTATION:
  7614. case CommonConstants.TYPE_PLEX:
  7615. case CommonConstants.TYPE_DAOLIYU:
  7616. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  7617. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  7618. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7619. this.stop();
  7620. }
  7621. this.resetFindPagedLocalQueueState();
  7622. this.preserveExistingQueueOnNextPlay = false;
  7623. this.nextPlayQueueScope = 'view';
  7624. if (isOpen) {
  7625. this.currentSong = item
  7626. if (index !== undefined) {
  7627. this.curIndex = index
  7628. }
  7629. this.songList = []
  7630. this.songList.push(item)
  7631. this.sonDataSource.pushArrayData(this.songList)
  7632. } else if (isFromSonPlayList) {
  7633. // 点击来自右下角的播放列表
  7634. this.currentSong = item
  7635. if (index !== undefined) {
  7636. this.curIndex = index
  7637. }
  7638. // 设置播放队列作用域为歌单
  7639. this.playQueueScope = 'playlist'
  7640. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7641. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  7642. } else {
  7643. // 从全局网络音频列表中查找
  7644. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  7645. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  7646. if (this.curIndex === -1 && index !== undefined) {
  7647. this.curIndex = index;
  7648. }
  7649. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  7650. this.currentSong = this.songList[this.curIndex];
  7651. this.sonDataSource.pushArrayData(this.songList)
  7652. }
  7653. await this.hydrateRemoteSongFromDb(this.currentSong);
  7654. await this.hydrateRemoteSongFromDb(this.currentSong);
  7655. AppStorage.setOrCreate('currentSong', this.currentSong);
  7656. const remotePlayLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  7657. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-remote');
  7658. if (!playbackUrl) {
  7659. if (remotePlayLoading) {
  7660. this.hideLoadIng();
  7661. }
  7662. return;
  7663. }
  7664. this.videoUrl = playbackUrl;
  7665. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  7666. this.name = this.currentSong.name
  7667. this.cover = this.currentSong.pixelMapPath
  7668. this.artist = this.currentSong.artist
  7669. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  7670. this.startPlayOrResumePlay()
  7671. break;
  7672. }
  7673. }
  7674. private async openIsoArchiveDialog(item: VideoItem): Promise<void> {
  7675. if (!item || StrUtil.isEmpty(item.filePath)) {
  7676. Logger.error(TAG, `heanup ISO open dialog invalid path=${item ? item.filePath : ''}`)
  7677. ToastUtil.showToast('ISO 文件无效')
  7678. return
  7679. }
  7680. if (this.isIsoExtracting) {
  7681. if (ArrayUtil.isNotEmpty(this.isoAudioEntries)) {
  7682. if (this.isoSourceFilePath !== item.filePath) {
  7683. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行,已打开提取进度窗口')
  7684. }
  7685. this.presentIsoArchiveDialog()
  7686. return
  7687. }
  7688. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行')
  7689. return
  7690. }
  7691. Logger.info(TAG, `heanup ISO open dialog path=${item.filePath}, name=${item.fileName || item.name}`)
  7692. this.closeIsoDialog()
  7693. this.isoSourceFilePath = item.filePath
  7694. this.isoSourceFileName = item.fileName || item.name
  7695. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  7696. progress: 0,
  7697. backCancel: false,
  7698. autoCancel: false,
  7699. loadColor: this.themeColor,
  7700. fontColor: this.themeColor
  7701. })
  7702. try {
  7703. const task = new taskpool.Task(listIsoAudioEntriesTask, item.filePath)
  7704. const entries = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoArchiveAudioEntry[]
  7705. this.isoAudioEntries = Array.isArray(entries) ? entries : []
  7706. Logger.info(TAG, `heanup ISO list entries done count=${this.isoAudioEntries.length}, path=${item.filePath}`)
  7707. if (ArrayUtil.isEmpty(this.isoAudioEntries)) {
  7708. Logger.error(TAG, `heanup ISO list entries empty path=${item.filePath}`)
  7709. ToastUtil.showToast('ISO 内未发现可提取的媒体文件')
  7710. this.closeIsoDialog()
  7711. return
  7712. }
  7713. this.selectedIsoAudioPaths = []
  7714. } catch (error) {
  7715. Logger.error(TAG, `heanup 解析 ISO 失败: ${(error as Error).message}`)
  7716. ToastUtil.showToast('解析 ISO 失败')
  7717. this.closeIsoDialog()
  7718. return
  7719. } finally {
  7720. if (this.loadingProgressDialogId) {
  7721. DialogHelper.closeDialog(this.loadingProgressDialogId)
  7722. this.loadingProgressDialogId = ''
  7723. }
  7724. }
  7725. this.presentIsoArchiveDialog()
  7726. }
  7727. private presentIsoArchiveDialog(): void {
  7728. if (this.isoComponentId > 0) {
  7729. return
  7730. }
  7731. this.getUIContext().getPromptAction().openCustomDialog({
  7732. builder: () => {
  7733. this.isoComptentBuilder()
  7734. },
  7735. isModal: true,
  7736. showInSubWindow: false,
  7737. maskColor: Color.Transparent,
  7738. dialogTransition: TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7739. .animation({ duration: 600, curve: Curve.Smooth }),
  7740. maskTransition: TransitionEffect.opacity(0.5)
  7741. .animation({ duration: 600, curve: Curve.Smooth })
  7742. }).then((dialogId: number) => {
  7743. this.isoComponentId = dialogId
  7744. }).catch((error: BusinessError) => {
  7745. Logger.error(TAG, `heanup 打开 ISO 弹窗失败: ${error.message}`)
  7746. this.closeIsoDialog()
  7747. })
  7748. }
  7749. private toggleIsoEntrySelection(path: string, checked: boolean): void {
  7750. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7751. if (checked) {
  7752. selectedPathSet.add(path)
  7753. } else {
  7754. selectedPathSet.delete(path)
  7755. }
  7756. this.selectedIsoAudioPaths = this.isoAudioEntries
  7757. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7758. .map((entry: IsoArchiveAudioEntry) => entry.path)
  7759. Logger.info(TAG,
  7760. `heanup ISO toggle selection path=${path}, checked=${checked}, total=${this.selectedIsoAudioPaths.length}`)
  7761. }
  7762. private toggleIsoEntrySelectAll(): void {
  7763. if (this.selectedIsoAudioPaths.length === this.isoAudioEntries.length) {
  7764. this.selectedIsoAudioPaths = []
  7765. Logger.info(TAG, 'heanup ISO toggle select all cleared')
  7766. return
  7767. }
  7768. this.selectedIsoAudioPaths = this.isoAudioEntries.map((entry: IsoArchiveAudioEntry) => entry.path)
  7769. Logger.info(TAG, `heanup ISO toggle select all count=${this.selectedIsoAudioPaths.length}`)
  7770. }
  7771. private startIsoExtractProgressWatcher(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): void {
  7772. this.stopIsoExtractProgressWatcher()
  7773. this.isoExtractExpectedOutputPaths = this.buildIsoExtractExpectedOutputPaths(entries, destinationDir)
  7774. this.isoExtractTotalBytes = entries.reduce((total: number, entry: IsoArchiveAudioEntry) => {
  7775. const size = entry && entry.size > 0 ? entry.size : 0
  7776. return total + size
  7777. }, 0)
  7778. this.isoExtractReceivedTaskProgress = false
  7779. this.isoExtractDisplayedProgress = 0
  7780. this.isoExtractLastActivityTime = Date.now()
  7781. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths)) {
  7782. return
  7783. }
  7784. this.isoExtractProgressTimer = setInterval(() => {
  7785. this.updateIsoExtractProgressFromFiles()
  7786. }, 500)
  7787. }
  7788. private stopIsoExtractProgressWatcher(): void {
  7789. if (this.isoExtractProgressTimer) {
  7790. clearInterval(this.isoExtractProgressTimer)
  7791. this.isoExtractProgressTimer = 0
  7792. }
  7793. this.isoExtractExpectedOutputPaths = []
  7794. this.isoExtractTotalBytes = 0
  7795. this.isoExtractReceivedTaskProgress = false
  7796. this.isoExtractLastActivityTime = 0
  7797. }
  7798. private markIsoExtractActivity(): void {
  7799. this.isoExtractLastActivityTime = Date.now()
  7800. }
  7801. private updateIsoExtractProgressFromFiles(): void {
  7802. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths) ||
  7803. this.isoExtractReceivedTaskProgress) {
  7804. return
  7805. }
  7806. let writtenBytes = 0
  7807. let existingCount = 0
  7808. for (let i = 0; i < this.isoExtractExpectedOutputPaths.length; i++) {
  7809. const outputPath = this.isoExtractExpectedOutputPaths[i]
  7810. if (!FileUtil.accessSync(outputPath)) {
  7811. continue
  7812. }
  7813. existingCount++
  7814. try {
  7815. const stat = fs.statSync(outputPath) as fs.Stat
  7816. if (typeof stat.size === 'number' && stat.size > 0) {
  7817. writtenBytes += stat.size
  7818. }
  7819. } catch (_error) {
  7820. }
  7821. }
  7822. let progress = 0
  7823. if (writtenBytes > 0) {
  7824. progress = Math.ceil((writtenBytes / this.isoExtractTotalBytes) * 100)
  7825. if (progress > 99) {
  7826. progress = 99
  7827. }
  7828. this.markIsoExtractActivity()
  7829. } else if (existingCount > 0) {
  7830. progress = 1
  7831. this.markIsoExtractActivity()
  7832. }
  7833. if (progress > 0) {
  7834. this.updateIsoExtractProgressState(progress,
  7835. `正在提取 ${progress}% (${existingCount}/${this.isoExtractExpectedOutputPaths.length})`)
  7836. return
  7837. }
  7838. if (this.isoExtractTask && this.isoExtractLastActivityTime > 0 &&
  7839. Date.now() - this.isoExtractLastActivityTime > this.isoExtractStallTimeoutMs) {
  7840. Logger.warn(TAG, `heanup ISO 提取进度长时间无变化: timeout=${this.isoExtractStallTimeoutMs}`)
  7841. this.markIsoExtractActivity()
  7842. this.updateIsoExtractProgressState(1, '准备提取 1%')
  7843. }
  7844. }
  7845. private updateIsoExtractProgressState(progress: number, message: string, currentName: string = '',
  7846. force: boolean = false): void {
  7847. let safeProgress = progress
  7848. if (safeProgress < 0) {
  7849. safeProgress = 0
  7850. }
  7851. if (safeProgress > 100) {
  7852. safeProgress = 100
  7853. }
  7854. if (!force && safeProgress < this.isoExtractDisplayedProgress) {
  7855. return
  7856. }
  7857. this.isoExtractDisplayedProgress = safeProgress
  7858. this.isoExtractProgress = safeProgress
  7859. this.isoExtractProgressText = message
  7860. if (force || StrUtil.isNotEmpty(currentName)) {
  7861. this.isoExtractCurrentEntryName = currentName
  7862. }
  7863. }
  7864. private resetIsoExtractProgressState(): void {
  7865. this.isoExtractProgress = 0
  7866. this.isoExtractProgressText = ''
  7867. this.isoExtractCurrentEntryName = ''
  7868. this.isoExtractDisplayedProgress = 0
  7869. }
  7870. private buildIsoExtractExpectedOutputPaths(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): Array<string> {
  7871. const outputPaths: Array<string> = []
  7872. const occupiedPaths: Set<string> = new Set<string>()
  7873. for (let i = 0; i < entries.length; i++) {
  7874. const entry = entries[i]
  7875. const fileName = entry.name || this.getIsoLastPathSegment(entry.path)
  7876. const outputPath = this.buildIsoExpectedOutputPath(destinationDir, fileName, occupiedPaths)
  7877. occupiedPaths.add(outputPath)
  7878. outputPaths.push(outputPath)
  7879. }
  7880. return outputPaths
  7881. }
  7882. private buildIsoExpectedOutputPath(destinationDir: string, fileName: string, occupiedPaths: Set<string>): string {
  7883. const cleanName = this.sanitizeIsoOutputFileName(fileName)
  7884. const extension = this.getIsoOutputFileExtension(cleanName)
  7885. const baseName = extension.length > 0 ? cleanName.substring(0, cleanName.length - extension.length) : cleanName
  7886. let candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${cleanName}`
  7887. let suffix = 0
  7888. while (occupiedPaths.has(candidatePath) || FileUtil.accessSync(candidatePath)) {
  7889. suffix++
  7890. candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${baseName} (${suffix})${extension}`
  7891. }
  7892. return candidatePath
  7893. }
  7894. private sanitizeIsoOutputFileName(fileName: string): string {
  7895. const lastSegment = this.getIsoLastPathSegment(fileName)
  7896. let sanitized = ''
  7897. for (let i = 0; i < lastSegment.length; i++) {
  7898. const char = lastSegment[i]
  7899. if (char === '/' || char === '\\' || char === ':' || char === '*' || char === '?' || char === '"' ||
  7900. char === '<' || char === '>' || char === '|') {
  7901. sanitized += '_'
  7902. } else {
  7903. sanitized += char
  7904. }
  7905. }
  7906. if (sanitized.trim().length === 0) {
  7907. return 'iso_audio.bin'
  7908. }
  7909. return sanitized
  7910. }
  7911. private getIsoLastPathSegment(path: string): string {
  7912. const normalizedPath = path.replace(/\\/g, '/')
  7913. const lastSeparator = normalizedPath.lastIndexOf('/')
  7914. if (lastSeparator < 0) {
  7915. return normalizedPath
  7916. }
  7917. return normalizedPath.substring(lastSeparator + 1)
  7918. }
  7919. private getIsoOutputFileExtension(fileName: string): string {
  7920. const lastDot = fileName.lastIndexOf('.')
  7921. if (lastDot < 0) {
  7922. return ''
  7923. }
  7924. return fileName.substring(lastDot)
  7925. }
  7926. private trimIsoOutputTrailingSeparator(path: string): string {
  7927. if (path.endsWith('/')) {
  7928. return path.substring(0, path.length - 1)
  7929. }
  7930. return path
  7931. }
  7932. private cancelIsoExtraction(reason?: string): void {
  7933. const currentTask = this.isoExtractTask
  7934. Logger.info(TAG,
  7935. `heanup ISO cancel request reason=${reason || ''}, hasTask=${currentTask ? 'true' : 'false'}`)
  7936. this.isoExtractCanceled = true
  7937. this.isoExtractCancelMessage = reason ? reason : ''
  7938. this.isoExtractTask = undefined
  7939. this.updateIsoExtractProgressState(this.isoExtractProgress, '正在停止提取...', this.isoExtractCurrentEntryName, true)
  7940. if (currentTask) {
  7941. try {
  7942. taskpool.terminateTask(currentTask)
  7943. } catch (error) {
  7944. Logger.error(TAG, `heanup 终止 ISO 提取任务失败: ${(error as Error).message}`)
  7945. }
  7946. }
  7947. }
  7948. private moveIsoExtractionToBackground(): void {
  7949. this.closeIsoDialog(false)
  7950. ToastUtil.showToast('ISO 提取已转入后台')
  7951. }
  7952. private async extractSelectedIsoAudioFiles(): Promise<void> {
  7953. if (this.isIsoExtracting) {
  7954. return
  7955. }
  7956. if (ArrayUtil.isEmpty(this.selectedIsoAudioPaths)) {
  7957. ToastUtil.showToast('请先选择要提取的文件')
  7958. return
  7959. }
  7960. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7961. const selectedEntries = this.isoAudioEntries
  7962. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7963. if (ArrayUtil.isEmpty(selectedEntries)) {
  7964. ToastUtil.showToast('未找到要提取的文件')
  7965. return
  7966. }
  7967. const hasSacdTrack: boolean = selectedEntries.some((entry: IsoArchiveAudioEntry) => entry.entryType === 'sacd_track')
  7968. const destinationDir: string = this.currentPath
  7969. this.isIsoExtracting = true
  7970. this.isoExtractCanceled = false
  7971. this.isoExtractCancelMessage = ''
  7972. this.isoExtractDestinationDir = destinationDir
  7973. Logger.info(TAG,
  7974. `heanup ISO extract start file=${this.isoSourceFilePath}, selected=${selectedEntries.length}, ` +
  7975. `hasSacd=${hasSacdTrack}, destinationDir=${destinationDir}`)
  7976. Logger.info(TAG,
  7977. `heanup ISO selected entries: ${selectedEntries.map((entry: IsoArchiveAudioEntry) => entry.path).join(', ')}`)
  7978. this.resetIsoExtractProgressState()
  7979. this.updateIsoExtractProgressState(1, '准备提取 1%', '', true)
  7980. this.startIsoExtractProgressWatcher(selectedEntries, destinationDir)
  7981. try {
  7982. const extractStartedAt = Date.now()
  7983. const outputPaths: string[] = this.buildIsoExtractExpectedOutputPaths(selectedEntries, destinationDir)
  7984. const payloadJson = JSON.stringify({
  7985. isoPath: this.isoSourceFilePath,
  7986. destinationDir,
  7987. entries: selectedEntries,
  7988. outputPaths
  7989. })
  7990. const task = new taskpool.Task(extractIsoAudioEntriesTask, payloadJson)
  7991. this.isoExtractTask = task
  7992. task.onReceiveData((progressData: IsoExtractProgressMessage) => {
  7993. this.markIsoExtractActivity()
  7994. const progress = typeof progressData.progress === 'number' ? Math.floor(progressData.progress) : 0
  7995. Logger.info(TAG,
  7996. `heanup ISO task receive stage=${progressData.stage || ''}, progress=${progress}, name=${progressData.name || ''}`)
  7997. if (progress > 1 && !this.isoExtractReceivedTaskProgress) {
  7998. this.isoExtractReceivedTaskProgress = true
  7999. if (this.isoExtractProgressTimer) {
  8000. clearInterval(this.isoExtractProgressTimer)
  8001. this.isoExtractProgressTimer = 0
  8002. }
  8003. Logger.info(TAG, `heanup ISO 提取切换为任务进度: progress=${progress}, stage=${progressData.stage || ''}`)
  8004. }
  8005. const stageText = progressData.stage === 'prepare' ? '准备提取' :
  8006. (progressData.stage === 'done' ? '提取完成' : (progressData.stage === 'error' ? '提取异常' : '正在提取'))
  8007. if (progress > this.isoExtractDisplayedProgress || progressData.stage !== 'extract') {
  8008. Logger.info(TAG,
  8009. `heanup ISO 提取任务进度: stage=${progressData.stage || ''}, progress=${progress}, ` +
  8010. `name=${progressData.name || ''}`)
  8011. }
  8012. this.updateIsoExtractProgressState(progress, `${stageText} ${progress}%`, progressData.name || '')
  8013. })
  8014. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoExtractTaskResult
  8015. const extractElapsedMs = Date.now() - extractStartedAt
  8016. this.isoExtractTask = undefined
  8017. Logger.info(TAG, `heanup ISO extract task completed canceled=${this.isoExtractCanceled}, elapsedMs=${extractElapsedMs}`)
  8018. if (this.isoExtractCanceled) {
  8019. return
  8020. }
  8021. const extractedPaths = result?.extractedPaths || []
  8022. const failedEntries = result?.failedEntries || []
  8023. const failureDetails = result?.failureDetails || []
  8024. Logger.info(TAG,
  8025. `heanup ISO extract result extracted=${extractedPaths.length}, failed=${failedEntries.length}, details=${failureDetails.length}`)
  8026. let importErrorMessage: string = ''
  8027. let importedCount: number = 0
  8028. if (ArrayUtil.isNotEmpty(extractedPaths)) {
  8029. const importStartedAt = Date.now()
  8030. try {
  8031. await this.postProcessExtractedIsoFiles(extractedPaths, selectedEntries, outputPaths)
  8032. importedCount = await this.importExtractedFilesToDirectory(extractedPaths, destinationDir)
  8033. Logger.info(TAG,
  8034. `heanup ISO import extracted files success elapsedMs=${Date.now() - importStartedAt}, ` +
  8035. `importedCount=${importedCount}`)
  8036. } catch (importError) {
  8037. importErrorMessage = (importError as Error).message || '导入媒体库失败'
  8038. Logger.error(TAG,
  8039. `heanup ISO import extracted files failed elapsedMs=${Date.now() - importStartedAt}, ` +
  8040. `message=${importErrorMessage}`)
  8041. }
  8042. }
  8043. if (extractedPaths.length > 0 && failedEntries.length > 0) {
  8044. if (StrUtil.isNotEmpty(importErrorMessage)) {
  8045. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,导入失败`)
  8046. } else if (importedCount > 0) {
  8047. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,已入库 ${importedCount} 个音频文件`)
  8048. } else {
  8049. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个`)
  8050. }
  8051. } else if (extractedPaths.length > 0) {
  8052. if (StrUtil.isNotEmpty(importErrorMessage)) {
  8053. ToastUtil.showToast(`提取完成,但导入媒体库失败: ${importErrorMessage}`)
  8054. } else if (importedCount > 0) {
  8055. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件,入库 ${importedCount} 个音频文件`)
  8056. } else {
  8057. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件`)
  8058. }
  8059. } else if (ArrayUtil.isNotEmpty(failureDetails)) {
  8060. const firstFailure: IsoExtractFailureDetail = failureDetails[0]
  8061. const reasonText = firstFailure.reason && firstFailure.reason.length > 0 ? firstFailure.reason : '提取失败'
  8062. ToastUtil.showToast(reasonText)
  8063. } else if (hasSacdTrack) {
  8064. ToastUtil.showToast('SACD ISO 轨道提取失败')
  8065. } else {
  8066. ToastUtil.showToast('提取失败')
  8067. }
  8068. } catch (error) {
  8069. this.isoExtractTask = undefined
  8070. if (this.isoExtractCanceled) {
  8071. return
  8072. }
  8073. Logger.error(TAG, `heanup 提取 ISO 文件失败: ${(error as Error).message}`)
  8074. ToastUtil.showToast('提取 ISO 文件失败')
  8075. } finally {
  8076. const shouldResetDialogState: boolean = this.isoComponentId <= 0
  8077. this.stopIsoExtractProgressWatcher()
  8078. this.isoExtractTask = undefined
  8079. this.isIsoExtracting = false
  8080. Logger.info(TAG,
  8081. `heanup ISO extract finally canceled=${this.isoExtractCanceled}, cancelMessage=${this.isoExtractCancelMessage}`)
  8082. if (this.isoExtractCanceled && this.isoExtractCancelMessage.length > 0) {
  8083. ToastUtil.showToast(this.isoExtractCancelMessage)
  8084. }
  8085. this.isoExtractCanceled = false
  8086. this.isoExtractCancelMessage = ''
  8087. if (shouldResetDialogState) {
  8088. this.resetIsoDialogState()
  8089. } else {
  8090. this.selectedIsoAudioPaths = []
  8091. this.resetIsoExtractProgressState()
  8092. }
  8093. }
  8094. }
  8095. private async postProcessExtractedIsoFiles(extractedPaths: Array<string>, selectedEntries: Array<IsoArchiveAudioEntry>,
  8096. outputPaths: Array<string>): Promise<void> {
  8097. if (ArrayUtil.isEmpty(extractedPaths) || ArrayUtil.isEmpty(selectedEntries) || ArrayUtil.isEmpty(outputPaths)) {
  8098. return
  8099. }
  8100. const entryByOutputPath: Map<string, IsoArchiveAudioEntry> = new Map<string, IsoArchiveAudioEntry>()
  8101. for (let i = 0; i < outputPaths.length && i < selectedEntries.length; i++) {
  8102. entryByOutputPath.set(outputPaths[i], selectedEntries[i])
  8103. }
  8104. for (let i = 0; i < extractedPaths.length; i++) {
  8105. const extractedPath = extractedPaths[i]
  8106. const entry = entryByOutputPath.get(extractedPath)
  8107. if (!entry) {
  8108. continue
  8109. }
  8110. await this.postProcessExtractedIsoEntry(extractedPath, entry)
  8111. }
  8112. }
  8113. private async postProcessExtractedIsoEntry(filePath: string, entry: IsoArchiveAudioEntry): Promise<void> {
  8114. if (!Utility.isMusicByExtension(filePath)) {
  8115. return
  8116. }
  8117. const hasEmbeddedMetadata: boolean = StrUtil.isNotEmpty(entry.title) || StrUtil.isNotEmpty(entry.album) ||
  8118. StrUtil.isNotEmpty(entry.artist) || StrUtil.isNotEmpty(entry.albumArtist) || StrUtil.isNotEmpty(entry.comment) ||
  8119. !!(entry.trackNumber && entry.trackNumber > 0)
  8120. if (entry.entryType !== 'sacd_track' && !hasEmbeddedMetadata) {
  8121. return
  8122. }
  8123. const tags: FFMpegTags = this.buildIsoExtractedMetadata(entry)
  8124. if (Object.keys(tags).length > 0) {
  8125. try {
  8126. const metadataResult = await repairAudioMetadata(filePath, '', tags, true, '')
  8127. Logger.info(TAG,
  8128. `heanup ISO metadata post-process path=${filePath}, success=${metadataResult}, type=${entry.entryType || ''}`)
  8129. } catch (error) {
  8130. Logger.error(TAG, `heanup ISO metadata post-process failed path=${filePath}, message=${(error as Error).message}`)
  8131. }
  8132. }
  8133. if (!filePath.toLowerCase().endsWith('.dsf')) {
  8134. return
  8135. }
  8136. const coverUrl = await this.resolveIsoExtractCoverUrl(entry)
  8137. if (StrUtil.isEmpty(coverUrl)) {
  8138. return
  8139. }
  8140. try {
  8141. const coverResult = await changeMusicCover(this.context, filePath, coverUrl, true, '')
  8142. Logger.info(TAG, `heanup ISO cover post-process path=${filePath}, success=${coverResult}`)
  8143. } catch (error) {
  8144. Logger.error(TAG, `heanup ISO cover post-process failed path=${filePath}, message=${(error as Error).message}`)
  8145. }
  8146. }
  8147. private buildIsoExtractedMetadata(entry: IsoArchiveAudioEntry): FFMpegTags {
  8148. const metadata: FFMpegTags = {}
  8149. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  8150. if (StrUtil.isNotEmpty(title)) {
  8151. metadata.title = title
  8152. metadata.TITLE = title
  8153. }
  8154. if (StrUtil.isNotEmpty(entry.artist)) {
  8155. metadata.artist = entry.artist
  8156. metadata.ARTIST = entry.artist
  8157. }
  8158. if (StrUtil.isNotEmpty(entry.album)) {
  8159. metadata.album = entry.album
  8160. metadata.ALBUM = entry.album
  8161. }
  8162. if (entry.trackNumber && entry.trackNumber > 0) {
  8163. metadata.track = `${entry.trackNumber}`
  8164. metadata.TRACK = `${entry.trackNumber}`
  8165. }
  8166. if (StrUtil.isNotEmpty(entry.albumArtist)) {
  8167. metadata.ALBUMARTIST = entry.albumArtist
  8168. metadata.album_artist = entry.albumArtist
  8169. metadata.TPE2 = entry.albumArtist
  8170. }
  8171. if (StrUtil.isNotEmpty(entry.comment)) {
  8172. metadata.comment = entry.comment
  8173. metadata.COMMENT = entry.comment
  8174. metadata.COMM = entry.comment
  8175. }
  8176. return metadata
  8177. }
  8178. private getIsoEntryBaseName(fileName: string): string {
  8179. const lastSegment = this.getIsoLastPathSegment(fileName)
  8180. const lastDot = lastSegment.lastIndexOf('.')
  8181. if (lastDot <= 0) {
  8182. return lastSegment
  8183. }
  8184. return lastSegment.substring(0, lastDot)
  8185. }
  8186. private async resolveIsoExtractCoverUrl(entry: IsoArchiveAudioEntry): Promise<string> {
  8187. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  8188. const artist = entry.artist || entry.albumArtist || ''
  8189. if (StrUtil.isEmpty(title) || PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8190. return ''
  8191. }
  8192. try {
  8193. const coverUrl = await NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', ''))
  8194. if (StrUtil.isNotEmpty(coverUrl) && coverUrl !== 'unknown') {
  8195. return coverUrl
  8196. }
  8197. } catch (error) {
  8198. Logger.error(TAG,
  8199. `heanup ISO resolve cover failed title=${title}, artist=${artist}, message=${(error as Error).message}`)
  8200. }
  8201. return ''
  8202. }
  8203. private async importExtractedFilesToDirectory(paths: Array<string>, destinationDir: string): Promise<number> {
  8204. if (ArrayUtil.isEmpty(paths)) {
  8205. return 0
  8206. }
  8207. let importedCount: number = 0
  8208. for (let i = 0; i < paths.length; i++) {
  8209. const filePath = paths[i]
  8210. if (destinationDir === this.lockPath || !Utility.isMeidaByExtension(filePath) ||
  8211. filePath.endsWith('.lrc') || filePath.endsWith('.srt') || Utility.isIsoByExtension(filePath)) {
  8212. continue
  8213. }
  8214. const mediaItem = await Utility.uriGetMusicAssetsFromFile(this.context, filePath,
  8215. CommonConstants.TYPE_LOCAL, this.autoParseMusicName)
  8216. await new Promise<void>((resolve) => {
  8217. this.table.insert(mediaItem, (_id: number) => resolve())
  8218. })
  8219. importedCount++
  8220. }
  8221. this.cache.delete(destinationDir)
  8222. if (this.currentPath === destinationDir) {
  8223. this.pageCache.clear()
  8224. this.pageHasMoreCache.clear()
  8225. this.pageTotalCountCache.clear()
  8226. if (destinationDir === this.lockPath) {
  8227. this.getSortedFiles(destinationDir, true)
  8228. } else {
  8229. await this.resetAndLoadFirstPage()
  8230. }
  8231. }
  8232. return importedCount
  8233. }
  8234. private resetIsoDialogState(): void {
  8235. this.isoAudioEntries = []
  8236. this.selectedIsoAudioPaths = []
  8237. this.isoSourceFileName = ''
  8238. this.isoSourceFilePath = ''
  8239. this.isoExtractDestinationDir = ''
  8240. this.isIsoExtracting = false
  8241. this.stopIsoExtractProgressWatcher()
  8242. this.isoExtractTask = undefined
  8243. this.resetIsoExtractProgressState()
  8244. }
  8245. private closeIsoDialog(reset: boolean = true): void {
  8246. if (this.isoComponentId > 0) {
  8247. try {
  8248. this.getUIContext().getPromptAction().closeCustomDialog(this.isoComponentId)
  8249. } catch (_error) {
  8250. }
  8251. this.isoComponentId = 0
  8252. }
  8253. if (!reset) {
  8254. return
  8255. }
  8256. this.resetIsoDialogState()
  8257. }
  8258. @Builder
  8259. isoComptentBuilder() {
  8260. IsoExtractComptent({
  8261. isoFileName: this.isoSourceFileName,
  8262. entries: this.isoAudioEntries,
  8263. selectedPaths: this.selectedIsoAudioPaths,
  8264. isLongNameRoLL: this.isLongNameRoLL,
  8265. isExtracting: this.isIsoExtracting,
  8266. extractProgress: this.isoExtractProgress,
  8267. extractProgressText: this.isoExtractProgressText,
  8268. extractCurrentName: this.isoExtractCurrentEntryName,
  8269. onToggleSelection: (path: string, checked: boolean) => {
  8270. this.toggleIsoEntrySelection(path, checked)
  8271. },
  8272. onToggleSelectAll: () => {
  8273. this.toggleIsoEntrySelectAll()
  8274. },
  8275. onExtract: async () => {
  8276. await this.extractSelectedIsoAudioFiles()
  8277. },
  8278. onRunInBackground: () => {
  8279. this.moveIsoExtractionToBackground()
  8280. },
  8281. onStopExtract: () => {
  8282. this.cancelIsoExtraction('已取消 ISO 提取')
  8283. },
  8284. onCancel: () => {
  8285. if (this.isIsoExtracting) {
  8286. this.moveIsoExtractionToBackground()
  8287. return
  8288. }
  8289. this.closeIsoDialog()
  8290. }
  8291. })
  8292. }
  8293. private cueComponentId: number = 0
  8294. private async handleCueTrackImport(cueinfo: CueInfo): Promise<void> {
  8295. try {
  8296. let sourceItem = Utility.getItemByFilePath(this.videoLocalList, cueinfo.filePath);
  8297. if (!sourceItem) {
  8298. sourceItem = await this.table.queryVideoByFilePath(cueinfo.filePath) || undefined;
  8299. }
  8300. const importedItems = await importCueTracks(this.context, this.table, cueinfo, sourceItem);
  8301. if (ArrayUtil.isEmpty(importedItems)) {
  8302. ToastUtil.showToast('未导入到任何分轨');
  8303. return;
  8304. }
  8305. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId);
  8306. await this.resetAndLoadFirstPage();
  8307. ToastUtil.showToast(`分轨完成,已入库 ${importedItems.length} 首`);
  8308. } catch (error) {
  8309. Logger.error(TAG, `CUE 分轨入库失败: ${(error as Error).message}`);
  8310. ToastUtil.showToast('分轨失败');
  8311. }
  8312. }
  8313. //显示cue分轨列表对话框
  8314. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  8315. this.getUIContext().getPromptAction().openCustomDialog({
  8316. builder: () => {
  8317. this.cueComptentBuilder(cueTracks,cueinfo)
  8318. },
  8319. isModal:true,
  8320. showInSubWindow:false,
  8321. maskColor: Color.Transparent,
  8322. dialogTransition: // 设置弹窗内容显示的过渡效果
  8323. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  8324. .animation({ duration: 600, curve: Curve.Smooth }),
  8325. maskTransition: // 设置蒙层显示的过渡效果
  8326. TransitionEffect.opacity(0.5)
  8327. .animation({ duration: 600, curve: Curve.Smooth })
  8328. }).then((dialogId: number) => {
  8329. this.cueComponentId = dialogId
  8330. })
  8331. .catch((error: BusinessError) => {
  8332. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  8333. })
  8334. }
  8335. @Builder
  8336. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  8337. CueComptent({
  8338. title:cueinfo.title,
  8339. cueTracks:cueTracks,
  8340. isLongNameRoLL:this.isLongNameRoLL,
  8341. onCancel:()=>{
  8342. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  8343. },
  8344. onSplitTracks: async ()=>{
  8345. await this.handleCueTrackImport(cueinfo)
  8346. },
  8347. onDoItemClick: async (item: CueTrack, index: number)=>{
  8348. //获取cueinfo对应的filePath
  8349. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  8350. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  8351. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  8352. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  8353. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  8354. if (this.currentSong){
  8355. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  8356. this.stop();//播放之前先停止之前播放。
  8357. }
  8358. this.songList = globalVideoList
  8359. this.sonDataSource.pushArrayData(this.songList)
  8360. if (this.currentSong) {
  8361. try {
  8362. const cueUrl = await this.resolvePlaybackUrlForCurrentSong('cue-track-play');
  8363. if (!cueUrl) {
  8364. return;
  8365. }
  8366. this.videoUrl = cueUrl;
  8367. } catch (error) {
  8368. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  8369. this.videoUrl = this.currentSong.filePath;
  8370. }
  8371. }
  8372. this.name = item.title||this.currentSong.name
  8373. this.cover = this.currentSong.pixelMapPath
  8374. this.artist = item.performer||this.currentSong.artist
  8375. this.currentSong.name = this.name
  8376. this.currentSong.artist = this.artist
  8377. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  8378. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  8379. }
  8380. }
  8381. })
  8382. }
  8383. @State isFrontWhite: boolean = false
  8384. private showCoverScaleGuideIfNeeded(): void {
  8385. const hasShown = PreferencesUtil.getBooleanSync(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, false)
  8386. if (hasShown) {
  8387. return
  8388. }
  8389. this.isShowCoverScaleGuide = true
  8390. setTimeout(() => {
  8391. if (this.isShowCoverScaleGuide) {
  8392. this.dismissCoverScaleGuide()
  8393. }
  8394. }, 9000)
  8395. }
  8396. private dismissCoverScaleGuide(): void {
  8397. this.isShowCoverScaleGuide = false
  8398. PreferencesUtil.put(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, true)
  8399. }
  8400. private resolveMiniBarDismissTarget() {
  8401. const viewportWidthVp = this.windowWidth > 0 ? px2vp(this.windowWidth) : 360
  8402. const viewportHeightVp = this.windowHeight > 0 ? px2vp(this.windowHeight) : 800
  8403. const useFixedBottomMargin = DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  8404. || this.curDisplayIsHiCar
  8405. return resolvePlayerDismissMorphTarget(viewportWidthVp, viewportHeightVp, this.bottomSafeHeight, useFixedBottomMargin)
  8406. }
  8407. private clearPlayDismissTimer(): void {
  8408. if (this.playDismissTimer >= 0) {
  8409. clearTimeout(this.playDismissTimer)
  8410. this.playDismissTimer = -1
  8411. }
  8412. }
  8413. private clearPlayOpenTimer(): void {
  8414. if (this.playOpenTimer >= 0) {
  8415. clearTimeout(this.playOpenTimer)
  8416. this.playOpenTimer = -1
  8417. }
  8418. }
  8419. private resetMusicPlayDismissState(): void {
  8420. this.clearPlayDismissTimer()
  8421. this.clearPlayOpenTimer()
  8422. this.playOpenFromMiniBarPending = false
  8423. this.translateY = 0
  8424. this.playDismissTranslateX = 0
  8425. this.playDismissScale = 1
  8426. this.playDismissScaleY = 1
  8427. this.playDismissOpacity = 1
  8428. this.playDismissBorderRadius = 0
  8429. this.playDismissProxySize = 0
  8430. this.playDismissProxyOpacity = 0
  8431. this.scaleValueImage = 1
  8432. this.scaleValueText = 1
  8433. this.playDragUiOpacity = 1
  8434. }
  8435. private preparePlayerViewOpenFromMiniBar(): void {
  8436. const target = this.resolveMiniBarDismissTarget()
  8437. this.playOpenFromMiniBarPending = true
  8438. this.translateY = target.translateY
  8439. this.playDismissTranslateX = 0
  8440. this.playDismissScale = 0.9
  8441. this.playDismissScaleY = 0.8
  8442. this.playDismissOpacity = 0
  8443. this.playDismissBorderRadius = 48
  8444. this.playDismissProxySize = 0
  8445. this.playDismissProxyOpacity = 0
  8446. this.playDragUiOpacity = 0
  8447. this.scaleValueImage = 0.82
  8448. this.scaleValueText = 0.88
  8449. }
  8450. private startPlayerViewOpenAnimationIfNeeded(): void {
  8451. if (!this.playOpenFromMiniBarPending) {
  8452. return
  8453. }
  8454. this.playOpenFromMiniBarPending = false
  8455. this.getUIContext()?.animateTo({
  8456. duration: this.playOpenExpandDuration,
  8457. curve: Curve.Friction
  8458. }, () => {
  8459. this.playDismissProxySize = 0
  8460. this.playDismissProxyOpacity = 0
  8461. this.translateY = 0
  8462. this.playDismissTranslateX = 0
  8463. this.playDismissScale = 1
  8464. this.playDismissScaleY = 1
  8465. this.playDismissOpacity = 1
  8466. this.playDismissBorderRadius = 0
  8467. this.playDragUiOpacity = 1
  8468. this.scaleValueImage = 1
  8469. this.scaleValueText = 1
  8470. })
  8471. }
  8472. setShowPlayTrue(){
  8473. this.getUIContext()?.animateTo({
  8474. duration: 500,
  8475. curve: Curve.Friction
  8476. }, () => {
  8477. this.isShowPlay = true;
  8478. this.showCoverScaleGuideIfNeeded()
  8479. });
  8480. }
  8481. setShowPlayFalse(){
  8482. this.getUIContext()?.animateTo({
  8483. duration: 500,
  8484. curve: Curve.Friction
  8485. }, () => {
  8486. this.isShowPlay = false;
  8487. });
  8488. this.isShowCoverScaleGuide = false
  8489. }
  8490. //打开播放页
  8491. showPlayerView() {
  8492. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  8493. if (ArrayUtil.isNotEmpty(this.songList)) {
  8494. // this.setShowPlayTrue()
  8495. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  8496. this.initLyric(lyricPath);
  8497. this.startAutoHide();
  8498. } else {
  8499. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  8500. }
  8501. }
  8502. //打开播放列表
  8503. openPlayList(){
  8504. if (ArrayUtil.isNotEmpty(this.songList)) {
  8505. this.isShowSheet = !this.isShowSheet;
  8506. this.isFrontWhite = false
  8507. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  8508. this.scrollIndex()
  8509. if (this.shouldHydrateFullMediaPlayListOnOpen()) {
  8510. void this.hydrateFullMediaPlayListIfNeeded();
  8511. }
  8512. } else {
  8513. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  8514. }
  8515. }
  8516. scrollIndex(){
  8517. try {
  8518. setTimeout(() => {
  8519. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8520. if(this.curIndex>60){
  8521. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  8522. }else{
  8523. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  8524. }
  8525. })
  8526. }, 123)
  8527. }catch (error) {
  8528. console.error(`onecold scrollIndex出错: ${error}`);
  8529. }
  8530. }
  8531. scrollIndexMain(dialogId?:string){
  8532. try {
  8533. setTimeout(() => {
  8534. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8535. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  8536. if(dialogId)
  8537. DialogHelper.closeDialog(dialogId)
  8538. let isAni:boolean = false
  8539. if(this.curIndex<50){
  8540. isAni = true
  8541. }
  8542. if(this.twoFingerType==4){
  8543. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8544. }else{
  8545. if(this.isGridMusic){
  8546. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8547. }else{
  8548. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8549. }
  8550. }
  8551. })
  8552. }, 123)
  8553. }catch (error) {
  8554. console.error(`onecold scrollIndexMain出错: ${error}`);
  8555. }
  8556. }
  8557. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  8558. async locateCurrentSong(): Promise<void> {
  8559. if (!this.currentSong) {
  8560. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  8561. return;
  8562. }
  8563. // 检查当前播放歌曲是否在已加载的列表中
  8564. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8565. if (targetIndex > 0) {
  8566. // 歌曲在当前列表中,直接滚动
  8567. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  8568. this.curIndex = targetIndex;
  8569. this.scrollIndexMain();
  8570. } else {
  8571. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  8572. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  8573. const dialogID = DialogHelper.showLoadingDialog()
  8574. await this.hydrateFullMediaPlayListIfNeeded(false);
  8575. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8576. this.scrollIndexMain(dialogID);
  8577. }
  8578. }
  8579. //播放列表布局
  8580. @Builder
  8581. PlayListSheet() {
  8582. Column() {
  8583. this.PlayList()
  8584. }
  8585. .width('100%')
  8586. .height('100%')
  8587. }
  8588. @State titleStr: string = ''
  8589. @State ablumStr: string = ''
  8590. @State artistStr: string = ''
  8591. @State lyricConStr: string = ''
  8592. @State currentEditItem: string = ''
  8593. @State yearStr: string = ''
  8594. @State trackStr: string = ''
  8595. @State genreStr: string = ''
  8596. @State imagePathStr: string = ''
  8597. @State albumArtistStr: string = ''
  8598. @State composerStr: string = ''
  8599. @State lyricistStr: string = ''
  8600. @State commentStr: string = ''
  8601. @State discStr: string = ''
  8602. doUpdateData() {
  8603. setTimeout(async () => {
  8604. if (this.modeType === 0) {
  8605. this.deleteCache(this.currentPath)
  8606. await this.resetAndLoadFirstPage();
  8607. }else if (this.modeType === 1){
  8608. await this.resetAndLoadFirstPage();
  8609. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8610. }
  8611. }, 500)
  8612. }
  8613. doAllUpdateData() {
  8614. setTimeout(async () => {
  8615. if (this.modeType === 0) {
  8616. this.deleteCache(this.currentPath)
  8617. await this.resetAndLoadFirstPage();
  8618. }else{
  8619. await this.resetAndLoadFirstPage();
  8620. }
  8621. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8622. workerInstance.postMessage({ code: 3, data: this.context });
  8623. workerInstance.postMessage({ code: 4, data: this.context });
  8624. }, 999)
  8625. }
  8626. private delayMs(ms: number): Promise<void> {
  8627. return new Promise(resolve => {
  8628. setTimeout(() => resolve(), ms);
  8629. });
  8630. }
  8631. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  8632. if (!items || items.length === 0) {
  8633. return;
  8634. }
  8635. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  8636. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  8637. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  8638. if (!this.isScrolling || items.length <= directAppendThreshold) {
  8639. this.videoLocalList.push(...items);
  8640. this.dataSource.appendArrayData(items);
  8641. return;
  8642. }
  8643. const chunkSize = isHeavyGridWaterMode
  8644. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  8645. : (isMediaLibraryListMode
  8646. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  8647. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  8648. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  8649. for (let index = 0; index < items.length; index += chunkSize) {
  8650. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  8651. this.videoLocalList.push(...chunk);
  8652. this.dataSource.appendArrayData(chunk);
  8653. if (index + chunkSize < items.length) {
  8654. await this.delayMs(chunkDelay);
  8655. }
  8656. }
  8657. }
  8658. /**
  8659. * 加载指定页的数据
  8660. */
  8661. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  8662. try {
  8663. // 1. 检查缓存
  8664. if (this.pageCache.has(pageIndex)) {
  8665. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  8666. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8667. const cachedData = this.pageCache.get(pageIndex)!;
  8668. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  8669. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  8670. if (cachedHasMore !== undefined) {
  8671. this.hasMoreData = cachedHasMore;
  8672. }
  8673. if (cachedTotal !== undefined) {
  8674. this.totalCount = cachedTotal;
  8675. if (this.modeType === 1) {
  8676. this.mediaKuCount = cachedTotal;
  8677. }
  8678. }
  8679. if (append) {
  8680. this.prefetchListThumbsFromItems(cachedData, 26);
  8681. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8682. await this.appendItemsSmoothly(cachedData);
  8683. } else {
  8684. this.videoLocalList = cachedData;
  8685. this.dataSource.pushArrayData(this.videoLocalList);
  8686. if (inMediaLibraryWarmup) {
  8687. this.prefetchListThumbsFromItems(cachedData, 8);
  8688. } else {
  8689. this.prefetchListThumbsFromItems(cachedData, 30);
  8690. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8691. }
  8692. }
  8693. this.setButtonStatus();
  8694. if (inMediaLibraryWarmup) {
  8695. this.scheduleAlphaBetRebuild(900);
  8696. } else {
  8697. this.markAlphaBetDirty();
  8698. }
  8699. if (this.hasMoreData) {
  8700. if (inMediaLibraryWarmup) {
  8701. if (this.mediaLibraryWarmupPrefetchTimer) {
  8702. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8703. }
  8704. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8705. this.mediaLibraryWarmupPrefetchTimer = 0;
  8706. if (this.modeType === 1 && !this.isCanBack) {
  8707. this.prefetchFollowingPages(pageIndex + 1);
  8708. }
  8709. }, 900) as number;
  8710. } else {
  8711. this.prefetchFollowingPages(pageIndex + 1);
  8712. }
  8713. }
  8714. return;
  8715. }
  8716. this.isLoadingPage = true;
  8717. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  8718. // 2. 构造查询参数
  8719. const options: PageQueryOptions = {
  8720. pageIndex: pageIndex,
  8721. pageSize: this.pageSize,
  8722. sortType: this.sortType,
  8723. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8724. isShowFileName: this.isShowFileName
  8725. };
  8726. // 根据 modeType 补充查询条件
  8727. if (this.modeType === 0) {
  8728. options.parentPath = this.currentPath;
  8729. }
  8730. // 3. 执行查询
  8731. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8732. switch (this.modeType) {
  8733. case 0:
  8734. result = await this.table.queryByParentPathPaged(options);
  8735. result.items = this.filterOutLocalIsoItems(result.items);
  8736. // modeType=0时,第一页需要添加文件夹列表
  8737. if (pageIndex === 0 && !this.isSearchMode) {
  8738. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  8739. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  8740. result.items = [...directories, ...isoItems, ...result.items];
  8741. result.totalCount += directories.length + isoItems.length;
  8742. }
  8743. break;
  8744. case 1:
  8745. result = await this.table.queryMediaLibraryPaged(options);
  8746. break;
  8747. case 2:
  8748. result = await this.table.queryArtistsPaged(options);
  8749. break;
  8750. case 3:
  8751. result = await this.table.queryAlbumsPaged(options);
  8752. break;
  8753. default:
  8754. result = await this.table.queryMediaLibraryPaged(options);
  8755. break;
  8756. }
  8757. if (!result || result.items.length === 0) {
  8758. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  8759. this.isLoadingPage = false;
  8760. this.hasMoreData = false;
  8761. // 仅首页为空时清空,后续页为空只终止继续分页
  8762. if (pageIndex === 0) {
  8763. this.totalCount = 0;
  8764. this.videoLocalList = [];
  8765. this.dataSource.pushArrayData(this.videoLocalList);
  8766. this.setButtonStatus();
  8767. this.markAlphaBetDirty();
  8768. }
  8769. return;
  8770. }
  8771. // 4. 更新状态和缓存
  8772. this.totalCount = result.totalCount;
  8773. this.hasMoreData = result.hasMore;
  8774. if (this.modeType === 1) {
  8775. this.mediaKuCount = result.totalCount;
  8776. }
  8777. if (this.modeType === 2 && result.countMap) {
  8778. this.mergeArtistCountMap(result.countMap);
  8779. } else if (this.modeType === 3 && result.countMap) {
  8780. this.mergeAlbumCountMap(result.countMap);
  8781. }
  8782. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  8783. // 缓存管理 - 只保留最近3页
  8784. this.pageCache.set(pageIndex, result.items);
  8785. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  8786. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  8787. this.cleanOldCache(pageIndex);
  8788. // 5. 更新显示列表
  8789. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8790. if (append) {
  8791. this.prefetchListThumbsFromItems(result.items, 26);
  8792. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8793. await this.appendItemsSmoothly(result.items);
  8794. } else {
  8795. this.videoLocalList = result.items;
  8796. this.dataSource.pushArrayData(this.videoLocalList);
  8797. if (inMediaLibraryWarmup) {
  8798. this.prefetchListThumbsFromItems(result.items, 8);
  8799. } else {
  8800. this.prefetchListThumbsFromItems(result.items, 30);
  8801. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8802. }
  8803. }
  8804. this.setButtonStatus();
  8805. if (inMediaLibraryWarmup) {
  8806. this.scheduleAlphaBetRebuild(900);
  8807. } else {
  8808. this.markAlphaBetDirty();
  8809. }
  8810. if (inMediaLibraryWarmup) {
  8811. if (this.mediaLibraryWarmupPrefetchTimer) {
  8812. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8813. }
  8814. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8815. this.mediaLibraryWarmupPrefetchTimer = 0;
  8816. if (this.modeType === 1 && !this.isCanBack) {
  8817. this.prefetchFollowingPages(pageIndex + 1);
  8818. }
  8819. }, 900) as number;
  8820. } else {
  8821. this.prefetchFollowingPages(pageIndex + 1);
  8822. }
  8823. this.isLoadingPage = false;
  8824. } catch (err) {
  8825. const error = err as Error;
  8826. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  8827. // ToastUtil.showToast('加载数据失败');
  8828. this.isLoadingPage = false;
  8829. this.hasMoreData = false;
  8830. }
  8831. }
  8832. /**
  8833. * 清理旧缓存 - 只保留当前页前后各1页
  8834. */
  8835. private cleanOldCache(currentPage: number): void {
  8836. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  8837. const keysToDelete: number[] = [];
  8838. this.pageCache.forEach((_, page) => {
  8839. if (!pagesToKeep.has(page)) {
  8840. keysToDelete.push(page);
  8841. }
  8842. });
  8843. keysToDelete.forEach(page => {
  8844. this.pageCache.delete(page);
  8845. this.pageHasMoreCache.delete(page);
  8846. this.pageTotalCountCache.delete(page);
  8847. });
  8848. if (keysToDelete.length > 0) {
  8849. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  8850. }
  8851. }
  8852. private async prefetchNextPage(nextPage: number): Promise<void> {
  8853. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8854. return;
  8855. }
  8856. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  8857. return;
  8858. }
  8859. const expectedModeType = this.modeType;
  8860. const expectedSortType = this.sortType;
  8861. const expectedIsShowFileName = this.isShowFileName;
  8862. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  8863. const expectedParentPath = this.currentPath;
  8864. this.prefetchingPages.add(nextPage);
  8865. try {
  8866. const options: PageQueryOptions = {
  8867. pageIndex: nextPage,
  8868. pageSize: this.pageSize,
  8869. sortType: this.sortType,
  8870. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8871. isShowFileName: this.isShowFileName
  8872. };
  8873. if (this.modeType === 0) {
  8874. options.parentPath = this.currentPath;
  8875. }
  8876. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8877. switch (this.modeType) {
  8878. case 0:
  8879. result = await this.table.queryByParentPathPaged(options);
  8880. result.items = this.filterOutLocalIsoItems(result.items);
  8881. break;
  8882. case 1:
  8883. result = await this.table.queryMediaLibraryPaged(options);
  8884. break;
  8885. case 2:
  8886. result = await this.table.queryArtistsPaged(options);
  8887. if (result.countMap) {
  8888. this.mergeArtistCountMap(result.countMap);
  8889. }
  8890. break;
  8891. case 3:
  8892. result = await this.table.queryAlbumsPaged(options);
  8893. if (result.countMap) {
  8894. this.mergeAlbumCountMap(result.countMap);
  8895. }
  8896. break;
  8897. default:
  8898. result = await this.table.queryMediaLibraryPaged(options);
  8899. break;
  8900. }
  8901. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  8902. if (expectedModeType !== this.modeType ||
  8903. expectedSortType !== this.sortType ||
  8904. expectedIsShowFileName !== this.isShowFileName ||
  8905. expectedSearchKeyword !== currentSearchKeyword ||
  8906. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  8907. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  8908. return;
  8909. }
  8910. this.pageHasMoreCache.set(nextPage, result.hasMore);
  8911. this.pageTotalCountCache.set(nextPage, result.totalCount);
  8912. if (result.items.length > 0) {
  8913. this.pageCache.set(nextPage, result.items);
  8914. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  8915. this.cleanOldCache(nextPage);
  8916. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  8917. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  8918. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  8919. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  8920. Logger.info('heanup LocalMusic',
  8921. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  8922. this.scheduleLoadNextPage(8);
  8923. }
  8924. }
  8925. }
  8926. } catch (err) {
  8927. const error = err as Error;
  8928. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  8929. } finally {
  8930. this.prefetchingPages.delete(nextPage);
  8931. }
  8932. }
  8933. private mergeArtistCountMap(countMap: Map<string, number>): void {
  8934. const nextMap = new Map(this.artistSongCountMap);
  8935. countMap.forEach((count, artist) => {
  8936. nextMap.set(artist, count);
  8937. });
  8938. this.artistSongCountMap = nextMap;
  8939. }
  8940. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  8941. const nextMap = new Map(this.albumSongCountMap);
  8942. countMap.forEach((count, album) => {
  8943. nextMap.set(album, count);
  8944. });
  8945. this.albumSongCountMap = nextMap;
  8946. }
  8947. private getArtistSongCount(artist: string): number {
  8948. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  8949. }
  8950. private getAlbumSongCount(album: string): number {
  8951. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  8952. }
  8953. /**
  8954. * 加载文件夹列表(仅用于modeType=0的首页模式)
  8955. */
  8956. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  8957. try {
  8958. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  8959. // 检查缓存
  8960. const cacheKey = curPath + "_dirList";
  8961. const cachedDirList = this.findCache(cacheKey);
  8962. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  8963. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  8964. return cachedDirList as VideoItem[];
  8965. }
  8966. // 从文件系统读取
  8967. const fileList = FileUtil.listFileSync(curPath);
  8968. const directories: VideoItem[] = [];
  8969. for (let i = 0; i < fileList.length; i++) {
  8970. const path = curPath + '/' + fileList[i];
  8971. if (FileUtil.isDirectory(path)) {
  8972. const item: VideoItem = new VideoItem(
  8973. fileList[i].toString(),
  8974. fileList[i].toString(),
  8975. path,
  8976. CommonConstants.TYPE_IS_DIR,
  8977. 0,
  8978. ''
  8979. );
  8980. if (this.isShowDir(item.name)) {
  8981. directories.push(item);
  8982. }
  8983. }
  8984. }
  8985. // 排序
  8986. Utility.doSortListAscending(directories);
  8987. // 缓存文件夹列表
  8988. if (curPath === this.rootPath) {
  8989. this.dirList = directories;
  8990. this.addCache(cacheKey, directories);
  8991. }
  8992. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  8993. return directories;
  8994. } catch (err) {
  8995. const error = err as Error;
  8996. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  8997. return [];
  8998. }
  8999. }
  9000. /**
  9001. * 构建播放队列(避免一次性加载全量)
  9002. */
  9003. private buildPlayQueueFromView(): Array<VideoItem> {
  9004. if (this.modeType === 4) {
  9005. this.playQueueScope = 'playlist';
  9006. return this.currentSongList;
  9007. }
  9008. if (this.isHistory) {
  9009. this.playQueueScope = 'history';
  9010. return this.historyList;
  9011. }
  9012. if (this.isFavMusic) {
  9013. this.playQueueScope = 'fav';
  9014. return this.favList;
  9015. }
  9016. this.playQueueScope = 'view';
  9017. return Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  9018. }
  9019. private openSpecialLocalList(target: string): void {
  9020. this.mType = 0
  9021. this.isShowDrawer = false
  9022. this.offsetX = 0
  9023. this.isHistory = false
  9024. this.isFavMusic = false
  9025. if (target === 'recent') {
  9026. this.titleName = '最近播放'
  9027. this.currentTitleName = '最近播放'
  9028. this.currentTitleCover = $r('app.media.alt')
  9029. this.updateListData(this.historyList, true)
  9030. if (ArrayUtil.isNotEmpty(this.historyList)) {
  9031. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  9032. }
  9033. this.isHistory = true
  9034. return
  9035. }
  9036. if (target === 'favorite') {
  9037. this.titleName = '我的收藏'
  9038. this.currentTitleName = '我的收藏'
  9039. this.currentTitleCover = $r('app.media.alt')
  9040. this.updateListData(this.favList, true)
  9041. if (ArrayUtil.isNotEmpty(this.favList)) {
  9042. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  9043. }
  9044. this.isFavMusic = true
  9045. }
  9046. }
  9047. private async tryLoadNextPageForPlayback(): Promise<void> {
  9048. if (this.playQueueScope === 'find_paged_local') {
  9049. // 发现页的本地随机分页队列单独补页,不去动主媒体库列表状态。
  9050. await this.loadMoreFindPagedLocalSongs();
  9051. return;
  9052. }
  9053. if (this.playQueueScope !== 'view') {
  9054. return;
  9055. }
  9056. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  9057. return;
  9058. }
  9059. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9060. return;
  9061. }
  9062. await this.loadNextPage();
  9063. const nextList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  9064. if (nextList.length > this.songList.length) {
  9065. this.songList = nextList;
  9066. this.sonDataSource.pushArrayData(this.songList);
  9067. }
  9068. }
  9069. private async loadMoreFindPagedLocalSongs(): Promise<void> {
  9070. if (!this.findPagedLocalQueueHasMore || this.isLoadingFindPagedLocalQueue) {
  9071. return;
  9072. }
  9073. this.isLoadingFindPagedLocalQueue = true;
  9074. const nextPage = this.findPagedLocalQueuePageIndex + 1;
  9075. Logger.info(TAG,
  9076. `loadMoreFindPagedLocalSongs: page=${nextPage}, size=${this.findPagedLocalQueuePageSize}, ` +
  9077. `loaded=${this.songList.length}, total=${this.findPagedLocalQueueTotalCount}`);
  9078. try {
  9079. // 继续按发现页建立队列时的排序规则查询下一页,保证后续页和初始页顺序一致。
  9080. const result = await this.table.queryMediaLibraryPaged({
  9081. pageIndex: nextPage,
  9082. pageSize: this.findPagedLocalQueuePageSize,
  9083. sortType: this.findPagedLocalQueueSortType,
  9084. isShowFileName: this.isShowFileName
  9085. });
  9086. this.findPagedLocalQueuePageIndex = nextPage;
  9087. this.findPagedLocalQueueHasMore = result.hasMore;
  9088. if (result.totalCount > 0) {
  9089. this.findPagedLocalQueueTotalCount = result.totalCount;
  9090. this.totalCount = result.totalCount;
  9091. }
  9092. if (!result.items || result.items.length === 0) {
  9093. return;
  9094. }
  9095. const existingPaths = new Set(this.songList.map((item: VideoItem) => item.filePath));
  9096. // 随机播放过程中可能已经把“未加载页里的歌曲”临时插进队列,这里要去重后再追加。
  9097. const newItems = result.items.filter((item: VideoItem) => !existingPaths.has(item.filePath));
  9098. if (newItems.length === 0) {
  9099. return;
  9100. }
  9101. this.songList.push(...newItems);
  9102. this.currentSongList = this.songList;
  9103. this.sonDataSource.appendArrayData(newItems);
  9104. PreferencesUtil.putSync('LastMusicList', this.songList);
  9105. } catch (error) {
  9106. Logger.error(TAG, `loadMoreFindPagedLocalSongs failed: ${(error as Error).message}`);
  9107. } finally {
  9108. this.isLoadingFindPagedLocalQueue = false;
  9109. }
  9110. }
  9111. /**
  9112. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  9113. * 当播放列表弹窗滚动到底部时调用
  9114. */
  9115. private async loadMoreNavidromeSongs(): Promise<void> {
  9116. const beforeCount = this.songList.length;
  9117. const hasMore = hasMoreData();
  9118. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  9119. if (!hasMore) {
  9120. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  9121. return;
  9122. }
  9123. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  9124. const success = await triggerLoadMoreSongs(1);
  9125. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  9126. if (success) {
  9127. // 获取更新后的完整列表
  9128. const updatedList = getNavidromeVideoItems();
  9129. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  9130. if (updatedList.length > beforeCount) {
  9131. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  9132. this.songList = updatedList;
  9133. this.sonDataSource.pushArrayData(this.songList);
  9134. } else {
  9135. Logger.info('heanup', '列表长度未增加');
  9136. }
  9137. } else {
  9138. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  9139. }
  9140. }
  9141. /**
  9142. * 重置分页状态并加载首页
  9143. */
  9144. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  9145. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  9146. this.currentPage = 0;
  9147. if (clearExistingList) {
  9148. this.videoLocalList = [];
  9149. }
  9150. this.pageCache.clear();
  9151. this.pageHasMoreCache.clear();
  9152. this.pageTotalCountCache.clear();
  9153. this.prefetchingPages.clear();
  9154. this.hasMoreData = true;
  9155. this.totalCount = 0;
  9156. this.lastScrollTriggerPage = -1;
  9157. this.lastVisibleEndIndex = -1;
  9158. this.listScrollAlphaCheckAt = 0;
  9159. this.listScrollPagingCheckAt = 0;
  9160. this.listScrollLastAlphaStart = -1;
  9161. this.listScrollLastPagingEnd = -1;
  9162. this.gridScrollPagingCheckAt = 0;
  9163. this.gridScrollLastPagingEnd = -1;
  9164. this.waterScrollPagingCheckAt = 0;
  9165. this.waterScrollLastPagingEnd = -1;
  9166. this.listVisibleStart = -1;
  9167. this.listVisibleEnd = -1;
  9168. this.listThumbWarmupCheckAt = 0;
  9169. this.listThumbWarmupStart = -1;
  9170. this.listThumbWarmupEnd = -1;
  9171. this.gridThumbWarmupCheckAt = 0;
  9172. this.gridThumbWarmupStart = -1;
  9173. this.gridThumbWarmupEnd = -1;
  9174. this.waterThumbWarmupCheckAt = 0;
  9175. this.waterThumbWarmupStart = -1;
  9176. this.waterThumbWarmupEnd = -1;
  9177. this.gridVisibleStart = -1;
  9178. this.gridVisibleEnd = -1;
  9179. this.waterVisibleStart = -1;
  9180. this.waterVisibleEnd = -1;
  9181. this.gridWaterLastActiveTs = 0;
  9182. this.isPagingTransition = false;
  9183. if (this.pagingScheduleTimer) {
  9184. clearTimeout(this.pagingScheduleTimer);
  9185. this.pagingScheduleTimer = 0;
  9186. }
  9187. if (this.gridWaterScrollIdleTimer) {
  9188. clearTimeout(this.gridWaterScrollIdleTimer);
  9189. this.gridWaterScrollIdleTimer = 0;
  9190. }
  9191. this.coverThumbCache.clearPending();
  9192. this.pendingCoverThumbRefresh = false;
  9193. if (this.modeType === 2) {
  9194. this.artistSongCountMap = new Map();
  9195. } else if (this.modeType === 3) {
  9196. this.albumSongCountMap = new Map();
  9197. }
  9198. await this.loadPage(0, false);
  9199. }
  9200. private markGridWaterScrollingActive(): void {
  9201. if (!this.isScrolling) {
  9202. this.isScrolling = true;
  9203. }
  9204. const now = Date.now();
  9205. if (now - this.gridWaterLastActiveTs < 80) {
  9206. return;
  9207. }
  9208. this.gridWaterLastActiveTs = now;
  9209. if (this.gridWaterScrollIdleTimer) {
  9210. clearTimeout(this.gridWaterScrollIdleTimer);
  9211. }
  9212. this.gridWaterScrollIdleTimer = setTimeout(() => {
  9213. this.gridWaterScrollIdleTimer = 0;
  9214. if (this.isScrolling) {
  9215. this.isScrolling = false;
  9216. }
  9217. this.flushPendingCoverThumbRefresh();
  9218. }, 120);
  9219. }
  9220. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  9221. if (!this.autoHideTitle) {
  9222. return;
  9223. }
  9224. const now = Date.now();
  9225. if (now - this.titleBarLastCheckTs < 36) {
  9226. return;
  9227. }
  9228. this.titleBarLastCheckTs = now;
  9229. const delta = currentOffsetY - this.prevOffsetY;
  9230. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  9231. return;
  9232. }
  9233. if (delta > 0) {
  9234. if (this.isShowTitleBar) {
  9235. this.isShowTitleBar = false;
  9236. }
  9237. } else {
  9238. if (!this.isShowTitleBar) {
  9239. this.isShowTitleBar = true;
  9240. }
  9241. }
  9242. this.prevOffsetY = currentOffsetY;
  9243. }
  9244. private shouldPrefetchSecondPage(): boolean {
  9245. if (this.isMediaLibraryListMode()) {
  9246. return this.pageSize <= 120;
  9247. }
  9248. if (this.pageSize > 60) {
  9249. return false;
  9250. }
  9251. return this.isGridMusic || this.twoFingerType == 4;
  9252. }
  9253. private isMediaLibraryListMode(): boolean {
  9254. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  9255. }
  9256. private isMediaLibraryWarmupWindow(): boolean {
  9257. if (this.modeType !== 1 || this.isCanBack) {
  9258. return false;
  9259. }
  9260. if (this.mediaLibraryEnterTs <= 0) {
  9261. return false;
  9262. }
  9263. return Date.now() - this.mediaLibraryEnterTs < 1800;
  9264. }
  9265. private getDynamicPreloadStartRatio(): number {
  9266. if (this.twoFingerType == 4) {
  9267. return 0.10;
  9268. }
  9269. if (this.isGridMusic) {
  9270. return 0.14;
  9271. }
  9272. if (this.isMediaLibraryListMode()) {
  9273. return 0.12;
  9274. }
  9275. return this.preloadStartRatio;
  9276. }
  9277. private getDynamicAppendStartRatio(): number {
  9278. if (this.twoFingerType == 4) {
  9279. return 0.18;
  9280. }
  9281. if (this.isGridMusic) {
  9282. return 0.22;
  9283. }
  9284. if (this.isMediaLibraryListMode()) {
  9285. return 0.22;
  9286. }
  9287. return this.appendStartRatio;
  9288. }
  9289. private getDynamicEarlyAppendReserveCount(): number {
  9290. if (this.twoFingerType == 4) {
  9291. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9292. }
  9293. if (this.isGridMusic) {
  9294. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  9295. }
  9296. if (this.isMediaLibraryListMode()) {
  9297. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  9298. }
  9299. return this.earlyAppendReserveCount;
  9300. }
  9301. private prefetchFollowingPages(nextPage: number): void {
  9302. void this.prefetchNextPage(nextPage);
  9303. if (this.shouldPrefetchSecondPage()) {
  9304. void this.prefetchNextPage(nextPage + 1);
  9305. }
  9306. }
  9307. private scrollToTopForCurrentLayout(): void {
  9308. if (this.twoFingerType == 4) {
  9309. this.waterScroller.scrollEdge(Edge.Top);
  9310. this.scroller.scrollEdge(Edge.Top);
  9311. return;
  9312. }
  9313. if (this.isGridMusic) {
  9314. this.scroller.scrollEdge(Edge.Top);
  9315. return;
  9316. }
  9317. this.listScroller.scrollEdge(Edge.Top);
  9318. }
  9319. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  9320. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9321. if (coverVersion < -1) {
  9322. return fallback;
  9323. }
  9324. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9325. return fallback;
  9326. }
  9327. const sourceUri = item.pixelMapPath as string;
  9328. this.initCoverThumbCacheIfNeeded();
  9329. const targetSize = this.getListThumbTargetSize();
  9330. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9331. if (cachedThumb) {
  9332. return cachedThumb;
  9333. }
  9334. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9335. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  9336. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  9337. const isNearVisible = !hasRange ||
  9338. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  9339. if (isNearVisible) {
  9340. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9341. }
  9342. }
  9343. return sourceUri;
  9344. }
  9345. private getListThumbTargetSize(): number {
  9346. if (this.twoFingerType == 1) {
  9347. return 96;
  9348. }
  9349. if (this.twoFingerType == 2) {
  9350. return 112;
  9351. }
  9352. return 128;
  9353. }
  9354. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  9355. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  9356. return;
  9357. }
  9358. this.initCoverThumbCacheIfNeeded();
  9359. const targetSize = this.getListThumbTargetSize();
  9360. const maxCount = Math.min(limit, items.length);
  9361. for (let i = 0; i < maxCount; i++) {
  9362. const item = items[i];
  9363. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9364. continue;
  9365. }
  9366. const sourceUri = item.pixelMapPath as string;
  9367. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9368. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9369. }
  9370. }
  9371. }
  9372. private warmupListVisibleThumbs(start: number, end: number): void {
  9373. if (!this.isMediaLibraryListMode()) {
  9374. return;
  9375. }
  9376. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9377. return;
  9378. }
  9379. const now = Date.now();
  9380. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  9381. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  9382. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  9383. return;
  9384. }
  9385. this.listThumbWarmupCheckAt = now;
  9386. this.listThumbWarmupStart = start;
  9387. this.listThumbWarmupEnd = end;
  9388. this.initCoverThumbCacheIfNeeded();
  9389. const targetSize = this.getListThumbTargetSize();
  9390. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  9391. const begin = Math.max(0, start - 4);
  9392. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9393. for (let index = begin; index <= last; index++) {
  9394. const item = this.videoLocalList[index];
  9395. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9396. continue;
  9397. }
  9398. const sourceUri = item.pixelMapPath as string;
  9399. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9400. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9401. }
  9402. }
  9403. }
  9404. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  9405. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  9406. return;
  9407. }
  9408. this.initCoverThumbCacheIfNeeded();
  9409. const isWater = this.twoFingerType == 4;
  9410. const targetSize = this.getCoverThumbTargetSize(isWater);
  9411. const maxCount = Math.min(limit, items.length);
  9412. for (let i = 0; i < maxCount; i++) {
  9413. const item = items[i];
  9414. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9415. continue;
  9416. }
  9417. const sourceUri = item.pixelMapPath as string;
  9418. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9419. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9420. }
  9421. }
  9422. }
  9423. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  9424. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  9425. return;
  9426. }
  9427. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9428. return;
  9429. }
  9430. const now = Date.now();
  9431. let lastStart = -1;
  9432. let lastEnd = -1;
  9433. let lastCheckAt = 0;
  9434. if (isWater) {
  9435. lastStart = this.waterThumbWarmupStart;
  9436. lastEnd = this.waterThumbWarmupEnd;
  9437. lastCheckAt = this.waterThumbWarmupCheckAt;
  9438. } else {
  9439. lastStart = this.gridThumbWarmupStart;
  9440. lastEnd = this.gridThumbWarmupEnd;
  9441. lastCheckAt = this.gridThumbWarmupCheckAt;
  9442. }
  9443. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  9444. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  9445. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  9446. return;
  9447. }
  9448. if (isWater) {
  9449. this.waterThumbWarmupCheckAt = now;
  9450. this.waterThumbWarmupStart = start;
  9451. this.waterThumbWarmupEnd = end;
  9452. } else {
  9453. this.gridThumbWarmupCheckAt = now;
  9454. this.gridThumbWarmupStart = start;
  9455. this.gridThumbWarmupEnd = end;
  9456. }
  9457. this.initCoverThumbCacheIfNeeded();
  9458. const columns = isWater ? Math.max(this.columns, 1) :
  9459. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9460. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  9461. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  9462. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9463. const targetSize = this.getCoverThumbTargetSize(isWater);
  9464. for (let index = begin; index <= last; index++) {
  9465. const item = this.videoLocalList[index];
  9466. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9467. continue;
  9468. }
  9469. const sourceUri = item.pixelMapPath as string;
  9470. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9471. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9472. }
  9473. }
  9474. }
  9475. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  9476. coverVersion: number = 0): ResourceStr {
  9477. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9478. if (coverVersion < -1) {
  9479. return fallback;
  9480. }
  9481. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9482. return fallback;
  9483. }
  9484. const sourceUri = item.pixelMapPath as string;
  9485. this.initCoverThumbCacheIfNeeded();
  9486. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  9487. const targetSize = this.getCoverThumbTargetSize(isWater);
  9488. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9489. if (cachedThumb) {
  9490. return cachedThumb;
  9491. }
  9492. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  9493. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  9494. const columns = isWater ? Math.max(this.columns, 1) :
  9495. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9496. const preloadBuffer = Math.max(columns * 2, 8);
  9497. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  9498. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  9499. if (!isRemoteCover && isNearVisible) {
  9500. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9501. }
  9502. if (!this.isScrolling) {
  9503. return sourceUri;
  9504. }
  9505. if (isNearVisible) {
  9506. return sourceUri;
  9507. }
  9508. return fallback;
  9509. }
  9510. private flushPendingCoverThumbRefresh(): void {
  9511. if (!this.pendingCoverThumbRefresh) {
  9512. return;
  9513. }
  9514. this.pendingCoverThumbRefresh = false;
  9515. this.coverThumbVersion++;
  9516. }
  9517. private initCoverThumbCacheIfNeeded(): void {
  9518. if (this.coverThumbCacheReady) {
  9519. return;
  9520. }
  9521. this.coverThumbCache.setContext(this.context);
  9522. this.coverThumbCache.setOnThumbReady(() => {
  9523. if (this.isScrolling) {
  9524. this.pendingCoverThumbRefresh = true;
  9525. return;
  9526. }
  9527. this.coverThumbVersion++;
  9528. });
  9529. this.coverThumbCacheReady = true;
  9530. }
  9531. private getCoverThumbTargetSize(isWater: boolean): number {
  9532. if (isWater) {
  9533. if (this.columns >= 4) {
  9534. return 160;
  9535. }
  9536. if (this.columns == 3) {
  9537. return 200;
  9538. }
  9539. return 260;
  9540. }
  9541. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  9542. if (this.twoFingerType == 1) {
  9543. return baseSize;
  9544. }
  9545. if (this.twoFingerType == 2) {
  9546. return Math.floor(baseSize * 1.1);
  9547. }
  9548. return Math.floor(baseSize * 1.15);
  9549. }
  9550. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  9551. if (this.videoLocalList.length <= 0) {
  9552. return;
  9553. }
  9554. const columns = Math.max(this.columns, 1);
  9555. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  9556. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  9557. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  9558. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  9559. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  9560. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  9561. this.waterVisibleStart = startIndex;
  9562. this.waterVisibleEnd = estimatedEnd;
  9563. this.lastVisibleEndIndex = estimatedEnd;
  9564. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  9565. const now = Date.now();
  9566. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  9567. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  9568. this.waterScrollPagingCheckAt = now;
  9569. this.waterScrollLastPagingEnd = estimatedEnd;
  9570. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  9571. }
  9572. }
  9573. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  9574. if (this.modeType === 4) {
  9575. return;
  9576. }
  9577. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  9578. return;
  9579. }
  9580. if (this.isHistory || this.isFavMusic) {
  9581. return;
  9582. }
  9583. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9584. return;
  9585. }
  9586. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  9587. return;
  9588. }
  9589. const nextPage = this.currentPage + 1;
  9590. const next2Page = this.currentPage + 2;
  9591. const totalLoaded = this.videoLocalList.length;
  9592. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  9593. const remainCount = this.videoLocalList.length - endIndex - 1;
  9594. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  9595. const appendStartRatio = this.getDynamicAppendStartRatio();
  9596. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  9597. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  9598. if (seenRatio >= preloadStartRatio) {
  9599. if (!this.pageCache.has(nextPage)) {
  9600. void this.prefetchNextPage(nextPage);
  9601. }
  9602. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  9603. void this.prefetchNextPage(next2Page);
  9604. }
  9605. }
  9606. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  9607. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  9608. const shouldGapAppend = this.pageCache.has(nextPage) &&
  9609. seenRatio >= (appendStartRatio - 0.08) &&
  9610. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9611. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  9612. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  9613. return;
  9614. }
  9615. if (this.lastScrollTriggerPage === this.currentPage) {
  9616. return;
  9617. }
  9618. this.lastScrollTriggerPage = this.currentPage;
  9619. Logger.info('heanup LocalMusic',
  9620. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  9621. this.scheduleLoadNextPage(8);
  9622. }
  9623. private scheduleLoadNextPage(delayMs: number = 0): void {
  9624. if (this.pagingScheduleTimer) {
  9625. return;
  9626. }
  9627. this.pagingScheduleTimer = setTimeout(() => {
  9628. this.pagingScheduleTimer = 0;
  9629. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9630. return;
  9631. }
  9632. void this.loadNextPage();
  9633. }, delayMs);
  9634. }
  9635. /**
  9636. * 加载下一页
  9637. */
  9638. private async loadNextPage(): Promise<void> {
  9639. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9640. return;
  9641. }
  9642. this.isPagingTransition = true;
  9643. this.currentPage++;
  9644. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  9645. try {
  9646. await this.loadPage(this.currentPage, true);
  9647. } finally {
  9648. this.isPagingTransition = false;
  9649. }
  9650. }
  9651. //编辑信息
  9652. async doEdit(item: VideoItem) {
  9653. if (!item) {
  9654. return
  9655. }
  9656. if (StrUtil.isEmpty(this.titleStr)) {
  9657. ToastUtil.showToast('标题不能为空')
  9658. return
  9659. }
  9660. //内嵌音乐标签不能开启监听
  9661. // this.deletionWatcher?.stop();
  9662. this.loadingDialogId = DialogHelper.showLoadingDialog()
  9663. if (isRemoteCloudType(item.type)) {
  9664. await this.saveRemoteSongEdit(item);
  9665. return;
  9666. }
  9667. await PermissionUtil.activatePermission(item.filePath)
  9668. let tempOutPath = ''
  9669. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  9670. if(!item.filePath.toLowerCase().includes(this.packName)){
  9671. tempOutPath = this.currentPath + '/' + item.fileName
  9672. }
  9673. console.info('onecold tempOutPath ='+tempOutPath)
  9674. //用户更改了封面,那就内嵌下封面
  9675. if(StrUtil.isNotEmpty(this.imagePathStr)){
  9676. const resultCover:boolean = await changeMusicCover(this.context,
  9677. item.filePath,this.imagePathStr,true,tempOutPath);
  9678. this.imagePathStr = ''
  9679. if(resultCover){
  9680. ToastUtil.showToast('内嵌封面成功')
  9681. }
  9682. }
  9683. const metadata:FFMpegTags = {
  9684. title: this.titleStr,
  9685. artist: this.artistStr,
  9686. album: this.ablumStr,
  9687. TYER:this.yearStr,
  9688. genre:this.genreStr,
  9689. track:this.trackStr,
  9690. album_artist:this.albumArtistStr,
  9691. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  9692. COMPOSER:this.composerStr,
  9693. lyricist:this.lyricistStr,
  9694. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  9695. comment:this.commentStr,
  9696. disc:this.discStr,
  9697. };
  9698. let newInput = item.filePath
  9699. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  9700. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  9701. newInput = tempOutPath
  9702. tempOutPath = ''
  9703. }
  9704. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  9705. ||newInput.toLowerCase().endsWith('.ape')
  9706. ||newInput.toLowerCase().endsWith('.dsf')
  9707. ||newInput.toLowerCase().endsWith('.dff');
  9708. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  9709. const result:boolean = await repairAudioMetadata(
  9710. newInput,
  9711. this.lyricConStr,
  9712. metadata,
  9713. true,
  9714. tempOutPath
  9715. );
  9716. // ToastUtil.showToast('result ='+ result)
  9717. if (result||isWav) {
  9718. if(!item.filePath.includes(this.packName)){
  9719. //内嵌成功的歌路径如果不是包含包名,则要入库
  9720. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  9721. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  9722. this.table.insert(newItem, (id: number) => {
  9723. //加入数据库
  9724. if(this.modeType==0){
  9725. this.deleteCache(this.currentPath)
  9726. this.getSortedFiles(this.currentPath)
  9727. }
  9728. });
  9729. }
  9730. const task = new taskpool.Task(
  9731. updateInfoDb,
  9732. this.context,
  9733. item.filePath,
  9734. this.titleStr,
  9735. this.artistStr,
  9736. this.ablumStr,
  9737. this.lyricConStr,
  9738. this.yearStr,this.genreStr,
  9739. this.trackStr,this.albumArtistStr,
  9740. this.composerStr, this.lyricistStr,
  9741. this.commentStr,this.discStr
  9742. );
  9743. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  9744. if (result) {
  9745. console.log(" onecold 编辑信息成功,数据库已同步");
  9746. if(isWav){
  9747. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  9748. }else{
  9749. ToastUtil.showToast('内嵌音乐标签成功')
  9750. }
  9751. this.isShowMoreView = false
  9752. this.name = this.titleStr
  9753. this.syncEditedFields(item)
  9754. if (item.filePath == this.currentSong?.filePath) {
  9755. this.currentSong.name = this.titleStr
  9756. this.artist = this.artistStr
  9757. this.currentSong.artist = this.artistStr
  9758. this.currentSong.album = this.ablumStr
  9759. this.currentSong.year = this.yearStr
  9760. this.currentSong.genre = this.genreStr
  9761. this.currentSong.track = this.trackStr
  9762. this.currentSong.lyricContent = this.lyricConStr
  9763. this.currentSong.ALBUMARTIST = this.albumArtistStr
  9764. this.currentSong.COMPOSER = this.composerStr
  9765. this.currentSong.LYRICIST = this.lyricistStr
  9766. this.currentSong.COMMENT = this.commentStr
  9767. }
  9768. this.syncListsAfterEdit(item.filePath)
  9769. this.doUpateEditedFields(item)
  9770. //this.doUpdateData()
  9771. } else {
  9772. // ToastUtil.showToast('保存失败' + error?.toString())
  9773. console.error(" onecold 编辑信息数据库失败 ");
  9774. }
  9775. // 关闭进度条
  9776. DialogHelper.closeDialog(this.loadingDialogId)
  9777. }).catch((error: Error) => {
  9778. // 关闭进度条
  9779. DialogHelper.closeDialog(this.loadingDialogId)
  9780. console.error('onecold Subtitle sync failed:', error);
  9781. });
  9782. console.log(' onecold 元数据标签更新成功,');
  9783. } else {
  9784. // 关闭进度条
  9785. DialogHelper.closeDialog(this.loadingDialogId)
  9786. ToastUtil.showToast('内嵌音乐标签失败')
  9787. console.log('onecold 内嵌音乐标签失败');
  9788. }
  9789. this.longItemFilePath = ''
  9790. this.tempLyricContent = ''
  9791. this.isShowEdit = false
  9792. }
  9793. private normalizeEditedCoverPath(path: string): string {
  9794. if (StrUtil.isEmpty(path)) {
  9795. return '';
  9796. }
  9797. const lowerPath = path.toLowerCase();
  9798. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  9799. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  9800. return path;
  9801. }
  9802. return fileUri.getUriFromPath(path);
  9803. }
  9804. private emitRemoteMetadataUpdated(item: VideoItem): void {
  9805. if (!item || StrUtil.isEmpty(item.filePath)) {
  9806. return;
  9807. }
  9808. const payload: WebDavMetadataUpdatePayload = {
  9809. filePath: item.filePath,
  9810. pixelMapPath: item.pixelMapPath,
  9811. isCustomCover: item.isCustomCover,
  9812. md5Str: item.md5Str,
  9813. name: item.name,
  9814. artist: item.artist
  9815. };
  9816. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  9817. emitter.emit(eventUpdate, { data: [payload] });
  9818. }
  9819. private syncRemoteManagerSong(item: VideoItem): void {
  9820. if (!item || StrUtil.isEmpty(item.filePath)) {
  9821. return;
  9822. }
  9823. const remoteManager = RemoteDriveManager.getInstance();
  9824. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  9825. if (!target) {
  9826. return;
  9827. }
  9828. this.mergeVideoItemFromSource(target, item);
  9829. }
  9830. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  9831. try {
  9832. this.syncEditedFields(item);
  9833. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  9834. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  9835. item.isCustomCover = 1;
  9836. }
  9837. this.name = this.titleStr;
  9838. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  9839. this.syncEditedFields(this.currentSong);
  9840. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  9841. mergeCoverWithPriority(this.currentSong, item.pixelMapPath, item.isCustomCover ?? 0);
  9842. this.cover = this.currentSong.pixelMapPath || item.pixelMapPath;
  9843. }
  9844. this.artist = this.currentSong.artist ?? '';
  9845. this.currentSong = cloneVideoItem(this.currentSong);
  9846. AppStorage.setOrCreate('currentSong', this.currentSong);
  9847. }
  9848. this.syncListsAfterEdit(item.filePath);
  9849. this.syncRemoteManagerSong(item);
  9850. await this.persistRemoteMetadataToDb(item);
  9851. this.emitRemoteMetadataUpdated(item);
  9852. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  9853. } catch (error) {
  9854. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  9855. ToastUtil.showToast('网盘歌曲编辑失败');
  9856. } finally {
  9857. DialogHelper.closeDialog(this.loadingDialogId);
  9858. this.longItemFilePath = '';
  9859. this.tempLyricContent = '';
  9860. this.isShowEdit = false;
  9861. this.imagePathStr = '';
  9862. this.isShowMoreView = false;
  9863. }
  9864. }
  9865. // 内嵌标签更新当前内嵌的Item
  9866. async doUpateEditedFields(item: VideoItem) {
  9867. // 找到当前项在 videoLocalList 中的索引
  9868. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  9869. if (index !== -1) {
  9870. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  9871. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  9872. // 只有当查询结果不为 null 时才更新列表
  9873. if (updatedItem !== null) {
  9874. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  9875. this.videoLocalList = [
  9876. ...this.videoLocalList.slice(0, index),
  9877. updatedItem,
  9878. ...this.videoLocalList.slice(index + 1)
  9879. ];
  9880. // 同步更新 LazyDataSource
  9881. this.dataSource.pushArrayData(this.videoLocalList)
  9882. } else {
  9883. ToastUtil.showToast('未找到更新的数据');
  9884. }
  9885. }
  9886. DialogHelper.closeDialog(this.loadingDialogId)
  9887. }
  9888. @Builder
  9889. editSheet(item: VideoItem) {
  9890. Scroll() {
  9891. Column() {
  9892. this.editDetail(item)
  9893. }
  9894. }
  9895. .width('100%')
  9896. .height('100%')
  9897. }
  9898. @Builder
  9899. editDetail(item: VideoItem) {
  9900. Column() {
  9901. if (item) {
  9902. Row() {
  9903. Stack() {
  9904. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  9905. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  9906. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  9907. item.pixelMapPath)
  9908. .fillColor(this.themeColor)
  9909. .height(88)
  9910. .width(88)
  9911. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9912. .borderRadius(12)
  9913. .clip(true)
  9914. .opacity(this.opacityItem)// 绑定透明度
  9915. .margin({ left: 25 })
  9916. }
  9917. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9918. .onClick(async () => {
  9919. const imagePath:string | undefined = await this.goSelectImage(item);
  9920. if (imagePath) {
  9921. //用户更改过图片
  9922. this.imagePathStr = imagePath
  9923. }
  9924. })
  9925. .width('28%')
  9926. Row() {
  9927. Column() {
  9928. Text(item.name)
  9929. .fontSize(17)
  9930. .maxLines(1)
  9931. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9932. .animation({
  9933. duration: 555,
  9934. curve: 'Linear',
  9935. })
  9936. .fontColor(this.themeColor)
  9937. .margin({ left: 8 })
  9938. Row() {
  9939. Text(item.artist)
  9940. .fontSize(14)
  9941. .maxLines(1)
  9942. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9943. .padding({ top: 8 })
  9944. .fontColor(this.themeColor)
  9945. .margin({ left: 8 })
  9946. }
  9947. }
  9948. .height('100%')
  9949. .width(100)
  9950. .layoutWeight(1)
  9951. .justifyContent(FlexAlign.Center)
  9952. .alignItems(HorizontalAlign.Start)
  9953. Column() {
  9954. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9955. Row(){
  9956. SymbolGlyph($r('sys.symbol.picture'))
  9957. .fontSize(18)
  9958. .fontColor([Color.White])
  9959. Text('获取封面')
  9960. .margin({ left: 4 })
  9961. .fontSize(11)
  9962. .fontColor(Color.White)
  9963. .fontWeight(480)
  9964. .textAlign(TextAlign.Center)
  9965. }
  9966. .justifyContent(FlexAlign.Center)
  9967. }
  9968. .height(38)
  9969. .width(100)
  9970. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9971. .backgroundColor(this.themeColor)
  9972. .stateEffect(true)
  9973. .margin({ right: 35 })
  9974. .onClick(async () => {
  9975. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9976. this.showTipsDialog();
  9977. return; // Return empty string when no API is configured
  9978. }
  9979. const imagePath:string | undefined = await this.doSearchCover(item,
  9980. this.titleStr,this.artistStr);
  9981. console.info('onecold imagePath = '+imagePath)
  9982. if (StrUtil.isNotEmpty(imagePath)) {
  9983. //用户更改过图片
  9984. this.imagePathStr = imagePath
  9985. ToastUtil.showToast('获取封面成功')
  9986. }else{
  9987. ToastUtil.showToast('获取封面失败,请重试')
  9988. }
  9989. })
  9990. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9991. Row(){
  9992. SymbolGlyph($r('sys.symbol.input_mode'))
  9993. .fontSize(18)
  9994. .fontColor([Color.White])
  9995. Text('获取歌词')
  9996. .margin({ left: 4 })
  9997. .fontSize(11)
  9998. .fontColor(Color.White)
  9999. .fontWeight(480)
  10000. .textAlign(TextAlign.Center)
  10001. }
  10002. .justifyContent(FlexAlign.Center)
  10003. }
  10004. .height(38)
  10005. .width(100)
  10006. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10007. .backgroundColor(this.themeColor)
  10008. .stateEffect(true)
  10009. .margin({ top: 9, right: 35 })
  10010. .onClick(async () => {
  10011. //判断有没有设置api
  10012. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  10013. if (StrUtil.isEmpty(apiUrl)) {
  10014. this.isLyricSetting = false
  10015. this.showTipsDialog()
  10016. return
  10017. }
  10018. let res: string | undefined = await getApiLyric(apiUrl,
  10019. this.titleStr, this.artistStr, false);
  10020. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10021. this.lyricConStr = res;
  10022. ToastUtil.showToast('获取歌词成功')
  10023. }else{
  10024. ToastUtil.showToast('获取歌词失败,请重试')
  10025. }
  10026. })
  10027. }
  10028. .justifyContent(FlexAlign.Start)
  10029. }
  10030. .height('100%')
  10031. .justifyContent(FlexAlign.Start)
  10032. .layoutWeight(1)
  10033. }
  10034. .width('100%')
  10035. .height(98)
  10036. Row() {
  10037. Text('标题:')
  10038. .fontSize(14)
  10039. .fontColor($r('app.color.text_color'))
  10040. .margin({ left: 22 })
  10041. TextInput({ text: this.titleStr })
  10042. .height(40)
  10043. .maxLines(1)
  10044. .fontSize(14)
  10045. .layoutWeight(1)
  10046. .fontColor($r('app.color.text_color'))
  10047. .margin({ right: 15, left: 10 })
  10048. .onChange((val: string) => {
  10049. this.titleStr = val
  10050. })
  10051. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  10052. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10053. .backgroundColor(this.themeColor)
  10054. .fontSize(10)
  10055. .margin({ right: 20})
  10056. .onClick(async () => {
  10057. let hwTags = await extractHwMediaMetadata(item.filePath)
  10058. let artist = hwTags?.artist|| '';
  10059. let title = hwTags?.title|| '';
  10060. let album = hwTags?.album|| '';
  10061. console.info('onecold 乱码修正 artist='+artist);
  10062. console.info('onecold 乱码修正 title='+title);
  10063. console.info('onecold 乱码修正 album='+album);
  10064. this.titleStr = title;
  10065. this.artistStr = artist;
  10066. this.ablumStr = album;
  10067. })
  10068. }
  10069. .width('100%')
  10070. .margin({ top: 10, bottom: 10 })
  10071. .justifyContent(FlexAlign.Start)
  10072. Row() {
  10073. Text('艺术家:')
  10074. .fontSize(14)
  10075. .fontColor($r('app.color.text_color'))
  10076. .margin({ left: 22 })
  10077. TextInput({ text: this.artistStr })
  10078. .height(40)
  10079. .maxLines(1)
  10080. .fontSize(14)
  10081. .layoutWeight(1)
  10082. .fontColor($r('app.color.text_color'))
  10083. .margin({ right: 20, left: 10 })
  10084. .onChange((val: string) => {
  10085. this.artistStr = val
  10086. })
  10087. }
  10088. .width('100%')
  10089. .margin({ top: 10, bottom: 10 })
  10090. .justifyContent(FlexAlign.Start)
  10091. Row() {
  10092. Text('专辑名:')
  10093. .fontSize(14)
  10094. .fontColor($r('app.color.text_color'))
  10095. .margin({ left: 22 })
  10096. TextInput({ text: this.ablumStr})
  10097. .height(40)
  10098. .maxLines(1)
  10099. .fontSize(14)
  10100. .layoutWeight(1)
  10101. .fontColor($r('app.color.text_color'))
  10102. .margin({ right: 20, left: 10 })
  10103. .onChange((val: string) => {
  10104. this.ablumStr = val
  10105. })
  10106. }
  10107. .width('100%')
  10108. .margin({ top: 10, bottom: 10 })
  10109. .justifyContent(FlexAlign.Start)
  10110. Row() {
  10111. Column(){
  10112. Column(){
  10113. Text('歌词:')
  10114. .fontSize(14)
  10115. .fontColor($r('app.color.text_color'))
  10116. .margin({ top:9,left: 22 })
  10117. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10118. SymbolGlyph($r('sys.symbol.trash_fill'))
  10119. .fontSize(25)
  10120. .alignSelf(ItemAlign.Center)
  10121. .margin({ left: 22,top:25})
  10122. }
  10123. .backgroundColor(Color.Transparent)
  10124. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10125. Visibility.None:Visibility.Visible)
  10126. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10127. .onClick(()=>{
  10128. this.lyricConStr = ''
  10129. this.lyricContent = ''
  10130. this.tempLyricContent = ''
  10131. })
  10132. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10133. SymbolGlyph($r('sys.symbol.plus'))
  10134. .fontSize(25)
  10135. .alignSelf(ItemAlign.Center)
  10136. .margin({ left: 22,top:25})
  10137. }
  10138. .backgroundColor(Color.Transparent)
  10139. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10140. .onClick( ()=>{
  10141. this.callFilePickerSelectFileForLyric()
  10142. })
  10143. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10144. SymbolGlyph($r('sys.symbol.traditional_square'))
  10145. .fontSize(25)
  10146. .alignSelf(ItemAlign.Center)
  10147. .margin({ left: 22,top:25})
  10148. }
  10149. .backgroundColor(Color.Transparent)
  10150. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10151. Visibility.None:Visibility.Visible)
  10152. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10153. .onClick( ()=>{
  10154. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  10155. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  10156. })
  10157. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10158. Image($r('app.media.jianti'))
  10159. .height(25)
  10160. .fillColor($r('app.color.text_color'))
  10161. .alignSelf(ItemAlign.Center)
  10162. .margin({ left: 22,top:25})
  10163. }
  10164. .backgroundColor(Color.Transparent)
  10165. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  10166. Visibility.None:Visibility.Visible)
  10167. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10168. .onClick( ()=>{
  10169. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  10170. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  10171. })
  10172. }
  10173. .layoutWeight(1)
  10174. }
  10175. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  10176. this.tempLyricContent })
  10177. .type(TextAreaType.NORMAL)
  10178. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  10179. .fontSize(14)
  10180. .layoutWeight(1)
  10181. .fontColor($r('app.color.text_color'))
  10182. .margin({ right: 20, left: 10 })
  10183. .onChange((val: string) => {
  10184. this.lyricConStr = val
  10185. })
  10186. }
  10187. .width('100%')
  10188. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  10189. .margin({ top: 10, bottom: 10 })
  10190. .justifyContent(FlexAlign.Start)
  10191. Row() {
  10192. Text('年份:')
  10193. .fontSize(14)
  10194. .fontColor($r('app.color.text_color'))
  10195. .margin({ left: 22 })
  10196. TextInput({ text: item.year })
  10197. .height(40)
  10198. .maxLines(1)
  10199. .fontSize(14)
  10200. .type(InputType.Number)
  10201. .layoutWeight(1)
  10202. .fontColor($r('app.color.text_color'))
  10203. .margin({ right: 20, left: 10 })
  10204. .onChange((val: string) => {
  10205. this.yearStr = val
  10206. })
  10207. }
  10208. .width('100%')
  10209. .margin({ top: 10, bottom: 10 })
  10210. .justifyContent(FlexAlign.Start)
  10211. Row() {
  10212. Text('音轨号:')
  10213. .fontSize(14)
  10214. .fontColor($r('app.color.text_color'))
  10215. .margin({ left: 22 })
  10216. TextInput({ text:item.track=='未知'?'': item.track })
  10217. .height(40)
  10218. .maxLines(1)
  10219. .fontSize(14)
  10220. .type(InputType.Number)
  10221. .layoutWeight(1)
  10222. .fontColor($r('app.color.text_color'))
  10223. .margin({ right: 20, left: 10 })
  10224. .onChange((val: string) => {
  10225. this.trackStr = val
  10226. })
  10227. }
  10228. .width('100%')
  10229. .margin({ top: 10, bottom: 10 })
  10230. .justifyContent(FlexAlign.Start)
  10231. Row() {
  10232. Text('碟号:')
  10233. .fontSize(14)
  10234. .fontColor($r('app.color.text_color'))
  10235. .margin({ left: 22 })
  10236. TextInput({ text:item.disc })
  10237. .height(40)
  10238. .maxLines(1)
  10239. .fontSize(14)
  10240. .type(InputType.Number)
  10241. .layoutWeight(1)
  10242. .fontColor($r('app.color.text_color'))
  10243. .margin({ right: 20, left: 10 })
  10244. .onChange((val: string) => {
  10245. this.discStr = val
  10246. })
  10247. }
  10248. .width('100%')
  10249. .margin({ top: 10, bottom: 10 })
  10250. .justifyContent(FlexAlign.Start)
  10251. Row() {
  10252. Text('风格:')
  10253. .fontSize(14)
  10254. .fontColor($r('app.color.text_color'))
  10255. .margin({ left: 22 })
  10256. TextInput({ text: item.genre })
  10257. .height(40)
  10258. .maxLines(1)
  10259. .fontSize(14)
  10260. .layoutWeight(1)
  10261. .fontColor($r('app.color.text_color'))
  10262. .margin({ right: 20, left: 10 })
  10263. .onChange((val: string) => {
  10264. this.genreStr = val
  10265. })
  10266. }
  10267. .width('100%')
  10268. .margin({ top: 10, bottom: 10 })
  10269. .justifyContent(FlexAlign.Start)
  10270. Row() {
  10271. Text('专辑艺术家:')
  10272. .fontSize(14)
  10273. .fontColor($r('app.color.text_color'))
  10274. .margin({ left: 22 })
  10275. TextInput({ text: item.ALBUMARTIST })
  10276. .height(40)
  10277. .maxLines(1)
  10278. .fontSize(14)
  10279. .layoutWeight(1)
  10280. .fontColor($r('app.color.text_color'))
  10281. .margin({ right: 20, left: 10 })
  10282. .onChange((val: string) => {
  10283. this.albumArtistStr = val
  10284. })
  10285. }
  10286. .width('100%')
  10287. .margin({ top: 10, bottom: 10 })
  10288. .justifyContent(FlexAlign.Start)
  10289. Row() {
  10290. Text('作曲:')
  10291. .fontSize(14)
  10292. .fontColor($r('app.color.text_color'))
  10293. .margin({ left: 22 })
  10294. TextInput({ text: item.COMPOSER })
  10295. .height(40)
  10296. .maxLines(1)
  10297. .fontSize(14)
  10298. .layoutWeight(1)
  10299. .fontColor($r('app.color.text_color'))
  10300. .margin({ right: 20, left: 10 })
  10301. .onChange((val: string) => {
  10302. this.composerStr = val
  10303. })
  10304. }
  10305. .width('100%')
  10306. .margin({ top: 10, bottom: 10 })
  10307. .justifyContent(FlexAlign.Start)
  10308. Row() {
  10309. Text('作词:')
  10310. .fontSize(14)
  10311. .fontColor($r('app.color.text_color'))
  10312. .margin({ left: 22 })
  10313. TextInput({ text: item.LYRICIST })
  10314. .height(40)
  10315. .maxLines(1)
  10316. .fontSize(14)
  10317. .layoutWeight(1)
  10318. .fontColor($r('app.color.text_color'))
  10319. .margin({ right: 20, left: 10 })
  10320. .onChange((val: string) => {
  10321. this.lyricistStr = val
  10322. })
  10323. }
  10324. .width('100%')
  10325. .margin({ top: 10, bottom: 10 })
  10326. .justifyContent(FlexAlign.Start)
  10327. Row() {
  10328. Text('注释:')
  10329. .fontSize(14)
  10330. .fontColor($r('app.color.text_color'))
  10331. .margin({ left: 22 })
  10332. TextInput({ text: item.COMMENT })
  10333. .height(40)
  10334. .maxLines(1)
  10335. .fontSize(14)
  10336. .layoutWeight(1)
  10337. .fontColor($r('app.color.text_color'))
  10338. .margin({ right: 20, left: 10 })
  10339. .onChange((val: string) => {
  10340. this.commentStr = val
  10341. })
  10342. }
  10343. .width('100%')
  10344. .margin({ top: 10, bottom: 10 })
  10345. .justifyContent(FlexAlign.Start)
  10346. Row() {
  10347. Button('保存')
  10348. .fontColor(Color.White)
  10349. .layoutWeight(1)
  10350. .height(50)
  10351. .width(100)
  10352. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10353. .backgroundColor(this.themeColor)
  10354. .stateEffect(true)
  10355. .margin({ right: 20, bottom: 20 })
  10356. .onClick(async () => {
  10357. this.doEdit(item)
  10358. })
  10359. Button('取消')
  10360. .fontColor(Color.White)
  10361. .layoutWeight(1)
  10362. .height(50)
  10363. .width(100)
  10364. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10365. .backgroundColor(this.themeColor)
  10366. .stateEffect(true)
  10367. .margin({ left: 20, bottom: 20 })
  10368. .onClick(async () => {
  10369. if(this.isGridMusic){
  10370. this.longItemFilePath =''
  10371. }else{
  10372. this.isShowEdit = false
  10373. }
  10374. this.setEditStrEmpty()
  10375. if(this.isShowPlay){
  10376. this.isShowEdit = false
  10377. }
  10378. })
  10379. }
  10380. .margin({
  10381. left: 38,
  10382. right: 38,
  10383. top: 10,
  10384. bottom: 10
  10385. })
  10386. .width(250)
  10387. .height(60)
  10388. }
  10389. }
  10390. .margin({ bottom: 20 })
  10391. }
  10392. setEditStrEmpty(){
  10393. this.imagePathStr = ''
  10394. this.lyricConStr = ''
  10395. this.artistStr = ''
  10396. this.titleStr = ''
  10397. this.ablumStr = ''
  10398. this.genreStr = ''
  10399. this.yearStr = ''
  10400. this.trackStr = ''
  10401. this.albumArtistStr = ''
  10402. this.composerStr = ''
  10403. this.lyricistStr = ''
  10404. this.commentStr = ''
  10405. this.discStr = ''
  10406. }
  10407. initEditFields(item?: VideoItem) {
  10408. if (!item) {
  10409. this.setEditStrEmpty()
  10410. return
  10411. }
  10412. this.imagePathStr = ''
  10413. this.titleStr = item.name ?? ''
  10414. this.artistStr = item.artist ?? ''
  10415. this.ablumStr = item.album ?? ''
  10416. this.genreStr = item.genre ?? ''
  10417. this.yearStr = item.year ?? ''
  10418. this.trackStr = item.track ?? ''
  10419. this.albumArtistStr = item.ALBUMARTIST ?? ''
  10420. this.composerStr = item.COMPOSER ?? ''
  10421. this.lyricistStr = item.LYRICIST ?? ''
  10422. this.commentStr = item.COMMENT ?? ''
  10423. this.discStr = item.disc ?? ''
  10424. this.lyricConStr = item.lyricContent ?? ''
  10425. }
  10426. private syncEditedFields(target?: VideoItem) {
  10427. if (!target) {
  10428. return
  10429. }
  10430. target.name = this.titleStr
  10431. target.artist = this.artistStr
  10432. target.album = this.ablumStr
  10433. target.lyricContent = this.lyricConStr
  10434. target.year = this.yearStr
  10435. target.genre = this.genreStr
  10436. target.track = this.trackStr
  10437. target.ALBUMARTIST = this.albumArtistStr
  10438. target.COMPOSER = this.composerStr
  10439. target.LYRICIST = this.lyricistStr
  10440. target.COMMENT = this.commentStr
  10441. target.disc = this.discStr
  10442. }
  10443. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  10444. apply?: (next: Array<VideoItem>) => void) {
  10445. if (!list || ArrayUtil.isEmpty(list)) {
  10446. return
  10447. }
  10448. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  10449. if (index < 0) {
  10450. return
  10451. }
  10452. const nextList = [...list]
  10453. this.syncEditedFields(nextList[index])
  10454. apply?.(nextList)
  10455. }
  10456. private syncListsAfterEdit(filePath: string) {
  10457. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  10458. this.videoLocalList = next
  10459. this.dataSource.pushArrayData(next)
  10460. })
  10461. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  10462. this.songList = next
  10463. this.sonDataSource.pushArrayData(next)
  10464. })
  10465. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  10466. this.favList = next
  10467. })
  10468. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  10469. this.historyList = next
  10470. })
  10471. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  10472. this.currentSongList = next
  10473. })
  10474. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  10475. this.mediaKuList = next
  10476. })
  10477. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  10478. this.filteredList = next
  10479. })
  10480. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  10481. this.artistList = next
  10482. })
  10483. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  10484. this.albumList = next
  10485. })
  10486. this.listRefreshKey++
  10487. }
  10488. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  10489. if (!mainListUpdated && !playlistUpdated) {
  10490. return;
  10491. }
  10492. this.listRefreshKey++;
  10493. if (mainListUpdated) {
  10494. this.dataSource.notifyDataReload();
  10495. }
  10496. if (playlistUpdated) {
  10497. this.sonDataSource.notifyDataReload();
  10498. }
  10499. }
  10500. @Builder
  10501. detailSheet(item:VideoItem) {
  10502. Scroll() {
  10503. Column() {
  10504. this.songDetail(item)
  10505. }
  10506. }
  10507. .width('100%')
  10508. .height('100%')
  10509. }
  10510. @Builder
  10511. songDetail(currentItem:VideoItem) {
  10512. Column() {
  10513. if (currentItem) {
  10514. Row() {
  10515. Stack() {
  10516. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  10517. currentItem.pixelMapPath)
  10518. .fillColor(this.themeColor)
  10519. .height(80)
  10520. .width(80)
  10521. .borderRadius(10)
  10522. .opacity(this.opacityItem)// 绑定透明度
  10523. .margin({ left: 22 })
  10524. }
  10525. Column() {
  10526. Column() {
  10527. Text(currentItem.name)
  10528. .fontSize(16)
  10529. .maxLines(1)
  10530. .animation({
  10531. duration: 555,
  10532. curve: 'Linear',
  10533. })
  10534. .fontColor($r('app.color.text_color'))
  10535. .margin({ left: 15 })
  10536. }
  10537. .height('100%')
  10538. .width('100%')
  10539. .justifyContent(FlexAlign.Center)
  10540. .alignItems(HorizontalAlign.Start)
  10541. }
  10542. .height('100%')
  10543. }
  10544. .width('100%')
  10545. .height(90)
  10546. .justifyContent(FlexAlign.SpaceBetween)
  10547. Row() {
  10548. Text('艺术家:')
  10549. .fontSize(14)
  10550. .fontColor($r('app.color.text_color'))
  10551. .margin({ left: 22 })
  10552. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  10553. .fontSize(14)
  10554. .fontColor($r('app.color.text_color'))
  10555. .margin({ left: 10 })
  10556. .layoutWeight(1)
  10557. }
  10558. .width('100%')
  10559. .margin({ top: 10, bottom: 10 })
  10560. .justifyContent(FlexAlign.Start)
  10561. Row() {
  10562. Text('专辑名:')
  10563. .fontSize(14)
  10564. .fontColor($r('app.color.text_color'))
  10565. .margin({ left: 22 })
  10566. Text(currentItem?.album ?currentItem.album : '未知专辑')
  10567. .fontSize(14)
  10568. .margin({ left: 10 })
  10569. .fontColor($r('app.color.text_color'))
  10570. .layoutWeight(1)
  10571. }
  10572. .width('100%')
  10573. .margin({ top: 10, bottom: 10 })
  10574. .justifyContent(FlexAlign.Start)
  10575. Row() {
  10576. Text('时长:')
  10577. .fontSize(14)
  10578. .fontColor($r('app.color.text_color'))
  10579. .margin({ left: 22 })
  10580. Text(StrUtil.isEmpty(currentItem.duration)?
  10581. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  10582. .fontSize(14)
  10583. .margin({ left: 10 })
  10584. .fontColor($r('app.color.text_color'))
  10585. .layoutWeight(1)
  10586. }
  10587. .width('100%')
  10588. .margin({ top: 10, bottom: 10 })
  10589. .justifyContent(FlexAlign.Start)
  10590. Row() {
  10591. Text('采样率:')
  10592. .fontSize(14)
  10593. .fontColor($r('app.color.text_color'))
  10594. .margin({ left: 22 })
  10595. Text(Utility.convertToKHz(currentItem.sampleRate))
  10596. .fontSize(14)
  10597. .margin({ left: 10 })
  10598. .fontColor($r('app.color.text_color'))
  10599. .layoutWeight(1)
  10600. }
  10601. .width('100%')
  10602. .margin({ top: 10, bottom: 10 })
  10603. .justifyContent(FlexAlign.Start)
  10604. Row() {
  10605. Text('比特率:')
  10606. .fontSize(14)
  10607. .fontColor($r('app.color.text_color'))
  10608. .margin({ left: 22 })
  10609. Text(currentItem.bit_rate)
  10610. .fontSize(14)
  10611. .margin({ left: 10 })
  10612. .fontColor($r('app.color.text_color'))
  10613. .layoutWeight(1)
  10614. }
  10615. .width('100%')
  10616. .margin({ top: 10, bottom: 10 })
  10617. .justifyContent(FlexAlign.Start)
  10618. Row() {
  10619. Text('位深:')
  10620. .fontSize(14)
  10621. .fontColor($r('app.color.text_color'))
  10622. .margin({ left: 22 })
  10623. Text(`${currentItem.bits_per_raw_sample} bits`)
  10624. .fontSize(14)
  10625. .margin({ left: 10 })
  10626. .fontColor($r('app.color.text_color'))
  10627. .layoutWeight(1)
  10628. }
  10629. .width('100%')
  10630. .margin({ top: 10, bottom: 10 })
  10631. .justifyContent(FlexAlign.Start)
  10632. Row() {
  10633. Text('声道:')
  10634. .fontSize(14)
  10635. .fontColor($r('app.color.text_color'))
  10636. .margin({ left: 22 })
  10637. Text(`${currentItem.channels}`)
  10638. .fontSize(14)
  10639. .margin({ left: 10 })
  10640. .fontColor($r('app.color.text_color'))
  10641. .layoutWeight(1)
  10642. }
  10643. .width('100%')
  10644. .margin({ top: 10, bottom: 10 })
  10645. .justifyContent(FlexAlign.Start)
  10646. Row() {
  10647. Text('声道布局:')
  10648. .fontSize(14)
  10649. .fontColor($r('app.color.text_color'))
  10650. .margin({ left: 22 })
  10651. Text(`${currentItem.channel_layout}`)
  10652. .fontSize(14)
  10653. .margin({ left: 10 })
  10654. .fontColor($r('app.color.text_color'))
  10655. .layoutWeight(1)
  10656. }
  10657. .width('100%')
  10658. .margin({ top: 10, bottom: 10 })
  10659. .justifyContent(FlexAlign.Start)
  10660. Row() {
  10661. Text('起始播放点:')
  10662. .fontSize(14)
  10663. .fontColor($r('app.color.text_color'))
  10664. .margin({ left: 22 })
  10665. Text(`${currentItem.start_time}`)
  10666. .fontSize(14)
  10667. .margin({ left: 10 })
  10668. .fontColor($r('app.color.text_color'))
  10669. .layoutWeight(1)
  10670. }
  10671. .width('100%')
  10672. .margin({ top: 10, bottom: 10 })
  10673. .justifyContent(FlexAlign.Start)
  10674. Row() {
  10675. Text('风格:')
  10676. .fontSize(14)
  10677. .fontColor($r('app.color.text_color'))
  10678. .margin({ left: 22 })
  10679. Text(currentItem.genre)
  10680. .fontSize(14)
  10681. .margin({ left: 10 })
  10682. .fontColor($r('app.color.text_color'))
  10683. .layoutWeight(1)
  10684. }
  10685. .width('100%')
  10686. .margin({ top: 10, bottom: 10 })
  10687. .justifyContent(FlexAlign.Start)
  10688. Row() {
  10689. Text('发行时间:')
  10690. .fontSize(14)
  10691. .fontColor($r('app.color.text_color'))
  10692. .margin({ left: 22 })
  10693. Text(currentItem.year)
  10694. .fontSize(14)
  10695. .margin({ left: 10 })
  10696. .fontColor($r('app.color.text_color'))
  10697. .layoutWeight(1)
  10698. }
  10699. .width('100%')
  10700. .margin({ top: 10, bottom: 10 })
  10701. .justifyContent(FlexAlign.Start)
  10702. Row() {
  10703. Text('质量评分:')
  10704. .fontSize(14)
  10705. .fontColor($r('app.color.text_color'))
  10706. .margin({ left: 22 })
  10707. Text(currentItem.probe_score+"")
  10708. .fontSize(14)
  10709. .margin({ left: 10 })
  10710. .fontColor($r('app.color.text_color'))
  10711. .layoutWeight(1)
  10712. }
  10713. .width('100%')
  10714. .margin({ top: 10, bottom: 10 })
  10715. .justifyContent(FlexAlign.Start)
  10716. Row() {
  10717. Text('音轨号:')
  10718. .fontSize(14)
  10719. .fontColor($r('app.color.text_color'))
  10720. .margin({ left: 22 })
  10721. Text(currentItem.track)
  10722. .fontSize(14)
  10723. .margin({ left: 10 })
  10724. .fontColor($r('app.color.text_color'))
  10725. .layoutWeight(1)
  10726. }
  10727. .width('100%')
  10728. .margin({ top: 10, bottom: 10 })
  10729. .justifyContent(FlexAlign.Start)
  10730. Row() {
  10731. Text('碟号:')
  10732. .fontSize(14)
  10733. .fontColor($r('app.color.text_color'))
  10734. .margin({ left: 22 })
  10735. Text(currentItem.disc)
  10736. .fontSize(14)
  10737. .margin({ left: 10 })
  10738. .fontColor($r('app.color.text_color'))
  10739. .layoutWeight(1)
  10740. }
  10741. .width('100%')
  10742. .margin({ top: 10, bottom: 10 })
  10743. .justifyContent(FlexAlign.Start)
  10744. Row() {
  10745. Text('专辑艺术家:')
  10746. .fontSize(14)
  10747. .fontColor($r('app.color.text_color'))
  10748. .margin({ left: 22 })
  10749. Text(currentItem.ALBUMARTIST)
  10750. .fontSize(14)
  10751. .margin({ left: 10 })
  10752. .fontColor($r('app.color.text_color'))
  10753. .layoutWeight(1)
  10754. }
  10755. .width('100%')
  10756. .margin({ top: 10, bottom: 10 })
  10757. .justifyContent(FlexAlign.Start)
  10758. Row() {
  10759. Text('作曲家:')
  10760. .fontSize(14)
  10761. .fontColor($r('app.color.text_color'))
  10762. .margin({ left: 22 })
  10763. Text(currentItem.COMPOSER)
  10764. .fontSize(14)
  10765. .margin({ left: 10 })
  10766. .fontColor($r('app.color.text_color'))
  10767. .layoutWeight(1)
  10768. }
  10769. .width('100%')
  10770. .margin({ top: 10, bottom: 10 })
  10771. .justifyContent(FlexAlign.Start)
  10772. Row() {
  10773. Text('作词家:')
  10774. .fontSize(14)
  10775. .fontColor($r('app.color.text_color'))
  10776. .margin({ left: 22 })
  10777. Text(currentItem.LYRICIST)
  10778. .fontSize(14)
  10779. .margin({ left: 10 })
  10780. .fontColor($r('app.color.text_color'))
  10781. .layoutWeight(1)
  10782. }
  10783. .width('100%')
  10784. .margin({ top: 10, bottom: 10 })
  10785. .justifyContent(FlexAlign.Start)
  10786. Row() {
  10787. Text('注释:')
  10788. .fontSize(14)
  10789. .fontColor($r('app.color.text_color'))
  10790. .margin({ left: 22 })
  10791. Text(currentItem.COMMENT)
  10792. .fontSize(14)
  10793. .margin({ left: 10 })
  10794. .fontColor($r('app.color.text_color'))
  10795. .layoutWeight(1)
  10796. }
  10797. .width('100%')
  10798. .margin({ top: 10, bottom: 10 })
  10799. .justifyContent(FlexAlign.Start)
  10800. Row() {
  10801. Text('格式:')
  10802. .fontSize(14)
  10803. .fontColor($r('app.color.text_color'))
  10804. .margin({ left: 22 })
  10805. Text(Utility.formatMimeType(currentItem.mimeType))
  10806. .fontSize(14)
  10807. .margin({ left: 10 })
  10808. .fontColor($r('app.color.text_color'))
  10809. .layoutWeight(1)
  10810. }
  10811. .width('100%')
  10812. .margin({ top: 10, bottom: 10 })
  10813. .justifyContent(FlexAlign.Start)
  10814. Row() {
  10815. Text('播放次数:')
  10816. .fontSize(14)
  10817. .fontColor($r('app.color.text_color'))
  10818. .margin({ left: 22 })
  10819. Text(currentItem.playCount?.toString())
  10820. .fontSize(14)
  10821. .margin({ left: 10 })
  10822. .fontColor($r('app.color.text_color'))
  10823. .layoutWeight(1)
  10824. }
  10825. .width('100%')
  10826. .margin({ top: 10, bottom: 10 })
  10827. .justifyContent(FlexAlign.Start)
  10828. Row() {
  10829. Text('流数量:')
  10830. .fontSize(14)
  10831. .fontColor($r('app.color.text_color'))
  10832. .margin({ left: 22 })
  10833. Text(currentItem.nb_streams?.toString())
  10834. .fontSize(14)
  10835. .margin({ left: 10 })
  10836. .fontColor($r('app.color.text_color'))
  10837. .layoutWeight(1)
  10838. }
  10839. .width('100%')
  10840. .margin({ top: 10, bottom: 10 })
  10841. .justifyContent(FlexAlign.Start)
  10842. Row() {
  10843. Text('文件大小:')
  10844. .fontSize(14)
  10845. .fontColor($r('app.color.text_color'))
  10846. .margin({ left: 22 })
  10847. Text(currentItem.size)
  10848. .fontSize(14)
  10849. .margin({ left: 10 })
  10850. .fontColor($r('app.color.text_color'))
  10851. .layoutWeight(1)
  10852. }
  10853. .width('100%')
  10854. .margin({ top: 10, bottom: 10 })
  10855. .justifyContent(FlexAlign.Start)
  10856. Row() {
  10857. Text('文件名:')
  10858. .fontSize(14)
  10859. .fontColor($r('app.color.text_color'))
  10860. .margin({ left: 22 })
  10861. Text(currentItem.fileName)
  10862. .fontSize(14)
  10863. .margin({ left: 10 })
  10864. .fontColor($r('app.color.text_color'))
  10865. .layoutWeight(1)
  10866. }
  10867. .width('100%')
  10868. .margin({ top: 10, bottom: 10 })
  10869. .justifyContent(FlexAlign.Start)
  10870. Row() {
  10871. Text('修改时间:')
  10872. .fontSize(14)
  10873. .fontColor($r('app.color.text_color'))
  10874. .margin({ left: 22 })
  10875. Text(currentItem.cTime)
  10876. .fontSize(14)
  10877. .margin({ left: 10 })
  10878. .fontColor($r('app.color.text_color'))
  10879. .layoutWeight(1)
  10880. }
  10881. .width('100%')
  10882. .margin({ top: 10, bottom: 10 })
  10883. .justifyContent(FlexAlign.Start)
  10884. Row() {
  10885. Text('存放目录:')
  10886. .fontSize(14)
  10887. .fontColor($r('app.color.text_color'))
  10888. .margin({ left: 22 })
  10889. Text(currentItem.filePath)
  10890. .fontSize(12)
  10891. .margin({ left: 10 })
  10892. .fontColor($r('app.color.text_color'))
  10893. .layoutWeight(1)
  10894. }
  10895. .margin({ top: 10, bottom: 10 })
  10896. .width('100%')
  10897. .justifyContent(FlexAlign.Start)
  10898. Row() {
  10899. Text('内嵌歌词:')
  10900. .fontSize(14)
  10901. .fontColor($r('app.color.text_color'))
  10902. .margin({ left: 22 })
  10903. Text(currentItem.lyricContent)
  10904. .fontSize(12)
  10905. .copyOption(CopyOptions.InApp)
  10906. .margin({ left: 10 })
  10907. .fontColor($r('app.color.text_color'))
  10908. .layoutWeight(1)
  10909. }
  10910. .margin({ top: 10, bottom: 10 })
  10911. .width('100%')
  10912. .justifyContent(FlexAlign.Start)
  10913. }
  10914. }
  10915. .margin({ bottom: 20 })
  10916. }
  10917. //定时关闭布局
  10918. @Builder
  10919. TimeCloseSheet() {
  10920. Scroll() {
  10921. Column() {
  10922. this.TimeClose()
  10923. }
  10924. }
  10925. .width('100%')
  10926. .height('100%')
  10927. }
  10928. //倒计时关闭音乐,退出App功能实现。
  10929. @State selectedMinutes: number = 0 // 0表示未开启
  10930. @State remainingSeconds: number = 0
  10931. // 预设时间选项
  10932. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  10933. private formatTime(seconds: number): string {
  10934. const mins = Math.floor(seconds / 60)
  10935. const secs = seconds % 60
  10936. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  10937. }
  10938. // 开始倒计时
  10939. private handleTimeSelect(minutes: number) {
  10940. if (minutes === this.selectedMinutes) {
  10941. this.stopCountdown();
  10942. this.selectedMinutes = 0;
  10943. return;
  10944. }
  10945. this.selectedMinutes = minutes;
  10946. this.remainingSeconds = minutes * 60;
  10947. this.startCountdown(); // 新增调用
  10948. }
  10949. @Builder
  10950. TimeClose() {
  10951. Column() {
  10952. // 倒计时显示区域
  10953. Text(this.selectedMinutes > 0 ?
  10954. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  10955. "定时关闭未开启")
  10956. .fontSize(17)
  10957. .fontColor($r('app.color.text_color'))
  10958. .margin({ top: 2, bottom: 8 });
  10959. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10960. ForEach(this.presetTimes, (minutes: number, index: number) => {
  10961. // 单行时间选项容器
  10962. Row() {
  10963. // 文字描述区域
  10964. Text(this.getDisplayText(minutes))
  10965. .fontSize(15)
  10966. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  10967. $r('app.color.text_color'))// 选中态颜色变化
  10968. .textAlign(TextAlign.Start)
  10969. .layoutWeight(1); // 占据剩余空间
  10970. // 复选框样式的选择器
  10971. Row() {
  10972. if (minutes === this.selectedMinutes) {
  10973. // 选中状态 - 带勾号的圆形复选框
  10974. Row() {
  10975. // 使用系统内置的勾号图标
  10976. Image($r('sys.media.ohos_ic_public_ok'))
  10977. .width(14)
  10978. .height(14)
  10979. .fillColor(Color.White)
  10980. }
  10981. .width(24)
  10982. .height(24)
  10983. .borderRadius(12)
  10984. .backgroundColor(this.themeColor)
  10985. .justifyContent(FlexAlign.Center)
  10986. .alignItems(VerticalAlign.Center)
  10987. } else {
  10988. // 未选中状态的圆形边框
  10989. Row()
  10990. .width(24)
  10991. .height(24)
  10992. .borderRadius(12)
  10993. .border({
  10994. width: 2,
  10995. color: $r('app.color.text_color'),
  10996. style: BorderStyle.Solid
  10997. })
  10998. .backgroundColor(Color.Transparent)
  10999. }
  11000. }
  11001. .width(24)
  11002. .height(24)
  11003. .margin({ left: 20 })
  11004. .justifyContent(FlexAlign.Center)
  11005. .alignItems(VerticalAlign.Center)
  11006. }
  11007. .width('100%')
  11008. .padding({
  11009. top: 18,
  11010. bottom: 18,
  11011. left: 18,
  11012. right: 18
  11013. })
  11014. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  11015. $r('app.color.bottom_control_background')) // 选中背景高亮
  11016. .borderRadius(12)
  11017. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11018. .margin({ bottom: 18 })
  11019. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  11020. });
  11021. }
  11022. .width('100%')
  11023. .padding(16)
  11024. }
  11025. }
  11026. // 获取显示文本
  11027. private getDisplayText(minutes: number): string {
  11028. if (minutes === -1) {
  11029. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  11030. }
  11031. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  11032. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  11033. }
  11034. // 处理选择事件
  11035. private handleSelect(minutes: number): void {
  11036. if (minutes === -1) { // 自定义
  11037. // 弹出自定义时间对话框
  11038. DialogHelper.showTextInputDialog({
  11039. title: '自定义时间',
  11040. maskColor: Color.Transparent,
  11041. inputType: InputType.Number,
  11042. text: '',
  11043. onChange: (text) => {
  11044. console.error("onChange: " + text);
  11045. },
  11046. onAction: (action, dialogId, content) => {
  11047. if (action == DialogAction.TWO) {
  11048. const customMinutes = Number(content);
  11049. if (customMinutes > 0) {
  11050. this.handleTimeSelect(customMinutes); // 设置自定义时间
  11051. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  11052. }
  11053. }
  11054. }
  11055. });
  11056. } else {
  11057. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  11058. }
  11059. }
  11060. // 添加定时器引用
  11061. private timerId: number = -1;
  11062. // 启动/重置倒计时
  11063. private startCountdown() {
  11064. // 清除旧定时器
  11065. if (this.timerId !== -1) {
  11066. clearInterval(this.timerId);
  11067. }
  11068. // 创建新定时器
  11069. if (this.selectedMinutes > 0) {
  11070. this.timerId = setInterval(() => {
  11071. if (this.remainingSeconds === 15) {
  11072. this.showConfirmationDialog();
  11073. }
  11074. if (this.remainingSeconds > 0) {
  11075. this.remainingSeconds -= 1;
  11076. } else {
  11077. this.stopCountdown();
  11078. this.handleTimeout();
  11079. }
  11080. }, 1000);
  11081. }
  11082. }
  11083. // 15倒计时后再次提示显示确认是否关闭App对话框
  11084. private showConfirmationDialog() {
  11085. DialogHelper.showAlertDialog({
  11086. backgroundColor: $r('app.color.btn_green'),
  11087. title: '确认关闭',
  11088. maskColor: Color.Transparent,
  11089. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  11090. borderStyle: BorderStyle.Dashed,
  11091. primaryButton: '暂不关闭',
  11092. secondaryButton: '确定',
  11093. onAction: (action) => {
  11094. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  11095. this.stopCountdown();
  11096. this.selectedMinutes = 0
  11097. } else if (action == DialogAction.TWO) {
  11098. }
  11099. }
  11100. })
  11101. }
  11102. // 停止倒计时
  11103. private stopCountdown() {
  11104. if (this.timerId !== -1) {
  11105. clearInterval(this.timerId);
  11106. this.timerId = -1;
  11107. }
  11108. }
  11109. // 超时处理
  11110. private handleTimeout() {
  11111. // 执行播放器关闭逻辑
  11112. this.selectedMinutes = 0;
  11113. ToastUtil.showToast(" 定时关闭已完成");
  11114. this.stop(); // 假设存在的播放器实例
  11115. //退出APP
  11116. const mContext = getContext(this) as common.UIAbilityContext
  11117. mContext.terminateSelf();
  11118. AvSessionController.getInstance(true).unregisterSessionListener()
  11119. }
  11120. //倒计时关闭音乐,退出App功能实现结束。
  11121. //播放列表的拖动List 重新排序
  11122. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  11123. //左滑操作 移动文件 重命名 删除等操作
  11124. @Builder
  11125. sonButton(item: VideoItem, index: number, filePath: string) {
  11126. Row() {
  11127. //加入下一首播放
  11128. Button() {
  11129. Image($r('app.media.next_to_play'))
  11130. .fillColor(Color.White)
  11131. .width(20)
  11132. }
  11133. .width(40)
  11134. .height(40)
  11135. .type(ButtonType.Circle)
  11136. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11137. .backgroundColor(this.themeColor)
  11138. .margin(5)
  11139. .onClick(() => {
  11140. this.addToNextPlay(item);
  11141. })
  11142. Button() {
  11143. Image($r('app.media.close'))
  11144. .fillColor(Color.White)
  11145. .width(20)
  11146. }
  11147. .width(40)
  11148. .height(40)
  11149. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11150. .type(ButtonType.Circle)
  11151. .backgroundColor(this.themeColor)
  11152. .margin(5)
  11153. .onClick(() => {
  11154. this.songList.splice(Number(index), 1)
  11155. this.sonDataSource.pushArrayData(this.songList)
  11156. })
  11157. Button() {
  11158. Image($r('app.media.share2'))
  11159. .fillColor(Color.White)
  11160. .width(20)
  11161. }
  11162. .width(40)
  11163. .height(40)
  11164. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  11165. .type(ButtonType.Circle)
  11166. .backgroundColor(this.themeColor)
  11167. .margin(5)
  11168. .onClick(() => {
  11169. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11170. })
  11171. }
  11172. }
  11173. itemMoveSon(index: number, newIndex: number): void {
  11174. if (newIndex < 0 || newIndex >= this.songList.length) {
  11175. return;
  11176. }
  11177. let tmp = this.songList.splice(index, 1);
  11178. this.songList.splice(newIndex, 0, tmp[0]);
  11179. this.sonDataSource.pushArrayData(this.songList)
  11180. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  11181. if(this.modeType==4&&this.playlistTable){
  11182. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  11183. }
  11184. }
  11185. @Builder
  11186. PlayList() {
  11187. List({ scroller: this.playListScroller }) {
  11188. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  11189. ListItem() {
  11190. this.MusicItemSon(item, index)
  11191. }
  11192. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  11193. .animation({
  11194. duration: 666,
  11195. curve: 'ease-in-out' // 可选动画曲线
  11196. })
  11197. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  11198. // TransitionEffect.scale({ x: 0, y: 0 })))
  11199. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  11200. //拖动List关键代码开始
  11201. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  11202. .zIndex(this.dragItem === index ? 1 : 0)
  11203. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  11204. .gesture(
  11205. GestureGroup(GestureMode.Sequence,
  11206. LongPressGesture({ repeat: true })
  11207. .onAction((event?: GestureEvent) => {
  11208. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11209. this.scaleItem = index
  11210. })
  11211. })
  11212. .onActionEnd(() => {
  11213. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11214. this.scaleItem = -1
  11215. })
  11216. }),
  11217. PanGesture({ fingers: 1, direction: null, distance: 0 })
  11218. .onActionStart(() => {
  11219. this.dragItem = index // 记录当前拖动项索引
  11220. this.dragRefOffset = 0 // 重置偏移基准
  11221. })
  11222. .onActionUpdate((event: GestureEvent) => {
  11223. this.offsetY = event.offsetY - this.dragRefOffset;
  11224. this.neighborItem = -1;
  11225. let indexA = this.songList.indexOf(item);
  11226. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  11227. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  11228. let value: number = 0;
  11229. if (this.offsetY < 0) {
  11230. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  11231. this.neighborItem = indexA - 1;
  11232. this.neighborScale = 1 - value / 20;
  11233. } else if (this.offsetY > 0) {
  11234. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  11235. this.neighborItem = indexA + 1;
  11236. this.neighborScale = 1 - value / 20;
  11237. }
  11238. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  11239. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11240. this.offsetY -= this.ITEM_INTV;
  11241. this.dragRefOffset += this.ITEM_INTV;
  11242. this.itemMoveSon(indexA, indexA + 1);
  11243. });
  11244. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  11245. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11246. this.offsetY += this.ITEM_INTV;
  11247. this.dragRefOffset -= this.ITEM_INTV;
  11248. this.itemMoveSon(indexA, indexA - 1);
  11249. });
  11250. }
  11251. })
  11252. .onActionEnd((event: GestureEvent) => {
  11253. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11254. this.dragItem = -1
  11255. this.neighborItem = -1
  11256. })
  11257. animateTo({
  11258. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11259. }, () => {
  11260. this.scaleItem = -1
  11261. })
  11262. })
  11263. )
  11264. .onCancel(() => {
  11265. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11266. this.dragItem = -1
  11267. this.neighborItem = -1
  11268. })
  11269. animateTo({
  11270. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11271. }, () => {
  11272. this.scaleItem = -1
  11273. })
  11274. })
  11275. ) //拖动List关键代码结束
  11276. .onClick(() => {
  11277. this.doPlay(item, index, true)
  11278. })
  11279. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  11280. }
  11281. .width('100%')
  11282. .height('100%')
  11283. .onReachEnd(() => {
  11284. if(this.modeType === 4 && !this.isFindPagedLocalQueueActive())
  11285. return;
  11286. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  11287. const isStreamingSong = this.currentSong && (
  11288. isNavidromeType(this.currentSong.type) ||
  11289. isJellyfinType(this.currentSong.type) ||
  11290. isEmbyType(this.currentSong.type) ||
  11291. isAudioStationType(this.currentSong.type) ||
  11292. isPlexType(this.currentSong.type)
  11293. );
  11294. if (isStreamingSong && hasMoreData()) {
  11295. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  11296. void this.loadMoreNavidromeSongs();
  11297. } else {
  11298. void this.tryLoadNextPageForPlayback();
  11299. }
  11300. })
  11301. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11302. // .animation({ duration: 500, curve: Curve.Ease }))
  11303. .cachedCount(10)
  11304. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  11305. .gesture(PinchGesture({ fingers: 2 })
  11306. .onActionEnd((event: GestureEvent) => {
  11307. this.setSonListTwoFingers()
  11308. })
  11309. .onActionUpdate(e => {
  11310. this.scaleValue = this.pinchValue * e.scale
  11311. })
  11312. .onActionStart(e => {
  11313. }))
  11314. .padding({
  11315. bottom: 0
  11316. })
  11317. }
  11318. setSonListTwoFingers() {
  11319. this.pinchValue = this.scaleValue;
  11320. Logger.info('this.pinchValue = ' + this.pinchValue);
  11321. if (this.pinchValue >= 1) {
  11322. this.sonTwoFingerType++
  11323. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  11324. if (this.sonTwoFingerType > 3) {
  11325. this.sonTwoFingerType = 1
  11326. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  11327. }
  11328. } else {
  11329. this.sonTwoFingerType--
  11330. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  11331. if (this.sonTwoFingerType < 1) {
  11332. this.sonTwoFingerType = 1
  11333. }
  11334. }
  11335. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  11336. this.pinchValue = 1;
  11337. this.scaleValue = 1;
  11338. }
  11339. @State sonTwoFingerType:number = 3
  11340. @Builder
  11341. private MusicItemSon(item: VideoItem, index?: number) {
  11342. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11343. Row() {
  11344. Stack() {
  11345. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  11346. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11347. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11348. .alt($r('app.media.alt'))
  11349. .fillColor(this.themeColor)
  11350. .borderRadius(this.isCoverRectangle?11:'100%')
  11351. .clip(true)
  11352. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  11353. .draggable(false)// 禁止长按手势拖动
  11354. .autoResize(true) // 重采样,可减少内存占用
  11355. .margin({ left: 20 })
  11356. }
  11357. .width('15%')
  11358. Column() {
  11359. Column() {
  11360. Text(this.isShowFileName?item.fileName :item.name)
  11361. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  11362. .fontColor(this.curIndex === index ? this.themeColor :
  11363. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  11364. .maxLines(1)
  11365. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  11366. Row() {
  11367. Column(){
  11368. Text(item.md5Str?.includes('Lossless')?
  11369. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  11370. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  11371. .padding({ top: 3,right:6,left:6,bottom:3 })
  11372. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  11373. $r('app.color.text_color'))
  11374. .fontWeight(500)
  11375. .borderRadius(12)
  11376. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  11377. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  11378. .backgroundColor('#FFC107')
  11379. }
  11380. .padding({ top: 8 })
  11381. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  11382. item.artist + ' ' + item?.duration)
  11383. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11384. .padding({ top: 8 })
  11385. .maxLines(1)
  11386. .fontColor(this.curIndex === index ? this.themeColor :
  11387. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11388. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  11389. Blank()
  11390. Text(item.size)
  11391. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11392. .padding({ top: 8 })
  11393. .maxLines(1)
  11394. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  11395. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  11396. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11397. .margin({ left: 10 })
  11398. }
  11399. }
  11400. .height('100%')
  11401. .width('100%')
  11402. .justifyContent(FlexAlign.Center)
  11403. .alignItems(HorizontalAlign.Start)
  11404. }
  11405. .height('100%')
  11406. .width('65%')
  11407. Column() {
  11408. PlayingIndicator({
  11409. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  11410. indicatorSize: 18
  11411. })
  11412. }
  11413. .width('20%')
  11414. }
  11415. }
  11416. .backgroundColor(Color.Transparent)
  11417. .width('100%')
  11418. .reuseId('son_item')
  11419. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  11420. .shadow(this.scaleItem === index ? {
  11421. radius: 70,
  11422. color: '#15000000',
  11423. offsetX: 0,
  11424. offsetY: 0
  11425. } :
  11426. {
  11427. radius: 0,
  11428. color: '#15000000',
  11429. offsetX: 0,
  11430. offsetY: 0
  11431. })
  11432. .animation({ curve: Curve.Sharp, duration: 300 })
  11433. }
  11434. @Builder
  11435. private MusicPlayDismissProxyDot() {
  11436. Stack({ alignContent: Alignment.Center }) {
  11437. Image(StrUtil.isNotEmpty(this.cover) ? this.cover as string : $r('app.media.alt'))
  11438. .width('100%')
  11439. .height('100%')
  11440. .objectFit(ImageFit.Cover)
  11441. .alt($r('app.media.alt'))
  11442. }
  11443. .width(this.playDismissProxySize)
  11444. .height(this.playDismissProxySize)
  11445. .borderRadius(this.playDismissProxySize)
  11446. .clip(true)
  11447. .opacity(this.playDismissProxyOpacity)
  11448. .translate({ x: this.playDismissTranslateX, y: this.translateY })
  11449. .shadow({
  11450. radius: 18,
  11451. type: ShadowType.BLUR,
  11452. color: 'on_primary'
  11453. })
  11454. }
  11455. @Builder
  11456. MusicPlayBuilder() {
  11457. Column() {
  11458. this.IjkMusicPlayerView()
  11459. }
  11460. .transition(TransitionEffect.asymmetric(
  11461. TransitionEffect.opacity(1),
  11462. TransitionEffect.OPACITY
  11463. ))
  11464. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  11465. new hdsEffect.HdsEffectBuilder()
  11466. .shaderEffect({
  11467. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  11468. animation: {
  11469. duration: 10000,
  11470. iterations: -1,
  11471. autoPlay: true,
  11472. onFinish: ()=> {
  11473. console.info('Succeeded in finishing');
  11474. }
  11475. },
  11476. controller: this.bgController,
  11477. })
  11478. .buildEffect():null)
  11479. .height('100%')
  11480. .width('100%')
  11481. .onDisAppear(() => {
  11482. this.translateY = 0;
  11483. this.playDragUiOpacity = 1
  11484. })
  11485. .translate({ y: this.translateY })
  11486. .gesture(
  11487. PanGesture(this.panOption)
  11488. .onActionUpdate((event?: GestureEvent) => {
  11489. if (event) {
  11490. // 判断滑动方向
  11491. const offsetY = event.offsetY ?? 0;
  11492. const isSwipeUp = offsetY < 0;
  11493. if (isSwipeUp) {
  11494. // 向上滑动:不应用位移动画,保持 translateY = 0
  11495. this.translateY = 0;
  11496. this.scaleValueImage = 1
  11497. this.scaleValueText = 1
  11498. this.playDragUiOpacity = 1
  11499. } else {
  11500. if(this.isGeKongPlayNext){
  11501. return
  11502. }
  11503. // 向下滑动:应用位移动画
  11504. this.translateY = offsetY;
  11505. // 向下滑动时的缩放效果
  11506. this.getUIContext().animateTo({
  11507. duration: 500,
  11508. curve: Curve.Sharp
  11509. }, () => {
  11510. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - this.translateY / 880));
  11511. console.info('onecold scaleValueImage:', this.scaleValueImage)
  11512. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  11513. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  11514. })
  11515. }
  11516. }
  11517. })
  11518. .onActionEnd((event?: GestureEvent) => {
  11519. // 判断滑动方向
  11520. const offsetY = event?.offsetY ?? 0;
  11521. const isSwipeUp = offsetY < 0;
  11522. const minDistance = 300; // 最小滑动距离
  11523. const minVelocity = 500; // 最小滑动速度
  11524. const velocity = event?.velocityY ?? 0;
  11525. if (isSwipeUp) {
  11526. // 向上滑动:切换下一首
  11527. const shouldSwitch = this.isPlayPageSwipeNext &&
  11528. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  11529. if (shouldSwitch) {
  11530. // 直接切换下一首,无需动画(因为界面没有移动)
  11531. this.playbackController.playNext().catch(() => {
  11532. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  11533. });
  11534. }
  11535. } else {
  11536. //这里加个变量,是否开启隔空手势播放下一首
  11537. if(this.isGeKongPlayNext){
  11538. void this.playbackController.playNext()
  11539. return
  11540. }
  11541. // 向下滑动:关闭播放页
  11542. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  11543. if (shouldClose) {
  11544. // 添加关闭动画
  11545. this.getUIContext().animateTo({
  11546. duration: 600,
  11547. curve: Curve.Friction
  11548. }, () => {
  11549. this.isShowPlay = false;
  11550. this.scaleValueImage = 1
  11551. this.scaleValueText = 1
  11552. this.playDragUiOpacity = 1
  11553. this.translateY = 0;
  11554. })
  11555. } else {
  11556. // 回弹动画
  11557. this.getUIContext().animateTo({
  11558. duration: 600,
  11559. curve: Curve.Friction
  11560. }, () => {
  11561. this.scaleValueImage = 1
  11562. this.scaleValueText = 1
  11563. this.playDragUiOpacity = 1
  11564. this.translateY = 0;
  11565. })
  11566. }
  11567. }
  11568. })
  11569. )
  11570. }
  11571. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  11572. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  11573. HeightBreakpoint.HEIGHT_LG;
  11574. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  11575. @State topBarHeight: number = 50
  11576. @State barOpacity: number = 1
  11577. @State barBottomOpacity: number = 1
  11578. private hideDone: boolean = false;
  11579. @State currentYOffset: number = 0;
  11580. @State bottomBarHeight: number = 68;
  11581. private isHiding: boolean = false;
  11582. //是否是Pura X外屏,或者小屏幕
  11583. isPuraWP() {
  11584. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  11585. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  11586. }
  11587. //是否是Pura X外屏,或者小屏幕,手机横屏
  11588. /**
  11589. * 是否是Pura X外屏,或者小屏幕,手机横屏
  11590. * @returns
  11591. */
  11592. isCoverOpacity() {
  11593. if (this.isPuraWP()) {
  11594. return true
  11595. }
  11596. if (this.isPhoneLan()) {
  11597. return true
  11598. }
  11599. if (deviceInfo.marketName.includes('Pura X')
  11600. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  11601. return true
  11602. }
  11603. return false
  11604. }
  11605. //是不是手机横屏
  11606. isPhoneLan() {
  11607. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  11608. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  11609. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  11610. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  11611. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  11612. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  11613. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  11614. if (this.isHiCarKuanBianPing()) {
  11615. return true
  11616. }
  11617. if (this.isHiCar()) {
  11618. return false
  11619. }
  11620. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11621. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  11622. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  11623. return true
  11624. }
  11625. return false
  11626. }
  11627. //是不是1920x720的hicar的屏幕分辨率
  11628. isHiCarKuanBianPing(){
  11629. // if(!this.isHiCar()){
  11630. // return false
  11631. // }
  11632. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11633. { ratio: 1920 / 720, name: "1920x720" },
  11634. ];
  11635. const currentRatio: number = this.windowWidth / this.windowHeight;
  11636. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11637. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  11638. for (const hiCarRatio of hiCarAspectRatios) {
  11639. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  11640. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11641. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11642. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11643. //宽扁平的尺寸设置列表展示
  11644. this.twoFingerType ==3
  11645. this.isGridMusic = false
  11646. return true;
  11647. }
  11648. }
  11649. return false;
  11650. }
  11651. //是不是hicar的屏幕分辨率
  11652. isHiCarSmall() {
  11653. if(!this.isHiCar()){
  11654. return false
  11655. }
  11656. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  11657. {
  11658. this.columns = 6
  11659. return false
  11660. }
  11661. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11662. { ratio: 800 / 480, name: "800x480" },
  11663. { ratio: 1280 / 720, name: "1280x720" },
  11664. { ratio: 1920 / 1080, name: "1920x1080" },
  11665. ];
  11666. const currentRatio: number = this.windowWidth / this.windowHeight;
  11667. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11668. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  11669. for (const hiCarRatio of hiCarAspectRatios) {
  11670. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  11671. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11672. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  11673. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11674. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11675. //宽扁平的尺寸设置列表展示
  11676. return true;
  11677. }
  11678. }
  11679. return false;
  11680. }
  11681. isHiCar(): boolean {
  11682. return this.curDisplayIsHiCar;
  11683. }
  11684. //是不是正常的手机竖屏
  11685. isPhonePortrait() {
  11686. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  11687. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  11688. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  11689. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11690. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  11691. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  11692. return true
  11693. }
  11694. return false
  11695. }
  11696. @State showSpeedDialog: boolean = false
  11697. @State longPressSpeed: number = 3 //长按默认倍数
  11698. @Builder
  11699. SpeedDialog() {
  11700. Stack() {
  11701. Column() {
  11702. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11703. .fontColor(Color.White)
  11704. .visibility(Visibility.Hidden)
  11705. }
  11706. .backgroundColor(Color.Black)
  11707. .borderRadius(20)
  11708. .padding({
  11709. top: 10,
  11710. right: 20,
  11711. left: 15,
  11712. bottom: 20
  11713. })
  11714. .opacity(0.6)
  11715. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11716. .fontColor(Color.White)
  11717. }
  11718. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  11719. .zIndex(5)
  11720. .margin({ top: 80 })
  11721. }
  11722. @Builder
  11723. IjkMusicPlayerView() {
  11724. Stack() {
  11725. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  11726. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  11727. HdsVisualComponent()
  11728. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  11729. console.info('Succeeded in finishing');
  11730. })
  11731. .width('100%')
  11732. .height('100%')
  11733. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  11734. }
  11735. Column() {
  11736. Column() {
  11737. //播放标题
  11738. Column() {
  11739. this.PlayTitle()
  11740. }
  11741. .opacity(this.playDragUiOpacity)
  11742. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 40 })
  11743. .width('100%')
  11744. .margin({ top: 0 })
  11745. .height(PlayConstants.HEIGHT)
  11746. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  11747. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  11748. if (this.showSpeedDialog) {
  11749. this.SpeedDialog()
  11750. }
  11751. Stack() {
  11752. //手势拖动快进
  11753. Column()
  11754. .width(CommonConstants.FULL_PERCENT)
  11755. .height('100%')
  11756. .gesture(
  11757. GestureGroup(GestureMode.Parallel,
  11758. // 长按屏幕倍数播放
  11759. LongPressGesture({ repeat: true })
  11760. .onAction(() => {
  11761. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11762. this.showSpeedDialog = true;
  11763. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  11764. }
  11765. })
  11766. .onActionEnd(() => {
  11767. this.showSpeedDialog = false;
  11768. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11769. }),
  11770. )
  11771. )
  11772. }
  11773. .height('65%')
  11774. Swiper() {
  11775. this.CoverInfo()
  11776. this.PlayerLyrics()
  11777. }
  11778. .onChange((index: number) => {
  11779. this.currentSwiperIndex = index
  11780. if (index === 1) {
  11781. this.syncLyricPositionNow()
  11782. }
  11783. })
  11784. .indicator(false)
  11785. .displayCount(this.getPlayerSwiperDisplayCount())
  11786. .clip(false)
  11787. .loop(false)
  11788. .autoPlay(false)
  11789. // .interval(8000)
  11790. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  11791. .height('100%')
  11792. .hitTestBehavior(HitTestMode.Transparent)
  11793. Image($r('app.media.icon_replay'))
  11794. .objectFit(ImageFit.Auto)
  11795. .width('120px')
  11796. .height('120px')
  11797. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  11798. .border({ width: 0 })
  11799. .visibility(Visibility.None)
  11800. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  11801. .onClick(() => {
  11802. console.info('onecold startPlayOrResumePlay 6744')
  11803. this.startPlayOrResumePlay();
  11804. })
  11805. }
  11806. .width(CommonConstants.FULL_PERCENT)
  11807. .height(CommonConstants.FULL_PERCENT)
  11808. .justifyContent(FlexAlign.End)
  11809. }
  11810. .justifyContent(FlexAlign.End)
  11811. .margin({ bottom: 5 })
  11812. }
  11813. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  11814. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  11815. .animation({
  11816. duration: 666,
  11817. curve: 'ease-in-out' // 可选动画曲线
  11818. })
  11819. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  11820. ? BlurStyle.NONE :
  11821. BlurStyle.BACKGROUND_ULTRA_THICK)
  11822. .hitTestBehavior(HitTestMode.Transparent)
  11823. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  11824. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  11825. .onClick(() => {
  11826. if(this.isHiCar())
  11827. return
  11828. if(this.is_auto_hide_progress){
  11829. this.is_auto_hide_progress = false
  11830. }
  11831. this.startAutoHide()
  11832. })
  11833. }
  11834. @StorageLink('progressValue') progressValue: number = 0;
  11835. @State currentTime: string = "00:00";
  11836. @State totalTime: string = "00:00";
  11837. @State loadingVisible: Visibility = Visibility.None;
  11838. @State replayVisible: Visibility = Visibility.None;
  11839. @State slideEnable: boolean = false;
  11840. @State aspRatio: number = 0.5;
  11841. @State mContext: object | undefined = undefined;
  11842. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  11843. @State mFirst: boolean = true;
  11844. @State mDestroyPage: boolean = false;
  11845. @State playSpeed: number = 1;
  11846. @State oldSeconds: number = 0;
  11847. @State isSeekTo: boolean = false;
  11848. @State isCurrentTime: boolean = false;
  11849. @State videoWidth: string = '100%';
  11850. @State videoHeight: string = '100%';
  11851. @State initAspectRatio: number = 1;
  11852. @State videoAspectRatio: number = this.initAspectRatio;
  11853. @State videoUrl: string = '';
  11854. private last: number = 0;
  11855. @State videoParentAspectRatio: number = this.initAspectRatio;
  11856. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  11857. @StorageLink('CONTROL_PlayStatus') CONTROL_PlayStatus: number = PlayStatus.INIT;
  11858. @State PROGRESS_MAX_VALUE: number = 100;
  11859. @State updateProgressTimer: number = 0;
  11860. private readonly progressUpdateIntervalMs: number = 120;
  11861. private readonly lyricUpdateMinDeltaMs: number = 24;
  11862. private lastLyricRenderPosition: number = Number.NaN;
  11863. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  11864. @State name: string = '';
  11865. // @State loop: boolean = false;
  11866. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  11867. @State multiple: string = '1.0X';
  11868. xcomponentController: XComponentController = new XComponentController()
  11869. private panOptionBright: PanGestureOptions =
  11870. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  11871. private panOptionVolume: PanGestureOptions =
  11872. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  11873. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  11874. //手势的音量控制和亮度控制
  11875. private positionX: number = PlayConstants.POSITION_X;
  11876. private positionY: number = PlayConstants.POSITION_Y;
  11877. private windowClass: window.Window = globalThis.windowClass
  11878. @State volume: number = 0.8;
  11879. @State volumeBoostPercent: number = 0
  11880. @State volumeSmall: boolean = false
  11881. @State autoParseMusicName: boolean = true
  11882. @State isShowFileName: boolean = false
  11883. @State isLongNameRoLL: boolean = true//长歌名滚动
  11884. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  11885. private readonly volumeBoostMaxPercent: number = 500;
  11886. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  11887. @State bright: number = PlayConstants.BRIGHT;
  11888. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  11889. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  11890. @State screenWidth: number = 0
  11891. @State screenHeight: number = 0
  11892. @State statusBarHeight: number = 0
  11893. @State isYesFull: boolean = false
  11894. private seekValue: number = 0
  11895. @State isVideoLock: boolean = false; // Whether the video playback is locked
  11896. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  11897. private playbackUrlRequestSerial: number = 0;
  11898. eventHub = getContext().eventHub;
  11899. private isAppForeground: boolean = true;
  11900. private lastBufferingLogTs: number = 0;
  11901. private readonly bufferingLogIntervalMs: number = 5000;
  11902. //投播组件
  11903. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  11904. // 新的投播控制器(封装了官方示例的逻辑)
  11905. private castControllerWrapper: CastController | undefined = undefined;
  11906. // 保留原始的 avCastController 引用(用于兼容旧代码)
  11907. private castController: avSession.AVCastController | undefined = undefined;
  11908. @State isCastPlaying: boolean = false;
  11909. @State currentTime2: number = 0;
  11910. @State currentStringTime: string = '00:00';
  11911. @State duration: number = 0;
  11912. @State isReady: boolean = false;
  11913. @State durationTime: number = 0;
  11914. @State durationStringTime: string = '00:00';
  11915. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  11916. // @State isPlaying: boolean = false;
  11917. private castSeek: boolean = false;
  11918. private castItem: avSession.AVQueueItem | undefined = undefined;
  11919. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  11920. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  11921. @State rotateAngle2: number = -9
  11922. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  11923. @StorageLink('cover') cover: string | undefined = '';
  11924. @State artist: string | undefined = ''
  11925. // 1.初始化controller
  11926. private lyricController: LyricController = new LyricController()
  11927. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  11928. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  11929. private parser = new LyricParser()
  11930. @State randomShakenX: number = 0
  11931. @State randomShakenY: number = 0
  11932. @State lyricTextSize: number = 24
  11933. @State lyricContent: string = ''
  11934. @State isDebug: boolean = false
  11935. @State isHightLightCenter: boolean = true
  11936. private syncWordByWordLyricMode(): void {
  11937. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11938. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11939. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11940. }
  11941. private syncLyricLightTextMode(): void {
  11942. this.lyricController.setLightText(this.isLightText)
  11943. this.lyricControllerXF.setLightText(this.isLightText)
  11944. this.lyricControllerSingle.setLightText(this.isLightText)
  11945. }
  11946. /**
  11947. * 初始化歌词加载与展示逻辑
  11948. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  11949. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  11950. * @param isApi2 是否使用API2获取歌词(可选)
  11951. *
  11952. * 主要流程:
  11953. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  11954. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  11955. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  11956. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  11957. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  11958. * 6. 解析失败或读取失败时,清空歌词显示。
  11959. *
  11960. * 注意事项:
  11961. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  11962. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  11963. * - 歌词内容解析后通过lyricController驱动UI渲染。
  11964. */
  11965. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  11966. if (StrUtil.isEmpty(lyricPath)) {
  11967. return
  11968. }
  11969. this.syncWordByWordLyricMode()
  11970. this.syncLyricLightTextMode()
  11971. this.initPipLyricSetting()
  11972. this.lyricControllerSingle
  11973. .setTextSize(15)
  11974. .setCacheSize(4)
  11975. .setTextColor("#FFFFFF")
  11976. .setHighlightColor(this.currentHighLightLyricColor)
  11977. .setHighlightScale(1.2)
  11978. .setEmptyHint("")
  11979. .setLineSpace(1)
  11980. .setAlignMode('center')
  11981. .setAnimationDuration(500)
  11982. .setSingleLine(true)
  11983. this.lyricContent = ''
  11984. this.lyricController
  11985. .setTextSize(this.currentLyricSize)
  11986. .setCacheSize(4)
  11987. .setTextColor("#DDDDDD")
  11988. .setHighlightColor("#FFFFFF")
  11989. .setEmptyHint("")
  11990. .setAnimationDuration(1000)
  11991. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  11992. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  11993. this.setBlurDegree(this.blurDegree, false)
  11994. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  11995. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  11996. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  11997. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  11998. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  11999. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  12000. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  12001. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  12002. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  12003. this.lyricController.setTextWeight(this.lyricTextWeight)
  12004. this.showSingleLyric = false
  12005. // 加载已保存的歌词时间偏移
  12006. this.loadLyricTimeOffset()
  12007. this.lyricController.setLyric(null)
  12008. this.lyricControllerSingle.setLyric(null)
  12009. console.log("onecold lyricPath =" + lyricPath)
  12010. // 1. 检查内嵌歌词
  12011. let neiqianLrc = ''
  12012. let lyContent = this.currentSong?.lyricContent
  12013. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  12014. neiqianLrc = lyContent
  12015. }
  12016. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  12017. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  12018. // Navidrome JSON歌词转换
  12019. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  12020. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  12021. if (convertedLyric) {
  12022. neiqianLrc = convertedLyric;
  12023. console.log("onecold Navidrome歌词转换成功");
  12024. }
  12025. }
  12026. this.setLyricToControllers(neiqianLrc);
  12027. return
  12028. }
  12029. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  12030. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  12031. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  12032. song: this.currentSong,
  12033. playbackUrl: this.videoUrl,
  12034. manager: RemoteDriveManager.getInstance(),
  12035. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  12036. });
  12037. if (StrUtil.isNotEmpty(remoteLyric)) {
  12038. this.currentSong.lyricContent = remoteLyric;
  12039. this.setLyricToControllers(remoteLyric);
  12040. void this.persistRemoteMetadataToDb(this.currentSong);
  12041. return;
  12042. }
  12043. }
  12044. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  12045. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  12046. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  12047. || isPlexType(this.currentSong.type))) {
  12048. const manager = RemoteDriveManager.getInstance();
  12049. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  12050. // 将currentSong转换为SongData接口
  12051. const songData: SongData = {
  12052. webdav_account_id: this.currentSong.webdav_account_id,
  12053. artist: this.currentSong.artist,
  12054. name: this.currentSong.name,
  12055. webdav_id: this.currentSong.webdav_id,
  12056. lyricIndex: this.currentSong.lyricIndex,
  12057. type: this.currentSong.type
  12058. };
  12059. let serverLyric = '';
  12060. if (!serverLyric && isNavidromeType(songData.type)) {
  12061. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  12062. }
  12063. if (!serverLyric && isJellyfinType(songData.type)) {
  12064. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  12065. }
  12066. if (!serverLyric && isEmbyType(songData.type)) {
  12067. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  12068. }
  12069. if (!serverLyric && isAudioStationType(songData.type)) {
  12070. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  12071. }
  12072. if (!serverLyric && isPlexType(songData.type)) {
  12073. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  12074. }
  12075. if (serverLyric) {
  12076. this.setLyricToControllers(serverLyric, lyricPath);
  12077. return;
  12078. }
  12079. }
  12080. // 4. 尝试在线歌词API
  12081. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  12082. && !Utility.isVideoByExtension(this.videoUrl))) {
  12083. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  12084. return;
  12085. }
  12086. // 5. 从本地文件读取歌词
  12087. await this.loadLyricFromFile(lyricPath, isLocal || false);
  12088. }
  12089. /**
  12090. * 从本地文件加载歌词
  12091. */
  12092. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  12093. try {
  12094. let realLyricPath = lyricPath;
  12095. // 读取文件内容
  12096. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  12097. const stat = await fileIo.stat(file.fd);
  12098. const arrayBuffer = new ArrayBuffer(stat.size);
  12099. fs.read(file.fd, arrayBuffer)
  12100. .then((readLen: number) => {
  12101. console.info("read file data succeed");
  12102. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  12103. if (buf.length === 0) {
  12104. throw new Error("Buffer is empty after reading the file");
  12105. }
  12106. try {
  12107. // 检测文件编码
  12108. let detectedEncoding = this.detect(arrayBuffer);
  12109. console.info("onecoldT Detected encoding: " + detectedEncoding);
  12110. // 使用检测到的编码解码,解决中文乱码问题
  12111. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  12112. console.info("onecoldT Detected textDecoder: " + textDecoder);
  12113. let fileContent = textDecoder.decode(buf);
  12114. console.info(`onecoldT The content of file1: ${fileContent}`);
  12115. console.info(`onecold The content of file2: ${fileContent}`);
  12116. this.lyricContent = fileContent;
  12117. if(isLocal){
  12118. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  12119. this.lyricConStr = fileContent;
  12120. }
  12121. this.setLyricToControllers(fileContent);
  12122. console.info(`The content of file: ${fileContent}`);
  12123. } catch (chardetError) {
  12124. console.error("chardet.detect failed with error: " + chardetError.message);
  12125. this.clearLyricControllers();
  12126. }
  12127. })
  12128. .catch((err: BusinessError) => {
  12129. this.clearLyricControllers();
  12130. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  12131. })
  12132. .catch((err: Error) => {
  12133. this.clearLyricControllers();
  12134. console.error("read file 2 data failed with error message: " + err.message);
  12135. })
  12136. .finally(() => {
  12137. fs.closeSync(file);
  12138. });
  12139. } catch (error) {
  12140. this.clearLyricControllers();
  12141. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  12142. }
  12143. }
  12144. detect(data: ArrayBuffer): string {
  12145. //创建检测对象
  12146. let detector: UniversalDetector = new UniversalDetector();
  12147. // 限制检测数据大小,避免内存溢出
  12148. // 通常只需要检测文件前16KB就足够判断编码格式
  12149. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  12150. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  12151. // 传入检测数据并实时判断编码格式
  12152. detector.handleData(data, 0, detectSize);
  12153. // 标记检测数据 读取结束
  12154. detector.dataEnd();
  12155. // 获取检测结果
  12156. let detected: string = detector.getDetectedCharset();
  12157. // 释放资源
  12158. detector.reset();
  12159. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  12160. return detected;
  12161. }
  12162. /**
  12163. * 设置歌词到所有控制器
  12164. * @param lyricText 歌词文本
  12165. * @param savePath 可选,如果提供则保存到本地文件
  12166. */
  12167. private setLyricToControllers(lyricText: string, savePath?: string): void {
  12168. if (StrUtil.isEmpty(lyricText)) {
  12169. this.clearLyricControllers();
  12170. return;
  12171. }
  12172. this.lyricContent = lyricText;
  12173. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  12174. const lyric: Lyric = this.parser.parse(lines);
  12175. this.lyricController.setLyric(lyric);
  12176. this.lyricControllerXF.setLyric(lyric);
  12177. this.lyricControllerSingle.setLyric(lyric);
  12178. this.showSingleLyric = true;
  12179. // 如果提供了保存路径,保存歌词到本地
  12180. if (savePath) {
  12181. this.saveDataToFile(lyricText, savePath);
  12182. }
  12183. }
  12184. /**
  12185. * 清空所有歌词控制器
  12186. */
  12187. private clearLyricControllers(): void {
  12188. this.lyricController.setLyric(null);
  12189. this.lyricControllerXF.setLyric(null);
  12190. this.lyricControllerSingle.setLyric(null);
  12191. }
  12192. private extractLyricCopyLines(lyricText: string): string[] {
  12193. if (StrUtil.isEmpty(lyricText)) {
  12194. return [];
  12195. }
  12196. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  12197. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  12198. const lines = source.split('\n');
  12199. const result: string[] = [];
  12200. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  12201. for (let i = 0; i < lines.length; i++) {
  12202. const line = lines[i].trim();
  12203. if (!line || metaTagPattern.test(line)) {
  12204. continue;
  12205. }
  12206. const pureLine = line
  12207. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  12208. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  12209. .trim();
  12210. if (pureLine.length > 0) {
  12211. result.push(pureLine);
  12212. }
  12213. }
  12214. return result;
  12215. }
  12216. private openLyricCopySheet(): void {
  12217. const lines = this.extractLyricCopyLines(this.lyricContent);
  12218. if (ArrayUtil.isEmpty(lines)) {
  12219. ToastUtil.showToast('暂无可复制歌词');
  12220. return;
  12221. }
  12222. this.lyricCopyLines = lines;
  12223. this.lyricSelectedIndexes = [];
  12224. this.isShowLyricCopySheet = true;
  12225. }
  12226. private toggleLyricLineSelection(index: number): void {
  12227. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  12228. if (selectedIndex >= 0) {
  12229. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  12230. nextSelectedIndexes.splice(selectedIndex, 1);
  12231. this.lyricSelectedIndexes = nextSelectedIndexes;
  12232. return;
  12233. }
  12234. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  12235. }
  12236. private toggleLyricSelectAll(): void {
  12237. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  12238. this.lyricSelectedIndexes = [];
  12239. return;
  12240. }
  12241. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  12242. }
  12243. private copySelectedLyricLines(): void {
  12244. const selectedLines = this.getSelectedLyricLines();
  12245. if (ArrayUtil.isEmpty(selectedLines)) {
  12246. ToastUtil.showToast('暂无可复制歌词');
  12247. return;
  12248. }
  12249. Utility.copyText(selectedLines.join('\n'));
  12250. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  12251. }
  12252. private getSelectedLyricLines(): string[] {
  12253. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  12254. return [];
  12255. }
  12256. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  12257. const selectedLines: string[] = [];
  12258. for (let i = 0; i < selectedIndexes.length; i++) {
  12259. const index = selectedIndexes[i];
  12260. if (index >= 0 && index < this.lyricCopyLines.length) {
  12261. selectedLines.push(this.lyricCopyLines[index]);
  12262. }
  12263. }
  12264. return selectedLines;
  12265. }
  12266. private shareSelectedLyricLines(): void {
  12267. const selectedLines = this.getSelectedLyricLines();
  12268. if (ArrayUtil.isEmpty(selectedLines)) {
  12269. ToastUtil.showToast('暂无可分享歌词');
  12270. return;
  12271. }
  12272. const shareTitle = `${this.currentSong?.name ?? '歌词'}歌词`;
  12273. Utility.doShareText(selectedLines.join('\n'), this.context, shareTitle, '分享歌词');
  12274. }
  12275. /**
  12276. * 从在线API获取歌词
  12277. */
  12278. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  12279. if (!this.currentSong) {
  12280. this.clearLyricControllers();
  12281. if (isOnLineAndToast) {
  12282. ToastUtil.showShort('未获取到歌词!');
  12283. }
  12284. return;
  12285. }
  12286. let artist = this.currentSong.artist || '';
  12287. if (isApi2 === undefined) {
  12288. isApi2 = false;
  12289. }
  12290. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  12291. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  12292. this.setLyricToControllers(res, lyricPath);
  12293. } else {
  12294. this.clearLyricControllers();
  12295. if (isOnLineAndToast) {
  12296. ToastUtil.showShort('未获取到歌词!');
  12297. }
  12298. }
  12299. });
  12300. }
  12301. //初始化悬浮歌词的自定义设置
  12302. initPipLyricSetting() {
  12303. this.lyricControllerXF
  12304. .setTextSize(this.currentLyricSize)
  12305. .setCacheSize(4)
  12306. .setTextColor("#DDDDDD")
  12307. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  12308. .setEmptyHint("")
  12309. .setAnimationDuration(1000)
  12310. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  12311. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  12312. this.setBlurDegree(this.blurDegreePip, true)
  12313. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  12314. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  12315. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  12316. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  12317. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  12318. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  12319. this.lyricControllerXF.setHightLightCenter(true)
  12320. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  12321. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  12322. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  12323. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  12324. if (this.pipBgIndex === 0) {
  12325. if (this.cover) {
  12326. this.pipBg = this.cover
  12327. } else {
  12328. this.pipBg = this.imageColor
  12329. }
  12330. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  12331. }
  12332. }
  12333. //根据item返回歌词内容
  12334. async getLyricContent(item: VideoItem): Promise<string> {
  12335. let neiqianLrc = ''
  12336. let lyContent = item?.lyricContent
  12337. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  12338. neiqianLrc = lyContent
  12339. return neiqianLrc
  12340. }
  12341. try {
  12342. //取数据库里面的歌词lyContent
  12343. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  12344. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  12345. console.log("onecold Lyrics:", lyricContent);
  12346. neiqianLrc = lyricContent
  12347. return neiqianLrc
  12348. }
  12349. } catch (error) {
  12350. console.error("Error fetching lyrics:", error);
  12351. }
  12352. try {
  12353. let filePath = item.filePath;
  12354. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  12355. let realLyricPath = lyricPath;
  12356. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  12357. const stat = await fileIo.stat(file.fd);
  12358. const arrayBuffer = new ArrayBuffer(stat.size);
  12359. const readLen = await fs.read(file.fd, arrayBuffer);
  12360. console.info("read file data succeed");
  12361. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  12362. if (buf.length === 0) {
  12363. throw new Error("Buffer is empty after reading the file");
  12364. }
  12365. // let detectedEncoding = chardet.detect(buf);
  12366. let detectedEncoding = this.detect(arrayBuffer)
  12367. console.info("Detected encoding: " + detectedEncoding);
  12368. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  12369. let fileContent = textDecoder.decode(buf);
  12370. console.info(`onecold The content of file1: ${fileContent}`);
  12371. fs.closeSync(file);
  12372. return fileContent;
  12373. } catch (error) {
  12374. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  12375. return '';
  12376. }
  12377. }
  12378. async saveDataToFile(content: string, filePath: string) {
  12379. if (StrUtil.isEmpty(filePath)) {
  12380. return
  12381. }
  12382. try {
  12383. let lyricContent = ''
  12384. lyricContent = content
  12385. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  12386. // 清空文件内容
  12387. await fileIo.truncate(file.fd, 0);
  12388. await fileIo.write(file.fd, lyricContent);
  12389. await fileIo.close(file);
  12390. console.log('onecold lyric file Data saved successfully.');
  12391. } catch (error) {
  12392. console.error('onecold lyric file Failed to save data:', error);
  12393. }
  12394. }
  12395. // 定义开始旋转的方法
  12396. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  12397. @State timer: number = 0
  12398. @State rotateAngle: number = 0
  12399. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  12400. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  12401. // 页面可见性变化回调
  12402. onPageVisibilityChange() {
  12403. // 当页面可见性改变时,重新启动/停止旋转动画
  12404. this.animationRoFun()
  12405. }
  12406. //封面旋转动画
  12407. animationRoFun() {
  12408. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  12409. // 启动旋转动画
  12410. if (!this.isRotationRunning) {
  12411. this.isRotationRunning = true
  12412. this.startContinuousRotation()
  12413. }
  12414. this.startRotation()
  12415. } else {
  12416. // 停止旋转动画
  12417. this.isRotationRunning = false
  12418. clearInterval(this.timer)
  12419. this.stopRotation()
  12420. }
  12421. }
  12422. // 使用持续的动画进行旋转,避免频繁状态更新
  12423. private startContinuousRotation() {
  12424. clearInterval(this.timer)
  12425. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  12426. // 不使用 % 360 取模,让角度持续累加,避免反转
  12427. this.timer = setInterval(() => {
  12428. if (this.isRotationRunning) {
  12429. this.rotateAngle = this.rotateAngle + 36
  12430. }
  12431. }, 1000)
  12432. }
  12433. // 定义开始旋转的方法
  12434. startRotation() {
  12435. if (this.isPlaying) {
  12436. animateTo({
  12437. duration: 777,
  12438. iterations: 1,
  12439. curve: Curve.Linear
  12440. }, () => {
  12441. this.rotateAngle2 = -9
  12442. })
  12443. }
  12444. }
  12445. // 回调,暂停和播放按钮回调,下一首和上一首
  12446. playChange() {
  12447. // if(this.isCoverRectangle){
  12448. // return
  12449. // }
  12450. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12451. this.setIsPlaying(true)
  12452. this.animationState = AnimationStatus.Running
  12453. } else {
  12454. this.setIsPlaying(false)
  12455. this.animationState = AnimationStatus.Paused
  12456. }
  12457. AppStorage.setOrCreate('animationState', this.animationState);
  12458. }
  12459. // 定义停止旋转的方法
  12460. stopRotation() {
  12461. if (this.isCoverRectangle) {
  12462. this.rotateAngle = 0
  12463. } else {
  12464. //唱针以左上角为点选择逆时针40度
  12465. animateTo({
  12466. duration: 1000,
  12467. curve: Curve.Linear,
  12468. iterations: 1,
  12469. }, () => {
  12470. this.rotateAngle2 = -45;
  12471. });
  12472. }
  12473. }
  12474. @Builder
  12475. private LyricsTopItem() {
  12476. Row() {
  12477. Stack({ alignContent: Alignment.Center }) {
  12478. Image( StrUtil.isNotEmpty(this.cover)?
  12479. this.cover:$r('app.media.alt'))
  12480. .height(58)
  12481. .width(58)
  12482. .clip(true)
  12483. .sourceSize({width:38, height:38})
  12484. .alt($r('app.media.alt'))
  12485. .borderRadius(8)
  12486. .clickEffect({ level: ClickEffectLevel.HEAVY })
  12487. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  12488. .shadow({
  12489. radius: 22,
  12490. type: ShadowType.BLUR,
  12491. color: 'on_primary'
  12492. })
  12493. }
  12494. .width(62)
  12495. .height('100%')
  12496. Column() {
  12497. Column() {
  12498. Text(this.name)
  12499. .fontSize(16)
  12500. .maxLines(1)
  12501. .fontWeight(FontWeight.Bolder)
  12502. .fontColor(Color.White)
  12503. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12504. .margin({ left: 10 })
  12505. Row() {
  12506. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  12507. .fontSize(13)
  12508. .fontWeight(FontWeight.Bolder)
  12509. .padding({ top: 8 })
  12510. .fontColor(Color.White)
  12511. .margin({ left: 10 })
  12512. Blank()
  12513. }
  12514. }
  12515. .height('100%')
  12516. .width('100%')
  12517. .justifyContent(FlexAlign.Center)
  12518. .alignItems(HorizontalAlign.Start)
  12519. }
  12520. .height('100%')
  12521. .layoutWeight(1)
  12522. .margin({ right: 8 })
  12523. Column() {
  12524. PointLightDefaultButton({
  12525. isSysBol:false,
  12526. pointColor:Color.White,
  12527. imageResource:$r('app.media.lyric'),
  12528. isPx: false,
  12529. builderHeight: 23,
  12530. builderWidth: 23,
  12531. })
  12532. .onClick(() => {
  12533. this.isLyricSetting = !this.isLyricSetting;
  12534. })
  12535. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  12536. height: '99%',
  12537. dragBar: true,
  12538. preferType: SheetType.CENTER,
  12539. showClose: true,
  12540. blurStyle: BlurStyle.Thin,
  12541. backgroundColor: Color.Transparent,
  12542. title: { title: $r('app.string.lyric_setting') }
  12543. })
  12544. }
  12545. .width(44)
  12546. .height('100%')
  12547. .justifyContent(FlexAlign.Center)
  12548. .alignItems(HorizontalAlign.End)
  12549. }
  12550. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  12551. .padding({ left: 28, right: 28 })
  12552. .height(58)
  12553. .alignItems(VerticalAlign.Center)
  12554. }
  12555. //歌词显示
  12556. @Builder
  12557. PlayerLyrics() {
  12558. Column() {
  12559. Column() {
  12560. this.LyricsTopItem()
  12561. }
  12562. .height(this.isPuraWP() ? 15 : 58)
  12563. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  12564. Visibility.None : Visibility.Visible)
  12565. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  12566. .width("100%")
  12567. Column() {
  12568. LyricView2({
  12569. controller: this.lyricController,
  12570. enableSeek: true,
  12571. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12572. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12573. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12574. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  12575. if (!this.isPlaying) {
  12576. console.info('onecold startPlayOrResumePlay 7527')
  12577. this.startPlayOrResumePlay()
  12578. }
  12579. else {
  12580. this.dispatchSeekToPosition(position, 'lyric-seek-action')
  12581. }
  12582. return true
  12583. }
  12584. })
  12585. .width("100%")
  12586. .layoutWeight(1)
  12587. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  12588. .gesture(LongPressGesture()
  12589. .onAction(() => {
  12590. this.openLyricCopySheet();
  12591. }))
  12592. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  12593. height: '99%',
  12594. dragBar: true,
  12595. showClose: true,
  12596. preferType: SheetType.CENTER,
  12597. blurStyle: BlurStyle.Thin,
  12598. title: { title: '歌词' }
  12599. })
  12600. if (this.isPhoneLan()) {
  12601. Column() {
  12602. if (this.isShowSpectrum) {
  12603. this.InlineSpectrumView()
  12604. }
  12605. this.playProgressView()
  12606. }
  12607. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  12608. }
  12609. }
  12610. .position({
  12611. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  12612. (this.isPuraWP() ? 58 : 99)
  12613. })
  12614. .justifyContent(FlexAlign.Center)
  12615. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  12616. }
  12617. }
  12618. @Builder
  12619. LyricCopySheetBuilder() {
  12620. LyricCopySheet({
  12621. lyricCopyLines: this.lyricCopyLines,
  12622. lyricSelectedIndexes: this.lyricSelectedIndexes,
  12623. isDarkMode: this.isDarkMode,
  12624. themeColor: this.themeColor,
  12625. bottomSafeHeight: this.bottomSafeHeight,
  12626. onToggleLyricLine: (index: number) => {
  12627. this.toggleLyricLineSelection(index);
  12628. },
  12629. onToggleSelectAll: () => {
  12630. this.toggleLyricSelectAll();
  12631. },
  12632. onCopySelectedLines: () => {
  12633. this.copySelectedLyricLines();
  12634. },
  12635. onShareSelectedLines: () => {
  12636. this.shareSelectedLyricLines();
  12637. }
  12638. })
  12639. }
  12640. @Builder
  12641. SingleLyricView() {
  12642. Column() {
  12643. Column() {
  12644. LyricView2({
  12645. controller: this.lyricControllerSingle,
  12646. enableSeek: false,
  12647. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12648. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12649. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12650. })
  12651. .gesture(LongPressGesture()
  12652. .onAction(() => {
  12653. this.openLyricCopySheet();
  12654. }))
  12655. }
  12656. .height(82)
  12657. .margin({ bottom: 20 })
  12658. }
  12659. .opacity(this.playDragUiOpacity)
  12660. }
  12661. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  12662. @Builder
  12663. BottomControl() {
  12664. Column() {
  12665. if (this.isShowSpectrum) {
  12666. this.InlineSpectrumView()
  12667. }
  12668. this.TopPlayProgressView()
  12669. //播放 暂停,下一首,上一首
  12670. this.playCenterView()
  12671. if(!this.curDisplayIsHiCar){
  12672. //播放进度条
  12673. this.BottomView()
  12674. }
  12675. }
  12676. .justifyContent(FlexAlign.Center)
  12677. .alignItems(HorizontalAlign.Center)
  12678. .opacity(this.playDragUiOpacity)
  12679. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  12680. }
  12681. @Builder
  12682. playMenuBuilder(){
  12683. Image($r('app.media.menu'))
  12684. .width(24)
  12685. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12686. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  12687. height: '99%',
  12688. preferType:SheetType.CENTER,
  12689. dragBar: true,
  12690. showClose: true,
  12691. blurStyle: BlurStyle.Thin,
  12692. title: { title: $r('app.string.more') },
  12693. backgroundColor: Color.Transparent,
  12694. })
  12695. }
  12696. //播放控制上一首 下一首 暂停和播放
  12697. @Builder
  12698. playCenterView(){
  12699. Row() {
  12700. PointLightButton({
  12701. builder: () => {
  12702. this.playMenuBuilder()
  12703. },
  12704. isPx: false,
  12705. builderHeight: 26,
  12706. builderWidth: 26,
  12707. })
  12708. .onClick(async () =>{
  12709. this.isShowMoreView = !this.isShowMoreView;
  12710. })
  12711. PointLightButton({
  12712. builder: () => {
  12713. this.playPreviousBuilder()
  12714. },
  12715. isPx: false,
  12716. builderHeight: 26,
  12717. builderWidth: 26,
  12718. })
  12719. .onClick(async () =>{
  12720. await this.playbackController.playPrevious()
  12721. })
  12722. PointLightButton({
  12723. builder: () => {
  12724. this.PlayOrPauseButton()
  12725. },
  12726. isPx: false,
  12727. builderHeight: this.isPhoneLan()?38:41,
  12728. builderWidth: this.isPhoneLan()?38:41,
  12729. })
  12730. .onClick(() =>{
  12731. this.playbackController.playOrPause()
  12732. })
  12733. PointLightButton({
  12734. builder: () => {
  12735. this.playNextBuilder()
  12736. },
  12737. isPx: false,
  12738. builderHeight: 26,
  12739. builderWidth: 26,
  12740. })
  12741. .onClick(async () =>{
  12742. await this.playbackController.playNext()
  12743. })
  12744. this.playModeButton()
  12745. }
  12746. .width('95%')
  12747. .margin({ bottom:this.isCoverOpacity()?0:15 })
  12748. .justifyContent(FlexAlign.SpaceEvenly)
  12749. }
  12750. @Builder
  12751. playPreviousBuilder(){
  12752. Image($r('app.media.ic_previous'))
  12753. .width(32)
  12754. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12755. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12756. }
  12757. @Builder
  12758. playNextBuilder(){
  12759. Image($r('app.media.ic_next'))
  12760. .width(32)
  12761. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12762. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12763. }
  12764. @Builder
  12765. PlayOrPauseButton(){
  12766. Stack() {
  12767. Column() {
  12768. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  12769. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  12770. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  12771. .width(this.isPhoneLan()?38:40)
  12772. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12773. .fillColor(Color.White)
  12774. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12775. }
  12776. // 加载进度圈
  12777. if (this.isPlayerLoading) {
  12778. Progress({value:0,total:100,type:ProgressType.Ring })
  12779. .width(this.isPhoneLan()?40:43)
  12780. .height(this.isPhoneLan()?40:43)
  12781. .color(Color.White)
  12782. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  12783. }
  12784. }
  12785. .width(this.isPhoneLan()?38:41)
  12786. .height(this.isPhoneLan()?38:41)
  12787. }
  12788. @Builder
  12789. TopPlayProgressView(){
  12790. Column() {
  12791. Row(){
  12792. Stack(){
  12793. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  12794. .fontColor([Color.White])
  12795. .fontSize(21)
  12796. .effectStrategy(1)
  12797. Text(this.fastForwardSeconds)
  12798. .fontColor(Color.White)
  12799. .fontSize(10)
  12800. .fontWeight(FontWeight.Bold)
  12801. }
  12802. .padding({left:12,bottom:6})
  12803. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12804. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12805. .onClick(()=>{
  12806. this.backForward()
  12807. })
  12808. Slider({
  12809. value: this.progressValue,
  12810. min: 0,
  12811. max: this.PROGRESS_MAX_VALUE,
  12812. step: 1,
  12813. style: SliderStyle.InSet
  12814. })
  12815. .height(20)
  12816. .blockColor('rgba(255,255,255,1)')
  12817. .trackColor('rgba(255,255,255,0.3)')
  12818. .selectedColor(Color.White)
  12819. .trackThickness(4)
  12820. .showSteps(false)
  12821. .showTips(true)
  12822. .layoutWeight(1)
  12823. .enabled(this.slideEnable)
  12824. .onChange((value: number, mode: SliderChangeMode) => {
  12825. if (mode !== 2) {
  12826. return
  12827. }
  12828. this.dispatchSeekFromPercent(value, 'top-progress-slider')
  12829. })
  12830. Stack(){
  12831. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  12832. .fontColor([Color.White])
  12833. .fontSize(21)
  12834. .effectStrategy(1)
  12835. Text(this.fastForwardSeconds)
  12836. .fontColor(Color.White)
  12837. .fontSize(10)
  12838. .fontWeight(FontWeight.Bold)
  12839. }
  12840. .padding({right:10,bottom:6})
  12841. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12842. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12843. .onClick(()=>{
  12844. this.fastForward()
  12845. })
  12846. }
  12847. .justifyContent(FlexAlign.Center)
  12848. .padding({left:20,right:20})
  12849. .width(this.isLandscape?'88%':'95%')
  12850. Row() {
  12851. Text(this.currentTime)
  12852. .fontSize(10)
  12853. .fontColor(Color.White)
  12854. .margin({left:25})
  12855. Blank()
  12856. Text(this.totalTime)
  12857. .fontSize(10)
  12858. .fontColor(Color.White)
  12859. .margin({right:25})
  12860. }
  12861. .width(this.isLandscape?'85%':'90%')
  12862. .height(10)
  12863. }
  12864. .width('100%')
  12865. .alignItems(HorizontalAlign.Center)
  12866. }
  12867. @Builder
  12868. playModeButton(){
  12869. PointLightButton({
  12870. builder: () => {
  12871. this.playModeBuilder()
  12872. },
  12873. isPx: false,
  12874. builderHeight: 26,
  12875. builderWidth: 26,
  12876. })
  12877. .onClick(async () =>{
  12878. await this.playbackController.setLoopMode()
  12879. })
  12880. }
  12881. @Builder
  12882. playModeBuilder(){
  12883. Column() {
  12884. if (this.playType === 0) {
  12885. Image($r('app.media.loop'))
  12886. .width(24)
  12887. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12888. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12889. } else if (this.playType === 1) {
  12890. Image($r('app.media.single'))
  12891. .width(24)
  12892. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12893. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12894. } else if (this.playType === 2) {
  12895. Image($r('app.media.normal_play'))
  12896. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12897. .width(24)
  12898. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12899. } else if (this.playType === 3) {
  12900. Image($r('app.media.random'))
  12901. .width(24)
  12902. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12903. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12904. } else if (this.playType === 4) {
  12905. Image($r('app.media.noloop'))
  12906. .width(24)
  12907. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12908. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12909. }
  12910. }
  12911. }
  12912. //播放进度条
  12913. @Builder
  12914. BottomView(){
  12915. Row() {
  12916. PointLightDefaultButton({
  12917. isSysBol:true,
  12918. pointColor:Color.White,
  12919. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12920. isPx: false,
  12921. builderHeight: 22,
  12922. builderWidth: 22,
  12923. })
  12924. .onClick(async () =>{
  12925. if (this.isLandscape) {
  12926. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12927. } else {
  12928. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12929. }
  12930. })
  12931. if(this.currentSong){
  12932. PointLightDefaultButton({
  12933. isSysBol:true,
  12934. pointColor:Color.White,
  12935. imageResource:$r('sys.symbol.rename'),
  12936. isPx: false,
  12937. builderHeight: 22,
  12938. builderWidth: 22,
  12939. })
  12940. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  12941. height: '99%',
  12942. dragBar: true,
  12943. showClose: true,
  12944. preferType: SheetType.BOTTOM,
  12945. title: { title: '编辑标签' }
  12946. })
  12947. .onClick(async () => {
  12948. this.initEditFields(this.currentSong)
  12949. this.tempLyricContent = this.lyricContent
  12950. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  12951. this.lyricConStr = this.tempLyricContent
  12952. }
  12953. this.isShowEdit = !this.isShowEdit;
  12954. })
  12955. }
  12956. PointLightDefaultButton({
  12957. isSysBol:true,
  12958. pointColor:Color.White,
  12959. imageResource:$r('sys.symbol.slider_vertical_3'),
  12960. isPx: false,
  12961. builderHeight: 22,
  12962. builderWidth: 22,
  12963. })
  12964. .onClick(async () => {
  12965. this.isEqualizerSheet = !this.isEqualizerSheet;
  12966. })
  12967. PointLightDefaultButton({
  12968. isSysBol:true,
  12969. pointColor:Color.White,
  12970. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  12971. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  12972. isPx: false,
  12973. builderHeight: 22,
  12974. builderWidth: 22,
  12975. })
  12976. .onClick(async () => {
  12977. if(this.currentSong){
  12978. this.doFav(this.currentSong)
  12979. }
  12980. })
  12981. this.playListBuilder()
  12982. }
  12983. .width(this.isLandscape?'88%':'95%')
  12984. .justifyContent(FlexAlign.SpaceAround)
  12985. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  12986. .height(30)
  12987. .animation({
  12988. duration: 666,
  12989. curve: 'ease-in-out' // 可选动画曲线
  12990. })
  12991. }
  12992. @Builder
  12993. fullButton(){
  12994. Column() {
  12995. Image($r('app.media.full_4'))
  12996. .width(25)
  12997. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12998. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12999. }
  13000. }
  13001. @Builder
  13002. playListBuilder(){
  13003. PointLightDefaultButton({
  13004. isSysBol:true,
  13005. pointColor:Color.White,
  13006. imageResource:$r('sys.symbol.music_note_list'),
  13007. isPx: false,
  13008. builderHeight: 26,
  13009. builderWidth: 26,
  13010. })
  13011. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  13012. height: '95%',
  13013. dragBar: true,
  13014. showClose: true,
  13015. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  13016. blurStyle: BlurStyle.Thin,
  13017. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  13018. title: {
  13019. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  13020. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  13021. + `(${this.getPlayListDisplayCount()}首)`
  13022. }
  13023. })
  13024. .onClick(() => {
  13025. this.isShowSheetView = !this.isShowSheetView;
  13026. if(this.isPlayListBgGrass){
  13027. this.isFrontWhite = true
  13028. }else{
  13029. this.isFrontWhite = false
  13030. }
  13031. this.scrollIndex()
  13032. if (this.shouldHydrateFullMediaPlayListOnOpen()) {
  13033. void this.hydrateFullMediaPlayListIfNeeded();
  13034. }
  13035. })
  13036. }
  13037. //旧版本播放进度条(现在是手机横屏的播放条)
  13038. @Builder
  13039. playProgressView() {
  13040. Row() {
  13041. Column(){
  13042. PointLightDefaultButton({
  13043. isSysBol:true,
  13044. pointColor:Color.White,
  13045. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  13046. isPx: false,
  13047. builderHeight: 26,
  13048. builderWidth: 26,
  13049. })
  13050. .onClick(async () =>{
  13051. if (this.isLandscape) {
  13052. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  13053. } else {
  13054. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  13055. }
  13056. })
  13057. }
  13058. .margin({ right: 10,bottom:6})
  13059. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  13060. .animation({
  13061. duration: 666,
  13062. curve: 'ease-in-out' // 可选动画曲线
  13063. })
  13064. Text(this.currentTime)
  13065. .fontSize($r('app.float.slider_font_size'))
  13066. .fontColor(Color.White)
  13067. .margin(3)
  13068. Slider({
  13069. value: this.progressValue,
  13070. min: 0,
  13071. max: this.PROGRESS_MAX_VALUE,
  13072. step: 1,
  13073. style: SliderStyle.InSet
  13074. })
  13075. .width('600px')
  13076. .blockColor('rgba(255,255,255,1)')
  13077. .trackColor('rgba(255,255,255,0.3)')
  13078. .selectedColor(Color.White)
  13079. .trackThickness(5)
  13080. .layoutWeight(1)
  13081. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  13082. .showSteps(false)
  13083. .showTips(true)
  13084. .enabled(this.slideEnable)
  13085. .onChange((value: number, mode: SliderChangeMode) => {
  13086. if (mode !== 2) {
  13087. return
  13088. }
  13089. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  13090. this.dispatchSeekFromPercent(value, 'landscape-progress-slider')
  13091. })
  13092. Text(this.totalTime)
  13093. .fontSize($r('app.float.slider_font_size'))
  13094. .fontColor(Color.White)
  13095. .margin(3)
  13096. //播放列表
  13097. Column(){
  13098. this.playListBuilder()
  13099. }
  13100. .margin({ left: 10,bottom:6})
  13101. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  13102. .animation({
  13103. duration: 666,
  13104. curve: 'ease-in-out' // 可选动画曲线
  13105. })
  13106. }
  13107. //x5的竖屏模式需要99%
  13108. .width(this.isPhonePortrait() ? '93.4%'
  13109. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  13110. .height(this.isPhoneLan() ? 25 : 33)
  13111. .alignItems(VerticalAlign.Bottom)
  13112. .animation({
  13113. duration: 666,
  13114. curve: 'ease-in-out' // 可选动画曲线
  13115. })
  13116. }
  13117. isBigScreen() {
  13118. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  13119. return true
  13120. }
  13121. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  13122. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  13123. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  13124. return false
  13125. } else {
  13126. return true
  13127. }
  13128. return false
  13129. }
  13130. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  13131. // 添加控制缩放的状态变量
  13132. @State scaleValueImage: number = 1
  13133. @State scaleValueText: number = 1
  13134. @State playDragUiOpacity: number = 1
  13135. @Builder
  13136. private CoverScaleGuideOverlay() {
  13137. Stack() {
  13138. Column({ space: 10 }) {
  13139. SymbolGlyph($r('sys.symbol.arrow_up_left_and_arrow_down_right'))
  13140. .fontSize(34)
  13141. .fontColor([Color.White])
  13142. Text('双指缩放封面')
  13143. .fontSize(16)
  13144. .fontWeight(FontWeight.Bold)
  13145. .fontColor(Color.White)
  13146. Text('在封面区域双指捏合,可调整封面大小')
  13147. .fontSize(12)
  13148. .fontColor(Color.White)
  13149. .opacity(0.88)
  13150. .textAlign(TextAlign.Center)
  13151. }
  13152. .padding({ left: 18, right: 18, top: 16, bottom: 16 })
  13153. .backgroundColor('#A6000000')
  13154. .borderRadius(18)
  13155. .width(this.isPhoneLan() ? 230 : 240)
  13156. }
  13157. .width('100%')
  13158. .height(this.isPhoneLan() ? 260 : 360)
  13159. .align(Alignment.Center)
  13160. .zIndex(10)
  13161. .visibility(this.isShowCoverScaleGuide ? Visibility.Visible : Visibility.None)
  13162. .onClick(() => {
  13163. this.dismissCoverScaleGuide()
  13164. })
  13165. }
  13166. @Builder
  13167. CoverInfo() {
  13168. Column() {
  13169. Stack() {
  13170. Column() {
  13171. //方形封面布局
  13172. if (this.isCoverRectangle) {
  13173. this.RectangleCoverView()
  13174. } else {
  13175. //圆形封面布局
  13176. this.CicleCoverView()
  13177. }
  13178. this.musicNameInfo(false)
  13179. if (this.isPhoneLan()) {
  13180. Text(this.name+"--"+this.artist)
  13181. .fontSize(18)
  13182. .fontWeight(FontWeight.Bold)
  13183. .margin({ top: 13 })
  13184. .textOverflow({ overflow: TextOverflow.Ellipsis })
  13185. .maxLines(1)
  13186. .width('99%')
  13187. .textAlign(TextAlign.Center)
  13188. .fontColor(Color.White)
  13189. }
  13190. }
  13191. .width('100%')
  13192. Column({ space: 8 }) {
  13193. Text(this.name)
  13194. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  13195. .fontWeight(FontWeight.Bold)
  13196. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13197. .maxLines(1)
  13198. .width('85%')
  13199. .textAlign(TextAlign.Center)
  13200. .fontColor(Color.White)
  13201. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13202. Text(this.artist)
  13203. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  13204. .fontColor(Color.White)
  13205. .fontWeight(FontWeight.Bold)
  13206. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13207. }
  13208. .justifyContent(FlexAlign.Start)
  13209. .zIndex(1)
  13210. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  13211. this.CoverScaleGuideOverlay()
  13212. }
  13213. .margin({
  13214. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  13215. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  13216. top: this.isCoverOpacity() ? 0 : 20
  13217. })
  13218. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  13219. this.SingleLyricView()
  13220. }
  13221. if (this.isPhoneLan()) {
  13222. Column() {
  13223. this.playCenterView()
  13224. }
  13225. .position({ left: 28, bottom: 35 })
  13226. } else {
  13227. this.BottomControl()
  13228. }
  13229. }
  13230. .width(CommonConstants.FULL_PERCENT)
  13231. .clip(true)
  13232. }
  13233. //方形封面布局
  13234. @Builder
  13235. RectangleCoverView(){
  13236. Stack({alignContent:Alignment.Center}){
  13237. Image( StrUtil.isNotEmpty(this.cover)?
  13238. this.cover:$r('app.media.alt'))
  13239. .height(this.getRectangleCoverHeight())
  13240. .width(this.getRectangleCoverWidth())
  13241. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13242. .alt($r('app.media.alt'))
  13243. .margin({ right: 8, left: 8, top: 5 })
  13244. .aspectRatio(1)
  13245. .opacity(this.opacityValueImage)
  13246. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13247. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  13248. {
  13249. preview: MenuPreviewMode.IMAGE,
  13250. previewAnimationOptions: { scale: [0.8, 1.0] },
  13251. })
  13252. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  13253. {
  13254. preview: MenuPreviewMode.IMAGE,
  13255. previewAnimationOptions: { scale: [0.8, 1.0] },
  13256. })
  13257. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13258. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13259. .clip(true)
  13260. .animation({
  13261. duration: 1000, // 与 setInterval 同步
  13262. curve: Curve.Linear,
  13263. iterations: 1
  13264. })
  13265. .shadow({
  13266. radius: 22,
  13267. type: ShadowType.BLUR,
  13268. color: 'on_primary'
  13269. })
  13270. .onClick(() => {
  13271. this.isMusicBGCover = !this.isMusicBGCover
  13272. })
  13273. .gesture(PinchGesture({ fingers: 2 })
  13274. .onActionUpdate((event: GestureEvent) => {
  13275. this.updateRectangleCoverScaleByPinch(event.scale)
  13276. })
  13277. .onActionEnd(() => {
  13278. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13279. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13280. }))
  13281. }
  13282. .scale({ x: this.scaleValueImage, y: this.scaleValueImage})
  13283. }
  13284. private getRectangleCoverWidth(): string | number {
  13285. if (this.isHiCar() || this.isCoverOpacity()) {
  13286. return 'auto'
  13287. }
  13288. const baseWidth = this.isBigScreen() ? 72 : this.isCoverTopBig ? 100 : 88
  13289. return `${Math.min(100, Math.max(48, baseWidth * this.rectangleCoverScale))}%`
  13290. }
  13291. private getRectangleCoverHeight(): string | number {
  13292. if (this.isHiCar()) {
  13293. return px2vp(this.windowHeight) * 0.4 * this.rectangleCoverScale
  13294. }
  13295. if (this.isCoverOpacity()) {
  13296. return px2vp(this.windowHeight) * 0.54 * this.rectangleCoverScale
  13297. }
  13298. return 'auto'
  13299. }
  13300. private updateCoverScaleByPinch(scale: number): void {
  13301. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * scale))
  13302. }
  13303. private updateRectangleCoverScaleByPinch(scale: number): void {
  13304. const dampedScale = 1 + (scale - 1) * 0.45
  13305. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * dampedScale))
  13306. }
  13307. private persistCoverScaleAfterPinch(): void {
  13308. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13309. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13310. }
  13311. @Builder
  13312. CicleCoverView() {
  13313. //圆形封面布局
  13314. Stack({alignContent:Alignment.Center}) {
  13315. Image($r('app.media.ic_music_disc'))
  13316. .width(245)
  13317. .height(245)
  13318. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  13319. .aspectRatio(1)
  13320. .opacity(this.isCoverOpacity() ? 0 : 1)
  13321. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  13322. .borderRadius('100%')
  13323. .align(Alignment.Center)
  13324. .clip(true)
  13325. .rotate({
  13326. angle: this.rotateAngle,
  13327. centerX: "50%",
  13328. centerY: "50%",
  13329. })
  13330. .animation({
  13331. duration: 1000, // 改为 1000ms 与 setInterval 同步
  13332. curve: Curve.Linear,
  13333. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  13334. })
  13335. .shadow({
  13336. radius: 22,
  13337. type: ShadowType.BLUR,
  13338. color: 'on_primary'
  13339. })
  13340. Image( StrUtil.isNotEmpty(this.cover)?
  13341. this.cover:$r('app.media.alt'))
  13342. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  13343. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  13344. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13345. .alt($r('app.media.alt'))
  13346. .margin({ right: 20, left: 20,
  13347. top:this.isCoverRectangle||this.isLandscape?0:50})
  13348. .aspectRatio(1)
  13349. .opacity(this.opacityValueImage)
  13350. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13351. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13352. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13353. .align(Alignment.Center)//
  13354. .clip(true)
  13355. .shadow({
  13356. radius: 22,
  13357. type: ShadowType.BLUR,
  13358. color: 'on_primary'
  13359. })
  13360. .rotate({
  13361. x: 0,
  13362. y: 0,
  13363. z: 1,
  13364. angle: this.rotateAngle
  13365. })
  13366. .animation({
  13367. duration: 1000, // 与 setInterval 同步
  13368. curve: Curve.Linear,
  13369. iterations: 1
  13370. })
  13371. .onClick(() => {
  13372. this.isMusicBGCover = !this.isMusicBGCover
  13373. })
  13374. // 唱针以左上角为点选择逆时针40度
  13375. Image($r('app.media.ic_music_cover_hand'))
  13376. .height(130)
  13377. .margin({ bottom: 200, top: 0 })
  13378. // .position({ x: this.windowWidth/2, y: 0 })
  13379. .align(Alignment.Top)
  13380. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  13381. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  13382. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  13383. }
  13384. .scale({ x: this.scaleValueImage * this.rectangleCoverScale, y: this.scaleValueImage * this.rectangleCoverScale,
  13385. centerX: '50%',
  13386. centerY: '50%' })
  13387. .priorityGesture(PinchGesture({ fingers: 2 })
  13388. .onActionStart(() => {
  13389. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13390. })
  13391. .onActionUpdate((event: GestureEvent) => {
  13392. this.updateCoverScaleByPinch(event.scale)
  13393. })
  13394. .onActionEnd(() => {
  13395. this.persistCoverScaleAfterPinch()
  13396. }))
  13397. }
  13398. @Builder
  13399. MenuImageBuilder(cover: string|undefined) {
  13400. Menu(){
  13401. MenuItem({
  13402. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  13403. content: '查看封面'
  13404. })
  13405. .onClick(async() => {
  13406. if (StrUtil.isEmpty(cover)) {
  13407. ToastUtil.showToast('当前没有可用封面')
  13408. return;
  13409. }
  13410. this.getUIContext().getRouter().pushUrl({
  13411. url: 'pages/WallpaperPreviewPage',
  13412. params: {
  13413. imageUri: cover
  13414. }
  13415. })
  13416. })
  13417. MenuItem({
  13418. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  13419. content: '更换封面'
  13420. })
  13421. .onClick(async() => {
  13422. await this.replaceCurrentSongCoverByAlbum();
  13423. })
  13424. }
  13425. }
  13426. @Builder
  13427. private musicNameInfo(isHidden: boolean) {
  13428. Row(){
  13429. Column({ space: 8 }) {
  13430. Text(this.name)
  13431. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  13432. .fontWeight(FontWeight.Bold)
  13433. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13434. .maxLines(1)
  13435. .width('99%')
  13436. .textAlign(TextAlign.Start)
  13437. .fontColor(Color.White)
  13438. Text(this.artist + ' ' + this.currentSong?.album)
  13439. .fontSize(this.isCoverOpacity() ? 12 : 15)
  13440. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13441. .fontColor(Color.White)
  13442. .textAlign(TextAlign.Start)
  13443. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  13444. .width('99%')
  13445. .maxLines(1)
  13446. }
  13447. .zIndex(1)
  13448. .layoutWeight(1)
  13449. .margin({ left: 15 })
  13450. Blank()
  13451. Row(){
  13452. PointLightDefaultButton({
  13453. isSysBol:true,
  13454. pointColor:Color.White,
  13455. imageResource:this.showSimple?
  13456. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  13457. isPx: false,
  13458. builderHeight: 26,
  13459. builderWidth: 26,
  13460. })
  13461. .onClick(async () => {
  13462. this.showSimple = !this.showSimple
  13463. PreferencesUtil.put('showSimple', this.showSimple)
  13464. })
  13465. }
  13466. .margin({ left: 8,right:8 })
  13467. }
  13468. .width(this.isLandscape?'83%':'90%')
  13469. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  13470. .opacity(this.playDragUiOpacity)
  13471. .margin({ top:this.isCoverRectangle?15: 0 })
  13472. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  13473. }
  13474. @Builder
  13475. private PlayTitle() {
  13476. Row() {
  13477. Row() {
  13478. PointLightDefaultButton({
  13479. isSysBol: true,
  13480. pointColor: Color.White,
  13481. imageResource: $r('sys.symbol.chevron_down'),
  13482. isPx: false,
  13483. builderHeight: 26,
  13484. builderWidth: 26,
  13485. })
  13486. .onClick(() => {
  13487. this.setShowPlayFalse()
  13488. })
  13489. }
  13490. .width('100%')
  13491. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  13492. }
  13493. .width(PlayConstants.ROW_WIDTH)
  13494. }
  13495. @Builder
  13496. lyricSettingSheet(isPip: boolean) {
  13497. Scroll() {
  13498. this.lyricSetting(isPip)
  13499. }
  13500. .width('100%')
  13501. .height('100%')
  13502. }
  13503. @Builder
  13504. lyricSetting(isPip: boolean) {
  13505. Column() {
  13506. // 时间调节模块
  13507. if (!isPip) {
  13508. this.BuildTimeControls()
  13509. }
  13510. // 字号控制模块
  13511. this.BuildFontControls(isPip)
  13512. }
  13513. }
  13514. // 歌词时间偏移状态
  13515. @State timeOffset: number = 0.0
  13516. @State currentLyricColor: string = '#FFFFFF'
  13517. @State currentLyricColorPip: string = '#FFFFFF'
  13518. @State currentHighLightLyricColor: string = '#FF4081'
  13519. @State currentHighLightLyricColorPip: string = '#FF4081'
  13520. // 歌词字号状态
  13521. @State currentLyricSize: number = 20
  13522. @State currentLyricSizePip: number = 20
  13523. // 高亮歌词放大倍数
  13524. @State currentHightLyricSize: number = 1.2
  13525. @State currentHightLyricSizePip: number = 1.2
  13526. @State currentLyricLineSpace: number = 10
  13527. @State currentLyricLineSpacePip: number = 10
  13528. @State currentLyricAlignMode: number = 1
  13529. @State currentLyricAlignModePip: number = 1
  13530. @State blurDegree: number = 2
  13531. @State blurDegreePip: number = 2
  13532. @State isShowSelectColor: boolean = false
  13533. @State isShowHLSelectColor: boolean = false
  13534. @State isShowPipBgSelectColor: boolean = false
  13535. @State pipLyWidth: number = 330
  13536. @State pipLyHeight: number = 120
  13537. // 构建颜色选择器
  13538. @Builder
  13539. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  13540. Row({ space: 10 }) {
  13541. HSBColorPicker({
  13542. color: '#FFFFFF',
  13543. radius: 8,
  13544. layout: HSBColorPickerLayout.COLUMN,
  13545. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  13546. '#fa7105'],
  13547. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  13548. this.changeLyricColor(value, isPip, isBGPip)
  13549. })
  13550. .height(250)
  13551. .layoutWeight(1)
  13552. .padding(25)
  13553. }
  13554. .width('66%')
  13555. }
  13556. @State isOpenPip: boolean = false
  13557. @State pipBgIndex: number = 0
  13558. // 构建字号控制器
  13559. @Builder
  13560. BuildFontControls(isPip: boolean) {
  13561. Column() {
  13562. if (isPip) {
  13563. Column() {
  13564. Row() {
  13565. Text('悬浮歌词')
  13566. .margin({ left: 18 })
  13567. .fontSize(15)
  13568. .fontColor(Color.White)
  13569. .fontWeight(480)
  13570. .layoutWeight(1)
  13571. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  13572. .selectedColor(this.themeColor)
  13573. .switchPointColor(Color.White)
  13574. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13575. .margin({ right: 18 })
  13576. .onChange((checked: boolean) => {
  13577. this.isOpenPip = checked;
  13578. if (this.isOpenPip) {
  13579. this.startPip()
  13580. } else {
  13581. this.stopPip()
  13582. }
  13583. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  13584. })
  13585. .width(50)
  13586. .height(30);
  13587. }
  13588. .height(55)
  13589. }
  13590. .backgroundColor(Color.Transparent)
  13591. .borderRadius(15)
  13592. .margin({
  13593. left: 30,
  13594. right: 30,
  13595. top: 0,
  13596. bottom: 20
  13597. })
  13598. .padding(0)
  13599. .border({
  13600. color: Color.White,
  13601. width: 1.8
  13602. })
  13603. }else{
  13604. Row() {
  13605. Row() {
  13606. Text(`迷你歌词:`)
  13607. .fontSize(14)
  13608. .fontColor(Color.White)
  13609. .width(88)
  13610. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  13611. .selectedColor(this.themeColor)
  13612. .switchPointColor(Color.White)
  13613. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13614. .onChange((checked: boolean) => {
  13615. this.isShowSingleLineLyric = checked;
  13616. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  13617. })
  13618. .width(50)
  13619. .height(30)
  13620. .alignSelf(ItemAlign.Start)
  13621. .margin({ left: 12 })
  13622. Blank()
  13623. }
  13624. .layoutWeight(1)
  13625. Row() {
  13626. Text(`逐字歌词:`)
  13627. .fontSize(14)
  13628. .fontColor(Color.White)
  13629. .width(88)
  13630. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  13631. .selectedColor(this.themeColor)
  13632. .switchPointColor(Color.White)
  13633. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13634. .onChange((checked: boolean) => {
  13635. this.isEnableWordByWordLyric = checked;
  13636. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  13637. this.syncWordByWordLyricMode()
  13638. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13639. })
  13640. .width(50)
  13641. .height(30)
  13642. .alignSelf(ItemAlign.Start)
  13643. .margin({ left: 12 })
  13644. Blank()
  13645. }
  13646. .layoutWeight(1)
  13647. }
  13648. .width('100%')
  13649. .margin({
  13650. left: 20,
  13651. right: 15,
  13652. top: 10,
  13653. bottom: 10
  13654. })
  13655. }
  13656. if (!isPip) {
  13657. Row() {
  13658. Row() {
  13659. Text(`歌词发光:`)
  13660. .fontSize(14)
  13661. .fontColor(Color.White)
  13662. .width(88)
  13663. Toggle({ type: ToggleType.Switch, isOn: this.isLightText })
  13664. .selectedColor(this.themeColor)
  13665. .switchPointColor(Color.White)
  13666. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13667. .onChange((checked: boolean) => {
  13668. this.isLightText = checked;
  13669. PreferencesUtil.putSync(SettingPage.IS_LIGHT_TEXT, this.isLightText)
  13670. this.syncLyricLightTextMode()
  13671. })
  13672. .width(50)
  13673. .height(30)
  13674. .alignSelf(ItemAlign.Start)
  13675. .margin({ left: 12 })
  13676. Blank()
  13677. }
  13678. .layoutWeight(1)
  13679. Row() {
  13680. Text(`高亮居中:`)
  13681. .fontSize(14)
  13682. .fontColor(Color.White)
  13683. .width(88)
  13684. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  13685. .selectedColor(this.themeColor)
  13686. .switchPointColor(Color.White)
  13687. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13688. .onChange((checked: boolean) => {
  13689. this.isHightLightCenter = checked;
  13690. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  13691. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  13692. })
  13693. .width(50)
  13694. .height(30)
  13695. .alignSelf(ItemAlign.Start)
  13696. .margin({ left: 12 })
  13697. Blank()
  13698. }
  13699. .layoutWeight(1)
  13700. }
  13701. .width('100%')
  13702. .margin({
  13703. left: 20,
  13704. right: 15,
  13705. top: 10,
  13706. bottom: 10
  13707. })
  13708. }
  13709. Row() {
  13710. Text(`歌词居中:`)
  13711. .fontSize(14)
  13712. .fontColor(Color.White)
  13713. Row() {
  13714. ForEach(['居中', '居左'], (size: string, index: number) => {
  13715. Button(size)
  13716. .width(60)
  13717. .height(28)
  13718. .fontSize(12)
  13719. .fontColor('#FFFFFF')
  13720. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  13721. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  13722. .border({
  13723. color: (!isPip && this.currentLyricAlignMode === index) ||
  13724. (isPip && this.currentLyricAlignModePip === index) ?
  13725. '#007DFF' : '#DDDDDD',
  13726. width: 1.8
  13727. })
  13728. .onClick(() => {
  13729. this.setLyricAlignMode(index, isPip)
  13730. })
  13731. .margin({ left: 10, right: 8 })
  13732. })
  13733. }
  13734. .layoutWeight(1)
  13735. Blank()
  13736. }
  13737. .width('100%')
  13738. .margin({
  13739. top: 10,
  13740. bottom: 10,
  13741. right: 15,
  13742. left: 20
  13743. })
  13744. if (isPip) {
  13745. Row() {
  13746. Text(`悬浮背景:`)
  13747. .fontSize(14)
  13748. .fontColor(Color.White)
  13749. Select([
  13750. { value: CommonConstants.PIP_LYRIC_BG[0] },
  13751. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  13752. .font({ size: 13, weight: FontWeight.Medium })
  13753. .fontColor(Color.White)
  13754. .margin({ left: 10 })
  13755. .selected(this.pipBgIndex)
  13756. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  13757. .onSelect(async (_index: number, text?: string | undefined) => {
  13758. this.pipBgIndex = _index
  13759. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  13760. if (this.pipBgIndex === 0) {
  13761. if (this.cover) {
  13762. this.pipBg = this.cover
  13763. } else {
  13764. this.pipBg = this.imageColor
  13765. }
  13766. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13767. } else {
  13768. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  13769. }
  13770. })
  13771. Column() {
  13772. }
  13773. .backgroundColor(this.pipBg)
  13774. .margin({ left: 10, right: 10 })
  13775. .borderRadius(20)
  13776. .height(28)
  13777. .width(28)
  13778. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13779. Row() {
  13780. SymbolGlyph($r('sys.symbol.paintbrush'))
  13781. .fontColor([Color.White])
  13782. .effectStrategy(1)
  13783. Text(`选择颜色`)
  13784. .fontSize(13)
  13785. .margin({ left: 10 })
  13786. .fontColor(Color.White)
  13787. }
  13788. }
  13789. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  13790. .backgroundColor(Color.Transparent)
  13791. .border({
  13792. color: '#FFFFFF',
  13793. radius: 20,
  13794. width: 1.8
  13795. })
  13796. .height(36)
  13797. .width(110)
  13798. .onClick(() => {
  13799. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  13800. })
  13801. .bindPopup(this.isShowPipBgSelectColor, {
  13802. builder: this.SelectColor(false, isPip, true),
  13803. placement: Placement.Top,
  13804. mask: { color: '#33000000' },
  13805. enableArrow: false, //是否显示箭头
  13806. showInSubWindow: false,
  13807. onStateChange: (e) => {
  13808. if (!e.isVisible) {
  13809. this.isShowPipBgSelectColor = false
  13810. }
  13811. }
  13812. })
  13813. }
  13814. .width('100%')
  13815. .margin({ bottom: 5, right: 15, left: 20 })
  13816. }
  13817. Row() {
  13818. Text(`歌词颜色:`)
  13819. .fontSize(14)
  13820. .fontColor(Color.White)
  13821. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13822. .fontSize(15)
  13823. .fontColor(Color.White)
  13824. .margin({ left: 6, right: 6 })
  13825. Column() {
  13826. }
  13827. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13828. .margin({ right: 12 })
  13829. .borderRadius(20)
  13830. .height(28)
  13831. .width(28)
  13832. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13833. Row() {
  13834. SymbolGlyph($r('sys.symbol.paintbrush'))
  13835. .fontColor([Color.White])
  13836. .effectStrategy(1)
  13837. Text(`选择颜色`)
  13838. .fontSize(13)
  13839. .margin({ left: 10 })
  13840. .fontColor(Color.White)
  13841. }
  13842. }
  13843. .backgroundColor(Color.Transparent)
  13844. .border({
  13845. color: '#FFFFFF',
  13846. radius: 20,
  13847. width: 1.8
  13848. })
  13849. .height(36)
  13850. .width(110)
  13851. .onClick(() => {
  13852. this.isShowSelectColor = !this.isShowSelectColor
  13853. })
  13854. .bindPopup(this.isShowSelectColor, {
  13855. builder: this.SelectColor(false, isPip),
  13856. placement: Placement.Top,
  13857. mask: { color: '#33000000' },
  13858. enableArrow: false, //是否显示箭头
  13859. showInSubWindow: false,
  13860. onStateChange: (e) => {
  13861. if (!e.isVisible) {
  13862. this.isShowSelectColor = false
  13863. }
  13864. }
  13865. })
  13866. }
  13867. .width('100%')
  13868. .margin({
  13869. top: 10,
  13870. bottom: 10,
  13871. right: 15,
  13872. left: 20
  13873. })
  13874. Row() {
  13875. Text(`高亮颜色:`)
  13876. .fontSize(14)
  13877. .fontColor(Color.White)
  13878. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13879. .fontSize(15)
  13880. .fontColor(Color.White)
  13881. .margin({ left: 6, right: 6 })
  13882. Column() {
  13883. }
  13884. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13885. .margin({ right: 12 })
  13886. .borderRadius(20)
  13887. .height(28)
  13888. .width(28)
  13889. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13890. Row() {
  13891. SymbolGlyph($r('sys.symbol.paintbrush'))
  13892. .fontColor([Color.White])
  13893. .effectStrategy(1)
  13894. Text(`选择颜色`)
  13895. .fontSize(13)
  13896. .margin({ left: 10 })
  13897. .fontColor(Color.White)
  13898. }
  13899. }
  13900. .backgroundColor(Color.Transparent)
  13901. .border({
  13902. color: '#FFFFFF',
  13903. radius: 20,
  13904. width: 1.8
  13905. })
  13906. .height(36)
  13907. .width(110)
  13908. .onClick(() => {
  13909. this.isShowHLSelectColor = !this.isShowHLSelectColor
  13910. })
  13911. .bindPopup(this.isShowHLSelectColor, {
  13912. builder: this.SelectColor(true, isPip),
  13913. placement: Placement.Top,
  13914. mask: { color: '#33000000' },
  13915. enableArrow: false, //是否显示箭头
  13916. showInSubWindow: false,
  13917. onStateChange: (e) => {
  13918. if (!e.isVisible) {
  13919. this.isShowHLSelectColor = false
  13920. }
  13921. }
  13922. })
  13923. }
  13924. .width('100%')
  13925. .margin({
  13926. top: 10,
  13927. bottom: 10,
  13928. right: 15,
  13929. left: 20
  13930. })
  13931. if (isPip) {
  13932. Row() {
  13933. Text(`显示宽度:`)
  13934. .fontSize(14)
  13935. .fontColor(Color.White)
  13936. Slider({
  13937. value: this.pipLyWidth,
  13938. min: 10,
  13939. max: 800,
  13940. step: 1,
  13941. style: SliderStyle.OutSet
  13942. })
  13943. .blockColor(this.themeColor)
  13944. .trackColor($r('app.color.speed_text_color'))
  13945. .selectedColor(Color.White)
  13946. .trackThickness(6)
  13947. .onChange((value: number) => {
  13948. this.pipLyWidth = value
  13949. if (this.pipController) {
  13950. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13951. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  13952. }
  13953. })
  13954. .layoutWeight(1)
  13955. }
  13956. .justifyContent(FlexAlign.Start)
  13957. .margin({
  13958. left: 20,
  13959. right: 15,
  13960. top: 5,
  13961. bottom: 5
  13962. })
  13963. Row() {
  13964. Text(`显示高度:`)
  13965. .fontSize(14)
  13966. .fontColor(Color.White)
  13967. Slider({
  13968. value: this.pipLyHeight,
  13969. min: 10,
  13970. max: 1000,
  13971. step: 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.pipLyHeight = value
  13980. if (this.pipController) {
  13981. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13982. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  13983. }
  13984. })
  13985. .layoutWeight(1)
  13986. }
  13987. .justifyContent(FlexAlign.Start)
  13988. .margin({
  13989. left: 20,
  13990. right: 15,
  13991. top: 5,
  13992. bottom: 5
  13993. })
  13994. }
  13995. Row() {
  13996. Text(`歌词字号:`)
  13997. .fontSize(14)
  13998. .fontColor(Color.White)
  13999. Slider({
  14000. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  14001. min: 12,
  14002. max: 30,
  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.setLyricTextSize(value, isPip)
  14012. })
  14013. .layoutWeight(1)
  14014. .margin({ right: 3 })
  14015. Text(this.getLyricSizeDisplayValue(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.currentHightLyricSizePip : this.currentHightLyricSize,
  14033. min: 1,
  14034. max: 2,
  14035. step: 0.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.setHighLyricTextSize(value, isPip)
  14044. })
  14045. .layoutWeight(1)
  14046. .margin({ right: 3 })
  14047. Text(this.getHighLyricSizeDisplayValue(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. Row() {
  14060. Text(`歌词间隙:`)
  14061. .fontSize(14)
  14062. .fontColor(Color.White)
  14063. Slider({
  14064. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  14065. min: 0,
  14066. max: 100,
  14067. step: 1,
  14068. style: SliderStyle.OutSet
  14069. })
  14070. .blockColor(this.themeColor)
  14071. .trackColor($r('app.color.speed_text_color'))
  14072. .selectedColor(Color.White)
  14073. .trackThickness(6)
  14074. .onChange((value: number) => {
  14075. this.setLyricLineSpace(value, isPip)
  14076. })
  14077. .layoutWeight(1)
  14078. .margin({ right: 3 })
  14079. Text(this.getLyricLineSpaceDisplayValue(isPip))
  14080. .fontSize(13)
  14081. .fontColor(Color.White)
  14082. .textAlign(TextAlign.Start)
  14083. }
  14084. .width('100%')
  14085. .margin({
  14086. left: 20,
  14087. right: 15,
  14088. top: 5,
  14089. bottom: 5
  14090. })
  14091. //取值间隔为100,默认为400,取值越大,字体越粗
  14092. Row() {
  14093. Text(`歌词字重:`)
  14094. .fontSize(14)
  14095. .fontColor(Color.White)
  14096. Slider({
  14097. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  14098. min: 100,
  14099. max: 900,
  14100. step: 100,
  14101. style: SliderStyle.OutSet
  14102. })
  14103. .blockColor(this.themeColor)
  14104. .trackColor($r('app.color.speed_text_color'))
  14105. .selectedColor(Color.White)
  14106. .trackThickness(6)
  14107. .onChange((value: number) => {
  14108. if (isPip) {
  14109. this.lyricTextWeightPip = value
  14110. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  14111. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  14112. } else {
  14113. this.lyricTextWeight = value
  14114. this.lyricController.setTextWeight(this.lyricTextWeight)
  14115. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  14116. }
  14117. })
  14118. .layoutWeight(1)
  14119. .margin({ right: 3 })
  14120. Text(this.getLyricTextWeightDisplayValue(isPip))
  14121. .fontSize(13)
  14122. .fontColor(Color.White)
  14123. .textAlign(TextAlign.Start)
  14124. }
  14125. .width('100%')
  14126. .margin({
  14127. left: 20,
  14128. right: 15,
  14129. top: 5,
  14130. bottom: 5
  14131. })
  14132. Row() {
  14133. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  14134. this.pushLyricButton($r('app.media.share2'), 2, '分享歌词')
  14135. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  14136. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  14137. }
  14138. .justifyContent(FlexAlign.Center)
  14139. .margin({ top: 3, bottom: 10 })
  14140. }
  14141. .width('88%')
  14142. }
  14143. private getLyricSizeDisplayValue(isPip: boolean): string {
  14144. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  14145. return lyricSize.toFixed(1);
  14146. }
  14147. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  14148. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  14149. return highLyricSize.toFixed(1);
  14150. }
  14151. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  14152. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  14153. return Math.round(lyricLineSpace).toString();
  14154. }
  14155. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  14156. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  14157. return Math.round(lyricTextWeightValue).toString();
  14158. }
  14159. private setBlurDegree(index: number, isPip: boolean) {
  14160. if (isPip) {
  14161. this.blurDegreePip = index
  14162. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  14163. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  14164. } else {
  14165. this.blurDegree = index
  14166. this.lyricController.setBlurDegree(this.blurDegree)
  14167. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  14168. }
  14169. }
  14170. private setLyricAlignMode(index: number, isPip: boolean) {
  14171. if (isPip) {
  14172. this.currentLyricAlignModePip = index
  14173. if (this.currentLyricAlignModePip === 1) {
  14174. this.lyricControllerXF.setAlignMode("left")
  14175. } else {
  14176. this.lyricControllerXF.setAlignMode("center")
  14177. }
  14178. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  14179. } else {
  14180. this.currentLyricAlignMode = index
  14181. if (this.currentLyricAlignMode === 1) {
  14182. this.lyricController.setAlignMode("left")
  14183. } else {
  14184. this.lyricController.setAlignMode("center")
  14185. }
  14186. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  14187. }
  14188. }
  14189. private setLyricTextSize(index: number, isPip: boolean) {
  14190. if (isPip) {
  14191. this.currentLyricSizePip = index
  14192. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  14193. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  14194. } else {
  14195. this.currentLyricSize = index
  14196. this.lyricController.setTextSize(this.currentLyricSize)
  14197. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  14198. }
  14199. }
  14200. private setHighLyricTextSize(scale: number, isPip: boolean) {
  14201. if (isPip) {
  14202. this.currentHightLyricSizePip = scale
  14203. this.lyricControllerXF
  14204. .setHighlightScale(this.currentHightLyricSizePip)
  14205. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  14206. } else {
  14207. this.currentHightLyricSize = scale
  14208. this.lyricController
  14209. .setHighlightScale(this.currentHightLyricSize)
  14210. PreferencesUtil.putSync('HighLyricTextSize', scale)
  14211. }
  14212. }
  14213. private setLyricLineSpace(index: number, isPip: boolean) {
  14214. if (isPip) {
  14215. this.currentLyricLineSpacePip = index
  14216. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  14217. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  14218. } else {
  14219. this.currentLyricLineSpace = index
  14220. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  14221. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  14222. }
  14223. }
  14224. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  14225. LogUtil.info('onecold isBG = ' + isBG)
  14226. if (isBG) { //如果是设置悬浮背景
  14227. this.pipBg = color
  14228. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  14229. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  14230. return
  14231. }
  14232. if (isPip) {
  14233. this.currentLyricColorPip = color
  14234. this.lyricControllerXF
  14235. .setTextColor(this.currentLyricColorPip)
  14236. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  14237. } else {
  14238. this.currentLyricColor = color
  14239. this.lyricController
  14240. .setTextColor(this.currentLyricColor)
  14241. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  14242. }
  14243. }
  14244. private changeLyricHightLightColor(color: string, isPip: boolean) {
  14245. if (isPip) {
  14246. this.currentHighLightLyricColorPip = color
  14247. this.lyricControllerXF
  14248. .setHighlightColor(this.currentHighLightLyricColorPip)
  14249. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  14250. } else {
  14251. this.currentHighLightLyricColor = color
  14252. this.lyricController
  14253. .setHighlightColor(this.currentHighLightLyricColor)
  14254. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  14255. }
  14256. }
  14257. // 构建时间控制器
  14258. @Builder
  14259. BuildTimeControls() {
  14260. Column() {
  14261. // 时间显示
  14262. Text(this.getTimeText())
  14263. .fontSize(18)
  14264. .fontColor(Color.White)
  14265. .margin({ bottom: 10 })
  14266. Row() {
  14267. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  14268. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  14269. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  14270. }
  14271. .justifyContent(FlexAlign.Center)
  14272. }
  14273. .margin({ top: 12, bottom: 8 })
  14274. }
  14275. // 精度按钮组件
  14276. @Builder
  14277. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  14278. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14279. Column() {
  14280. Image(icon)
  14281. .width(28)
  14282. .margin({ bottom: 5 })
  14283. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  14284. Text(label)
  14285. .fontSize(12)
  14286. .fontColor('#FFFFFF')
  14287. }
  14288. }
  14289. .backgroundColor(Color.Transparent)
  14290. .enabled(!this.isButtonDisabled(step))
  14291. .onClick(() => this.handlePrecisionAdjust(step))
  14292. .padding(5)
  14293. .width(66)
  14294. .height(66)
  14295. .margin({ left: 18, right: 18 })
  14296. .border({
  14297. color: '#FFFFFF',
  14298. width: 1.8
  14299. })
  14300. }
  14301. private handlePrecisionAdjust(step: number) {
  14302. if (step === 0) {
  14303. this.timeOffset = 0
  14304. this.saveLyricTimeOffset()
  14305. return
  14306. }
  14307. // 精度处理:保留1位小数
  14308. const newOffset = Number((this.timeOffset + step).toFixed(5))
  14309. // 边界保护(±15.0秒)
  14310. if (newOffset < -30.0 || newOffset > 30.0) {
  14311. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  14312. return
  14313. }
  14314. // 状态更新
  14315. this.timeOffset = newOffset
  14316. // 保存歌词时间偏移
  14317. this.saveLyricTimeOffset()
  14318. }
  14319. // 按钮禁用逻辑
  14320. private isButtonDisabled(step: number): boolean {
  14321. const futureOffset = this.timeOffset + step
  14322. return (futureOffset < -30.0) || (futureOffset > 30.0)
  14323. }
  14324. // 时间显示文本升级
  14325. private getTimeText(): string {
  14326. const absValue = Math.abs(this.timeOffset)
  14327. return this.timeOffset === 0
  14328. ? '歌词时间已重置'
  14329. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  14330. }
  14331. /**
  14332. * 获取当前歌曲的唯一标识key
  14333. * 使用歌曲的filePath作为唯一标识
  14334. */
  14335. private getLyricOffsetKey(): string {
  14336. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  14337. // 使用MD5对filePath进行加密,作为存储key
  14338. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  14339. }
  14340. return ''
  14341. }
  14342. /**
  14343. * 保存当前歌曲的歌词时间偏移
  14344. */
  14345. private saveLyricTimeOffset(): void {
  14346. try {
  14347. const key = this.getLyricOffsetKey()
  14348. if (StrUtil.isEmpty(key)) {
  14349. console.warn('heanup saveLyricTimeOffset: key is empty')
  14350. return
  14351. }
  14352. PreferencesUtil.putSync(key, this.timeOffset)
  14353. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  14354. } catch (e) {
  14355. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  14356. }
  14357. }
  14358. /**
  14359. * 加载当前歌曲的歌词时间偏移
  14360. */
  14361. private loadLyricTimeOffset(): void {
  14362. try {
  14363. const key = this.getLyricOffsetKey()
  14364. if (StrUtil.isEmpty(key)) {
  14365. console.warn('heanup loadLyricTimeOffset: key is empty')
  14366. return
  14367. }
  14368. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  14369. if (savedOffset !== 0) {
  14370. this.timeOffset = savedOffset
  14371. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  14372. }else{
  14373. this.timeOffset = 0
  14374. }
  14375. } catch (e) {
  14376. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  14377. }
  14378. }
  14379. // 导入 本地歌词 搜索歌词
  14380. @Builder
  14381. pushLyricButton(icon: Resource, step: number, label: string) {
  14382. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14383. Row() {
  14384. Image(icon)
  14385. .width(14)
  14386. .margin({ left: 13 })
  14387. Text(label)
  14388. .fontSize(12)
  14389. .margin({ left: 6 })
  14390. .fontColor('#FFFFFF')
  14391. }
  14392. }
  14393. .onClick(() => {
  14394. switch (step) {
  14395. case 0:
  14396. this.callFilePickerSelectFileForLyric()
  14397. break;
  14398. case 1:
  14399. //判断有没有设置api
  14400. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  14401. this.isLyricSetting = false
  14402. this.showTipsDialog()
  14403. return
  14404. }
  14405. if (StrUtil.isNotEmpty(this.videoUrl)) {
  14406. ToastUtil.showToast('正在获取')
  14407. this.isLyricSetting = false
  14408. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  14409. this.initLyric(lyricPath, true);
  14410. }
  14411. break;
  14412. case 2:
  14413. this.isLyricSetting = false
  14414. this.openLyricCopySheet()
  14415. break;
  14416. }
  14417. })
  14418. .padding(5)
  14419. .layoutWeight(1)
  14420. .backgroundColor(Color.Transparent)
  14421. .height(40)
  14422. .margin({ left: 4, right: 4 })
  14423. .border({
  14424. color: '#FFFFFF',
  14425. radius: 20,
  14426. width: 1.8
  14427. })
  14428. }
  14429. showVipDialog() {
  14430. DialogHelper.showCustomContentDialog({
  14431. dialogId: 'vip',
  14432. title: "友情提示",
  14433. autoCancel: false, //点击遮障层时,不关闭弹窗
  14434. backCancel: true, //点击返回键,不关闭弹窗
  14435. contentBuilder: () => {
  14436. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  14437. },
  14438. buttons: [],
  14439. })
  14440. }
  14441. //去赞助的自定义内容
  14442. @Builder
  14443. customVipBuilder(content: string) {
  14444. Column() {
  14445. Text(content)
  14446. .fontColor(Color.Gray)
  14447. .fontSize(16)
  14448. .alignSelf(ItemAlign.Start)
  14449. .margin({ bottom: 15 })
  14450. .fontSize(16)
  14451. Row() {
  14452. Button('取消')
  14453. .fontColor(Color.White)
  14454. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14455. .height(50)
  14456. .layoutWeight(1)
  14457. .stateEffect(true)
  14458. .margin({ right: 6 })
  14459. .onClick(() => {
  14460. DialogHelper.closeDialog('vip'); //关闭弹框
  14461. })
  14462. Button('开通')
  14463. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14464. .layoutWeight(1)
  14465. .height(50)
  14466. .backgroundColor(this.themeColor)
  14467. .stateEffect(true)
  14468. .margin({ left: 6 })
  14469. .onClick(() => {
  14470. DialogHelper.closeDialog('vip'); //关闭弹框
  14471. this.isShowPlay = false
  14472. this.mType = 1 //跳转到用户中心
  14473. // router.pushUrl({
  14474. // url: 'pages/VipPage'
  14475. // }, router.RouterMode.Single);
  14476. })
  14477. }
  14478. }
  14479. .width("100%")
  14480. .padding(10)
  14481. }
  14482. showTipsDialog() {
  14483. DialogHelper.showCustomContentDialog({
  14484. dialogId: 'tips',
  14485. title: "友情提示",
  14486. autoCancel: false, //点击遮障层时,不关闭弹窗
  14487. backCancel: true, //点击返回键,不关闭弹窗
  14488. contentBuilder: () => {
  14489. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  14490. },
  14491. buttons: [],
  14492. })
  14493. }
  14494. @Builder
  14495. customTipsBuilder(content: string) {
  14496. Column() {
  14497. Text(content)
  14498. .fontColor(Color.Gray)
  14499. .fontSize(16)
  14500. .alignSelf(ItemAlign.Start)
  14501. .margin({ bottom: 15 })
  14502. .fontSize(16)
  14503. Row() {
  14504. Button('取消')
  14505. .fontColor(Color.White)
  14506. .backgroundColor(this.themeColor)
  14507. .height(50)
  14508. .layoutWeight(1)
  14509. .stateEffect(true)
  14510. .margin({ right: 6 })
  14511. .onClick(() => {
  14512. DialogHelper.closeDialog('tips'); //关闭弹框
  14513. })
  14514. Button('跳转')
  14515. .fontColor(Color.White)//
  14516. .layoutWeight(1)
  14517. .height(50)
  14518. .backgroundColor(this.themeColor)
  14519. .stateEffect(true)
  14520. .margin({ left: 6 })
  14521. .onClick(() => {
  14522. DialogHelper.closeDialog('tips'); //关闭弹框
  14523. this.isShowEdit = false
  14524. this.longItemFilePath = ''
  14525. // if(this.isGridMusic&&!this.isShowPlay){
  14526. // this.longItemFilePath== ''
  14527. // }else{
  14528. // this.isShowEdit = false
  14529. // }
  14530. this.isShowMoreView = false;
  14531. this.isShowPlay = false
  14532. this.mType = 4
  14533. // router.pushUrl({
  14534. // url: 'pages/SettingPage'
  14535. // }, router.RouterMode.Single);
  14536. })
  14537. }
  14538. }
  14539. .width("100%")
  14540. .padding(10)
  14541. }
  14542. @Builder
  14543. PlayMoreSheet() {
  14544. Column() {
  14545. this.MoreList()
  14546. }
  14547. .width('100%')
  14548. .height('100%')
  14549. }
  14550. @Builder
  14551. MoreList() {
  14552. Scroll() {
  14553. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  14554. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  14555. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14556. Row() {
  14557. if (more.id === 3&&this.currentSong) {
  14558. Image(more.image)
  14559. .width(24)
  14560. .height(24)
  14561. .margin({ left: 10, right: 10 })
  14562. Text(more.title)
  14563. .fontSize(16)
  14564. .fontColor(Color.White)
  14565. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  14566. height: '99%',
  14567. dragBar: true,
  14568. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14569. showClose: true,
  14570. blurStyle: BlurStyle.Thin,
  14571. backgroundColor: Color.Transparent,
  14572. title: { title: '歌曲信息' }
  14573. })
  14574. } else if (more.id === 15 && this.currentSong) { //编辑标签
  14575. Image(more.image)
  14576. .width(24)
  14577. .height(24)
  14578. .margin({ left: 10, right: 10 })
  14579. Text(more.title)
  14580. .fontSize(16)
  14581. .fontColor(Color.White)
  14582. } else if (more.id === 5) { //定时关闭
  14583. Image(more.image)
  14584. .width(24)
  14585. .height(24)
  14586. .margin({ left: 10, right: 10 })
  14587. Text(more.title)
  14588. .fontSize(16)
  14589. .fontColor(Color.White)
  14590. .onClick(() => {
  14591. this.doMore(more.id)
  14592. })
  14593. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  14594. height: this.isCoverOpacity() ? '95%' : '95%',
  14595. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14596. dragBar: true,
  14597. showClose: true,
  14598. title: { title: $r('app.string.time_close') }
  14599. })
  14600. } else if (more.id === 2) { //歌词设置
  14601. Image(more.image)
  14602. .width(24)
  14603. .height(24)
  14604. .margin({ left: 10, right: 10 })
  14605. Text(more.title)
  14606. .fontSize(16)
  14607. .fontColor(Color.White)
  14608. } else if (more.id === 16) { //悬浮歌词设置
  14609. Image(more.image)
  14610. .width(24)
  14611. .height(24)
  14612. .margin({ left: 10, right: 10 })
  14613. Text(more.title)
  14614. .fontSize(16)
  14615. .fontColor(Color.White)
  14616. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  14617. height: '99%',
  14618. dragBar: true,
  14619. preferType: SheetType.CENTER,
  14620. showClose: true,
  14621. blurStyle: BlurStyle.Thin,
  14622. backgroundColor: Color.Transparent,
  14623. title: { title: '悬浮歌词' }
  14624. })
  14625. } else if (more.id === 11) {
  14626. Image(more.image)
  14627. .width(24)
  14628. .height(24)
  14629. .margin({ left: 10, right: 10 })
  14630. Text(more.title)
  14631. .fontSize(16)
  14632. .fontColor(Color.White)
  14633. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  14634. height: this.isCoverOpacity() ? '95%' : '60%',
  14635. dragBar: true,
  14636. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14637. showClose: true,
  14638. blurStyle: BlurStyle.Thin,
  14639. backgroundColor: Color.Transparent,
  14640. title: { title: '跳过头尾' }
  14641. })
  14642. } else if (more.id === 12) { //投播
  14643. AVCastPicker({
  14644. customPicker: (): void => this.TPImageBuilder(more),
  14645. onStateChange: (state) => {
  14646. if (state == AVCastPickerState.STATE_APPEARING) {
  14647. console.log(' The picker starts showing.');
  14648. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14649. console.log(' The picker finishes presenting.');
  14650. }
  14651. },
  14652. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  14653. sessionType: 'video'
  14654. })
  14655. .id('AVCastPicker')
  14656. } else {
  14657. if(more.id >= 22){
  14658. SymbolGlyph(more.image)
  14659. .fontSize(24)
  14660. .fontColor([Color.White])
  14661. .alignSelf(ItemAlign.Center)
  14662. .margin({ left: 10, right: 10,bottom:5})
  14663. // .padding({bottom:4})
  14664. .onClick(() => {
  14665. this.doMore(more.id)
  14666. })
  14667. }else{
  14668. Image(more.image)
  14669. .width(24)
  14670. .height(24)
  14671. .fillColor(Color.White)
  14672. .margin({ left: 10, right: 10 })
  14673. .onClick(() => {
  14674. this.doMore(more.id)
  14675. })
  14676. }
  14677. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  14678. .fontSize(16)
  14679. .margin({top:more.id >= 22?3:0})
  14680. .fontColor(Color.White)
  14681. .onClick(() => {
  14682. this.doMore(more.id)
  14683. })
  14684. Select([//倍速
  14685. { value: '0.25x' },
  14686. { value: '0.5x' },
  14687. { value: '0.75x' },
  14688. { value: '1x' },
  14689. { value: '1.25x' },
  14690. { value: '1.5x' },
  14691. { value: '1.75x' },
  14692. { value: '2x' },
  14693. { value: '3x' }])
  14694. .font({ size: 16, weight: FontWeight.Medium })
  14695. .fontColor($r('sys.color.white'))
  14696. .margin({ left: 25 })
  14697. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  14698. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  14699. .value(Utility.optimizedFormat(this.playSpeed))
  14700. .onSelect(async (_index: number, text?: string | undefined) => {
  14701. let speed = parseFloat(text?.replace('x', '') || '1');
  14702. if (!CommonConstants.video_speed_list.includes(speed)) {
  14703. speed = 1;
  14704. }
  14705. this.playSpeed = speed
  14706. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14707. })
  14708. Slider({
  14709. value: this.volume,
  14710. min: 0,
  14711. max: 1,
  14712. step: 0.1,
  14713. style: SliderStyle.OutSet
  14714. })
  14715. .margin({ left: 18, right: 8 })
  14716. .blockColor(this.themeColor)
  14717. .trackColor($r('app.color.speed_text_color'))
  14718. .selectedColor(Color.White)
  14719. .trackThickness(9)
  14720. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14721. .onChange((value: number) => {
  14722. this.volume = value;
  14723. this.applyCurrentVolume();
  14724. PreferencesUtil.putSync('DefalutVolume',this.volume)
  14725. })
  14726. .layoutWeight(1)
  14727. Slider({
  14728. value: this.volumeBoostPercent,
  14729. min: 0,
  14730. max: this.volumeBoostMaxPercent,
  14731. step: 1,
  14732. style: SliderStyle.OutSet
  14733. })
  14734. .margin({ left: 18, right: 8 })
  14735. .blockColor(this.themeColor)
  14736. .trackColor($r('app.color.speed_text_color'))
  14737. .selectedColor(Color.White)
  14738. .trackThickness(9)
  14739. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14740. .onChange((value: number) => {
  14741. this.volumeBoostPercent = Math.round(value);
  14742. this.applyCurrentVolume();
  14743. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  14744. })
  14745. .layoutWeight(1)
  14746. Text(`${Math.round(this.volumeBoostPercent)}%`)
  14747. .fontSize(13)
  14748. .fontColor(Color.White)
  14749. .margin({ left: 8, right: 8 })
  14750. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14751. Text(`${Math.round(this.volume*100)}%`)
  14752. .fontSize(13)
  14753. .fontColor(Color.White)
  14754. .margin({ left: 8, right: 8 })
  14755. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14756. Blank()
  14757. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  14758. .selectedColor(this.themeColor)
  14759. .switchPointColor(Color.White)
  14760. .margin({ right: 15 })
  14761. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14762. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  14763. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14764. if (more.id == 6) {
  14765. this.isMusicMemoryPlay = checked;
  14766. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  14767. if (this.isMusicMemoryPlay) {
  14768. ToastUtil.showToast('记忆播放已开启')
  14769. } else {
  14770. ToastUtil.showToast('记忆播放已关闭')
  14771. }
  14772. }
  14773. })
  14774. .width(48)
  14775. .height(24);
  14776. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  14777. .selectedColor(this.themeColor)
  14778. .switchPointColor(Color.White)
  14779. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14780. .margin({ right: 15 })
  14781. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  14782. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14783. if (more.id == 7) {
  14784. this.isMusicBGCover = checked;
  14785. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  14786. if (this.isMusicBGCover) {
  14787. ToastUtil.showToast('播放背景随音乐封面已开启')
  14788. } else {
  14789. ToastUtil.showToast('播放背景随音乐封面已关闭')
  14790. }
  14791. }
  14792. })
  14793. .width(48)
  14794. .height(24);
  14795. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  14796. .selectedColor(this.themeColor)
  14797. .switchPointColor(Color.White)
  14798. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14799. .margin({ right: 15 })
  14800. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  14801. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14802. if (more.id == 8) {
  14803. this.isSavePlayMode = checked;
  14804. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  14805. if (this.isSavePlayMode) {
  14806. ToastUtil.showToast('保存播放模式已开启')
  14807. } else {
  14808. ToastUtil.showToast('保存播放模式已关闭')
  14809. }
  14810. }
  14811. })
  14812. .width(48)
  14813. .height(24);
  14814. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  14815. .selectedColor(this.themeColor)
  14816. .switchPointColor(Color.White)
  14817. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14818. .margin({ right: 15 })
  14819. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  14820. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14821. if (more.id == 13) {
  14822. this.isCoverRectangle = checked;
  14823. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  14824. if (this.isCoverRectangle) {
  14825. ToastUtil.showToast('封面方形已开启,双指缩放封面可以调整封面大小')
  14826. this.animationRoFun()
  14827. } else {
  14828. ToastUtil.showToast('封面圆形已开启,双指缩放封面可以调整封面大小')
  14829. this.animationRoFun()
  14830. }
  14831. }
  14832. })
  14833. .width(48)
  14834. .height(24);
  14835. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  14836. .selectedColor(this.themeColor)
  14837. .switchPointColor(Color.White)
  14838. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14839. .margin({ right: 15 })
  14840. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  14841. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14842. if (more.id == 25) {
  14843. this.isShowSpectrum = checked;
  14844. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  14845. }
  14846. })
  14847. .width(48)
  14848. .height(24);
  14849. // 频谱特效类型选择器
  14850. Select([
  14851. { value: '柱状' },
  14852. { value: '波形' },
  14853. { value: '水波纹' },
  14854. { value: '圆形' },
  14855. { value: '粒子' },
  14856. { value: '脉冲' },
  14857. { value: '镜像柱' },
  14858. { value: '影子柱' },
  14859. { value: '轨道线' },
  14860. { value: '点阵' },
  14861. { value: '星爆' },
  14862. { value: '心电图' },
  14863. { value: '特效' }
  14864. ])
  14865. .font({ size: 14, weight: FontWeight.Medium })
  14866. .fontColor(Color.White)
  14867. .margin({ left: 25 })
  14868. .margin({top:more.id >= 22?3:0})
  14869. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  14870. .selected(this.spectrumModeIndex)
  14871. .value(['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'][this.spectrumModeIndex])
  14872. .onSelect((index: number, _text?: string) => {
  14873. this.spectrumModeIndex = index;
  14874. // 使用同步方法保存,确保立即生效
  14875. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  14876. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  14877. const modeNames = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  14878. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  14879. });
  14880. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  14881. .selectedColor(this.themeColor)
  14882. .switchPointColor(Color.White)
  14883. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14884. .margin({ right: 15 })
  14885. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  14886. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14887. if (more.id == 22) {
  14888. this.showSimple = checked;
  14889. PreferencesUtil.put('showSimple', this.showSimple)
  14890. }
  14891. })
  14892. .width(48)
  14893. .height(24);
  14894. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  14895. .selectedColor(this.themeColor)
  14896. .switchPointColor(Color.White)
  14897. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14898. .margin({ right: 15 })
  14899. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  14900. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14901. if (more.id == 23) {
  14902. this.enablePointLight = checked;
  14903. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  14904. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  14905. }
  14906. })
  14907. .width(48)
  14908. .height(24);
  14909. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  14910. .selectedColor(this.themeColor)
  14911. .switchPointColor(Color.White)
  14912. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14913. .margin({ right: 15 })
  14914. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  14915. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14916. if (more.id == 27) {
  14917. this.isGeKongPlayNext = checked;
  14918. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  14919. }
  14920. })
  14921. .width(48)
  14922. .height(24);
  14923. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  14924. .selectedColor(this.themeColor)
  14925. .switchPointColor(Color.White)
  14926. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14927. .margin({ right: 15 })
  14928. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  14929. .onChange((checked: boolean) => { // 是否开启背景流光效果
  14930. if (more.id == 21) {
  14931. this.isShowBgLiuGUANG = checked;
  14932. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  14933. }
  14934. })
  14935. .width(48)
  14936. .height(24);
  14937. }
  14938. }
  14939. .width('100%')
  14940. .height(45)
  14941. .padding(15)
  14942. .backgroundColor(Color.Transparent)
  14943. .borderRadius(12)
  14944. .margin({ bottom: 6 })
  14945. }
  14946. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  14947. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  14948. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  14949. .backgroundColor(Color.Transparent)
  14950. .onClick(() => {
  14951. this.doMore(more.id)
  14952. })
  14953. });
  14954. }
  14955. .width('100%')
  14956. .padding(16)
  14957. }.margin({ bottom: 18 })
  14958. }
  14959. @Builder
  14960. TPImageBuilder(more: MoreItem): void {
  14961. Row() {
  14962. Image($r('app.media.tuoping'))
  14963. .width(22)
  14964. .height(22)
  14965. .margin({ left: 10, right: 10 })
  14966. Text(more.title)
  14967. .fontSize(16)
  14968. .fontColor(Color.White)
  14969. }
  14970. .width('100%')
  14971. .layoutWeight(1)
  14972. .alignItems(VerticalAlign.Center)
  14973. .justifyContent(FlexAlign.Start)
  14974. }
  14975. private moreItems: MoreItem[] = [
  14976. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  14977. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  14978. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  14979. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  14980. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  14981. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  14982. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  14983. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  14984. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  14985. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  14986. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  14987. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  14988. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  14989. { id: 4, image: $r('app.media.share2'), title: '分享' },
  14990. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  14991. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  14992. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  14993. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  14994. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  14995. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  14996. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  14997. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  14998. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  14999. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  15000. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  15001. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  15002. ];
  15003. @State isShowBgLiuGUANG: boolean = false;
  15004. @State isShowMoreView: boolean = false;
  15005. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  15006. @State isShowTimeCloseMore: boolean = false
  15007. @State isShowDetailMore: boolean = false
  15008. @State isMusicBGCover: boolean = true
  15009. @State isSavePlayMode: boolean = true
  15010. @State isLyricSetting: boolean = false
  15011. @State isJumpSetting: boolean = false
  15012. @State isShowEdit: boolean = false
  15013. @State showPipLyric: boolean = false
  15014. @State isShowSpectrum: boolean = false//是否显示频谱
  15015. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  15016. private getEqualizerVolumeBoostRisk(): number {
  15017. const equalizerManager = EqualizerManager.getInstance();
  15018. if (!equalizerManager.enabled) {
  15019. return 0;
  15020. }
  15021. const gainStats = equalizerManager.getCurrentGainStats();
  15022. if (gainStats.maxPositiveGain <= 0 || gainStats.positiveGainSum <= 0) {
  15023. return 0;
  15024. }
  15025. const peakRisk = (gainStats.maxPositiveGain / 12) * 0.65;
  15026. const spreadRisk = (gainStats.positiveGainSum / 24) * 0.35;
  15027. return Math.max(0, Math.min(peakRisk + spreadRisk, 1));
  15028. }
  15029. private getSafeBoostPercent(): number {
  15030. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  15031. let compressedBoostPercent = rawBoostPercent;
  15032. if (rawBoostPercent <= 150) {
  15033. compressedBoostPercent = rawBoostPercent;
  15034. } else if (rawBoostPercent <= 300) {
  15035. compressedBoostPercent = 150 + (rawBoostPercent - 150) * 0.45;
  15036. } else {
  15037. compressedBoostPercent = 217.5 + (rawBoostPercent - 300) * 0.15;
  15038. }
  15039. const equalizerRisk = this.getEqualizerVolumeBoostRisk();
  15040. if (equalizerRisk <= 0) {
  15041. return compressedBoostPercent;
  15042. }
  15043. const protectedBoostPercent = compressedBoostPercent * (1 - equalizerRisk * 0.45);
  15044. const cappedBoostPercent = 220 - equalizerRisk * 140;
  15045. return Math.max(0, Math.min(protectedBoostPercent, cappedBoostPercent));
  15046. }
  15047. private getVolumeBoostFactor(): number {
  15048. return 1 + this.getSafeBoostPercent() / 100;
  15049. }
  15050. private getCurrentOutputVolume(): number {
  15051. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  15052. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  15053. const maxOutputVolume = this.getVolumeBoostFactor();
  15054. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  15055. }
  15056. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  15057. if (!this.mIjkMediaPlayer) {
  15058. return;
  15059. }
  15060. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  15061. this.mIjkMediaPlayer.setVolume('1', '1');
  15062. return;
  15063. }
  15064. const outputVolume = this.getCurrentOutputVolume();
  15065. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  15066. }
  15067. async setRingTone() {
  15068. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  15069. return
  15070. }
  15071. // 确定后的逻辑
  15072. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  15073. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  15074. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  15075. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  15076. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  15077. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  15078. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  15079. , this.videoUrl, this.name).then(res => {
  15080. LogUtil.info('onecold setFlag :' + res);
  15081. });
  15082. }
  15083. doMore(moreId: number) {
  15084. switch (moreId) {
  15085. case 30: //歌词
  15086. this.isLyricSetting = !this.isLyricSetting;
  15087. this.isShowMoreView = false
  15088. break;
  15089. case 3: //详情
  15090. this.isShowDetailMore = !this.isShowDetailMore;
  15091. break;
  15092. case 4: //分享
  15093. if (this.currentSong !== undefined) {
  15094. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  15095. }
  15096. this.isShowMoreView = false
  15097. break;
  15098. case 5: //定时关闭
  15099. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  15100. break;
  15101. case 10: //设为铃声
  15102. this.setRingTone()
  15103. this.isShowMoreView = false
  15104. break;
  15105. case 11: //跳过头尾
  15106. this.isJumpSetting = !this.isJumpSetting;
  15107. break;
  15108. case 13: //倍速
  15109. break;
  15110. case 14: //搜索封面
  15111. if (this.currentSong !== undefined) {
  15112. this.doSearchCover(this.currentSong)
  15113. }
  15114. this.isShowMoreView = false
  15115. break;
  15116. case 15: //编辑标签
  15117. this.initEditFields(this.currentSong)
  15118. this.tempLyricContent = this.lyricContent
  15119. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  15120. this.lyricConStr = this.tempLyricContent
  15121. }
  15122. this.isShowEdit = !this.isShowEdit;
  15123. break;
  15124. case 16: //悬浮歌词
  15125. this.showPipLyric = !this.showPipLyric;
  15126. break;
  15127. case 17: //横屏模式
  15128. if (this.isLandscape) {
  15129. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  15130. } else {
  15131. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  15132. }
  15133. this.isShowMoreView = false
  15134. break;
  15135. case 20://AB循环
  15136. this.isABSheet = !this.isABSheet
  15137. break;
  15138. case 24://均衡器
  15139. this.isEqualizerSheet = !this.isEqualizerSheet
  15140. break;
  15141. }
  15142. }
  15143. //AB循环
  15144. @State isOpenAB:boolean = false
  15145. @State jumpATime:number = 0
  15146. @State jumpBTime:number = 0
  15147. @State isABSheet:boolean = false
  15148. @State isEqualizerSheet: boolean = false
  15149. @State eqApplying: boolean = false
  15150. @State eqAppliedAt: number = 0
  15151. @State eqCurrentPresetName: string = '正常'
  15152. @State eqCurrentEnabled: boolean = false
  15153. @Builder
  15154. ABLoopSheet() {
  15155. ABLoopComptent({
  15156. jumpATime:this.jumpATime,
  15157. jumpBTime:this.jumpBTime,
  15158. onClickAItem: async ()=>{
  15159. if(this.mIjkMediaPlayer){
  15160. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  15161. }
  15162. },
  15163. onClickBItem: async ()=>{
  15164. if(this.mIjkMediaPlayer){
  15165. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  15166. if(this.jumpBTime<=this.jumpATime){
  15167. ToastUtil.showToast('设置B点时间不能小于A点时间')
  15168. this.jumpBTime = 0
  15169. }
  15170. }
  15171. },
  15172. onCancleButtonClick: async ()=>{
  15173. this.isOpenAB = false
  15174. this.isABSheet = false
  15175. },
  15176. onStartButtonClick: async ()=>{
  15177. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  15178. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  15179. return
  15180. }
  15181. this.isABSheet = false
  15182. this.startABLoop()
  15183. },
  15184. })
  15185. }
  15186. private syncEqualizerUi(): void {
  15187. const equalizerManager = EqualizerManager.getInstance();
  15188. this.eqCurrentEnabled = equalizerManager.enabled;
  15189. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15190. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  15191. this.eqAppliedAt = 0;
  15192. }
  15193. }
  15194. private markEqualizerApplied(): void {
  15195. const equalizerManager = EqualizerManager.getInstance();
  15196. this.eqCurrentEnabled = equalizerManager.enabled;
  15197. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15198. this.eqAppliedAt = Date.now();
  15199. this.eqApplying = false;
  15200. }
  15201. private applyEqualizerToCurrentPlayback(): void {
  15202. if (this.eqApplying) {
  15203. return;
  15204. }
  15205. if (this.castControllerWrapper && this.isCastPlaying) {
  15206. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  15207. return;
  15208. }
  15209. if (!this.currentSong || !this.mIjkMediaPlayer) {
  15210. ToastUtil.showToast('暂无可应用的播放');
  15211. return;
  15212. }
  15213. this.eqApplying = true;
  15214. try {
  15215. const equalizerManager = EqualizerManager.getInstance();
  15216. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15217. this.applyCurrentVolume();
  15218. this.markEqualizerApplied();
  15219. ToastUtil.showToast('均衡器已实时生效');
  15220. } catch (error) {
  15221. this.eqApplying = false;
  15222. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  15223. }
  15224. }
  15225. @Builder
  15226. private EqualizerApplyStatusBar(): void {
  15227. Row() {
  15228. Column() {
  15229. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  15230. .fontSize(12)
  15231. .fontColor($r('app.color.text_color'))
  15232. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  15233. .fontSize(10)
  15234. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  15235. }
  15236. .alignItems(HorizontalAlign.Start)
  15237. Blank()
  15238. Button('重新应用')
  15239. .fontSize(12)
  15240. .fontColor(Color.White)
  15241. .backgroundColor('#666666')
  15242. .height(28)
  15243. .padding({ left: 14, right: 14 })
  15244. .borderRadius(14)
  15245. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  15246. .onClick(() => {
  15247. this.applyEqualizerToCurrentPlayback();
  15248. })
  15249. }
  15250. .width('100%')
  15251. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  15252. .backgroundColor($r('app.color.settings_background_main'))
  15253. .borderRadius(12)
  15254. }
  15255. @Builder
  15256. EqualizerSheet() {
  15257. Column() {
  15258. Column() {
  15259. EqualizerViewWithCallback({
  15260. onEqualizerChanged: () => {
  15261. this.syncEqualizerUi();
  15262. if (this.mIjkMediaPlayer) {
  15263. const equalizerManager = EqualizerManager.getInstance();
  15264. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15265. this.applyCurrentVolume();
  15266. this.markEqualizerApplied();
  15267. }
  15268. }
  15269. })
  15270. }
  15271. .margin({ top: 8 })
  15272. Column() {
  15273. this.EqualizerApplyStatusBar()
  15274. }
  15275. .margin({ top: 8 })
  15276. }
  15277. .padding({ left: 12, right: 12, bottom: 20 })
  15278. .width('100%')
  15279. }
  15280. //开始AB循环
  15281. startABLoop(){
  15282. if(this.mIjkMediaPlayer){
  15283. this.seekTo(this.jumpATime+'')
  15284. this.isOpenAB = true
  15285. }
  15286. }
  15287. /**
  15288. * 切换横竖屏
  15289. *
  15290. */
  15291. setOrientation(orientation: number) {
  15292. this.windowClass.setPreferredOrientation(orientation).then(() => {
  15293. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  15294. }).catch((err: BusinessError) => {
  15295. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  15296. });
  15297. }
  15298. /**
  15299. * 画中画功能(悬浮歌词功能)
  15300. *
  15301. */
  15302. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  15303. pipController?: PiPWindow.PiPController;
  15304. navigationId: string = '';
  15305. @State curState: string = '';
  15306. @State curError: ResourceStr = '';
  15307. @State pipBg: string = '#E8E8E8'
  15308. @State buttonAction: string = '';
  15309. //开启画中画功能
  15310. async startPip() {
  15311. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  15312. if (!this.pipController) {
  15313. await this.createPipController();
  15314. }
  15315. if (!this.pipController) {
  15316. Logger.info(`[${TAG}] pipController create error`);
  15317. return;
  15318. }
  15319. await this.pipController.startPiP();
  15320. }
  15321. async stopPip() {
  15322. if (!this.pipController) {
  15323. Logger.info(`[${TAG}] pipController is not exist`);
  15324. return;
  15325. }
  15326. this.isOpenPip = false
  15327. await this.pipController.stopPiP();
  15328. }
  15329. async createPipController() {
  15330. this.pipController = await PiPWindow.create({
  15331. context: getContext(this),
  15332. componentController: this.xcomponentController,
  15333. navigationId: this.navigationId,
  15334. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  15335. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  15336. customUIController: this.nodeController,
  15337. });
  15338. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  15339. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  15340. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  15341. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  15342. this.onStateChange(state, reason);
  15343. });
  15344. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  15345. this.onActionEvent(event, status);
  15346. });
  15347. }
  15348. destroyPipController() {
  15349. if (!this.pipController) {
  15350. return;
  15351. }
  15352. this.pipController.off('stateChange');
  15353. this.pipController.off('controlPanelActionEvent');
  15354. this.pipController = undefined;
  15355. }
  15356. onStateChange(state: PiPWindow.PiPState, reason: string) {
  15357. switch (state) {
  15358. case PiPWindow.PiPState.ABOUT_TO_START:
  15359. this.curState = 'ABOUT_TO_START';
  15360. this.curError = $r('app.string.current_error_hint');
  15361. break;
  15362. case PiPWindow.PiPState.STARTED:
  15363. this.curState = 'STARTED';
  15364. this.curError = $r('app.string.current_error_hint');
  15365. break;
  15366. case PiPWindow.PiPState.ABOUT_TO_STOP:
  15367. this.curState = 'ABOUT_TO_STOP';
  15368. this.curError = $r('app.string.current_error_hint');
  15369. break;
  15370. case PiPWindow.PiPState.STOPPED:
  15371. this.curState = 'STOPPED';
  15372. this.curError = $r('app.string.current_error_hint');
  15373. this.stopPip()
  15374. this.destroyPipController()
  15375. break;
  15376. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  15377. this.curState = 'ABOUT_TO_RESTORE';
  15378. this.curError = $r('app.string.current_error_hint');
  15379. break;
  15380. case PiPWindow.PiPState.ERROR:
  15381. this.curState = 'ERROR';
  15382. this.curError = reason;
  15383. break;
  15384. default:
  15385. break;
  15386. }
  15387. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  15388. }
  15389. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  15390. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  15391. switch (event) {
  15392. case 'playbackStateChanged':
  15393. if (status === 0) {
  15394. this.pause();
  15395. } else {
  15396. console.info('onecold startPlayOrResumePlay 9869')
  15397. this.startPlayOrResumePlay();
  15398. }
  15399. break;
  15400. case 'nextVideo':
  15401. // 切换到下一个视频
  15402. this.playbackController.playNext().catch(() => {
  15403. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  15404. });
  15405. break;
  15406. case 'previousVideo':
  15407. // 切换到上一个视频
  15408. this.playbackController.playPrevious().catch(() => {
  15409. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  15410. });
  15411. break;
  15412. case 'previousVideo':
  15413. // 切换到上一个视频
  15414. this.playbackController.playPrevious().catch(() => {
  15415. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  15416. });
  15417. break;
  15418. default:
  15419. }
  15420. this.buttonAction = event + `-status:${status}`;
  15421. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  15422. }
  15423. /**
  15424. * 画中画功能(悬浮歌词功能)结束
  15425. *
  15426. */
  15427. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  15428. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  15429. this.isShowMoreView = false;
  15430. this.showTipsDialog();
  15431. return ''; // Return empty string when no API is configured
  15432. }
  15433. if (!item) {
  15434. return ''; // Return empty string if item is undefined
  15435. }
  15436. const titleS = title||item?.name || '';
  15437. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  15438. return this.searchCover(item, titleS, artistS, true); // Await is not needed here as we return the promise directly
  15439. }
  15440. /**
  15441. *api搜索封面
  15442. *item,根据title和artist
  15443. */
  15444. searchCover(item: VideoItem, title: string, artist: string, markAsCustomCover: boolean = false): Promise<string> {
  15445. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  15446. LogUtil.debug("onecold res =" + res);
  15447. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  15448. if (item.filePath == this.currentSong?.filePath) {
  15449. if (this.currentSong) {
  15450. mergeCoverWithPriority(this.currentSong, res, markAsCustomCover ? 1 : 0);
  15451. this.cover = this.currentSong.pixelMapPath || res;
  15452. }
  15453. }
  15454. if (isRemoteCloudType(item.type)) {
  15455. mergeCoverWithPriority(item, res, markAsCustomCover ? 1 : 0);
  15456. this.syncRemoteManagerSong(item);
  15457. try {
  15458. await this.persistRemoteMetadataToDb(item);
  15459. this.emitRemoteMetadataUpdated(item);
  15460. } catch (error) {
  15461. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  15462. }
  15463. } else {
  15464. // Update pixel map path but always return res regardless of success
  15465. if (markAsCustomCover) {
  15466. item.isCustomCover = 1;
  15467. this.table.updateCustomCoverPath(item.filePath, res, (success: boolean, error?: string) => {
  15468. if (success) {
  15469. this.doUpdateData();
  15470. console.log("onecold 更新音乐封面成功,数据库已同步");
  15471. } else {
  15472. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15473. }
  15474. });
  15475. } else {
  15476. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  15477. if (success) {
  15478. this.doUpdateData();
  15479. console.log("onecold 更新音乐封面成功,数据库已同步");
  15480. } else {
  15481. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15482. }
  15483. });
  15484. }
  15485. }
  15486. LogUtil.debug("onecold this.cover =" + this.cover);
  15487. }
  15488. return res; // Always return res regardless of updatePixelMapPath result
  15489. });
  15490. }
  15491. @State jumpTopTime: number = 0
  15492. @State jumpEndTime: number = 0
  15493. @State isOpenJump: boolean = false
  15494. @Builder
  15495. JumpTopEndSheet() {
  15496. Scroll() {
  15497. Column() {
  15498. Column() {
  15499. Text('仅对本播放列表有效')
  15500. .fontSize(16)
  15501. .fontColor($r('app.color.text_color'))
  15502. // 跳过头尾
  15503. Column() {
  15504. Row() {
  15505. Text('跳过片头:')
  15506. .fontSize(16)
  15507. .fontColor($r('app.color.text_color'))
  15508. Text(this.jumpTopTime + 's')
  15509. .fontSize(16)
  15510. .fontColor($r('app.color.text_color'))
  15511. }
  15512. .margin({ bottom: 5 })
  15513. Row() {
  15514. Slider({
  15515. value: this.jumpTopTime,
  15516. min: 0,
  15517. max: 120,
  15518. step: 1,
  15519. style: SliderStyle.OutSet
  15520. })
  15521. .blockColor(this.themeColor)
  15522. .trackColor($r('app.color.speed_text_color'))
  15523. .selectedColor(Color.White)
  15524. .trackThickness(8)
  15525. .onChange((value: number) => {
  15526. this.jumpTopTime = value;
  15527. })
  15528. .width('85%')
  15529. }
  15530. .alignItems(VerticalAlign.Top)
  15531. }
  15532. .margin({ top: 10, bottom: 10 })
  15533. // 跳过头尾
  15534. Column() {
  15535. Row() {
  15536. Text('跳过片尾:')
  15537. .fontSize(16)
  15538. .fontColor($r('app.color.text_color'))
  15539. Text(this.jumpEndTime + 's')
  15540. .fontSize(16)
  15541. .fontColor($r('app.color.text_color'))
  15542. }
  15543. .margin({ bottom: 5 })
  15544. Row() {
  15545. Slider({
  15546. value: this.jumpEndTime,
  15547. min: 0,
  15548. max: 120,
  15549. step: 1,
  15550. style: SliderStyle.OutSet
  15551. })
  15552. .blockColor(this.themeColor)
  15553. .trackColor($r('app.color.speed_text_color'))
  15554. .selectedColor(Color.White)
  15555. .trackThickness(8)
  15556. .onChange((value: number) => {
  15557. this.jumpEndTime = value;
  15558. })
  15559. .width('85%')
  15560. }
  15561. .alignItems(VerticalAlign.Top)
  15562. }
  15563. .margin({ top: 10, bottom: 10 })
  15564. Row() {
  15565. Button('保存设置')
  15566. .fontColor(Color.White)
  15567. .layoutWeight(1)
  15568. .height(40)
  15569. .width(80)
  15570. .backgroundColor(this.themeColor)
  15571. .stateEffect(true)
  15572. .margin({ left: 0, bottom: 20 })
  15573. .onClick(async () => {
  15574. if (!Utility.isNoble()) {
  15575. this.isJumpSetting = false
  15576. this.isShowMoreView = false
  15577. this.showVipDialog()
  15578. return
  15579. }
  15580. if (this.currentSong === undefined) {
  15581. return
  15582. }
  15583. if (this.modeType === 0) {
  15584. let parentPath = FileUtil.getParentPath(this.videoUrl)
  15585. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  15586. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  15587. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  15588. } else if (this.modeType === 1) { //媒体库
  15589. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  15590. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  15591. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  15592. } else if (this.modeType === 2) { //艺术家
  15593. if (this.currentSong?.artist) {
  15594. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  15595. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  15596. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  15597. }
  15598. } else if (this.modeType === 3) { //专辑
  15599. if (this.currentSong?.album) {
  15600. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  15601. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  15602. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  15603. }
  15604. }
  15605. ToastUtil.showShort("保存成功")
  15606. this.isJumpSetting = false
  15607. })
  15608. }
  15609. .margin({
  15610. left: 38,
  15611. right: 38,
  15612. top: 10,
  15613. bottom: 10
  15614. })
  15615. .width(120)
  15616. .height(50)
  15617. }
  15618. }
  15619. }
  15620. .width('100%')
  15621. .height('100%')
  15622. }
  15623. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  15624. private onStateVastChange(state: AVCastPickerState) {
  15625. if (state == AVCastPickerState.STATE_APPEARING) {
  15626. console.log('The picker starts showing.');
  15627. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  15628. console.log('The picker finishes presenting.');
  15629. }
  15630. }
  15631. private showSelectLyric() {
  15632. DialogHelper.showActionSheetDialog({
  15633. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  15634. // sheets: ["本地歌词", "搜索歌词"],
  15635. sheets: [
  15636. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  15637. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  15638. ],
  15639. maskColor: Color.Transparent,
  15640. backgroundColor: $r('app.color.bg_card'),
  15641. transition: AnimationHelper.transitionInDown(666),
  15642. onAction: (index) => {
  15643. switch (index) {
  15644. case 0:
  15645. this.callFilePickerSelectFileForLyric()
  15646. break;
  15647. case 1:
  15648. if (StrUtil.isNotEmpty(this.videoUrl)) {
  15649. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15650. this.initLyric(lyricPath);
  15651. }
  15652. break;
  15653. }
  15654. }
  15655. })
  15656. }
  15657. // 拉起picker选择文件管理器
  15658. async callFilePickerSelectFileForLyric(): Promise<void> {
  15659. try {
  15660. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  15661. DocumentSelectOptions.maxSelectNumber = 1
  15662. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  15663. let documentPicker = new picker.DocumentViewPicker();
  15664. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  15665. Logger.info(TAG,
  15666. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  15667. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  15668. this.saveVideoDatasLyric(DocumentSelectResult)
  15669. }
  15670. }).catch((err: BusinessError) => {
  15671. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  15672. });
  15673. } catch (err) {
  15674. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  15675. }
  15676. }
  15677. async saveVideoDatasLyric(uris: string[]) {
  15678. if (ArrayUtil.isEmpty(uris)) {
  15679. return
  15680. }
  15681. let newUris: string[] = [];
  15682. for (let i = 0; i < uris.length; i++) {
  15683. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  15684. Logger.info(TAG, 'filePath uri: ' + filePath);
  15685. newUris.push(filePath)
  15686. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  15687. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  15688. fileIo.copyFileSync(file.fd, file2.fd)
  15689. fileIo.closeSync(file);
  15690. fileIo.closeSync(file2);
  15691. this.initLyric(filePath,false,false,true)
  15692. }
  15693. }
  15694. private initDelayPlay(context: object) {
  15695. this.mContext = context;
  15696. }
  15697. startPipLyric() {
  15698. if (this.pipController) {
  15699. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15700. PiPWindow.PiPControlStatus.PLAY);
  15701. }
  15702. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  15703. if (this.isOpenPip) {
  15704. this.startPip()
  15705. } else {
  15706. this.stopPip()
  15707. }
  15708. }
  15709. //startOffset 从cue分轨时间开始播
  15710. private startPlayOrResumePlay(startOffset?:number) {
  15711. this.isHostSnapshotDisplayOnly = false
  15712. let finalStartOffset = startOffset
  15713. if ((finalStartOffset === undefined || finalStartOffset === null) && this.currentSong && isCueSplitItem(this.currentSong)) {
  15714. finalStartOffset = 0
  15715. }
  15716. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  15717. //针对dsf文件高采样率,统一转wav播放
  15718. // const sampleRate = this.currentSong?.sampleRate||0
  15719. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  15720. // console.info('onecold 采样率 ='+sampleRate)
  15721. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  15722. // console.info('onecold newDsfPath ='+newDsfPath)
  15723. // if(!FileUtil.accessSync(newDsfPath)){
  15724. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  15725. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  15726. // this.videoUrl = newDsfPath
  15727. // this.startPlay(startOffset)
  15728. // }).catch((e:object)=>{
  15729. // console.info("task1 catch e: " + e);
  15730. // })
  15731. // }else{
  15732. // this.videoUrl = newDsfPath
  15733. // this.startPlay(startOffset)
  15734. // }
  15735. //
  15736. // }else{
  15737. // this.startPlay(startOffset)
  15738. // }
  15739. this.startPlay(finalStartOffset)
  15740. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  15741. // 排除用户拖动进度条的情况
  15742. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  15743. void this.preloadNextSongInternal();
  15744. }
  15745. }
  15746. startPlay(startOffset?:number) {
  15747. this.startPipLyric()
  15748. this.mDestroyPage = false;
  15749. this.animationState = AnimationStatus.Running
  15750. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  15751. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  15752. this.stopProgressTask();
  15753. this.startProgressTask();
  15754. this.clearInitialSeekGuardTimer();
  15755. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  15756. this.remoteRestoreSeekToken++;
  15757. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  15758. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  15759. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  15760. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  15761. this.videoUrl.includes('://');
  15762. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  15763. // 网盘歌曲起播阶段统一显示加载圈,prepared/首帧后再收起
  15764. this.isPlayerLoading = !!isRemoteStreamSong;
  15765. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15766. Logger.info(
  15767. TAG,
  15768. `[remote-play] startPlay type=${this.currentSong.type}, memory=${this.pendingMemorySeekPosition}, ` +
  15769. `waitInitial=${this.waitInitialSeekBeforeStart}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15770. );
  15771. }
  15772. this.play(this.videoUrl.toString(),startOffset);
  15773. }
  15774. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  15775. this.mIjkMediaPlayer.start();
  15776. this.setProgress()
  15777. this.CONTROL_PlayStatus = PlayStatus.PLAY
  15778. }
  15779. this.setIsPlaying(true)
  15780. this.updateSessionPlayState(true)
  15781. this.watchStatus();
  15782. this.updateLastPlayTimeStr(this.videoUrl)
  15783. }
  15784. updateLastPlayTimeStr(filePath: string) {
  15785. const activeSong = this.currentSong;
  15786. let targetFilePath = this.currentSong?.filePath || filePath;
  15787. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15788. const remoteStoragePath = this.resolveRemoteStoragePath(activeSong);
  15789. if (remoteStoragePath) {
  15790. targetFilePath = remoteStoragePath;
  15791. }
  15792. Logger.info(`heanup 检测到网络音频播放,改为更新远程歌曲最近播放: ${targetFilePath}`)
  15793. }
  15794. if (!targetFilePath) {
  15795. Logger.warn(TAG, `更新最近播放时间失败,目标路径为空: ${filePath}`);
  15796. return;
  15797. }
  15798. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  15799. const applyHistoryUpdate = (): void => {
  15800. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (success: boolean, error?: string) => {
  15801. if (success) {
  15802. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15803. this.currentSong.lastPlayedStr = lastPlayTime
  15804. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15805. }
  15806. this.getHistoryList(false)
  15807. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  15808. return;
  15809. }
  15810. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15811. Logger.warn(TAG, `远程歌曲最近播放更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  15812. this.persistRemoteMetadataToDb(activeSong)
  15813. .then(() => {
  15814. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (retrySuccess: boolean,
  15815. retryError?: string) => {
  15816. if (retrySuccess) {
  15817. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15818. this.currentSong.lastPlayedStr = lastPlayTime
  15819. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15820. }
  15821. this.getHistoryList(false)
  15822. Logger.info(TAG, `远程歌曲最近播放补入库后更新成功: ${targetFilePath}`);
  15823. } else {
  15824. Logger.error(TAG,
  15825. `远程歌曲最近播放补入库后仍更新失败: ${targetFilePath}, error=${retryError}`);
  15826. }
  15827. });
  15828. })
  15829. .catch((persistError: Error) => {
  15830. Logger.error(TAG,
  15831. `远程歌曲最近播放补入库失败: ${targetFilePath}, error=${persistError.message}`);
  15832. });
  15833. return;
  15834. }
  15835. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  15836. });
  15837. };
  15838. applyHistoryUpdate();
  15839. }
  15840. private completionNum(num: number): string | number {
  15841. if (num < 10) {
  15842. return '0' + num;
  15843. } else {
  15844. return num;
  15845. }
  15846. }
  15847. private parseDurationToMs(duration?: string): number {
  15848. if (!duration) {
  15849. return 0;
  15850. }
  15851. const parts = duration.split(':').map((item) => Number(item));
  15852. if (parts.some((item) => Number.isNaN(item))) {
  15853. return 0;
  15854. }
  15855. if (parts.length === 2) {
  15856. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  15857. }
  15858. if (parts.length === 3) {
  15859. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  15860. }
  15861. return 0;
  15862. }
  15863. private sanitizePlaybackUrl(url?: string): string {
  15864. if (!url) {
  15865. return '';
  15866. }
  15867. let sanitized = url.replace(/(access_token=)[^&]+/ig, '$1***');
  15868. sanitized = sanitized.replace(/(refresh_token=)[^&]+/ig, '$1***');
  15869. sanitized = sanitized.replace(/(Authorization=)[^&]+/ig, '$1***');
  15870. if (sanitized.length > 220) {
  15871. return `${sanitized.substring(0, 220)}...`;
  15872. }
  15873. return sanitized;
  15874. }
  15875. private sanitizePlaylistDebugPath(path?: string): string {
  15876. if (!path) {
  15877. return '';
  15878. }
  15879. return path.length > 48 ? `...${path.substring(path.length - 48)}` : path;
  15880. }
  15881. private buildSongDebugItem(item?: VideoItem): string {
  15882. if (!item) {
  15883. return 'unknown';
  15884. }
  15885. const title = item.name || item.fileName || '未知歌曲';
  15886. return `${title}|type=${item.type}|acc=${item.webdav_account_id || ''}|path=${this.sanitizePlaylistDebugPath(item.filePath)}`;
  15887. }
  15888. private buildSongListDebugLog(items: VideoItem[], limit: number = 5): string {
  15889. if (!items || items.length === 0) {
  15890. return '[]';
  15891. }
  15892. const parts: string[] = [];
  15893. const maxCount = Math.min(limit, items.length);
  15894. for (let i = 0; i < maxCount; i++) {
  15895. parts.push(this.buildSongDebugItem(items[i]));
  15896. }
  15897. return `[${parts.join('; ')}](${items.length})`;
  15898. }
  15899. private buildPathListDebugLog(paths: string[], limit: number = 5): string {
  15900. if (!paths || paths.length === 0) {
  15901. return '[]';
  15902. }
  15903. const parts: string[] = [];
  15904. const maxCount = Math.min(limit, paths.length);
  15905. for (let i = 0; i < maxCount; i++) {
  15906. parts.push(this.sanitizePlaylistDebugPath(paths[i]));
  15907. }
  15908. return `[${parts.join('; ')}](${paths.length})`;
  15909. }
  15910. private async dispatchPlaylistPlayRequest(playlistData: PlaylistPlayRequest): Promise<void> {
  15911. clearPendingPlaylistPlay();
  15912. Logger.info(
  15913. TAG,
  15914. `[remote-debug] dispatchPlaylistPlayRequest id=${playlistData.playlistId}, name=${playlistData.playlistName}, ` +
  15915. `songCount=${playlistData.songCount}, startIndex=${playlistData.startIndex}, playType=${playlistData.playType ?? -1}, ` +
  15916. `paths=${this.buildPathListDebugLog(playlistData.songFilePaths)}`
  15917. );
  15918. if (playlistData.playType !== undefined) {
  15919. this.applyRequestedPlayType(playlistData.playType);
  15920. }
  15921. await this.handlePlaylistPlayRequest(
  15922. playlistData.playlistId,
  15923. playlistData.playlistName,
  15924. playlistData.songFilePaths,
  15925. playlistData.startIndex,
  15926. playlistData.isJump ?? false,
  15927. playlistData.songCount
  15928. );
  15929. }
  15930. private async resolvePlaybackUrlForCurrentSong(source: string): Promise<string | null> {
  15931. const song = this.currentSong;
  15932. if (!song) {
  15933. Logger.warn(TAG, `[play-url] skip source=${source}, currentSong is null`);
  15934. return null;
  15935. }
  15936. const expectedFilePath = song.filePath || '';
  15937. const requestSerial = ++this.playbackUrlRequestSerial;
  15938. Logger.info(
  15939. TAG,
  15940. `[play-url] begin serial=${requestSerial}, source=${source}, song=${song.name}, path=${expectedFilePath}`
  15941. );
  15942. const resolvedUrl = await setVideoUrlForSong(song, {
  15943. context: this.context,
  15944. autoParseMusicName: this.autoParseMusicName
  15945. });
  15946. const currentFilePath = this.currentSong?.filePath || '';
  15947. if (requestSerial !== this.playbackUrlRequestSerial || currentFilePath !== expectedFilePath) {
  15948. Logger.warn(
  15949. TAG,
  15950. `[play-url] stale serial=${requestSerial}, source=${source}, expected=${expectedFilePath}, ` +
  15951. `current=${currentFilePath}, drop=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15952. );
  15953. return null;
  15954. }
  15955. Logger.info(
  15956. TAG,
  15957. `[play-url] apply serial=${requestSerial}, source=${source}, song=${song.name}, ` +
  15958. `url=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15959. );
  15960. return resolvedUrl;
  15961. }
  15962. private beginSeekTrace(source: string, requestMs: number): void {
  15963. this.lastSeekSource = source;
  15964. this.lastSeekRequestMs = requestMs;
  15965. this.seekTraceUntilTs = Date.now() + this.seekTraceLogWindowMs;
  15966. this.lastSeekTraceLogTs = 0;
  15967. }
  15968. private isSeekTraceActive(): boolean {
  15969. return this.seekTraceUntilTs > 0 && Date.now() <= this.seekTraceUntilTs;
  15970. }
  15971. private logSeekTrace(stage: string, position?: number, playerDuration?: number, force: boolean = false): void {
  15972. if (!force && !this.isSeekTraceActive()) {
  15973. return;
  15974. }
  15975. const now = Date.now();
  15976. if (!force && now - this.lastSeekTraceLogTs < this.seekTraceLogIntervalMs) {
  15977. return;
  15978. }
  15979. this.lastSeekTraceLogTs = now;
  15980. const currentPosition = typeof position === 'number' ? position : this.mIjkMediaPlayer.getCurrentPosition();
  15981. const resolvedPlayerDuration = typeof playerDuration === 'number' ? playerDuration : this.mIjkMediaPlayer.getDuration();
  15982. Logger.info(
  15983. TAG,
  15984. `[seek-trace] stage=${stage}, source=${this.lastSeekSource || 'unknown'}, req=${this.lastSeekRequestMs}, ` +
  15985. `current=${currentPosition}, playerDuration=${resolvedPlayerDuration}, uiDuration=${this.duration}, ` +
  15986. `activeDuration=${this.getActiveDuration()}, isPlaying=${this.mIjkMediaPlayer.isPlaying()}, ` +
  15987. `isSeekTo=${this.isSeekTo}, waitInitial=${this.waitInitialSeekBeforeStart}, ` +
  15988. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15989. );
  15990. }
  15991. private shouldShowSeekBlockedToast(source: string): boolean {
  15992. return source === 'top-progress-slider' ||
  15993. source === 'landscape-progress-slider' ||
  15994. source === 'fast-forward-button' ||
  15995. source === 'rewind-button' ||
  15996. source === 'session-fast-forward' ||
  15997. source === 'session-rewind' ||
  15998. source === 'session-seek';
  15999. }
  16000. private handleBlockedSeek(seekPos: number, source: string): boolean {
  16001. const decision = resolveSeekGuardDecision(this.videoUrl, seekPos);
  16002. if (decision.allow) {
  16003. return false;
  16004. }
  16005. Logger.warn(
  16006. TAG,
  16007. `[seek] blocked source=${source}, target=${seekPos}, reason=${decision.reason}, ` +
  16008. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16009. );
  16010. if (this.shouldShowSeekBlockedToast(source) && StrUtil.isNotEmpty(decision.toastMessage)) {
  16011. ToastUtil.showToast(decision.toastMessage);
  16012. }
  16013. if (this.waitInitialSeekBeforeStart) {
  16014. this.finishInitialSeekWait(`blocked-${decision.reason}`, true);
  16015. } else {
  16016. this.hideLoadIng();
  16017. }
  16018. this.isSeekTo = false;
  16019. this.logSeekTrace(`seek-blocked-${decision.reason}`, undefined, undefined, true);
  16020. return true;
  16021. }
  16022. private stringForTime(timeMs: number): string {
  16023. let totalSeconds: number | string = (timeMs / 1000);
  16024. let newSeconds: number | string = totalSeconds % 60;
  16025. let minutes: number | string = (totalSeconds / 60) % 60;
  16026. let hours: number | string = totalSeconds / 3600;
  16027. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  16028. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  16029. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  16030. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  16031. if (this.isCurrentTime) {
  16032. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  16033. this.oldSeconds = newSeconds
  16034. } else {
  16035. newSeconds = this.oldSeconds
  16036. }
  16037. }
  16038. newSeconds = this.completionNum(newSeconds);
  16039. if (hours > 0) {
  16040. return hours + ":" + minutes + ":" + newSeconds;
  16041. } else {
  16042. return minutes + ":" + newSeconds;
  16043. }
  16044. }
  16045. private getPlayerSwiperDisplayCount(): number {
  16046. return new BreakpointType<number>({
  16047. sm: 1,
  16048. md: 2,
  16049. lg: 2,
  16050. xl: 2,
  16051. xxl: 2
  16052. }).getValue(this.currentBreakpoint) ?? 1
  16053. }
  16054. private shouldUpdateMainLyricPanel(): boolean {
  16055. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  16056. }
  16057. private getActivePlaybackPositionMs(): number {
  16058. if (this.castControllerWrapper && this.isCastPlaying) {
  16059. return this.currentTime2 * 1000
  16060. }
  16061. return this.mIjkMediaPlayer.getCurrentPosition()
  16062. }
  16063. private notifyPlaybackCardStateChanged(): void {
  16064. try {
  16065. const context = this.getUIContext().getHostContext() as common.UIAbilityContext
  16066. const options = new MusicCardPlaybackStateOptions()
  16067. options.currentSong = this.currentSong
  16068. options.isPlaying = this.CONTROL_PlayStatus === PlayStatus.PLAY
  16069. options.positionMs = this.getActivePlaybackPositionMs()
  16070. options.durationMs = this.getActiveDuration()
  16071. options.lyricText = this.lyricContent
  16072. options.coverPath = this.currentSong?.pixelMapPath ?? this.cover ?? ''
  16073. options.coverImageName = ''
  16074. const snapshot = MusicCardManager.getInstance().buildSnapshotFromPlaybackState(options)
  16075. MusicCardManager.getInstance().notifyPlaybackStateChanged(context, snapshot)
  16076. } catch (error) {
  16077. Logger.warn(TAG, `notifyPlaybackCardStateChanged failed: ${error}`)
  16078. }
  16079. }
  16080. private syncLyricPositionNow(): void {
  16081. const position = this.getActivePlaybackPositionMs()
  16082. if (position < 0) {
  16083. return
  16084. }
  16085. this.updateLyricPosition(position + this.timeOffset * 1000)
  16086. }
  16087. private updateLyricPosition(lyricPosition: number): void {
  16088. if (!this.isAppForeground || !this.isPageVisible) {
  16089. return;
  16090. }
  16091. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  16092. const shouldUpdatePipLyric = this.showPipLyric
  16093. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  16094. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  16095. return
  16096. }
  16097. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  16098. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  16099. return;
  16100. }
  16101. this.lastLyricRenderPosition = lyricPosition;
  16102. if (shouldUpdateMainLyric) {
  16103. this.lyricController.updatePosition(lyricPosition);
  16104. }
  16105. if (shouldUpdatePipLyric) {
  16106. this.lyricControllerXF.updatePosition(lyricPosition);
  16107. }
  16108. if (shouldUpdateSingleLineLyric) {
  16109. this.lyricControllerSingle.updatePosition(lyricPosition);
  16110. }
  16111. }
  16112. private setProgress() {
  16113. if (this.castControllerWrapper && this.isCastPlaying) {
  16114. return;
  16115. }
  16116. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  16117. const rawPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16118. const rawDuration = this.mIjkMediaPlayer.getDuration();
  16119. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  16120. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  16121. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  16122. const cueTrackDuration = cueTrackItem ? getCueTrackDuration(cueTrackItem) : 0;
  16123. let position = rawPosition;
  16124. let duration = rawDuration;
  16125. if (cueTrackItem) {
  16126. position = Math.max(0, rawPosition - cueTrackStartOffset);
  16127. if (cueTrackDuration > 0) {
  16128. duration = cueTrackDuration;
  16129. } else if (cueTrackEndOffset > cueTrackStartOffset) {
  16130. duration = cueTrackEndOffset - cueTrackStartOffset;
  16131. } else if (rawDuration > cueTrackStartOffset) {
  16132. duration = rawDuration - cueTrackStartOffset;
  16133. }
  16134. if (duration > 0 && position > duration) {
  16135. position = duration;
  16136. }
  16137. }
  16138. if (duration <= 0 && this.duration > 0) {
  16139. duration = this.duration;
  16140. }
  16141. let pos = 0;
  16142. if (duration > 0) {
  16143. this.slideEnable = true;
  16144. let curPercent = position / duration;
  16145. pos = curPercent * 100;
  16146. if (shouldRefreshUi) {
  16147. if (pos > this.PROGRESS_MAX_VALUE) {
  16148. this.progressValue = this.PROGRESS_MAX_VALUE
  16149. } else {
  16150. this.progressValue = pos;
  16151. }
  16152. }
  16153. }
  16154. this.logSeekTrace('progress-tick', position, duration);
  16155. // LogUtils.getInstance()
  16156. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  16157. if (shouldRefreshUi) {
  16158. this.totalTime = this.stringForTime(duration);
  16159. }
  16160. if (position > duration) {
  16161. position = duration;
  16162. }
  16163. if (shouldRefreshUi) {
  16164. const lyricPosition = (cueTrackItem ? rawPosition : position) + this.timeOffset * 1000;
  16165. this.isCurrentTime = true;
  16166. this.updateLyricPosition(lyricPosition);
  16167. // 蓝牙歌词更新逻辑
  16168. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  16169. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  16170. // 仅在歌词行变化时更新,避免频繁调用
  16171. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  16172. this.lastBluetoothLyricLine = currentLyricLine;
  16173. this.avSessionController.updateBluetoothLyric(
  16174. currentLyricLine,
  16175. this.currentSong.name || '',
  16176. this.currentSong.artist || '',
  16177. this.bluetoothLyricMode
  16178. );
  16179. }
  16180. }
  16181. this.currentTime = this.stringForTime(position);
  16182. this.isCurrentTime = false
  16183. }
  16184. if (this.mIjkMediaPlayer.isPlaying()) {
  16185. const isCueTrackCompleted = cueTrackItem &&
  16186. cueTrackEndOffset > cueTrackStartOffset &&
  16187. rawPosition >= cueTrackEndOffset;
  16188. //如果是开启AB循环
  16189. if(this.isOpenAB){
  16190. if(position >=this.jumpBTime){
  16191. this.seekTo(this.jumpATime+'')
  16192. return
  16193. }
  16194. }
  16195. // 判断是否播放到结束时间
  16196. if ((this.isOpenJump && duration > this.jumpEndTime * 1000 &&
  16197. position >= duration - this.jumpEndTime * 1000) || isCueTrackCompleted) {
  16198. const completionAction = MusicPlaybackController.resolveCompletionAction(this.playType, this.curIndex,
  16199. this.songList.length)
  16200. if(completionAction.action === 'replay_current'){//跳过尾部如果是单曲循环就选择单曲循环
  16201. this.CONTROL_PlayStatus = PlayStatus.INIT
  16202. this.startPlayOrResumePlay();
  16203. }else if (completionAction.action === 'stop_current') {
  16204. if (completionAction.showBoundaryToast) {
  16205. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  16206. }
  16207. this.stopPlaybackAtTrackEnd(duration, completionAction.showBoundaryToast)
  16208. }else{
  16209. this.playbackController.playNext().catch(() => {
  16210. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  16211. });
  16212. }
  16213. }
  16214. }
  16215. try {
  16216. this.playbackStateBridge.updatePlaybackState(
  16217. this.CONTROL_PlayStatus === PlayStatus.PLAY,
  16218. position,
  16219. duration
  16220. )
  16221. } catch (error) {
  16222. // setProgress 频率较高,这里仅做兜底避免影响主流程
  16223. }
  16224. try {
  16225. MusicCardManager.getInstance().notifyProgressTick(
  16226. this.getUIContext().getHostContext() as common.UIAbilityContext,
  16227. this.currentSong,
  16228. this.CONTROL_PlayStatus === PlayStatus.PLAY,
  16229. position,
  16230. duration,
  16231. this.lyricContent,
  16232. this.currentSong?.pixelMapPath ?? this.cover ?? '',
  16233. ''
  16234. )
  16235. } catch (_error) {
  16236. // 卡片刷新不能影响主播放流程
  16237. }
  16238. }
  16239. private startProgressTask() {
  16240. let that = this;
  16241. if (this.updateProgressTimer) {
  16242. clearInterval(this.updateProgressTimer);
  16243. this.updateProgressTimer = 0;
  16244. }
  16245. this.updateProgressTimer = setInterval(() => {
  16246. //LogUtils.getInstance().LOGI("startProgressTask");
  16247. if (!that.mDestroyPage) {
  16248. that.setProgress();
  16249. }
  16250. }, this.progressUpdateIntervalMs);
  16251. }
  16252. private stopPlaybackAtTrackEnd(duration: number, showBoundaryToast: boolean = false): void {
  16253. if (showBoundaryToast) {
  16254. ToastUtil.showToast('已经是最后一首了')
  16255. }
  16256. this.showRePlay()
  16257. this.currentTime = this.stringForTime(duration)
  16258. this.progressValue = this.PROGRESS_MAX_VALUE
  16259. this.slideEnable = false
  16260. this.stop()
  16261. }
  16262. private dispatchSeekFromPercent(percent: number, source: string): void {
  16263. if (this.isSeekTo) {
  16264. return
  16265. }
  16266. this.isSeekTo = true
  16267. this.mDestroyPage = false
  16268. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  16269. this.showLoadIng()
  16270. }
  16271. const seekValue = MusicPlaybackController.resolveSeekValueFromPercent(percent, this.getActiveDuration())
  16272. void this.playbackController.seekTo(seekValue + '', source)
  16273. }
  16274. private dispatchSeekFromEditorSlider(percent: number, expectedFilePath: string): void {
  16275. if (this.videoUrl != expectedFilePath) {
  16276. this.videoUrl == expectedFilePath
  16277. return
  16278. }
  16279. if (this.isSeekTo) {
  16280. return
  16281. }
  16282. this.isSeekTo = true
  16283. this.mDestroyPage = false
  16284. this.showLoadIng()
  16285. const seekValue = MusicPlaybackController.resolveSeekValueFromPercent(percent, this.getActiveDuration())
  16286. void this.playbackController.seekTo(seekValue + '', 'editor-slider')
  16287. }
  16288. private dispatchSeekToPosition(position: number, source: string): void {
  16289. if (this.isSeekTo) {
  16290. return
  16291. }
  16292. this.isSeekTo = true
  16293. this.mDestroyPage = false
  16294. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  16295. this.showLoadIng()
  16296. }
  16297. void this.playbackController.seekTo(position + '', source)
  16298. }
  16299. private dispatchTogglePlayForItem(item: VideoItem, allowAnyCurrentPlaying: boolean = false): void {
  16300. const toggleAction = MusicPlaybackController.resolveItemPlaybackToggleAction(
  16301. this.videoUrl,
  16302. item.filePath,
  16303. this.isPlaying,
  16304. allowAnyCurrentPlaying
  16305. )
  16306. if (toggleAction === 'toggle_current') {
  16307. this.playbackController.playOrPause()
  16308. return
  16309. }
  16310. this.videoUrl == item.filePath
  16311. this.doPlay(item, 0, false, true)
  16312. }
  16313. private applyCurrentSongMetadata(song?: VideoItem): void {
  16314. if (!song) {
  16315. return
  16316. }
  16317. this.name = song.name
  16318. this.artist = song.artist
  16319. this.notifyPlaybackCardStateChanged()
  16320. }
  16321. private applySelectedQueueSong(index: number): void {
  16322. this.curIndex = index
  16323. this.currentSong = this.songList[this.curIndex]
  16324. this.applyCurrentSongMetadata(this.currentSong)
  16325. this.playbackStateBridge.replaceQueue(this.songList, this.curIndex)
  16326. }
  16327. private ensureSongQueued(song: VideoItem): number {
  16328. const queueFilePaths = this.songList.map((item: VideoItem): string => item.filePath)
  16329. const queueResolution = MusicPlaybackController.resolveQueueSongIndex(queueFilePaths, song.filePath)
  16330. if (queueResolution.shouldAppend) {
  16331. this.songList = [...this.songList, song]
  16332. this.sonDataSource.pushArrayData(this.songList)
  16333. }
  16334. return queueResolution.index
  16335. }
  16336. private markPreparedSongSwitch(song: VideoItem, addToPlayedIndices: boolean = false): void {
  16337. const queueIndex = this.ensureSongQueued(song)
  16338. this.curIndex = queueIndex
  16339. if (addToPlayedIndices) {
  16340. this.playedIndices.add(queueIndex)
  16341. }
  16342. this.CONTROL_PlayStatus = PlayStatus.INIT
  16343. this.stop()
  16344. this.songList[this.curIndex] = song
  16345. this.currentSong = this.songList[this.curIndex]
  16346. }
  16347. private applyCastTrackDurationState(durationMs: number): void {
  16348. if (durationMs <= 0 || !this.currentSong) {
  16349. return
  16350. }
  16351. this.duration = durationMs
  16352. this.durationTime = Math.floor(durationMs / 1000)
  16353. this.durationStringTime = secondToTime(this.durationTime)
  16354. this.totalTime = this.stringForTime(durationMs)
  16355. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent)
  16356. }
  16357. private finalizeLocalTrackSwitch(loadingShown: boolean): void {
  16358. this.CONTROL_PlayStatus = PlayStatus.INIT
  16359. this.stop()
  16360. if (loadingShown) {
  16361. this.showLoadIng()
  16362. }
  16363. this.changeImageAnimation()
  16364. }
  16365. private async prepareCurrentSongPlayback(source: string): Promise<SongPlaybackPreparationResult> {
  16366. const loadingShown = this.beginRemoteSongSwitchLoading(this.currentSong)
  16367. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong(source)
  16368. if (!playbackUrl) {
  16369. if (loadingShown) {
  16370. this.hideLoadIng()
  16371. }
  16372. return {
  16373. success: false,
  16374. loadingShown
  16375. }
  16376. }
  16377. this.videoUrl = playbackUrl
  16378. return {
  16379. success: true,
  16380. loadingShown
  16381. }
  16382. }
  16383. private async startPreparedCurrentSongPlayback(source: string, useSwitchAnimation: boolean = true): Promise<boolean> {
  16384. const preparation = await this.prepareCurrentSongPlayback(source)
  16385. if (!preparation.success) {
  16386. return false
  16387. }
  16388. this.applyCurrentSongMetadata(this.currentSong)
  16389. if (useSwitchAnimation) {
  16390. this.changeImageAnimation()
  16391. } else {
  16392. this.cover = this.currentSong?.pixelMapPath
  16393. this.startPlayOrResumePlay()
  16394. }
  16395. return true
  16396. }
  16397. private async dispatchPreparedQueueSwitch(source: string, castActionName: string,
  16398. castRunner: (durationMs: number) => Promise<void>, updateCoverAfterCast: boolean = false): Promise<void> {
  16399. const preparation = await this.prepareCurrentSongPlayback(source)
  16400. if (!preparation.success) {
  16401. return
  16402. }
  16403. if (this.castControllerWrapper) {
  16404. Logger.info('heanup queueSwitch', `投播模式切歌: ${castActionName}`)
  16405. try {
  16406. const durationMs = this.getSongDurationMs(this.currentSong)
  16407. this.applyCastTrackDurationState(durationMs)
  16408. this.updateCastProgress(0)
  16409. await castRunner(durationMs)
  16410. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying()
  16411. if (preparation.loadingShown) {
  16412. this.hideLoadIng()
  16413. }
  16414. if (updateCoverAfterCast && this.currentSong) {
  16415. this.cover = this.currentSong.pixelMapPath
  16416. }
  16417. return
  16418. } catch (error) {
  16419. Logger.error('heanup queueSwitch', `${castActionName}失败: ${error}`)
  16420. this.isCastPlaying = false
  16421. }
  16422. }
  16423. this.finalizeLocalTrackSwitch(preparation.loadingShown)
  16424. }
  16425. private async ensureRemoteSongAccountAvailable(song: VideoItem, source: string): Promise<boolean> {
  16426. if (!isRemoteCloudType(song.type) || !song.webdav_account_id) {
  16427. return true
  16428. }
  16429. const manager = RemoteDriveManager.getInstance()
  16430. const account = await manager.getWebDavAccountById(song.webdav_account_id)
  16431. if (account) {
  16432. return true
  16433. }
  16434. Logger.warn(TAG, `${source}: 歌曲账号ID无效: ${song.webdav_account_id}, 尝试查找同类型账号`)
  16435. const allAccounts = manager.getAllWebDavAccounts()
  16436. let foundAccount: WebDavAccount | null = null
  16437. for (let i = 0; i < allAccounts.length; i++) {
  16438. if (allAccounts[i].webType === song.type) {
  16439. foundAccount = allAccounts[i]
  16440. break
  16441. }
  16442. }
  16443. if (foundAccount && foundAccount.id) {
  16444. Logger.info(TAG, `${source}: 找到同类型账号,更新webdav_account_id: ${song.webdav_account_id} -> ${foundAccount.id}`)
  16445. song.webdav_account_id = foundAccount.id.toString()
  16446. await this.table.updateWebDavAccountId(song.filePath, foundAccount.id.toString())
  16447. return true
  16448. }
  16449. Logger.error(TAG, `${source}: 无法找到类型为${song.type}的账号`)
  16450. return false
  16451. }
  16452. private stopProgressTask() {
  16453. LogUtils.getInstance().LOGI("stopProgressTask");
  16454. clearInterval(this.updateProgressTimer);
  16455. this.updateProgressTimer = 0;
  16456. }
  16457. private showLoadIng() {
  16458. this.isPlayerLoading = true;
  16459. this.loadingVisible = Visibility.Visible;
  16460. this.replayVisible = Visibility.None;
  16461. }
  16462. private hideLoadIng() {
  16463. this.isPlayerLoading = false;
  16464. this.loadingVisible = Visibility.None;
  16465. this.replayVisible = Visibility.None;
  16466. }
  16467. private showRePlay() {
  16468. this.isPlayerLoading = false;
  16469. this.loadingVisible = Visibility.None;
  16470. this.replayVisible = Visibility.Visible;
  16471. }
  16472. private beginRemoteSongSwitchLoading(song?: VideoItem): boolean {
  16473. const shouldShow = !!song && isRemoteCloudType(song.type);
  16474. if (shouldShow) {
  16475. this.showLoadIng();
  16476. }
  16477. return shouldShow;
  16478. }
  16479. private clearInitialSeekGuardTimer(): void {
  16480. if (this.initialSeekGuardTimer) {
  16481. clearTimeout(this.initialSeekGuardTimer);
  16482. this.initialSeekGuardTimer = 0;
  16483. }
  16484. }
  16485. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  16486. try {
  16487. if (!this.mIjkMediaPlayer.isPlaying()) {
  16488. this.mIjkMediaPlayer.start();
  16489. }
  16490. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16491. this.setIsPlaying(true);
  16492. this.updateSessionPlayState(true);
  16493. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  16494. } catch (error) {
  16495. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  16496. }
  16497. }
  16498. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  16499. this.clearInitialSeekGuardTimer();
  16500. const wasWaiting = this.waitInitialSeekBeforeStart;
  16501. this.waitInitialSeekBeforeStart = false;
  16502. this.pendingMemorySeekPosition = 0;
  16503. this.isPlayerLoading = false;
  16504. this.hideLoadIng();
  16505. if (wasWaiting) {
  16506. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  16507. }
  16508. if (shouldStart) {
  16509. this.ensurePlayerStartedAfterInitialSeek(reason);
  16510. }
  16511. }
  16512. private startInitialSeekGuardTimer(scene: string): void {
  16513. this.clearInitialSeekGuardTimer();
  16514. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  16515. return;
  16516. }
  16517. const token = this.remoteRestoreSeekToken;
  16518. this.initialSeekGuardTimer = setTimeout(() => {
  16519. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  16520. return;
  16521. }
  16522. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  16523. this.finishInitialSeekWait('seek-timeout', true);
  16524. }, this.initialSeekGuardTimeoutMs);
  16525. }
  16526. private async play(url: string,startOffset?:number) {
  16527. this.lyricController.setLyric(null)
  16528. this.lyricControllerSingle.setLyric(null)
  16529. this.lastLyricRenderPosition = Number.NaN;
  16530. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  16531. console.info('onecold this.url 1= '+url)
  16532. if(!url.toLowerCase().startsWith('http')){
  16533. let hasPermission = await PermissionUtil.activatePermission(url)
  16534. console.info('onecold this.hasPermission 1= '+hasPermission)
  16535. if(!url.includes(this.packName)){
  16536. const file = fs.openSync(url)
  16537. this.videoUrl = file.path
  16538. url= this.videoUrl
  16539. }
  16540. console.info('onecold this.hasPermission 1= '+hasPermission)
  16541. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  16542. }
  16543. let that = this;
  16544. const isBaiduStreamingPlayback = isBaiduStreamingPlaybackUrl(url);
  16545. if (this.waitInitialSeekBeforeStart) {
  16546. that.showLoadIng();
  16547. } else {
  16548. that.hideLoadIng();
  16549. }
  16550. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  16551. this.isOpenAB = false
  16552. //设置XComponent回调的context
  16553. if (!!this.mContext) {
  16554. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  16555. }
  16556. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  16557. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  16558. try {
  16559. this.mIjkMediaPlayer.reset();
  16560. Logger.info(TAG, 'IjkPlayer reset 成功');
  16561. } catch (error) {
  16562. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  16563. }
  16564. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16565. //设置debug模式(用于EQ日志采集)
  16566. this.mIjkMediaPlayer.setDebug(true);
  16567. //初始化配置
  16568. this.mIjkMediaPlayer.native_setup();
  16569. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  16570. this.applyCurrentVolume(true);
  16571. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  16572. const headers = new Map<string, string>();
  16573. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  16574. headers.set("Accept", "*/*");
  16575. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  16576. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  16577. //如果封面为空,则搜索封面
  16578. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  16579. }
  16580. // 仅对确实需要额外认证头的远程类型补充请求头。
  16581. // Navidrome/Plex/AudioStation/DaoLiYu 等类型的播放链接已自带认证参数,这里不要再误走 WebDAV 认证分支。
  16582. if (this.currentSong
  16583. && (isWebDavType(this.currentSong.type) || isJellyfinType(this.currentSong.type) || isEmbyType(this.currentSong.type))) {
  16584. Logger.info(`heanup 远程歌曲认证头构建 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  16585. if (this.currentSong.webdav_account_id) {
  16586. try {
  16587. const webdavManager = RemoteDriveManager.getInstance();
  16588. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16589. if (webDavHeaders && webDavHeaders.size > 0) {
  16590. webDavHeaders.forEach((value, key) => headers.set(key, value));
  16591. Logger.info(`heanup 成功通过webdav_account_id获取并合并远程认证头`);
  16592. } else {
  16593. Logger.warn(`heanup 通过webdav_account_id未获取到额外认证头`);
  16594. }
  16595. } catch (error) {
  16596. const err = error as Error;
  16597. Logger.error(`heanup 获取远程认证头时出错: ${err.message}`);
  16598. }
  16599. } else {
  16600. Logger.error(`heanup 远程歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法构建认证头`);
  16601. }
  16602. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  16603. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  16604. }
  16605. // 统一设置带认证的请求头
  16606. // 百度类型也需要特殊请求头
  16607. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  16608. try {
  16609. const webdavManager = RemoteDriveManager.getInstance();
  16610. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16611. baiduHeaders.forEach((value, key) => headers.set(key, value));
  16612. const headerSnapshotList: string[] = [];
  16613. headers.forEach((value, key) => headerSnapshotList.push(`${key}=${value}`));
  16614. Logger.info(TAG, `Baidu播放请求头: ${headerSnapshotList.join('; ')}`);
  16615. } catch (error) {
  16616. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  16617. }
  16618. }
  16619. //设置视频源(先准备好认证头,再设置数据源)
  16620. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  16621. this.mIjkMediaPlayer.setDataSource(url);
  16622. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  16623. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  16624. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  16625. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  16626. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  16627. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  16628. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  16629. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  16630. // 缓冲和播放优化设置
  16631. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  16632. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  16633. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  16634. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  16635. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  16636. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  16637. // 网络相关设置
  16638. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  16639. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  16640. // 重连设置
  16641. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  16642. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  16643. } else if ((this.currentSong && isBaiduType(this.currentSong.type)) || isBaiduStreamingPlayback) {
  16644. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  16645. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  16646. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  16647. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  16648. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  16649. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  16650. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  16651. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  16652. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  16653. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  16654. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  16655. }
  16656. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  16657. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  16658. // }
  16659. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  16660. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  16661. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  16662. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  16663. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  16664. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  16665. //停止预读的最小帧数
  16666. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  16667. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  16668. // 设置其他缓冲相关选项
  16669. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  16670. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  16671. //启动预加载
  16672. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  16673. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  16674. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  16675. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  16676. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  16677. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  16678. // 因此需要播放器丢包,才不会累积延时
  16679. // 这个和第三个参数packet-buffering无关。
  16680. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  16681. // 无限制收流
  16682. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  16683. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  16684. // 屏幕常亮
  16685. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  16686. // 开启hls起播优化 默认是关闭的
  16687. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  16688. // 设置超时
  16689. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  16690. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  16691. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  16692. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  16693. // 变速播放
  16694. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  16695. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  16696. let Speed = this.mIjkMediaPlayer.getSpeed()
  16697. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  16698. //是否开启循环播放
  16699. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  16700. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  16701. (width: number, height: number, sar_num: number, sar_den: number) => {
  16702. if (height === 0) {
  16703. return;
  16704. }
  16705. const va = width / height;
  16706. const vpa = that.videoParentAspectRatio;
  16707. if (vpa > va) {
  16708. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  16709. } else {
  16710. that.videoWidth = '100%';
  16711. }
  16712. if (width && height) {
  16713. that.videoAspectRatio = width / height;
  16714. }
  16715. LogUtils.getInstance()
  16716. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  16717. if (!that.waitInitialSeekBeforeStart) {
  16718. that.hideLoadIng();
  16719. }
  16720. }
  16721. );
  16722. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  16723. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  16724. async () => {
  16725. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  16726. Logger.info(
  16727. TAG,
  16728. `[seek] prepared enter, waitInitial=${this.waitInitialSeekBeforeStart}, pendingMemory=${this.pendingMemorySeekPosition}, ` +
  16729. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16730. );
  16731. if (!this.waitInitialSeekBeforeStart) {
  16732. // 无记忆seek时,prepared后可直接隐藏加载
  16733. this.isPlayerLoading = false;
  16734. }
  16735. try {
  16736. //保存碰一碰分享的当前的歌曲
  16737. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  16738. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  16739. await this.initLyric(lyricPath);
  16740. const applyDuration = (durationMs: number): void => {
  16741. const cueTrackDuration = this.currentSong && isCueSplitItem(this.currentSong)
  16742. ? getCueTrackDuration(this.currentSong)
  16743. : 0;
  16744. const effectiveDuration = cueTrackDuration > 0 ? cueTrackDuration : durationMs;
  16745. if (effectiveDuration <= 0) {
  16746. return;
  16747. }
  16748. this.duration = effectiveDuration;
  16749. this.durationTime = Math.floor(effectiveDuration / 1000);
  16750. this.durationStringTime = secondToTime(this.durationTime);
  16751. this.totalTime = this.stringForTime(effectiveDuration);
  16752. if (this.currentSong) {
  16753. this.currentSong.duration = this.totalTime;
  16754. try {
  16755. this.avSessionController.setAVMetadataMusic(this.currentSong, effectiveDuration, this.lyricContent);
  16756. } catch (metaError) {
  16757. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  16758. }
  16759. }
  16760. };
  16761. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  16762. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  16763. return 0;
  16764. }
  16765. const httpRequest = http.createHttp();
  16766. try {
  16767. const response = await httpRequest.request(url, {
  16768. method: http.RequestMethod.GET,
  16769. connectTimeout: 8000,
  16770. readTimeout: 8000,
  16771. expectDataType: http.HttpDataType.STRING,
  16772. header: {
  16773. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  16774. 'Host': 'pan.baidu.com',
  16775. 'Referer': 'https://pan.baidu.com/disk/home',
  16776. 'Accept-Encoding': 'identity'
  16777. }
  16778. });
  16779. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  16780. return 0;
  16781. }
  16782. const text = response.result;
  16783. if (text.indexOf('#EXTM3U') < 0) {
  16784. return 0;
  16785. }
  16786. const lines = text.split('\n');
  16787. let totalSeconds = 0;
  16788. for (let i = 0; i < lines.length; i++) {
  16789. const line = lines[i].trim();
  16790. if (line.startsWith('#EXTINF:')) {
  16791. const colonIndex = line.indexOf(':');
  16792. if (colonIndex < 0) {
  16793. continue;
  16794. }
  16795. const content = line.substring(colonIndex + 1);
  16796. const commaIndex = content.indexOf(',');
  16797. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  16798. const seconds = Number(numberPart);
  16799. if (!Number.isNaN(seconds) && seconds > 0) {
  16800. totalSeconds += seconds;
  16801. }
  16802. }
  16803. }
  16804. if (totalSeconds > 0) {
  16805. return Math.floor(totalSeconds * 1000);
  16806. }
  16807. return 0;
  16808. } catch (fetchError) {
  16809. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  16810. return 0;
  16811. } finally {
  16812. httpRequest.destroy();
  16813. }
  16814. };
  16815. const fetchDurationFallback = async (): Promise<void> => {
  16816. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16817. if (durationMs > 0) {
  16818. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  16819. applyDuration(durationMs);
  16820. return;
  16821. }
  16822. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  16823. };
  16824. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  16825. Logger.info(
  16826. TAG,
  16827. `[seek] prepared duration snapshot, playerDuration=${preparedDuration}, metaDuration=${this.currentSong?.duration ?? ''}, ` +
  16828. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16829. );
  16830. if (preparedDuration > 0) {
  16831. applyDuration(preparedDuration);
  16832. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  16833. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16834. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  16835. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  16836. applyDuration(durationMs);
  16837. }
  16838. }
  16839. } else {
  16840. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  16841. if (metaDurationMs > 0) {
  16842. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  16843. applyDuration(metaDurationMs);
  16844. } else {
  16845. fetchDurationFallback();
  16846. }
  16847. }
  16848. setTimeout(() => {
  16849. this.avSessionController.initAvSession(false);
  16850. if (this.duration > 0) {
  16851. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  16852. }
  16853. this.setAvSessionListener();
  16854. this.updateSessionPlayState(true)
  16855. this.setCurrentPlayMode()
  16856. const cueTrackStartOffset = this.currentSong && isCueSplitItem(this.currentSong)
  16857. ? getCueTrackStartOffset(this.currentSong)
  16858. : 0;
  16859. if ((startOffset && startOffset > 0) || cueTrackStartOffset > 0) {//cue分轨播放
  16860. const cueSeekValue = cueTrackStartOffset > 0 && (!startOffset || startOffset <= 0) ? 0 : startOffset;
  16861. this.seekTo((cueSeekValue || 0) + "");
  16862. this.saveLastPlayList()
  16863. return
  16864. }
  16865. }, 500)
  16866. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16867. let timeoutPlay = 0
  16868. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16869. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  16870. timeoutPlay = 400
  16871. }
  16872. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  16873. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  16874. timeoutPlay = Math.max(timeoutPlay,
  16875. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  16876. }
  16877. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  16878. if (this.modeType === 0) { //文件夹
  16879. let parentPath = FileUtil.getParentPath(this.videoUrl)
  16880. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  16881. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  16882. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  16883. } else if (this.modeType === 1) { //媒体库
  16884. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  16885. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  16886. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  16887. } else if (this.modeType === 2) { //艺术家
  16888. if (this.currentSong?.artist) {
  16889. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  16890. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  16891. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  16892. }
  16893. } else if (this.modeType === 3) { //专辑
  16894. if (this.currentSong?.album) {
  16895. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  16896. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  16897. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  16898. }
  16899. }
  16900. const playerDuration = this.mIjkMediaPlayer.getDuration()
  16901. if (playerDuration > 0 && (!this.currentSong || !isCueSplitItem(this.currentSong))) {
  16902. this.duration = playerDuration
  16903. }
  16904. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  16905. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  16906. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  16907. let targetSeekPosition = memoryPosition;
  16908. if (this.isOpenJump) {
  16909. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  16910. }
  16911. this.pendingMemorySeekPosition = targetSeekPosition;
  16912. this.startInitialSeekGuardTimer('prepared-memory-seek');
  16913. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  16914. setTimeout(() => {
  16915. if (!this.waitInitialSeekBeforeStart) {
  16916. return;
  16917. }
  16918. this.restorePlaybackPosition();
  16919. }, timeoutPlay);
  16920. this.isFirstStartPlay = false
  16921. this.saveLastPlayList()
  16922. return
  16923. }
  16924. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  16925. if (this.mIjkMediaPlayer != null) {
  16926. let jumpTopTimeMs = this.jumpTopTime*1000;
  16927. if (jumpTopTimeMs <= this.duration) {
  16928. // 调用 seekTo 方法,跳到指定时间
  16929. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16930. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16931. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  16932. }
  16933. }, timeoutPlay)
  16934. } else {
  16935. // 提示用户无法跳过
  16936. ToastUtil.showToast('跳过时间超过视频时长');
  16937. }
  16938. }
  16939. } else {
  16940. this.jumpTopTime = 0
  16941. this.jumpEndTime = 0
  16942. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  16943. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  16944. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  16945. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  16946. //记忆播放(每一首都会记忆播放)
  16947. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16948. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16949. if (this.pendingMemorySeekPosition > 0 ||
  16950. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  16951. this.restorePlaybackPosition() //读取播放记忆功能
  16952. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  16953. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  16954. this.restorePlaybackPosition() //读取播放记忆功能
  16955. }
  16956. this.isFirstStartPlay = false
  16957. }, timeoutPlay)
  16958. } else {
  16959. this.isFirstStartPlay = false
  16960. }
  16961. }
  16962. this.saveLastPlayList()
  16963. } catch (error) {
  16964. let err: BusinessError = error as BusinessError;
  16965. console.error('onecold failed with err: ' + JSON.stringify(err));
  16966. if (this.waitInitialSeekBeforeStart) {
  16967. this.finishInitialSeekWait('prepared-exception', true);
  16968. }
  16969. }
  16970. }
  16971. );
  16972. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  16973. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  16974. (text: string) => {
  16975. }
  16976. );
  16977. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  16978. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  16979. () => {
  16980. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  16981. const completionAction = MusicPlaybackController.resolveCompletionAction(this.playType, this.curIndex,
  16982. this.songList.length)
  16983. if (completionAction.action === 'play_next') {
  16984. this.playbackController.playNext().catch(() => {
  16985. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16986. });
  16987. } else if (completionAction.action === 'replay_current') {
  16988. this.CONTROL_PlayStatus = PlayStatus.INIT
  16989. that.startPlayOrResumePlay();
  16990. } else if (completionAction.action === 'stop_current') {
  16991. if (completionAction.showBoundaryToast) {
  16992. Logger.info('heanup OnCompletionListener', '连续播放不循环模式:已到达最后一首,停止播放');
  16993. }
  16994. that.stopPlaybackAtTrackEnd(that.getActiveDuration(), completionAction.showBoundaryToast)
  16995. } else if (completionAction.action === 'random_next') {
  16996. this.randomPlay().catch(() => {
  16997. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  16998. });
  16999. }
  17000. }
  17001. );
  17002. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  17003. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  17004. (percent: number) => {
  17005. if (this.isDebug) {
  17006. const now = Date.now();
  17007. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  17008. this.lastBufferingLogTs = now;
  17009. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  17010. }
  17011. }
  17012. }
  17013. );
  17014. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  17015. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  17016. () => {
  17017. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  17018. that.logSeekTrace('seek-complete', undefined, undefined, true);
  17019. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  17020. setTimeout(() => {
  17021. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  17022. that.isSeekTo = false;
  17023. if (waitingInitialSeek) {
  17024. that.finishInitialSeekWait('seek-complete', true);
  17025. } else {
  17026. that.hideLoadIng();
  17027. }
  17028. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  17029. }
  17030. );
  17031. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  17032. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  17033. (what: number, extra: number) => {
  17034. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  17035. if (that.isSeekTraceActive()) {
  17036. Logger.info(
  17037. TAG,
  17038. `[seek] onInfo what=${what}, extra=${extra}, source=${that.lastSeekSource || 'unknown'}, ` +
  17039. `req=${that.lastSeekRequestMs}, url=${that.sanitizePlaybackUrl(that.videoUrl)}`
  17040. );
  17041. that.logSeekTrace(`info-${what}`, undefined, undefined, true);
  17042. }
  17043. if (!that.waitInitialSeekBeforeStart) {
  17044. that.hideLoadIng();
  17045. }
  17046. }
  17047. );
  17048. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  17049. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  17050. (what: number, extra: number) => {
  17051. this.finishInitialSeekWait('player-error', false);
  17052. this.stopProgressTask();
  17053. this.logSeekTrace(`error-${what}-${extra}`, undefined, undefined, true);
  17054. Logger.error(
  17055. TAG,
  17056. `[seek] onError what=${what}, extra=${extra}, url=${this.sanitizePlaybackUrl(this.videoUrl)}, ` +
  17057. `song=${JSON.stringify(this.currentSong)}`
  17058. );
  17059. // 检查是否为WebDAV播放错误
  17060. let isWebDavError = false;
  17061. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  17062. try {
  17063. const globalContext = GlobalContext.getContext();
  17064. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  17065. if (webDavAuthInfo) {
  17066. isWebDavError = true;
  17067. }
  17068. } catch (error) {
  17069. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  17070. }
  17071. }
  17072. if (isWebDavError) {
  17073. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  17074. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  17075. // this.currentWebDavAuthInfo = null;
  17076. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  17077. // 根据错误代码提供更具体的错误信息
  17078. let errorMessage = "WebDAV播放失败";
  17079. if (what === -1) { // 网络错误
  17080. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  17081. } else if (what === -1004) { // HTTP 404
  17082. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  17083. } else if (what === -1001) { // 超时
  17084. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  17085. } else if (what === -1003) { // 无法解析主机
  17086. errorMessage = "无法连接到WebDAV服务器";
  17087. }
  17088. ToastUtil.showToast(errorMessage);
  17089. } else {
  17090. if (StrUtil.isNotEmpty(this.videoUrl) &&
  17091. !this.videoUrl.startsWith('http') &&
  17092. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  17093. !FileUtil.accessSync(this.videoUrl)) {
  17094. console.info('heanup 播放.文件不存在');
  17095. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  17096. }
  17097. }
  17098. that.hideLoadIng();
  17099. }
  17100. );
  17101. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  17102. this.mIjkMediaPlayer.setMessageListener();
  17103. // 应用均衡器设置
  17104. try {
  17105. const equalizerManager = EqualizerManager.getInstance();
  17106. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  17107. Logger.info(TAG, 'heanup 均衡器设置已应用');
  17108. this.markEqualizerApplied();
  17109. } catch (eqError) {
  17110. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  17111. this.eqApplying = false;
  17112. }
  17113. this.mIjkMediaPlayer.prepareAsync();
  17114. this.mIjkMediaPlayer.start();
  17115. }
  17116. //保存最后播放的那首歌和已经对应的播放列表
  17117. saveLastPlayList() {
  17118. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  17119. // 新队列刚刚完成落盘时,首帧 prepared 会立刻再进一次这里,跳过这次重复写入即可。
  17120. if (this.skipNextPlaylistPersist) {
  17121. this.skipNextPlaylistPersist = false
  17122. } else {
  17123. PreferencesUtil.putSync('LastMusicList', this.songList)
  17124. }
  17125. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  17126. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  17127. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  17128. }
  17129. // 清空播放记录
  17130. clearVideoHistory() {
  17131. this.table.clearPlayHistory((success: boolean, error?: string) => {
  17132. if (success) {
  17133. this.historyList = [];
  17134. this.updateListData(this.historyList)
  17135. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  17136. ToastUtil.showToast('清空播放记录成功')
  17137. } else {
  17138. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  17139. }
  17140. });
  17141. }
  17142. public async setAvSessionListener() {
  17143. if (!this.avSessionController) {
  17144. return;
  17145. }
  17146. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  17147. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  17148. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  17149. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  17150. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  17151. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  17152. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  17153. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  17154. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  17155. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  17156. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  17157. }
  17158. setLoopMode() {
  17159. const nextMode = MusicPlaybackController.resolveNextLoopMode(this.playType)
  17160. this.playType = nextMode.playType
  17161. ToastUtil.showToast(nextMode.toastText)
  17162. PreferencesUtil.putSync('musicPlayType', this.playType)
  17163. this.setCurrentPlayMode()
  17164. }
  17165. private sessionSetLoopModeCallback = (mode: number) => {
  17166. if (this.mIjkMediaPlayer != null) {
  17167. if (MusicPlaybackController.shouldIgnoreInternalLoopModeEvent(this.pendingInternalLoopModeReport, mode)) {
  17168. this.pendingInternalLoopModeReport = -1
  17169. return
  17170. }
  17171. this.pendingInternalLoopModeReport = -1
  17172. ToastUtil.showToast('当前播放模式:' + mode)
  17173. Logger.info('onecold 当前播放模式= ' + mode)
  17174. const resolvedMode = MusicPlaybackController.resolveSessionLoopMode(mode)
  17175. this.playType = resolvedMode.playType
  17176. ToastUtil.showToast(resolvedMode.toastText)
  17177. PreferencesUtil.putSync('musicPlayType', this.playType)
  17178. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  17179. this.pendingInternalLoopModeReport = resolvedMode.reportedLoopMode
  17180. let playBackState: avSession.AVPlaybackState = {
  17181. loopMode: resolvedMode.reportedLoopMode,
  17182. };
  17183. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  17184. console.info(`set setLoopMode AVPlaybackState successfully`);
  17185. }).catch((err: BusinessError) => {
  17186. this.pendingInternalLoopModeReport = -1
  17187. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  17188. });
  17189. }
  17190. }
  17191. setCurrentPlayMode() {
  17192. if (!this.avSessionController) {
  17193. return;
  17194. }
  17195. const mLoopMode = MusicPlaybackController.resolveAvSessionLoopMode(this.playType)
  17196. this.pendingInternalLoopModeReport = mLoopMode
  17197. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  17198. let playBState: avSession.AVPlaybackState = {
  17199. loopMode: mLoopMode,
  17200. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  17201. };
  17202. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  17203. console.info(`set setLoopMode AVPlaybackState successfully`);
  17204. }).catch((err: BusinessError) => {
  17205. this.pendingInternalLoopModeReport = -1
  17206. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  17207. });
  17208. }
  17209. private applyRequestedPlayType(playType: number): void {
  17210. if (playType < 0 || playType > 4 || this.playType === playType) {
  17211. return
  17212. }
  17213. this.playType = playType
  17214. PreferencesUtil.putSync('musicPlayType', this.playType)
  17215. this.setCurrentPlayMode()
  17216. }
  17217. private sessionToggleFavoriteCallback = (assetId: string) => {
  17218. if (this.mIjkMediaPlayer != null && this.currentSong) {
  17219. console.info(`on toggleFavorite `);
  17220. // 应用收到收藏命令,进行收藏处理。
  17221. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  17222. this.doFav(this.currentSong)
  17223. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  17224. let playbackState: avSession.AVPlaybackState = {
  17225. isFavorite: !this.isFac,
  17226. };
  17227. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  17228. console.info(`SetAVPlaybackState successfully`);
  17229. }).catch((err: BusinessError) => {
  17230. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  17231. });
  17232. }
  17233. }
  17234. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  17235. device: avSession.OutputDeviceInfo) => {
  17236. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  17237. // 将 connectState 转换为可读的字符串
  17238. let stateName = 'UNKNOWN';
  17239. switch (connectState) {
  17240. case avSession.ConnectionState.STATE_CONNECTED:
  17241. stateName = 'CONNECTED(1)';
  17242. break;
  17243. case avSession.ConnectionState.STATE_DISCONNECTED:
  17244. stateName = 'DISCONNECTED(2)';
  17245. break;
  17246. case avSession.ConnectionState.STATE_CONNECTING:
  17247. stateName = 'CONNECTING(3)';
  17248. break;
  17249. default:
  17250. stateName = `OTHER(${connectState})`;
  17251. }
  17252. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  17253. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  17254. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  17255. await this.startCasting();
  17256. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  17257. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  17258. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  17259. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  17260. if (device) {
  17261. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  17262. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  17263. this.endCasting();
  17264. }
  17265. }
  17266. };
  17267. private async startCasting() {
  17268. try {
  17269. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  17270. // 获取原始的 AVCastController
  17271. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  17272. if (!avCastCtrl) {
  17273. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  17274. return;
  17275. }
  17276. this.castController = avCastCtrl;
  17277. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  17278. // 创建新的 CastController 封装器
  17279. this.castControllerWrapper = new CastController(avCastCtrl);
  17280. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  17281. // 设置回调函数
  17282. let callbacks: CastControllerCallbacks = {
  17283. onPlayNext: () => {
  17284. Logger.info('heanup CastController', '收到 playNext 回调');
  17285. void this.playbackController.playNext();
  17286. },
  17287. onPlayPrevious: () => {
  17288. Logger.info('heanup CastController', '收到 playPrevious 回调');
  17289. void this.playbackController.playPrevious();
  17290. },
  17291. onPositionChanged: (position: number) => {
  17292. this.positionChange(position);
  17293. },
  17294. onDurationChanged: (duration: number) => {
  17295. this.playDurationChange(duration);
  17296. }
  17297. };
  17298. this.castControllerWrapper.setCallbacks(callbacks);
  17299. Logger.info('heanup startCasting', '✅ 设置回调成功');
  17300. // 暂停本地播放
  17301. this.pause();
  17302. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  17303. // 初始化投播会话
  17304. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  17305. await this.castControllerWrapper.initAVCast(
  17306. this.songList,
  17307. this.curIndex,
  17308. this.mIjkMediaPlayer.getCurrentPosition(),
  17309. this.videoUrl,
  17310. this.getActiveDuration()
  17311. );
  17312. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  17313. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  17314. refToIsCasting?.set(true);
  17315. this.castSeek = true;
  17316. // 从 CastController 获取投播状态
  17317. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17318. if (this.isCastPlaying) {
  17319. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  17320. this.setIsPlaying(true);
  17321. this.updateSessionPlayState(true);
  17322. }
  17323. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  17324. } catch (error) {
  17325. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  17326. }
  17327. }
  17328. async changeCasting() {
  17329. Logger.info('heanup changeCasting', '切换投播');
  17330. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  17331. this.initQueueItem();
  17332. await this.prepare();
  17333. this.setPlaybackStateChangeListener();
  17334. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  17335. this.castSeek = true;
  17336. }
  17337. public endCasting() {
  17338. Logger.info('heanup endCasting', 'endCasting被调用');
  17339. this.avSessionController.getAvSession()?.stopCasting();
  17340. this.stopCast();
  17341. // 关闭文件描述符
  17342. if (this.castFile) {
  17343. try {
  17344. fs.closeSync(this.castFile);
  17345. this.castFile = undefined;
  17346. Logger.info('heanup endCasting', '关闭投播文件描述符');
  17347. } catch (error) {
  17348. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  17349. }
  17350. }
  17351. this.isCastPlaying = false;
  17352. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  17353. refToIsCasting?.set(false);
  17354. this.pause();
  17355. this.setIsPlaying(false);
  17356. // if (this.curIndex === this.curSource.index) {
  17357. // this.play
  17358. // this.seek(this.currentTime * 1000);
  17359. // this.setIsPlaying(true);
  17360. // } else {
  17361. // this.pauseVideo();
  17362. // this.setIsPlaying(false);
  17363. // }
  17364. }
  17365. public setIsPlaying(isPlayer: boolean) {
  17366. this.isPlaying = isPlayer;
  17367. // 发送播放状态变化事件给歌单详情页面
  17368. try {
  17369. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  17370. const currentFilePath = this.currentSong?.filePath || ''
  17371. const eventData: emitter.EventData = {
  17372. data: {
  17373. isPlaying: this.isPlaying,
  17374. curIndex: this.curIndex,
  17375. currentFilePath: currentFilePath
  17376. }
  17377. };
  17378. emitter.emit(eventPlaybackStatus, eventData)
  17379. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  17380. } catch (error) {
  17381. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  17382. }
  17383. try {
  17384. this.playbackStateBridge.updatePlaybackState(
  17385. this.CONTROL_PlayStatus === PlayStatus.PLAY,
  17386. this.getActivePlaybackPositionMs(),
  17387. this.getActiveDuration()
  17388. )
  17389. } catch (error) {
  17390. Logger.warn(TAG, `回写 PlaybackStateBridge 失败: ${error}`)
  17391. }
  17392. this.notifyPlaybackCardStateChanged()
  17393. }
  17394. private setPlaybackStateChangeListener(): void {
  17395. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  17396. // 我们需要通过其他方式来判断播放状态
  17397. // 1. 监听位置变化
  17398. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  17399. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  17400. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  17401. this.positionChange(playbackState.position.elapsedTime);
  17402. }
  17403. });
  17404. // 2. 监听时长变化
  17405. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  17406. const duration = playbackState?.extras?.duration;
  17407. if (typeof duration === 'number') {
  17408. this.playDurationChange(duration);
  17409. }
  17410. });
  17411. // 3. 监听所有状态变化(用于调试和状态判断)
  17412. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  17413. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  17414. // 检查是否有 state 字段(某些设备可能返回)
  17415. if (playbackState.state !== undefined) {
  17416. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  17417. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  17418. this.isCastPlaying = true;
  17419. }
  17420. }
  17421. });
  17422. // 4. 监听播放完成事件
  17423. this.castController?.on('endOfStream', this.playNextCallback);
  17424. this.castController?.on('playNext', this.playNextCallback);
  17425. this.castController?.on('playPrevious', this.playPreviousCallback);
  17426. // 5. 监听错误事件
  17427. this.castController?.on('error', (error: BusinessError) => {
  17428. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  17429. this.isCastPlaying = false;
  17430. });
  17431. }
  17432. private updateSessionPlayState(isPlay: boolean): void {
  17433. // if(!this.isBgPlayOpen)
  17434. // return
  17435. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  17436. : this.mIjkMediaPlayer.getCurrentPosition();
  17437. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  17438. this.setAVSessionPlayState({
  17439. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  17440. position: {
  17441. elapsedTime: elapsedTime,
  17442. updateTime: new Date().getTime()
  17443. }
  17444. });
  17445. }
  17446. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  17447. this.avSessionController.setAvSessionPlayState(playbackState)
  17448. }
  17449. private positionChange(position: number) {
  17450. this.currentTime2 = position / 1000;
  17451. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  17452. if (this.castControllerWrapper && this.isCastPlaying) {
  17453. this.updateCastProgress(position);
  17454. if (this.isSeekTo) {
  17455. this.isSeekTo = false;
  17456. }
  17457. }
  17458. }
  17459. private playDurationChange(duration: number) {
  17460. this.duration = duration;
  17461. this.durationTime = Math.floor(this.duration / 1000);
  17462. this.durationStringTime = secondToTime((this.durationTime));
  17463. if (this.castControllerWrapper && this.isCastPlaying) {
  17464. this.totalTime = this.stringForTime(this.duration);
  17465. }
  17466. }
  17467. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  17468. private reloadCasting = async () => {
  17469. Logger.info('heanup reloadCasting', '重新加载投播');
  17470. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  17471. this.initQueueItem();
  17472. await this.prepare();
  17473. };
  17474. public playNextCallback = (): void => {
  17475. this.playbackController.playNext().catch(() => {
  17476. Logger.error('heanup playNextCallback', `播放下一首失败`);
  17477. });
  17478. };
  17479. public playPreviousCallback = (): void => {
  17480. this.playbackController.playPrevious().catch(() => {
  17481. Logger.error('heanup playNextCallback', `播放上一首失败`);
  17482. });
  17483. };
  17484. async prepare() {
  17485. try {
  17486. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  17487. await this.castController?.prepare(this.castItem);
  17488. Logger.info('heanup prepare', '投播prepare成功');
  17489. await this.castController?.start(this.castItem);
  17490. Logger.info('heanup prepare', '投播start成功');
  17491. // 投播启动成功,设置为投播状态
  17492. this.isCastPlaying = true;
  17493. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  17494. } catch (error) {
  17495. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  17496. this.isCastPlaying = false;
  17497. }
  17498. }
  17499. public initQueueItem() {
  17500. let item = this.songList[this.curIndex];
  17501. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  17502. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  17503. let isStreaming = this.isUrl(this.videoUrl);
  17504. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  17505. // 关闭之前的文件描述符
  17506. if (this.castFile) {
  17507. try {
  17508. fs.closeSync(this.castFile);
  17509. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  17510. } catch (error) {
  17511. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  17512. }
  17513. }
  17514. let description: avSession.AVMediaDescription = {
  17515. assetId: 'AUDIO-' + item.filePath,
  17516. title: item.name,
  17517. artist: item.artist || '',
  17518. // 该字段大写,音频'AUDIO',视频'VIDEO'
  17519. mediaType: 'AUDIO',
  17520. mediaSize: item.videoSize,
  17521. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  17522. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  17523. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  17524. duration: this.duration,
  17525. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  17526. appName: this.appName,
  17527. lyricContent: item.lyricContent,
  17528. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  17529. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  17530. };
  17531. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  17532. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  17533. if (isStreaming) {
  17534. // 流媒体地址使用 mediaUri
  17535. description.mediaUri = this.videoUrl;
  17536. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  17537. } else {
  17538. // 本地文件使用 fdSrc
  17539. const localPath = this.videoUrl || item.filePath;
  17540. let uri = fileUri.getUriFromPath(localPath);
  17541. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  17542. let fdSrc: media.AVFileDescriptor = {
  17543. fd: this.castFile.fd
  17544. };
  17545. description.fdSrc = fdSrc;
  17546. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  17547. }
  17548. this.castItem = {
  17549. itemId: this.curIndex,
  17550. description: description
  17551. };
  17552. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  17553. title: description.title,
  17554. mediaType: description.mediaType,
  17555. hasMediaUri: !!description.mediaUri,
  17556. hasFdSrc: !!description.fdSrc,
  17557. duration: description.duration
  17558. })}`);
  17559. }
  17560. // 判断是否是 URL 或流媒体地址
  17561. private isUrl(str: string): boolean {
  17562. if (!str) {
  17563. return false;
  17564. }
  17565. // 检查常见的流媒体协议
  17566. if (str.startsWith('http://') || str.startsWith('https://') ||
  17567. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  17568. str.startsWith('rtp://') || str.startsWith('mms://')) {
  17569. return true;
  17570. }
  17571. // 扩展的URL正则表达式,支持多种协议
  17572. const urlPattern = new RegExp(
  17573. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  17574. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  17575. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  17576. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  17577. 'localhost)' + // 或localhost
  17578. '(\\:\\d+)?' + // 端口号(可选)
  17579. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  17580. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  17581. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  17582. 'i' // 不区分大小写
  17583. );
  17584. return urlPattern.test(str);
  17585. }
  17586. async stopCast() {
  17587. try {
  17588. // 使用 CastController 释放资源
  17589. if (this.castControllerWrapper) {
  17590. await this.castControllerWrapper.releaseAVCast();
  17591. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  17592. }
  17593. // 清空引用
  17594. this.castControllerWrapper = undefined;
  17595. this.castController = undefined;
  17596. this.castItem = undefined;
  17597. this.castFile = undefined;
  17598. } catch (error) {
  17599. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  17600. }
  17601. }
  17602. private sessionPlayCallback = (): void => {
  17603. this.playbackController.playOrPause()
  17604. };
  17605. private sessionPauseCallback = (): void => {
  17606. this.pause()
  17607. };
  17608. private async playOrPause() {
  17609. if (this.isHostSnapshotDisplayOnly) {
  17610. await BackgroundAudioPlaybackHost.getInstance().getRuntime().playOrPause()
  17611. return
  17612. }
  17613. if (!this.debounce()) {
  17614. return;
  17615. }
  17616. const toggleAction = MusicPlaybackController.resolveTogglePlaybackAction(
  17617. this.CONTROL_PlayStatus === PlayStatus.PLAY,
  17618. !!this.castControllerWrapper && this.isCastPlaying
  17619. )
  17620. if (toggleAction === 'pause') {
  17621. await this.pause();
  17622. } else {
  17623. // 如果是投播模式,使用 CastController 的 play 方法
  17624. if (toggleAction === 'resume_cast' && this.castControllerWrapper) {
  17625. try {
  17626. Logger.info('heanup playOrPause', '投播模式播放');
  17627. await this.castControllerWrapper.setPlaying();
  17628. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  17629. this.setIsPlaying(true);
  17630. this.updateSessionPlayState(true);
  17631. Logger.info('heanup playOrPause', '投播播放成功');
  17632. this.playChange();
  17633. } catch (error) {
  17634. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  17635. }
  17636. } else {
  17637. console.info('onecold startPlayOrResumePlay 11064')
  17638. this.startPlayOrResumePlay();
  17639. this.playChange()
  17640. }
  17641. }
  17642. }
  17643. private sessionPlayNextCallback = (): void => {
  17644. this.playbackController.playNext().catch(() => {
  17645. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  17646. });
  17647. };
  17648. private sessionPlayPreviousCallback = (): void => {
  17649. this.playbackController.playPrevious().catch(() => {
  17650. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  17651. });
  17652. };
  17653. private sessionStopCallback = (): void => {
  17654. this.stop()
  17655. };
  17656. private sessionFastForwardCallback = async (time?: number) => {
  17657. if (!time) {
  17658. return;
  17659. }
  17660. let curPosition: number;
  17661. if (this.castController && this.isCastPlaying) {
  17662. // 投播模式,使用UI显示的时间
  17663. curPosition = this.currentTime2 * 1000;
  17664. } else if (this.mIjkMediaPlayer != null) {
  17665. // 本地播放器模式
  17666. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17667. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17668. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17669. }
  17670. } else {
  17671. return;
  17672. }
  17673. let seeTime = curPosition + time * 1000;
  17674. // 限制 seekValue 在合法范围内
  17675. if (seeTime < 0) {
  17676. seeTime = 0;
  17677. } else if (seeTime > this.duration) {
  17678. seeTime = this.duration;
  17679. }
  17680. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  17681. this.setSeekToActionProgress(seeTime);
  17682. await this.seekTo(seeTime + "", 'session-fast-forward');
  17683. };
  17684. private getActiveDuration(): number {
  17685. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17686. const cueDuration = getCueTrackDuration(this.currentSong);
  17687. if (cueDuration > 0) {
  17688. return cueDuration;
  17689. }
  17690. }
  17691. let duration = this.mIjkMediaPlayer.getDuration();
  17692. if (this.castControllerWrapper && this.isCastPlaying) {
  17693. return this.duration > 0 ? this.duration : duration;
  17694. }
  17695. if (duration <= 0 && this.duration > 0) {
  17696. duration = this.duration;
  17697. }
  17698. return duration;
  17699. }
  17700. @Builder
  17701. InlineSpectrumView() {
  17702. SpectrumView({
  17703. isVisible: this.currentSwiperIndex === 0,
  17704. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  17705. })
  17706. .width( '83%')
  17707. .height(this.isCoverOpacity() ? 80 : 100)
  17708. .margin({bottom: 3 })
  17709. .clip(true)
  17710. .zIndex(-2)
  17711. .onClick(()=>{
  17712. this.cycleSpectrumMode();
  17713. })
  17714. }
  17715. private cycleSpectrumMode(): void {
  17716. const modeNames: string[] = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  17717. if (modeNames.length <= 0) {
  17718. return;
  17719. }
  17720. const nextIndex: number = (this.spectrumModeIndex + 1) % modeNames.length;
  17721. this.spectrumModeIndex = nextIndex;
  17722. PreferencesUtil.putSync('spectrumModeIndex', nextIndex);
  17723. AppStorage.setOrCreate<number>('spectrumMode', nextIndex);
  17724. Logger.info('heanup-LocalMusic', `频谱特效已顺序切换为: ${modeNames[nextIndex]}`);
  17725. }
  17726. private getSongDurationMs(song?: VideoItem): number {
  17727. if (!song || !song.duration) {
  17728. return 0;
  17729. }
  17730. const raw = song.duration.trim();
  17731. if (!raw) {
  17732. return 0;
  17733. }
  17734. const parts = raw.split(':').map((part) => Number(part));
  17735. if (parts.some((part) => Number.isNaN(part))) {
  17736. return 0;
  17737. }
  17738. let seconds = 0;
  17739. if (parts.length === 3) {
  17740. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  17741. } else if (parts.length === 2) {
  17742. seconds = parts[0] * 60 + parts[1];
  17743. } else if (parts.length === 1) {
  17744. seconds = parts[0];
  17745. }
  17746. return seconds > 0 ? seconds * 1000 : 0;
  17747. }
  17748. private updateCastProgress(position: number): void {
  17749. const duration = this.getActiveDuration();
  17750. if (duration <= 0) {
  17751. return;
  17752. }
  17753. this.slideEnable = true;
  17754. let pos = (position / duration) * 100;
  17755. if (pos > this.PROGRESS_MAX_VALUE) {
  17756. this.progressValue = this.PROGRESS_MAX_VALUE;
  17757. } else if (pos < 0) {
  17758. this.progressValue = 0;
  17759. } else {
  17760. this.progressValue = pos;
  17761. }
  17762. this.totalTime = this.stringForTime(duration);
  17763. if (position > duration) {
  17764. position = duration;
  17765. }
  17766. this.isCurrentTime = true;
  17767. this.currentTime = this.stringForTime(position);
  17768. this.isCurrentTime = false;
  17769. const lyricPosition = position + this.timeOffset * 1000;
  17770. this.updateLyricPosition(lyricPosition);
  17771. }
  17772. /**
  17773. * Gesture method onActionUpdate.
  17774. *
  17775. * @param event Gesture event.手势拖动设置快进和后退
  17776. */
  17777. private setSeekToActionProgress(position: number) {
  17778. // 投播模式使用this.duration,本地模式使用播放器获取
  17779. let duration = this.getActiveDuration();
  17780. let pos = 0;
  17781. if (duration > 0) {
  17782. this.slideEnable = true;
  17783. let curPercent = position / duration;
  17784. pos = curPercent * 100;
  17785. if (pos > this.PROGRESS_MAX_VALUE) {
  17786. this.progressValue = this.PROGRESS_MAX_VALUE
  17787. } else {
  17788. this.progressValue = pos;
  17789. }
  17790. }
  17791. // LogUtils.getInstance()
  17792. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  17793. this.totalTime = this.stringForTime(duration);
  17794. if (position > duration) {
  17795. position = duration;
  17796. }
  17797. this.isCurrentTime = true;
  17798. this.currentTime = this.stringForTime(position);
  17799. this.isCurrentTime = false
  17800. }
  17801. private sessionRewindCallback = async (time?: number) => {
  17802. if (!time) {
  17803. return;
  17804. }
  17805. let curPosition: number;
  17806. if (this.castController && this.isCastPlaying) {
  17807. // 投播模式,使用UI显示的时间
  17808. curPosition = this.currentTime2 * 1000;
  17809. } else if (this.mIjkMediaPlayer != null) {
  17810. // 本地播放器模式
  17811. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17812. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17813. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17814. }
  17815. } else {
  17816. return;
  17817. }
  17818. let seeTime = curPosition - time * 1000;
  17819. // 限制 seekValue 在合法范围内
  17820. if (seeTime < 0) {
  17821. seeTime = 0;
  17822. } else if (seeTime > this.duration) {
  17823. seeTime = this.duration;
  17824. }
  17825. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  17826. this.setSeekToActionProgress(seeTime);
  17827. await this.seekTo(seeTime + "", 'session-rewind');
  17828. };
  17829. private sessionSeekCallback = async (seekTime: number) => {
  17830. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  17831. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  17832. await this.seekTo(seekTime + "", 'session-seek');
  17833. };
  17834. private async getFileSize(filePath: string): Promise<number> {
  17835. try {
  17836. const stat = await fs.stat(filePath);
  17837. return stat.size;
  17838. } catch (err) {
  17839. console.error('Failed to get file size: ' + err.message);
  17840. return 0;
  17841. }
  17842. }
  17843. private async pause(clearInterruptResumeFlag: boolean = true) {
  17844. if (this.isHostSnapshotDisplayOnly) {
  17845. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17846. await BackgroundAudioPlaybackHost.getInstance().getRuntime().playOrPause()
  17847. }
  17848. return
  17849. }
  17850. if (clearInterruptResumeFlag) {
  17851. this.audioInterruptResumePending = false;
  17852. }
  17853. // 如果是投播模式,使用 CastController 的 pause 方法
  17854. if (this.castControllerWrapper && this.isCastPlaying) {
  17855. try {
  17856. Logger.info('heanup pause', '投播模式暂停');
  17857. await this.castControllerWrapper.setPause();
  17858. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17859. this.setIsPlaying(false);
  17860. this.updateSessionPlayState(false);
  17861. Logger.info('heanup pause', '投播暂停成功');
  17862. } catch (error) {
  17863. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  17864. }
  17865. } else if (this.mIjkMediaPlayer.isPlaying() || this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17866. // 本地播放器模式
  17867. this.savePlaybackPosition();
  17868. if (this.mIjkMediaPlayer.isPlaying()) {
  17869. this.mIjkMediaPlayer.pause();
  17870. this.setProgress();
  17871. }
  17872. this.mDestroyPage = true;
  17873. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17874. this.updateSessionPlayState(false)
  17875. this.playChange()
  17876. if (this.pipController) {
  17877. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  17878. PiPWindow.PiPControlStatus.PAUSE);
  17879. }
  17880. }
  17881. }
  17882. private stop() {
  17883. this.audioInterruptResumePending = false;
  17884. this.savePlaybackPosition();
  17885. this.clearInitialSeekGuardTimer();
  17886. this.waitInitialSeekBeforeStart = false;
  17887. this.pendingMemorySeekPosition = 0;
  17888. this.isPlayerLoading = false;
  17889. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17890. this.mIjkMediaPlayer.stop();
  17891. this.mIjkMediaPlayer.release();
  17892. console.info('kkMusic stop ..this.CONTROL_PlayStatus '+this.CONTROL_PlayStatus )
  17893. this.stopProgressTask();
  17894. this.updateSessionPlayState(false)
  17895. this.playChange()
  17896. this.watchStatus();
  17897. }
  17898. //保持记忆播放功能
  17899. private savePlaybackPosition() {
  17900. if (this.mIjkMediaPlayer != null) {
  17901. let position = this.mIjkMediaPlayer.getCurrentPosition();
  17902. // ToastUtil.showToast('保存记忆播放 = ' + position)
  17903. let duration = this.mIjkMediaPlayer.getDuration();
  17904. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17905. position = Math.max(0, position - getCueTrackStartOffset(this.currentSong));
  17906. const cueDuration = getCueTrackDuration(this.currentSong);
  17907. if (cueDuration > 0) {
  17908. duration = cueDuration;
  17909. }
  17910. }
  17911. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  17912. // 如果播放位置接近视频末尾,则保存 position 为 0
  17913. const playbackPosition = (duration - position < threshold) ? 0 : position;
  17914. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  17915. PreferencesUtil.putSync(memoryKey, playbackPosition);
  17916. }
  17917. }
  17918. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  17919. if (song && isRemoteCloudType(song.type)) {
  17920. const accountId = song.webdav_account_id || 'unknown';
  17921. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  17922. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  17923. }
  17924. if (song && isCueSplitItem(song)) {
  17925. return `memory_play_local_cue:${song.filePath}`;
  17926. }
  17927. return playbackUrl || '';
  17928. }
  17929. private getPlaybackMemoryKey(): string {
  17930. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  17931. }
  17932. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  17933. if (token !== this.remoteRestoreSeekToken) {
  17934. return;
  17935. }
  17936. if (!this.mIjkMediaPlayer || position <= 0) {
  17937. if (this.waitInitialSeekBeforeStart) {
  17938. this.finishInitialSeekWait('invalid-memory-position', true);
  17939. }
  17940. return;
  17941. }
  17942. const duration = this.getActiveDuration();
  17943. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  17944. let safePosition = position;
  17945. if (duration > 0) {
  17946. safePosition = Math.max(0, Math.min(position, duration - 500));
  17947. } else {
  17948. safePosition = Math.max(0, position);
  17949. }
  17950. if (safePosition <= 0) {
  17951. if (this.waitInitialSeekBeforeStart) {
  17952. this.finishInitialSeekWait('memory-position-too-small', true);
  17953. }
  17954. return;
  17955. }
  17956. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  17957. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  17958. }
  17959. this.seekTo(safePosition + "", retryCount === 0 ? 'remote-memory-restore' : 'remote-memory-retry');
  17960. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  17961. return;
  17962. }
  17963. setTimeout(() => {
  17964. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  17965. return;
  17966. }
  17967. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  17968. if (Math.abs(latestPos - safePosition) <= 1500) {
  17969. return;
  17970. }
  17971. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  17972. }, this.remoteMemorySeekRetryIntervalMs);
  17973. }
  17974. //获取记忆播放功能
  17975. private restorePlaybackPosition() {
  17976. const position: number = this.pendingMemorySeekPosition > 0 ?
  17977. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  17978. if (!this.mIjkMediaPlayer || position <= 0) {
  17979. if (this.waitInitialSeekBeforeStart) {
  17980. this.finishInitialSeekWait('no-memory-position', true);
  17981. }
  17982. return;
  17983. }
  17984. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17985. if (isRemoteSong && this.videoUrl.includes('://')) {
  17986. const token = this.remoteRestoreSeekToken;
  17987. this.restoreRemotePlaybackPositionSafely(position, token);
  17988. return;
  17989. }
  17990. const duration = this.getActiveDuration();
  17991. let safePosition = position;
  17992. if (duration > 0) {
  17993. safePosition = Math.max(0, Math.min(position, duration - 500));
  17994. } else {
  17995. safePosition = Math.max(0, position);
  17996. }
  17997. if (safePosition <= 0) {
  17998. if (this.waitInitialSeekBeforeStart) {
  17999. this.finishInitialSeekWait('memory-position-too-small', true);
  18000. }
  18001. return;
  18002. }
  18003. this.seekTo(safePosition + "", isRemoteSong ? 'remote-memory-restore' : 'memory-restore');
  18004. }
  18005. private async seekTo(value: string, source: string = 'internal') {
  18006. if (this.isHostSnapshotDisplayOnly) {
  18007. await BackgroundAudioPlaybackHost.getInstance().getRuntime().seekTo(value, source)
  18008. return
  18009. }
  18010. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  18011. // ToastUtil.showToast('wma格式不支持拖动快进。')
  18012. // return
  18013. // }
  18014. // 如果是投播模式,使用 CastController 的 seek 方法
  18015. if (this.castControllerWrapper && this.isCastPlaying) {
  18016. try {
  18017. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  18018. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  18019. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  18020. const duration = this.getActiveDuration();
  18021. const resolvedSeek = MusicPlaybackController.resolveSeekPosition({
  18022. requestedValue: value,
  18023. activeDuration: duration,
  18024. cueTrackStartOffset,
  18025. cueTrackEndOffset
  18026. })
  18027. if (!resolvedSeek.canSeek) {
  18028. return
  18029. }
  18030. const seekPos = resolvedSeek.seekPos
  18031. this.beginSeekTrace(source, seekPos);
  18032. this.isSeekTo = true;
  18033. Logger.info(
  18034. TAG,
  18035. `[seek] cast dispatch, source=${source}, target=${seekPos}, duration=${duration}, ` +
  18036. `uiDuration=${this.duration}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  18037. );
  18038. // 检查是否接近末尾
  18039. if (this.duration > 0 && seekPos >= this.duration - 500) {
  18040. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  18041. }
  18042. await this.castControllerWrapper.seek(seekPos);
  18043. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  18044. } catch (error) {
  18045. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  18046. }
  18047. } else {
  18048. // 本地播放器模式
  18049. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  18050. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  18051. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  18052. const duration = this.getActiveDuration();
  18053. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  18054. const resolvedSeek = MusicPlaybackController.resolveSeekPosition({
  18055. requestedValue: value,
  18056. activeDuration: duration,
  18057. cueTrackStartOffset,
  18058. cueTrackEndOffset,
  18059. isRemoteSong
  18060. })
  18061. if (!resolvedSeek.canSeek) {
  18062. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${resolvedSeek.seekPos}ms`);
  18063. return;
  18064. }
  18065. const seekPos = resolvedSeek.seekPos
  18066. if (isRemoteSong && duration <= 0) {
  18067. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  18068. }
  18069. if (source !== 'internal') {
  18070. this.beginSeekTrace(source, seekPos);
  18071. }
  18072. if (this.handleBlockedSeek(seekPos, source)) {
  18073. return;
  18074. }
  18075. this.isSeekTo = true
  18076. try {
  18077. if (isRemoteSong || source !== 'internal' || this.isSeekTraceActive()) {
  18078. Logger.info(
  18079. TAG,
  18080. `[seek] player dispatch, source=${source}, target=${seekPos}, activeDuration=${duration}, ` +
  18081. `playerDuration=${this.mIjkMediaPlayer.getDuration()}, current=${this.mIjkMediaPlayer.getCurrentPosition()}, ` +
  18082. `isPlaying=${this.mIjkMediaPlayer.isPlaying()}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  18083. );
  18084. }
  18085. this.mIjkMediaPlayer.seekTo(seekPos + "");
  18086. this.logSeekTrace('seek-dispatched', this.mIjkMediaPlayer.getCurrentPosition(), this.mIjkMediaPlayer.getDuration(), true);
  18087. this.setProgress()
  18088. } catch (error) {
  18089. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  18090. this.logSeekTrace('seek-dispatch-error', undefined, undefined, true);
  18091. } finally {
  18092. this.isSeekTo = false
  18093. }
  18094. }
  18095. }
  18096. // 添加到下一首播放
  18097. private addToNextPlay(song: VideoItem) {
  18098. if (!this.debounce()) {
  18099. return;
  18100. }
  18101. if (this.currentSong) {
  18102. if (this.currentSong === song) {
  18103. ToastUtil.showToast('当前已经在播放这首歌了!')
  18104. return
  18105. }
  18106. }
  18107. // 如果未开始播放或队列为空
  18108. if (this.curIndex === -1 || this.songList.length === 0) {
  18109. this.songList = [song];
  18110. this.curIndex = 0;
  18111. this.doPlay(song)
  18112. return;
  18113. }
  18114. // 插入到当前索引+1的位置
  18115. const insertPos = this.curIndex + 1;
  18116. this.songList.splice(insertPos, 0, song);
  18117. this.songList = [...this.songList]; // 触发状态更新
  18118. this.sonDataSource.pushArrayData(this.songList)
  18119. ToastUtil.showToast('已添加至下一首播放')
  18120. }
  18121. //后退10s,可再设置设置默认几秒
  18122. async backForward() {
  18123. // 如果是投播模式,从currentTime2获取当前位置
  18124. let pos: number;
  18125. if (this.castController && this.isCastPlaying) {
  18126. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  18127. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  18128. } else if (this.mIjkMediaPlayer) {
  18129. pos = this.mIjkMediaPlayer.getCurrentPosition();
  18130. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  18131. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  18132. }
  18133. } else {
  18134. return;
  18135. }
  18136. let value = pos - Number(this.fastForwardSeconds) * 1000;
  18137. if (value < 0) {
  18138. value = 0;
  18139. }
  18140. await this.seekTo(value + "", 'rewind-button');
  18141. }
  18142. //快进10s,可再设置设置默认几秒
  18143. async fastForward() {
  18144. // 如果是投播模式,从currentTime2获取当前位置
  18145. let pos: number;
  18146. if (this.castController && this.isCastPlaying) {
  18147. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  18148. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  18149. } else if (this.mIjkMediaPlayer) {
  18150. pos = this.mIjkMediaPlayer.getCurrentPosition();
  18151. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  18152. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  18153. }
  18154. } else {
  18155. return;
  18156. }
  18157. let value = pos + Number(this.fastForwardSeconds) * 1000;
  18158. // 限制不超过总时长
  18159. if (this.duration > 0 && value > this.duration) {
  18160. value = this.duration;
  18161. }
  18162. await this.seekTo(value + "", 'fast-forward-button');
  18163. }
  18164. //下一个
  18165. private async playNext() {
  18166. if (this.isHostSnapshotDisplayOnly) {
  18167. await BackgroundAudioPlaybackHost.getInstance().getRuntime().playNext()
  18168. return
  18169. }
  18170. this.lyricController.setLyric(null)
  18171. this.lyricControllerXF.setLyric(null)
  18172. this.lyricControllerSingle.setLyric(null)
  18173. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  18174. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  18175. if (!this.debounce()) {
  18176. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  18177. return;
  18178. }
  18179. Logger.info('heanup playNext', `playType=${this.playType}`);
  18180. const nextPlaybackAction = MusicPlaybackController.resolveNextPlaybackAction(
  18181. this.playType,
  18182. this.curIndex,
  18183. this.songList.length
  18184. )
  18185. if (nextPlaybackAction === 'random_play') {
  18186. Logger.info('heanup playNext', '随机播放模式');
  18187. await this.randomPlay()
  18188. return;
  18189. }
  18190. if (ArrayUtil.isNotEmpty(this.songList)) {
  18191. if (this.curIndex >= this.songList.length - 1) {
  18192. if (nextPlaybackAction === 'stop_at_end') {
  18193. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  18194. this.stopPlaybackAtTrackEnd(this.getActiveDuration(), true)
  18195. return;
  18196. }
  18197. await this.tryLoadNextPageForPlayback();
  18198. }
  18199. const nextQueueIndex = MusicPlaybackController.resolveNextQueueIndex(this.curIndex, this.songList.length)
  18200. this.curIndex = nextQueueIndex.nextIndex
  18201. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  18202. this.applySelectedQueueSong(this.curIndex)
  18203. const nextSong = this.currentSong
  18204. if (!nextSong) {
  18205. return;
  18206. }
  18207. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${nextSong.name}, type: ${nextSong.type}`);
  18208. await this.dispatchPreparedQueueSwitch(
  18209. 'playNext',
  18210. '播放下一首',
  18211. async (durationMs: number): Promise<void> => {
  18212. await this.castControllerWrapper!.playNext(this.songList, this.curIndex, this.videoUrl, durationMs);
  18213. }
  18214. )
  18215. }
  18216. }
  18217. changeImageAnimation() {
  18218. if(this.openSkipSongAnimate){
  18219. // 第一步:淡出动画
  18220. this.getUIContext()?.animateTo({
  18221. duration: 500,
  18222. curve: Curve.EaseOut,
  18223. }, () => {
  18224. this.opacityValueImage = 0.1;
  18225. if(this.isCoverRectangle){
  18226. this.scaleValueImage = 0.88
  18227. }
  18228. });
  18229. // 第二步:切换图片后淡入
  18230. setTimeout(() => {
  18231. this.cover = this.songList[this.curIndex].pixelMapPath
  18232. this.getUIContext()?.animateTo({
  18233. duration: 500,
  18234. curve: Curve.EaseIn,
  18235. }, () => {
  18236. this.opacityValueImage = 1;
  18237. this.scaleValueImage = 1 // 图标恢复到原始大小
  18238. this.startPlayOrResumePlay()
  18239. });
  18240. }, 500);
  18241. }else{
  18242. this.cover = this.songList[this.curIndex].pixelMapPath
  18243. this.startPlayOrResumePlay()
  18244. }
  18245. }
  18246. // 内部方法:提前缓存下一首
  18247. private async preloadNextSongInternal(): Promise<void> {
  18248. // 随机模式下传递已播放索引集合
  18249. if (this.playType === 3) {
  18250. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  18251. this.songList,
  18252. this.curIndex,
  18253. this.playType,
  18254. this.playedIndices
  18255. );
  18256. } else {
  18257. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  18258. this.songList,
  18259. this.curIndex,
  18260. this.playType
  18261. );
  18262. }
  18263. }
  18264. // 存储已播放的歌曲索引
  18265. private playedIndices: Set<number> = new Set();
  18266. // 存储已播放的本地歌曲路径(随机播放去重用)
  18267. private playedLocalFilePaths: Set<string> = new Set();
  18268. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  18269. private randomPlayHistory: VideoItem[] = [];
  18270. //随机播放
  18271. private async randomPlay() {
  18272. // if (!this.debounce()) {
  18273. // return;
  18274. // }
  18275. // 网盘模式: 渐进式扩展播放库的随机播放
  18276. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  18277. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  18278. if (isCloudSong) {
  18279. const findRemoteQueue = getFindVideoItems();
  18280. const isSameFindQueue = this.songList.length === findRemoteQueue.length &&
  18281. this.songList.every((item: VideoItem, index: number) => item.filePath === findRemoteQueue[index]?.filePath);
  18282. const useFindRemoteQueue = this.playQueueScope === 'playlist' &&
  18283. findRemoteQueue.length > 0 &&
  18284. isSameFindQueue &&
  18285. findRemoteQueue.every((item: VideoItem) => isRemoteCloudType(item.type)) &&
  18286. findRemoteQueue.some((item: VideoItem) => item.filePath === this.currentSong?.filePath);
  18287. // 阈值常量
  18288. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  18289. const LOAD_MORE_PAGES = 3; // 每次加载页数
  18290. // 获取网盘播放列表
  18291. const navidromeList = useFindRemoteQueue ? [] : getNavidromeVideoItems();
  18292. const webdavList = useFindRemoteQueue ? [] : getWebdavVideoItems();
  18293. const isNavidrome = !useFindRemoteQueue && navidromeList.length > 0;
  18294. const remoteList = useFindRemoteQueue ? findRemoteQueue : (isNavidrome ? navidromeList : webdavList);
  18295. if (remoteList.length > 0) {
  18296. // 将当前歌加入历史栈
  18297. if (this.currentSong) {
  18298. this.randomPlayHistory.unshift(this.currentSong);
  18299. if (this.randomPlayHistory.length > 50) {
  18300. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  18301. }
  18302. // 标记当前歌曲为已播放
  18303. markAsPlayed(this.currentSong.filePath);
  18304. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  18305. }
  18306. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  18307. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  18308. const totalCount = remoteList.length;
  18309. const playedCount = isNavidrome ? getPlayedCount() : 0;
  18310. Logger.info(TAG,
  18311. `randomPlay(网盘模式): source=${useFindRemoteQueue ? 'find-playlist' : (isNavidrome ? 'navidrome' : 'webdav')}, ` +
  18312. `总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  18313. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  18314. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  18315. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  18316. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  18317. if (loadSuccess) {
  18318. // 重新获取未播放数量
  18319. unplayedCount = getUnplayedCount();
  18320. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  18321. }
  18322. }
  18323. // 从未播放歌曲中随机选择
  18324. let candidates: VideoItem[];
  18325. if (isNavidrome) {
  18326. candidates = getUnplayedSongs();
  18327. // 如果全部播放完,重置已播放记录
  18328. if (candidates.length === 0) {
  18329. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  18330. clearPlayedHistory();
  18331. // 排除当前歌曲
  18332. const currentFilePath = this.currentSong?.filePath;
  18333. candidates = currentFilePath
  18334. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  18335. : getNavidromeVideoItems();
  18336. }
  18337. } else {
  18338. // WebDAV模式:简单排除当前歌曲
  18339. const currentFilePath = this.currentSong?.filePath;
  18340. candidates = currentFilePath
  18341. ? remoteList.filter(v => v.filePath !== currentFilePath)
  18342. : remoteList;
  18343. }
  18344. if (candidates.length > 0) {
  18345. const randomIndex = Math.floor(Math.random() * candidates.length);
  18346. const randomSong = candidates[randomIndex];
  18347. // 标记为已播放
  18348. if (isNavidrome) {
  18349. markAsPlayed(randomSong.filePath);
  18350. }
  18351. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  18352. this.markPreparedSongSwitch(randomSong, true)
  18353. const didStartRemoteListSong = await this.startPreparedCurrentSongPlayback('randomPlay-remote-list')
  18354. if (!didStartRemoteListSong) {
  18355. return;
  18356. }
  18357. return;
  18358. }
  18359. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  18360. }
  18361. }
  18362. if (this.currentSong) {
  18363. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  18364. this.randomPlayHistory.unshift(this.currentSong);
  18365. // 限制历史栈大小,避免无限增长
  18366. if (this.randomPlayHistory.length > 50) {
  18367. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  18368. }
  18369. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  18370. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  18371. const currentFilePath = this.currentSong.filePath;
  18372. if (isCurrentRemote) {
  18373. const remoteOptions: RandomSongQueryOptions = {
  18374. type: this.currentSong.type,
  18375. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18376. };
  18377. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  18378. if (randomRemoteSong) {
  18379. const isAccountAvailable = await this.ensureRemoteSongAccountAvailable(randomRemoteSong, 'randomPlay-remote-db')
  18380. if (!isAccountAvailable) {
  18381. return;
  18382. }
  18383. this.markPreparedSongSwitch(randomRemoteSong, true)
  18384. const didStartRemoteDbSong = await this.startPreparedCurrentSongPlayback('randomPlay-remote-db')
  18385. if (!didStartRemoteDbSong) {
  18386. return;
  18387. }
  18388. return;
  18389. }
  18390. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  18391. } else {
  18392. if (currentFilePath) {
  18393. this.playedLocalFilePaths.add(currentFilePath);
  18394. }
  18395. // 根据modeType构建不同的查询选项
  18396. const localOptions: RandomSongQueryOptions = {
  18397. type: CommonConstants.TYPE_LOCAL,
  18398. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  18399. };
  18400. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  18401. // modeType==0: 文件夹模式,添加parentPath过滤
  18402. if (this.modeType === 0 && this.currentPath) {
  18403. localOptions.parentPath = this.currentPath;
  18404. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  18405. }
  18406. // modeType==4: 歌单模式,添加playlistSongFilePaths
  18407. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18408. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18409. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  18410. } else if (this.modeType === 4) {
  18411. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  18412. }
  18413. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  18414. if (!randomLocalSong) {
  18415. this.playedLocalFilePaths.clear();
  18416. if (currentFilePath) {
  18417. this.playedLocalFilePaths.add(currentFilePath);
  18418. }
  18419. const fallbackLocalOptions: RandomSongQueryOptions = {
  18420. type: CommonConstants.TYPE_LOCAL,
  18421. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18422. };
  18423. // fallback时也要保持modeType的过滤条件
  18424. if (this.modeType === 0 && this.currentPath) {
  18425. fallbackLocalOptions.parentPath = this.currentPath;
  18426. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18427. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18428. }
  18429. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  18430. }
  18431. if (randomLocalSong !== null) {
  18432. const selectedLocalSong = randomLocalSong;
  18433. this.markPreparedSongSwitch(selectedLocalSong, true)
  18434. const didStartLocalRandomSong = await this.startPreparedCurrentSongPlayback('randomPlay-local-db')
  18435. if (!didStartLocalRandomSong) {
  18436. return;
  18437. }
  18438. return;
  18439. }
  18440. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  18441. }
  18442. }
  18443. if (ArrayUtil.isNotEmpty(this.songList)) {
  18444. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  18445. this.playedIndices.add(this.curIndex);
  18446. }
  18447. if (this.songList.length > 3) {
  18448. // 优先使用预缓存的随机索引(仅网盘播放时)
  18449. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  18450. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  18451. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  18452. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  18453. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  18454. this.curIndex = this.preloadNextRandomIndex;
  18455. this.playedIndices.add(this.curIndex);
  18456. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  18457. // 立即预缓存下一首,避免下次点击时没有预缓存
  18458. void this.preloadNextSongInternal();
  18459. } else {
  18460. // 如果没有预缓存索引,则正常随机选择
  18461. // 如果所有歌曲都播放过一次,清空已播放索引集合
  18462. if (this.playedIndices.size === this.songList.length) {
  18463. this.playedIndices.clear();
  18464. }
  18465. // 随机选择一个未播放的歌曲索引
  18466. let newIndex: number;
  18467. // 添加超时机制防止无限循环
  18468. let attempt = 0;
  18469. const maxAttempts = 100; // 根据需求调整
  18470. do {
  18471. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  18472. attempt++;
  18473. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  18474. if (attempt >= maxAttempts) {
  18475. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  18476. newIndex = Math.floor(Math.random() * this.songList.length);
  18477. }
  18478. this.curIndex = newIndex;
  18479. this.playedIndices.add(newIndex);
  18480. }
  18481. } else {
  18482. // 当歌曲数量小于或等于3时,直接播放下一首
  18483. if (this.curIndex == this.songList.length - 1) {
  18484. this.curIndex = 0;
  18485. } else {
  18486. this.curIndex++;
  18487. }
  18488. }
  18489. this.markPreparedSongSwitch(this.songList[this.curIndex])
  18490. const didStartFallbackSong = await this.startPreparedCurrentSongPlayback('randomPlay-fallback')
  18491. if (!didStartFallbackSong) {
  18492. return;
  18493. }
  18494. // 预缓存下一首(包括网盘和本地)
  18495. void this.preloadNextSongInternal();
  18496. }
  18497. }
  18498. private async playIndex(index: number) {
  18499. if (!this.debounce()) {
  18500. return;
  18501. }
  18502. if (ArrayUtil.isNotEmpty(this.songList)) {
  18503. this.applySelectedQueueSong(index)
  18504. const playIndexPreparation = await this.prepareCurrentSongPlayback('playIndex')
  18505. if (!playIndexPreparation.success) {
  18506. return;
  18507. }
  18508. // 如果是投播模式,需要为投播设备准备当前歌曲
  18509. if (this.castController && this.isCastPlaying) {
  18510. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  18511. this.initQueueItem();
  18512. await this.prepare();
  18513. if (playIndexPreparation.loadingShown) {
  18514. this.hideLoadIng();
  18515. }
  18516. const playIndexSong = this.currentSong
  18517. if (!playIndexSong) {
  18518. return;
  18519. }
  18520. this.cover = playIndexSong.pixelMapPath;
  18521. return;
  18522. }
  18523. // 本地播放器模式,需要先stop
  18524. this.finalizeLocalTrackSwitch(playIndexPreparation.loadingShown)
  18525. }
  18526. }
  18527. //上一个
  18528. private async playPrevious() {
  18529. if (this.isHostSnapshotDisplayOnly) {
  18530. await BackgroundAudioPlaybackHost.getInstance().getRuntime().playPrevious()
  18531. return
  18532. }
  18533. if (!this.debounce()) {
  18534. return;
  18535. }
  18536. const previousPlaybackAction = MusicPlaybackController.resolvePreviousPlaybackAction(this.playType)
  18537. if (previousPlaybackAction === 'history_previous') {
  18538. this.randomModePlayFromHistory()
  18539. return;
  18540. }
  18541. if (ArrayUtil.isEmpty(this.songList)) {
  18542. return;
  18543. }
  18544. this.curIndex = MusicPlaybackController.resolvePreviousQueueIndex(this.curIndex, this.songList.length).nextIndex;
  18545. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  18546. this.applySelectedQueueSong(this.curIndex)
  18547. const previousSong = this.currentSong
  18548. if (!previousSong) {
  18549. return;
  18550. }
  18551. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${previousSong.name}, type: ${previousSong.type}`);
  18552. const isCurrentSongAccountAvailable = await this.ensureRemoteSongAccountAvailable(previousSong, 'playPrevious')
  18553. if (!isCurrentSongAccountAvailable) {
  18554. this.curIndex = MusicPlaybackController.resolvePreviousQueueIndex(this.curIndex, this.songList.length).nextIndex;
  18555. this.applySelectedQueueSong(this.curIndex)
  18556. }
  18557. await this.dispatchPreparedQueueSwitch(
  18558. 'playPrevious',
  18559. '播放上一首',
  18560. async (durationMs: number): Promise<void> => {
  18561. await this.castControllerWrapper!.playPrevious(this.songList, this.curIndex, this.videoUrl, durationMs);
  18562. },
  18563. true
  18564. )
  18565. }
  18566. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  18567. private async randomModePlayFromHistory() {
  18568. if (this.randomPlayHistory.length >= 1) {
  18569. // 播放历史栈的第一首(刚刚播放过的)
  18570. const prevSong = this.randomPlayHistory[0];
  18571. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  18572. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  18573. this.randomPlayHistory.shift();
  18574. this.curIndex = this.ensureSongQueued(prevSong);
  18575. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18576. this.stop();
  18577. const isHistorySongAccountAvailable = await this.ensureRemoteSongAccountAvailable(prevSong, 'randomModePlayFromHistory')
  18578. if (!isHistorySongAccountAvailable) {
  18579. if (this.randomPlayHistory.length >= 1) {
  18580. this.randomModePlayFromHistory();
  18581. return;
  18582. } else {
  18583. ToastUtil.showToast('没有更多历史记录');
  18584. return;
  18585. }
  18586. }
  18587. this.songList[this.curIndex] = prevSong;
  18588. this.currentSong = this.songList[this.curIndex];
  18589. const didStartHistorySong = await this.startPreparedCurrentSongPlayback('randomPlay-history', false)
  18590. if (!didStartHistorySong) {
  18591. return;
  18592. }
  18593. } else {
  18594. ToastUtil.showToast('随机播放模式暂无历史记录');
  18595. }
  18596. }
  18597. debounce() {
  18598. const delay = 600;
  18599. let cur = new Date().getTime();
  18600. if (cur - this.last > delay) {
  18601. this.last = cur;
  18602. return true;
  18603. }
  18604. return false;
  18605. }
  18606. /**
  18607. * Sets whether the screen is a constant based on the playback status.
  18608. */
  18609. watchStatus() {
  18610. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  18611. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  18612. this.windowClass.setWindowKeepScreenOn(true);
  18613. } else {
  18614. this.windowClass.setWindowKeepScreenOn(false);
  18615. }
  18616. }
  18617. /**
  18618. * Volume gesture method onActionStart.
  18619. *
  18620. * @param event Gesture event.
  18621. */
  18622. private customDialogComponentIdMM: number = 0
  18623. @Builder
  18624. customDialogComponentMM() {
  18625. Column() {
  18626. Row() {
  18627. Blank()
  18628. Text('验证密码')
  18629. .fontSize(22)
  18630. .fontColor($r('app.color.pri_bg'))
  18631. .margin({ top: 18 })
  18632. Blank()
  18633. Image($r('app.media.close'))
  18634. .fillColor(Color.White)
  18635. .margin({ top: 18, right: 18 })
  18636. .width(20)
  18637. .onClick(() => {
  18638. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18639. })
  18640. }
  18641. .width('100%') // 使Row占据整个宽度
  18642. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  18643. Verify({
  18644. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  18645. });
  18646. }.height('60%')
  18647. .backgroundColor($r('app.color.index_background'))
  18648. .justifyContent(FlexAlign.SpaceBetween)
  18649. }
  18650. private handleVerifyCompleted(isSuccess: boolean) {
  18651. if (isSuccess) {
  18652. console.log('验证成功');
  18653. // 在这里处理验证成功后的逻辑
  18654. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18655. this.currentPath = this.lockPath
  18656. this.getSortedFiles(this.currentPath)
  18657. } else {
  18658. // console.log('验证失败');
  18659. ToastUtil.showToast('验证失败')
  18660. }
  18661. }
  18662. private showVerifyDialog() {
  18663. promptAction.openCustomDialog({
  18664. transition: TransitionEffect.asymmetric(
  18665. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  18666. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18667. ,
  18668. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  18669. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18670. ),
  18671. builder: () => {
  18672. this.customDialogComponentMM()
  18673. },
  18674. isModal: true,
  18675. autoCancel: true,
  18676. maskColor: Color.Transparent,
  18677. alignment: DialogAlignment.Bottom,
  18678. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  18679. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  18680. console.log("dialog onWillDismiss")
  18681. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  18682. dismissDialogAction.dismiss()
  18683. }
  18684. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  18685. dismissDialogAction.dismiss()
  18686. }
  18687. }
  18688. }).then((dialogId: number) => {
  18689. this.customDialogComponentIdMM = dialogId
  18690. })
  18691. }
  18692. //左滑操作 移动文件 重命名 删除等操作
  18693. @Builder
  18694. DeleteButton(item: VideoItem, index: number, filePath: string) {
  18695. Row() {
  18696. //加入收藏
  18697. // Button() {
  18698. // Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  18699. // .fillColor(Color.White)
  18700. // .width(20)
  18701. // }
  18702. // .width(40)
  18703. // .height(40)
  18704. // .type(ButtonType.Circle)
  18705. // .backgroundColor(this.themeColor)
  18706. // .margin(5)
  18707. // .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18708. // .onClick(() => {
  18709. // if (item) {
  18710. // this.doFav(item)
  18711. // }
  18712. // })
  18713. //加入下一首播放
  18714. Button() {
  18715. Image($r('app.media.next_to_play'))
  18716. .fillColor(Color.White)
  18717. .width(20)
  18718. }
  18719. .width(40)
  18720. .height(40)
  18721. .type(ButtonType.Circle)
  18722. .backgroundColor(this.themeColor)
  18723. .margin(5)
  18724. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18725. .onClick(() => {
  18726. this.addToNextPlay(item);
  18727. })
  18728. //复制文件
  18729. Button() {
  18730. Image($r('app.media.copy'))
  18731. .fillColor(Color.White)
  18732. .width(20)
  18733. }
  18734. .width(40)
  18735. .height(40)
  18736. .type(ButtonType.Circle)
  18737. .backgroundColor(this.themeColor)
  18738. .margin(5)
  18739. .id(filePath + 'copy')
  18740. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18741. .onClick(() => {
  18742. this.showCopyDialog(false, item, index, filePath + 'copy');
  18743. })
  18744. //移动文件
  18745. Button() {
  18746. Image($r('app.media.cut'))
  18747. .fillColor(Color.White)
  18748. .width(20)
  18749. }
  18750. .width(40)
  18751. .height(40)
  18752. .type(ButtonType.Circle)
  18753. .backgroundColor(this.themeColor)
  18754. .margin(5)
  18755. .id(filePath)
  18756. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18757. .onClick(() => {
  18758. this.showCutDialog(false, item, index, filePath);
  18759. })
  18760. Button() {
  18761. Image($r('app.media.cut_current'))
  18762. .fillColor(Color.White)
  18763. .width(20)
  18764. }
  18765. .width(40)
  18766. .height(40)
  18767. .type(ButtonType.Circle)
  18768. .backgroundColor(this.themeColor)
  18769. .margin(5)
  18770. .id(filePath + 'current')
  18771. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  18772. (this.isHasDir ? Visibility.Visible : Visibility.None))
  18773. .onClick(() => {
  18774. this.showCutDialog(true, item, index, filePath + 'current');
  18775. })
  18776. //重命名
  18777. // Button() {
  18778. // Image($r('app.media.rename2'))
  18779. // .fillColor(Color.White)
  18780. // .width(20)
  18781. // }
  18782. // .width(40)
  18783. // .height(40)
  18784. // .type(ButtonType.Circle)
  18785. // .backgroundColor(this.themeColor)
  18786. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18787. // (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18788. // item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18789. // .margin(5)
  18790. // .onClick(() => {
  18791. // this.showReNameDialog(item, index + '', filePath)
  18792. //
  18793. // })
  18794. Button() {
  18795. Image($r('app.media.delete2'))
  18796. .fillColor(Color.White)
  18797. .width(20)
  18798. }
  18799. .width(40)
  18800. .height(40)
  18801. .type(ButtonType.Circle)
  18802. .backgroundColor(this.themeColor)
  18803. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18804. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18805. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18806. .margin({ left:5,top:5,bottom:5,right:20} )
  18807. .onClick(() => {
  18808. this.selectSingleItemForDelete(item)
  18809. this.showWarnIsDelete()
  18810. // this.showWarnIsDeleteFile(item, index + '', filePath)
  18811. })
  18812. // Button() {
  18813. // Image($r('app.media.share2'))
  18814. // .fillColor(Color.White)
  18815. // .width(20)
  18816. // }
  18817. // .width(40)
  18818. // .height(40)
  18819. // .type(ButtonType.Circle)
  18820. // .backgroundColor(this.themeColor)
  18821. // .margin(5)
  18822. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18823. // .onClick(() => {
  18824. // Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  18825. // })
  18826. }
  18827. }
  18828. /**
  18829. * 穿山甲banner广告
  18830. */
  18831. // private declare bannerAd: CSJNativeExpressAd;
  18832. // @State private status: string = "未加载"
  18833. // @State private isShowAd: boolean = false
  18834. // private declare mAdSlot: AdSlot;
  18835. // private mBiddingAdm = '' //服务端bidding才需要设置
  18836. // private expressLoadAdListener: NativeExpressAdListener = {
  18837. // /**
  18838. // * 加载失败的回调
  18839. // *
  18840. // * @param code
  18841. // * @param message
  18842. // */
  18843. // onError: (code: number, message: string) => {
  18844. // console.error("加载广告失败,code=" + code + ",message=" + message);
  18845. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  18846. // },
  18847. //
  18848. // /**
  18849. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  18850. // *
  18851. // * @param ads 返回的广告列表
  18852. // */
  18853. //
  18854. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  18855. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  18856. // if (ads && ads.length > 0) {
  18857. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  18858. // ad.setExpressInteractionListener({
  18859. // /**
  18860. // *广告的点击回调
  18861. // * @param type 广告的交互类型
  18862. // */
  18863. // onAdClicked: (type: number) => {
  18864. // console.log("BannerExpressAdPage==onAdClicked......");
  18865. // },
  18866. //
  18867. // /**
  18868. // * 广告的展示回调 每个广告仅回调一次
  18869. // * @param type 广告的交互类型
  18870. // */
  18871. // onAdShow: (type: number) => {
  18872. // console.log("BannerExpressAdPage==onAdShow......");
  18873. // },
  18874. //
  18875. // /**
  18876. // * 模板渲染失败
  18877. // */
  18878. // onRenderFail: (code: number, msg: string) => {
  18879. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  18880. // },
  18881. //
  18882. // /**
  18883. // * 模板渲染成功
  18884. // * @param width 返回view的宽 单位 vp
  18885. // * @param height 返回view的高 单位 vp
  18886. // */
  18887. // onRenderSuccess: (width: number, height: number) => {
  18888. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  18889. // this.bannerAd = ad;
  18890. // this.status = "广告加载完成待展示";
  18891. //
  18892. // this.showBannerAd()
  18893. // }
  18894. // })
  18895. // //渲染广告
  18896. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  18897. // this.setDislikeCallback(ad); //设置dislike
  18898. // ad.render(this.getUIContext())
  18899. // this.status = "广告加载中...";
  18900. // });
  18901. // }
  18902. // }
  18903. // }
  18904. //
  18905. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  18906. // ad.setDislikeCallback({
  18907. // /**
  18908. // * dislike show
  18909. // */
  18910. // onShow: () => {
  18911. // console.log("BannerExpressAdPage==dislike......show");
  18912. // },
  18913. //
  18914. // /**
  18915. // * @param position 选择的位置
  18916. // * @param value 选择的内容
  18917. // * @param enforceRemove 是否强制关闭广告
  18918. // */
  18919. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  18920. // this.isShowAd = false;
  18921. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  18922. // ",enforce=" + enforceRemove);
  18923. // },
  18924. //
  18925. // /**
  18926. // * 点击取消
  18927. // */
  18928. // onCancel: () => {
  18929. // console.log("BannerExpressAdPage==dislike......onCancel");
  18930. // }
  18931. //
  18932. // })
  18933. // }
  18934. /**
  18935. * 加载Banner广告
  18936. */
  18937. loadBannerAd(rit: string) {
  18938. // if (Utility.isNoble()) {
  18939. // return
  18940. // }
  18941. // if (!Utility.isPassInstallTime(2)) {
  18942. // return
  18943. // }
  18944. // this.isShowAd = false;
  18945. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  18946. // this.mAdSlot = new AdSlotBuilder()
  18947. // .setCodeId(rit)
  18948. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  18949. // .setAdCount(1)
  18950. // .setBidAdm(this.mBiddingAdm)
  18951. // .build()
  18952. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  18953. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  18954. // this.status = "广告加载中..."
  18955. }
  18956. /**
  18957. * 展示Banner广告
  18958. */
  18959. // showBannerAd() {
  18960. // if (!this.bannerAd) {
  18961. // return
  18962. // }
  18963. // this.isShowAd = true
  18964. // this.status = "已展示"
  18965. // }
  18966. /**
  18967. * 穿山甲广告代码结束
  18968. */
  18969. /**
  18970. * 处理歌单播放请求
  18971. */
  18972. private syncWebdavQueueWithoutRestart(): void {
  18973. try {
  18974. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  18975. return;
  18976. }
  18977. const webdavList = getWebdavVideoItems();
  18978. if (!ArrayUtil.isNotEmpty(webdavList)) {
  18979. return;
  18980. }
  18981. const currentPath = this.currentSong.filePath;
  18982. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  18983. if (targetIndex < 0) {
  18984. const memoryIndex = getWebdavCurrentPlayIndex();
  18985. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  18986. targetIndex = memoryIndex;
  18987. }
  18988. }
  18989. if (targetIndex < 0) {
  18990. targetIndex = 0;
  18991. }
  18992. this.songList = [...webdavList];
  18993. this.currentSongList = [...webdavList];
  18994. this.sonDataSource.pushArrayData(this.songList);
  18995. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  18996. this.curIndex = targetIndex;
  18997. PreferencesUtil.putSync('LastMusicList', this.songList);
  18998. this.skipNextPlaylistPersist = true
  18999. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  19000. } catch (error) {
  19001. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  19002. }
  19003. }
  19004. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  19005. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  19006. try {
  19007. const totalCount = songCount ?? songFilePaths.length;
  19008. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  19009. // 检查是否为WebDAV播放请求
  19010. if (playlistId === 'webdav-playlist') {
  19011. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  19012. // 从全局内存读取videoItems数据
  19013. const videoItems = getWebdavVideoItems();
  19014. const currentPlayIndex = getWebdavCurrentPlayIndex();
  19015. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  19016. if (videoItems && videoItems.length > 0) {
  19017. // 验证webdav_account_id设置情况
  19018. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  19019. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  19020. if(isJump){
  19021. this.setShowPlayTrue()//显示播放页
  19022. }
  19023. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  19024. return
  19025. } else {
  19026. return
  19027. }
  19028. }
  19029. if (playlistId === 'navidrome-playlist') {
  19030. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  19031. const videoItems = getNavidromeVideoItems();
  19032. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  19033. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  19034. if (videoItems && videoItems.length > 0) {
  19035. if(isJump){
  19036. this.setShowPlayTrue()//显示播放页
  19037. }
  19038. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  19039. return;
  19040. } else {
  19041. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  19042. return;
  19043. }
  19044. }
  19045. if (playlistId === 'find-album-playlist' || playlistId.indexOf('find-') === 0) {
  19046. Logger.info(`heanup 检测到发现页播放请求,从内存读取videoItems`)
  19047. const videoItems = getFindVideoItems();
  19048. const currentPlayIndex = getFindCurrentPlayIndex();
  19049. const findPlaylistMeta = getFindPlaylistMeta();
  19050. Logger.info(`heanup 发现页歌曲列表长度: ${videoItems.length}, 索引: ${currentPlayIndex}`)
  19051. Logger.info(
  19052. TAG,
  19053. `[remote-debug] handlePlaylistPlayRequest find-memory playlist=${playlistId}, loaded=${videoItems.length}, ` +
  19054. `declaredTotal=${totalCount}, sample=${this.buildSongListDebugLog(videoItems)}`
  19055. )
  19056. if (videoItems && videoItems.length > 0) {
  19057. if (isJump) {
  19058. this.setShowPlayTrue()
  19059. }
  19060. // 只有“随心所欲分页随机”才读取分页元数据,其他发现页队列仍按原有歌单模式处理。
  19061. const findMeta = isFindLocalRandomPagedPlaylist(playlistId) && findPlaylistMeta.isPagedLocalQueue
  19062. ? findPlaylistMeta
  19063. : undefined;
  19064. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount, findMeta)
  19065. return
  19066. } else {
  19067. Logger.warn('heanup 发现页播放请求缺少歌曲数据')
  19068. return
  19069. }
  19070. }
  19071. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  19072. const songMap: Map<number, VideoItem> = new Map()
  19073. let completedQueries = 0
  19074. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  19075. // 遍历所有文件路径,使用索引记录位置
  19076. for (let i = 0; i < songFilePaths.length; i++) {
  19077. const filePath = songFilePaths[i]
  19078. const index = i
  19079. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  19080. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  19081. const queryPromise = this.table.queryVideoByFilePath(filePath)
  19082. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  19083. queryPromise.then((videoItem) => {
  19084. completedQueries++
  19085. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  19086. if (videoItem) {
  19087. // 使用索引作为key保存到Map中,保持原始顺序
  19088. songMap.set(index, videoItem)
  19089. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  19090. } else {
  19091. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  19092. }
  19093. // 检查是否所有歌曲都已加载完成
  19094. if (completedQueries === songFilePaths.length) {
  19095. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  19096. // 按照索引顺序重建歌曲数组
  19097. const songs: VideoItem[] = []
  19098. for (let j = 0; j < songFilePaths.length; j++) {
  19099. const song = songMap.get(j)
  19100. if (song) {
  19101. songs.push(song)
  19102. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  19103. }
  19104. }
  19105. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  19106. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  19107. }
  19108. }).catch((error: Error) => {
  19109. completedQueries++
  19110. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  19111. // 即使出错也要检查是否完成所有查询
  19112. if (completedQueries === songFilePaths.length) {
  19113. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  19114. // 按照索引顺序重建歌曲数组
  19115. const songs: VideoItem[] = []
  19116. for (let j = 0; j < songFilePaths.length; j++) {
  19117. const song = songMap.get(j)
  19118. if (song) {
  19119. songs.push(song)
  19120. }
  19121. }
  19122. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  19123. }
  19124. })
  19125. }
  19126. } catch (error) {
  19127. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  19128. ToastUtil.showToast('播放失败')
  19129. }
  19130. }
  19131. /**
  19132. * 完成歌单加载并开始播放
  19133. */
  19134. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number,
  19135. findMeta?: FindPlaylistMeta) {
  19136. if (songs.length === 0) {
  19137. Logger.error('heanup 没有找到任何可播放的歌曲')
  19138. ToastUtil.showToast('没有找到可播放的歌曲')
  19139. return
  19140. }
  19141. const isFindPagedLocalQueue = !!findMeta?.isPagedLocalQueue;
  19142. this.songList = songs
  19143. this.currentSongList = songs // 同步更新 currentSongList
  19144. this.sonDataSource.pushArrayData(songs)
  19145. this.curIndex = startIndex
  19146. const actualTotal = totalCount ?? songs.length;
  19147. if (isFindPagedLocalQueue) {
  19148. // 这类队列只保存当前页歌曲,总数和分页游标放到独立状态里继续滚动加载。
  19149. this.applyFindPagedLocalQueueState(findMeta, actualTotal);
  19150. this.currentPlaylistSongFilePaths = [];
  19151. } else {
  19152. this.resetFindPagedLocalQueueState();
  19153. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  19154. }
  19155. // 如果是网盘播放,保存服务端总数到全局存储
  19156. if (!isFindPagedLocalQueue && totalCount && totalCount > 0 && songs.length > 0) {
  19157. const firstSong = songs[0];
  19158. if (firstSong && (isNavidromeType(firstSong.type) ||
  19159. isJellyfinType(firstSong.type) ||
  19160. isEmbyType(firstSong.type) ||
  19161. isAudioStationType(firstSong.type) ||
  19162. isPlexType(firstSong.type) ||
  19163. isDaoLiYuType(firstSong.type))) {
  19164. setNavidromeTotalCount(totalCount);
  19165. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  19166. }
  19167. }
  19168. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  19169. Logger.info(
  19170. TAG,
  19171. `[remote-debug] finishLoadingPlaylist playlist=${playlistName}, loaded=${songs.length}, actualTotal=${actualTotal}, ` +
  19172. `startIndex=${startIndex}, sample=${this.buildSongListDebugLog(songs)}`
  19173. );
  19174. if (songs[startIndex]) {
  19175. // 确保当前播放的歌曲也更新到存储
  19176. AppStorage.setOrCreate('currentSong', songs[startIndex])
  19177. if (isFindPagedLocalQueue) {
  19178. // 不要把发现页分页随机队列降级成普通歌单,否则后面又会触发全量 hydrate。
  19179. this.preserveExistingQueueOnNextPlay = true
  19180. this.nextPlayQueueScope = 'find_paged_local'
  19181. this.doPlay(songs[startIndex], startIndex, false)
  19182. } else {
  19183. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  19184. this.doPlay(songs[startIndex], startIndex, true)
  19185. }
  19186. }
  19187. PreferencesUtil.putSync('LastMusicList', this.songList)
  19188. this.skipNextPlaylistPersist = true
  19189. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  19190. }
  19191. }
  19192. //视频气泡窗口的布局
  19193. @Builder
  19194. function customPopupBuilder(dataBu: BubbleBean) {
  19195. List() {
  19196. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  19197. ListItem() {
  19198. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19199. Row() {
  19200. Column() {
  19201. Image(dataBu.imageRes[index])
  19202. .height(28)
  19203. .fillColor(dataBu.color)
  19204. .alignSelf(ItemAlign.Center)
  19205. }
  19206. .width(32)
  19207. Text(item)
  19208. .padding({
  19209. top: 10,
  19210. bottom: 10,
  19211. right: 10,
  19212. left: 10
  19213. })
  19214. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  19215. .textAlign(TextAlign.Start)
  19216. .width("100%")
  19217. }
  19218. }
  19219. .backgroundColor($r('app.color.settings_background_main'))
  19220. .margin({ top: 6, bottom: 6 })
  19221. }
  19222. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  19223. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  19224. TransitionEffect.scale({ x: 0, y: 0 })))
  19225. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  19226. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  19227. .onClick(() => {
  19228. dataBu.onItemClick?.(index)
  19229. })
  19230. })
  19231. }
  19232. .scrollBar(BarState.Off)
  19233. .width(120)
  19234. .divider({
  19235. strokeWidth: 1,
  19236. color: "#22FFFFFF"
  19237. })
  19238. }
  19239. // Function to calculate a hash for the file list
  19240. function simpleHash(fileList: string[]): string {
  19241. let hash = 0;
  19242. const str = fileList.join(',');
  19243. for (let i = 0; i < str.length; i++) {
  19244. const char = str.charCodeAt(i);
  19245. hash = (hash << 5) - hash + char;
  19246. hash |= 0; // Convert to 32bit integer
  19247. }
  19248. return hash.toString();
  19249. }
  19250. interface MoreItem {
  19251. id: number;
  19252. image: Resource;
  19253. title: string;
  19254. }
  19255. //视频气泡窗口的布局
  19256. @Builder
  19257. function cutPopupBuilder(dataBu: BubbleBean) {
  19258. Column() {
  19259. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  19260. .padding({
  19261. top: 10,
  19262. bottom: 10,
  19263. right: 10,
  19264. left: 10
  19265. })
  19266. .textAlign(TextAlign.Start)
  19267. .width(160)
  19268. .fontWeight(666)
  19269. .fontSize(16)
  19270. List() {
  19271. ForEach(dataBu.data, (item: string, index: number) => {
  19272. ListItem() {
  19273. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19274. Row() {
  19275. Column() {
  19276. Image($r('app.media.music_group'))
  19277. .height(28)
  19278. .fillColor(dataBu.color)
  19279. .alignSelf(ItemAlign.Center)
  19280. }
  19281. .width(32)
  19282. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  19283. .padding({
  19284. top: 10,
  19285. bottom: 10,
  19286. right: 10,
  19287. left: 10
  19288. })
  19289. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  19290. .fontSize(15)
  19291. }
  19292. }
  19293. .backgroundColor(Color.Transparent)
  19294. .margin({ top: 7, bottom: 7 })
  19295. }
  19296. .onClick(() => {
  19297. dataBu.onItemClick?.(index)
  19298. })
  19299. })
  19300. }
  19301. .scrollBar(BarState.Off)
  19302. .width(150)
  19303. .divider({
  19304. strokeWidth: 1,
  19305. color: "#22FFFFFF"
  19306. })
  19307. }
  19308. .height(300)
  19309. .padding({
  19310. bottom: 30
  19311. })
  19312. }
  19313. @Concurrent
  19314. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  19315. const alphabetSet = new Set<string>()
  19316. for (const item of items) {
  19317. let text = isShowFileName ? (item.fileName || '') :
  19318. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  19319. if (sortType === 0 || sortType == 1) {
  19320. text = item.artist || ''
  19321. } else if (sortType === 2 || sortType == 3) {
  19322. text = item.album || ''
  19323. }
  19324. if (text && text.length > 0) {
  19325. const first = getFirstLetter(text)
  19326. if (!alphabetSet.has(first)) {
  19327. alphabetSet.add(first)
  19328. }
  19329. }
  19330. }
  19331. const sorted = Array.from(alphabetSet).sort((a, b) => {
  19332. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  19333. return a.localeCompare(b)
  19334. }
  19335. return b.localeCompare(a)
  19336. })
  19337. return sorted
  19338. }
  19339. function getFileDirName(filePath: string,rootPath:string): string{
  19340. if(filePath===rootPath){
  19341. return '首页'
  19342. }
  19343. let result = FileUtil.getFileName(filePath)
  19344. if(StrUtil.isEmpty(result))
  19345. return ''
  19346. if(result.startsWith('.'))
  19347. result = result.replace(/\./g, '')
  19348. return result
  19349. }
  19350. //只扫描当前目录下文件(不扫描子文件夹)的方法
  19351. @Concurrent
  19352. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  19353. const table: MediaTable = new MediaTable(context);
  19354. try {
  19355. // 直接获取当前目录下的文件列表
  19356. const files = FileUtil.listFileSync(dirPath);
  19357. await Promise.all(files.map(async (file) => {
  19358. const fPath = `${dirPath}/${file}`;
  19359. // 跳过目录,只处理文件
  19360. if (FileUtil.isDirectory(fPath)) {
  19361. return;
  19362. }
  19363. // 跳过特定格式文件
  19364. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  19365. return;
  19366. }
  19367. // 检查是否为媒体文件
  19368. if (Utility.isMeidaByExtension(fPath)) {
  19369. let mType = CommonConstants.TYPE_LOCAL;
  19370. if (fPath.includes(lockPath)) {
  19371. mType = CommonConstants.TYPE_LOCK;
  19372. }
  19373. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  19374. context, fPath, mType, true
  19375. );
  19376. table.insert(mediaItem, (id: number) => {
  19377. // 插入回调函数
  19378. }, cover_api);
  19379. }
  19380. }));
  19381. } catch (error) {
  19382. console.error(' 扫描当前目录失败:', error);
  19383. }
  19384. }
  19385. //内嵌标签后更新库
  19386. @Concurrent
  19387. async function updateInfoDb(
  19388. context: Context,
  19389. filePath: string,
  19390. titleStr: string,
  19391. artistStr: string,
  19392. albumStr: string,
  19393. lyricConStr: string,
  19394. yearStr: string,
  19395. genreStr: string,
  19396. trackStr: string,
  19397. albumArtistStr: string,
  19398. composerStr: string,
  19399. lyricistStr: string,
  19400. commentStr: string,
  19401. discStr: string,
  19402. ): Promise<boolean> {
  19403. const table: MediaTable = new MediaTable(context);
  19404. await new Promise<void>((resolve, reject) => {
  19405. table.getRdbStore(context, (err:Error) => {
  19406. err ? reject(err) : resolve();
  19407. });
  19408. });
  19409. return await new Promise<boolean>((resolve) => {
  19410. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  19411. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  19412. (success: boolean, error?: string) => {
  19413. if (success) {
  19414. console.log("onecold 编辑信息成功,数据库已同步");
  19415. } else {
  19416. console.error("onecold 编辑信息数据库失败原因: " + error);
  19417. }
  19418. resolve(success);
  19419. });
  19420. });
  19421. }
  19422. @Concurrent
  19423. async function replaceLocalMusicCoverTask(
  19424. context: Context,
  19425. filePath: string,
  19426. sandboxCoverPath: string
  19427. ): Promise<boolean> {
  19428. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  19429. if (!coverResult) {
  19430. return false;
  19431. }
  19432. const table: MediaTable = new MediaTable(context);
  19433. await new Promise<void>((resolve, reject) => {
  19434. table.getRdbStore(context, (err: Error) => {
  19435. err ? reject(err) : resolve();
  19436. });
  19437. });
  19438. return await new Promise<boolean>((resolve) => {
  19439. table.updateCustomCoverPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  19440. (success: boolean, _error?: string) => {
  19441. resolve(success);
  19442. });
  19443. });
  19444. }