LocalMusic.ets 744 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831
  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 { getFindVideoItems, getFindCurrentPlayIndex } from '../common/util/FindPlaylistStore';
  18. import { triggerLoadMoreSongs, hasMoreData } from '../common/util/NavidromeRandomLoader';
  19. import {
  20. ImplOnBufferingUpdateListener,
  21. ImplOnCompletionListener,
  22. ImplOnErrorListener,
  23. ImplOnInfoListener,
  24. ImplOnPreparedListener,
  25. ImplOnSeekCompleteListener,
  26. ImplOnTimedTextListener,
  27. ImplOnVideoSizeChangedListener
  28. } from '../common/IjkPlayerListenerImpls';
  29. import {
  30. ImageFancyModifier,
  31. } from '../common/util/AttributeModifierUtil'
  32. import {
  33. AppUtil,
  34. ArrayUtil,
  35. Base64Util,
  36. DateUtil,
  37. DeviceUtil,
  38. FileUtil,
  39. GlobalContext,
  40. LogUtil,
  41. MD5,
  42. PreferencesUtil,
  43. RandomUtil,
  44. StrUtil,
  45. ToastUtil
  46. } from '@pura/harmony-utils';
  47. import { imagePathToPixelMap } from '../common/util/CommUtils';
  48. import LyricUtil from '../common/util/LyricUtil';
  49. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  50. import { CommonConstants } from '../common/constants/CommonConstants';
  51. import { BaiduConstants } from '../common/constants/BaiduConstants';
  52. import { EventConstants } from '../common/constants/EventConstants';
  53. import Logger from '../common/util/Logger';
  54. import { http } from '@kit.NetworkKit';
  55. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  56. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  57. import { BubbleBean } from '../viewmodel/BubbleBean';
  58. import { PopupPosition, XPopup } from '@chinalike/popup';
  59. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  60. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  61. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  62. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  63. import { Verify } from './Verify';
  64. import { taskpool } from '@kit.ArkTS';
  65. import { RotatingCover } from './RotatingCover';
  66. import { SpectrumView } from './spectrum/SpectrumView';
  67. import { PlayingIndicator } from './PlayingIndicator';
  68. import { PointLightButton } from './PointLight/PointLightButton';
  69. import { TitleBarPointLightButton } from './PointLight/TitleBarPointLightButton'
  70. import { PlayConstants } from '../common/constants/PlayConstants';
  71. import { effectKit } from '@kit.ArkGraphics2D';
  72. import { ColorConversion } from '../common/util/ColorConversion';
  73. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  74. import { AvSessionController } from '../controller/AvSessionController';
  75. import { EqualizerManager } from '../common/util/EqualizerManager';
  76. import { EqualizerViewWithCallback } from './EqualizerView';
  77. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  78. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  79. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  80. import { TagsContentCover } from '../view/TagsContentCover';
  81. import {
  82. DeviceChangeReason,
  83. IjkMediaPlayer,
  84. InterruptEvent,
  85. InterruptHintType,
  86. LogUtils,
  87. OnBufferingUpdateListener,
  88. OnCompletionListener,
  89. OnErrorListener,
  90. OnInfoListener,
  91. OnPreparedListener,
  92. OnSeekCompleteListener,
  93. OnTimedTextListener,
  94. OnVideoSizeChangedListener
  95. } from '@ohos/ijkplayer';
  96. import { PlayStatus } from '../common/PlayStatus';
  97. import fs from '@ohos.file.fs';
  98. import { image } from '@kit.ImageKit';
  99. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  100. import { media } from '@kit.MediaKit';
  101. import { UniversalDetector } from '@ohos/juniversalchardet';
  102. import { SettingPage } from '../pages/SettingPage';
  103. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  104. import { CommonConstants2 } from '../common/util/CommonConstants2';
  105. import { hilog } from '@kit.PerformanceAnalysisKit';
  106. import { LazyDataSource } from '../common/util/LazyDataSource';
  107. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  108. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  109. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  110. import { ringtone } from '@kit.RingtoneKit';
  111. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  112. import { resourceManager } from '@kit.LocalizationKit';
  113. import { deviceInfo } from '@kit.BasicServicesKit';
  114. import '../common/network/RemoteCacheRegistry';
  115. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  116. import { lyricService, SongData } from '../common/service/LyricService';
  117. import { shouldResolveRemoteLyricOnPlay, tryResolveRemotePlaybackLyric } from '../common/util/RemotePlaybackLyricUtil';
  118. import {
  119. cloneVideoItem,
  120. preloadNextSongIfNeeded,
  121. setVideoUrlForSong,
  122. getTypeOrder,
  123. isWebDavType,
  124. isSmbType,
  125. isNavidromeType,
  126. isFtpType,
  127. isBaiduType,
  128. isJellyfinType,
  129. isEmbyType,
  130. isAudioStationType,
  131. isPlexType,
  132. isRemoteCloudType,
  133. mergeCoverWithPriority,
  134. WorkerEditMusicResult,
  135. WebDavMetadataUpdatePayload,
  136. isDaoLiYuType
  137. } from '../common/util/RemotePlayerUtil';
  138. import { PlaylistPlayRequest, consumePendingPlaylistPlay, clearPendingPlaylistPlay } from '../common/util/PlaylistPlayRequestStore';
  139. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  140. import app from '@system.app';
  141. import { TextNodeController } from './PipLyricTextBuilder';
  142. import { IndexerView } from './IndexerView';
  143. import { KeyCode } from '@kit.InputKit';
  144. import { KnockController } from '../controller/KnockController';
  145. import { DeleteComptent } from '../view/DeleteComptent';
  146. import { ABLoopComptent } from '../view/ABLoopComptent';
  147. import { FixMessyView } from '../view/FixMessyView';
  148. import {
  149. parseCueFile,
  150. CueTrack,
  151. CueInfo,
  152. getCueTrackDuration,
  153. getCueTrackEndOffset,
  154. getCueTrackStartOffset,
  155. importCueTracks,
  156. isCueSplitItem
  157. } from '../common/util/CueUtils';
  158. import { CueComptent } from '../view/CueComptent';
  159. import { SearchHistoryUtil } from '../common/util/SearchHistoryUtil';
  160. import { IsoExtractComptent } from '../view/IsoExtractComptent';
  161. import PlaylistTable from '../common/util/PlaylistTable';
  162. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  163. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  164. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  165. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  166. import { Song } from '../viewmodel/Song';
  167. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  168. import { SongType } from '../common/enums/SongType';
  169. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  170. buildHttpHeadersWithWebDav,
  171. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  172. import PermissionUtil from '../common/util/PermissionUtil'
  173. import { EditAudio, setRingTone } from './EditAudio';
  174. import { ExtractAccompaniment } from './ExtractAccompaniment';
  175. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  176. import { AudioFormatConverter } from './AudioFormatConverter';
  177. import { MergeAudio } from './MergeAudio';
  178. import { AIVoiceSeparation } from './AIVoiceSeparation';
  179. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  180. import { ChangeTone } from './ChangeTone';
  181. import {
  182. hdsEffect,
  183. HdsVisualComponent,
  184. HdsSceneController,
  185. HdsSceneType,
  186. HdsVisualComponentAttribute,
  187. } from '@kit.UIDesignKit';
  188. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  189. import { getFirstLetter } from '../Constants';
  190. import { audio } from '@kit.AudioKit';
  191. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  192. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  193. import { LyricCopySheet } from './LyricCopySheet';
  194. import {
  195. IsoArchiveAudioEntry,
  196. IsoExtractFailureDetail,
  197. IsoExtractProgressMessage,
  198. IsoExtractTaskResult,
  199. listIsoAudioEntriesTask,
  200. extractIsoAudioEntriesTask
  201. } from '../common/util/IsoArchiveUtil';
  202. const TAG = 'LocalMusic';
  203. const HICAR_LOG_TAG = 'HiCarWindow';
  204. const PREF_PLAY_COVER_SCALE_GUIDE_SHOWN = 'play_cover_scale_guide_show';
  205. function logHiCarWindow(message: string): void {
  206. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  207. }
  208. export interface WorkerMetadataPayload {
  209. originFilePath: string;
  210. originId?: string;
  211. bit_rate?: string;
  212. duration?: string;
  213. sampleRate?: string;
  214. mimeType?: string;
  215. md5Str?: string;
  216. videoSize?: number;
  217. size?: string;
  218. pixelMapPath?: string;
  219. artist?: string;
  220. album?: string;
  221. name?: string;
  222. lyricContent?: string;
  223. bits_per_raw_sample?: string;
  224. channels?: string;
  225. channel_layout?: string;
  226. start_time?: string;
  227. genre?: string;
  228. year?: string;
  229. probe_score?: number;
  230. track?: string;
  231. disc?: string;
  232. ALBUMARTIST?: string;
  233. COMPOSER?: string;
  234. COMMENT?: string;
  235. LYRICIST?: string;
  236. nb_streams?: number;
  237. nb_programs?: number;
  238. error?: string;
  239. }
  240. interface WorkerMessageScanDone {
  241. code: 101;
  242. data: Record<string, never>;
  243. }
  244. interface WorkerMessageMediaList {
  245. code: 102;
  246. data: Array<VideoItem>;
  247. totalCount: number;
  248. }
  249. interface WorkerMessageArtistList {
  250. code: 103;
  251. data1: Map<string, Array<VideoItem>>;
  252. data2: Array<VideoItem>;
  253. totalCount: number;
  254. }
  255. interface WorkerMessageAlbumList {
  256. code: 104;
  257. data1: Map<string, Array<VideoItem>>;
  258. data2: Array<VideoItem>;
  259. totalCount: number;
  260. }
  261. interface WorkerMessageMetadata {
  262. code: 105;
  263. data: WorkerMetadataPayload;
  264. }
  265. interface WorkerMessageEditResult {
  266. code: 106;
  267. data: WorkerEditMusicResult;
  268. }
  269. interface AlphaTaskItem {
  270. type: number;
  271. name?: string;
  272. pyStr?: string;
  273. fileName?: string;
  274. artist?: string;
  275. album?: string;
  276. }
  277. type LocalMusicWorkerMessage =
  278. WorkerMessageScanDone
  279. | WorkerMessageMediaList
  280. | WorkerMessageArtistList
  281. | WorkerMessageAlbumList
  282. | WorkerMessageMetadata
  283. | WorkerMessageEditResult;
  284. const DEFAULT_INDEX =
  285. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  286. 'X', 'Y', 'Z']
  287. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  288. // 元数据提取状态追踪
  289. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  290. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  291. // 定义接口
  292. interface HiCarAspectRatio {
  293. ratio: number;
  294. name: string;
  295. }
  296. interface GeneratedObjectLiteralInterface_1 {
  297. assetId: string;
  298. title: string;
  299. artist: string;
  300. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  301. mediaUri: string;
  302. // 该字段大写,音频'AUDIO',视频'VIDEO'
  303. mediaType: string;
  304. mediaSize: number;
  305. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  306. startPosition: number;
  307. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  308. duration: number;
  309. albumCoverUri: string;
  310. albumTitle: string;
  311. appName: string;
  312. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  313. drmScheme: string;
  314. }
  315. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  316. const ITEM_HEIGHT: number = 65; // 列表项中高度
  317. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  318. /**
  319. * 排序模式枚举
  320. * 定义各种排序方式的升序基准值
  321. */
  322. export enum SortMode {
  323. ByArtist = 0, // 按艺术家升序
  324. ByAlbum = 2, // 按专辑升序
  325. ByName = 4, // 按名称升序
  326. ByTime = 6, // 按时间升序
  327. ByAddTime = 7, // 按添加时间(只有降序)
  328. ByCount = 8, // 按数量升序
  329. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  330. }
  331. //功能强大的音乐播放器
  332. @Preview
  333. @Component
  334. export struct LocalMusic {
  335. @State default_layout:number = 0
  336. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  337. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  338. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  339. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  340. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  341. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  342. @State showFindLocation: boolean = true
  343. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  344. @State showSimple: boolean = true//开启沉浸模式
  345. @State isPaging: boolean = true;//是否分页加载机制
  346. @State isCoverRectangle: boolean = true;
  347. @State showZMIndex: boolean = false //是否右侧显示字母索引
  348. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  349. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  350. // 字母表
  351. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  352. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  353. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  354. @State selectAlphaBetIndex: number = 0
  355. @State isShowAlphaBet: boolean = false
  356. @State isScrolling: boolean = false
  357. @State isTouchingAlphaBet: boolean = false
  358. @State alphabetHeight: number = 0
  359. public enableShowAlphabet: boolean = true // 是否显示字母表
  360. private alphaBetHideTimer: number = 0
  361. private alphaBetRebuildTimer: number = 0
  362. private alphaBetDirty: boolean = false
  363. private alphaBetCacheKey: string = ''
  364. private alphaBetBuildVersion: number = 0
  365. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  366. //背景两侧流光控制器
  367. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  368. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  369. new HdsSceneController()
  370. .setSceneParams({
  371. backgroundMaskColors: [Color.Green, Color.Red],
  372. firstEdgeFlowLight: {
  373. startPos: 0,
  374. endPos: 0.5,
  375. color: Color.Red
  376. },
  377. secondEdgeFlowLight: {
  378. startPos: 0,
  379. endPos: -0.5,
  380. color: Color.Green
  381. }
  382. }) : undefined;
  383. //背景流光控制器
  384. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  385. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  386. new hdsEffect.ShaderEffectController():undefined;
  387. @State showAddSheet:boolean = false
  388. private loadingDialogId: string = ''
  389. private loadingProgressDialogId: string = ''
  390. @State isoAudioEntries: IsoArchiveAudioEntry[] = []
  391. @State selectedIsoAudioPaths: string[] = []
  392. @State isoSourceFileName: string = ''
  393. @State isIsoExtracting: boolean = false
  394. @State isoExtractProgress: number = 0
  395. @State isoExtractProgressText: string = ''
  396. @State isoExtractCurrentEntryName: string = ''
  397. private isoSourceFilePath: string = ''
  398. private isoExtractDestinationDir: string = ''
  399. private isoComponentId: number = 0
  400. private isoExtractProgressTimer: number = 0
  401. private isoExtractExpectedOutputPaths: Array<string> = []
  402. private isoExtractTotalBytes: number = 0
  403. private isoExtractDisplayedProgress: number = 0
  404. private isoExtractReceivedTaskProgress: boolean = false
  405. private isoExtractTask: taskpool.Task | undefined = undefined
  406. private isoExtractLastActivityTime: number = 0
  407. private readonly isoExtractStallTimeoutMs: number = 15000
  408. private isoExtractCanceled: boolean = false
  409. private isoExtractCancelMessage: string = ''
  410. searchController: SearchController = new SearchController()
  411. @State rightTopImage:Resource = $r('sys.symbol.sort')
  412. @State isEditAudio:boolean = false
  413. @State isExtractAcc:boolean = false
  414. @State isConverter:boolean = false
  415. @State isAIVoiceSeparation:boolean = false
  416. @State isExtractAudio:boolean = false
  417. @State isMergeAudio:boolean = false
  418. @State isCopyFileToDownLoad: boolean = false
  419. @State isChangeTone:boolean = false
  420. @State offHeight: number = 75
  421. @State currentSongList: Array<VideoItem> = []//当前歌单
  422. @Consume currentSongListName:string //当前歌单名称
  423. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  424. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  425. @State isRefreshing: boolean = false;
  426. @State maxRefreshingHeight: number = 100.0;
  427. @State isPlayerLoading: boolean = false; // 播放器加载状态
  428. private contentNode?: ComponentContent<Object> = undefined;
  429. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  430. @State ratioL: number = 1;
  431. @State mediaKuCount: number = 0;
  432. @State albumCount: number = 0;
  433. @State artistCount: number = 0;
  434. @State fastForwardSeconds: string = '10'
  435. @State isShowBackFast: boolean = true//快进快退按钮
  436. @State isCanAuto:boolean = true
  437. @State opacityValueImage: number = 1;
  438. @State tipPopup:boolean = false
  439. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  440. @Consume mType: number;
  441. @StorageProp('themeColor') themeColor: string =
  442. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  443. themeMode: number = 0;
  444. @State titleName: string = '文件夹'//首页就是文件夹
  445. @State textStr: string = ''
  446. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  447. // private download_path: string = '';
  448. @Consume rootPath: string //音频根目录
  449. @Consume currentPath: string
  450. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  451. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  452. @State lockPath: string = ''
  453. @State favPath: string = ''
  454. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  455. @State historyPath: string = ''
  456. @State historyList: Array<VideoItem> = []
  457. @Consume isHistory: boolean
  458. static readonly HISTORY_MUSIC: string = 'music_historyList';
  459. private table: MediaTable = new MediaTable(getContext(this))
  460. private playlistTable: PlaylistTable | null = null
  461. private deletionWatcher: FileDeletionWatcher | null = null
  462. @State allPlaylists: Playlist[] = []
  463. @State isZero: boolean = false
  464. @State fileList: Array<string> = []
  465. @State dirList: Array<VideoItem> = []
  466. @Consume videoLocalList:VideoItem[]
  467. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  468. @State listRefreshKey: number = 0
  469. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  470. @State artistList: Array<VideoItem> = []; //艺术家文件
  471. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  472. @State artistSongCountMap: Map<string, number> = new Map();
  473. @State albumList: Array<VideoItem> = []; //专辑文件
  474. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  475. @State albumSongCountMap: Map<string, number> = new Map();
  476. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  477. @State imageOpacities: number[] = [];
  478. @Consume isCanBack: boolean
  479. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  480. @State showSingleLyric: boolean = false
  481. @State sortType: number = 4 //默认排序方式
  482. @State isShowSimi: boolean = false //是否显示私密音频
  483. @State isShowFAV: boolean = true //是否显示我的收藏
  484. @State isShowTitleBar: boolean = true //是否显示分类导航条
  485. @State isShowAllBar: boolean = true //是否显示播放全部条
  486. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  487. @State isEnableWordByWordLyric: boolean = true //是否开启逐字歌词
  488. @State isShowHistory: boolean = true //是否显示最近播放
  489. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  490. @State isGridMusic: boolean = false //是否网格布局
  491. @State isCircleBtn: boolean = false //是否圆形播放按钮
  492. @State twoFingerType: number = 3 //双支放大缩小的类型
  493. @State isScrollHide: boolean = false //是否滚动隐藏
  494. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  495. @State isStartAutoPlay: boolean = false //启动后自动播放
  496. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  497. @State isShowHeader: boolean = true
  498. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  499. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  500. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  501. @State rectangleCoverScale: number = 1
  502. @State rectangleCoverPinchValue: number = 1
  503. @State isSwipe: boolean = false //listItem的左滑开关
  504. @State openSkipSongAnimate: boolean = true//切歌动画效果
  505. @State isPlayPageSwipeNext: boolean = true // 播放页上滑切歌
  506. @State isLightText: boolean = true //是否开启歌词发光
  507. @State customizeBgPath: string | undefined = '';
  508. @State isDarkMode: boolean = false
  509. @State lyricTextWeight: number = 400
  510. @State lyricTextWeightPip: number = 400
  511. @State currentSwiperIndex: number = 0
  512. @State blurValue: number = 0 //背景模糊
  513. @State bgBrightness: number = 0 //背景亮度
  514. private listScroller: ListScroller = new ListScroller()
  515. private playListScroller: Scroller = new Scroller()
  516. @State isOneKeyTags:boolean = false
  517. @State isFixMessy:boolean = false
  518. // 分页相关状态
  519. @State private currentPage: number = 0 // 当前页码
  520. @State private pageSize: number = 53 // 每页数量
  521. @State private totalCount: number = 0 // 总记录数
  522. @State private hasMoreData: boolean = true // 是否还有更多数据
  523. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  524. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  525. private pageHasMoreCache: Map<number, boolean> = new Map()
  526. private pageTotalCountCache: Map<number, number> = new Map()
  527. private prefetchingPages: Set<number> = new Set()
  528. private preloadStartRatio: number = 0.18
  529. private appendStartRatio: number = 0.30
  530. private earlyAppendReserveCount: number = 28
  531. private lastScrollTriggerPage: number = -1
  532. private lastVisibleEndIndex: number = -1
  533. private isPagingTransition: boolean = false
  534. private pagingScheduleTimer: number = 0
  535. private listScrollAlphaCheckAt: number = 0
  536. private listScrollPagingCheckAt: number = 0
  537. private listScrollLastAlphaStart: number = -1
  538. private listScrollLastPagingEnd: number = -1
  539. private gridScrollPagingCheckAt: number = 0
  540. private gridScrollLastPagingEnd: number = -1
  541. private waterScrollPagingCheckAt: number = 0
  542. private waterScrollLastPagingEnd: number = -1
  543. private gridWaterScrollIdleTimer: number = 0
  544. private gridWaterLastActiveTs: number = 0
  545. private listUpdateTimer: number = 0
  546. private listUpdateVersion: number = 0
  547. private detailBackTransitioning: boolean = false
  548. private mediaLibraryEnterTs: number = 0
  549. private mediaLibraryWarmupPrefetchTimer: number = 0
  550. private listVisibleStart: number = -1
  551. private listVisibleEnd: number = -1
  552. private listThumbWarmupCheckAt: number = 0
  553. private listThumbWarmupStart: number = -1
  554. private listThumbWarmupEnd: number = -1
  555. private gridThumbWarmupCheckAt: number = 0
  556. private gridThumbWarmupStart: number = -1
  557. private gridThumbWarmupEnd: number = -1
  558. private waterThumbWarmupCheckAt: number = 0
  559. private waterThumbWarmupStart: number = -1
  560. private waterThumbWarmupEnd: number = -1
  561. private gridVisibleStart: number = -1
  562. private gridVisibleEnd: number = -1
  563. private waterVisibleStart: number = -1
  564. private waterVisibleEnd: number = -1
  565. private titleBarToggleMinDelta: number = 12
  566. private titleBarLastCheckTs: number = 0
  567. @State private coverThumbVersion: number = 0
  568. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  569. private coverThumbCacheReady: boolean = false
  570. private pendingCoverThumbRefresh: boolean = false
  571. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  572. private isHydratingPlayList: boolean = false
  573. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  574. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  575. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  576. @StorageProp('windowWidth') windowWidth: number = 0;
  577. @StorageProp('windowHeight') windowHeight: number = 0;
  578. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  579. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  580. private UNKONWN:string = '';
  581. private listArea: Area = {
  582. width: 0,
  583. height: 0,
  584. position: {},
  585. globalPosition: {}
  586. }
  587. @State private pointLightOptions: hdsEffect.PointLightOptions | undefined = undefined
  588. @State private activePointLightItemKey: string = ''
  589. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  590. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  591. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  592. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  593. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  594. private activePlaybackMemoryKey: string = '';
  595. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  596. private remoteRestoreSeekToken: number = 0;
  597. // 本次是否需要先seek到记忆点再开始播放
  598. private waitInitialSeekBeforeStart: boolean = false;
  599. // 本次播放记忆点(毫秒)
  600. private pendingMemorySeekPosition: number = 0;
  601. // 记忆播放seek兜底,避免一直转圈
  602. private initialSeekGuardTimer: number = 0;
  603. private readonly initialSeekGuardTimeoutMs: number = 2000;
  604. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  605. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  606. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  607. private lastSeekRequestMs: number = -1;
  608. private lastSeekSource: string = '';
  609. private seekTraceUntilTs: number = 0;
  610. private lastSeekTraceLogTs: number = 0;
  611. private readonly seekTraceLogWindowMs: number = 4000;
  612. private readonly seekTraceLogIntervalMs: number = 400;
  613. //瀑布流的列数横竖屏动态切换
  614. onIsLandscapeChange() {
  615. if(this.isLandscape){
  616. this.columns = 4
  617. }else{
  618. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  619. }
  620. }
  621. onColorModeChange() {
  622. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  623. }
  624. //点击某个歌单id发生变化的时候回调
  625. onIDChange(){
  626. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  627. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  628. if(this.modeType==4){
  629. this.titleName = this.currentSongListName
  630. this.rightTopImage = $r('sys.symbol.sort')
  631. //获取缓存
  632. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  633. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  634. if(StrUtil.isNotEmpty(cacheSongs)){
  635. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  636. this.updateListData(this.currentSongList, true)
  637. }
  638. this.doSongListTask()//获取歌单信息
  639. }
  640. }
  641. async doSongListTask() {
  642. // 初始化歌单数据库
  643. const playlistTable = new PlaylistTable(this.context);
  644. // 查询歌单中的所有歌曲
  645. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  646. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  647. if (ArrayUtil.isEmpty(playlistSongs)) {
  648. this.updateListData([], true)
  649. // 清空歌单路径列表
  650. this.currentPlaylistSongFilePaths = [];
  651. } else {
  652. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  653. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  654. this.updateListData(this.currentSongList, true)
  655. // 保存歌单的歌曲路径列表,用于随机播放
  656. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  657. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  658. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  659. // 只保存前100条记录到缓存中
  660. let canceList = this.currentSongList.slice(0, 100);
  661. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  662. JSON.stringify(canceList))
  663. } else {
  664. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  665. }
  666. }
  667. this.isRefreshing = false
  668. }
  669. async onModeChange(preserveList: boolean = false): Promise<void> {
  670. this.isFavMusic = false
  671. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  672. this.refreshDirVisibilitySettings()
  673. if (this.mediaLibraryWarmupPrefetchTimer) {
  674. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  675. this.mediaLibraryWarmupPrefetchTimer = 0
  676. }
  677. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  678. switch (this.modeType) {
  679. case 0:
  680. // 首页模式已在 resetAndLoadFirstPage 中处理
  681. // 切换模式时加载对应的排序类型
  682. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  683. this.sortType = this.loadSortTypeForCurrentMode()
  684. this.mediaLibraryEnterTs = 0
  685. break
  686. case 1:
  687. this.rightTopImage = $r('sys.symbol.sort')
  688. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  689. // 切换模式时加载对应的排序类型
  690. this.sortType = this.loadSortTypeForCurrentMode()
  691. this.mediaLibraryEnterTs = Date.now()
  692. break
  693. case 2:
  694. this.rightTopImage = $r('sys.symbol.sort')
  695. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  696. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  697. this.sortType = this.loadSortTypeForCurrentMode()
  698. this.mediaLibraryEnterTs = 0
  699. break
  700. case 3:
  701. this.rightTopImage = $r('sys.symbol.sort')
  702. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  703. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  704. this.sortType = this.loadSortTypeForCurrentMode()
  705. this.mediaLibraryEnterTs = 0
  706. break
  707. }
  708. // 模式切换时重置分页状态并加载第一页
  709. await this.resetAndLoadFirstPage(!preserveList);
  710. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  711. }
  712. // @Consume currentSong: VideoItem | undefined;
  713. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  714. // @StorageLink('isPlay') isPlay: boolean = false;
  715. @Consume isShowPlay: boolean ;
  716. @State isShowCoverScaleGuide: boolean = false
  717. @StorageLink('songList') songList: Array<VideoItem> = [];
  718. @State translateY: number = 0;
  719. @State isShowSheet: boolean = false;
  720. @State isShowSheetView: boolean = false;
  721. @State isShowLyricCopySheet: boolean = false;
  722. @State lyricCopyLines: string[] = [];
  723. @State lyricSelectedIndexes: number[] = [];
  724. @State isShowTimeCloseView: boolean = false;
  725. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  726. @StorageLink('currIndex') curIndex: number = 0;
  727. @Consume isShowDrawer: boolean;
  728. @Consume offsetX: number;
  729. @State isFac: boolean = false;
  730. @State favList: Array<VideoItem> = []
  731. @Consume isFavMusic: boolean
  732. @State isClickedPLayAll: boolean = false;
  733. private scrollerForlist: ListScroller = new ListScroller();
  734. private knockController: KnockController | undefined = undefined;
  735. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  736. // 缓存机制
  737. private cache: Map<string, Array<VideoItem>> = new Map();
  738. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  739. // 持久化缓存
  740. private async saveCacheToStorage() {
  741. const cacheArray = Array.from(this.cache.entries());
  742. const stringCacheArray = Array.from(this.stringCache.entries());
  743. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  744. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  745. }
  746. // 载入缓存
  747. private async loadCacheFromStorage() {
  748. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  749. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  750. if (cacheString) {
  751. const parsedCache: Object | null = JSON.parse(cacheString);
  752. if (parsedCache && Array.isArray(parsedCache)) {
  753. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  754. this.cache = new Map(cacheArray);
  755. }
  756. }
  757. if (stringCacheString) {
  758. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  759. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  760. const stringCacheArray: [string, string][] = parsedStringCache;
  761. this.stringCache = new Map(stringCacheArray);
  762. }
  763. }
  764. }
  765. // 查找缓存
  766. private findCache(key: string): Array<VideoItem> | undefined {
  767. return this.cache.get(key);
  768. }
  769. // 查找字符串缓存
  770. private findStringCache(key: string): string | undefined {
  771. return this.stringCache.get(key);
  772. }
  773. // 添加缓存
  774. private addCache(key: string, value: Array<VideoItem>) {
  775. this.cache.set(key, value);
  776. }
  777. // 添加字符串缓存
  778. private addStringCache(key: string, value: string) {
  779. this.stringCache.set(key, value);
  780. }
  781. // 删除缓存
  782. private deleteCache(key: string) {
  783. this.cache.delete(key);
  784. this.saveCacheToStorage()
  785. }
  786. // 删除字符串缓存
  787. private deleteStringCache(key: string) {
  788. this.stringCache.delete(key);
  789. }
  790. // 多选机制
  791. @State selectedFiles: Array<VideoItem> = [];
  792. @Consume isMultiSelect: boolean;
  793. @State isAllSelected: boolean = false;
  794. @State appName: string = ''
  795. @State isHasDir: boolean = false
  796. @State packName: string = ''
  797. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  798. doSwipBack() {
  799. if(this.isSearchMode){
  800. console.info('onecold doSwipBack = ' +this.isSearchMode)
  801. this.isSearchMode = false
  802. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  803. this.searchText = ''
  804. this.getSortedFiles(this.currentPath)
  805. return
  806. }
  807. this.onSearchInput('')
  808. return
  809. }
  810. this.isZero = false
  811. if (this.modeType !== 0 && this.isCanBack) {
  812. if (this.detailBackTransitioning) {
  813. return
  814. }
  815. this.detailBackTransitioning = true
  816. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  817. this.isCanBack = false
  818. this.rightTopImage = $r('sys.symbol.sort')
  819. if (this.modeType == 2) {
  820. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  821. if (ArrayUtil.isNotEmpty(this.artistList)) {
  822. this.updateListData(this.artistList, true, true)
  823. }
  824. } else if (this.modeType == 3) {
  825. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  826. if (ArrayUtil.isNotEmpty(this.albumList)) {
  827. this.updateListData(this.albumList, true, true)
  828. }
  829. }
  830. // 返回列表页时保留当前列表,避免先清空导致闪现
  831. void this.onModeChange(true).then(() => {
  832. if (this.modeType == 2) {
  833. if (this.isGridMusic||this.twoFingerType==4) {
  834. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  835. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  836. if(this.twoFingerType==4){
  837. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  838. }else{
  839. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  840. }
  841. } else {
  842. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  843. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  844. }
  845. } else if (this.modeType == 3) {
  846. if (this.isGridMusic||this.twoFingerType==4) {
  847. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  848. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  849. if(this.twoFingerType==4){
  850. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  851. }else{
  852. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  853. }
  854. } else {
  855. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  856. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  857. }
  858. }
  859. this.detailBackTransitioning = false
  860. }).catch((error: Error) => {
  861. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  862. this.detailBackTransitioning = false
  863. })
  864. return
  865. }
  866. this.mediaLibraryEnterTs = 0
  867. if (this.isHistory || this.isFavMusic) {
  868. this.isHistory = false
  869. this.getSortedFiles(this.currentPath)
  870. return
  871. }
  872. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  873. animateTo({ duration: 555 }, () => {
  874. // 动画闭包内控制Image组件的出现和消失
  875. this.isShowDrawer = !this.isShowDrawer
  876. this.offsetX = 0
  877. })
  878. return
  879. }
  880. //返回上一级歌单的滚动位置
  881. setTimeout(() => {
  882. if (this.modeType == 0) {
  883. if (this.isGridMusic||this.twoFingerType==4) {
  884. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  885. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  886. if(this.twoFingerType==4){
  887. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  888. }else{
  889. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  890. }
  891. } else {
  892. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  893. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  894. }
  895. }
  896. }, 100)
  897. this.currentPath = Utility.getParentDirectory(this.currentPath)
  898. Logger.info('this.currentPath2 = ' + this.currentPath)
  899. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  900. }
  901. private triggerSwipeBackWithAnimation(): void {
  902. animateTo({ duration: 555 }, () => {
  903. this.doSwipBack()
  904. })
  905. }
  906. // 组件生命周期
  907. aboutToAppear() {
  908. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  909. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  910. this.updateListData(this.videoLocalList)
  911. }
  912. // 初始化 PlaylistTable
  913. this.playlistTable = new PlaylistTable(getContext(this))
  914. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  915. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  916. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  917. this.tipPopup = !this.tipPopup
  918. PreferencesUtil.putSync('isFirstTiped',false)
  919. }
  920. this.loadSearchHistory()
  921. this.initSetting()
  922. this.syncEqualizerUi();
  923. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  924. Utility.getAppName(getContext(this)).then((appName: string) => {
  925. this.appName = appName
  926. })
  927. this.packName = AppUtil.getBundleName()
  928. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  929. this.loadCacheFromStorage(); // 加载文件夹缓存
  930. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  931. this.initLoadCache()
  932. this.mkDownLoadDir()
  933. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  934. // 监听广播事件(打开其他应用处理)
  935. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  936. this.saveVideoDatas([eventData.data?.message], true)
  937. });
  938. //侧滑广播接收时间
  939. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  940. // 监听广播事件(手势返回处理)
  941. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  942. this.triggerSwipeBackWithAnimation()
  943. });
  944. //ScanFilePage广播接收时间
  945. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  946. // 监听ScanFilePage广播事件(更新数据库)
  947. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  948. this.doUpdateData()
  949. });
  950. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  951. emitter.on(eventEqualizerChanged, () => {
  952. this.syncEqualizerUi();
  953. if (this.mIjkMediaPlayer) {
  954. const equalizerManager = EqualizerManager.getInstance();
  955. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  956. this.markEqualizerApplied();
  957. }
  958. });
  959. // 监听歌单播放请求事件
  960. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  961. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  962. const data = eventData.data as Record<string, Object>
  963. if (!data) {
  964. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  965. return
  966. }
  967. // 检查歌单播放数据结构
  968. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  969. const playlistData = new PlaylistPlayRequest(
  970. data.playlistId as string,
  971. data.playlistName as string,
  972. data.songCount as number,
  973. data.startIndex as number,
  974. data.songFilePaths as string[],
  975. data.isJump as boolean,
  976. data.playType as number
  977. )
  978. await this.dispatchPlaylistPlayRequest(playlistData)
  979. return
  980. }
  981. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  982. });
  983. Promise.resolve().then(async (): Promise<void> => {
  984. const pendingPlaylistRequest = consumePendingPlaylistPlay();
  985. if (!pendingPlaylistRequest) {
  986. return;
  987. }
  988. Logger.info(TAG,
  989. `检测到待处理播放请求,准备补偿执行: ${pendingPlaylistRequest.playlistName}, startIndex=${pendingPlaylistRequest.startIndex}`);
  990. await this.dispatchPlaylistPlayRequest(pendingPlaylistRequest);
  991. });
  992. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  993. // 监听广播事件(通用设置配置更新)
  994. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  995. if(this.modeType ==4){
  996. this.doSongListTask()//获取歌单信息
  997. }
  998. });
  999. let eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  1000. emitter.on(eventQueueRefresh, () => {
  1001. this.syncWebdavQueueWithoutRestart();
  1002. });
  1003. let eventOpenLocalSpecialList: emitter.InnerEvent = { eventId: EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST }
  1004. emitter.on(eventOpenLocalSpecialList, (eventData: emitter.EventData) => {
  1005. const data = eventData.data as Record<string, Object>
  1006. const target = data?.target as string
  1007. this.openSpecialLocalList(target)
  1008. });
  1009. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1010. // 监听广播事件(通用设置配置更新)
  1011. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1012. this.initSetting()
  1013. });
  1014. // 监听 WebDAV 元数据更新事件
  1015. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  1016. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  1017. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  1018. if (!payloads || payloads.length === 0) {
  1019. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  1020. return;
  1021. }
  1022. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  1023. // 处理每个元数据更新
  1024. for (let i = 0; i < payloads.length; i++) {
  1025. const payload = payloads[i];
  1026. if (!payload || !payload.filePath) {
  1027. continue;
  1028. }
  1029. // 重要:只更新当前正在播放的歌曲
  1030. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  1031. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  1032. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  1033. if (payload.name && payload.name.length > 0) {
  1034. this.name = payload.name;
  1035. if (this.currentSong) {
  1036. this.currentSong.name = payload.name;
  1037. }
  1038. }
  1039. if (payload.artist && payload.artist.length > 0) {
  1040. this.artist = payload.artist;
  1041. if (this.currentSong) {
  1042. this.currentSong.artist = payload.artist;
  1043. }
  1044. }
  1045. if (this.currentSong) {
  1046. const coverMutated = mergeCoverWithPriority(this.currentSong, payload.pixelMapPath,
  1047. payload.isCustomCover ?? 0);
  1048. if (coverMutated && this.currentSong.pixelMapPath) {
  1049. this.cover = this.currentSong.pixelMapPath;
  1050. Logger.info(TAG, `LocalMusic: 封面已更新: ${this.currentSong.pixelMapPath}`);
  1051. }
  1052. if (payload.md5Str && payload.md5Str.length > 0) {
  1053. this.currentSong.md5Str = payload.md5Str;
  1054. }
  1055. }
  1056. // 同步更新 AppStorage
  1057. AppStorage.setOrCreate('currentSong', this.currentSong);
  1058. } else {
  1059. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  1060. }
  1061. }
  1062. });
  1063. // 监听广播事件(通用设置配置更新)
  1064. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1065. this.doChangeSetting()
  1066. });
  1067. let event: Callback<InterruptEvent> = (event) => {
  1068. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1069. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1070. this.savePlaybackPosition()
  1071. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1072. this.pause();
  1073. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1074. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1075. this.startPlayOrResumePlay();
  1076. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1077. console.info(`heanup onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1078. if(!this.isSameTimePlay){
  1079. this.stop();
  1080. }
  1081. }
  1082. }
  1083. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1084. // 音频设备断连回调处理比如蓝牙耳机断开
  1085. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1086. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1087. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1088. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1089. console.info('heanup onecold 音频设备断开连接, 暂停播放')
  1090. this.pause();
  1091. }
  1092. }
  1093. // 订阅音频设备断开和连接事件
  1094. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1095. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1096. // 监听广播事件(hicar断开暂停播放)
  1097. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1098. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1099. this.pause();
  1100. });
  1101. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1102. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1103. // 监听蓝牙音响断开音频设备状态变化。
  1104. audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1105. console.info(`onecold device change type : ${deviceChanged.type}`); // 设备连接状态变化,0为连接,1为断开连接。
  1106. console.info(`onecold device descriptor size : ${deviceChanged.deviceDescriptors.length}`);
  1107. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole}`); // 设备角色。
  1108. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType}`);
  1109. // 蓝牙设备类型为8
  1110. const isBluetooth = deviceChanged.deviceDescriptors[0].deviceType === 8;
  1111. if (isBluetooth) {
  1112. if (deviceChanged.type === 0) {
  1113. // 蓝牙连接
  1114. this.isBluetoothConnected = true;
  1115. console.info('onecold 蓝牙设备已连接');
  1116. } else if (deviceChanged.type === 1) {
  1117. // 蓝牙断开
  1118. this.isBluetoothConnected = false;
  1119. this.lastBluetoothLyricLine = '';
  1120. console.info('onecold 蓝牙设备已断开');
  1121. // 恢复原始元数据
  1122. if (this.currentSong) {
  1123. this.avSessionController.restoreOriginalMetadata(
  1124. this.currentSong.name || '',
  1125. this.currentSong.artist || ''
  1126. );
  1127. }
  1128. // 蓝牙断开暂停
  1129. if (this.bluetoothDisconnectPause && deviceChanged.deviceDescriptors[0].deviceRole === 2) {
  1130. console.info('heanup onecold 蓝牙音响断开, 暂停播放');
  1131. this.pause();
  1132. }
  1133. }
  1134. }
  1135. });
  1136. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1137. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1138. console.info('onecold device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1139. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1140. if(deviceChanged.type==1&&
  1141. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1142. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1143. console.info('heanup onecold 有线耳机断开, 暂停播放')
  1144. this.pause();
  1145. }
  1146. });
  1147. this.makeWorker()
  1148. //折叠屏的屏幕显示模式变化
  1149. display.on('foldDisplayModeChange', (data) => {
  1150. this.doChangeBarHeight()
  1151. });
  1152. display.on('foldStatusChange', (data) => {
  1153. Logger.info('onecold foldStatusChange ')
  1154. });
  1155. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1156. this.rectangleCoverScale = PreferencesUtil.getNumberSync(SettingPage.RECTANGLE_COVER_SCALE, 1)
  1157. if (this.rectangleCoverScale < 0.7 || this.rectangleCoverScale > 1.4) {
  1158. this.rectangleCoverScale = 1
  1159. }
  1160. // 读取 themeMode 并同步 currentColorMode
  1161. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1162. this.applyThemeMode(this.themeMode)
  1163. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1164. AppStorage.setOrCreate('themeColor', themeColor);
  1165. this.themeColor = themeColor;
  1166. this.doChangeSetting()
  1167. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1168. LogUtil.info('onecold windowSizeChange')
  1169. this.doChangeBarHeight()
  1170. let viewWidth = px2vp(size.width);
  1171. let viewHeight = px2vp(size.height);
  1172. if(this.isPhoneLan()){
  1173. this.is_auto_hide_progress = false
  1174. if(this.isHiCar()){
  1175. return
  1176. }
  1177. setTimeout(() => {
  1178. this.is_auto_hide_progress = true
  1179. }, 6000)
  1180. }else{
  1181. this.startAutoHide()
  1182. }
  1183. });
  1184. this.eventHub.on('onStateChange', (fg: boolean) => {
  1185. this.isAppForeground = fg;
  1186. if (fg && this.curState === 'STARTED') {
  1187. this.stopPip();
  1188. this.syncLyricPositionNow();
  1189. }
  1190. });
  1191. //NewIndex的博空调收到eventHub消息控制播放
  1192. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1193. if (ArrayUtil.isNotEmpty(this.songList)) {
  1194. this.playOrPause();
  1195. } else {
  1196. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1197. }
  1198. });
  1199. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1200. if (ArrayUtil.isNotEmpty(this.songList)) {
  1201. this.playPrevious();
  1202. } else {
  1203. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1204. }
  1205. });
  1206. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1207. if (ArrayUtil.isNotEmpty(this.songList)) {
  1208. this.playNext();
  1209. } else {
  1210. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1211. }
  1212. });
  1213. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1214. this.showPlayerView();
  1215. });
  1216. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1217. this.openPlayList();
  1218. });
  1219. }
  1220. //载入媒体库,艺术家,专辑等缓存
  1221. initLoadCache(){
  1222. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1223. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1224. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1225. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1226. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1227. if(ArrayUtil.isNotEmpty(cachedList)){
  1228. this.mediaKuList = cachedList
  1229. if(this.modeType==1){
  1230. this.updateListData(this.mediaKuList)
  1231. }
  1232. }
  1233. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1234. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1235. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1236. this.artistList = artistCachedList
  1237. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1238. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1239. this.artistMap = new Map(parsedArray);
  1240. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1241. if(this.modeType==2){
  1242. this.updateListData(this.artistList)
  1243. }
  1244. }
  1245. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1246. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1247. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1248. this.albumList = albumCachedList
  1249. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1250. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1251. this.albumMap = new Map(parsedArray);
  1252. if(this.modeType==3){
  1253. this.updateListData(this.albumList)
  1254. }
  1255. }
  1256. }
  1257. startAutoHide() {
  1258. if(this.isHiCar()){
  1259. return
  1260. }
  1261. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1262. console.info('onecold startAutoHide')
  1263. this.is_auto_hide_progress = false
  1264. setTimeout(() => {
  1265. this.is_auto_hide_progress = true
  1266. }, 6000)
  1267. }
  1268. }
  1269. applyThemeMode(mode: number) {
  1270. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1271. if (mode === 1) {
  1272. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1273. } else if (mode === 2) {
  1274. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1275. }
  1276. AppStorage.setOrCreate('currentColorMode', colorMode)
  1277. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1278. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1279. AppStorage.setOrCreate('themeMode', mode)
  1280. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1281. // 只有强制浅色/深色时才主动设置
  1282. const context = getContext(this) as common.UIAbilityContext
  1283. context.getApplicationContext().setColorMode(colorMode)
  1284. }
  1285. initSetting() {
  1286. this.default_layout = PreferencesUtil.getNumberSync('default_layout', 0)
  1287. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1288. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1289. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1290. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1291. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1292. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1293. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1294. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1295. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1296. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1297. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1298. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1299. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1300. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1301. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1302. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1303. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  1304. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1305. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1306. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1307. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1308. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1309. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1310. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1311. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1312. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1313. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  1314. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1315. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1316. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1317. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1318. this.isEnableWordByWordLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, true)
  1319. this.isLightText = PreferencesUtil.getBooleanSync(SettingPage.IS_LIGHT_TEXT, true)
  1320. this.syncWordByWordLyricMode()
  1321. this.syncLyricLightTextMode()
  1322. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1323. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1324. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1325. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1326. const volumeBoostPercent = PreferencesUtil.getNumberSync(this.volumeBoostPreferenceKey, 0)
  1327. this.volumeBoostPercent = Math.max(0, Math.min(volumeBoostPercent, this.volumeBoostMaxPercent))
  1328. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1329. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1330. this.isPlayPageSwipeNext = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYPAGE_SWIPE_NEXT, true)
  1331. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1332. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1333. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1334. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1335. this.refreshDirVisibilitySettings()
  1336. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1337. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1338. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1339. let audioManager = audio.getAudioManager();
  1340. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1341. if(this.isSameTimePlay){
  1342. //与其他应用同时播放,关键代码
  1343. let strategy: audio.AudioSessionStrategy = {
  1344. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1345. };
  1346. audioSessionManager.activateAudioSession(strategy).then(() => {
  1347. console.info('onecold Succeeded in doing activateAudioSession.');
  1348. }).catch((err: BusinessError) => {
  1349. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1350. });
  1351. }else{
  1352. let isActivated = audioSessionManager.isAudioSessionActivated();
  1353. if(isActivated){
  1354. audioSessionManager.deactivateAudioSession().then(() => {
  1355. console.info('Succeeded in doing deactivateAudioSession.');
  1356. }).catch((err: BusinessError) => {
  1357. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1358. });
  1359. }
  1360. }
  1361. //如果是hicar连接状态,这些都是false
  1362. if(this.isHiCar()){
  1363. this.autoHideTitle = false
  1364. this.isCoverRectangle= true
  1365. this.columns=4
  1366. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1367. {
  1368. this.isGridMusic= false//用list不用网格
  1369. this.isCoverTopBig = false
  1370. }
  1371. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1372. }
  1373. if (this.isSavePlayMode) {
  1374. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1375. }
  1376. }
  1377. doChangeSetting() {
  1378. this.initSetting()
  1379. this.deleteCache(this.currentPath)
  1380. if (this.modeType === 0) {
  1381. this.getSortedFiles(this.currentPath)
  1382. }
  1383. }
  1384. doChangeBarHeight() {
  1385. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1386. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1387. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1388. this.setBarHeightNormal()
  1389. }
  1390. }
  1391. onPageShow() {
  1392. this.knockController?.immersiveListening();
  1393. app.setImageCacheCount(100);
  1394. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1395. app.setImageRawDataCacheSize(104857600);
  1396. this.refreshDirVisibilitySettings();
  1397. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1398. }
  1399. //开启线程查看各个数据库
  1400. makeWorker() {
  1401. setTimeout(() => {
  1402. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1403. // ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1404. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1405. workerInstance.postMessage({
  1406. code: 1,
  1407. data1: this.context,
  1408. data2: this.rootPath,
  1409. data3: this.lockPath,
  1410. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1411. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1412. });
  1413. PreferencesUtil.putSync('isFirstApp', false)
  1414. } else {
  1415. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1416. workerInstance.postMessage({ code: 3, data: this.context });
  1417. workerInstance.postMessage({ code: 4, data: this.context });
  1418. this.getHistoryList(false)
  1419. }
  1420. }, 1000)
  1421. workerInstance.onmessage = (e: MessageEvents): void => {
  1422. const message = e.data as LocalMusicWorkerMessage;
  1423. switch (message.code) {
  1424. case 101: //第一次扫描文件夹入库
  1425. ToastUtil.showToast('刷新同步数据库成功!')
  1426. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1427. this.doAllUpdateData()
  1428. break;
  1429. case 102: //查询媒体库列表
  1430. this.isRefreshing = false
  1431. this.mediaKuList = message.data // 只包含前100条
  1432. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1433. this.mediaKuCount = mediaTotalCount;
  1434. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1435. Utility.doSortListAscending(this.mediaKuList)
  1436. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1437. // 媒体库模式下重新加载第一页(分页查询)
  1438. if (this.modeType === 1) {
  1439. this.resetAndLoadFirstPage();
  1440. }
  1441. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1442. // 只保存前100条记录到缓存中
  1443. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1444. break;
  1445. case 103: //收到查询艺术家列表
  1446. this.isRefreshing = false
  1447. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1448. this.artistList = message.data2; // 只包含前100个艺术家
  1449. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1450. this.artistCount = artistTotalCount;
  1451. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1452. this.artistMap.forEach((songs, artist) => {
  1453. nextArtistCountMap.set(artist, songs.length);
  1454. });
  1455. this.artistSongCountMap = nextArtistCountMap;
  1456. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1457. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1458. // 艺术家模式下重新加载第一页(分页查询)
  1459. if (this.modeType === 2) {
  1460. this.resetAndLoadFirstPage();
  1461. }
  1462. // 保存前100条艺术家列表
  1463. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1464. // 保存前60条艺术家的歌曲Map
  1465. const sortedEntries = Array.from(this.artistMap.entries());
  1466. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1467. break;
  1468. case 104: //收到查询专辑列表
  1469. this.isRefreshing = false
  1470. this.albumMap = message.data1;
  1471. this.albumList = message.data2
  1472. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1473. this.albumCount = albumTotalCount;
  1474. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1475. this.albumMap.forEach((songs, album) => {
  1476. nextAlbumCountMap.set(album, songs.length);
  1477. });
  1478. this.albumSongCountMap = nextAlbumCountMap;
  1479. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1480. // 专辑模式下重新加载第一页(分页查询)
  1481. if (this.modeType === 3) {
  1482. this.resetAndLoadFirstPage();
  1483. }
  1484. //查询完毕在启动是否自动播放
  1485. if (this.isStartAutoPlay&&this.isCanAuto) {
  1486. this.isCanAuto = false
  1487. console.info('onecold startPlayOrResumePlay 757')
  1488. this.startPlayOrResumePlay()
  1489. }
  1490. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1491. // 保存前100条专辑列表(Worker已经只发送了100条)
  1492. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1493. // 保存前60条专辑Map(Worker已经只发送了60条)
  1494. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1495. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1496. break;
  1497. case 105: // 缓存完成后返回的元数据
  1498. this.handleWorkerMetadataPayload(message.data);
  1499. break;
  1500. case 106: // 编辑音乐元数据和封面完成
  1501. this.handleEditMusicResult(message.data);
  1502. break;
  1503. }
  1504. };
  1505. // 在调用terminate后,执行onexit
  1506. workerInstance.onexit = (code) => {
  1507. metadataExtractionInFlight.clear();
  1508. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1509. }
  1510. workerInstance.onerror = (err: ErrorEvent) => {
  1511. metadataExtractionInFlight.clear();
  1512. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1513. }
  1514. }
  1515. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1516. if (!payload || !payload.originFilePath) {
  1517. return;
  1518. }
  1519. metadataExtractionInFlight.delete(payload.originFilePath);
  1520. if (payload.error) {
  1521. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1522. return;
  1523. }
  1524. this.applyMetadataToCollections(payload.originFilePath, payload);
  1525. }
  1526. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1527. const targets: Array<VideoItem> = [];
  1528. let mainListUpdated = false;
  1529. let playlistUpdated = false;
  1530. if (this.currentSong && this.currentSong.filePath === filePath) {
  1531. targets.push(this.currentSong);
  1532. }
  1533. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1534. if (!list || list.length === 0) {
  1535. return;
  1536. }
  1537. const found = Utility.getItemByFilePath(list, filePath);
  1538. if (found) {
  1539. markUpdated?.();
  1540. targets.push(found);
  1541. }
  1542. };
  1543. collectFromList(this.videoLocalList, () => {
  1544. mainListUpdated = true;
  1545. });
  1546. collectFromList(this.songList, () => {
  1547. playlistUpdated = true;
  1548. });
  1549. collectFromList(this.historyList);
  1550. collectFromList(this.favList);
  1551. const remoteManager = RemoteDriveManager.getInstance();
  1552. collectFromList(remoteManager.webDavSongs);
  1553. const updated = new Set<VideoItem>();
  1554. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1555. for (let i = 0; i < targets.length; i++) {
  1556. const target = targets[i];
  1557. if (!target || updated.has(target)) {
  1558. continue;
  1559. }
  1560. updated.add(target);
  1561. this.mergeVideoItemWithPayload(target, payload);
  1562. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1563. remoteMetadataUpdates.set(target.filePath, {
  1564. filePath: target.filePath,
  1565. pixelMapPath: target.pixelMapPath,
  1566. isCustomCover: target.isCustomCover,
  1567. md5Str: target.md5Str,
  1568. name: target.name,
  1569. artist: target.artist
  1570. });
  1571. }
  1572. }
  1573. if (this.currentSong && this.currentSong.filePath === filePath) {
  1574. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1575. if (payload.name) {
  1576. this.name = payload.name;
  1577. }
  1578. if (payload.artist) {
  1579. this.artist = payload.artist;
  1580. }
  1581. if (payload.pixelMapPath && this.currentSong?.pixelMapPath) {
  1582. this.cover = this.currentSong.pixelMapPath;
  1583. }
  1584. if (payload.lyricContent) {
  1585. this.applyInlineLyricContent(payload.lyricContent);
  1586. }
  1587. let avSessionDurationMs: number = this.duration;
  1588. if (payload.duration) {
  1589. const durationSeconds = Number(payload.duration);
  1590. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1591. avSessionDurationMs = durationSeconds * 1000;
  1592. this.duration = avSessionDurationMs;
  1593. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1594. this.durationStringTime = secondToTime(this.durationTime);
  1595. }
  1596. }
  1597. if (avSessionDurationMs > 0) {
  1598. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1599. }
  1600. this.currentSong = cloneVideoItem(this.currentSong);
  1601. AppStorage.setOrCreate('currentSong', this.currentSong);
  1602. }
  1603. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1604. if (primaryTarget) {
  1605. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1606. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1607. });
  1608. }
  1609. if (remoteMetadataUpdates.size > 0) {
  1610. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1611. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1612. }
  1613. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1614. }
  1615. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1616. // 关闭进度条
  1617. DialogHelper.closeDialog(this.loadingDialogId)
  1618. if (result.success) {
  1619. console.log("heanup 编辑信息成功,数据库已同步");
  1620. if (result.coverResult) {
  1621. ToastUtil.showToast('内嵌封面成功');
  1622. }
  1623. ToastUtil.showToast('内嵌音乐标签成功');
  1624. this.isShowMoreView = false;
  1625. this.name = this.titleStr;
  1626. // 同步当前播放的歌曲信息
  1627. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1628. this.currentSong.name = this.titleStr;
  1629. this.artist = this.artistStr;
  1630. this.currentSong.artist = this.artistStr;
  1631. this.currentSong.album = this.ablumStr;
  1632. this.currentSong.year = this.yearStr;
  1633. this.currentSong.genre = this.genreStr;
  1634. this.currentSong.track = this.trackStr;
  1635. this.currentSong.lyricContent = this.lyricConStr;
  1636. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1637. this.currentSong.COMPOSER = this.composerStr;
  1638. this.currentSong.LYRICIST = this.lyricistStr;
  1639. this.currentSong.COMMENT = this.commentStr;
  1640. }
  1641. // if (result.needRefreshList && this.modeType == 0) {
  1642. // this.deleteCache(this.currentPath);
  1643. // this.getSortedFiles(this.currentPath);
  1644. // }
  1645. // 同步编辑字段到本地列表
  1646. if (this.editingItem) {
  1647. this.syncEditedFields(this.editingItem);
  1648. this.syncListsAfterEdit(this.editingItem.filePath);
  1649. this.doUpateEditedFields(this.editingItem);
  1650. }
  1651. // 清理临时变量
  1652. this.longItemFilePath = '';
  1653. this.tempLyricContent = '';
  1654. this.isShowEdit = false;
  1655. this.imagePathStr = '';
  1656. } else {
  1657. console.error("heanup 编辑信息失败: " + result.error);
  1658. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1659. // 清理临时变量
  1660. this.longItemFilePath = '';
  1661. this.tempLyricContent = '';
  1662. this.isShowEdit = false;
  1663. this.imagePathStr = '';
  1664. }
  1665. }
  1666. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1667. if (value === undefined || value === null) {
  1668. return;
  1669. }
  1670. const text = value.toString();
  1671. if (!allowEmpty && text.trim().length === 0) {
  1672. return;
  1673. }
  1674. Reflect.set(target, key as string, value);
  1675. }
  1676. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1677. if (value === undefined || value === null || Number.isNaN(value)) {
  1678. return;
  1679. }
  1680. Reflect.set(target, key as string, value);
  1681. }
  1682. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1683. if (!target || !payload) {
  1684. return;
  1685. }
  1686. this.assignStringMetadata(target, 'name', payload.name);
  1687. this.assignStringMetadata(target, 'artist', payload.artist);
  1688. this.assignStringMetadata(target, 'album', payload.album);
  1689. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1690. this.assignStringMetadata(target, 'duration', payload.duration);
  1691. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1692. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1693. this.assignStringMetadata(target, 'md5Str', payload.md5Str);
  1694. this.assignStringMetadata(target, 'size', payload.size);
  1695. mergeCoverWithPriority(target, payload.pixelMapPath);
  1696. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1697. this.assignStringMetadata(target, 'genre', payload.genre);
  1698. this.assignStringMetadata(target, 'track', payload.track);
  1699. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1700. this.assignStringMetadata(target, 'channels', payload.channels);
  1701. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1702. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1703. this.assignStringMetadata(target, 'year', payload.year);
  1704. this.assignStringMetadata(target, 'disc', payload.disc);
  1705. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1706. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1707. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1708. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1709. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1710. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1711. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1712. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1713. }
  1714. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1715. if (!target || !source) {
  1716. return;
  1717. }
  1718. this.assignStringMetadata(target, 'name', source.name);
  1719. this.assignStringMetadata(target, 'artist', source.artist);
  1720. this.assignStringMetadata(target, 'album', source.album);
  1721. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1722. this.assignStringMetadata(target, 'duration', source.duration);
  1723. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1724. this.assignStringMetadata(target, 'md5Str', source.md5Str);
  1725. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1726. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1727. this.assignStringMetadata(target, 'size', source.size);
  1728. mergeCoverWithPriority(target, source.pixelMapPath, source.isCustomCover ?? 0);
  1729. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1730. this.assignStringMetadata(target, 'genre', source.genre);
  1731. this.assignStringMetadata(target, 'track', source.track);
  1732. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1733. this.assignStringMetadata(target, 'channels', source.channels);
  1734. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1735. this.assignStringMetadata(target, 'start_time', source.start_time);
  1736. this.assignStringMetadata(target, 'year', source.year);
  1737. this.assignStringMetadata(target, 'disc', source.disc);
  1738. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1739. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1740. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1741. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1742. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1743. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1744. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1745. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1746. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1747. target.remote_rel_path = source.remote_rel_path;
  1748. }
  1749. }
  1750. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1751. if (!item || !isRemoteCloudType(item.type)) {
  1752. return;
  1753. }
  1754. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1755. if (!storagePath) {
  1756. return;
  1757. }
  1758. try {
  1759. const cached = await this.table.queryVideoByFilePath(storagePath);
  1760. if (!cached) {
  1761. return;
  1762. }
  1763. this.mergeVideoItemFromSource(item, cached);
  1764. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1765. item.remote_rel_path = storagePath;
  1766. }
  1767. if (item === this.currentSong) {
  1768. if (StrUtil.isNotEmpty(item.name)) {
  1769. this.name = item.name;
  1770. }
  1771. if (StrUtil.isNotEmpty(item.artist)) {
  1772. this.artist = item.artist!;
  1773. }
  1774. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1775. this.cover = item.pixelMapPath!;
  1776. }
  1777. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1778. this.applyInlineLyricContent(item.lyricContent as string);
  1779. }
  1780. }
  1781. } catch (error) {
  1782. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1783. }
  1784. }
  1785. private applyInlineLyricContent(content: string): void {
  1786. if (StrUtil.isEmpty(content)) {
  1787. return;
  1788. }
  1789. this.lyricContent = content;
  1790. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1791. const lyric: Lyric = this.parser.parse(lines);
  1792. this.lyricController.setLyric(lyric);
  1793. this.lyricControllerXF.setLyric(lyric);
  1794. this.lyricControllerSingle.setLyric(lyric);
  1795. }
  1796. private extractParentPathFromStoragePath(path: string): string {
  1797. if (!path) {
  1798. return '';
  1799. }
  1800. const lastSlash = path.lastIndexOf('/');
  1801. if (lastSlash <= 0) {
  1802. return '';
  1803. }
  1804. return path.substring(0, lastSlash);
  1805. }
  1806. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1807. if (!target || !isRemoteCloudType(target.type)) {
  1808. return null;
  1809. }
  1810. if (isWebDavType(target.type)) {
  1811. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1812. if (storagePath) {
  1813. target.remote_rel_path = storagePath;
  1814. return storagePath;
  1815. }
  1816. return null;
  1817. }
  1818. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1819. return target.remote_rel_path;
  1820. }
  1821. return null;
  1822. }
  1823. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1824. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1825. return;
  1826. }
  1827. const storagePath = this.resolveRemoteStoragePath(target);
  1828. if (!storagePath) {
  1829. return;
  1830. }
  1831. const table = new MediaTable(this.context);
  1832. await new Promise<void>((resolve) => {
  1833. table.getRdbStore(this.context as Context, () => resolve());
  1834. });
  1835. const cloneItem = cloneVideoItem(target);
  1836. cloneItem.filePath = storagePath;
  1837. cloneItem.remote_rel_path = storagePath;
  1838. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1839. await table.saveOrUpdateWebDavItem(cloneItem);
  1840. }
  1841. onPageHide() {
  1842. this.knockController?.immersiveDisableListening();
  1843. }
  1844. @State isFirstStartPlay: boolean = false
  1845. private async startFileDeletionWatcher(): Promise<void> {
  1846. if (!this.rootPath) {
  1847. return;
  1848. }
  1849. if (!this.deletionWatcher) {
  1850. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1851. }
  1852. try {
  1853. await this.deletionWatcher.watchDirectories([
  1854. this.rootPath,
  1855. this.lockPath,
  1856. this.favPath,
  1857. this.historyPath
  1858. ]);
  1859. } catch (error) {
  1860. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1861. }
  1862. }
  1863. //获取download_path
  1864. async mkDownLoadDir() {
  1865. const documentViewPicker = new picker.DocumentViewPicker()
  1866. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1867. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1868. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1869. this.currentPath = this.rootPath
  1870. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1871. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1872. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1873. Logger.info('onecold rootPath = ' + this.rootPath)
  1874. if (!FileUtil.accessSync(this.favPath)) {
  1875. FileUtil.mkdirSync(this.favPath)
  1876. }
  1877. if (!FileUtil.accessSync(this.historyPath)) {
  1878. FileUtil.mkdirSync(this.historyPath)
  1879. }
  1880. // await this.startFileDeletionWatcher();
  1881. this.getSortedFiles(this.rootPath).then(async () => {
  1882. this.isFavMusic = false
  1883. //穿山甲
  1884. // this.loadBannerAd(CSJUtil.getBannerID())
  1885. this.restoreLastPlayContext();
  1886. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1887. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1888. if (ArrayUtil.isEmpty(this.songList)) {
  1889. this.songList = this.videoLocalList.filter(item =>
  1890. item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  1891. } else {
  1892. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1893. }
  1894. if (ArrayUtil.isNotEmpty(this.songList)) {
  1895. this.isFirstStartPlay = true
  1896. this.sonDataSource.pushArrayData(this.songList)
  1897. if (this.currentSong === undefined) {
  1898. this.isFirstStartPlay = false
  1899. this.currentSong = this.songList[0]
  1900. }
  1901. const restoredUrl = await this.resolvePlaybackUrlForCurrentSong('restore-last-song');
  1902. if (!restoredUrl) {
  1903. return;
  1904. }
  1905. this.videoUrl = restoredUrl;
  1906. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1907. this.name = this.currentSong.name
  1908. this.cover = this.currentSong.pixelMapPath
  1909. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1910. } else {
  1911. this.name = '空空如也'
  1912. }
  1913. })
  1914. this.getFavList(false)
  1915. }
  1916. getFavList(isFavRefresh: boolean) {
  1917. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1918. this.favList = result
  1919. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1920. this.videoLocalList = this.favList
  1921. this.updateListData(this.videoLocalList, true)
  1922. }
  1923. })
  1924. }
  1925. getHistoryList(isRefresh: boolean) {
  1926. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1927. this.historyList = result
  1928. // for (let i = 0; i < this.historyList.length; i++) {
  1929. //
  1930. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1931. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1932. // }
  1933. if (isRefresh) {
  1934. this.videoLocalList = this.historyList
  1935. this.updateListData(this.videoLocalList, true)
  1936. }
  1937. })
  1938. }
  1939. // 组件消失生命周期
  1940. aboutToDisappear() {
  1941. console.info('LifeCycleComponent aboutToDisappear');
  1942. if (this.alphaBetHideTimer) {
  1943. clearTimeout(this.alphaBetHideTimer);
  1944. this.alphaBetHideTimer = 0;
  1945. }
  1946. if (this.alphaBetRebuildTimer) {
  1947. clearTimeout(this.alphaBetRebuildTimer);
  1948. this.alphaBetRebuildTimer = 0;
  1949. }
  1950. if (this.pagingScheduleTimer) {
  1951. clearTimeout(this.pagingScheduleTimer);
  1952. this.pagingScheduleTimer = 0;
  1953. }
  1954. if (this.gridWaterScrollIdleTimer) {
  1955. clearTimeout(this.gridWaterScrollIdleTimer);
  1956. this.gridWaterScrollIdleTimer = 0;
  1957. }
  1958. if (this.listUpdateTimer) {
  1959. clearTimeout(this.listUpdateTimer);
  1960. this.listUpdateTimer = 0;
  1961. }
  1962. if (this.mediaLibraryWarmupPrefetchTimer) {
  1963. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  1964. this.mediaLibraryWarmupPrefetchTimer = 0;
  1965. }
  1966. this.clearInitialSeekGuardTimer();
  1967. this.alphaBetBuildVersion++;
  1968. this.gridWaterLastActiveTs = 0;
  1969. this.coverThumbCache.dispose();
  1970. this.coverThumbCacheReady = false;
  1971. this.pendingCoverThumbRefresh = false;
  1972. this.deletionWatcher?.stop();
  1973. this.knockController?.immersiveDisableListening();
  1974. this.curIndex = 0
  1975. this.isAppForeground = false;
  1976. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1977. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1978. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1979. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1980. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  1981. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  1982. emitter.off(EventConstants.EVENT_PLAYLIST_PLAY);
  1983. emitter.off(EventConstants.EVENT_PLAYLIST_REFRESH_SORT);
  1984. emitter.off(EventConstants.EVENT_PLAY_QUEUE_REFRESH);
  1985. emitter.off(EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST);
  1986. emitter.off(EventConstants.EVENT_PLAY_PAUSE);
  1987. this.mDestroyPage = true;
  1988. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1989. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1990. this.stop();
  1991. }
  1992. this.mIjkMediaPlayer.off('audioInterrupt');
  1993. this.mIjkMediaPlayer.off('deviceChange');
  1994. if (workerInstance) {
  1995. workerInstance.terminate();
  1996. }
  1997. this.stopPip();
  1998. this.destroyPipController()
  1999. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  2000. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  2001. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2002. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2003. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2004. this.eventHub.off('onStateChange');
  2005. }
  2006. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  2007. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  2008. this.isFavMusic = false
  2009. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2010. if (isWorkerPost) {
  2011. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2012. }
  2013. if (this.modeType !== 0) {
  2014. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  2015. if (isOpen && destPath) {
  2016. this.openMusic(true, destPath, openItem)
  2017. }
  2018. return
  2019. }
  2020. console.info('onecold getSortedFiles 2')
  2021. this.isCanBack = false
  2022. this.currentPath = curPath
  2023. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2024. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2025. if (curPath === this.rootPath) {
  2026. this.rightTopImage = $r('sys.symbol.sort')
  2027. } else {
  2028. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2029. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2030. this.rightTopImage = $r('sys.symbol.chevron_left')
  2031. }
  2032. }
  2033. // Get the current file list and calculate its hash
  2034. this.fileList = FileUtil.listFileSync(curPath);
  2035. const currentHash = simpleHash(this.fileList);
  2036. // Check cache
  2037. const cachedValue = this.findCache(curPath);
  2038. Logger.info('onecold cachedValue = ' + cachedValue)
  2039. const cachedHash = this.findStringCache(curPath + '_hash');
  2040. const cachedDirList = this.findCache(curPath + "_dirList");
  2041. if (cachedValue !== undefined&&!this.isRefreshing) {
  2042. // this.videoLocalList = cachedValue;
  2043. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2044. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2045. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2046. }
  2047. this.isRefreshing = false
  2048. this.updateListData(cachedValue, undefined, immediateListUpdate)
  2049. if (scrollTopAfterUpdate) {
  2050. this.scrollToTopForCurrentLayout()
  2051. }
  2052. }
  2053. if (cachedDirList !== undefined) {
  2054. this.dirList = cachedDirList
  2055. }
  2056. //通过当前hash值和缓存hash判断list有没有变化
  2057. if (cachedValue && cachedHash === currentHash) {
  2058. return;
  2059. }
  2060. // this.fileList = FileUtil.listFileSync(curPath)
  2061. let directories: Array<VideoItem> = [];
  2062. let isoFiles: Array<VideoItem> = this.getLocalIsoItems(curPath, this.fileList);
  2063. let files: Array<VideoItem> = [];
  2064. for (let i = 0; i < this.fileList.length; i++) {
  2065. // console.info(`The name of file: ${this.fileList[i]}`);
  2066. let path = curPath + '/' + this.fileList[i]
  2067. if (FileUtil.isDirectory(path)) {
  2068. let item: VideoItem =
  2069. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2070. '')
  2071. if (this.isShowDir(item.name)) {
  2072. directories.push(item);
  2073. }
  2074. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2075. // Utility.doSortListAscending(directories)
  2076. } else {
  2077. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2078. let item: VideoItem =
  2079. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2080. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2081. files.push(item);
  2082. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2083. // this.doSortListAscending(files)
  2084. }
  2085. }
  2086. }
  2087. }
  2088. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2089. if (this.currentPath !== this.lockPath) {
  2090. files = result.filter(item => !this.isIsoLocalFile(item));
  2091. }
  2092. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2093. Utility.doSortListAscending(files)
  2094. Utility.doSortListAscending(isoFiles)
  2095. if (this.currentPath === this.rootPath) {
  2096. this.dirList = directories
  2097. this.addCache(curPath + "_dirList", this.dirList);
  2098. }
  2099. //插入广告先注释掉
  2100. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2101. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2102. // directories.push(adItem)
  2103. // }
  2104. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2105. this.videoLocalList = directories.concat(isoFiles).concat(files);
  2106. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2107. if (scrollTopAfterUpdate) {
  2108. this.scrollToTopForCurrentLayout()
  2109. }
  2110. if (ArrayUtil.isNotEmpty(files)) {
  2111. if (this.currentPath != this.rootPath) {
  2112. if (files) {
  2113. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2114. }
  2115. }
  2116. }
  2117. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2118. this.addCache(curPath, this.videoLocalList);
  2119. await this.saveCacheToStorage();
  2120. this.addStringCache(curPath + '_hash', currentHash);
  2121. }
  2122. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2123. for (let i = 0; i < this.videoLocalList.length; i++) {
  2124. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2125. }
  2126. // this.setButtonStatus()
  2127. this.openMusic(isOpen, destPath,openItem)
  2128. this.isRefreshing = false
  2129. });
  2130. }
  2131. //第三方app打开天天静听导入音乐后播放
  2132. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2133. if (isOpen&&destPath) {
  2134. if (destPath === undefined) {
  2135. // 处理 destPath 为 undefined 的情况
  2136. return
  2137. }
  2138. if (destPath.endsWith('.lrc')) {
  2139. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2140. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2141. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2142. this.initLyric(lyricPath);
  2143. }
  2144. return
  2145. }
  2146. if(openItem){
  2147. this.doPlay(openItem,0,false,true)
  2148. // this.isShowPlay = true
  2149. this.setShowPlayTrue()
  2150. }
  2151. }
  2152. }
  2153. //扫描文件夹入库
  2154. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2155. const files = FileUtil.listFileSync(curPath);
  2156. let mediaItems: VideoItem[] = [];
  2157. Logger.info('onecold scanDirectory start ')
  2158. for (const file of files) {
  2159. const fPath = `${curPath}/${file}`;
  2160. if (fPath === this.lockPath) {
  2161. Logger.info(`Skipping locked path: ${fPath}`);
  2162. continue;
  2163. }
  2164. if (FileUtil.isDirectory(fPath)) {
  2165. // Recursively scan subdirectories
  2166. const subDirItems = await this.scanDirectory(fPath);
  2167. mediaItems = mediaItems.concat(subDirItems);
  2168. } else {
  2169. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2170. // Process media files
  2171. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2172. let mediaItem: VideoItem =
  2173. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2174. mediaItems.push(mediaItem);
  2175. this.table.insert(mediaItem, (id: number) => {
  2176. });
  2177. }
  2178. }
  2179. }
  2180. return mediaItems;
  2181. }
  2182. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2183. this.isShowTitleBar = true
  2184. const shouldAnimate = !immediate
  2185. if (this.listUpdateTimer) {
  2186. clearTimeout(this.listUpdateTimer)
  2187. this.listUpdateTimer = 0
  2188. }
  2189. const updateVersion = ++this.listUpdateVersion
  2190. if (shouldAnimate) {
  2191. this.getUIContext().animateTo({ duration: 666 }, () => {
  2192. this.opacityItem = 0.5;
  2193. });
  2194. }
  2195. const applyListData = () => {
  2196. if (updateVersion !== this.listUpdateVersion) {
  2197. return
  2198. }
  2199. this.videoLocalList = mList;
  2200. if (!noSort) {
  2201. if (this.modeType === 0 || this.modeType === 1) {
  2202. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2203. this.doSortType(this.sortType)
  2204. }
  2205. }
  2206. this.dataSource.pushArrayData(this.videoLocalList)
  2207. if (shouldAnimate) {
  2208. this.getUIContext().animateTo({ duration: 666 }, () => {
  2209. this.opacityItem = 1;
  2210. });
  2211. } else {
  2212. this.opacityItem = 1;
  2213. }
  2214. this.setButtonStatus()
  2215. //添加到字母索引表
  2216. this.markAlphaBetDirty()
  2217. };
  2218. if (immediate) {
  2219. applyListData();
  2220. return;
  2221. }
  2222. this.listUpdateTimer = setTimeout(() => {
  2223. this.listUpdateTimer = 0
  2224. applyListData();
  2225. }, 200);
  2226. }
  2227. getCurFileList(): Array<VideoItem> {
  2228. const source = this.isSearchMode ? this.filteredList : this.videoLocalList
  2229. let files: Array<VideoItem> = [];
  2230. if (ArrayUtil.isNotEmpty(source)) {
  2231. for (let i = 0; i < source.length; i++) {
  2232. if (this.isSelectableLocalItem(source[i])) {
  2233. files.push(source[i]);
  2234. }
  2235. }
  2236. }
  2237. return files
  2238. }
  2239. private isProtectedLocalDirectory(item: VideoItem): boolean {
  2240. return item.type === CommonConstants.TYPE_IS_DIR &&
  2241. (item.name === LocalMusic.STR_LOCK_VIDEO ||
  2242. item.name === LocalMusic.STR_FAC_VIDEO ||
  2243. item.name === LocalMusic.STR_HISTORY_MUSIC)
  2244. }
  2245. private isIsoLocalFile(item?: VideoItem | null): boolean {
  2246. if (!item || item.type !== CommonConstants.TYPE_LOCAL) {
  2247. return false
  2248. }
  2249. return Utility.isIsoByExtension(item.filePath || item.fileName || item.name || '')
  2250. }
  2251. private supportsLocalAudioActions(item: VideoItem): boolean {
  2252. return !!item && item.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(item)
  2253. }
  2254. private buildLocalIsoItem(filePath: string, fileName?: string): VideoItem {
  2255. const displayName = fileName || FileUtil.getFileName(filePath) || filePath
  2256. let fileSize = 0
  2257. try {
  2258. const stat = fs.statSync(filePath) as fs.Stat
  2259. if (typeof stat.size === 'number') {
  2260. fileSize = stat.size
  2261. }
  2262. } catch (_error) {
  2263. }
  2264. const item = new VideoItem(
  2265. displayName,
  2266. filePath,
  2267. filePath,
  2268. CommonConstants.TYPE_LOCAL,
  2269. fileSize,
  2270. Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
  2271. Utility.formatFSize(fileSize),
  2272. '',
  2273. 'ISO 镜像',
  2274. '可提取音频',
  2275. displayName
  2276. )
  2277. item.mimeType = 'application/x-iso9660-image'
  2278. item.duration = ''
  2279. return item
  2280. }
  2281. private getLocalIsoItems(curPath: string, fileNames?: Array<string>): Array<VideoItem> {
  2282. let sourceNames: Array<string> = []
  2283. if (fileNames !== undefined && fileNames.length > 0) {
  2284. sourceNames = fileNames
  2285. } else {
  2286. const listedNames = FileUtil.listFileSync(curPath)
  2287. sourceNames = listedNames ? listedNames : []
  2288. }
  2289. const isoItems: Array<VideoItem> = []
  2290. for (let i = 0; i < sourceNames.length; i++) {
  2291. const name = sourceNames[i]
  2292. const fullPath = `${curPath}/${name}`
  2293. if (FileUtil.isDirectory(fullPath) || !Utility.isIsoByExtension(fullPath)) {
  2294. continue
  2295. }
  2296. isoItems.push(this.buildLocalIsoItem(fullPath, name))
  2297. }
  2298. Utility.doSortListAscending(isoItems)
  2299. return isoItems
  2300. }
  2301. private filterOutLocalIsoItems(items: Array<VideoItem>): Array<VideoItem> {
  2302. return items.filter(item => !this.isIsoLocalFile(item))
  2303. }
  2304. private isSelectableLocalItem(item: VideoItem): boolean {
  2305. if (!item) {
  2306. return false
  2307. }
  2308. if (item.type === CommonConstants.TYPE_LOCAL) {
  2309. return true
  2310. }
  2311. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2312. return !this.isProtectedLocalDirectory(item)
  2313. }
  2314. return false
  2315. }
  2316. private isLocalItemSelected(item: VideoItem): boolean {
  2317. return this.selectedFiles.some(x => x.filePath === item.filePath)
  2318. }
  2319. private hasSelectedDirectories(): boolean {
  2320. return this.selectedFiles.some(item => item.type === CommonConstants.TYPE_IS_DIR)
  2321. }
  2322. private getSelectedPlayableFiles(): Array<VideoItem> {
  2323. return this.selectedFiles.filter(item => item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2324. }
  2325. private syncLocalSelectionState(): void {
  2326. const selectableItems = this.getCurFileList()
  2327. const selectableKeys: Set<string> = new Set(selectableItems.map(item => item.filePath))
  2328. const nextSelected = this.selectedFiles.filter(item => selectableKeys.has(item.filePath))
  2329. if (nextSelected.length !== this.selectedFiles.length) {
  2330. this.selectedFiles = [...nextSelected]
  2331. }
  2332. this.isAllSelected = nextSelected.length > 0 && nextSelected.length === selectableItems.length
  2333. }
  2334. private enterLocalMultiSelect(item: VideoItem): void {
  2335. if (!this.isSelectableLocalItem(item)) {
  2336. return
  2337. }
  2338. if (!this.isMultiSelect) {
  2339. this.isMultiSelect = true
  2340. }
  2341. if (!this.isLocalItemSelected(item)) {
  2342. this.selectedFiles = [...this.selectedFiles, item]
  2343. }
  2344. this.syncLocalSelectionState()
  2345. }
  2346. private selectSingleItemForDelete(item: VideoItem): void {
  2347. if (!this.isSelectableLocalItem(item)) {
  2348. return
  2349. }
  2350. this.selectedFiles = [item]
  2351. this.isAllSelected = false
  2352. }
  2353. setButtonStatus() {
  2354. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2355. this.isZero = false
  2356. } else {
  2357. this.isZero = true
  2358. }
  2359. if (this.currentPath !== this.rootPath &&
  2360. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2361. this.isHasDir = true //不为空,说明有子文件夹
  2362. } else {
  2363. this.isHasDir = false
  2364. }
  2365. }
  2366. private getPlayListDisplayCount(): number {
  2367. if (this.playQueueScope === 'history') {
  2368. return this.historyList.length;
  2369. }
  2370. if (this.playQueueScope === 'fav') {
  2371. return this.favList.length;
  2372. }
  2373. if (this.playQueueScope === 'playlist') {
  2374. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2375. // 如果是,优先返回服务端总数
  2376. const navidromeTotalCount = getNavidromeTotalCount();
  2377. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2378. if (navidromeTotalCount > 0 && this.currentSong && (
  2379. isNavidromeType(this.currentSong.type) ||
  2380. isJellyfinType(this.currentSong.type) ||
  2381. isEmbyType(this.currentSong.type) ||
  2382. isAudioStationType(this.currentSong.type) ||
  2383. isPlexType(this.currentSong.type) ||
  2384. isDaoLiYuType(this.currentSong.type)
  2385. )) {
  2386. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2387. return navidromeTotalCount;
  2388. }
  2389. Logger.info('heanup getPlayListDisplayCount', `返回 currentSongList.length: ${this.currentSongList.length}`);
  2390. return this.currentSongList.length;
  2391. }
  2392. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2393. return this.totalCount;
  2394. }
  2395. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2396. return this.songList.length;
  2397. }
  2398. private restoreLastPlayContext(): void {
  2399. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2400. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  2401. this.playQueueScope = scope;
  2402. } else {
  2403. this.playQueueScope = 'view';
  2404. }
  2405. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2406. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2407. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2408. this.totalCount = lastTotalCount;
  2409. }
  2410. }
  2411. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2412. if (this.isHydratingPlayList) {
  2413. return;
  2414. }
  2415. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2416. return;
  2417. }
  2418. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2419. return;
  2420. }
  2421. this.isHydratingPlayList = true;
  2422. try {
  2423. const fullList: VideoItem[] = [];
  2424. let pageIndex = 0;
  2425. let hasMore = true;
  2426. while (hasMore) {
  2427. const result = await this.table.queryMediaLibraryPaged({
  2428. pageIndex,
  2429. pageSize: this.pageSize,
  2430. sortType: this.sortType,
  2431. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2432. isShowFileName: this.isShowFileName
  2433. });
  2434. if (result.items.length === 0) {
  2435. break;
  2436. }
  2437. fullList.push(...result.items);
  2438. hasMore = result.hasMore;
  2439. pageIndex += 1;
  2440. if (fullList.length >= result.totalCount) {
  2441. hasMore = false;
  2442. }
  2443. }
  2444. if (fullList.length > 0) {
  2445. if(isSonList){
  2446. this.songList = fullList;
  2447. this.sonDataSource.pushArrayData(this.songList);
  2448. }else{
  2449. this.videoLocalList = fullList;
  2450. this.dataSource.pushArrayData(this.videoLocalList);
  2451. }
  2452. }
  2453. } finally {
  2454. this.isHydratingPlayList = false;
  2455. }
  2456. }
  2457. @Builder
  2458. SortMenuBuilder() {
  2459. Menu() {
  2460. MenuItem({
  2461. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2462. content: "按艺术家",
  2463. builder: this.SubSortBuilder(SortMode.ByArtist),
  2464. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2465. })
  2466. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByArtist)))
  2467. MenuItem({
  2468. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2469. content: "按专辑",
  2470. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2471. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2472. })
  2473. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByAlbum)))
  2474. MenuItem({
  2475. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2476. content: "按名称",
  2477. builder: this.SubSortBuilder(SortMode.ByName),
  2478. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2479. })
  2480. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2481. MenuItem({
  2482. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2483. content: $r('app.string.sort_by_time'),
  2484. builder: this.SubSortBuilder(SortMode.ByTime),
  2485. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2486. })
  2487. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByTime)))
  2488. MenuItem({
  2489. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2490. content: '按碟片音轨号',
  2491. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2492. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2493. })
  2494. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByDiscTrack)))
  2495. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2496. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2497. }.attributeModifier(new MenuModifier())
  2498. }
  2499. @Builder
  2500. SortMenuForArtistAblumBuilder() {
  2501. Menu() {
  2502. MenuItem({
  2503. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2504. content: "按名称",
  2505. builder: this.SubSortBuilder(SortMode.ByName),
  2506. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2507. })
  2508. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2509. MenuItem({
  2510. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2511. content: '按数量',
  2512. builder: this.SubSortBuilder(SortMode.ByCount),
  2513. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2514. })
  2515. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByCount)))
  2516. }.attributeModifier(new MenuModifier())
  2517. }
  2518. @Builder SubSortBuilder(sortType: number){
  2519. Menu(){
  2520. MenuItem({
  2521. content: "升序",
  2522. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2523. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2524. })
  2525. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType, true))
  2526. .onClick(async () => {
  2527. await this.doSortType(sortType)
  2528. })
  2529. MenuItem({
  2530. content: "降序",
  2531. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2532. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2533. })
  2534. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType + 1, false))
  2535. .onClick(async () => {
  2536. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2537. })
  2538. }
  2539. }
  2540. async doSortType(index: number): Promise<void> {
  2541. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2542. this.sortType = index;
  2543. this.saveSortTypeForCurrentMode(index);
  2544. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2545. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2546. await this.reloadCurrentDetailSongs();
  2547. } else {
  2548. // 分页模式下,排序需要重新从数据库查询
  2549. await this.resetAndLoadFirstPage();
  2550. }
  2551. }
  2552. /**
  2553. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2554. * 用于详情页切换排序方式时重新查询并排序
  2555. */
  2556. private async reloadCurrentDetailSongs(): Promise<void> {
  2557. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2558. try {
  2559. if (this.modeType === 2) {
  2560. // 艺术家详情页: 重新查询该艺术家的歌曲
  2561. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2562. if (ArrayUtil.isNotEmpty(mList)) {
  2563. // 使用带排序类型的缓存键
  2564. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2565. this.artistMap.set(cacheKey, mList);
  2566. this.totalCount = mList.length;
  2567. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2568. this.updateListData(mList, true);
  2569. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2570. }
  2571. } else if (this.modeType === 3) {
  2572. // 专辑详情页: 重新查询该专辑的歌曲
  2573. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2574. if (ArrayUtil.isNotEmpty(albumList)) {
  2575. // 使用带排序类型的缓存键
  2576. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2577. this.albumMap.set(cacheKey, albumList);
  2578. this.totalCount = albumList.length;
  2579. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2580. this.updateListData(albumList, true);
  2581. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2582. }
  2583. }
  2584. } catch (err) {
  2585. const error = err as Error;
  2586. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2587. ToastUtil.showToast('重新加载数据失败');
  2588. }
  2589. }
  2590. /**
  2591. * 根据当前模式保存排序类型到不同的存储键
  2592. * 区分列表页和详情页的排序设置
  2593. */
  2594. private saveSortTypeForCurrentMode(sortType: number): void {
  2595. let storageKey = SettingPage.SORT_TYPE;
  2596. if (this.modeType === 2) {
  2597. // 艺术家模式
  2598. if (this.isCanBack) {
  2599. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2600. } else {
  2601. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2602. }
  2603. } else if (this.modeType === 3) {
  2604. // 专辑模式
  2605. if (this.isCanBack) {
  2606. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2607. } else {
  2608. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2609. }
  2610. } else {
  2611. storageKey = SettingPage.SORT_TYPE;
  2612. }
  2613. PreferencesUtil.putSync(storageKey, sortType);
  2614. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2615. }
  2616. /**
  2617. * 根据当前模式加载排序类型
  2618. * 区分列表页和详情页的排序设置
  2619. */
  2620. private loadSortTypeForCurrentMode(): number {
  2621. let storageKey = SettingPage.SORT_TYPE;
  2622. let defaultSortType = 4;
  2623. if (this.modeType === 2) {
  2624. // 艺术家模式
  2625. if (this.isCanBack) {
  2626. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2627. defaultSortType = 4; // 详情页默认按名称升序
  2628. } else {
  2629. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2630. defaultSortType = 9; // 列表页默认按数量降序
  2631. }
  2632. } else if (this.modeType === 3) {
  2633. // 专辑模式
  2634. if (this.isCanBack) {
  2635. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2636. defaultSortType = 4; // 详情页默认按名称升序
  2637. } else {
  2638. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2639. defaultSortType = 9; // 列表页默认按数量降序
  2640. }
  2641. }
  2642. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2643. }
  2644. /**
  2645. * 检查当前sortType是否在指定排序类型的范围内
  2646. * 用于判断是否显示打勾图标
  2647. * @param baseSortType 基础排序类型(升序的值)
  2648. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2649. */
  2650. private isSortTypeInRange(baseSortType: number): boolean {
  2651. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2652. }
  2653. private getSortModeItemBackground(isSelected: boolean): ResourceColor {
  2654. if (!isSelected) {
  2655. return Color.Transparent;
  2656. }
  2657. return this.isDarkMode ? '#334967' : '#EAF2FF';
  2658. }
  2659. private getSortOrderItemBackground(isSelected: boolean, isAsc: boolean): ResourceColor {
  2660. if (!isSelected) {
  2661. return Color.Transparent;
  2662. }
  2663. if (isAsc) {
  2664. return this.isDarkMode ? '#295B8A' : '#DCEEFF';
  2665. }
  2666. return this.isDarkMode ? '#7A4D22' : '#FFE9D5';
  2667. }
  2668. showSheelDialog() {
  2669. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2670. // this.showTips()
  2671. // return
  2672. // }
  2673. this.showAddDialog()
  2674. }
  2675. showAddDialog() {
  2676. if (this.modeType === 2 || this.modeType === 3) {
  2677. return
  2678. }
  2679. DialogHelper.showActionSheetDialog({
  2680. title: "请选择添加方式(建议歌词文件一起导入)",
  2681. sheets: [
  2682. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2683. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2684. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2685. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2686. ],
  2687. maskColor: Color.Transparent,
  2688. backgroundColor: $r('app.color.bg_card'),
  2689. transition: AnimationHelper.transitionInDown(555),
  2690. onAction: (index) => {
  2691. switch (index) {
  2692. case 0:
  2693. if (this.modeType === 0) {
  2694. this.showMkDialog()
  2695. } else {
  2696. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2697. }
  2698. break;
  2699. case 1:
  2700. this.callFilePickerSelectFile()
  2701. break;
  2702. case 2:
  2703. this.showTips()
  2704. break;
  2705. case 3:
  2706. this.goSelectMusic()
  2707. break;
  2708. }
  2709. }
  2710. })
  2711. }
  2712. //拉起音频
  2713. goSelectMusic() {
  2714. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2715. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2716. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2717. ) {
  2718. ToastUtil.showToast('暂时不支持该设备')
  2719. return
  2720. }
  2721. try {
  2722. let documentSelectOptions = new picker.DocumentSelectOptions();
  2723. documentSelectOptions.authMode = true
  2724. documentSelectOptions.multiAuthMode = true
  2725. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2726. documentSelectOptions.maxSelectNumber = 20000
  2727. }
  2728. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2729. let documentPicker = new picker.DocumentViewPicker(this.context);
  2730. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2731. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2732. this.saveVideoDatas(documentSelectResult)
  2733. }
  2734. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2735. JSON.stringify(documentSelectResult));
  2736. }).catch((err: BusinessError) => {
  2737. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2738. });
  2739. } catch (error) {
  2740. let err: BusinessError = error as BusinessError;
  2741. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2742. }
  2743. }
  2744. async showTips() {
  2745. try {
  2746. this.getUIContext().getPromptAction().showDialog({
  2747. title: '导入指南',
  2748. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2749. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2750. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2751. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2752. buttons: [
  2753. {
  2754. text: '知道了',
  2755. color: '#000000'
  2756. },
  2757. ]
  2758. }, (err, data) => {
  2759. if (err) {
  2760. console.error('showDialog err: ' + err);
  2761. return;
  2762. }
  2763. console.info('showDialog success callback, click button: ' + data.index);
  2764. });
  2765. } catch (error) {
  2766. let message = (error as BusinessError).message;
  2767. let code = (error as BusinessError).code;
  2768. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2769. };
  2770. }
  2771. showMkDialog() {
  2772. DialogHelper.showTextInputDialog({
  2773. title: '新建歌单',
  2774. maskColor: Color.Transparent,
  2775. text: '',
  2776. transition: AnimationHelper.transitionInDown(666),
  2777. onChange: (text) => {
  2778. console.error("onChange: " + text);
  2779. },
  2780. onAction: (action, dialogId, content) => {
  2781. // ToastUtil.showToast('content = ' +content)
  2782. if (action == DialogAction.TWO) {
  2783. const newName = content
  2784. const newPath = this.currentPath + '/' + newName
  2785. FileUtil.mkdir(newPath, true).then(() => {
  2786. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2787. this.getSortedFiles(this.currentPath)
  2788. }).catch((error: BusinessError) => {
  2789. console.error(error.message);
  2790. });
  2791. }
  2792. }
  2793. })
  2794. }
  2795. @State progress: number = 0;
  2796. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2797. if (ArrayUtil.isEmpty(uris)) {
  2798. return;
  2799. }
  2800. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2801. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2802. this.saveVideoDatasToDownLoad(uris,isOpen)
  2803. return
  2804. }
  2805. // 初始化进度条
  2806. this.progress = 0;
  2807. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2808. progress: this.progress,
  2809. backCancel: false,
  2810. autoCancel: false,
  2811. loadColor: $r('app.color.title_bar_bg'),
  2812. fontColor: $r('app.color.title_bar_bg')
  2813. });
  2814. // 计算处理总数用于进度计算
  2815. const totalItems = uris.length;
  2816. let processedItems = 0;
  2817. for (let i = 0; i < uris.length; i++) {
  2818. let filePath = uris[i];
  2819. try {
  2820. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2821. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2822. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2823. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2824. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2825. if (!filePath.includes(this.rootPath)) {
  2826. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2827. mediaItem.parentPath = this.currentPath;
  2828. }
  2829. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2830. this.table.insert(mediaItem, (id: number) => {
  2831. // 插入完成回调
  2832. });
  2833. }
  2834. }
  2835. // 更新进度
  2836. processedItems++;
  2837. this.progress = Math.floor((processedItems / totalItems) * 100);
  2838. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2839. } catch (error) {
  2840. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2841. // 即使出错也更新进度
  2842. processedItems++;
  2843. this.progress = Math.floor((processedItems / totalItems) * 100);
  2844. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2845. }
  2846. }
  2847. // 关闭进度条
  2848. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2849. this.isZero = false
  2850. // 删除目标路径缓存
  2851. setTimeout(() => {
  2852. this.cache.delete(this.currentPath);
  2853. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2854. this.setButtonStatus()
  2855. }, 500);
  2856. }
  2857. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2858. if (ArrayUtil.isEmpty(uris)) {
  2859. return;
  2860. }
  2861. let newUris: string[] = [];
  2862. this.progress = 0
  2863. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2864. progress: this.progress,
  2865. backCancel: false,
  2866. autoCancel: false,
  2867. loadColor: this.themeColor,
  2868. fontColor: this.themeColor
  2869. });
  2870. // 计算所有文件的总大小
  2871. let totalSize = 0;
  2872. for (let uri of uris) {
  2873. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2874. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2875. await fileIo.close(sourceFile.fd);
  2876. }
  2877. let totalRead = 0;
  2878. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2879. Logger.info(TAG, 'destPath uri: ' + destPath);
  2880. for (let i = 0; i < uris.length; i++) {
  2881. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2882. Logger.info(TAG, 'filePath uri: ' + filePath);
  2883. newUris.push(filePath);
  2884. try {
  2885. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2886. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2887. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2888. const buffer = new ArrayBuffer(buffSize);
  2889. let len = await fileIo.read(sourceFile.fd, buffer);
  2890. while (len > 0) {
  2891. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2892. totalRead += len;
  2893. // 计算总进度
  2894. this.progress = Math.floor((totalRead / totalSize) * 100);
  2895. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2896. len = await fileIo.read(sourceFile.fd, buffer);
  2897. }
  2898. await fileIo.close(sourceFile.fd);
  2899. await fileIo.close(destFile.fd);
  2900. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2901. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2902. let mediaItem: VideoItem =
  2903. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2904. this.table.insert(mediaItem, (id: number) => {
  2905. // 删除目标路径缓存
  2906. this.cache.delete(this.currentPath);
  2907. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2908. });
  2909. }
  2910. }
  2911. } catch (error) {
  2912. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2913. }
  2914. }
  2915. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2916. this.isZero = false
  2917. Logger.info(TAG, 'scan select video result:' + newUris)
  2918. }
  2919. //拉起音频
  2920. // goSelectMusic(){
  2921. //
  2922. // try {
  2923. // let audioSelectOptions = new picker.AudioSelectOptions();
  2924. // let audioPicker = new picker.AudioViewPicker(this.context);
  2925. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2926. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2927. // this.saveVideoDatas(audioSelectResult)
  2928. // }
  2929. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2930. // }).catch((err: BusinessError) => {
  2931. //
  2932. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2933. // });
  2934. // } catch (error) {
  2935. // let err: BusinessError = error as BusinessError;
  2936. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2937. // }
  2938. //
  2939. //
  2940. //
  2941. // }
  2942. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2943. if (!item) {
  2944. return undefined;
  2945. }
  2946. try {
  2947. let selectUris: Array<string> = [];
  2948. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2949. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2950. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2951. photoSelectOptions.maxSelectNumber = 1;
  2952. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2953. selectUris = photoSelectResult.photoUris;
  2954. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2955. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2956. console.info('file fd: ' + file.fd);
  2957. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2958. let imagePath = this.context.filesDir + FileUtil.separator + name
  2959. imagePath = fileUri.getUriFromPath(imagePath)
  2960. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2961. fileIo.copyFileSync(file.fd, file2.fd)
  2962. fileIo.closeSync(file);
  2963. fileIo.closeSync(file2);
  2964. if (item.filePath == this.currentSong?.filePath) {
  2965. this.cover = imagePath
  2966. if (this.currentSong) {
  2967. this.currentSong.isCustomCover = 1;
  2968. }
  2969. }
  2970. if (item) {
  2971. item.pixelMapPath = imagePath
  2972. item.isCustomCover = 1;
  2973. }
  2974. if (isRemoteCloudType(item.type)) {
  2975. return FileUtil.getFilePath(imagePath);
  2976. }
  2977. this.table.updateCustomCoverPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2978. if (success) {
  2979. this.doUpdateData()
  2980. console.log("onecold 更新音乐封面成功,数据库已同步");
  2981. } else {
  2982. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2983. }
  2984. });
  2985. LogUtil.debug("onecold this.cover =" + this.cover)
  2986. return FileUtil.getFilePath(imagePath); // Return the image path here
  2987. } catch (err) {
  2988. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2989. return undefined;
  2990. }
  2991. }
  2992. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  2993. try {
  2994. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  2995. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2996. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2997. photoSelectOptions.maxSelectNumber = 1;
  2998. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2999. const selectUris = photoSelectResult.photoUris;
  3000. if (!selectUris || selectUris.length === 0) {
  3001. return undefined;
  3002. }
  3003. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  3004. if (!FileUtil.accessSync(coverDir)) {
  3005. FileUtil.mkdirSync(coverDir);
  3006. }
  3007. const sourceUri = selectUris[0];
  3008. const sourceName = FileUtil.getFileName(sourceUri) || '';
  3009. let suffix = '.jpg';
  3010. const dotIndex = sourceName.lastIndexOf('.');
  3011. if (dotIndex >= 0) {
  3012. suffix = sourceName.substring(dotIndex);
  3013. }
  3014. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  3015. const targetPath = coverDir + FileUtil.separator + targetName;
  3016. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  3017. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  3018. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  3019. fileIo.closeSync(sourceFile.fd);
  3020. fileIo.closeSync(targetFile.fd);
  3021. return fileUri.getUriFromPath(targetPath);
  3022. } catch (error) {
  3023. const err = error as BusinessError;
  3024. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  3025. return undefined;
  3026. }
  3027. }
  3028. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  3029. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  3030. ToastUtil.showToast('当前歌曲无效');
  3031. return;
  3032. }
  3033. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  3034. if (StrUtil.isEmpty(sandboxCoverUri)) {
  3035. return;
  3036. }
  3037. const coverUri = sandboxCoverUri as string;
  3038. this.loadingDialogId = DialogHelper.showLoadingDialog();
  3039. try {
  3040. if (isRemoteCloudType(this.currentSong.type)) {
  3041. this.cover = coverUri;
  3042. this.currentSong.pixelMapPath = coverUri;
  3043. this.currentSong.isCustomCover = 1;
  3044. this.syncRemoteManagerSong(this.currentSong);
  3045. await this.persistRemoteMetadataToDb(this.currentSong);
  3046. this.emitRemoteMetadataUpdated(this.currentSong);
  3047. this.currentSong = cloneVideoItem(this.currentSong);
  3048. AppStorage.setOrCreate('currentSong', this.currentSong);
  3049. ToastUtil.showToast('更换封面成功');
  3050. return;
  3051. }
  3052. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  3053. ToastUtil.showToast('当前歌曲类型暂不支持更换封面');
  3054. return;
  3055. }
  3056. const task = new taskpool.Task(
  3057. replaceLocalMusicCoverTask,
  3058. this.context,
  3059. this.currentSong.filePath,
  3060. FileUtil.getFilePath(coverUri)
  3061. );
  3062. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  3063. if (!result) {
  3064. ToastUtil.showToast('更换封面失败');
  3065. return;
  3066. }
  3067. this.cover = coverUri;
  3068. this.currentSong.pixelMapPath = coverUri;
  3069. this.currentSong.isCustomCover = 1;
  3070. await this.doUpateEditedFields(this.currentSong);
  3071. ToastUtil.showToast('更换封面成功');
  3072. } catch (error) {
  3073. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  3074. ToastUtil.showToast('更换封面失败');
  3075. } finally {
  3076. DialogHelper.closeDialog(this.loadingDialogId);
  3077. }
  3078. }
  3079. // 拉起picker选择文件管理器
  3080. async callFilePickerSelectFile(): Promise<void> {
  3081. try {
  3082. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  3083. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  3084. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  3085. } else {
  3086. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  3087. }
  3088. let documentPicker = new picker.DocumentViewPicker();
  3089. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  3090. Logger.info(TAG,
  3091. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  3092. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  3093. this.saveVideoDatas(DocumentSelectResult)
  3094. }
  3095. }).catch((err: BusinessError) => {
  3096. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  3097. });
  3098. } catch (err) {
  3099. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  3100. }
  3101. }
  3102. //重命名的对话框
  3103. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  3104. if(!item.filePath.includes(this.packName)){
  3105. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  3106. return
  3107. }
  3108. DialogHelper.showTextInputDialog({
  3109. title: '重命名',
  3110. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : (item.fileName || item.name),
  3111. maskColor: Color.Transparent,
  3112. backgroundColor: Color.Grey,
  3113. transition: AnimationHelper.transitionInDown(666),
  3114. onChange: (text) => {
  3115. console.error("onChange: " + text);
  3116. },
  3117. onAction: (action, dialogId, content) => {
  3118. // ToastUtil.showToast('content = ' +content)
  3119. if (action == DialogAction.TWO) {
  3120. const newName = content
  3121. const newPath = this.currentPath + '/' + newName
  3122. console.log("onecold item = " + item.type);
  3123. this.doReName(index, newName, filePath, newPath, item)
  3124. }
  3125. }
  3126. })
  3127. }
  3128. //剪切 移动到另个文件夹的对话框
  3129. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3130. Logger.info('onecold showCutDialog')
  3131. let mList: Array<string> = []
  3132. let rPath = this.rootPath
  3133. if (isCurrent) {
  3134. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3135. rPath = this.currentPath
  3136. } else {
  3137. mList = Utility.getNameList(this.dirList);
  3138. rPath = this.rootPath
  3139. }
  3140. let dataBean = new BubbleBean()
  3141. dataBean.data = mList
  3142. dataBean.color = this.themeColor
  3143. dataBean.onItemClick = (i) => {
  3144. const targetName = item.fileName || item.name
  3145. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3146. Logger.info('newPath = ' + newPath)
  3147. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3148. ToastUtil.showToast('移动成功')
  3149. this.table.deleteData(item, () => {
  3150. });
  3151. if (!Utility.isIsoByExtension(newPath)) {
  3152. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3153. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3154. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3155. this.table.insert(newItem, (id: number) => {
  3156. //加入数据库
  3157. });
  3158. }
  3159. }
  3160. this.cache.delete(this.currentPath); // 删除原路径缓存
  3161. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3162. this.getSortedFiles(this.currentPath, true)
  3163. }).catch((error: BusinessError) => {
  3164. console.error(error.message);
  3165. });
  3166. XPopup.dismissTop()
  3167. }
  3168. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3169. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3170. popupPosition = PopupPosition.TOP
  3171. }
  3172. if (index <= 3) {
  3173. popupPosition = PopupPosition.BOTTOM
  3174. }
  3175. let pup: XPopup
  3176. if (this.isDarkMode) {
  3177. pup = XPopup.Builder()
  3178. .setPopupPosition(popupPosition)
  3179. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  3180. .setBackgroundColor(Color.Black)
  3181. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3182. .show()
  3183. } else {
  3184. pup = XPopup.Builder()
  3185. .setPopupPosition(popupPosition)
  3186. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  3187. .setBackgroundColor(Color.White)
  3188. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3189. .show()
  3190. }
  3191. }
  3192. //复制 到另个文件夹的对话框
  3193. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3194. Logger.info('onecoldv showCopyDialog')
  3195. let mList: Array<string> = []
  3196. let rPath = this.rootPath
  3197. if (isCurrent) {
  3198. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3199. rPath = this.currentPath
  3200. } else {
  3201. mList = Utility.getNameList(this.dirList);
  3202. rPath = this.rootPath
  3203. }
  3204. let dataBean = new BubbleBean()
  3205. dataBean.data = mList
  3206. dataBean.isCopy = true
  3207. dataBean.color = this.themeColor
  3208. dataBean.onItemClick = (i) => {
  3209. const targetName = item.fileName || item.name
  3210. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3211. Logger.info('newPath = ' + newPath)
  3212. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3213. ToastUtil.showToast('复制成功')
  3214. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3215. this.getSortedFiles(this.currentPath)
  3216. if (!Utility.isIsoByExtension(newPath)) {
  3217. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3218. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3219. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3220. this.table.insert(newItem, (id: number) => {
  3221. //加入数据库
  3222. });
  3223. }
  3224. }
  3225. }).catch((error: BusinessError) => {
  3226. console.error(error.message);
  3227. });
  3228. XPopup.dismissTop()
  3229. }
  3230. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3231. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3232. popupPosition = PopupPosition.TOP
  3233. }
  3234. if (index <= 3) {
  3235. popupPosition = PopupPosition.BOTTOM
  3236. }
  3237. let pup: XPopup
  3238. if (this.isDarkMode) {
  3239. pup = XPopup.Builder()
  3240. .setPopupPosition(popupPosition)
  3241. .atView(id)
  3242. .setMaxHeight('60%')
  3243. .setBackgroundColor(Color.Black)
  3244. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3245. .show();
  3246. } else {
  3247. pup = XPopup.Builder()
  3248. .setPopupPosition(popupPosition)
  3249. .atView(id)
  3250. .setMaxHeight('60%')
  3251. .setBackgroundColor(Color.White)
  3252. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3253. .show();
  3254. }
  3255. }
  3256. //重命名索引index的视频
  3257. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3258. FileUtil.rename(oldPath, newPath).then(async () => {
  3259. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3260. let refreshedItem: VideoItem = info
  3261. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3262. //如果是文件夹先删除源数据,再添加新数据
  3263. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3264. if (success) {
  3265. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3266. } else {
  3267. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3268. }
  3269. });
  3270. this.scanDirectory(newPath)
  3271. refreshedItem = new VideoItem(newName, newName, newPath, CommonConstants.TYPE_IS_DIR, 0, '')
  3272. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3273. if (Utility.isIsoByExtension(oldPath) || Utility.isIsoByExtension(newPath)) {
  3274. refreshedItem = this.buildLocalIsoItem(newPath, newName)
  3275. } else {
  3276. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3277. if (success) {
  3278. console.log(" onecold 重命名成功,数据库已同步");
  3279. } else {
  3280. console.error(" onecold 重命名数据库失败原因: " + error);
  3281. }
  3282. });
  3283. refreshedItem =
  3284. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3285. }
  3286. } else {
  3287. return
  3288. }
  3289. this.videoLocalList[index] = refreshedItem;
  3290. }
  3291. this.cache.delete(this.currentPath)
  3292. this.cache.delete(oldPath)
  3293. this.cache.delete(newPath)
  3294. this.getSortedFiles(this.currentPath, true)
  3295. }).catch((error: BusinessError) => {
  3296. console.error(error.message);
  3297. });
  3298. }
  3299. build() {
  3300. Stack() {
  3301. this.ContentBuild()
  3302. Stack() {
  3303. Column()
  3304. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3305. height: '95%',
  3306. dragBar: true,
  3307. showClose: true,
  3308. blurStyle: BlurStyle.Thin,
  3309. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3310. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3311. title: {
  3312. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3313. + `(${this.getPlayListDisplayCount()}首)`
  3314. }
  3315. })
  3316. }
  3317. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3318. modalTransition:ModalTransition.DEFAULT,
  3319. onWillDisappear: () => {
  3320. this.setShowPlayFalse()
  3321. },
  3322. })
  3323. }
  3324. .alignContent(Alignment.Bottom)
  3325. .width('100%')
  3326. .height('100%')
  3327. }
  3328. @Builder
  3329. ContentBuild() {
  3330. Scroll() {
  3331. Column() {
  3332. Stack() {
  3333. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3334. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3335. controller: this.xcomponentController })
  3336. .onLoad(async (event?: object) => {
  3337. })
  3338. .focusable(true)
  3339. .height(0)
  3340. .focusOnTouch(true)
  3341. .defaultFocus(true) // 自动获取键盘焦点
  3342. .onKeyEvent((event?: KeyEvent) => {
  3343. console.info('onecold点击 onKeyEvent')
  3344. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3345. if (!event || event.type !== KeyType.Down) {
  3346. return;
  3347. }
  3348. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3349. //空格键 Space key controls pause/play
  3350. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3351. this.playOrPause()
  3352. }
  3353. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3354. this.playPrevious()
  3355. }
  3356. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3357. this.playNext()
  3358. }
  3359. // Right-click to fast forward
  3360. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3361. this.fastForward()
  3362. }
  3363. // Left-click to rewind
  3364. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3365. this.backForward()
  3366. }
  3367. })
  3368. Column() {
  3369. XComponent({
  3370. id: 'xcomponentId',
  3371. type: 'surface',
  3372. libraryname: 'ijkplayer_napi',
  3373. controller: this.xcomponentController
  3374. })
  3375. .onLoad((event?: object) => {
  3376. if (!!event) {
  3377. this.initDelayPlay(event);
  3378. }
  3379. })
  3380. .onDestroy(() => {
  3381. })
  3382. .width('100%')// .width(this.videoWidth)
  3383. .aspectRatio(this.videoAspectRatio)
  3384. }
  3385. .aspectRatio(this.videoAspectRatio)
  3386. .justifyContent(FlexAlign.Center)
  3387. .backgroundColor(Color.Transparent)
  3388. .visibility(Visibility.Hidden)
  3389. .height(CommonConstants.FULL_PERCENT)
  3390. .width(CommonConstants.FULL_PERCENT)
  3391. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3392. height:this.isLandscape?'80%': '43%',
  3393. dragBar: true,
  3394. showClose: true,
  3395. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3396. blurStyle:BlurStyle.Thin,
  3397. backgroundColor:Color.Transparent,
  3398. title: { title: 'AB循环' }
  3399. })
  3400. Stack() {
  3401. Column() {
  3402. if(this.twoFingerType==4){
  3403. this.getWaterView()
  3404. }else{
  3405. if(this.isGridMusic){
  3406. this.getGridView()
  3407. }else {
  3408. this.getListView()
  3409. }
  3410. }
  3411. if (this.modeType ==0||this.modeType==4) {
  3412. Column() {
  3413. emptyView(this.themeColor)
  3414. }
  3415. .padding({ right:6 })
  3416. .onClick(()=>{
  3417. this.asyncCurrentPathOnlyFile()
  3418. })
  3419. .alignItems(HorizontalAlign.Center)
  3420. .position({ top: 200 })
  3421. .justifyContent(FlexAlign.Center)
  3422. .opacity(this.isZero ? 1 : 0)
  3423. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3424. ? Visibility.Visible : Visibility.None)
  3425. .animation({
  3426. duration: 500,
  3427. curve: Curve.Friction // 可选动画曲线
  3428. })
  3429. .width('100%')
  3430. }
  3431. }
  3432. .layoutWeight(1)
  3433. .height('100%')
  3434. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3435. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3436. .onDrop((event?: DragEvent) => {
  3437. try {
  3438. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3439. if (dragData !== undefined) {
  3440. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3441. if (records.length > 0) {
  3442. for (let i = 0; i < records.length; i++) {
  3443. let types = records[i].getTypes();
  3444. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3445. const fileUriUds =
  3446. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3447. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3448. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3449. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3450. this.targetFile = fileUriUds.oriUri;
  3451. this.saveVideoDatas([this.targetFile])
  3452. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3453. }
  3454. }
  3455. }
  3456. } else {
  3457. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3458. }
  3459. } else {
  3460. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3461. }
  3462. } catch (error) {
  3463. const err = error as BusinessError;
  3464. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3465. }
  3466. })
  3467. // 右侧居中的字母表索引
  3468. this.indexBuilder()
  3469. this.topTitleBar()
  3470. }
  3471. .alignContent(Alignment.Top)
  3472. .layoutWeight(1)
  3473. .height('100%')
  3474. Row() {
  3475. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3476. .width(45)
  3477. .height(45)
  3478. .fontSize(10)
  3479. .margin({ top: 10, bottom: 10, right: 6 })
  3480. .backgroundColor(this.themeColor)
  3481. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3482. .onClick(() => {
  3483. if (this.isAllSelected) {
  3484. // 全不选
  3485. this.selectedFiles = [];
  3486. } else {
  3487. // 全选
  3488. this.selectedFiles = [...this.getCurFileList()];
  3489. }
  3490. this.syncLocalSelectionState();
  3491. })
  3492. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3493. .width(72)
  3494. .height(45)
  3495. .fontSize(10)
  3496. .margin({ top: 10, bottom: 10, right: 6 })
  3497. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3498. .backgroundColor(this.themeColor)
  3499. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3500. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3501. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3502. })
  3503. .onClick(() => {
  3504. if (this.hasSelectedDirectories()) {
  3505. ToastUtil.showToast('文件夹不支持批量内嵌标签')
  3506. return
  3507. }
  3508. this.isOneKeyTags = !this.isOneKeyTags
  3509. })
  3510. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3511. .width(45)
  3512. .height(45)
  3513. .fontSize(10)
  3514. .margin({ top: 10, bottom: 10, right: 6 })
  3515. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3516. .backgroundColor(this.themeColor)
  3517. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3518. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3519. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3520. })
  3521. .onClick(() => {
  3522. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3523. if (this.hasSelectedDirectories()) {
  3524. ToastUtil.showToast('文件夹不支持合并')
  3525. return
  3526. }
  3527. if(ArrayUtil.isNotEmpty(selectedMediaFiles)&&Utility.isMerge(selectedMediaFiles,this.packName)){
  3528. this.isMergeAudio = !this.isMergeAudio
  3529. }else{
  3530. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3531. }
  3532. })
  3533. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3534. .width(45)
  3535. .height(45)
  3536. .fontSize(10)
  3537. .margin({ top: 10, bottom: 10, right: 6 })
  3538. .backgroundColor(this.themeColor)
  3539. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3540. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3541. .onClick(async () => {
  3542. this.longItemFilePath = ''
  3543. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3544. if (ArrayUtil.isEmpty(selectedMediaFiles)) {
  3545. ToastUtil.showToast('请先选择音频文件')
  3546. return
  3547. }
  3548. await this.openAddToPlaylistDialog(selectedMediaFiles)
  3549. })
  3550. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3551. // .width(45)
  3552. // .height(45)
  3553. // .fontSize(10)
  3554. // .margin({ top: 10, bottom: 10, right: 6 })
  3555. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3556. // .backgroundColor(this.themeColor)
  3557. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3558. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3559. // })
  3560. // .onClick(() => {
  3561. // this.isFixMessy = !this.isFixMessy
  3562. // })
  3563. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3564. // .width('35%')
  3565. // .height(60)
  3566. // .id('music_cut')
  3567. // .margin({ top: 10, bottom: 10, right: 6 })
  3568. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3569. // .backgroundColor(this.themeColor)
  3570. // .onClick(() => {
  3571. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3572. // })
  3573. //
  3574. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3575. // .width('35%')
  3576. // .height(60)
  3577. // .id('music_cut_current')
  3578. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3579. // .margin({ top: 10, bottom: 10, right: 6 })
  3580. // .backgroundColor(this.themeColor)
  3581. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3582. // .onClick(() => {
  3583. //
  3584. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3585. // })
  3586. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3587. // .width('35%')
  3588. // .height(60)
  3589. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3590. // .margin({ top: 10, bottom: 10, right: 6 })
  3591. // .backgroundColor(this.themeColor)
  3592. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3593. // .onClick(() => {
  3594. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3595. // })
  3596. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3597. .width(45)
  3598. .height(45)
  3599. .fontSize(10)
  3600. .margin({ top: 10, bottom: 10, right: 6 })
  3601. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3602. .backgroundColor(this.themeColor)
  3603. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3604. .onClick(() => {
  3605. this.showWarnIsDelete()
  3606. })
  3607. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3608. .width(45)
  3609. .height(45)
  3610. .fontSize(10)
  3611. .margin({ top: 10, bottom: 10, right: 6 })
  3612. .backgroundColor(this.themeColor)
  3613. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3614. .onClick(() => {
  3615. this.selectedFiles = [];
  3616. this.isAllSelected = false
  3617. this.isMultiSelect = false
  3618. })
  3619. }
  3620. .width('100%')
  3621. .justifyContent(FlexAlign.Center)
  3622. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3623. .opacity(this.isMultiSelect ? 1 : 0)
  3624. .animation({
  3625. duration: 666,
  3626. curve: 'ease-in-out' // 可选动画曲线
  3627. })
  3628. .position({ bottom: 20 }) // 将 Row 固定在底部
  3629. }
  3630. .width('100%')
  3631. .height('100%')
  3632. .alignContent(Alignment.Top)
  3633. }
  3634. .width('100%')
  3635. .height('100%')
  3636. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3637. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3638. .backgroundImagePosition(Alignment.Center)
  3639. .backdropBlur(this.blurValue)
  3640. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3641. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3642. }
  3643. }
  3644. //字母表索引
  3645. @Builder
  3646. indexBuilder(){
  3647. Column({space: 5}){
  3648. if(this.showZMIndex&&this.enableShowAlphabet){
  3649. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3650. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3651. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3652. .attributeModifier(this.alphaBetStyle)
  3653. .usingPopup(this.isTouchingAlphaBet)
  3654. .onAreaChange((old_value,new_value)=>{
  3655. this.alphabetHeight = new_value.height as number
  3656. })
  3657. .popupPosition({
  3658. x: 40,
  3659. y: this.alphabetHeight / 2
  3660. })
  3661. .onSelect((index: number) => {
  3662. void this.onSelectIndexItem(this.alphaBet[index])
  3663. })
  3664. .onTouch((event: TouchEvent) =>{
  3665. this.showAlphabetIndex()
  3666. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3667. this.isTouchingAlphaBet = false
  3668. this.hideAlphabetIndexAfterDelay(1500)
  3669. }else{
  3670. this.isTouchingAlphaBet = true
  3671. }
  3672. })
  3673. .transition(
  3674. TransitionEffect.translate({x: 10})
  3675. .combine(TransitionEffect.opacity(0.1))
  3676. .animation({
  3677. duration: 150,
  3678. curve: Curve.EaseInOut,
  3679. })
  3680. )
  3681. }
  3682. }
  3683. if(this.showFindLocation){
  3684. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3685. Blank()
  3686. .layoutWeight(1)
  3687. }
  3688. PointLightDefaultButton({
  3689. isSysBol:true,
  3690. pointColor:Color.Gray,
  3691. imageResource:$r('sys.symbol.local_fill'),
  3692. isPx: false,
  3693. builderHeight: 30,
  3694. builderWidth: 30,
  3695. })
  3696. .onClick(() =>{
  3697. void this.locateCurrentSong();
  3698. })
  3699. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3700. .margin({
  3701. bottom: this.bottomSafeHeight+100,right:10
  3702. })
  3703. }
  3704. }
  3705. .padding({
  3706. bottom: 0
  3707. })
  3708. .margin({right:5})
  3709. .position({x:'92%'})
  3710. .height('100%')
  3711. .justifyContent(FlexAlign.Center)
  3712. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3713. height: '100%',
  3714. dragBar: true,
  3715. showClose: true,
  3716. preferType: SheetType.CENTER ,
  3717. blurStyle: BlurStyle.Thin,
  3718. title: { title: '均衡器' },
  3719. onDisappear: () => {
  3720. this.isEqualizerSheet = false
  3721. }
  3722. })
  3723. }
  3724. async onSelectIndexItem(letter: string) {
  3725. await this.ensureFullListForAlphabetIndex();
  3726. const findTargetIndex = (): number => {
  3727. const songs = this.videoLocalList;
  3728. for (let i = 0; i < songs.length; i++) {
  3729. const song = songs[i];
  3730. let text = this.isShowFileName ? song.fileName :
  3731. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3732. if (this.sortType === 0 || this.sortType == 1) {
  3733. text = song.artist;
  3734. } else if (this.sortType === 2 || this.sortType == 3) {
  3735. text = song.album;
  3736. }
  3737. if (text) {
  3738. const firstPinyin = getFirstLetter(text);
  3739. if (firstPinyin && firstPinyin === letter) {
  3740. return i;
  3741. }
  3742. }
  3743. }
  3744. return -1;
  3745. };
  3746. const targetIndex = findTargetIndex();
  3747. if (targetIndex !== -1) {
  3748. if (this.isGridMusic || this.twoFingerType == 4) {
  3749. this.scroller.scrollToIndex(targetIndex, false);
  3750. } else {
  3751. this.listScroller.scrollToIndex(targetIndex);
  3752. }
  3753. }
  3754. }
  3755. private showAlphabetIndex(): void {
  3756. this.isShowAlphaBet = true;
  3757. if (this.alphaBetHideTimer) {
  3758. clearTimeout(this.alphaBetHideTimer);
  3759. this.alphaBetHideTimer = 0;
  3760. }
  3761. }
  3762. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3763. if (this.alphaBetHideTimer) {
  3764. clearTimeout(this.alphaBetHideTimer);
  3765. }
  3766. this.alphaBetHideTimer = setTimeout(() => {
  3767. if (!this.isTouchingAlphaBet) {
  3768. this.isShowAlphaBet = false;
  3769. }
  3770. this.alphaBetHideTimer = 0;
  3771. }, delayMs) as number;
  3772. }
  3773. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  3774. if (!this.showZMIndex) {
  3775. return;
  3776. }
  3777. if (this.alphaBetRebuildTimer) {
  3778. clearTimeout(this.alphaBetRebuildTimer);
  3779. }
  3780. this.alphaBetRebuildTimer = setTimeout(() => {
  3781. this.alphaBetRebuildTimer = 0;
  3782. if (this.isScrolling) {
  3783. this.alphaBetDirty = true;
  3784. return;
  3785. }
  3786. this.alphaBetDirty = false;
  3787. void this.setAlphaBet();
  3788. }, delayMs) as number;
  3789. }
  3790. private markAlphaBetDirty(): void {
  3791. if (!this.showZMIndex) {
  3792. return;
  3793. }
  3794. if (this.isMediaLibraryWarmupWindow()) {
  3795. this.alphaBetDirty = true;
  3796. this.scheduleAlphaBetRebuild(900);
  3797. return;
  3798. }
  3799. this.alphaBetDirty = true;
  3800. if (!this.isScrolling) {
  3801. this.scheduleAlphaBetRebuild(80);
  3802. }
  3803. }
  3804. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3805. if (this.isLoadingPage) {
  3806. return;
  3807. }
  3808. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3809. return;
  3810. }
  3811. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3812. return;
  3813. }
  3814. if (this.modeType !== 0 && this.modeType !== 1) {
  3815. return;
  3816. }
  3817. this.isLoadingPage = true;
  3818. try {
  3819. const options: PageQueryOptions = {
  3820. pageIndex: 0,
  3821. pageSize: this.totalCount,
  3822. sortType: this.sortType,
  3823. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3824. isShowFileName: this.isShowFileName
  3825. };
  3826. if (this.modeType === 0) {
  3827. options.parentPath = this.currentPath;
  3828. }
  3829. let result: PageQueryResult;
  3830. if (this.modeType === 0) {
  3831. result = await this.table.queryByParentPathPaged(options);
  3832. const dbItems = this.filterOutLocalIsoItems(result.items);
  3833. if (!this.isSearchMode) {
  3834. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3835. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  3836. result.items = [...directories, ...isoItems, ...dbItems];
  3837. } else {
  3838. result.items = dbItems;
  3839. }
  3840. } else {
  3841. result = await this.table.queryMediaLibraryPaged(options);
  3842. }
  3843. this.videoLocalList = result.items;
  3844. this.dataSource.pushArrayData(this.videoLocalList);
  3845. this.pageCache.clear();
  3846. this.pageHasMoreCache.clear();
  3847. this.pageTotalCountCache.clear();
  3848. this.prefetchingPages.clear();
  3849. this.currentPage = 0;
  3850. this.totalCount = this.modeType === 0 ? result.items.length : result.totalCount;
  3851. this.hasMoreData = false;
  3852. this.lastScrollTriggerPage = -1;
  3853. this.lastVisibleEndIndex = -1;
  3854. this.isPagingTransition = false;
  3855. if (this.pagingScheduleTimer) {
  3856. clearTimeout(this.pagingScheduleTimer);
  3857. this.pagingScheduleTimer = 0;
  3858. }
  3859. if (this.modeType === 1) {
  3860. this.mediaKuCount = result.totalCount;
  3861. }
  3862. this.setButtonStatus();
  3863. this.markAlphaBetDirty();
  3864. } catch (err) {
  3865. const error = err as Error;
  3866. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3867. } finally {
  3868. this.isLoadingPage = false;
  3869. }
  3870. }
  3871. // 找到对应字母表的索引
  3872. findAlphaBetIndex(song: VideoItem):number{
  3873. let text = this.isShowFileName?song.fileName:
  3874. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3875. if(this.sortType === 0||this.sortType==1){
  3876. text = song.artist
  3877. }else if(this.sortType === 2||this.sortType==3){
  3878. text = song.album
  3879. }
  3880. if(text){
  3881. let firstLetter = getFirstLetter(text)
  3882. for(let i=0;i<this.alphaBet.length;i++){
  3883. if(this.alphaBet[i] === firstLetter){
  3884. return i
  3885. }
  3886. }
  3887. }
  3888. return 0
  3889. }
  3890. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  3891. const items: Array<AlphaTaskItem> = []
  3892. for (const song of songs) {
  3893. items.push({
  3894. type: song.type,
  3895. name: song.name,
  3896. pyStr: song.pyStr,
  3897. fileName: song.fileName,
  3898. artist: song.artist,
  3899. album: song.album
  3900. })
  3901. }
  3902. return items
  3903. }
  3904. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  3905. const taskItems = this.buildAlphaTaskItems(songs)
  3906. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  3907. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  3908. if (version !== this.alphaBetBuildVersion) {
  3909. return
  3910. }
  3911. this.alphaBet = result
  3912. if (this.videoLocalList.length > 0) {
  3913. this.selectAlphaBetIndex = 0
  3914. }
  3915. }
  3916. async setAlphaBet(){
  3917. if(!this.showZMIndex){
  3918. return
  3919. }
  3920. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  3921. await this.refreshAlphaBetFromMediaLibrary()
  3922. return
  3923. }
  3924. try {
  3925. const songs = this.videoLocalList
  3926. if (songs.length > 40000) {
  3927. this.alphaBet = []
  3928. return
  3929. }
  3930. const version = ++this.alphaBetBuildVersion
  3931. await this.buildAlphaBetByTask(songs, version)
  3932. } catch (e) {
  3933. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3934. }
  3935. }
  3936. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  3937. if (this.totalCount <= 0) {
  3938. return
  3939. }
  3940. if (this.totalCount > 40000) {
  3941. this.alphaBet = []
  3942. return
  3943. }
  3944. const keyword = this.isSearchMode ? this.searchText : ''
  3945. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  3946. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  3947. return
  3948. }
  3949. const result = await this.table.queryMediaLibraryPaged({
  3950. pageIndex: 0,
  3951. pageSize: this.totalCount,
  3952. sortType: this.sortType,
  3953. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3954. isShowFileName: this.isShowFileName
  3955. })
  3956. const version = ++this.alphaBetBuildVersion
  3957. await this.buildAlphaBetByTask(result.items, version)
  3958. this.alphaBetCacheKey = cacheKey
  3959. }
  3960. @Builder
  3961. topTitleBar(){
  3962. Column() {
  3963. Row({ space: 15 }) {
  3964. if (!this.isSearchMode ) {
  3965. //左侧滑动按钮
  3966. TitleBarPointLightButton({
  3967. iconResource: this.rightTopImage,
  3968. iconSize: 25,
  3969. pointColor: this.themeColor,
  3970. clickScale: 0.6,
  3971. clickHandler: () => {
  3972. this.triggerSwipeBackWithAnimation()
  3973. }
  3974. })
  3975. }else{
  3976. //左侧搜索返回按钮
  3977. TitleBarPointLightButton({
  3978. iconResource: $r('sys.symbol.chevron_left'),
  3979. iconSize: 25,
  3980. pointColor: this.themeColor,
  3981. clickScale: 0.6,
  3982. clickHandler: () => {
  3983. this.isSearchMode = false
  3984. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3985. this.searchText = ''
  3986. this.getSortedFiles(this.currentPath)
  3987. return
  3988. }
  3989. this.onSearchInput('')
  3990. }
  3991. })
  3992. .margin({bottom:5})
  3993. }
  3994. if (!this.isSearchMode) {
  3995. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3996. .margin({left:3,right:10})
  3997. .fontColor($r('app.color.text_color'))
  3998. .fontSize(this.twoFingerType==3?17:16)
  3999. .maxLines(1)
  4000. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4001. .layoutWeight(1)
  4002. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4003. }
  4004. //搜索框
  4005. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  4006. .searchButton('搜索',{fontColor:this.themeColor})
  4007. .searchIcon({
  4008. src: $r('sys.media.ohos_ic_public_search_filled')
  4009. })
  4010. .cancelButton({
  4011. style: CancelButtonStyle.CONSTANT,
  4012. icon: {
  4013. src: $r('sys.media.ohos_ic_public_cancel_filled')
  4014. }
  4015. })
  4016. .layoutWeight(1)
  4017. .height(40)
  4018. .maxLength(20)
  4019. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  4020. .placeholderColor(Color.Grey)
  4021. .placeholderFont({ size: 14, weight: 400 })
  4022. .textFont({ size: 14, weight: 400 })
  4023. .onSubmit((value: string) => {
  4024. console.log('onecold onSubmit ='+value)
  4025. this.searchController.stopEditing()
  4026. if(this.modeType==0){
  4027. this.modeType =1//如果是首页 切换到媒体库搜索
  4028. }
  4029. this.commitSearchHistory(value)
  4030. this.onSearchInput(this.searchText);
  4031. })
  4032. .onChange((value: string) => {
  4033. console.log('onecold onChange ='+value)
  4034. if(this.modeType==0){
  4035. this.modeType =1//如果是首页 切换到媒体库搜索
  4036. }
  4037. this.onSearchInput(value);
  4038. })
  4039. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  4040. .animation({ duration: 300, curve: Curve.Ease })
  4041. //搜索按钮
  4042. if (!this.isSearchMode) {
  4043. TitleBarPointLightButton({
  4044. iconResource: $r('sys.symbol.magnifyingglass'),
  4045. iconSize: 25,
  4046. pointColor: this.themeColor,
  4047. clickScale: 0.6,
  4048. clickHandler: () => {
  4049. this.isSearchMode = true
  4050. this.loadSearchHistory()
  4051. }
  4052. })
  4053. //排序按钮
  4054. TitleBarPointLightButton({
  4055. iconResource: $r('sys.symbol.list_number'),
  4056. iconSize: 25,
  4057. pointColor: this.themeColor,
  4058. clickScale: 0.6
  4059. })
  4060. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  4061. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  4062. //添加按钮
  4063. TitleBarPointLightButton({
  4064. iconResource: $r('sys.symbol.plus'),
  4065. iconSize: 25,
  4066. pointColor: this.themeColor,
  4067. clickScale: 0.6,
  4068. clickHandler: () => {
  4069. this.showAddSheet = !this.showAddSheet;
  4070. }
  4071. })
  4072. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  4073. .bindSheet($$this.showAddSheet, this.addSheet(), {
  4074. height: SheetSize.FIT_CONTENT,
  4075. dragBar: true,
  4076. showClose: true,
  4077. preferType: SheetType.CENTER ,
  4078. title: {
  4079. title: '导入音乐'
  4080. }
  4081. })
  4082. }
  4083. }
  4084. }
  4085. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  4086. .width('100%')
  4087. .translate({
  4088. x: 0,
  4089. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  4090. })
  4091. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  4092. .animation({
  4093. duration: 240,
  4094. curve: Curve.EaseInOut
  4095. })
  4096. }
  4097. @Builder
  4098. addSheet() {
  4099. Scroll() {
  4100. Column() {
  4101. Column() {
  4102. Row() {
  4103. SymbolGlyph($r('sys.symbol.info_circle'))
  4104. .fontSize(22)
  4105. .fontColor([this.themeColor])
  4106. .alignSelf(ItemAlign.Center)
  4107. .margin({ left: 8 })
  4108. Text('导入音乐复制到DownLoad目录')
  4109. .margin({ left: 8 })
  4110. .fontSize(14)
  4111. .fontColor($r('app.color.text_color'))
  4112. .fontWeight(480)
  4113. .layoutWeight(1)
  4114. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  4115. .selectedColor(this.themeColor)
  4116. .switchPointColor(Color.White)
  4117. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4118. .margin({ right: 2 })
  4119. .onChange((checked: boolean) => {
  4120. this.isCopyFileToDownLoad = checked;
  4121. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  4122. })
  4123. .width(50)
  4124. .height(30);
  4125. }
  4126. .height(72)
  4127. .padding({ left:8,right:8 })
  4128. }
  4129. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4130. .backgroundColor($r('app.color.start_window_background'))
  4131. .borderRadius(15)
  4132. .width('85%')
  4133. .margin({
  4134. top: 10,
  4135. bottom: 10
  4136. })
  4137. .padding(0)
  4138. .border({
  4139. color: Color.White,
  4140. width: 1.8
  4141. })
  4142. Menu() {
  4143. MenuItem({
  4144. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  4145. content: "新建文件夹"
  4146. })
  4147. .backgroundColor($r('app.color.silvery'))
  4148. .border({
  4149. width: { bottom: 1 },
  4150. color: '#12ec5c87'
  4151. })
  4152. .margin(10)
  4153. .height(60)
  4154. .padding({left:15,right:15})
  4155. .onClick(async () => {
  4156. this.showMkDialog()
  4157. this.showAddSheet = !this.showAddSheet
  4158. })
  4159. MenuItem({
  4160. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  4161. content: $r('app.string.import_from_files')
  4162. })
  4163. .padding({left:15,right:15})
  4164. .backgroundColor($r('app.color.silvery'))
  4165. .border({
  4166. width: { bottom: 1 },
  4167. color: '#12ec5c87'
  4168. })
  4169. .margin(10)
  4170. .height(60)
  4171. .onClick(async () => {
  4172. this.callFilePickerSelectFile()
  4173. this.showAddSheet = !this.showAddSheet
  4174. })
  4175. MenuItem({
  4176. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  4177. content: '全选导入'
  4178. // content: '从下载文件夹导入(路径:Download/' +
  4179. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  4180. })
  4181. .padding({left:15,right:15})
  4182. .backgroundColor($r('app.color.silvery'))
  4183. .border({
  4184. width: { bottom: 1 },
  4185. color: '#12ec5c87'
  4186. })
  4187. .margin(10)
  4188. .height(60)
  4189. .onClick(async () => {
  4190. this.goSelectMusic()
  4191. this.showAddSheet = !this.showAddSheet
  4192. })
  4193. MenuItem({
  4194. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  4195. content: '自动导入教程'
  4196. })
  4197. .padding({left:15,right:15})
  4198. .backgroundColor($r('app.color.silvery'))
  4199. .border({
  4200. width: { bottom: 1 },
  4201. color: '#12ec5c87'
  4202. })
  4203. .margin(10)
  4204. .height(60)
  4205. .onClick(async () => {
  4206. this.showTips()
  4207. this.showAddSheet = !this.showAddSheet
  4208. })
  4209. MenuItem({
  4210. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  4211. content: '导入疑问'
  4212. })
  4213. .height(60)
  4214. .padding({left:15,right:15})
  4215. .backgroundColor($r('app.color.silvery'))
  4216. .border({
  4217. width: { bottom: 1 },
  4218. color: '#12ec5c87'
  4219. })
  4220. .margin(10)
  4221. .onClick(async () => {
  4222. this.showProblomTips()
  4223. this.showAddSheet = !this.showAddSheet
  4224. })
  4225. }.attributeModifier(new MenuModifier())
  4226. .margin({bottom:30})
  4227. .width('90%')
  4228. .borderRadius(15)
  4229. }
  4230. .layoutWeight(1)
  4231. }
  4232. }
  4233. async showProblomTips() {
  4234. try {
  4235. this.getUIContext().getPromptAction().showDialog({
  4236. title: '导入疑问',
  4237. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  4238. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  4239. buttons: [
  4240. {
  4241. text: '知道了',
  4242. color: '#000000'
  4243. },
  4244. ]
  4245. }, (err, data) => {
  4246. if (err) {
  4247. console.error('showDialog err: ' + err);
  4248. return;
  4249. }
  4250. console.info('showDialog success callback, click button: ' + data.index);
  4251. });
  4252. } catch (error) {
  4253. let message = (error as BusinessError).message;
  4254. let code = (error as BusinessError).code;
  4255. console.error(`showDialog args error code is ${code}, message is ${message}`);
  4256. };
  4257. }
  4258. @Builder
  4259. TagsContentCoverBuilder() {
  4260. Scroll() {
  4261. Column() {
  4262. TagsContentCover(
  4263. {
  4264. selectedFiles:this.selectedFiles,
  4265. isOneKeyTags:this.isOneKeyTags,
  4266. onSeePath:(path:string)=>{
  4267. this.modeType = 0
  4268. this.deleteCache(path)
  4269. this.getSortedFiles(path)
  4270. },
  4271. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4272. this.isMultiSelect = false
  4273. if(result){//如果嵌入成功,更新数据
  4274. this.listRefreshKey++
  4275. setTimeout(()=>{
  4276. this.doUpdateData()
  4277. },500)
  4278. }
  4279. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4280. if(deleteCache_path){
  4281. this.deleteCache(deleteCache_path)
  4282. }
  4283. }
  4284. }
  4285. )
  4286. }
  4287. }
  4288. .width('100%')
  4289. .height('100%')
  4290. }
  4291. @Builder
  4292. FixMessyViewBuilder() {
  4293. Scroll() {
  4294. Column() {
  4295. FixMessyView(
  4296. {
  4297. selectedFiles:this.selectedFiles,
  4298. isFixMessy:this.isFixMessy,
  4299. onFixResult:(result: boolean)=>{
  4300. this.isMultiSelect = false
  4301. if(result){//如果嵌入成功,更新数据
  4302. this.deleteCache(this.currentPath)
  4303. this.doUpdateData()
  4304. }
  4305. }
  4306. }
  4307. )
  4308. }
  4309. }
  4310. .width('100%')
  4311. .height('100%')
  4312. }
  4313. //剪辑音频
  4314. @Builder
  4315. EditAudioBuilder(item:VideoItem) {
  4316. Scroll() {
  4317. Column() {
  4318. EditAudio(
  4319. {
  4320. mVideoItem:item,
  4321. currentPath:this.currentPath,
  4322. videoUrl:this.videoUrl,
  4323. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4324. currentTime:this.currentTime,
  4325. progressValue:this.progressValue,
  4326. onBack:()=>{
  4327. this.isEditAudio = !this.isEditAudio
  4328. },
  4329. onSeeOutputPath:(outPutPath:string)=>{
  4330. this.isEditAudio = !this.isEditAudio
  4331. this.longItemFilePath = ''
  4332. this.modeType = 0
  4333. this.isShowFileName = true
  4334. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4335. },
  4336. onPlayOrPause:()=>{
  4337. if(this.videoUrl==item.filePath){
  4338. this.playOrPause()
  4339. }else{//如果不是当前播放的,则播放该文件
  4340. this.videoUrl==item.filePath
  4341. this.doPlay(item,0,false,true)
  4342. }
  4343. },
  4344. onSliderChange:(value:number)=>{
  4345. if(this.videoUrl!=item.filePath){
  4346. this.videoUrl==item.filePath
  4347. return
  4348. }
  4349. this.isSeekTo = true;
  4350. this.mDestroyPage = false;
  4351. this.showLoadIng();
  4352. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4353. let seekValue = value * (this.getActiveDuration() / 100);
  4354. this.seekTo(seekValue + "");
  4355. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4356. this.isSeekTo = false;
  4357. },
  4358. onResult:(result: boolean,outPath:string)=>{
  4359. if(result){//如果剪辑成功,更新数据
  4360. this.doUpdateData()
  4361. }else{
  4362. ToastUtil.showToast('剪辑失败')
  4363. }
  4364. }
  4365. }
  4366. )
  4367. }
  4368. }
  4369. .width('100%')
  4370. .height('100%')
  4371. }
  4372. //提取伴奏
  4373. @Builder
  4374. ConverterBuilder(item:VideoItem) {
  4375. Scroll() {
  4376. Column() {
  4377. AudioFormatConverter(
  4378. {
  4379. mVideoItem:item,
  4380. videoUrl:this.videoUrl,
  4381. currentPath:this.currentPath,
  4382. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4383. currentTime:this.currentTime,
  4384. progressValue:this.progressValue,
  4385. onBack:()=>{
  4386. this.isConverter = !this.isConverter
  4387. this.longItemFilePath = ''
  4388. },
  4389. onPlayOrPause:()=>{
  4390. if(this.videoUrl==item.filePath){
  4391. this.playOrPause()
  4392. }else{//如果不是当前播放的,则播放该文件
  4393. this.videoUrl==item.filePath
  4394. this.doPlay(item,0,false,true)
  4395. }
  4396. },
  4397. onSeeOutputPath:(outPutPath:string)=>{
  4398. this.isConverter = !this.isConverter
  4399. this.longItemFilePath = ''
  4400. this.modeType = 0
  4401. this.isShowFileName = true
  4402. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4403. },
  4404. onSliderChange:(value:number)=>{
  4405. if(this.videoUrl!=item.filePath){
  4406. this.videoUrl==item.filePath
  4407. return
  4408. }
  4409. this.isSeekTo = true;
  4410. this.mDestroyPage = false;
  4411. this.showLoadIng();
  4412. let seekValue = value * (this.getActiveDuration() / 100);
  4413. this.seekTo(seekValue + "");
  4414. this.isSeekTo = false;
  4415. },
  4416. onResult:(result: boolean,outPath:string)=>{
  4417. if(result){//如果成功,更新数据
  4418. this.doUpdateData()
  4419. }else{
  4420. ToastUtil.showToast('格式转化失败')
  4421. }
  4422. }
  4423. }
  4424. )
  4425. }
  4426. }
  4427. .width('100%')
  4428. .height('100%')
  4429. }
  4430. //提取伴奏
  4431. @Builder
  4432. ExtractAccBuilder(item:VideoItem) {
  4433. Scroll() {
  4434. Column() {
  4435. ExtractAccompaniment(
  4436. {
  4437. mVideoItem:item,
  4438. currentPath:this.currentPath,
  4439. videoUrl:this.videoUrl,
  4440. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4441. currentTime:this.currentTime,
  4442. progressValue:this.progressValue,
  4443. onBack:()=>{
  4444. this.isExtractAcc = !this.isExtractAcc
  4445. this.longItemFilePath = ''
  4446. },
  4447. onPlayOrPause:()=>{
  4448. if(this.videoUrl==item.filePath){
  4449. this.playOrPause()
  4450. }else{//如果不是当前播放的,则播放该文件
  4451. this.videoUrl==item.filePath
  4452. this.doPlay(item,0,false,true)
  4453. }
  4454. },
  4455. onSeeOutputPath:(outPutPath:string)=>{
  4456. this.isExtractAcc = !this.isExtractAcc
  4457. this.longItemFilePath = ''
  4458. this.modeType = 0
  4459. this.isShowFileName = true
  4460. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4461. },
  4462. onSliderChange:(value:number)=>{
  4463. if(this.videoUrl!=item.filePath){
  4464. this.videoUrl==item.filePath
  4465. return
  4466. }
  4467. this.isSeekTo = true;
  4468. this.mDestroyPage = false;
  4469. this.showLoadIng();
  4470. let seekValue = value * (this.getActiveDuration() / 100);
  4471. this.seekTo(seekValue + "");
  4472. this.isSeekTo = false;
  4473. },
  4474. onResult:(result: boolean,outPath:string)=>{
  4475. if(result){//如果成功,更新数据
  4476. this.doUpdateData()
  4477. }else{
  4478. ToastUtil.showToast('提取伴奏失败')
  4479. }
  4480. }
  4481. }
  4482. )
  4483. }
  4484. }
  4485. .width('100%')
  4486. .height('100%')
  4487. }
  4488. //AI人声分离
  4489. @Builder
  4490. AiBuilder(item:VideoItem) {
  4491. Scroll() {
  4492. Column() {
  4493. AIVoiceSeparation(
  4494. {
  4495. mVideoItem:item,
  4496. videoUrl:this.videoUrl,
  4497. currentPath:this.currentPath,
  4498. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4499. currentTime:this.currentTime,
  4500. progressValue:this.progressValue,
  4501. onBack:()=>{
  4502. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4503. this.longItemFilePath = ''
  4504. },
  4505. onPlayOrPause:()=>{
  4506. if(this.videoUrl==item.filePath||this.isPlaying){
  4507. this.playOrPause()
  4508. }else{//如果不是当前播放的,则播放该文件
  4509. this.videoUrl==item.filePath
  4510. this.doPlay(item,0,false,true)
  4511. }
  4512. },
  4513. onPlayPath:(path:string)=>{
  4514. this.videoUrl==path
  4515. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4516. if(itemP)
  4517. this.doPlay(itemP,0,false,true)
  4518. },
  4519. onSeeOutputPath:(outPutPath:string)=>{
  4520. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4521. this.longItemFilePath = ''
  4522. this.modeType = 0
  4523. this.isShowFileName = true
  4524. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4525. },
  4526. onSliderChange:(value:number)=>{
  4527. if(this.videoUrl!=item.filePath){
  4528. this.videoUrl==item.filePath
  4529. return
  4530. }
  4531. this.isSeekTo = true;
  4532. this.mDestroyPage = false;
  4533. this.showLoadIng();
  4534. let seekValue = value * (this.getActiveDuration() / 100);
  4535. this.seekTo(seekValue + "");
  4536. this.isSeekTo = false;
  4537. },
  4538. onResult:(result: boolean,outPath:string)=>{
  4539. if(result){//如果成功,更新数据
  4540. this.doUpdateData()
  4541. }else{
  4542. ToastUtil.showToast('Ai人声分离失败')
  4543. }
  4544. }
  4545. }
  4546. )
  4547. }
  4548. }
  4549. .width('100%')
  4550. .height('100%')
  4551. }
  4552. //变速变调
  4553. @Builder
  4554. ChangeToneBuilder(item:VideoItem) {
  4555. Scroll() {
  4556. Column() {
  4557. ChangeTone(
  4558. {
  4559. mVideoItem:item,
  4560. currentPath:this.currentPath,
  4561. videoUrl:this.videoUrl,
  4562. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4563. currentTime:this.currentTime,
  4564. progressValue:this.progressValue,
  4565. onBack:()=>{
  4566. this.isChangeTone = !this.isChangeTone
  4567. this.longItemFilePath = ''
  4568. },
  4569. onPlayOrPause:()=>{
  4570. if(this.videoUrl==item.filePath){
  4571. this.playOrPause()
  4572. }else{//如果不是当前播放的,则播放该文件
  4573. this.videoUrl==item.filePath
  4574. this.doPlay(item,0,false,true)
  4575. }
  4576. },
  4577. onSeeOutputPath:(outPutPath:string)=>{
  4578. this.isChangeTone = !this.isChangeTone
  4579. this.longItemFilePath = ''
  4580. this.modeType = 0
  4581. this.isShowFileName = true
  4582. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4583. },
  4584. onSliderChange:(value:number)=>{
  4585. if(this.videoUrl!=item.filePath){
  4586. this.videoUrl==item.filePath
  4587. return
  4588. }
  4589. this.isSeekTo = true;
  4590. this.mDestroyPage = false;
  4591. this.showLoadIng();
  4592. let seekValue = value * (this.getActiveDuration() / 100);
  4593. this.seekTo(seekValue + "");
  4594. this.isSeekTo = false;
  4595. },
  4596. onResult:(result: boolean,outPath:string)=>{
  4597. if(result){//如果成功,更新数据
  4598. this.doUpdateData()
  4599. }else{
  4600. ToastUtil.showToast('变速变调失败')
  4601. }
  4602. }
  4603. }
  4604. )
  4605. }
  4606. }
  4607. .width('100%')
  4608. .height('100%')
  4609. }
  4610. //提取视频中的音频
  4611. @Builder
  4612. extractAudioFromVideoBuilder(item:VideoItem) {
  4613. Scroll() {
  4614. Column() {
  4615. ExtractAudioFromVideo(
  4616. {
  4617. mVideoItem:item,
  4618. currentPath:this.currentPath,
  4619. videoUrl:this.videoUrl,
  4620. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4621. currentTime:this.currentTime,
  4622. progressValue:this.progressValue,
  4623. onBack:()=>{
  4624. this.isExtractAudio = !this.isExtractAudio
  4625. this.longItemFilePath = ''
  4626. },
  4627. onPlayOrPause:()=>{
  4628. if(this.videoUrl==item.filePath){
  4629. this.playOrPause()
  4630. }else{//如果不是当前播放的,则播放该文件
  4631. this.videoUrl==item.filePath
  4632. this.doPlay(item,0,false,true)
  4633. }
  4634. },
  4635. onSeeOutputPath:(outPutPath:string)=>{
  4636. this.isExtractAudio = !this.isExtractAudio
  4637. this.longItemFilePath = ''
  4638. this.modeType = 0
  4639. this.isShowFileName = true
  4640. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4641. },
  4642. onSliderChange:(value:number)=>{
  4643. if(this.videoUrl!=item.filePath){
  4644. this.videoUrl==item.filePath
  4645. return
  4646. }
  4647. this.isSeekTo = true;
  4648. this.mDestroyPage = false;
  4649. this.showLoadIng();
  4650. let seekValue = value * (this.getActiveDuration() / 100);
  4651. this.seekTo(seekValue + "");
  4652. this.isSeekTo = false;
  4653. },
  4654. onResult:(result: boolean,outPath:string)=>{
  4655. if(result){//如果成功,更新数据
  4656. this.doUpdateData()
  4657. }else{
  4658. ToastUtil.showToast('提取音频失败')
  4659. }
  4660. }
  4661. }
  4662. )
  4663. }
  4664. }
  4665. .width('100%')
  4666. .height('100%')
  4667. }
  4668. //合并音频
  4669. @Builder
  4670. MergeAudioBuilder() {
  4671. Scroll() {
  4672. Column() {
  4673. MergeAudio(
  4674. {
  4675. videoUrl:this.videoUrl,
  4676. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4677. currentPath:this.currentPath,
  4678. selectedFiles:this.selectedFiles,
  4679. currentTime:this.currentTime,
  4680. progressValue:this.progressValue,
  4681. onBack:()=>{
  4682. this.isMergeAudio = !this.isMergeAudio
  4683. this.longItemFilePath = ''
  4684. },
  4685. // onPlayPath:(path:string)=>{
  4686. // if(this.videoUrl==item.filePath){
  4687. // this.playOrPause()
  4688. // }else{//如果不是当前播放的,则播放该文件
  4689. // this.videoUrl==item.filePath
  4690. // this.doPlay(item,0,false,true)
  4691. // }
  4692. //
  4693. // },
  4694. onSeeOutputPath:(outPutPath:string)=>{
  4695. this.isMergeAudio = !this.isMergeAudio
  4696. this.longItemFilePath = ''
  4697. this.modeType = 0
  4698. this.isShowFileName = true
  4699. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4700. },
  4701. onResult:(result: boolean,outPath:string)=>{
  4702. if(result){//如果成功,更新数据
  4703. this.doUpdateData()
  4704. }else{
  4705. if(this.selectedFiles.length>=3){
  4706. ToastUtil.showToast('合并数量太多导致失败')
  4707. }else{
  4708. ToastUtil.showToast('合并失败')
  4709. }
  4710. }
  4711. }
  4712. }
  4713. )
  4714. }
  4715. }
  4716. .width('100%')
  4717. .height('100%')
  4718. }
  4719. asyncCurrentPathData() {
  4720. if (this.modeType == 0) {
  4721. workerInstance.postMessage({
  4722. code: 1,
  4723. data1: this.context,
  4724. data2: this.currentPath,
  4725. data3: this.lockPath,
  4726. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4727. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4728. });
  4729. }
  4730. }
  4731. // 处理文件选择的函数
  4732. handleFileSelection(item: VideoItem, checked: boolean) {
  4733. if (!this.isSelectableLocalItem(item)) {
  4734. return
  4735. }
  4736. const exists = this.isLocalItemSelected(item)
  4737. if (checked) {
  4738. if (!exists) {
  4739. this.selectedFiles = [...this.selectedFiles, item];
  4740. }
  4741. } else if (exists) {
  4742. this.selectedFiles = this.selectedFiles.filter(selected => selected.filePath !== item.filePath);
  4743. if (this.selectedFiles.length === 0) {
  4744. this.isAllSelected = false
  4745. }
  4746. }
  4747. this.syncLocalSelectionState()
  4748. }
  4749. private deleteComponentId: number = 0
  4750. private closeDeleteDialog(afterClose?: () => void): void {
  4751. if (this.deleteComponentId > 0) {
  4752. try {
  4753. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4754. } catch (_error) {
  4755. }
  4756. this.deleteComponentId = 0
  4757. }
  4758. if (afterClose) {
  4759. setTimeout(() => {
  4760. afterClose()
  4761. }, 16)
  4762. }
  4763. }
  4764. private resetDeleteSelectionState(): void {
  4765. this.isMultiSelect = false
  4766. this.selectedFiles = []
  4767. this.isAllSelected = false
  4768. }
  4769. private removeDisplayedLocalItemsByKeys(deletedKeys: Set<string>): void {
  4770. for (let index = this.dataSource.dataArray.length - 1; index >= 0; index--) {
  4771. const item = this.dataSource.dataArray[index]
  4772. if (item && deletedKeys.has(item.filePath)) {
  4773. this.dataSource.deleteData(index)
  4774. }
  4775. }
  4776. }
  4777. private async removeDeletedLocalItemsLocally(deletedItems: Array<VideoItem>): Promise<void> {
  4778. if (ArrayUtil.isEmpty(deletedItems) || this.modeType !== 0) {
  4779. return
  4780. }
  4781. const deletedKeys: Set<string> = new Set<string>()
  4782. for (let i = 0; i < deletedItems.length; i++) {
  4783. const item = deletedItems[i]
  4784. if (StrUtil.isNotEmpty(item?.filePath)) {
  4785. deletedKeys.add(item.filePath)
  4786. }
  4787. }
  4788. if (deletedKeys.size <= 0) {
  4789. return
  4790. }
  4791. const nextVideoLocalList = this.videoLocalList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4792. const nextDirList = this.dirList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4793. const nextFilteredList = this.filteredList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4794. const removedCount = this.videoLocalList.length - nextVideoLocalList.length
  4795. this.videoLocalList = nextVideoLocalList
  4796. this.dirList = nextDirList
  4797. this.filteredList = nextFilteredList
  4798. this.removeDisplayedLocalItemsByKeys(deletedKeys)
  4799. if (removedCount > 0 && this.totalCount > 0) {
  4800. this.totalCount = Math.max(0, this.totalCount - removedCount)
  4801. }
  4802. this.pageCache.clear()
  4803. this.pageHasMoreCache.clear()
  4804. this.pageTotalCountCache.clear()
  4805. this.setButtonStatus()
  4806. this.markAlphaBetDirty()
  4807. this.syncLocalSelectionState()
  4808. this.addCache(this.currentPath, nextVideoLocalList)
  4809. if (this.currentPath === this.rootPath) {
  4810. this.addCache(this.currentPath + '_dirList', nextDirList)
  4811. }
  4812. this.deleteStringCache(this.currentPath + '_hash')
  4813. await this.saveCacheToStorage()
  4814. }
  4815. //多选删除文件
  4816. showWarnIsDelete(){
  4817. this.getUIContext().getPromptAction().openCustomDialog({
  4818. builder: () => {
  4819. this.deleteComptentBuilder()
  4820. },
  4821. isModal:true,
  4822. showInSubWindow:false,
  4823. maskColor: Color.Transparent,
  4824. dialogTransition: // 设置弹窗内容显示的过渡效果
  4825. TransitionEffect.translate({ x: 0, y: 120, z: 0 })
  4826. .combine(TransitionEffect.opacity(0.01))
  4827. .animation({ duration: 260, curve: Curve.EaseOut }),
  4828. maskTransition: // 设置蒙层显示的过渡效果
  4829. TransitionEffect.opacity(0)
  4830. .animation({ duration: 220, curve: Curve.EaseOut })
  4831. }).then((dialogId: number) => {
  4832. this.deleteComponentId = dialogId
  4833. })
  4834. .catch((error: BusinessError) => {
  4835. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4836. })
  4837. }
  4838. @Builder
  4839. deleteComptentBuilder(){
  4840. DeleteComptent({
  4841. selectedFiles:this.selectedFiles,
  4842. isPlaylistMode: this.modeType == 4,
  4843. playlistId: this.currentSongListID,
  4844. onCancel:()=>{
  4845. this.closeDeleteDialog(() => {
  4846. this.resetDeleteSelectionState()
  4847. })
  4848. },
  4849. onDeleteResult:(result: boolean)=>{
  4850. const deletedItems = [...this.selectedFiles]
  4851. this.closeDeleteDialog(() => {
  4852. this.resetDeleteSelectionState()
  4853. if(result){//如果删除成功,更新数据
  4854. if (this.modeType == 4) {
  4855. this.doSongListTask()
  4856. } else {
  4857. void this.removeDeletedLocalItemsLocally(deletedItems)
  4858. }
  4859. }
  4860. })
  4861. }
  4862. })
  4863. }
  4864. //多选移动文件
  4865. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4866. Logger.info('onecold showCutDialogForMultipleFiles')
  4867. let mList: Array<string> = []
  4868. let rPath = this.rootPath
  4869. if (isCurrent) {
  4870. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4871. rPath = this.currentPath
  4872. } else {
  4873. mList = Utility.getNameList(this.dirList);
  4874. rPath = this.rootPath
  4875. }
  4876. let dataBean = new BubbleBean();
  4877. dataBean.data = mList;
  4878. dataBean.color = this.themeColor
  4879. dataBean.onItemClick = (i) => {
  4880. const newDirPath = rPath + '/' + mList[i];
  4881. // Logger.info('newDirPath = ' + newDirPath)
  4882. this.selectedFiles.forEach((item) => {
  4883. const targetName = item.fileName || item.name;
  4884. const newPath = newDirPath + '/' + targetName;
  4885. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4886. ToastUtil.showToast('移动成功');
  4887. this.table.deleteData(item, () => {
  4888. this.cache.delete(this.currentPath); // 删除原路径缓存
  4889. this.cache.delete(newDirPath); // 删除目标路径缓存
  4890. this.getSortedFiles(this.currentPath, true);
  4891. });
  4892. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4893. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4894. if (!Utility.isIsoByExtension(newPath)) {
  4895. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4896. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4897. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4898. this.table.insert(newItem, (id: number) => {
  4899. //加入数据库
  4900. });
  4901. }
  4902. }
  4903. }).catch((error: Error) => {
  4904. console.error(error.message);
  4905. });
  4906. });
  4907. this.isMultiSelect = false
  4908. this.selectedFiles = [];
  4909. this.isAllSelected = false
  4910. XPopup.dismissTop();
  4911. };
  4912. let pup: XPopup
  4913. if (this.isDarkMode) {
  4914. pup = XPopup.Builder()
  4915. .setPopupPosition(PopupPosition.TOP)
  4916. .atView(viewId)
  4917. .setBackgroundColor(Color.Black)
  4918. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4919. .show();
  4920. } else {
  4921. pup = XPopup.Builder()
  4922. .setPopupPosition(PopupPosition.TOP)
  4923. .atView(viewId)
  4924. .setBackgroundColor(Color.White)
  4925. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4926. .show();
  4927. }
  4928. }
  4929. /**
  4930. * 加载所有歌单
  4931. */
  4932. async loadAllPlaylists() {
  4933. try {
  4934. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4935. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4936. } catch (error) {
  4937. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4938. }
  4939. }
  4940. /**
  4941. * 显示添加到歌单对话框
  4942. */
  4943. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4944. const songs = Array.isArray(items) ? items : [items]
  4945. const musicItems = songs.filter(song =>
  4946. song.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(song))
  4947. if (musicItems.length === 0) {
  4948. ToastUtil.showToast('请选择要添加的歌曲')
  4949. return
  4950. }
  4951. // 加载最新的歌单列表
  4952. await this.loadAllPlaylists()
  4953. showAddToPlaylistDialog(
  4954. musicItems,
  4955. this.allPlaylists,
  4956. async (playlistId: string) => {
  4957. // 添加歌曲到歌单
  4958. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4959. musicItems.map(song => song.filePath))
  4960. if (success) {
  4961. const count = musicItems.length
  4962. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4963. // 重新加载歌单列表
  4964. await this.loadAllPlaylists()
  4965. } else {
  4966. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4967. }
  4968. this.longItemFilePath = ''
  4969. if (this.isMultiSelect) {
  4970. this.isMultiSelect = false
  4971. this.isAllSelected = false
  4972. this.selectedFiles = []
  4973. }
  4974. },
  4975. () => {
  4976. LogUtil.info('取消添加到歌单')
  4977. },
  4978. () => {
  4979. // 创建新歌单
  4980. showCreatePlaylistDialog(
  4981. async (name: string, description: string, coverPath?: string) => {
  4982. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4983. if (success) {
  4984. ToastUtil.showToast('歌单创建成功')
  4985. // 重新加载歌单列表并打开添加对话框
  4986. await this.loadAllPlaylists()
  4987. await this.openAddToPlaylistDialog(musicItems)
  4988. } else {
  4989. ToastUtil.showToast('歌单创建失败')
  4990. }
  4991. },
  4992. () => {
  4993. // 取消创建歌单
  4994. }
  4995. )
  4996. }
  4997. )
  4998. }
  4999. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  5000. const nextFavList = [...this.favList];
  5001. const itemFavKey = Utility.getFavMatchKey(item);
  5002. const favIndex = nextFavList.findIndex((favItem: VideoItem) => Utility.getFavMatchKey(favItem) === itemFavKey);
  5003. if (isFav === 1) {
  5004. if (favIndex >= 0) {
  5005. nextFavList[favIndex].isFav = 1;
  5006. } else {
  5007. const favItem = cloneVideoItem(item);
  5008. favItem.isFav = 1;
  5009. nextFavList.push(favItem);
  5010. }
  5011. } else if (favIndex >= 0) {
  5012. nextFavList.splice(favIndex, 1);
  5013. }
  5014. this.favList = nextFavList;
  5015. item.isFav = isFav;
  5016. if (this.currentSong && Utility.getFavMatchKey(this.currentSong) === itemFavKey) {
  5017. this.currentSong.isFav = isFav;
  5018. this.isFac = isFav === 1;
  5019. }
  5020. }
  5021. private syncFavoriteStateForPlainList(list: Array<VideoItem> | undefined, targetKey: string, isFav: number): boolean {
  5022. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5023. return false;
  5024. }
  5025. let changed = false;
  5026. for (let index = 0; index < list.length; index += 1) {
  5027. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5028. continue;
  5029. }
  5030. list[index].isFav = isFav;
  5031. changed = true;
  5032. }
  5033. return changed;
  5034. }
  5035. private syncFavoriteStateForVisibleList(list: Array<VideoItem> | undefined, dataSource: LazyDataSource<VideoItem>,
  5036. targetKey: string, isFav: number, removeOnCancel: boolean): boolean {
  5037. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5038. return false;
  5039. }
  5040. let changed = false;
  5041. for (let index = list.length - 1; index >= 0; index -= 1) {
  5042. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5043. continue;
  5044. }
  5045. changed = true;
  5046. if (removeOnCancel) {
  5047. list.splice(index, 1);
  5048. if (index < dataSource.dataArray.length) {
  5049. dataSource.deleteData(index);
  5050. }
  5051. } else {
  5052. list[index].isFav = isFav;
  5053. if (index < dataSource.dataArray.length) {
  5054. dataSource.dataArray[index].isFav = isFav;
  5055. dataSource.notifyDataChange(index);
  5056. }
  5057. }
  5058. }
  5059. return changed;
  5060. }
  5061. private syncFavoriteStateInCaches(targetKey: string, isFav: number): void {
  5062. if (StrUtil.isEmpty(targetKey) || this.cache.size === 0) {
  5063. return;
  5064. }
  5065. let changed = false;
  5066. this.cache.forEach((items: Array<VideoItem>) => {
  5067. for (let index = 0; index < items.length; index += 1) {
  5068. if (Utility.getFavMatchKey(items[index]) !== targetKey) {
  5069. continue;
  5070. }
  5071. items[index].isFav = isFav;
  5072. changed = true;
  5073. }
  5074. });
  5075. if (changed) {
  5076. void this.saveCacheToStorage();
  5077. }
  5078. }
  5079. private syncFavoriteStateAcrossCollections(item: VideoItem, isFav: number): void {
  5080. const targetKey = Utility.getFavMatchKey(item);
  5081. if (StrUtil.isEmpty(targetKey)) {
  5082. return;
  5083. }
  5084. const removeFromCurrentView = this.isFavMusic && isFav === 0;
  5085. const currentViewChanged = this.syncFavoriteStateForVisibleList(this.videoLocalList, this.dataSource, targetKey, isFav,
  5086. removeFromCurrentView);
  5087. this.syncFavoriteStateForVisibleList(this.songList, this.sonDataSource, targetKey, isFav, false);
  5088. this.syncFavoriteStateForPlainList(this.currentSongList, targetKey, isFav);
  5089. this.syncFavoriteStateForPlainList(this.historyList, targetKey, isFav);
  5090. this.syncFavoriteStateForPlainList(this.mediaKuList, targetKey, isFav);
  5091. this.syncFavoriteStateForPlainList(this.artistList, targetKey, isFav);
  5092. this.syncFavoriteStateForPlainList(this.albumList, targetKey, isFav);
  5093. this.syncFavoriteStateForPlainList(this.filteredList, targetKey, isFav);
  5094. this.syncFavoriteStateInCaches(targetKey, isFav);
  5095. if (this.isFavMusic) {
  5096. this.currentTitleCover = ArrayUtil.isNotEmpty(this.favList) ? Utility.getFirstCoverFromList(this.favList) :
  5097. $r('app.media.alt');
  5098. }
  5099. if (currentViewChanged) {
  5100. this.setButtonStatus();
  5101. if (removeFromCurrentView) {
  5102. this.markAlphaBetDirty();
  5103. }
  5104. }
  5105. }
  5106. private syncRemoteFavoriteState(item: VideoItem, isFav: number): void {
  5107. if (!item || !isRemoteCloudType(item.type) || StrUtil.isEmpty(item.filePath)) {
  5108. return;
  5109. }
  5110. const remoteManager = RemoteDriveManager.getInstance();
  5111. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  5112. if (target) {
  5113. target.isFav = isFav;
  5114. }
  5115. }
  5116. doFav(item: VideoItem) {
  5117. LogUtil.info('onecold doFav isFav=' + item.isFav)
  5118. let isFav = 0
  5119. if (Utility.getIsFav(this.favList, item)) {
  5120. isFav = 0
  5121. } else {
  5122. isFav = 1
  5123. }
  5124. const targetFilePath = isRemoteCloudType(item.type) ? (this.resolveRemoteStoragePath(item) || item.filePath) :
  5125. item.filePath;
  5126. const onUpdateSuccess = (): void => {
  5127. this.syncFavStateLocal(item, isFav);
  5128. this.syncRemoteFavoriteState(item, isFav);
  5129. this.syncFavoriteStateAcrossCollections(item, isFav);
  5130. if (isFav === 1) {
  5131. ToastUtil.showToast('收藏成功');
  5132. } else {
  5133. ToastUtil.showToast('取消收藏成功');
  5134. }
  5135. };
  5136. const updateFavorite = (): void => {
  5137. this.table.updateIsFavByFilePath(targetFilePath, isFav, async (result: boolean, error?: string) => {
  5138. if (result) {
  5139. onUpdateSuccess();
  5140. return;
  5141. }
  5142. if (isRemoteCloudType(item.type)) {
  5143. Logger.warn(TAG, `远程歌曲收藏更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  5144. try {
  5145. await this.persistRemoteMetadataToDb(item);
  5146. this.table.updateIsFavByFilePath(targetFilePath, isFav, (retryResult: boolean, retryError?: string) => {
  5147. if (retryResult) {
  5148. onUpdateSuccess();
  5149. } else {
  5150. Logger.error(TAG, `远程歌曲收藏补入库后仍失败: ${targetFilePath}, error=${retryError}`);
  5151. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5152. }
  5153. });
  5154. } catch (persistError) {
  5155. Logger.error(TAG,
  5156. `远程歌曲收藏补入库失败: ${targetFilePath}, error=${(persistError as Error).message}`);
  5157. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5158. }
  5159. return;
  5160. }
  5161. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5162. })
  5163. };
  5164. updateFavorite()
  5165. }
  5166. //多选复制文件
  5167. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5168. console.log('onecold showCopyDialogForMultipleFiles');
  5169. let mList: Array<string> = []
  5170. let rPath = this.rootPath
  5171. if (isCurrent) {
  5172. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5173. rPath = this.currentPath
  5174. } else {
  5175. mList = Utility.getNameList(this.dirList);
  5176. rPath = this.rootPath
  5177. }
  5178. let dataBean = new BubbleBean();
  5179. dataBean.data = mList;
  5180. dataBean.isCopy = true
  5181. dataBean.color = this.themeColor
  5182. dataBean.onItemClick = (i) => {
  5183. const newDirPath = rPath + '/' + mList[i];
  5184. // Logger.info('newDirPath = ' + newDirPath)
  5185. this.selectedFiles.forEach((item) => {
  5186. const targetName = item.fileName || item.name;
  5187. const newPath = newDirPath + '/' + targetName;
  5188. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  5189. ToastUtil.showToast('复制成功');
  5190. this.cache.delete(newDirPath); // 删除目标路径缓存
  5191. this.getSortedFiles(this.currentPath);
  5192. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5193. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5194. if (!Utility.isIsoByExtension(newPath)) {
  5195. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5196. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5197. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5198. this.table.insert(newItem, (id: number) => {
  5199. //加入数据库
  5200. });
  5201. }
  5202. }
  5203. }).catch((error: Error) => {
  5204. console.error(error.message);
  5205. });
  5206. });
  5207. this.isMultiSelect = false
  5208. this.selectedFiles = [];
  5209. this.isAllSelected = false
  5210. XPopup.dismissTop();
  5211. };
  5212. let pup: XPopup
  5213. if (this.isDarkMode) {
  5214. pup = XPopup.Builder()
  5215. .setPopupPosition(PopupPosition.TOP)
  5216. .atView(viewId)
  5217. .setBackgroundColor(Color.Black)
  5218. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5219. .show();
  5220. } else {
  5221. pup = XPopup.Builder()
  5222. .setPopupPosition(PopupPosition.TOP)
  5223. .atView(viewId)
  5224. .setBackgroundColor(Color.White)
  5225. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5226. .show();
  5227. }
  5228. }
  5229. @Builder
  5230. private DirItem(item: VideoItem, index?: number) {
  5231. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5232. Row() {
  5233. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ?
  5234. this.getListImageSource(item, index ?? -1, this.coverThumbVersion) :
  5235. $r('app.media.music_group'))
  5236. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5237. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5238. .fillColor(this.themeColor)// .fontSize(33)
  5239. .alt($r('app.media.music_group'))
  5240. .borderRadius(this.isCoverRectangle?9:'100%')
  5241. .clip(true)
  5242. .shadow({
  5243. radius: 2,
  5244. type: ShadowType.BLUR,
  5245. color: 'on_primary'
  5246. })
  5247. .sourceSize({width:38, height:38})
  5248. .margin({ left: 20, top: 8, bottom: 8 })
  5249. Column() {
  5250. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5251. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5252. .maxLines(1)// .width('88%')
  5253. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  5254. .margin({ left: 10, right: 20 })
  5255. .fontColor($r('app.color.text_color'))
  5256. Row() {
  5257. Text(`${this.getArtistSongCount(item.name)}首`)
  5258. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5259. .padding({ top: 8 })
  5260. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  5261. .fontColor($r('app.color.text_color'))
  5262. .margin({ left: 10 })
  5263. Text(`${this.getAlbumSongCount(item.name)}首`)
  5264. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5265. .padding({ top: 8 })
  5266. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  5267. .fontColor($r('app.color.text_color'))
  5268. .margin({ left: 10 })
  5269. Blank()
  5270. }
  5271. }
  5272. .height('100%')
  5273. .width('100%')
  5274. .justifyContent(FlexAlign.Center)
  5275. .alignItems(HorizontalAlign.Start)
  5276. Blank()
  5277. Checkbox({ name: 'dir_checkbox' + (index ?? -1) })
  5278. .select(this.isLocalItemSelected(item))
  5279. .selectedColor(this.themeColor)
  5280. .shape(CheckBoxShape.CIRCLE)
  5281. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5282. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible : Visibility.None)
  5283. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5284. .margin({ left: 20, top: 8, bottom: 8, right: 18 })
  5285. .width(22)
  5286. .height(22)
  5287. Image($r('app.media.arrow_right'))
  5288. .height(25)
  5289. .alignSelf(ItemAlign.Center)
  5290. .id(item.filePath)
  5291. .visibility(this.isShowAlphaBet || (this.isMultiSelect && this.isSelectableLocalItem(item)) ?
  5292. Visibility.None : Visibility.Visible)
  5293. }
  5294. }
  5295. .backgroundColor(Color.Transparent)
  5296. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5297. .width('98%')
  5298. .reuseId('dir_item')
  5299. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  5300. .opacity(this.opacityItem) // 绑定透明度
  5301. .onTouch((event: TouchEvent) => {
  5302. this.handlePointLightTouch(this.getPointLightItemKey('list_dir', item, index), event)
  5303. })
  5304. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5305. ? new hdsEffect.HdsEffectBuilder()
  5306. .pointLight({
  5307. options: this.getPointLightOptions(this.getPointLightItemKey('list_dir', item, index)),
  5308. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5309. })
  5310. .buildEffect()
  5311. : undefined)
  5312. }
  5313. private refreshDirVisibilitySettings(): void {
  5314. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  5315. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  5316. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  5317. }
  5318. isShowDir(dirName: string) {
  5319. if (dirName === undefined) {
  5320. return true
  5321. }
  5322. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  5323. return this.isShowSimi
  5324. }
  5325. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  5326. return this.isShowFAV
  5327. }
  5328. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  5329. return this.isShowHistory
  5330. }
  5331. return true
  5332. }
  5333. private getPointLightItemKey(prefix: string, item: VideoItem, index?: number): string {
  5334. const itemPath = StrUtil.isNotEmpty(item.filePath) ? item.filePath : `${item.name}_${index ?? -1}`
  5335. return `${prefix}_${itemPath}`
  5336. }
  5337. private handlePointLightTouch(itemKey: string, event: TouchEvent): void {
  5338. if (deviceInfo.sdkApiVersion < 20) {
  5339. return
  5340. }
  5341. if (event.type === TouchType.Down) {
  5342. this.activePointLightItemKey = itemKey
  5343. this.pointLightOptions = {
  5344. color: this.themeColor,
  5345. intensity: 1,
  5346. height: 60
  5347. }
  5348. return
  5349. }
  5350. if ((event.type === TouchType.Up || event.type === TouchType.Cancel) && this.activePointLightItemKey === itemKey) {
  5351. this.activePointLightItemKey = ''
  5352. this.pointLightOptions = undefined
  5353. }
  5354. }
  5355. private getPointLightOptions(itemKey: string): hdsEffect.PointLightOptions | undefined {
  5356. if (this.activePointLightItemKey !== itemKey) {
  5357. return undefined
  5358. }
  5359. return this.pointLightOptions
  5360. }
  5361. @State opacityItem: number = 1; // 控制透明度的状态变量
  5362. @Builder
  5363. private MusicItem(item: VideoItem, index?: number) {
  5364. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5365. Row() {
  5366. Stack() {
  5367. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5368. .fillColor(this.themeColor)
  5369. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5370. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5371. .alt($r('app.media.alt'))
  5372. .borderRadius(this.isCoverRectangle?9:'100%')
  5373. .clip(true)
  5374. .draggable(false)
  5375. .sourceSize({width:38, height:38})
  5376. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5377. // .autoResize(true) // 重采样,可减少内存占用
  5378. .opacity(this.opacityItem)// 绑定透明度
  5379. .margin({ left: 20 })
  5380. .shadow({
  5381. radius: this.isScrolling ? 0 : 10,
  5382. type: ShadowType.BLUR,
  5383. color: 'on_primary'
  5384. })
  5385. .onClick(()=>{
  5386. if (this.isMultiSelect) {
  5387. const isChecked = this.isLocalItemSelected(item);
  5388. this.handleFileSelection(item, !isChecked);
  5389. } else {
  5390. this.doPlay(item,index)
  5391. this.setShowPlayTrue()
  5392. }
  5393. })
  5394. }
  5395. Column() {
  5396. Column() {
  5397. Text(this.isShowFileName?item.fileName :item.name)
  5398. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5399. .maxLines(1)
  5400. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5401. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5402. $r('app.color.text_color'))
  5403. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5404. .padding({right:25})
  5405. .bindPopup(this.longItemFilePath === item.filePath, {
  5406. builder: this.MenuBuilder(item,index,item.filePath),
  5407. placement: Placement.Top,
  5408. // autoCancel: true,
  5409. mask: {color:'#33000000'},
  5410. // popupColor: Color.Yellow,
  5411. enableArrow: false,//是否显示箭头
  5412. showInSubWindow: false,
  5413. onStateChange: (e) => {
  5414. if (!e.isVisible) {
  5415. this.longItemFilePath = ''
  5416. this.tempLyricContent = ''
  5417. }
  5418. }
  5419. })
  5420. Row() {
  5421. Column(){
  5422. Text(item.md5Str?.includes('Lossless')?
  5423. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5424. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5425. .padding({ top: 3,right:6,left:6,bottom:3 })
  5426. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5427. $r('app.color.text_color'))
  5428. .fontWeight(500)
  5429. .borderRadius(12)
  5430. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  5431. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5432. .backgroundColor('#FFC107')
  5433. }
  5434. .padding({ top: 8 })
  5435. Text(StrUtil.isEmpty(item.artist) ? item.duration
  5436. :this.twoFingerType==2? item.artist +' ' + item.duration
  5437. : item.artist + ' ' + item?.duration)
  5438. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5439. .padding({ top: 8 ,right:25})
  5440. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  5441. .maxLines(1)
  5442. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  5443. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5444. Color.Gray)
  5445. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5446. Blank()
  5447. Text(this.isShowFileName?item.duration:item.size)
  5448. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5449. .padding({ top: 8 })
  5450. .maxLines(1)
  5451. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  5452. ? Visibility.Visible : Visibility.None)
  5453. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5454. Color.Gray)
  5455. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  5456. }
  5457. }
  5458. .height('100%')
  5459. .width('100%')
  5460. .margin({ right: 10 })
  5461. .justifyContent(FlexAlign.Center)
  5462. .alignItems(HorizontalAlign.Start)
  5463. }
  5464. .height('100%')
  5465. .margin({ left: 5 })
  5466. .layoutWeight(1)
  5467. Column() {
  5468. Checkbox({ name: 'checkbox' + index })
  5469. .select(this.isLocalItemSelected(item))
  5470. .selectedColor(this.themeColor)
  5471. .shape(CheckBoxShape.CIRCLE)
  5472. .opacity(this.isMultiSelect ? 1 : 0)
  5473. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  5474. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5475. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  5476. .width(22)
  5477. .height(22)
  5478. PlayingIndicator({
  5479. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  5480. indicatorSize: 18,
  5481. marginRight: 20,
  5482. marginTop: 8,
  5483. marginBottom: 8
  5484. })
  5485. }
  5486. }
  5487. }
  5488. .gesture(LongPressGesture()
  5489. .onAction(async () => {
  5490. //如果是专辑和艺术家的首页,不能长按
  5491. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5492. return
  5493. //如果是我的收藏 最近播放等也不能长按
  5494. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5495. item.name === LocalMusic.STR_HISTORY_MUSIC
  5496. )
  5497. return
  5498. this.longItemFilePath = item.filePath
  5499. this.tempLyricContent = this.supportsLocalAudioActions(item) ? await this.getLyricContent(item) : ''
  5500. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5501. })
  5502. .onActionEnd((event: GestureEvent) => {
  5503. }))
  5504. .backgroundColor(Color.Transparent)
  5505. .width('100%')
  5506. .reuseId('file_item')
  5507. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5508. .onTouch((event: TouchEvent) => {
  5509. this.handlePointLightTouch(this.getPointLightItemKey('list_music', item, index), event)
  5510. })
  5511. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5512. ? new hdsEffect.HdsEffectBuilder()
  5513. .pointLight({
  5514. options: this.getPointLightOptions(this.getPointLightItemKey('list_music', item, index)),
  5515. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5516. })
  5517. .buildEffect()
  5518. : undefined)
  5519. }
  5520. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5521. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5522. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5523. direction: Direction.Ltr,
  5524. buttonPadding:{top:12,bottom:12},
  5525. backgroundColor: Color.Transparent,
  5526. fontSize:14,
  5527. selectedFontSize:15,
  5528. selectedFontColor:Color.White,
  5529. selectedBackgroundColor: this.themeColor,
  5530. localizedTextPadding: {
  5531. end: LengthMetrics.vp(20),
  5532. start: LengthMetrics.vp(20)
  5533. }
  5534. })
  5535. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5536. //当胶囊按钮的选择发生变化时调用此函数
  5537. capsuleSelectedIndexesChanged() {
  5538. this.modeType = this.tabSelectedIndexes[0]
  5539. }
  5540. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5541. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5542. isShowCoverHeader() {
  5543. if (!this.isShowHeader) {
  5544. return false
  5545. }
  5546. if (this.modeType == 0) {
  5547. if (this.isHistory || this.isFavMusic) {
  5548. return true
  5549. }
  5550. if (this.currentPath != this.rootPath) {
  5551. return true
  5552. }
  5553. }
  5554. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5555. }
  5556. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5557. if (this.isCustomizeBg) {
  5558. return ('rgba(255,255,255,0.2)')
  5559. }
  5560. if (this.isDarkMode) {
  5561. return $r('app.color.user_center_card_background')
  5562. }
  5563. return this.currentTitleCover
  5564. }
  5565. // 第二步:popup构造器定义弹框内容
  5566. @Builder popupBuilder() {
  5567. Column({ space: 2 }) {
  5568. Text('友情提示:双指缩放可以放大缩小列表')
  5569. .fontSize(12)
  5570. .fontWeight(FontWeight.Regular)
  5571. .fontColor($r('app.color.text_color'))
  5572. }
  5573. .justifyContent(FlexAlign.SpaceAround)
  5574. .width(220)
  5575. .height(55)
  5576. .padding(15)
  5577. }
  5578. //搜索功能的实现
  5579. @State searchText: string = ''; // 用户输入内容
  5580. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5581. @State isSearchMode: boolean = false
  5582. @State searchHistoryItems: string[] = []
  5583. private readonly searchHistoryScope: string = 'local_music'
  5584. private loadSearchHistory(): void {
  5585. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope)
  5586. }
  5587. private saveSearchHistory(keyword: string): void {
  5588. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword)
  5589. }
  5590. private commitSearchHistory(keyword: string): void {
  5591. const normalized = keyword.trim()
  5592. if (normalized.length === 0) {
  5593. return
  5594. }
  5595. this.saveSearchHistory(normalized)
  5596. }
  5597. private applySearchHistory(keyword: string): void {
  5598. this.searchText = keyword
  5599. this.searchController.stopEditing()
  5600. void this.onSearchInput(keyword)
  5601. }
  5602. // 实时搜索逻辑(带防抖)
  5603. private async onSearchInput(value: string): Promise<void> {
  5604. this.searchText = value.trim();
  5605. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5606. // 清空搜索文本时保持搜索态,只重置为不带关键词的结果列表
  5607. if (this.searchText === '') {
  5608. this.loadSearchHistory()
  5609. await this.resetAndLoadFirstPage();
  5610. return;
  5611. }
  5612. // 进入搜索模式
  5613. if (!this.isSearchMode) {
  5614. this.isSearchMode = true;
  5615. }
  5616. // 使用数据库分页查询(带搜索条件)
  5617. await this.resetAndLoadFirstPage();
  5618. }
  5619. @Builder
  5620. private SearchHistoryView(): void {
  5621. Column({ space: 10 }) {
  5622. Row() {
  5623. Text('搜索历史')
  5624. .fontSize(14)
  5625. .fontWeight(FontWeight.Medium)
  5626. .fontColor($r('app.color.text_color'))
  5627. Blank()
  5628. Button('清空')
  5629. .fontSize(12)
  5630. .fontColor(this.themeColor)
  5631. .backgroundColor(Color.Transparent)
  5632. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  5633. .onClick(() => {
  5634. SearchHistoryUtil.clear(this.searchHistoryScope)
  5635. this.searchHistoryItems = []
  5636. })
  5637. }
  5638. .width('100%')
  5639. Flex({ wrap: FlexWrap.Wrap }) {
  5640. ForEach(this.searchHistoryItems, (keyword: string) => {
  5641. Button(keyword)
  5642. .fontSize(12)
  5643. .fontColor($r('app.color.text_color'))
  5644. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  5645. .borderRadius(16)
  5646. .margin({ right: 8, bottom: 8 })
  5647. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  5648. .onClick(() => {
  5649. this.applySearchHistory(keyword)
  5650. })
  5651. })
  5652. }
  5653. .width('100%')
  5654. }
  5655. .width('100%')
  5656. .padding({ left: 16, right: 16, top: 10, bottom: 10 })
  5657. }
  5658. @State dragItem: number = -1
  5659. @State scaleItem: number = -1
  5660. @State neighborItem: number = -1
  5661. @State neighborScale: number = -1
  5662. @State offsetY: number = 0
  5663. private dragRefOffset: number = 0
  5664. private ITEM_INTV: number = 78
  5665. scaleSelect(item: number): number {
  5666. if (this.scaleItem === item) {
  5667. return 1.05
  5668. } else if (this.neighborItem === item) {
  5669. return this.neighborScale
  5670. } else {
  5671. return 1
  5672. }
  5673. }
  5674. itemMove(index: number, newIndex: number): void {
  5675. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5676. return;
  5677. }
  5678. let tmp = this.videoLocalList.splice(index, 1);
  5679. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5680. this.dataSource.pushArrayData(this.videoLocalList)
  5681. if(this.modeType==4&&this.playlistTable){
  5682. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5683. }
  5684. }
  5685. //瀑布流布局 支持双指缩放
  5686. @State columns: number = 2;
  5687. @State waterFlowScale: number = 1;
  5688. @State imageScale: number = 1;
  5689. @State waterFlowOpacity: number = 1;
  5690. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5691. private columnChanged: boolean = false;
  5692. private oldColumn: number = this.columns;
  5693. private pinchTime: number = 0;
  5694. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5695. changeColumns(scale: number): void {
  5696. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5697. this.columns--;
  5698. this.columnChanged = true;
  5699. } else if (scale < 1 && this.columns < 4) {
  5700. this.columns++;
  5701. this.columnChanged = true;
  5702. }
  5703. }
  5704. @Builder
  5705. getWaterView(){
  5706. Scroll(this.scroller) {
  5707. Column() {
  5708. Blank().height(this.topSafeHeight + 55)
  5709. WaterFlow({
  5710. scroller:this.waterScroller,
  5711. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5712. }) {
  5713. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5714. FlowItem() {
  5715. this.MusicWaterCardItem(item,index)
  5716. }
  5717. .width('100%')
  5718. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5719. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5720. {
  5721. preview: MenuPreviewMode.IMAGE
  5722. })
  5723. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5724. {
  5725. preview: MenuPreviewMode.IMAGE
  5726. })
  5727. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5728. }
  5729. // .columnsTemplate('repeat(auto-fit, 160)')
  5730. .id('waterflow') // 设置id用于截图
  5731. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5732. .columnsGap(12) // 列间距
  5733. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5734. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5735. .padding({bottom:this.bottomBarHeight+10})
  5736. .scrollBar(BarState.Off)
  5737. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5738. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5739. .edgeEffect(EdgeEffect.None)
  5740. .width('90%')
  5741. .height('100%')
  5742. .opacity(this.waterFlowOpacity)
  5743. .scale({
  5744. x: this.waterFlowScale,
  5745. y: this.waterFlowScale,
  5746. centerX: 0,
  5747. centerY: 0
  5748. })
  5749. .onReachEnd(() => {
  5750. if(this.modeType === 4 )
  5751. return;
  5752. // 触底加载下一页
  5753. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5754. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5755. return;
  5756. }
  5757. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5758. this.scheduleLoadNextPage();
  5759. }
  5760. })
  5761. .onAppear(() => {
  5762. this.scroller.scrollEdge(Edge.Top)
  5763. })
  5764. .nestedScroll({
  5765. scrollForward: NestedScrollMode.PARENT_FIRST,
  5766. scrollBackward: NestedScrollMode.SELF_FIRST
  5767. })
  5768. .priorityGesture(
  5769. PinchGesture()
  5770. .onActionStart((event: GestureEvent) => {
  5771. // 双指捏合手势识别成功时截图
  5772. this.pinchTime = event.timestamp;
  5773. this.columnChanged = false;
  5774. this.oldColumn = this.columns;
  5775. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5776. if (error) {
  5777. console.info('error:' + JSON.stringify(error));
  5778. return;
  5779. }
  5780. this.waterFlowSnapshot = pixmap;
  5781. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5782. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5783. if (this.oldColumn ===4) {
  5784. this.twoFingerType =3
  5785. this.isGridMusic = true
  5786. }else if (this.oldColumn ===1) {
  5787. this.twoFingerType =1
  5788. this.isGridMusic = false
  5789. }
  5790. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5791. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5792. return;
  5793. }
  5794. })
  5795. })
  5796. .onActionUpdate((event: GestureEvent) => {
  5797. // 手势更新:处理缩放逻辑和视觉效果
  5798. // 边界限制:防止超出列数范围时继续缩放
  5799. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5800. return;
  5801. }
  5802. // 节流处理:避免过于频繁的更新,提升性能
  5803. if (event.timestamp - this.pinchTime < 10000000) {
  5804. return;
  5805. }
  5806. this.pinchTime = event.timestamp;
  5807. this.waterFlowScale = event.scale;
  5808. this.imageScale = event.scale;
  5809. // 根据缩放比例设置WaterFlow透明度
  5810. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5811. this.waterFlowOpacity *= 3;
  5812. if (!this.columnChanged) {
  5813. this.changeColumns(event.scale);
  5814. }
  5815. // 列数改变后的缩放比例调整:避免出现空白区域
  5816. if (this.columnChanged) {
  5817. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5818. // 限制缩放范围,确保视觉效果自然
  5819. if (event.scale < 1) {
  5820. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5821. } else {
  5822. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5823. }
  5824. }
  5825. })
  5826. .onActionEnd((event: GestureEvent) => {
  5827. // 手势结束:执行归位动画并保存状态
  5828. // 执行归位动画:平滑过渡到正常状态
  5829. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5830. this.waterFlowScale = 1;
  5831. this.waterFlowOpacity = 1;
  5832. })
  5833. // 持久化保存当前列数:下次启动时恢复
  5834. PreferencesUtil.putSync('lastColumns', this.columns);
  5835. })
  5836. )
  5837. .onScrollFrameBegin((offset: number) => {
  5838. this.markGridWaterScrollingActive()
  5839. // 获取当前滚动偏移量
  5840. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5841. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  5842. this.updateTitleBarByScrollOffset(currentOffsetY)
  5843. return { offsetRemain: offset };
  5844. })
  5845. }
  5846. }
  5847. .scrollBar(BarState.Off)
  5848. }
  5849. //瀑布流卡片布局
  5850. @Builder
  5851. private MusicWaterCardItem(item: VideoItem, index: number) {
  5852. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5853. Stack() {
  5854. Column() {
  5855. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  5856. .backgroundImageSize(ImageSize.Auto)
  5857. .borderRadius({
  5858. topLeft: 12,
  5859. topRight : 12,
  5860. bottomLeft: 0,
  5861. bottomRight: 0
  5862. })
  5863. .draggable(false)// 禁止长按手势拖动
  5864. .autoResize(true) // 重采样,可减少内存占用
  5865. .sourceSize({
  5866. width: this.getCoverThumbTargetSize(true),
  5867. height: this.getCoverThumbTargetSize(true)
  5868. })
  5869. .width('100%')
  5870. .height('auto')
  5871. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5872. .objectFit(ImageFit.Cover)
  5873. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5874. height: '99%' ,
  5875. dragBar: true,
  5876. onDisappear: () => {
  5877. this.longItemFilePath = '';
  5878. this.tempLyricContent = ''
  5879. },
  5880. showClose: true,
  5881. preferType: SheetType.CENTER ,
  5882. title: { title: '编辑标签' }
  5883. })
  5884. .draggable(false)
  5885. .opacity(this.opacityItem)// 绑定透明度
  5886. .margin({
  5887. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5888. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5889. })
  5890. Column() {
  5891. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5892. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5893. .maxLines(1)
  5894. .fontWeight(FontWeight.Bold)
  5895. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5896. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5897. height: '95%',
  5898. dragBar: true,
  5899. showClose: true,
  5900. onDisappear: () => {
  5901. this.longItemFilePathDetail = '';
  5902. },
  5903. blurStyle:BlurStyle.Thin,
  5904. backgroundColor:Color.Transparent,
  5905. preferType: SheetType.CENTER ,
  5906. title: { title: '详情' }
  5907. })
  5908. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5909. $r('app.color.text_color'))
  5910. Column() {
  5911. Text(`${this.getArtistSongCount(item.name)}首`)
  5912. .fontSize(11)
  5913. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5914. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5915. .fontColor($r('app.color.text_color'))
  5916. Text(`${this.getAlbumSongCount(item.name)}首`)
  5917. .fontSize(11)
  5918. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5919. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5920. .fontColor($r('app.color.text_color'))
  5921. Row(){
  5922. Column(){
  5923. Text(item.md5Str?.includes('Lossless')?
  5924. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5925. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5926. .padding({ top: 3,right:6,left:6,bottom:3 })
  5927. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5928. $r('app.color.text_color'))
  5929. .fontWeight(500)
  5930. .borderRadius(12)
  5931. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5932. .backgroundColor('#FFC107')
  5933. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5934. }
  5935. .margin({ top: 2 ,right:6})
  5936. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5937. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5938. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5939. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5940. .maxLines(1)
  5941. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  5942. .margin({ top: 2})
  5943. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5944. || item.type == CommonConstants.TYPE_IS_ALBUM
  5945. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5946. .fontWeight(FontWeight.Medium)
  5947. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5948. $r('app.color.text_color'))
  5949. }
  5950. }
  5951. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5952. }
  5953. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5954. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5955. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5956. .width('100%')
  5957. .justifyContent(FlexAlign.Center)
  5958. .margin({
  5959. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5960. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5961. })
  5962. }
  5963. .width('100%')
  5964. .borderRadius(12)
  5965. .backgroundColor($r('app.color.com_bg'))
  5966. Checkbox({ name: 'checkbox' + index })
  5967. .select(this.isLocalItemSelected(item))
  5968. .selectedColor(this.themeColor)
  5969. .shape(CheckBoxShape.CIRCLE)
  5970. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5971. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  5972. Visibility.None)
  5973. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5974. .margin({ left: 20, top: 8, bottom: 8 })
  5975. .width(38)
  5976. .height(38)
  5977. }
  5978. }
  5979. .backgroundColor(Color.Transparent)
  5980. .width('100%')
  5981. .height('auto')
  5982. .padding({top:2})
  5983. .shadow({
  5984. radius: this.isScrolling ? 0 : 8,
  5985. type: ShadowType.BLUR,
  5986. color: 'on_primary'
  5987. })
  5988. .reuseId('card_item')
  5989. .onTouch((event: TouchEvent) => {
  5990. this.handlePointLightTouch(this.getPointLightItemKey('water_music', item, index), event)
  5991. })
  5992. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5993. ? new hdsEffect.HdsEffectBuilder()
  5994. .pointLight({
  5995. options: this.getPointLightOptions(this.getPointLightItemKey('water_music', item, index)),
  5996. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5997. })
  5998. .buildEffect()
  5999. : undefined)
  6000. .onClick(() => {
  6001. if (this.isMultiSelect) {
  6002. if (this.isSelectableLocalItem(item)) {
  6003. const isChecked = this.isLocalItemSelected(item);
  6004. this.handleFileSelection(item, !isChecked);
  6005. }
  6006. return
  6007. }
  6008. this.doPlay(item, index)
  6009. })
  6010. }
  6011. // Grid布局的开始
  6012. private dragRefOffSetX: number = 0;
  6013. private dragRefOffSetY: number = 0;
  6014. private FIX_VP_X: number = 180;
  6015. private FIX_VP_Y: number = 84;
  6016. isDraggable(index: number): boolean {
  6017. return index >= 0;
  6018. }
  6019. getRowEnd(item: number) {
  6020. if (item.toString() === '0') {
  6021. return 1;
  6022. } else {
  6023. return 0;
  6024. }
  6025. }
  6026. isInLeft(index: number) {
  6027. return index % 2 == 0;
  6028. }
  6029. down(index: number): void {
  6030. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  6031. return;
  6032. }
  6033. this.offsetY -= this.FIX_VP_Y;
  6034. this.dragRefOffSetY += this.FIX_VP_Y;
  6035. this.itemMove(index, index + 1);
  6036. }
  6037. up(index: number): void {
  6038. if (!this.isDraggable(index - 2)) {
  6039. return;
  6040. }
  6041. this.offsetY += this.FIX_VP_Y;
  6042. this.dragRefOffSetY -= this.FIX_VP_Y;
  6043. this.itemMove(index, index - 1);
  6044. }
  6045. left(index: number): void {
  6046. if (this.isInLeft(index)) {
  6047. return;
  6048. }
  6049. if (!this.isDraggable(index - 1)) {
  6050. return;
  6051. }
  6052. this.offsetX += this.FIX_VP_X;
  6053. this.dragRefOffSetX -= this.FIX_VP_X;
  6054. this.itemMove(index, index - 1)
  6055. }
  6056. right(index: number): void {
  6057. if (!this.isInLeft(index)) {
  6058. return;
  6059. }
  6060. if (!this.isDraggable(index + 1)) {
  6061. return;
  6062. }
  6063. this.offsetX -= this.FIX_VP_X;
  6064. this.dragRefOffSetX += this.FIX_VP_X;
  6065. this.itemMove(index, index + 1)
  6066. }
  6067. private scroller: Scroller = new Scroller();
  6068. private waterScroller: Scroller = new Scroller();
  6069. private startIndex: number = 0
  6070. private endIndex: number = 0
  6071. @State scaleValue: number = 1
  6072. @State pinchValue: number = 1
  6073. layoutOptionsForHeader: GridLayoutOptions = {
  6074. regularSize: [1, 1], // 只支持[1, 1]
  6075. irregularIndexes: [0], // 索引为0的GridItem占用一行
  6076. };
  6077. @Builder
  6078. getGridView() {
  6079. Grid(this.scroller, this.layoutOptionsForHeader) {
  6080. GridItem() {
  6081. Column(){
  6082. Blank().height(this.topSafeHeight + 45)
  6083. }
  6084. }
  6085. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6086. GridItem() {
  6087. Stack() {
  6088. this.MusicItemGrid(item, index)
  6089. }
  6090. }
  6091. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  6092. {
  6093. preview: MenuPreviewMode.IMAGE
  6094. })
  6095. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  6096. {
  6097. preview: MenuPreviewMode.IMAGE
  6098. })
  6099. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  6100. // TransitionEffect.scale({ x: 0, y: 0 })))
  6101. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6102. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  6103. .zIndex(this.dragItem === index ? 1 : 0)
  6104. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  6105. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6106. }
  6107. .width('94%')
  6108. .height('100%')
  6109. .editMode(true)
  6110. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  6111. .reuseId('grid_item')
  6112. .layoutWeight(1)
  6113. .scrollBar(BarState.Off)
  6114. .supportAnimation(false)
  6115. .onReachEnd(() => {
  6116. if(this.modeType === 4 )
  6117. return;
  6118. // 触底加载下一页
  6119. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6120. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6121. return;
  6122. }
  6123. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6124. this.scheduleLoadNextPage();
  6125. }
  6126. })
  6127. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  6128. .columnsTemplate(
  6129. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  6130. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  6131. )
  6132. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  6133. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  6134. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6135. .gesture(PinchGesture({ fingers: 2 })
  6136. .onActionEnd((event: GestureEvent) => {
  6137. this.setGridTwoFingers()
  6138. })
  6139. .onActionUpdate(e => {
  6140. this.scaleValue = this.pinchValue * e.scale
  6141. })
  6142. .onActionStart(e => {
  6143. }))
  6144. .enableScrollInteraction(true)
  6145. .onScrollIndex((start: number, end: number) => {
  6146. this.startIndex = start
  6147. this.endIndex = end
  6148. this.gridVisibleStart = start
  6149. this.gridVisibleEnd = end
  6150. this.lastVisibleEndIndex = end
  6151. this.warmupGridWaterVisibleThumbs(start, end, false)
  6152. const now = Date.now()
  6153. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  6154. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  6155. this.gridScrollPagingCheckAt = now
  6156. this.gridScrollLastPagingEnd = end
  6157. this.tryTriggerLoadNextPageByScroll(end)
  6158. }
  6159. })
  6160. .onScrollFrameBegin((offset: number) => {
  6161. this.markGridWaterScrollingActive()
  6162. const currentOffsetY = this.scroller.currentOffset().yOffset;
  6163. this.updateTitleBarByScrollOffset(currentOffsetY)
  6164. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6165. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6166. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6167. if (this.isScrollHide) {
  6168. this.setBarHeightHide2(offset)
  6169. } else {
  6170. this.setBarHeightNormal()
  6171. }
  6172. } else {
  6173. this.setBarHeightHide(offset)
  6174. }
  6175. return { offsetRemain: offset };
  6176. })
  6177. }
  6178. @State targetFile: string = '';
  6179. setGridTwoFingers() {
  6180. this.pinchValue = this.scaleValue;
  6181. Logger.info('this.pinchValue = ' + this.pinchValue);
  6182. if (this.pinchValue >= 1) {
  6183. this.twoFingerType++
  6184. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6185. if(this.twoFingerType >= 4){
  6186. this.twoFingerType = 4//切换成瀑布流
  6187. this.columns = 4
  6188. }
  6189. } else {
  6190. this.twoFingerType--
  6191. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6192. if (this.twoFingerType < 1) {
  6193. this.twoFingerType = 3
  6194. this.isGridMusic = false
  6195. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6196. }
  6197. }
  6198. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6199. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6200. this.pinchValue = 1;
  6201. this.scaleValue = 1;
  6202. }
  6203. @State longItemFilePath: string = ''
  6204. @State tempLyricContent: string = ''
  6205. @State editingItem: VideoItem | null = null
  6206. @Builder
  6207. private MusicItemGrid(item: VideoItem, index: number) {
  6208. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6209. Stack() {
  6210. Column() {
  6211. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  6212. .height(this.getGridHeight())
  6213. .width(this.getGridWight())
  6214. .draggable(false)
  6215. .autoResize(true) // 重采样,可减少内存占用
  6216. .sourceSize({
  6217. width: this.getCoverThumbTargetSize(false),
  6218. height: this.getCoverThumbTargetSize(false)
  6219. })
  6220. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6221. .clip(true)
  6222. .borderRadius({
  6223. topLeft: 12,
  6224. topRight: 12,
  6225. bottomLeft: 0,
  6226. bottomRight: 0
  6227. })
  6228. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6229. height: '99%' ,
  6230. dragBar: true,
  6231. onDisappear: () => {
  6232. this.longItemFilePath = '';
  6233. this.tempLyricContent = ''
  6234. },
  6235. showClose: true,
  6236. preferType: SheetType.CENTER ,
  6237. title: { title: '编辑标签' }
  6238. })
  6239. .draggable(false)
  6240. .opacity(this.opacityItem)// 绑定透明度
  6241. .margin({
  6242. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6243. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6244. })
  6245. Column() {
  6246. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  6247. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6248. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  6249. .maxLines(1)
  6250. .fontWeight(FontWeight.Bold)
  6251. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6252. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6253. height: '100%',
  6254. dragBar: true,
  6255. showClose: true,
  6256. onDisappear: () => {
  6257. this.longItemFilePathDetail = '';
  6258. },
  6259. blurStyle:BlurStyle.Thin,
  6260. backgroundColor:Color.Transparent,
  6261. preferType: SheetType.CENTER ,
  6262. title: { title: '详情' }
  6263. })
  6264. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6265. $r('app.color.text_color'))
  6266. Column() {
  6267. Text(`${this.getArtistSongCount(item.name)}首`)
  6268. .fontSize(11)
  6269. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6270. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6271. .fontColor($r('app.color.text_color'))
  6272. Text(`${this.getAlbumSongCount(item.name)}首`)
  6273. .fontSize(11)
  6274. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6275. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6276. .fontColor($r('app.color.text_color'))
  6277. Row(){
  6278. Column(){
  6279. Text(item.md5Str?.includes('Lossless')?
  6280. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6281. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  6282. .padding({ top: 3,right:6,left:6,bottom:3 })
  6283. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6284. $r('app.color.text_color'))
  6285. .fontWeight(500)
  6286. .borderRadius(12)
  6287. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6288. .backgroundColor('#FFC107')
  6289. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6290. }
  6291. .margin({ top: 2 ,right:6})
  6292. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6293. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6294. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6295. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  6296. .maxLines(1)
  6297. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  6298. .margin({ top: 2})
  6299. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6300. || item.type == CommonConstants.TYPE_IS_ALBUM
  6301. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6302. .fontWeight(FontWeight.Medium)
  6303. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6304. $r('app.color.text_color'))
  6305. }
  6306. }
  6307. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6308. }
  6309. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  6310. .width(this.getGridWight())
  6311. .justifyContent(FlexAlign.Center)
  6312. .margin({
  6313. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6314. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6315. })
  6316. }
  6317. .width(this.getGridWight())
  6318. .borderRadius(12)
  6319. .backgroundColor($r('app.color.com_bg'))
  6320. Checkbox({ name: 'checkbox' + index })
  6321. .select(this.isLocalItemSelected(item))
  6322. .selectedColor(this.themeColor)
  6323. .shape(CheckBoxShape.CIRCLE)
  6324. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6325. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6326. Visibility.None)
  6327. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6328. .margin({ left: 20, top: 8, bottom: 8 })
  6329. .width(38)
  6330. .height(38)
  6331. }
  6332. }
  6333. .backgroundColor(Color.Transparent)
  6334. .width('100%')
  6335. .padding({ top: 15 })
  6336. .height(this.getGridAllHeight())
  6337. .onTouch((event: TouchEvent) => {
  6338. this.handlePointLightTouch(this.getPointLightItemKey('grid_music', item, index), event)
  6339. })
  6340. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6341. ? new hdsEffect.HdsEffectBuilder()
  6342. .pointLight({
  6343. options: this.getPointLightOptions(this.getPointLightItemKey('grid_music', item, index)),
  6344. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6345. })
  6346. .buildEffect()
  6347. : undefined)
  6348. .onClick(() => {
  6349. if (this.isMultiSelect) {
  6350. if (this.isSelectableLocalItem(item)) {
  6351. const isChecked = this.isLocalItemSelected(item);
  6352. this.handleFileSelection(item, !isChecked);
  6353. }
  6354. return
  6355. }
  6356. this.doPlay(item, index)
  6357. })
  6358. }
  6359. getGridAllHeight() {
  6360. let heightG = 222
  6361. switch (this.twoFingerType) {
  6362. case 1:
  6363. heightG = 143
  6364. break;
  6365. case 2:
  6366. heightG = 178
  6367. break;
  6368. case 3:
  6369. heightG = 222
  6370. break;
  6371. }
  6372. return heightG
  6373. }
  6374. getGridHeight() {
  6375. let heightG = 150
  6376. switch (this.twoFingerType) {
  6377. case 1:
  6378. heightG = 80
  6379. break;
  6380. case 2:
  6381. heightG = 110
  6382. break;
  6383. case 3:
  6384. heightG = 150
  6385. break;
  6386. }
  6387. return heightG
  6388. }
  6389. getGridWight() {
  6390. let wightG = 158
  6391. switch (this.twoFingerType) {
  6392. case 1:
  6393. wightG = 80
  6394. break;
  6395. case 2:
  6396. wightG = 110
  6397. break;
  6398. case 3:
  6399. wightG = 158
  6400. break;
  6401. }
  6402. return wightG
  6403. }
  6404. @State isShowDetail:boolean = false
  6405. @State longItemFilePathDetail:string =''
  6406. @Builder
  6407. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  6408. if(
  6409. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  6410. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6411. item.name === LocalMusic.STR_HISTORY_MUSIC)
  6412. ){
  6413. //如果是专辑和艺术家的首页,不能长按
  6414. //如果是我的收藏 最近播放等也不能长按
  6415. }else{
  6416. Scroll() {
  6417. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  6418. Menu() {
  6419. MenuItem({
  6420. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  6421. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  6422. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  6423. })
  6424. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6425. .onClick(() => {
  6426. if (item) {
  6427. this.doFav(item)
  6428. }
  6429. this.longItemFilePath = ''
  6430. })
  6431. MenuItem({
  6432. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  6433. content: '下一首播放'
  6434. })
  6435. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6436. .onClick(() => {
  6437. this.addToNextPlay(item);
  6438. this.longItemFilePath = ''
  6439. })
  6440. MenuItem({
  6441. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6442. content: '添加到歌单'
  6443. })
  6444. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6445. .onClick(async () => {
  6446. this.longItemFilePath = ''
  6447. await this.openAddToPlaylistDialog(item)
  6448. })
  6449. MenuItem({
  6450. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  6451. content: '编辑标签'
  6452. })
  6453. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  6454. height: '99%',
  6455. dragBar: true,
  6456. showClose: true,
  6457. preferType: SheetType.CENTER ,
  6458. title: { title: '编辑标签' }
  6459. })
  6460. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6461. .onClick(async() => {
  6462. this.initEditFields(item)
  6463. this.tempLyricContent = await this.getLyricContent(item);
  6464. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  6465. this.lyricConStr = this.tempLyricContent
  6466. }
  6467. if(this.isGridMusic||this.twoFingerType==4){
  6468. this.longItemFilePath = item.filePath
  6469. }else{
  6470. this.isShowEdit = !this.isShowEdit;
  6471. }
  6472. })
  6473. MenuItem({
  6474. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  6475. content: $r('app.string.select_all')
  6476. })
  6477. .onClick(() => {
  6478. this.longItemFilePath = ''
  6479. this.enterLocalMultiSelect(item)
  6480. })
  6481. MenuItem({
  6482. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6483. content: '提取ISO文件'
  6484. })
  6485. .visibility(this.isIsoLocalFile(item) ? Visibility.Visible : Visibility.None)
  6486. .onClick(async () => {
  6487. this.longItemFilePath = ''
  6488. await this.openIsoArchiveDialog(item)
  6489. })
  6490. MenuItem({
  6491. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  6492. content: $r('app.string.edit_audio')
  6493. })
  6494. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  6495. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6496. })
  6497. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6498. .onClick(() => {
  6499. this.isEditAudio = !this.isEditAudio
  6500. })
  6501. MenuItem({
  6502. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  6503. content: $r('app.string.extract_accompaniment')
  6504. })
  6505. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  6506. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6507. })
  6508. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6509. .onClick(() => {
  6510. if (!Utility.isNoble()) {
  6511. this.showVipDialog()
  6512. return
  6513. }
  6514. this.isExtractAcc = !this.isExtractAcc
  6515. })
  6516. MenuItem({
  6517. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  6518. content: $r('app.string.converter_audio')
  6519. })
  6520. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  6521. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6522. })
  6523. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6524. .onClick(() => {
  6525. if (!Utility.isNoble()) {
  6526. this.showVipDialog()
  6527. return
  6528. }
  6529. this.isConverter = !this.isConverter
  6530. })
  6531. // MenuItem({
  6532. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  6533. // content: $r('app.string.vocal_separation')
  6534. // })
  6535. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  6536. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6537. // })
  6538. // .onClick(() => {
  6539. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  6540. // })
  6541. MenuItem({
  6542. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  6543. content: $r('app.string.change_tone')
  6544. })
  6545. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  6546. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6547. })
  6548. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6549. .onClick(() => {
  6550. this.isChangeTone = !this.isChangeTone
  6551. })
  6552. if(Utility.isVideoByExtension(item.filePath)){
  6553. MenuItem({
  6554. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  6555. content: $r('app.string.extract_audio')
  6556. })
  6557. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  6558. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6559. })
  6560. .onClick(() => {
  6561. this.isExtractAudio = !this.isExtractAudio
  6562. })
  6563. }
  6564. MenuItem({
  6565. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  6566. content: $r('app.string.set_ring')
  6567. })
  6568. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6569. .onClick(async () => {
  6570. await PermissionUtil.activatePermission(item.filePath)
  6571. // if(item.filePath.includes(this.packName)){
  6572. setRingTone(this.context, item.filePath,item.name)
  6573. // }else{
  6574. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  6575. // }
  6576. this.longItemFilePath = ''
  6577. })
  6578. MenuItem({
  6579. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  6580. content: $r('app.string.rename')
  6581. })
  6582. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6583. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6584. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6585. .onClick(() => {
  6586. this.showReNameDialog(item, index + '', filePath)
  6587. this.longItemFilePath = ''
  6588. })
  6589. MenuItem({
  6590. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  6591. content: $r('app.string.delete')
  6592. })
  6593. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6594. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6595. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6596. .onClick(() => {
  6597. this.selectSingleItemForDelete(item)
  6598. this.showWarnIsDelete()
  6599. this.longItemFilePath = ''
  6600. })
  6601. MenuItem({
  6602. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6603. content: $r('app.string.detail')
  6604. })
  6605. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6606. height:'100%',
  6607. dragBar: true,
  6608. showClose: true,
  6609. blurStyle:BlurStyle.Thin,
  6610. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6611. backgroundColor:Color.Transparent,
  6612. title: { title: '详情信息' }
  6613. })
  6614. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6615. .onClick(() => {
  6616. if(this.isGridMusic||this.twoFingerType==4){
  6617. this.longItemFilePathDetail = item.filePath
  6618. }else{
  6619. this.isShowDetail = !this.isShowDetail
  6620. }
  6621. })
  6622. MenuItem({
  6623. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6624. content: $r('app.string.share')
  6625. })
  6626. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6627. .onClick(() => {
  6628. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6629. this.longItemFilePath = ''
  6630. })
  6631. }
  6632. .font({ size: 14, weight: FontWeight.Normal })
  6633. }
  6634. .width(180)
  6635. }
  6636. .height('auto')
  6637. .enableScrollInteraction(true)
  6638. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6639. }
  6640. }
  6641. private listMaxScrollOffsetY: number = 0
  6642. private selectedIndex: number = -1
  6643. setlistTwoFingers() {
  6644. this.pinchValue = this.scaleValue;
  6645. Logger.info('this.pinchValue = ' + this.pinchValue);
  6646. if (this.pinchValue >= 1) {
  6647. this.twoFingerType++
  6648. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6649. if (this.twoFingerType > 3) {
  6650. this.twoFingerType = 1
  6651. this.isGridMusic = true
  6652. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6653. }
  6654. } else {
  6655. this.twoFingerType--
  6656. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6657. if (this.twoFingerType < 1) {
  6658. this.twoFingerType = 4
  6659. this.columns = 1
  6660. }
  6661. }
  6662. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6663. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6664. this.pinchValue = 1;
  6665. this.scaleValue = 1;
  6666. }
  6667. @Builder
  6668. getList(){
  6669. Stack() {
  6670. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6671. this.getListView()
  6672. }
  6673. .pullDownRatio(this.ratioL)
  6674. .pullToRefresh(true)
  6675. .refreshOffset(0)
  6676. .onOffsetChange((offset: number) => {
  6677. // 越接近最大距离,下拉跟手系数越小。
  6678. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6679. })
  6680. .onStateChange((refreshStatus: RefreshStatus) => {
  6681. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6682. })
  6683. .onRefreshing(async () => {
  6684. if(this.modeType==0){
  6685. this.getHistoryList(false)
  6686. this.asyncCurrentPathOnlyFile()
  6687. }else if(this.modeType == 1){
  6688. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6689. }else if(this.modeType == 2){
  6690. workerInstance.postMessage({ code: 3, data: this.context });
  6691. }else if(this.modeType == 3){
  6692. workerInstance.postMessage({ code: 4, data: this.context });
  6693. }else if(this.modeType == 4){
  6694. this.doSongListTask()
  6695. }
  6696. console.log('onRefreshing test');
  6697. })
  6698. if (this.isLoadingPage) {
  6699. Row() {
  6700. LoadingProgress()
  6701. .width(24)
  6702. .height(24)
  6703. .color(this.themeColor)
  6704. Text('加载中...')
  6705. .margin({ left: 8 })
  6706. .fontSize(13)
  6707. .fontColor($r('app.color.text_color'))
  6708. }
  6709. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6710. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6711. .borderRadius(16)
  6712. .align(Alignment.Bottom)
  6713. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6714. }
  6715. }
  6716. }
  6717. // 扫描当前目录下的文件,不扫描子目录
  6718. asyncCurrentPathOnlyFile(){
  6719. if(this.modeType==0){
  6720. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6721. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6722. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6723. if(this.modeType==0){
  6724. setTimeout(()=>{
  6725. this.isRefreshing =false
  6726. this.deleteCache(this.currentPath)
  6727. this.getSortedFiles(this.currentPath)
  6728. },500)
  6729. }
  6730. }).catch((e:object)=>{
  6731. this.isRefreshing =false
  6732. console.info("onecold task1 catch e: " + e);
  6733. })
  6734. }
  6735. }
  6736. @Builder
  6737. getListView() {
  6738. List({ scroller: this.listScroller }) {
  6739. // ListItemGroup({ header: this.coverHeader() }) {
  6740. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6741. ListItem() {
  6742. Column() {
  6743. if (item.type === CommonConstants.TYPE_IS_DIR
  6744. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6745. this.DirItem(item, index)
  6746. } else {
  6747. this.MusicItem(item, index)
  6748. }
  6749. }
  6750. }
  6751. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6752. .swipeAction((
  6753. ((this.isSwipe && !this.isScrolling) &&
  6754. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6755. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6756. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6757. edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6758. .onClick(() => {
  6759. if (this.isMultiSelect) {
  6760. if (this.isSelectableLocalItem(item)) {
  6761. const isChecked = this.isLocalItemSelected(item);
  6762. this.handleFileSelection(item, !isChecked);
  6763. }
  6764. return
  6765. }
  6766. this.doPlay(item, index)
  6767. })
  6768. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6769. }
  6770. .onScrollStart(() => {
  6771. this.isScrolling = true
  6772. this.listVisibleStart = -1
  6773. this.listVisibleEnd = -1
  6774. this.listScrollAlphaCheckAt = 0
  6775. this.listScrollPagingCheckAt = 0
  6776. this.listScrollLastAlphaStart = -1
  6777. this.listScrollLastPagingEnd = -1
  6778. if (this.alphaBetRebuildTimer) {
  6779. clearTimeout(this.alphaBetRebuildTimer)
  6780. this.alphaBetRebuildTimer = 0
  6781. }
  6782. this.showAlphabetIndex()
  6783. })
  6784. .onScrollIndex((start: number,center:number,end:number) => {
  6785. this.selectedIndex = start
  6786. this.listVisibleStart = start
  6787. this.listVisibleEnd = end
  6788. this.lastVisibleEndIndex = end
  6789. if (!this.isMediaLibraryWarmupWindow()) {
  6790. this.warmupListVisibleThumbs(start, end)
  6791. }
  6792. const now = Date.now()
  6793. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  6794. if (!this.isMediaLibraryWarmupWindow() &&
  6795. start >= 0 && start < this.videoLocalList.length &&
  6796. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  6797. this.listScrollAlphaCheckAt = now
  6798. this.listScrollLastAlphaStart = start
  6799. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6800. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  6801. this.selectAlphaBetIndex = nextAlphaIndex
  6802. }
  6803. }
  6804. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  6805. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  6806. this.listScrollPagingCheckAt = now
  6807. this.listScrollLastPagingEnd = end
  6808. this.tryTriggerLoadNextPageByScroll(end)
  6809. }
  6810. })
  6811. .onScrollStop(() => {
  6812. if(this.isScrolling){
  6813. this.isScrolling = false
  6814. }
  6815. this.flushPendingCoverThumbRefresh()
  6816. if (this.alphaBetDirty) {
  6817. this.scheduleAlphaBetRebuild(0)
  6818. }
  6819. this.hideAlphabetIndexAfterDelay(1500)
  6820. })
  6821. .onReachEnd(() => {
  6822. if(this.modeType === 4 )//歌单不能加载下一页
  6823. return;
  6824. // 触底加载下一页
  6825. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6826. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6827. return;
  6828. }
  6829. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6830. this.scheduleLoadNextPage();
  6831. }
  6832. })
  6833. .scrollBar(BarState.Off)
  6834. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6835. .gesture(PinchGesture({ fingers: 2 })
  6836. .onActionEnd((event: GestureEvent) => {
  6837. this.setlistTwoFingers()
  6838. })
  6839. .onActionUpdate(e => {
  6840. this.scaleValue = this.pinchValue * e.scale
  6841. })
  6842. .onActionStart(e => {
  6843. }))
  6844. .contentStartOffset(this.topSafeHeight + 55)
  6845. .scrollBar(BarState.Off)
  6846. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6847. .cachedCount(this.modeType == 1 ? 4 : 8)
  6848. // .reuseId('list_item')
  6849. .borderRadius(20)
  6850. .layoutWeight(1)
  6851. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6852. .lanes(
  6853. new BreakpointType<number>({
  6854. sm: 1,
  6855. md: 2,
  6856. lg: 2,
  6857. xl: 3,
  6858. xxl: 4
  6859. }).getValue(this.currentBreakpoint),
  6860. new BreakpointType<number>({
  6861. sm: 0,
  6862. md: 12,
  6863. lg: 12,
  6864. xl: 16,
  6865. xxl: 20
  6866. }).getValue(this.currentBreakpoint)
  6867. )
  6868. .onAreaChange((oldValue: Area, newValue: Area) => {
  6869. this.listArea = newValue
  6870. if (this.twoFingerType == 3) {
  6871. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6872. } else if (this.twoFingerType == 2) {
  6873. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6874. } else if (this.twoFingerType == 1) {
  6875. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6876. }
  6877. })
  6878. .onScrollFrameBegin((offset: number) => {
  6879. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6880. this.updateTitleBarByScrollOffset(currentOffsetY)
  6881. return { offsetRemain: offset };
  6882. })
  6883. }
  6884. setBarHeightNormal() {
  6885. this.hideDone = false;
  6886. this.getUIContext().animateTo({
  6887. duration: 300
  6888. }, () => {
  6889. this.bottomBarHeight = 68 + 0;
  6890. this.topBarHeight = 50 + 0;
  6891. this.barOpacity = 1;
  6892. this.barBottomOpacity = 1
  6893. this.currentYOffset = 0;
  6894. this.isHiding = false;
  6895. });
  6896. }
  6897. setBarHeightHide(offset: number) {
  6898. if (offset > 0 && !this.hideDone) {
  6899. this.currentYOffset += offset;
  6900. if (this.currentYOffset <= 100) {
  6901. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6902. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6903. this.barOpacity = 1 - this.currentYOffset / 100;
  6904. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6905. } else {
  6906. this.topBarHeight = 0;
  6907. this.bottomBarHeight = 0;
  6908. this.barBottomOpacity = 0
  6909. this.barOpacity = 0;
  6910. this.hideDone = true;
  6911. }
  6912. this.isHiding = true;
  6913. }
  6914. if (offset < 0 && this.isHiding) {
  6915. this.hideDone = false;
  6916. this.getUIContext().animateTo({
  6917. duration: 300
  6918. }, () => {
  6919. this.bottomBarHeight = 68 + 0;
  6920. this.topBarHeight = 50 + 0;
  6921. this.barOpacity = 1;
  6922. this.barBottomOpacity = 1
  6923. this.currentYOffset = 0;
  6924. this.isHiding = false;
  6925. });
  6926. }
  6927. }
  6928. //这个方法没隐藏bottomBar,只隐藏topbar
  6929. setBarHeightHide2(offset: number) {
  6930. if (offset > 0 && !this.hideDone) {
  6931. this.currentYOffset += offset;
  6932. if (this.currentYOffset <= 100) {
  6933. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6934. this.barOpacity = 1 - this.currentYOffset / 100;
  6935. } else {
  6936. this.topBarHeight = 0;
  6937. this.barOpacity = 0;
  6938. this.hideDone = true;
  6939. }
  6940. this.isHiding = true;
  6941. }
  6942. if (offset < 0 && this.isHiding) {
  6943. this.hideDone = false;
  6944. this.getUIContext().animateTo({
  6945. duration: 300
  6946. }, () => {
  6947. this.topBarHeight = 50 + 0;
  6948. this.barOpacity = 1;
  6949. this.currentYOffset = 0;
  6950. this.isHiding = false;
  6951. });
  6952. }
  6953. }
  6954. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6955. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6956. switch (item.type) {
  6957. case CommonConstants.TYPE_IS_DIR:
  6958. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6959. let shouldScrollTopNow = true
  6960. let offsetB = 0
  6961. if(this.twoFingerType==4){
  6962. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6963. let cur = this.waterScroller.currentOffset()
  6964. if (cur && typeof cur.yOffset === 'number') {
  6965. offsetB = cur.yOffset
  6966. }
  6967. }
  6968. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6969. }else
  6970. if (this.isGridMusic) {
  6971. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6972. let cur = this.scroller.currentOffset()
  6973. if (cur && typeof cur.yOffset === 'number') {
  6974. offsetB = cur.yOffset
  6975. }
  6976. }
  6977. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6978. } else {
  6979. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6980. let cur = this.listScroller.currentOffset()
  6981. if (cur && typeof cur.yOffset === 'number') {
  6982. offsetB = cur.yOffset
  6983. }
  6984. }
  6985. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6986. }
  6987. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6988. this.showVerifyDialog()
  6989. this.currentTitleName = '私密音频'
  6990. this.currentTitleCover = $r('app.media.alt')
  6991. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6992. this.titleName = '最近播放'
  6993. this.currentTitleCover = $r('app.media.alt')
  6994. this.currentTitleName = '最近播放'
  6995. //加载动画效果
  6996. this.updateListData(this.historyList, true)
  6997. // this.videoLocalList = this.historyList
  6998. if (ArrayUtil.isEmpty(this.historyList)) {
  6999. ToastUtil.showToast('最近播放记录空空如也')
  7000. } else {
  7001. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  7002. }
  7003. this.isHistory = true
  7004. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  7005. this.titleName = '我的收藏'
  7006. this.currentTitleName = '我的收藏'
  7007. this.currentTitleCover = $r('app.media.alt')
  7008. //加载动画效果
  7009. this.updateListData(this.favList, true)
  7010. if (ArrayUtil.isEmpty(this.favList)) {
  7011. ToastUtil.showToast('无音乐收藏记录')
  7012. } else {
  7013. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  7014. }
  7015. this.isFavMusic = true
  7016. } else {
  7017. this.currentTitleName = item.name
  7018. this.currentPath = item.filePath
  7019. this.currentTitleCover = $r('app.media.alt')
  7020. shouldScrollTopNow = false
  7021. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  7022. }
  7023. //进入歌单的时候的滚动位置在顶部
  7024. if (shouldScrollTopNow) {
  7025. if(this.twoFingerType==4){
  7026. setTimeout(() => {
  7027. this.waterScroller.scrollEdge(Edge.Top)
  7028. this.scroller.scrollEdge(Edge.Top)
  7029. }, 200)
  7030. }else{
  7031. if (this.isGridMusic) {
  7032. this.scroller.scrollToIndex(0,false)
  7033. }else{
  7034. this.listScroller.scrollToIndex(0,false)
  7035. }
  7036. }
  7037. }
  7038. this.rightTopImage = $r('sys.symbol.chevron_left')
  7039. break;
  7040. case CommonConstants.TYPE_IS_ARTIST:
  7041. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  7042. let offsetA = 0
  7043. if(this.twoFingerType==4){
  7044. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7045. let cur = this.waterScroller.currentOffset()
  7046. if (cur && typeof cur.yOffset === 'number') {
  7047. offsetA = cur.yOffset
  7048. }
  7049. }
  7050. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  7051. }else
  7052. if (this.isGridMusic) {
  7053. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7054. let cur = this.scroller.currentOffset()
  7055. if (cur && typeof cur.yOffset === 'number') {
  7056. offsetA = cur.yOffset
  7057. }
  7058. }
  7059. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  7060. } else {
  7061. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7062. let cur = this.listScroller.currentOffset()
  7063. if (cur && typeof cur.yOffset === 'number') {
  7064. offsetA = cur.yOffset
  7065. }
  7066. }
  7067. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  7068. }
  7069. // 进入艺术家详情页前,先加载详情页的排序类型
  7070. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7071. const artistOriginalIsCanBack = this.isCanBack;
  7072. this.isCanBack = true;
  7073. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  7074. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  7075. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  7076. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7077. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  7078. let mList = this.artistMap.get(artistCacheKey)
  7079. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  7080. // 使用详情页的排序类型查询
  7081. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  7082. if (ArrayUtil.isNotEmpty(mList)) {
  7083. this.artistMap.set(artistCacheKey, mList);
  7084. }
  7085. }
  7086. // 设置当前排序类型为详情页排序
  7087. this.sortType = artistDetailSortType;
  7088. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  7089. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  7090. const nextArtistCountMap = new Map(this.artistSongCountMap);
  7091. nextArtistCountMap.set(item.name, mList.length);
  7092. this.artistSongCountMap = nextArtistCountMap;
  7093. this.isCanBack = true
  7094. this.hasMoreData = false
  7095. this.isLoadingPage = false
  7096. this.pageCache.clear()
  7097. this.pageHasMoreCache.clear()
  7098. this.pageTotalCountCache.clear()
  7099. this.prefetchingPages.clear()
  7100. this.lastScrollTriggerPage = -1
  7101. this.lastVisibleEndIndex = -1
  7102. this.isPagingTransition = false
  7103. if (this.pagingScheduleTimer) {
  7104. clearTimeout(this.pagingScheduleTimer)
  7105. this.pagingScheduleTimer = 0
  7106. }
  7107. this.totalCount = mList.length
  7108. this.titleName = item.name
  7109. this.currentTitleName = '艺术家:' + item.name
  7110. if (item.pixelMapPath) {
  7111. this.currentTitleCover = item.pixelMapPath
  7112. }
  7113. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7114. } else {
  7115. ToastUtil.showToast('未找到该艺术家的歌曲');
  7116. return;
  7117. }
  7118. this.rightTopImage = $r('sys.symbol.chevron_left')
  7119. //进入歌单的时候的滚动位置在顶部
  7120. if(this.twoFingerType==4){
  7121. setTimeout(() => {
  7122. this.waterScroller.scrollEdge(Edge.Top)
  7123. this.scroller.scrollEdge(Edge.Top)
  7124. }, 380)
  7125. }else{
  7126. if (this.isGridMusic) {
  7127. this.scroller.scrollEdge(Edge.Top)
  7128. }else{
  7129. this.listScroller.scrollEdge(Edge.Top)
  7130. }
  7131. }
  7132. break;
  7133. case CommonConstants.TYPE_IS_ALBUM:
  7134. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  7135. let offset = 0
  7136. if(this.twoFingerType==4){
  7137. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7138. let cur = this.waterScroller.currentOffset()
  7139. if (cur && typeof cur.yOffset === 'number') {
  7140. offset = cur.yOffset
  7141. }
  7142. }
  7143. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  7144. }else
  7145. if (this.isGridMusic) {
  7146. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7147. let cur = this.scroller.currentOffset()
  7148. if (cur && typeof cur.yOffset === 'number') {
  7149. offset = cur.yOffset
  7150. }
  7151. }
  7152. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  7153. } else {
  7154. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7155. let cur = this.listScroller.currentOffset()
  7156. if (cur && typeof cur.yOffset === 'number') {
  7157. offset = cur.yOffset
  7158. }
  7159. }
  7160. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  7161. }
  7162. // 进入专辑详情页前,先加载详情页的排序类型
  7163. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7164. const albumOriginalIsCanBack = this.isCanBack;
  7165. this.isCanBack = true;
  7166. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  7167. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  7168. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  7169. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7170. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  7171. let albumList = this.albumMap.get(albumCacheKey)
  7172. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  7173. // 使用详情页的排序类型查询
  7174. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  7175. if (ArrayUtil.isNotEmpty(albumList)) {
  7176. this.albumMap.set(albumCacheKey, albumList);
  7177. }
  7178. }
  7179. // 设置当前排序类型为详情页排序
  7180. this.sortType = albumDetailSortType;
  7181. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  7182. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  7183. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  7184. nextAlbumCountMap.set(item.name, albumList.length);
  7185. this.albumSongCountMap = nextAlbumCountMap;
  7186. this.isCanBack = true
  7187. this.hasMoreData = false
  7188. this.isLoadingPage = false
  7189. this.pageCache.clear()
  7190. this.pageHasMoreCache.clear()
  7191. this.pageTotalCountCache.clear()
  7192. this.prefetchingPages.clear()
  7193. this.lastScrollTriggerPage = -1
  7194. this.lastVisibleEndIndex = -1
  7195. this.isPagingTransition = false
  7196. if (this.pagingScheduleTimer) {
  7197. clearTimeout(this.pagingScheduleTimer)
  7198. this.pagingScheduleTimer = 0
  7199. }
  7200. this.totalCount = albumList.length
  7201. this.titleName = item.name
  7202. this.currentTitleName = '专辑:' + item.name
  7203. if (item.pixelMapPath) {
  7204. this.currentTitleCover = item.pixelMapPath
  7205. }
  7206. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7207. this.mScrollMap.set(item.name, this.selectedIndex)
  7208. this.rightTopImage = $r('sys.symbol.chevron_left')
  7209. } else {
  7210. ToastUtil.showToast('未找到该专辑的歌曲');
  7211. return;
  7212. }
  7213. //进入歌单的时候的滚动位置在顶部
  7214. if(this.twoFingerType==4){
  7215. setTimeout(() => {
  7216. this.waterScroller.scrollEdge(Edge.Top)
  7217. this.scroller.scrollEdge(Edge.Top)
  7218. }, 380)
  7219. }else{
  7220. if (this.isGridMusic) {
  7221. this.scroller.scrollEdge(Edge.Top)
  7222. }else{
  7223. this.listScroller.scrollEdge(Edge.Top)
  7224. }
  7225. }
  7226. break;
  7227. case CommonConstants.TYPE_IS_CSJAD:
  7228. return
  7229. break;
  7230. case CommonConstants.TYPE_LOCAL:
  7231. if (this.isIsoLocalFile(item)) {
  7232. await this.openIsoArchiveDialog(item)
  7233. return
  7234. }
  7235. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  7236. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  7237. const cueTracks:CueTrack[] = cueinfo.tracks
  7238. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  7239. if(ArrayUtil.isNotEmpty(cueTracks)){
  7240. this.showCueDialog(cueTracks,cueinfo)
  7241. }
  7242. // this.showCueSheet = !this.showCueSheet
  7243. return
  7244. }
  7245. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7246. this.stop();
  7247. }
  7248. if (isOpen) {
  7249. this.currentSong = item
  7250. if (index !== undefined) {
  7251. this.curIndex = index
  7252. }
  7253. this.songList = []
  7254. this.songList.push(item)
  7255. this.sonDataSource.pushArrayData(this.songList)
  7256. this.playQueueScope = 'single'
  7257. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  7258. this.currentSong = item
  7259. if (index !== undefined) {
  7260. this.curIndex = index
  7261. }
  7262. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7263. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  7264. this.playQueueScope = 'playlist'
  7265. // 确保歌单路径列表已设置(从songList重新构建,以防被清空)
  7266. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7267. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7268. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7269. }
  7270. }else {
  7271. const globalVideoList = this.buildPlayQueueFromView();
  7272. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  7273. if (this.curIndex < 0) {
  7274. globalVideoList.push(item);
  7275. this.curIndex = globalVideoList.length - 1;
  7276. }
  7277. this.songList = globalVideoList
  7278. this.sonDataSource.pushArrayData(this.songList)
  7279. this.currentSong = this.songList[this.curIndex]
  7280. // 只在非歌单模式下清空歌单路径列表
  7281. if (this.modeType !== 4) {
  7282. this.currentPlaylistSongFilePaths = [];
  7283. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  7284. } else {
  7285. // 歌单模式:确保歌单路径列表已设置
  7286. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7287. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7288. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7289. } else {
  7290. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7291. }
  7292. }
  7293. }
  7294. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7295. try {
  7296. const localUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-local');
  7297. this.videoUrl = localUrl || this.currentSong.filePath
  7298. } catch (error) {
  7299. Logger.error(TAG, `本地歌曲构建播放地址失败: ${(error as Error).message}`);
  7300. this.videoUrl = this.currentSong.filePath
  7301. }
  7302. this.name = this.currentSong.name
  7303. this.cover = this.currentSong.pixelMapPath
  7304. this.artist = this.currentSong.artist
  7305. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  7306. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  7307. this.startPlayOrResumePlay()
  7308. break;
  7309. case CommonConstants.TYPE_WEBDAV:
  7310. case CommonConstants.TYPE_SMB:
  7311. case CommonConstants.TYPE_NAVIDROME:
  7312. case CommonConstants.TYPE_FTP:
  7313. case CommonConstants.TYPE_BAIDU:
  7314. case CommonConstants.TYPE_JELLYFIN:
  7315. case CommonConstants.TYPE_EMBY:
  7316. case CommonConstants.TYPE_AUDIOSTATION:
  7317. case CommonConstants.TYPE_PLEX:
  7318. case CommonConstants.TYPE_DAOLIYU:
  7319. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  7320. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  7321. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7322. this.stop();
  7323. }
  7324. if (isOpen) {
  7325. this.currentSong = item
  7326. if (index !== undefined) {
  7327. this.curIndex = index
  7328. }
  7329. this.songList = []
  7330. this.songList.push(item)
  7331. this.sonDataSource.pushArrayData(this.songList)
  7332. } else if (isFromSonPlayList) {
  7333. // 点击来自右下角的播放列表
  7334. this.currentSong = item
  7335. if (index !== undefined) {
  7336. this.curIndex = index
  7337. }
  7338. // 设置播放队列作用域为歌单
  7339. this.playQueueScope = 'playlist'
  7340. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7341. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  7342. } else {
  7343. // 从全局网络音频列表中查找
  7344. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  7345. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  7346. if (this.curIndex === -1 && index !== undefined) {
  7347. this.curIndex = index;
  7348. }
  7349. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  7350. this.currentSong = this.songList[this.curIndex];
  7351. this.sonDataSource.pushArrayData(this.songList)
  7352. }
  7353. await this.hydrateRemoteSongFromDb(this.currentSong);
  7354. await this.hydrateRemoteSongFromDb(this.currentSong);
  7355. AppStorage.setOrCreate('currentSong', this.currentSong);
  7356. const remotePlayLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  7357. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-remote');
  7358. if (!playbackUrl) {
  7359. if (remotePlayLoading) {
  7360. this.hideLoadIng();
  7361. }
  7362. return;
  7363. }
  7364. this.videoUrl = playbackUrl;
  7365. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  7366. this.name = this.currentSong.name
  7367. this.cover = this.currentSong.pixelMapPath
  7368. this.artist = this.currentSong.artist
  7369. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  7370. this.startPlayOrResumePlay()
  7371. break;
  7372. }
  7373. }
  7374. private async openIsoArchiveDialog(item: VideoItem): Promise<void> {
  7375. if (!item || StrUtil.isEmpty(item.filePath)) {
  7376. Logger.error(TAG, `heanup ISO open dialog invalid path=${item ? item.filePath : ''}`)
  7377. ToastUtil.showToast('ISO 文件无效')
  7378. return
  7379. }
  7380. if (this.isIsoExtracting) {
  7381. if (ArrayUtil.isNotEmpty(this.isoAudioEntries)) {
  7382. if (this.isoSourceFilePath !== item.filePath) {
  7383. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行,已打开提取进度窗口')
  7384. }
  7385. this.presentIsoArchiveDialog()
  7386. return
  7387. }
  7388. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行')
  7389. return
  7390. }
  7391. Logger.info(TAG, `heanup ISO open dialog path=${item.filePath}, name=${item.fileName || item.name}`)
  7392. this.closeIsoDialog()
  7393. this.isoSourceFilePath = item.filePath
  7394. this.isoSourceFileName = item.fileName || item.name
  7395. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  7396. progress: 0,
  7397. backCancel: false,
  7398. autoCancel: false,
  7399. loadColor: this.themeColor,
  7400. fontColor: this.themeColor
  7401. })
  7402. try {
  7403. const task = new taskpool.Task(listIsoAudioEntriesTask, item.filePath)
  7404. const entries = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoArchiveAudioEntry[]
  7405. this.isoAudioEntries = Array.isArray(entries) ? entries : []
  7406. Logger.info(TAG, `heanup ISO list entries done count=${this.isoAudioEntries.length}, path=${item.filePath}`)
  7407. if (ArrayUtil.isEmpty(this.isoAudioEntries)) {
  7408. Logger.error(TAG, `heanup ISO list entries empty path=${item.filePath}`)
  7409. ToastUtil.showToast('ISO 内未发现可提取的媒体文件')
  7410. this.closeIsoDialog()
  7411. return
  7412. }
  7413. this.selectedIsoAudioPaths = []
  7414. } catch (error) {
  7415. Logger.error(TAG, `heanup 解析 ISO 失败: ${(error as Error).message}`)
  7416. ToastUtil.showToast('解析 ISO 失败')
  7417. this.closeIsoDialog()
  7418. return
  7419. } finally {
  7420. if (this.loadingProgressDialogId) {
  7421. DialogHelper.closeDialog(this.loadingProgressDialogId)
  7422. this.loadingProgressDialogId = ''
  7423. }
  7424. }
  7425. this.presentIsoArchiveDialog()
  7426. }
  7427. private presentIsoArchiveDialog(): void {
  7428. if (this.isoComponentId > 0) {
  7429. return
  7430. }
  7431. this.getUIContext().getPromptAction().openCustomDialog({
  7432. builder: () => {
  7433. this.isoComptentBuilder()
  7434. },
  7435. isModal: true,
  7436. showInSubWindow: false,
  7437. maskColor: Color.Transparent,
  7438. dialogTransition: TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7439. .animation({ duration: 600, curve: Curve.Smooth }),
  7440. maskTransition: TransitionEffect.opacity(0.5)
  7441. .animation({ duration: 600, curve: Curve.Smooth })
  7442. }).then((dialogId: number) => {
  7443. this.isoComponentId = dialogId
  7444. }).catch((error: BusinessError) => {
  7445. Logger.error(TAG, `heanup 打开 ISO 弹窗失败: ${error.message}`)
  7446. this.closeIsoDialog()
  7447. })
  7448. }
  7449. private toggleIsoEntrySelection(path: string, checked: boolean): void {
  7450. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7451. if (checked) {
  7452. selectedPathSet.add(path)
  7453. } else {
  7454. selectedPathSet.delete(path)
  7455. }
  7456. this.selectedIsoAudioPaths = this.isoAudioEntries
  7457. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7458. .map((entry: IsoArchiveAudioEntry) => entry.path)
  7459. Logger.info(TAG,
  7460. `heanup ISO toggle selection path=${path}, checked=${checked}, total=${this.selectedIsoAudioPaths.length}`)
  7461. }
  7462. private toggleIsoEntrySelectAll(): void {
  7463. if (this.selectedIsoAudioPaths.length === this.isoAudioEntries.length) {
  7464. this.selectedIsoAudioPaths = []
  7465. Logger.info(TAG, 'heanup ISO toggle select all cleared')
  7466. return
  7467. }
  7468. this.selectedIsoAudioPaths = this.isoAudioEntries.map((entry: IsoArchiveAudioEntry) => entry.path)
  7469. Logger.info(TAG, `heanup ISO toggle select all count=${this.selectedIsoAudioPaths.length}`)
  7470. }
  7471. private startIsoExtractProgressWatcher(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): void {
  7472. this.stopIsoExtractProgressWatcher()
  7473. this.isoExtractExpectedOutputPaths = this.buildIsoExtractExpectedOutputPaths(entries, destinationDir)
  7474. this.isoExtractTotalBytes = entries.reduce((total: number, entry: IsoArchiveAudioEntry) => {
  7475. const size = entry && entry.size > 0 ? entry.size : 0
  7476. return total + size
  7477. }, 0)
  7478. this.isoExtractReceivedTaskProgress = false
  7479. this.isoExtractDisplayedProgress = 0
  7480. this.isoExtractLastActivityTime = Date.now()
  7481. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths)) {
  7482. return
  7483. }
  7484. this.isoExtractProgressTimer = setInterval(() => {
  7485. this.updateIsoExtractProgressFromFiles()
  7486. }, 500)
  7487. }
  7488. private stopIsoExtractProgressWatcher(): void {
  7489. if (this.isoExtractProgressTimer) {
  7490. clearInterval(this.isoExtractProgressTimer)
  7491. this.isoExtractProgressTimer = 0
  7492. }
  7493. this.isoExtractExpectedOutputPaths = []
  7494. this.isoExtractTotalBytes = 0
  7495. this.isoExtractReceivedTaskProgress = false
  7496. this.isoExtractLastActivityTime = 0
  7497. }
  7498. private markIsoExtractActivity(): void {
  7499. this.isoExtractLastActivityTime = Date.now()
  7500. }
  7501. private updateIsoExtractProgressFromFiles(): void {
  7502. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths) ||
  7503. this.isoExtractReceivedTaskProgress) {
  7504. return
  7505. }
  7506. let writtenBytes = 0
  7507. let existingCount = 0
  7508. for (let i = 0; i < this.isoExtractExpectedOutputPaths.length; i++) {
  7509. const outputPath = this.isoExtractExpectedOutputPaths[i]
  7510. if (!FileUtil.accessSync(outputPath)) {
  7511. continue
  7512. }
  7513. existingCount++
  7514. try {
  7515. const stat = fs.statSync(outputPath) as fs.Stat
  7516. if (typeof stat.size === 'number' && stat.size > 0) {
  7517. writtenBytes += stat.size
  7518. }
  7519. } catch (_error) {
  7520. }
  7521. }
  7522. let progress = 0
  7523. if (writtenBytes > 0) {
  7524. progress = Math.ceil((writtenBytes / this.isoExtractTotalBytes) * 100)
  7525. if (progress > 99) {
  7526. progress = 99
  7527. }
  7528. this.markIsoExtractActivity()
  7529. } else if (existingCount > 0) {
  7530. progress = 1
  7531. this.markIsoExtractActivity()
  7532. }
  7533. if (progress > 0) {
  7534. this.updateIsoExtractProgressState(progress,
  7535. `正在提取 ${progress}% (${existingCount}/${this.isoExtractExpectedOutputPaths.length})`)
  7536. return
  7537. }
  7538. if (this.isoExtractTask && this.isoExtractLastActivityTime > 0 &&
  7539. Date.now() - this.isoExtractLastActivityTime > this.isoExtractStallTimeoutMs) {
  7540. Logger.warn(TAG, `heanup ISO 提取进度长时间无变化: timeout=${this.isoExtractStallTimeoutMs}`)
  7541. this.markIsoExtractActivity()
  7542. this.updateIsoExtractProgressState(1, '准备提取 1%')
  7543. }
  7544. }
  7545. private updateIsoExtractProgressState(progress: number, message: string, currentName: string = '',
  7546. force: boolean = false): void {
  7547. let safeProgress = progress
  7548. if (safeProgress < 0) {
  7549. safeProgress = 0
  7550. }
  7551. if (safeProgress > 100) {
  7552. safeProgress = 100
  7553. }
  7554. if (!force && safeProgress < this.isoExtractDisplayedProgress) {
  7555. return
  7556. }
  7557. this.isoExtractDisplayedProgress = safeProgress
  7558. this.isoExtractProgress = safeProgress
  7559. this.isoExtractProgressText = message
  7560. if (force || StrUtil.isNotEmpty(currentName)) {
  7561. this.isoExtractCurrentEntryName = currentName
  7562. }
  7563. }
  7564. private resetIsoExtractProgressState(): void {
  7565. this.isoExtractProgress = 0
  7566. this.isoExtractProgressText = ''
  7567. this.isoExtractCurrentEntryName = ''
  7568. this.isoExtractDisplayedProgress = 0
  7569. }
  7570. private buildIsoExtractExpectedOutputPaths(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): Array<string> {
  7571. const outputPaths: Array<string> = []
  7572. const occupiedPaths: Set<string> = new Set<string>()
  7573. for (let i = 0; i < entries.length; i++) {
  7574. const entry = entries[i]
  7575. const fileName = entry.name || this.getIsoLastPathSegment(entry.path)
  7576. const outputPath = this.buildIsoExpectedOutputPath(destinationDir, fileName, occupiedPaths)
  7577. occupiedPaths.add(outputPath)
  7578. outputPaths.push(outputPath)
  7579. }
  7580. return outputPaths
  7581. }
  7582. private buildIsoExpectedOutputPath(destinationDir: string, fileName: string, occupiedPaths: Set<string>): string {
  7583. const cleanName = this.sanitizeIsoOutputFileName(fileName)
  7584. const extension = this.getIsoOutputFileExtension(cleanName)
  7585. const baseName = extension.length > 0 ? cleanName.substring(0, cleanName.length - extension.length) : cleanName
  7586. let candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${cleanName}`
  7587. let suffix = 0
  7588. while (occupiedPaths.has(candidatePath) || FileUtil.accessSync(candidatePath)) {
  7589. suffix++
  7590. candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${baseName} (${suffix})${extension}`
  7591. }
  7592. return candidatePath
  7593. }
  7594. private sanitizeIsoOutputFileName(fileName: string): string {
  7595. const lastSegment = this.getIsoLastPathSegment(fileName)
  7596. let sanitized = ''
  7597. for (let i = 0; i < lastSegment.length; i++) {
  7598. const char = lastSegment[i]
  7599. if (char === '/' || char === '\\' || char === ':' || char === '*' || char === '?' || char === '"' ||
  7600. char === '<' || char === '>' || char === '|') {
  7601. sanitized += '_'
  7602. } else {
  7603. sanitized += char
  7604. }
  7605. }
  7606. if (sanitized.trim().length === 0) {
  7607. return 'iso_audio.bin'
  7608. }
  7609. return sanitized
  7610. }
  7611. private getIsoLastPathSegment(path: string): string {
  7612. const normalizedPath = path.replace(/\\/g, '/')
  7613. const lastSeparator = normalizedPath.lastIndexOf('/')
  7614. if (lastSeparator < 0) {
  7615. return normalizedPath
  7616. }
  7617. return normalizedPath.substring(lastSeparator + 1)
  7618. }
  7619. private getIsoOutputFileExtension(fileName: string): string {
  7620. const lastDot = fileName.lastIndexOf('.')
  7621. if (lastDot < 0) {
  7622. return ''
  7623. }
  7624. return fileName.substring(lastDot)
  7625. }
  7626. private trimIsoOutputTrailingSeparator(path: string): string {
  7627. if (path.endsWith('/')) {
  7628. return path.substring(0, path.length - 1)
  7629. }
  7630. return path
  7631. }
  7632. private cancelIsoExtraction(reason?: string): void {
  7633. const currentTask = this.isoExtractTask
  7634. Logger.info(TAG,
  7635. `heanup ISO cancel request reason=${reason || ''}, hasTask=${currentTask ? 'true' : 'false'}`)
  7636. this.isoExtractCanceled = true
  7637. this.isoExtractCancelMessage = reason ? reason : ''
  7638. this.isoExtractTask = undefined
  7639. this.updateIsoExtractProgressState(this.isoExtractProgress, '正在停止提取...', this.isoExtractCurrentEntryName, true)
  7640. if (currentTask) {
  7641. try {
  7642. taskpool.terminateTask(currentTask)
  7643. } catch (error) {
  7644. Logger.error(TAG, `heanup 终止 ISO 提取任务失败: ${(error as Error).message}`)
  7645. }
  7646. }
  7647. }
  7648. private moveIsoExtractionToBackground(): void {
  7649. this.closeIsoDialog(false)
  7650. ToastUtil.showToast('ISO 提取已转入后台')
  7651. }
  7652. private async extractSelectedIsoAudioFiles(): Promise<void> {
  7653. if (this.isIsoExtracting) {
  7654. return
  7655. }
  7656. if (ArrayUtil.isEmpty(this.selectedIsoAudioPaths)) {
  7657. ToastUtil.showToast('请先选择要提取的文件')
  7658. return
  7659. }
  7660. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7661. const selectedEntries = this.isoAudioEntries
  7662. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7663. if (ArrayUtil.isEmpty(selectedEntries)) {
  7664. ToastUtil.showToast('未找到要提取的文件')
  7665. return
  7666. }
  7667. const hasSacdTrack: boolean = selectedEntries.some((entry: IsoArchiveAudioEntry) => entry.entryType === 'sacd_track')
  7668. const destinationDir: string = this.currentPath
  7669. this.isIsoExtracting = true
  7670. this.isoExtractCanceled = false
  7671. this.isoExtractCancelMessage = ''
  7672. this.isoExtractDestinationDir = destinationDir
  7673. Logger.info(TAG,
  7674. `heanup ISO extract start file=${this.isoSourceFilePath}, selected=${selectedEntries.length}, ` +
  7675. `hasSacd=${hasSacdTrack}, destinationDir=${destinationDir}`)
  7676. Logger.info(TAG,
  7677. `heanup ISO selected entries: ${selectedEntries.map((entry: IsoArchiveAudioEntry) => entry.path).join(', ')}`)
  7678. this.resetIsoExtractProgressState()
  7679. this.updateIsoExtractProgressState(1, '准备提取 1%', '', true)
  7680. this.startIsoExtractProgressWatcher(selectedEntries, destinationDir)
  7681. try {
  7682. const extractStartedAt = Date.now()
  7683. const outputPaths: string[] = this.buildIsoExtractExpectedOutputPaths(selectedEntries, destinationDir)
  7684. const payloadJson = JSON.stringify({
  7685. isoPath: this.isoSourceFilePath,
  7686. destinationDir,
  7687. entries: selectedEntries,
  7688. outputPaths
  7689. })
  7690. const task = new taskpool.Task(extractIsoAudioEntriesTask, payloadJson)
  7691. this.isoExtractTask = task
  7692. task.onReceiveData((progressData: IsoExtractProgressMessage) => {
  7693. this.markIsoExtractActivity()
  7694. const progress = typeof progressData.progress === 'number' ? Math.floor(progressData.progress) : 0
  7695. Logger.info(TAG,
  7696. `heanup ISO task receive stage=${progressData.stage || ''}, progress=${progress}, name=${progressData.name || ''}`)
  7697. if (progress > 1 && !this.isoExtractReceivedTaskProgress) {
  7698. this.isoExtractReceivedTaskProgress = true
  7699. if (this.isoExtractProgressTimer) {
  7700. clearInterval(this.isoExtractProgressTimer)
  7701. this.isoExtractProgressTimer = 0
  7702. }
  7703. Logger.info(TAG, `heanup ISO 提取切换为任务进度: progress=${progress}, stage=${progressData.stage || ''}`)
  7704. }
  7705. const stageText = progressData.stage === 'prepare' ? '准备提取' :
  7706. (progressData.stage === 'done' ? '提取完成' : (progressData.stage === 'error' ? '提取异常' : '正在提取'))
  7707. if (progress > this.isoExtractDisplayedProgress || progressData.stage !== 'extract') {
  7708. Logger.info(TAG,
  7709. `heanup ISO 提取任务进度: stage=${progressData.stage || ''}, progress=${progress}, ` +
  7710. `name=${progressData.name || ''}`)
  7711. }
  7712. this.updateIsoExtractProgressState(progress, `${stageText} ${progress}%`, progressData.name || '')
  7713. })
  7714. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoExtractTaskResult
  7715. const extractElapsedMs = Date.now() - extractStartedAt
  7716. this.isoExtractTask = undefined
  7717. Logger.info(TAG, `heanup ISO extract task completed canceled=${this.isoExtractCanceled}, elapsedMs=${extractElapsedMs}`)
  7718. if (this.isoExtractCanceled) {
  7719. return
  7720. }
  7721. const extractedPaths = result?.extractedPaths || []
  7722. const failedEntries = result?.failedEntries || []
  7723. const failureDetails = result?.failureDetails || []
  7724. Logger.info(TAG,
  7725. `heanup ISO extract result extracted=${extractedPaths.length}, failed=${failedEntries.length}, details=${failureDetails.length}`)
  7726. let importErrorMessage: string = ''
  7727. let importedCount: number = 0
  7728. if (ArrayUtil.isNotEmpty(extractedPaths)) {
  7729. const importStartedAt = Date.now()
  7730. try {
  7731. await this.postProcessExtractedIsoFiles(extractedPaths, selectedEntries, outputPaths)
  7732. importedCount = await this.importExtractedFilesToDirectory(extractedPaths, destinationDir)
  7733. Logger.info(TAG,
  7734. `heanup ISO import extracted files success elapsedMs=${Date.now() - importStartedAt}, ` +
  7735. `importedCount=${importedCount}`)
  7736. } catch (importError) {
  7737. importErrorMessage = (importError as Error).message || '导入媒体库失败'
  7738. Logger.error(TAG,
  7739. `heanup ISO import extracted files failed elapsedMs=${Date.now() - importStartedAt}, ` +
  7740. `message=${importErrorMessage}`)
  7741. }
  7742. }
  7743. if (extractedPaths.length > 0 && failedEntries.length > 0) {
  7744. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7745. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,导入失败`)
  7746. } else if (importedCount > 0) {
  7747. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,已入库 ${importedCount} 个音频文件`)
  7748. } else {
  7749. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个`)
  7750. }
  7751. } else if (extractedPaths.length > 0) {
  7752. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7753. ToastUtil.showToast(`提取完成,但导入媒体库失败: ${importErrorMessage}`)
  7754. } else if (importedCount > 0) {
  7755. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件,入库 ${importedCount} 个音频文件`)
  7756. } else {
  7757. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件`)
  7758. }
  7759. } else if (ArrayUtil.isNotEmpty(failureDetails)) {
  7760. const firstFailure: IsoExtractFailureDetail = failureDetails[0]
  7761. const reasonText = firstFailure.reason && firstFailure.reason.length > 0 ? firstFailure.reason : '提取失败'
  7762. ToastUtil.showToast(reasonText)
  7763. } else if (hasSacdTrack) {
  7764. ToastUtil.showToast('SACD ISO 轨道提取失败')
  7765. } else {
  7766. ToastUtil.showToast('提取失败')
  7767. }
  7768. } catch (error) {
  7769. this.isoExtractTask = undefined
  7770. if (this.isoExtractCanceled) {
  7771. return
  7772. }
  7773. Logger.error(TAG, `heanup 提取 ISO 文件失败: ${(error as Error).message}`)
  7774. ToastUtil.showToast('提取 ISO 文件失败')
  7775. } finally {
  7776. const shouldResetDialogState: boolean = this.isoComponentId <= 0
  7777. this.stopIsoExtractProgressWatcher()
  7778. this.isoExtractTask = undefined
  7779. this.isIsoExtracting = false
  7780. Logger.info(TAG,
  7781. `heanup ISO extract finally canceled=${this.isoExtractCanceled}, cancelMessage=${this.isoExtractCancelMessage}`)
  7782. if (this.isoExtractCanceled && this.isoExtractCancelMessage.length > 0) {
  7783. ToastUtil.showToast(this.isoExtractCancelMessage)
  7784. }
  7785. this.isoExtractCanceled = false
  7786. this.isoExtractCancelMessage = ''
  7787. if (shouldResetDialogState) {
  7788. this.resetIsoDialogState()
  7789. } else {
  7790. this.selectedIsoAudioPaths = []
  7791. this.resetIsoExtractProgressState()
  7792. }
  7793. }
  7794. }
  7795. private async postProcessExtractedIsoFiles(extractedPaths: Array<string>, selectedEntries: Array<IsoArchiveAudioEntry>,
  7796. outputPaths: Array<string>): Promise<void> {
  7797. if (ArrayUtil.isEmpty(extractedPaths) || ArrayUtil.isEmpty(selectedEntries) || ArrayUtil.isEmpty(outputPaths)) {
  7798. return
  7799. }
  7800. const entryByOutputPath: Map<string, IsoArchiveAudioEntry> = new Map<string, IsoArchiveAudioEntry>()
  7801. for (let i = 0; i < outputPaths.length && i < selectedEntries.length; i++) {
  7802. entryByOutputPath.set(outputPaths[i], selectedEntries[i])
  7803. }
  7804. for (let i = 0; i < extractedPaths.length; i++) {
  7805. const extractedPath = extractedPaths[i]
  7806. const entry = entryByOutputPath.get(extractedPath)
  7807. if (!entry) {
  7808. continue
  7809. }
  7810. await this.postProcessExtractedIsoEntry(extractedPath, entry)
  7811. }
  7812. }
  7813. private async postProcessExtractedIsoEntry(filePath: string, entry: IsoArchiveAudioEntry): Promise<void> {
  7814. if (!Utility.isMusicByExtension(filePath)) {
  7815. return
  7816. }
  7817. const hasEmbeddedMetadata: boolean = StrUtil.isNotEmpty(entry.title) || StrUtil.isNotEmpty(entry.album) ||
  7818. StrUtil.isNotEmpty(entry.artist) || StrUtil.isNotEmpty(entry.albumArtist) || StrUtil.isNotEmpty(entry.comment) ||
  7819. !!(entry.trackNumber && entry.trackNumber > 0)
  7820. if (entry.entryType !== 'sacd_track' && !hasEmbeddedMetadata) {
  7821. return
  7822. }
  7823. const tags: FFMpegTags = this.buildIsoExtractedMetadata(entry)
  7824. if (Object.keys(tags).length > 0) {
  7825. try {
  7826. const metadataResult = await repairAudioMetadata(filePath, '', tags, true, '')
  7827. Logger.info(TAG,
  7828. `heanup ISO metadata post-process path=${filePath}, success=${metadataResult}, type=${entry.entryType || ''}`)
  7829. } catch (error) {
  7830. Logger.error(TAG, `heanup ISO metadata post-process failed path=${filePath}, message=${(error as Error).message}`)
  7831. }
  7832. }
  7833. if (!filePath.toLowerCase().endsWith('.dsf')) {
  7834. return
  7835. }
  7836. const coverUrl = await this.resolveIsoExtractCoverUrl(entry)
  7837. if (StrUtil.isEmpty(coverUrl)) {
  7838. return
  7839. }
  7840. try {
  7841. const coverResult = await changeMusicCover(this.context, filePath, coverUrl, true, '')
  7842. Logger.info(TAG, `heanup ISO cover post-process path=${filePath}, success=${coverResult}`)
  7843. } catch (error) {
  7844. Logger.error(TAG, `heanup ISO cover post-process failed path=${filePath}, message=${(error as Error).message}`)
  7845. }
  7846. }
  7847. private buildIsoExtractedMetadata(entry: IsoArchiveAudioEntry): FFMpegTags {
  7848. const metadata: FFMpegTags = {}
  7849. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  7850. if (StrUtil.isNotEmpty(title)) {
  7851. metadata.title = title
  7852. metadata.TITLE = title
  7853. }
  7854. if (StrUtil.isNotEmpty(entry.artist)) {
  7855. metadata.artist = entry.artist
  7856. metadata.ARTIST = entry.artist
  7857. }
  7858. if (StrUtil.isNotEmpty(entry.album)) {
  7859. metadata.album = entry.album
  7860. metadata.ALBUM = entry.album
  7861. }
  7862. if (entry.trackNumber && entry.trackNumber > 0) {
  7863. metadata.track = `${entry.trackNumber}`
  7864. metadata.TRACK = `${entry.trackNumber}`
  7865. }
  7866. if (StrUtil.isNotEmpty(entry.albumArtist)) {
  7867. metadata.ALBUMARTIST = entry.albumArtist
  7868. metadata.album_artist = entry.albumArtist
  7869. metadata.TPE2 = entry.albumArtist
  7870. }
  7871. if (StrUtil.isNotEmpty(entry.comment)) {
  7872. metadata.comment = entry.comment
  7873. metadata.COMMENT = entry.comment
  7874. metadata.COMM = entry.comment
  7875. }
  7876. return metadata
  7877. }
  7878. private getIsoEntryBaseName(fileName: string): string {
  7879. const lastSegment = this.getIsoLastPathSegment(fileName)
  7880. const lastDot = lastSegment.lastIndexOf('.')
  7881. if (lastDot <= 0) {
  7882. return lastSegment
  7883. }
  7884. return lastSegment.substring(0, lastDot)
  7885. }
  7886. private async resolveIsoExtractCoverUrl(entry: IsoArchiveAudioEntry): Promise<string> {
  7887. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  7888. const artist = entry.artist || entry.albumArtist || ''
  7889. if (StrUtil.isEmpty(title) || PreferencesUtil.getStringSync('COVER_API', '') === '') {
  7890. return ''
  7891. }
  7892. try {
  7893. const coverUrl = await NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', ''))
  7894. if (StrUtil.isNotEmpty(coverUrl) && coverUrl !== 'unknown') {
  7895. return coverUrl
  7896. }
  7897. } catch (error) {
  7898. Logger.error(TAG,
  7899. `heanup ISO resolve cover failed title=${title}, artist=${artist}, message=${(error as Error).message}`)
  7900. }
  7901. return ''
  7902. }
  7903. private async importExtractedFilesToDirectory(paths: Array<string>, destinationDir: string): Promise<number> {
  7904. if (ArrayUtil.isEmpty(paths)) {
  7905. return 0
  7906. }
  7907. let importedCount: number = 0
  7908. for (let i = 0; i < paths.length; i++) {
  7909. const filePath = paths[i]
  7910. if (destinationDir === this.lockPath || !Utility.isMeidaByExtension(filePath) ||
  7911. filePath.endsWith('.lrc') || filePath.endsWith('.srt') || Utility.isIsoByExtension(filePath)) {
  7912. continue
  7913. }
  7914. const mediaItem = await Utility.uriGetMusicAssetsFromFile(this.context, filePath,
  7915. CommonConstants.TYPE_LOCAL, this.autoParseMusicName)
  7916. await new Promise<void>((resolve) => {
  7917. this.table.insert(mediaItem, (_id: number) => resolve())
  7918. })
  7919. importedCount++
  7920. }
  7921. this.cache.delete(destinationDir)
  7922. if (this.currentPath === destinationDir) {
  7923. this.pageCache.clear()
  7924. this.pageHasMoreCache.clear()
  7925. this.pageTotalCountCache.clear()
  7926. if (destinationDir === this.lockPath) {
  7927. this.getSortedFiles(destinationDir, true)
  7928. } else {
  7929. await this.resetAndLoadFirstPage()
  7930. }
  7931. }
  7932. return importedCount
  7933. }
  7934. private resetIsoDialogState(): void {
  7935. this.isoAudioEntries = []
  7936. this.selectedIsoAudioPaths = []
  7937. this.isoSourceFileName = ''
  7938. this.isoSourceFilePath = ''
  7939. this.isoExtractDestinationDir = ''
  7940. this.isIsoExtracting = false
  7941. this.stopIsoExtractProgressWatcher()
  7942. this.isoExtractTask = undefined
  7943. this.resetIsoExtractProgressState()
  7944. }
  7945. private closeIsoDialog(reset: boolean = true): void {
  7946. if (this.isoComponentId > 0) {
  7947. try {
  7948. this.getUIContext().getPromptAction().closeCustomDialog(this.isoComponentId)
  7949. } catch (_error) {
  7950. }
  7951. this.isoComponentId = 0
  7952. }
  7953. if (!reset) {
  7954. return
  7955. }
  7956. this.resetIsoDialogState()
  7957. }
  7958. @Builder
  7959. isoComptentBuilder() {
  7960. IsoExtractComptent({
  7961. isoFileName: this.isoSourceFileName,
  7962. entries: this.isoAudioEntries,
  7963. selectedPaths: this.selectedIsoAudioPaths,
  7964. isLongNameRoLL: this.isLongNameRoLL,
  7965. isExtracting: this.isIsoExtracting,
  7966. extractProgress: this.isoExtractProgress,
  7967. extractProgressText: this.isoExtractProgressText,
  7968. extractCurrentName: this.isoExtractCurrentEntryName,
  7969. onToggleSelection: (path: string, checked: boolean) => {
  7970. this.toggleIsoEntrySelection(path, checked)
  7971. },
  7972. onToggleSelectAll: () => {
  7973. this.toggleIsoEntrySelectAll()
  7974. },
  7975. onExtract: async () => {
  7976. await this.extractSelectedIsoAudioFiles()
  7977. },
  7978. onRunInBackground: () => {
  7979. this.moveIsoExtractionToBackground()
  7980. },
  7981. onStopExtract: () => {
  7982. this.cancelIsoExtraction('已取消 ISO 提取')
  7983. },
  7984. onCancel: () => {
  7985. if (this.isIsoExtracting) {
  7986. this.moveIsoExtractionToBackground()
  7987. return
  7988. }
  7989. this.closeIsoDialog()
  7990. }
  7991. })
  7992. }
  7993. private cueComponentId: number = 0
  7994. private async handleCueTrackImport(cueinfo: CueInfo): Promise<void> {
  7995. try {
  7996. let sourceItem = Utility.getItemByFilePath(this.videoLocalList, cueinfo.filePath);
  7997. if (!sourceItem) {
  7998. sourceItem = await this.table.queryVideoByFilePath(cueinfo.filePath) || undefined;
  7999. }
  8000. const importedItems = await importCueTracks(this.context, this.table, cueinfo, sourceItem);
  8001. if (ArrayUtil.isEmpty(importedItems)) {
  8002. ToastUtil.showToast('未导入到任何分轨');
  8003. return;
  8004. }
  8005. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId);
  8006. await this.resetAndLoadFirstPage();
  8007. ToastUtil.showToast(`分轨完成,已入库 ${importedItems.length} 首`);
  8008. } catch (error) {
  8009. Logger.error(TAG, `CUE 分轨入库失败: ${(error as Error).message}`);
  8010. ToastUtil.showToast('分轨失败');
  8011. }
  8012. }
  8013. //显示cue分轨列表对话框
  8014. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  8015. this.getUIContext().getPromptAction().openCustomDialog({
  8016. builder: () => {
  8017. this.cueComptentBuilder(cueTracks,cueinfo)
  8018. },
  8019. isModal:true,
  8020. showInSubWindow:false,
  8021. maskColor: Color.Transparent,
  8022. dialogTransition: // 设置弹窗内容显示的过渡效果
  8023. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  8024. .animation({ duration: 600, curve: Curve.Smooth }),
  8025. maskTransition: // 设置蒙层显示的过渡效果
  8026. TransitionEffect.opacity(0.5)
  8027. .animation({ duration: 600, curve: Curve.Smooth })
  8028. }).then((dialogId: number) => {
  8029. this.cueComponentId = dialogId
  8030. })
  8031. .catch((error: BusinessError) => {
  8032. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  8033. })
  8034. }
  8035. @Builder
  8036. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  8037. CueComptent({
  8038. title:cueinfo.title,
  8039. cueTracks:cueTracks,
  8040. isLongNameRoLL:this.isLongNameRoLL,
  8041. onCancel:()=>{
  8042. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  8043. },
  8044. onSplitTracks: async ()=>{
  8045. await this.handleCueTrackImport(cueinfo)
  8046. },
  8047. onDoItemClick: async (item: CueTrack, index: number)=>{
  8048. //获取cueinfo对应的filePath
  8049. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  8050. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  8051. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  8052. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  8053. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  8054. if (this.currentSong){
  8055. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  8056. this.stop();//播放之前先停止之前播放。
  8057. }
  8058. this.songList = globalVideoList
  8059. this.sonDataSource.pushArrayData(this.songList)
  8060. if (this.currentSong) {
  8061. try {
  8062. const cueUrl = await this.resolvePlaybackUrlForCurrentSong('cue-track-play');
  8063. if (!cueUrl) {
  8064. return;
  8065. }
  8066. this.videoUrl = cueUrl;
  8067. } catch (error) {
  8068. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  8069. this.videoUrl = this.currentSong.filePath;
  8070. }
  8071. }
  8072. this.name = item.title||this.currentSong.name
  8073. this.cover = this.currentSong.pixelMapPath
  8074. this.artist = item.performer||this.currentSong.artist
  8075. this.currentSong.name = this.name
  8076. this.currentSong.artist = this.artist
  8077. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  8078. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  8079. }
  8080. }
  8081. })
  8082. }
  8083. @State isFrontWhite: boolean = false
  8084. private showCoverScaleGuideIfNeeded(): void {
  8085. const hasShown = PreferencesUtil.getBooleanSync(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, false)
  8086. if (hasShown) {
  8087. return
  8088. }
  8089. this.isShowCoverScaleGuide = true
  8090. setTimeout(() => {
  8091. if (this.isShowCoverScaleGuide) {
  8092. this.dismissCoverScaleGuide()
  8093. }
  8094. }, 9000)
  8095. }
  8096. private dismissCoverScaleGuide(): void {
  8097. this.isShowCoverScaleGuide = false
  8098. PreferencesUtil.put(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, true)
  8099. }
  8100. setShowPlayTrue(){
  8101. this.getUIContext()?.animateTo({
  8102. duration: 500,
  8103. curve: Curve.Friction
  8104. }, () => {
  8105. this.isShowPlay = true;
  8106. this.showCoverScaleGuideIfNeeded()
  8107. });
  8108. }
  8109. setShowPlayFalse(){
  8110. this.getUIContext()?.animateTo({
  8111. duration: 500,
  8112. curve: Curve.Friction
  8113. }, () => {
  8114. this.isShowPlay = false;
  8115. });
  8116. this.isShowCoverScaleGuide = false
  8117. }
  8118. //打开播放页
  8119. showPlayerView() {
  8120. this.showCoverScaleGuideIfNeeded()
  8121. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  8122. if (ArrayUtil.isNotEmpty(this.songList)) {
  8123. // this.setShowPlayTrue()
  8124. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  8125. this.initLyric(lyricPath);
  8126. this.startAutoHide();
  8127. } else {
  8128. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  8129. }
  8130. }
  8131. //打开播放列表
  8132. openPlayList(){
  8133. if (ArrayUtil.isNotEmpty(this.songList)) {
  8134. this.isShowSheet = !this.isShowSheet;
  8135. this.isFrontWhite = false
  8136. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  8137. this.scrollIndex()
  8138. // 只有在播放本地音乐时才自动加载完整列表
  8139. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  8140. void this.hydrateFullMediaPlayListIfNeeded();
  8141. }
  8142. } else {
  8143. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  8144. }
  8145. }
  8146. scrollIndex(){
  8147. try {
  8148. setTimeout(() => {
  8149. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8150. if(this.curIndex>60){
  8151. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  8152. }else{
  8153. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  8154. }
  8155. })
  8156. }, 123)
  8157. }catch (error) {
  8158. console.error(`onecold scrollIndex出错: ${error}`);
  8159. }
  8160. }
  8161. scrollIndexMain(dialogId?:string){
  8162. try {
  8163. setTimeout(() => {
  8164. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8165. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  8166. if(dialogId)
  8167. DialogHelper.closeDialog(dialogId)
  8168. let isAni:boolean = false
  8169. if(this.curIndex<50){
  8170. isAni = true
  8171. }
  8172. if(this.twoFingerType==4){
  8173. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8174. }else{
  8175. if(this.isGridMusic){
  8176. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8177. }else{
  8178. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8179. }
  8180. }
  8181. })
  8182. }, 123)
  8183. }catch (error) {
  8184. console.error(`onecold scrollIndexMain出错: ${error}`);
  8185. }
  8186. }
  8187. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  8188. async locateCurrentSong(): Promise<void> {
  8189. if (!this.currentSong) {
  8190. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  8191. return;
  8192. }
  8193. // 检查当前播放歌曲是否在已加载的列表中
  8194. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8195. if (targetIndex > 0) {
  8196. // 歌曲在当前列表中,直接滚动
  8197. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  8198. this.curIndex = targetIndex;
  8199. this.scrollIndexMain();
  8200. } else {
  8201. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  8202. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  8203. const dialogID = DialogHelper.showLoadingDialog()
  8204. await this.hydrateFullMediaPlayListIfNeeded(false);
  8205. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8206. this.scrollIndexMain(dialogID);
  8207. }
  8208. }
  8209. //播放列表布局
  8210. @Builder
  8211. PlayListSheet() {
  8212. Column() {
  8213. this.PlayList()
  8214. }
  8215. .width('100%')
  8216. .height('100%')
  8217. }
  8218. @State titleStr: string = ''
  8219. @State ablumStr: string = ''
  8220. @State artistStr: string = ''
  8221. @State lyricConStr: string = ''
  8222. @State currentEditItem: string = ''
  8223. @State yearStr: string = ''
  8224. @State trackStr: string = ''
  8225. @State genreStr: string = ''
  8226. @State imagePathStr: string = ''
  8227. @State albumArtistStr: string = ''
  8228. @State composerStr: string = ''
  8229. @State lyricistStr: string = ''
  8230. @State commentStr: string = ''
  8231. @State discStr: string = ''
  8232. doUpdateData() {
  8233. setTimeout(async () => {
  8234. if (this.modeType === 0) {
  8235. this.deleteCache(this.currentPath)
  8236. await this.resetAndLoadFirstPage();
  8237. }else if (this.modeType === 1){
  8238. await this.resetAndLoadFirstPage();
  8239. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8240. }
  8241. }, 500)
  8242. }
  8243. doAllUpdateData() {
  8244. setTimeout(async () => {
  8245. if (this.modeType === 0) {
  8246. this.deleteCache(this.currentPath)
  8247. await this.resetAndLoadFirstPage();
  8248. }else{
  8249. await this.resetAndLoadFirstPage();
  8250. }
  8251. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8252. workerInstance.postMessage({ code: 3, data: this.context });
  8253. workerInstance.postMessage({ code: 4, data: this.context });
  8254. }, 999)
  8255. }
  8256. private delayMs(ms: number): Promise<void> {
  8257. return new Promise(resolve => {
  8258. setTimeout(() => resolve(), ms);
  8259. });
  8260. }
  8261. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  8262. if (!items || items.length === 0) {
  8263. return;
  8264. }
  8265. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  8266. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  8267. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  8268. if (!this.isScrolling || items.length <= directAppendThreshold) {
  8269. this.videoLocalList.push(...items);
  8270. this.dataSource.appendArrayData(items);
  8271. return;
  8272. }
  8273. const chunkSize = isHeavyGridWaterMode
  8274. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  8275. : (isMediaLibraryListMode
  8276. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  8277. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  8278. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  8279. for (let index = 0; index < items.length; index += chunkSize) {
  8280. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  8281. this.videoLocalList.push(...chunk);
  8282. this.dataSource.appendArrayData(chunk);
  8283. if (index + chunkSize < items.length) {
  8284. await this.delayMs(chunkDelay);
  8285. }
  8286. }
  8287. }
  8288. /**
  8289. * 加载指定页的数据
  8290. */
  8291. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  8292. try {
  8293. // 1. 检查缓存
  8294. if (this.pageCache.has(pageIndex)) {
  8295. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  8296. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8297. const cachedData = this.pageCache.get(pageIndex)!;
  8298. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  8299. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  8300. if (cachedHasMore !== undefined) {
  8301. this.hasMoreData = cachedHasMore;
  8302. }
  8303. if (cachedTotal !== undefined) {
  8304. this.totalCount = cachedTotal;
  8305. if (this.modeType === 1) {
  8306. this.mediaKuCount = cachedTotal;
  8307. }
  8308. }
  8309. if (append) {
  8310. this.prefetchListThumbsFromItems(cachedData, 26);
  8311. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8312. await this.appendItemsSmoothly(cachedData);
  8313. } else {
  8314. this.videoLocalList = cachedData;
  8315. this.dataSource.pushArrayData(this.videoLocalList);
  8316. if (inMediaLibraryWarmup) {
  8317. this.prefetchListThumbsFromItems(cachedData, 8);
  8318. } else {
  8319. this.prefetchListThumbsFromItems(cachedData, 30);
  8320. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8321. }
  8322. }
  8323. this.setButtonStatus();
  8324. if (inMediaLibraryWarmup) {
  8325. this.scheduleAlphaBetRebuild(900);
  8326. } else {
  8327. this.markAlphaBetDirty();
  8328. }
  8329. if (this.hasMoreData) {
  8330. if (inMediaLibraryWarmup) {
  8331. if (this.mediaLibraryWarmupPrefetchTimer) {
  8332. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8333. }
  8334. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8335. this.mediaLibraryWarmupPrefetchTimer = 0;
  8336. if (this.modeType === 1 && !this.isCanBack) {
  8337. this.prefetchFollowingPages(pageIndex + 1);
  8338. }
  8339. }, 900) as number;
  8340. } else {
  8341. this.prefetchFollowingPages(pageIndex + 1);
  8342. }
  8343. }
  8344. return;
  8345. }
  8346. this.isLoadingPage = true;
  8347. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  8348. // 2. 构造查询参数
  8349. const options: PageQueryOptions = {
  8350. pageIndex: pageIndex,
  8351. pageSize: this.pageSize,
  8352. sortType: this.sortType,
  8353. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8354. isShowFileName: this.isShowFileName
  8355. };
  8356. // 根据 modeType 补充查询条件
  8357. if (this.modeType === 0) {
  8358. options.parentPath = this.currentPath;
  8359. }
  8360. // 3. 执行查询
  8361. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8362. switch (this.modeType) {
  8363. case 0:
  8364. result = await this.table.queryByParentPathPaged(options);
  8365. result.items = this.filterOutLocalIsoItems(result.items);
  8366. // modeType=0时,第一页需要添加文件夹列表
  8367. if (pageIndex === 0 && !this.isSearchMode) {
  8368. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  8369. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  8370. result.items = [...directories, ...isoItems, ...result.items];
  8371. result.totalCount += directories.length + isoItems.length;
  8372. }
  8373. break;
  8374. case 1:
  8375. result = await this.table.queryMediaLibraryPaged(options);
  8376. break;
  8377. case 2:
  8378. result = await this.table.queryArtistsPaged(options);
  8379. break;
  8380. case 3:
  8381. result = await this.table.queryAlbumsPaged(options);
  8382. break;
  8383. default:
  8384. result = await this.table.queryMediaLibraryPaged(options);
  8385. break;
  8386. }
  8387. if (!result || result.items.length === 0) {
  8388. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  8389. this.isLoadingPage = false;
  8390. this.hasMoreData = false;
  8391. // 仅首页为空时清空,后续页为空只终止继续分页
  8392. if (pageIndex === 0) {
  8393. this.totalCount = 0;
  8394. this.videoLocalList = [];
  8395. this.dataSource.pushArrayData(this.videoLocalList);
  8396. this.setButtonStatus();
  8397. this.markAlphaBetDirty();
  8398. }
  8399. return;
  8400. }
  8401. // 4. 更新状态和缓存
  8402. this.totalCount = result.totalCount;
  8403. this.hasMoreData = result.hasMore;
  8404. if (this.modeType === 1) {
  8405. this.mediaKuCount = result.totalCount;
  8406. }
  8407. if (this.modeType === 2 && result.countMap) {
  8408. this.mergeArtistCountMap(result.countMap);
  8409. } else if (this.modeType === 3 && result.countMap) {
  8410. this.mergeAlbumCountMap(result.countMap);
  8411. }
  8412. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  8413. // 缓存管理 - 只保留最近3页
  8414. this.pageCache.set(pageIndex, result.items);
  8415. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  8416. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  8417. this.cleanOldCache(pageIndex);
  8418. // 5. 更新显示列表
  8419. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8420. if (append) {
  8421. this.prefetchListThumbsFromItems(result.items, 26);
  8422. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8423. await this.appendItemsSmoothly(result.items);
  8424. } else {
  8425. this.videoLocalList = result.items;
  8426. this.dataSource.pushArrayData(this.videoLocalList);
  8427. if (inMediaLibraryWarmup) {
  8428. this.prefetchListThumbsFromItems(result.items, 8);
  8429. } else {
  8430. this.prefetchListThumbsFromItems(result.items, 30);
  8431. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8432. }
  8433. }
  8434. this.setButtonStatus();
  8435. if (inMediaLibraryWarmup) {
  8436. this.scheduleAlphaBetRebuild(900);
  8437. } else {
  8438. this.markAlphaBetDirty();
  8439. }
  8440. if (inMediaLibraryWarmup) {
  8441. if (this.mediaLibraryWarmupPrefetchTimer) {
  8442. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8443. }
  8444. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8445. this.mediaLibraryWarmupPrefetchTimer = 0;
  8446. if (this.modeType === 1 && !this.isCanBack) {
  8447. this.prefetchFollowingPages(pageIndex + 1);
  8448. }
  8449. }, 900) as number;
  8450. } else {
  8451. this.prefetchFollowingPages(pageIndex + 1);
  8452. }
  8453. this.isLoadingPage = false;
  8454. } catch (err) {
  8455. const error = err as Error;
  8456. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  8457. // ToastUtil.showToast('加载数据失败');
  8458. this.isLoadingPage = false;
  8459. this.hasMoreData = false;
  8460. }
  8461. }
  8462. /**
  8463. * 清理旧缓存 - 只保留当前页前后各1页
  8464. */
  8465. private cleanOldCache(currentPage: number): void {
  8466. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  8467. const keysToDelete: number[] = [];
  8468. this.pageCache.forEach((_, page) => {
  8469. if (!pagesToKeep.has(page)) {
  8470. keysToDelete.push(page);
  8471. }
  8472. });
  8473. keysToDelete.forEach(page => {
  8474. this.pageCache.delete(page);
  8475. this.pageHasMoreCache.delete(page);
  8476. this.pageTotalCountCache.delete(page);
  8477. });
  8478. if (keysToDelete.length > 0) {
  8479. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  8480. }
  8481. }
  8482. private async prefetchNextPage(nextPage: number): Promise<void> {
  8483. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8484. return;
  8485. }
  8486. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  8487. return;
  8488. }
  8489. const expectedModeType = this.modeType;
  8490. const expectedSortType = this.sortType;
  8491. const expectedIsShowFileName = this.isShowFileName;
  8492. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  8493. const expectedParentPath = this.currentPath;
  8494. this.prefetchingPages.add(nextPage);
  8495. try {
  8496. const options: PageQueryOptions = {
  8497. pageIndex: nextPage,
  8498. pageSize: this.pageSize,
  8499. sortType: this.sortType,
  8500. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8501. isShowFileName: this.isShowFileName
  8502. };
  8503. if (this.modeType === 0) {
  8504. options.parentPath = this.currentPath;
  8505. }
  8506. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8507. switch (this.modeType) {
  8508. case 0:
  8509. result = await this.table.queryByParentPathPaged(options);
  8510. result.items = this.filterOutLocalIsoItems(result.items);
  8511. break;
  8512. case 1:
  8513. result = await this.table.queryMediaLibraryPaged(options);
  8514. break;
  8515. case 2:
  8516. result = await this.table.queryArtistsPaged(options);
  8517. if (result.countMap) {
  8518. this.mergeArtistCountMap(result.countMap);
  8519. }
  8520. break;
  8521. case 3:
  8522. result = await this.table.queryAlbumsPaged(options);
  8523. if (result.countMap) {
  8524. this.mergeAlbumCountMap(result.countMap);
  8525. }
  8526. break;
  8527. default:
  8528. result = await this.table.queryMediaLibraryPaged(options);
  8529. break;
  8530. }
  8531. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  8532. if (expectedModeType !== this.modeType ||
  8533. expectedSortType !== this.sortType ||
  8534. expectedIsShowFileName !== this.isShowFileName ||
  8535. expectedSearchKeyword !== currentSearchKeyword ||
  8536. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  8537. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  8538. return;
  8539. }
  8540. this.pageHasMoreCache.set(nextPage, result.hasMore);
  8541. this.pageTotalCountCache.set(nextPage, result.totalCount);
  8542. if (result.items.length > 0) {
  8543. this.pageCache.set(nextPage, result.items);
  8544. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  8545. this.cleanOldCache(nextPage);
  8546. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  8547. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  8548. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  8549. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  8550. Logger.info('heanup LocalMusic',
  8551. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  8552. this.scheduleLoadNextPage(8);
  8553. }
  8554. }
  8555. }
  8556. } catch (err) {
  8557. const error = err as Error;
  8558. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  8559. } finally {
  8560. this.prefetchingPages.delete(nextPage);
  8561. }
  8562. }
  8563. private mergeArtistCountMap(countMap: Map<string, number>): void {
  8564. const nextMap = new Map(this.artistSongCountMap);
  8565. countMap.forEach((count, artist) => {
  8566. nextMap.set(artist, count);
  8567. });
  8568. this.artistSongCountMap = nextMap;
  8569. }
  8570. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  8571. const nextMap = new Map(this.albumSongCountMap);
  8572. countMap.forEach((count, album) => {
  8573. nextMap.set(album, count);
  8574. });
  8575. this.albumSongCountMap = nextMap;
  8576. }
  8577. private getArtistSongCount(artist: string): number {
  8578. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  8579. }
  8580. private getAlbumSongCount(album: string): number {
  8581. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  8582. }
  8583. /**
  8584. * 加载文件夹列表(仅用于modeType=0的首页模式)
  8585. */
  8586. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  8587. try {
  8588. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  8589. // 检查缓存
  8590. const cacheKey = curPath + "_dirList";
  8591. const cachedDirList = this.findCache(cacheKey);
  8592. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  8593. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  8594. return cachedDirList as VideoItem[];
  8595. }
  8596. // 从文件系统读取
  8597. const fileList = FileUtil.listFileSync(curPath);
  8598. const directories: VideoItem[] = [];
  8599. for (let i = 0; i < fileList.length; i++) {
  8600. const path = curPath + '/' + fileList[i];
  8601. if (FileUtil.isDirectory(path)) {
  8602. const item: VideoItem = new VideoItem(
  8603. fileList[i].toString(),
  8604. fileList[i].toString(),
  8605. path,
  8606. CommonConstants.TYPE_IS_DIR,
  8607. 0,
  8608. ''
  8609. );
  8610. if (this.isShowDir(item.name)) {
  8611. directories.push(item);
  8612. }
  8613. }
  8614. }
  8615. // 排序
  8616. Utility.doSortListAscending(directories);
  8617. // 缓存文件夹列表
  8618. if (curPath === this.rootPath) {
  8619. this.dirList = directories;
  8620. this.addCache(cacheKey, directories);
  8621. }
  8622. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  8623. return directories;
  8624. } catch (err) {
  8625. const error = err as Error;
  8626. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  8627. return [];
  8628. }
  8629. }
  8630. /**
  8631. * 构建播放队列(避免一次性加载全量)
  8632. */
  8633. private buildPlayQueueFromView(): Array<VideoItem> {
  8634. if (this.modeType === 4) {
  8635. this.playQueueScope = 'playlist';
  8636. return this.currentSongList;
  8637. }
  8638. if (this.isHistory) {
  8639. this.playQueueScope = 'history';
  8640. return this.historyList;
  8641. }
  8642. if (this.isFavMusic) {
  8643. this.playQueueScope = 'fav';
  8644. return this.favList;
  8645. }
  8646. this.playQueueScope = 'view';
  8647. return Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8648. }
  8649. private openSpecialLocalList(target: string): void {
  8650. this.mType = 0
  8651. this.isShowDrawer = false
  8652. this.offsetX = 0
  8653. this.isHistory = false
  8654. this.isFavMusic = false
  8655. if (target === 'recent') {
  8656. this.titleName = '最近播放'
  8657. this.currentTitleName = '最近播放'
  8658. this.currentTitleCover = $r('app.media.alt')
  8659. this.updateListData(this.historyList, true)
  8660. if (ArrayUtil.isNotEmpty(this.historyList)) {
  8661. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  8662. }
  8663. this.isHistory = true
  8664. return
  8665. }
  8666. if (target === 'favorite') {
  8667. this.titleName = '我的收藏'
  8668. this.currentTitleName = '我的收藏'
  8669. this.currentTitleCover = $r('app.media.alt')
  8670. this.updateListData(this.favList, true)
  8671. if (ArrayUtil.isNotEmpty(this.favList)) {
  8672. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  8673. }
  8674. this.isFavMusic = true
  8675. }
  8676. }
  8677. private async tryLoadNextPageForPlayback(): Promise<void> {
  8678. if (this.playQueueScope !== 'view') {
  8679. return;
  8680. }
  8681. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8682. return;
  8683. }
  8684. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  8685. return;
  8686. }
  8687. await this.loadNextPage();
  8688. const nextList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8689. if (nextList.length > this.songList.length) {
  8690. this.songList = nextList;
  8691. this.sonDataSource.pushArrayData(this.songList);
  8692. }
  8693. }
  8694. /**
  8695. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  8696. * 当播放列表弹窗滚动到底部时调用
  8697. */
  8698. private async loadMoreNavidromeSongs(): Promise<void> {
  8699. const beforeCount = this.songList.length;
  8700. const hasMore = hasMoreData();
  8701. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  8702. if (!hasMore) {
  8703. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  8704. return;
  8705. }
  8706. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  8707. const success = await triggerLoadMoreSongs(1);
  8708. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  8709. if (success) {
  8710. // 获取更新后的完整列表
  8711. const updatedList = getNavidromeVideoItems();
  8712. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  8713. if (updatedList.length > beforeCount) {
  8714. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  8715. this.songList = updatedList;
  8716. this.sonDataSource.pushArrayData(this.songList);
  8717. } else {
  8718. Logger.info('heanup', '列表长度未增加');
  8719. }
  8720. } else {
  8721. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  8722. }
  8723. }
  8724. /**
  8725. * 重置分页状态并加载首页
  8726. */
  8727. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  8728. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  8729. this.currentPage = 0;
  8730. if (clearExistingList) {
  8731. this.videoLocalList = [];
  8732. }
  8733. this.pageCache.clear();
  8734. this.pageHasMoreCache.clear();
  8735. this.pageTotalCountCache.clear();
  8736. this.prefetchingPages.clear();
  8737. this.hasMoreData = true;
  8738. this.totalCount = 0;
  8739. this.lastScrollTriggerPage = -1;
  8740. this.lastVisibleEndIndex = -1;
  8741. this.listScrollAlphaCheckAt = 0;
  8742. this.listScrollPagingCheckAt = 0;
  8743. this.listScrollLastAlphaStart = -1;
  8744. this.listScrollLastPagingEnd = -1;
  8745. this.gridScrollPagingCheckAt = 0;
  8746. this.gridScrollLastPagingEnd = -1;
  8747. this.waterScrollPagingCheckAt = 0;
  8748. this.waterScrollLastPagingEnd = -1;
  8749. this.listVisibleStart = -1;
  8750. this.listVisibleEnd = -1;
  8751. this.listThumbWarmupCheckAt = 0;
  8752. this.listThumbWarmupStart = -1;
  8753. this.listThumbWarmupEnd = -1;
  8754. this.gridThumbWarmupCheckAt = 0;
  8755. this.gridThumbWarmupStart = -1;
  8756. this.gridThumbWarmupEnd = -1;
  8757. this.waterThumbWarmupCheckAt = 0;
  8758. this.waterThumbWarmupStart = -1;
  8759. this.waterThumbWarmupEnd = -1;
  8760. this.gridVisibleStart = -1;
  8761. this.gridVisibleEnd = -1;
  8762. this.waterVisibleStart = -1;
  8763. this.waterVisibleEnd = -1;
  8764. this.gridWaterLastActiveTs = 0;
  8765. this.isPagingTransition = false;
  8766. if (this.pagingScheduleTimer) {
  8767. clearTimeout(this.pagingScheduleTimer);
  8768. this.pagingScheduleTimer = 0;
  8769. }
  8770. if (this.gridWaterScrollIdleTimer) {
  8771. clearTimeout(this.gridWaterScrollIdleTimer);
  8772. this.gridWaterScrollIdleTimer = 0;
  8773. }
  8774. this.coverThumbCache.clearPending();
  8775. this.pendingCoverThumbRefresh = false;
  8776. if (this.modeType === 2) {
  8777. this.artistSongCountMap = new Map();
  8778. } else if (this.modeType === 3) {
  8779. this.albumSongCountMap = new Map();
  8780. }
  8781. await this.loadPage(0, false);
  8782. }
  8783. private markGridWaterScrollingActive(): void {
  8784. if (!this.isScrolling) {
  8785. this.isScrolling = true;
  8786. }
  8787. const now = Date.now();
  8788. if (now - this.gridWaterLastActiveTs < 80) {
  8789. return;
  8790. }
  8791. this.gridWaterLastActiveTs = now;
  8792. if (this.gridWaterScrollIdleTimer) {
  8793. clearTimeout(this.gridWaterScrollIdleTimer);
  8794. }
  8795. this.gridWaterScrollIdleTimer = setTimeout(() => {
  8796. this.gridWaterScrollIdleTimer = 0;
  8797. if (this.isScrolling) {
  8798. this.isScrolling = false;
  8799. }
  8800. this.flushPendingCoverThumbRefresh();
  8801. }, 120);
  8802. }
  8803. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  8804. if (!this.autoHideTitle) {
  8805. return;
  8806. }
  8807. const now = Date.now();
  8808. if (now - this.titleBarLastCheckTs < 36) {
  8809. return;
  8810. }
  8811. this.titleBarLastCheckTs = now;
  8812. const delta = currentOffsetY - this.prevOffsetY;
  8813. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  8814. return;
  8815. }
  8816. if (delta > 0) {
  8817. if (this.isShowTitleBar) {
  8818. this.isShowTitleBar = false;
  8819. }
  8820. } else {
  8821. if (!this.isShowTitleBar) {
  8822. this.isShowTitleBar = true;
  8823. }
  8824. }
  8825. this.prevOffsetY = currentOffsetY;
  8826. }
  8827. private shouldPrefetchSecondPage(): boolean {
  8828. if (this.isMediaLibraryListMode()) {
  8829. return this.pageSize <= 120;
  8830. }
  8831. if (this.pageSize > 60) {
  8832. return false;
  8833. }
  8834. return this.isGridMusic || this.twoFingerType == 4;
  8835. }
  8836. private isMediaLibraryListMode(): boolean {
  8837. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  8838. }
  8839. private isMediaLibraryWarmupWindow(): boolean {
  8840. if (this.modeType !== 1 || this.isCanBack) {
  8841. return false;
  8842. }
  8843. if (this.mediaLibraryEnterTs <= 0) {
  8844. return false;
  8845. }
  8846. return Date.now() - this.mediaLibraryEnterTs < 1800;
  8847. }
  8848. private getDynamicPreloadStartRatio(): number {
  8849. if (this.twoFingerType == 4) {
  8850. return 0.10;
  8851. }
  8852. if (this.isGridMusic) {
  8853. return 0.14;
  8854. }
  8855. if (this.isMediaLibraryListMode()) {
  8856. return 0.12;
  8857. }
  8858. return this.preloadStartRatio;
  8859. }
  8860. private getDynamicAppendStartRatio(): number {
  8861. if (this.twoFingerType == 4) {
  8862. return 0.18;
  8863. }
  8864. if (this.isGridMusic) {
  8865. return 0.22;
  8866. }
  8867. if (this.isMediaLibraryListMode()) {
  8868. return 0.22;
  8869. }
  8870. return this.appendStartRatio;
  8871. }
  8872. private getDynamicEarlyAppendReserveCount(): number {
  8873. if (this.twoFingerType == 4) {
  8874. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  8875. }
  8876. if (this.isGridMusic) {
  8877. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  8878. }
  8879. if (this.isMediaLibraryListMode()) {
  8880. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  8881. }
  8882. return this.earlyAppendReserveCount;
  8883. }
  8884. private prefetchFollowingPages(nextPage: number): void {
  8885. void this.prefetchNextPage(nextPage);
  8886. if (this.shouldPrefetchSecondPage()) {
  8887. void this.prefetchNextPage(nextPage + 1);
  8888. }
  8889. }
  8890. private scrollToTopForCurrentLayout(): void {
  8891. if (this.twoFingerType == 4) {
  8892. this.waterScroller.scrollEdge(Edge.Top);
  8893. this.scroller.scrollEdge(Edge.Top);
  8894. return;
  8895. }
  8896. if (this.isGridMusic) {
  8897. this.scroller.scrollEdge(Edge.Top);
  8898. return;
  8899. }
  8900. this.listScroller.scrollEdge(Edge.Top);
  8901. }
  8902. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  8903. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  8904. if (coverVersion < -1) {
  8905. return fallback;
  8906. }
  8907. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8908. return fallback;
  8909. }
  8910. const sourceUri = item.pixelMapPath as string;
  8911. this.initCoverThumbCacheIfNeeded();
  8912. const targetSize = this.getListThumbTargetSize();
  8913. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  8914. if (cachedThumb) {
  8915. return cachedThumb;
  8916. }
  8917. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8918. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  8919. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  8920. const isNearVisible = !hasRange ||
  8921. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  8922. if (isNearVisible) {
  8923. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8924. }
  8925. }
  8926. return sourceUri;
  8927. }
  8928. private getListThumbTargetSize(): number {
  8929. if (this.twoFingerType == 1) {
  8930. return 96;
  8931. }
  8932. if (this.twoFingerType == 2) {
  8933. return 112;
  8934. }
  8935. return 128;
  8936. }
  8937. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  8938. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  8939. return;
  8940. }
  8941. this.initCoverThumbCacheIfNeeded();
  8942. const targetSize = this.getListThumbTargetSize();
  8943. const maxCount = Math.min(limit, items.length);
  8944. for (let i = 0; i < maxCount; i++) {
  8945. const item = items[i];
  8946. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8947. continue;
  8948. }
  8949. const sourceUri = item.pixelMapPath as string;
  8950. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8951. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8952. }
  8953. }
  8954. }
  8955. private warmupListVisibleThumbs(start: number, end: number): void {
  8956. if (!this.isMediaLibraryListMode()) {
  8957. return;
  8958. }
  8959. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  8960. return;
  8961. }
  8962. const now = Date.now();
  8963. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  8964. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  8965. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  8966. return;
  8967. }
  8968. this.listThumbWarmupCheckAt = now;
  8969. this.listThumbWarmupStart = start;
  8970. this.listThumbWarmupEnd = end;
  8971. this.initCoverThumbCacheIfNeeded();
  8972. const targetSize = this.getListThumbTargetSize();
  8973. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  8974. const begin = Math.max(0, start - 4);
  8975. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  8976. for (let index = begin; index <= last; index++) {
  8977. const item = this.videoLocalList[index];
  8978. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8979. continue;
  8980. }
  8981. const sourceUri = item.pixelMapPath as string;
  8982. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8983. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8984. }
  8985. }
  8986. }
  8987. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  8988. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  8989. return;
  8990. }
  8991. this.initCoverThumbCacheIfNeeded();
  8992. const isWater = this.twoFingerType == 4;
  8993. const targetSize = this.getCoverThumbTargetSize(isWater);
  8994. const maxCount = Math.min(limit, items.length);
  8995. for (let i = 0; i < maxCount; i++) {
  8996. const item = items[i];
  8997. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8998. continue;
  8999. }
  9000. const sourceUri = item.pixelMapPath as string;
  9001. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9002. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9003. }
  9004. }
  9005. }
  9006. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  9007. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  9008. return;
  9009. }
  9010. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9011. return;
  9012. }
  9013. const now = Date.now();
  9014. let lastStart = -1;
  9015. let lastEnd = -1;
  9016. let lastCheckAt = 0;
  9017. if (isWater) {
  9018. lastStart = this.waterThumbWarmupStart;
  9019. lastEnd = this.waterThumbWarmupEnd;
  9020. lastCheckAt = this.waterThumbWarmupCheckAt;
  9021. } else {
  9022. lastStart = this.gridThumbWarmupStart;
  9023. lastEnd = this.gridThumbWarmupEnd;
  9024. lastCheckAt = this.gridThumbWarmupCheckAt;
  9025. }
  9026. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  9027. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  9028. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  9029. return;
  9030. }
  9031. if (isWater) {
  9032. this.waterThumbWarmupCheckAt = now;
  9033. this.waterThumbWarmupStart = start;
  9034. this.waterThumbWarmupEnd = end;
  9035. } else {
  9036. this.gridThumbWarmupCheckAt = now;
  9037. this.gridThumbWarmupStart = start;
  9038. this.gridThumbWarmupEnd = end;
  9039. }
  9040. this.initCoverThumbCacheIfNeeded();
  9041. const columns = isWater ? Math.max(this.columns, 1) :
  9042. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9043. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  9044. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  9045. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9046. const targetSize = this.getCoverThumbTargetSize(isWater);
  9047. for (let index = begin; index <= last; index++) {
  9048. const item = this.videoLocalList[index];
  9049. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9050. continue;
  9051. }
  9052. const sourceUri = item.pixelMapPath as string;
  9053. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9054. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9055. }
  9056. }
  9057. }
  9058. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  9059. coverVersion: number = 0): ResourceStr {
  9060. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9061. if (coverVersion < -1) {
  9062. return fallback;
  9063. }
  9064. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9065. return fallback;
  9066. }
  9067. const sourceUri = item.pixelMapPath as string;
  9068. this.initCoverThumbCacheIfNeeded();
  9069. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  9070. const targetSize = this.getCoverThumbTargetSize(isWater);
  9071. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9072. if (cachedThumb) {
  9073. return cachedThumb;
  9074. }
  9075. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  9076. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  9077. const columns = isWater ? Math.max(this.columns, 1) :
  9078. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9079. const preloadBuffer = Math.max(columns * 2, 8);
  9080. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  9081. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  9082. if (!isRemoteCover && isNearVisible) {
  9083. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9084. }
  9085. if (!this.isScrolling) {
  9086. return sourceUri;
  9087. }
  9088. if (isNearVisible) {
  9089. return sourceUri;
  9090. }
  9091. return fallback;
  9092. }
  9093. private flushPendingCoverThumbRefresh(): void {
  9094. if (!this.pendingCoverThumbRefresh) {
  9095. return;
  9096. }
  9097. this.pendingCoverThumbRefresh = false;
  9098. this.coverThumbVersion++;
  9099. }
  9100. private initCoverThumbCacheIfNeeded(): void {
  9101. if (this.coverThumbCacheReady) {
  9102. return;
  9103. }
  9104. this.coverThumbCache.setContext(this.context);
  9105. this.coverThumbCache.setOnThumbReady(() => {
  9106. if (this.isScrolling) {
  9107. this.pendingCoverThumbRefresh = true;
  9108. return;
  9109. }
  9110. this.coverThumbVersion++;
  9111. });
  9112. this.coverThumbCacheReady = true;
  9113. }
  9114. private getCoverThumbTargetSize(isWater: boolean): number {
  9115. if (isWater) {
  9116. if (this.columns >= 4) {
  9117. return 160;
  9118. }
  9119. if (this.columns == 3) {
  9120. return 200;
  9121. }
  9122. return 260;
  9123. }
  9124. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  9125. if (this.twoFingerType == 1) {
  9126. return baseSize;
  9127. }
  9128. if (this.twoFingerType == 2) {
  9129. return Math.floor(baseSize * 1.1);
  9130. }
  9131. return Math.floor(baseSize * 1.15);
  9132. }
  9133. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  9134. if (this.videoLocalList.length <= 0) {
  9135. return;
  9136. }
  9137. const columns = Math.max(this.columns, 1);
  9138. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  9139. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  9140. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  9141. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  9142. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  9143. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  9144. this.waterVisibleStart = startIndex;
  9145. this.waterVisibleEnd = estimatedEnd;
  9146. this.lastVisibleEndIndex = estimatedEnd;
  9147. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  9148. const now = Date.now();
  9149. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  9150. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  9151. this.waterScrollPagingCheckAt = now;
  9152. this.waterScrollLastPagingEnd = estimatedEnd;
  9153. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  9154. }
  9155. }
  9156. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  9157. if (this.modeType === 4) {
  9158. return;
  9159. }
  9160. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  9161. return;
  9162. }
  9163. if (this.isHistory || this.isFavMusic) {
  9164. return;
  9165. }
  9166. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9167. return;
  9168. }
  9169. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  9170. return;
  9171. }
  9172. const nextPage = this.currentPage + 1;
  9173. const next2Page = this.currentPage + 2;
  9174. const totalLoaded = this.videoLocalList.length;
  9175. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  9176. const remainCount = this.videoLocalList.length - endIndex - 1;
  9177. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  9178. const appendStartRatio = this.getDynamicAppendStartRatio();
  9179. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  9180. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  9181. if (seenRatio >= preloadStartRatio) {
  9182. if (!this.pageCache.has(nextPage)) {
  9183. void this.prefetchNextPage(nextPage);
  9184. }
  9185. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  9186. void this.prefetchNextPage(next2Page);
  9187. }
  9188. }
  9189. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  9190. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  9191. const shouldGapAppend = this.pageCache.has(nextPage) &&
  9192. seenRatio >= (appendStartRatio - 0.08) &&
  9193. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9194. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  9195. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  9196. return;
  9197. }
  9198. if (this.lastScrollTriggerPage === this.currentPage) {
  9199. return;
  9200. }
  9201. this.lastScrollTriggerPage = this.currentPage;
  9202. Logger.info('heanup LocalMusic',
  9203. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  9204. this.scheduleLoadNextPage(8);
  9205. }
  9206. private scheduleLoadNextPage(delayMs: number = 0): void {
  9207. if (this.pagingScheduleTimer) {
  9208. return;
  9209. }
  9210. this.pagingScheduleTimer = setTimeout(() => {
  9211. this.pagingScheduleTimer = 0;
  9212. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9213. return;
  9214. }
  9215. void this.loadNextPage();
  9216. }, delayMs);
  9217. }
  9218. /**
  9219. * 加载下一页
  9220. */
  9221. private async loadNextPage(): Promise<void> {
  9222. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9223. return;
  9224. }
  9225. this.isPagingTransition = true;
  9226. this.currentPage++;
  9227. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  9228. try {
  9229. await this.loadPage(this.currentPage, true);
  9230. } finally {
  9231. this.isPagingTransition = false;
  9232. }
  9233. }
  9234. //编辑信息
  9235. async doEdit(item: VideoItem) {
  9236. if (!item) {
  9237. return
  9238. }
  9239. if (StrUtil.isEmpty(this.titleStr)) {
  9240. ToastUtil.showToast('标题不能为空')
  9241. return
  9242. }
  9243. //内嵌音乐标签不能开启监听
  9244. // this.deletionWatcher?.stop();
  9245. this.loadingDialogId = DialogHelper.showLoadingDialog()
  9246. if (isRemoteCloudType(item.type)) {
  9247. await this.saveRemoteSongEdit(item);
  9248. return;
  9249. }
  9250. await PermissionUtil.activatePermission(item.filePath)
  9251. let tempOutPath = ''
  9252. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  9253. if(!item.filePath.toLowerCase().includes(this.packName)){
  9254. tempOutPath = this.currentPath + '/' + item.fileName
  9255. }
  9256. console.info('onecold tempOutPath ='+tempOutPath)
  9257. //用户更改了封面,那就内嵌下封面
  9258. if(StrUtil.isNotEmpty(this.imagePathStr)){
  9259. const resultCover:boolean = await changeMusicCover(this.context,
  9260. item.filePath,this.imagePathStr,true,tempOutPath);
  9261. this.imagePathStr = ''
  9262. if(resultCover){
  9263. ToastUtil.showToast('内嵌封面成功')
  9264. }
  9265. }
  9266. const metadata:FFMpegTags = {
  9267. title: this.titleStr,
  9268. artist: this.artistStr,
  9269. album: this.ablumStr,
  9270. TYER:this.yearStr,
  9271. genre:this.genreStr,
  9272. track:this.trackStr,
  9273. album_artist:this.albumArtistStr,
  9274. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  9275. COMPOSER:this.composerStr,
  9276. lyricist:this.lyricistStr,
  9277. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  9278. comment:this.commentStr,
  9279. disc:this.discStr,
  9280. };
  9281. let newInput = item.filePath
  9282. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  9283. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  9284. newInput = tempOutPath
  9285. tempOutPath = ''
  9286. }
  9287. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  9288. ||newInput.toLowerCase().endsWith('.ape')
  9289. ||newInput.toLowerCase().endsWith('.dsf')
  9290. ||newInput.toLowerCase().endsWith('.dff');
  9291. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  9292. const result:boolean = await repairAudioMetadata(
  9293. newInput,
  9294. this.lyricConStr,
  9295. metadata,
  9296. true,
  9297. tempOutPath
  9298. );
  9299. // ToastUtil.showToast('result ='+ result)
  9300. if (result||isWav) {
  9301. if(!item.filePath.includes(this.packName)){
  9302. //内嵌成功的歌路径如果不是包含包名,则要入库
  9303. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  9304. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  9305. this.table.insert(newItem, (id: number) => {
  9306. //加入数据库
  9307. if(this.modeType==0){
  9308. this.deleteCache(this.currentPath)
  9309. this.getSortedFiles(this.currentPath)
  9310. }
  9311. });
  9312. }
  9313. const task = new taskpool.Task(
  9314. updateInfoDb,
  9315. this.context,
  9316. item.filePath,
  9317. this.titleStr,
  9318. this.artistStr,
  9319. this.ablumStr,
  9320. this.lyricConStr,
  9321. this.yearStr,this.genreStr,
  9322. this.trackStr,this.albumArtistStr,
  9323. this.composerStr, this.lyricistStr,
  9324. this.commentStr,this.discStr
  9325. );
  9326. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  9327. if (result) {
  9328. console.log(" onecold 编辑信息成功,数据库已同步");
  9329. if(isWav){
  9330. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  9331. }else{
  9332. ToastUtil.showToast('内嵌音乐标签成功')
  9333. }
  9334. this.isShowMoreView = false
  9335. this.name = this.titleStr
  9336. this.syncEditedFields(item)
  9337. if (item.filePath == this.currentSong?.filePath) {
  9338. this.currentSong.name = this.titleStr
  9339. this.artist = this.artistStr
  9340. this.currentSong.artist = this.artistStr
  9341. this.currentSong.album = this.ablumStr
  9342. this.currentSong.year = this.yearStr
  9343. this.currentSong.genre = this.genreStr
  9344. this.currentSong.track = this.trackStr
  9345. this.currentSong.lyricContent = this.lyricConStr
  9346. this.currentSong.ALBUMARTIST = this.albumArtistStr
  9347. this.currentSong.COMPOSER = this.composerStr
  9348. this.currentSong.LYRICIST = this.lyricistStr
  9349. this.currentSong.COMMENT = this.commentStr
  9350. }
  9351. this.syncListsAfterEdit(item.filePath)
  9352. this.doUpateEditedFields(item)
  9353. //this.doUpdateData()
  9354. } else {
  9355. // ToastUtil.showToast('保存失败' + error?.toString())
  9356. console.error(" onecold 编辑信息数据库失败 ");
  9357. }
  9358. // 关闭进度条
  9359. DialogHelper.closeDialog(this.loadingDialogId)
  9360. }).catch((error: Error) => {
  9361. // 关闭进度条
  9362. DialogHelper.closeDialog(this.loadingDialogId)
  9363. console.error('onecold Subtitle sync failed:', error);
  9364. });
  9365. console.log(' onecold 元数据标签更新成功,');
  9366. } else {
  9367. // 关闭进度条
  9368. DialogHelper.closeDialog(this.loadingDialogId)
  9369. ToastUtil.showToast('内嵌音乐标签失败')
  9370. console.log('onecold 内嵌音乐标签失败');
  9371. }
  9372. this.longItemFilePath = ''
  9373. this.tempLyricContent = ''
  9374. this.isShowEdit = false
  9375. }
  9376. private normalizeEditedCoverPath(path: string): string {
  9377. if (StrUtil.isEmpty(path)) {
  9378. return '';
  9379. }
  9380. const lowerPath = path.toLowerCase();
  9381. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  9382. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  9383. return path;
  9384. }
  9385. return fileUri.getUriFromPath(path);
  9386. }
  9387. private emitRemoteMetadataUpdated(item: VideoItem): void {
  9388. if (!item || StrUtil.isEmpty(item.filePath)) {
  9389. return;
  9390. }
  9391. const payload: WebDavMetadataUpdatePayload = {
  9392. filePath: item.filePath,
  9393. pixelMapPath: item.pixelMapPath,
  9394. isCustomCover: item.isCustomCover,
  9395. md5Str: item.md5Str,
  9396. name: item.name,
  9397. artist: item.artist
  9398. };
  9399. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  9400. emitter.emit(eventUpdate, { data: [payload] });
  9401. }
  9402. private syncRemoteManagerSong(item: VideoItem): void {
  9403. if (!item || StrUtil.isEmpty(item.filePath)) {
  9404. return;
  9405. }
  9406. const remoteManager = RemoteDriveManager.getInstance();
  9407. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  9408. if (!target) {
  9409. return;
  9410. }
  9411. this.mergeVideoItemFromSource(target, item);
  9412. }
  9413. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  9414. try {
  9415. this.syncEditedFields(item);
  9416. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  9417. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  9418. item.isCustomCover = 1;
  9419. }
  9420. this.name = this.titleStr;
  9421. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  9422. this.syncEditedFields(this.currentSong);
  9423. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  9424. mergeCoverWithPriority(this.currentSong, item.pixelMapPath, item.isCustomCover ?? 0);
  9425. this.cover = this.currentSong.pixelMapPath || item.pixelMapPath;
  9426. }
  9427. this.artist = this.currentSong.artist ?? '';
  9428. this.currentSong = cloneVideoItem(this.currentSong);
  9429. AppStorage.setOrCreate('currentSong', this.currentSong);
  9430. }
  9431. this.syncListsAfterEdit(item.filePath);
  9432. this.syncRemoteManagerSong(item);
  9433. await this.persistRemoteMetadataToDb(item);
  9434. this.emitRemoteMetadataUpdated(item);
  9435. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  9436. } catch (error) {
  9437. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  9438. ToastUtil.showToast('网盘歌曲编辑失败');
  9439. } finally {
  9440. DialogHelper.closeDialog(this.loadingDialogId);
  9441. this.longItemFilePath = '';
  9442. this.tempLyricContent = '';
  9443. this.isShowEdit = false;
  9444. this.imagePathStr = '';
  9445. this.isShowMoreView = false;
  9446. }
  9447. }
  9448. // 内嵌标签更新当前内嵌的Item
  9449. async doUpateEditedFields(item: VideoItem) {
  9450. // 找到当前项在 videoLocalList 中的索引
  9451. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  9452. if (index !== -1) {
  9453. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  9454. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  9455. // 只有当查询结果不为 null 时才更新列表
  9456. if (updatedItem !== null) {
  9457. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  9458. this.videoLocalList = [
  9459. ...this.videoLocalList.slice(0, index),
  9460. updatedItem,
  9461. ...this.videoLocalList.slice(index + 1)
  9462. ];
  9463. // 同步更新 LazyDataSource
  9464. this.dataSource.pushArrayData(this.videoLocalList)
  9465. } else {
  9466. ToastUtil.showToast('未找到更新的数据');
  9467. }
  9468. }
  9469. DialogHelper.closeDialog(this.loadingDialogId)
  9470. }
  9471. @Builder
  9472. editSheet(item: VideoItem) {
  9473. Scroll() {
  9474. Column() {
  9475. this.editDetail(item)
  9476. }
  9477. }
  9478. .width('100%')
  9479. .height('100%')
  9480. }
  9481. @Builder
  9482. editDetail(item: VideoItem) {
  9483. Column() {
  9484. if (item) {
  9485. Row() {
  9486. Stack() {
  9487. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  9488. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  9489. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  9490. item.pixelMapPath)
  9491. .fillColor(this.themeColor)
  9492. .height(88)
  9493. .width(88)
  9494. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9495. .borderRadius(12)
  9496. .clip(true)
  9497. .opacity(this.opacityItem)// 绑定透明度
  9498. .margin({ left: 25 })
  9499. }
  9500. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9501. .onClick(async () => {
  9502. const imagePath:string | undefined = await this.goSelectImage(item);
  9503. if (imagePath) {
  9504. //用户更改过图片
  9505. this.imagePathStr = imagePath
  9506. }
  9507. })
  9508. .width('28%')
  9509. Row() {
  9510. Column() {
  9511. Text(item.name)
  9512. .fontSize(17)
  9513. .maxLines(1)
  9514. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9515. .animation({
  9516. duration: 555,
  9517. curve: 'Linear',
  9518. })
  9519. .fontColor(this.themeColor)
  9520. .margin({ left: 8 })
  9521. Row() {
  9522. Text(item.artist)
  9523. .fontSize(14)
  9524. .maxLines(1)
  9525. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9526. .padding({ top: 8 })
  9527. .fontColor(this.themeColor)
  9528. .margin({ left: 8 })
  9529. }
  9530. }
  9531. .height('100%')
  9532. .width(100)
  9533. .layoutWeight(1)
  9534. .justifyContent(FlexAlign.Center)
  9535. .alignItems(HorizontalAlign.Start)
  9536. Column() {
  9537. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9538. Row(){
  9539. SymbolGlyph($r('sys.symbol.picture'))
  9540. .fontSize(18)
  9541. .fontColor([Color.White])
  9542. Text('获取封面')
  9543. .margin({ left: 4 })
  9544. .fontSize(11)
  9545. .fontColor(Color.White)
  9546. .fontWeight(480)
  9547. .textAlign(TextAlign.Center)
  9548. }
  9549. .justifyContent(FlexAlign.Center)
  9550. }
  9551. .height(38)
  9552. .width(100)
  9553. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9554. .backgroundColor(this.themeColor)
  9555. .stateEffect(true)
  9556. .margin({ right: 35 })
  9557. .onClick(async () => {
  9558. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9559. this.showTipsDialog();
  9560. return; // Return empty string when no API is configured
  9561. }
  9562. const imagePath:string | undefined = await this.doSearchCover(item,
  9563. this.titleStr,this.artistStr);
  9564. console.info('onecold imagePath = '+imagePath)
  9565. if (StrUtil.isNotEmpty(imagePath)) {
  9566. //用户更改过图片
  9567. this.imagePathStr = imagePath
  9568. ToastUtil.showToast('获取封面成功')
  9569. }else{
  9570. ToastUtil.showToast('获取封面失败,请重试')
  9571. }
  9572. })
  9573. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9574. Row(){
  9575. SymbolGlyph($r('sys.symbol.input_mode'))
  9576. .fontSize(18)
  9577. .fontColor([Color.White])
  9578. Text('获取歌词')
  9579. .margin({ left: 4 })
  9580. .fontSize(11)
  9581. .fontColor(Color.White)
  9582. .fontWeight(480)
  9583. .textAlign(TextAlign.Center)
  9584. }
  9585. .justifyContent(FlexAlign.Center)
  9586. }
  9587. .height(38)
  9588. .width(100)
  9589. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9590. .backgroundColor(this.themeColor)
  9591. .stateEffect(true)
  9592. .margin({ top: 9, right: 35 })
  9593. .onClick(async () => {
  9594. //判断有没有设置api
  9595. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  9596. if (StrUtil.isEmpty(apiUrl)) {
  9597. this.isLyricSetting = false
  9598. this.showTipsDialog()
  9599. return
  9600. }
  9601. let res: string | undefined = await getApiLyric(apiUrl,
  9602. this.titleStr, this.artistStr, false);
  9603. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9604. this.lyricConStr = res;
  9605. ToastUtil.showToast('获取歌词成功')
  9606. }else{
  9607. ToastUtil.showToast('获取歌词失败,请重试')
  9608. }
  9609. })
  9610. }
  9611. .justifyContent(FlexAlign.Start)
  9612. }
  9613. .height('100%')
  9614. .justifyContent(FlexAlign.Start)
  9615. .layoutWeight(1)
  9616. }
  9617. .width('100%')
  9618. .height(98)
  9619. Row() {
  9620. Text('标题:')
  9621. .fontSize(14)
  9622. .fontColor($r('app.color.text_color'))
  9623. .margin({ left: 22 })
  9624. TextInput({ text: this.titleStr })
  9625. .height(40)
  9626. .maxLines(1)
  9627. .fontSize(14)
  9628. .layoutWeight(1)
  9629. .fontColor($r('app.color.text_color'))
  9630. .margin({ right: 15, left: 10 })
  9631. .onChange((val: string) => {
  9632. this.titleStr = val
  9633. })
  9634. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  9635. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9636. .backgroundColor(this.themeColor)
  9637. .fontSize(10)
  9638. .margin({ right: 20})
  9639. .onClick(async () => {
  9640. let hwTags = await extractHwMediaMetadata(item.filePath)
  9641. let artist = hwTags?.artist|| '';
  9642. let title = hwTags?.title|| '';
  9643. let album = hwTags?.album|| '';
  9644. console.info('onecold 乱码修正 artist='+artist);
  9645. console.info('onecold 乱码修正 title='+title);
  9646. console.info('onecold 乱码修正 album='+album);
  9647. this.titleStr = title;
  9648. this.artistStr = artist;
  9649. this.ablumStr = album;
  9650. })
  9651. }
  9652. .width('100%')
  9653. .margin({ top: 10, bottom: 10 })
  9654. .justifyContent(FlexAlign.Start)
  9655. Row() {
  9656. Text('艺术家:')
  9657. .fontSize(14)
  9658. .fontColor($r('app.color.text_color'))
  9659. .margin({ left: 22 })
  9660. TextInput({ text: this.artistStr })
  9661. .height(40)
  9662. .maxLines(1)
  9663. .fontSize(14)
  9664. .layoutWeight(1)
  9665. .fontColor($r('app.color.text_color'))
  9666. .margin({ right: 20, left: 10 })
  9667. .onChange((val: string) => {
  9668. this.artistStr = val
  9669. })
  9670. }
  9671. .width('100%')
  9672. .margin({ top: 10, bottom: 10 })
  9673. .justifyContent(FlexAlign.Start)
  9674. Row() {
  9675. Text('专辑名:')
  9676. .fontSize(14)
  9677. .fontColor($r('app.color.text_color'))
  9678. .margin({ left: 22 })
  9679. TextInput({ text: this.ablumStr})
  9680. .height(40)
  9681. .maxLines(1)
  9682. .fontSize(14)
  9683. .layoutWeight(1)
  9684. .fontColor($r('app.color.text_color'))
  9685. .margin({ right: 20, left: 10 })
  9686. .onChange((val: string) => {
  9687. this.ablumStr = val
  9688. })
  9689. }
  9690. .width('100%')
  9691. .margin({ top: 10, bottom: 10 })
  9692. .justifyContent(FlexAlign.Start)
  9693. Row() {
  9694. Column(){
  9695. Column(){
  9696. Text('歌词:')
  9697. .fontSize(14)
  9698. .fontColor($r('app.color.text_color'))
  9699. .margin({ top:9,left: 22 })
  9700. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9701. SymbolGlyph($r('sys.symbol.trash_fill'))
  9702. .fontSize(25)
  9703. .alignSelf(ItemAlign.Center)
  9704. .margin({ left: 22,top:25})
  9705. }
  9706. .backgroundColor(Color.Transparent)
  9707. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9708. Visibility.None:Visibility.Visible)
  9709. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9710. .onClick(()=>{
  9711. this.lyricConStr = ''
  9712. this.lyricContent = ''
  9713. this.tempLyricContent = ''
  9714. })
  9715. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9716. SymbolGlyph($r('sys.symbol.plus'))
  9717. .fontSize(25)
  9718. .alignSelf(ItemAlign.Center)
  9719. .margin({ left: 22,top:25})
  9720. }
  9721. .backgroundColor(Color.Transparent)
  9722. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9723. .onClick( ()=>{
  9724. this.callFilePickerSelectFileForLyric()
  9725. })
  9726. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9727. SymbolGlyph($r('sys.symbol.traditional_square'))
  9728. .fontSize(25)
  9729. .alignSelf(ItemAlign.Center)
  9730. .margin({ left: 22,top:25})
  9731. }
  9732. .backgroundColor(Color.Transparent)
  9733. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9734. Visibility.None:Visibility.Visible)
  9735. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9736. .onClick( ()=>{
  9737. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9738. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  9739. })
  9740. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9741. Image($r('app.media.jianti'))
  9742. .height(25)
  9743. .fillColor($r('app.color.text_color'))
  9744. .alignSelf(ItemAlign.Center)
  9745. .margin({ left: 22,top:25})
  9746. }
  9747. .backgroundColor(Color.Transparent)
  9748. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9749. Visibility.None:Visibility.Visible)
  9750. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9751. .onClick( ()=>{
  9752. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9753. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  9754. })
  9755. }
  9756. .layoutWeight(1)
  9757. }
  9758. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  9759. this.tempLyricContent })
  9760. .type(TextAreaType.NORMAL)
  9761. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  9762. .fontSize(14)
  9763. .layoutWeight(1)
  9764. .fontColor($r('app.color.text_color'))
  9765. .margin({ right: 20, left: 10 })
  9766. .onChange((val: string) => {
  9767. this.lyricConStr = val
  9768. })
  9769. }
  9770. .width('100%')
  9771. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  9772. .margin({ top: 10, bottom: 10 })
  9773. .justifyContent(FlexAlign.Start)
  9774. Row() {
  9775. Text('年份:')
  9776. .fontSize(14)
  9777. .fontColor($r('app.color.text_color'))
  9778. .margin({ left: 22 })
  9779. TextInput({ text: item.year })
  9780. .height(40)
  9781. .maxLines(1)
  9782. .fontSize(14)
  9783. .type(InputType.Number)
  9784. .layoutWeight(1)
  9785. .fontColor($r('app.color.text_color'))
  9786. .margin({ right: 20, left: 10 })
  9787. .onChange((val: string) => {
  9788. this.yearStr = val
  9789. })
  9790. }
  9791. .width('100%')
  9792. .margin({ top: 10, bottom: 10 })
  9793. .justifyContent(FlexAlign.Start)
  9794. Row() {
  9795. Text('音轨号:')
  9796. .fontSize(14)
  9797. .fontColor($r('app.color.text_color'))
  9798. .margin({ left: 22 })
  9799. TextInput({ text:item.track=='未知'?'': item.track })
  9800. .height(40)
  9801. .maxLines(1)
  9802. .fontSize(14)
  9803. .type(InputType.Number)
  9804. .layoutWeight(1)
  9805. .fontColor($r('app.color.text_color'))
  9806. .margin({ right: 20, left: 10 })
  9807. .onChange((val: string) => {
  9808. this.trackStr = val
  9809. })
  9810. }
  9811. .width('100%')
  9812. .margin({ top: 10, bottom: 10 })
  9813. .justifyContent(FlexAlign.Start)
  9814. Row() {
  9815. Text('碟号:')
  9816. .fontSize(14)
  9817. .fontColor($r('app.color.text_color'))
  9818. .margin({ left: 22 })
  9819. TextInput({ text:item.disc })
  9820. .height(40)
  9821. .maxLines(1)
  9822. .fontSize(14)
  9823. .type(InputType.Number)
  9824. .layoutWeight(1)
  9825. .fontColor($r('app.color.text_color'))
  9826. .margin({ right: 20, left: 10 })
  9827. .onChange((val: string) => {
  9828. this.discStr = val
  9829. })
  9830. }
  9831. .width('100%')
  9832. .margin({ top: 10, bottom: 10 })
  9833. .justifyContent(FlexAlign.Start)
  9834. Row() {
  9835. Text('风格:')
  9836. .fontSize(14)
  9837. .fontColor($r('app.color.text_color'))
  9838. .margin({ left: 22 })
  9839. TextInput({ text: item.genre })
  9840. .height(40)
  9841. .maxLines(1)
  9842. .fontSize(14)
  9843. .layoutWeight(1)
  9844. .fontColor($r('app.color.text_color'))
  9845. .margin({ right: 20, left: 10 })
  9846. .onChange((val: string) => {
  9847. this.genreStr = val
  9848. })
  9849. }
  9850. .width('100%')
  9851. .margin({ top: 10, bottom: 10 })
  9852. .justifyContent(FlexAlign.Start)
  9853. Row() {
  9854. Text('专辑艺术家:')
  9855. .fontSize(14)
  9856. .fontColor($r('app.color.text_color'))
  9857. .margin({ left: 22 })
  9858. TextInput({ text: item.ALBUMARTIST })
  9859. .height(40)
  9860. .maxLines(1)
  9861. .fontSize(14)
  9862. .layoutWeight(1)
  9863. .fontColor($r('app.color.text_color'))
  9864. .margin({ right: 20, left: 10 })
  9865. .onChange((val: string) => {
  9866. this.albumArtistStr = val
  9867. })
  9868. }
  9869. .width('100%')
  9870. .margin({ top: 10, bottom: 10 })
  9871. .justifyContent(FlexAlign.Start)
  9872. Row() {
  9873. Text('作曲:')
  9874. .fontSize(14)
  9875. .fontColor($r('app.color.text_color'))
  9876. .margin({ left: 22 })
  9877. TextInput({ text: item.COMPOSER })
  9878. .height(40)
  9879. .maxLines(1)
  9880. .fontSize(14)
  9881. .layoutWeight(1)
  9882. .fontColor($r('app.color.text_color'))
  9883. .margin({ right: 20, left: 10 })
  9884. .onChange((val: string) => {
  9885. this.composerStr = val
  9886. })
  9887. }
  9888. .width('100%')
  9889. .margin({ top: 10, bottom: 10 })
  9890. .justifyContent(FlexAlign.Start)
  9891. Row() {
  9892. Text('作词:')
  9893. .fontSize(14)
  9894. .fontColor($r('app.color.text_color'))
  9895. .margin({ left: 22 })
  9896. TextInput({ text: item.LYRICIST })
  9897. .height(40)
  9898. .maxLines(1)
  9899. .fontSize(14)
  9900. .layoutWeight(1)
  9901. .fontColor($r('app.color.text_color'))
  9902. .margin({ right: 20, left: 10 })
  9903. .onChange((val: string) => {
  9904. this.lyricistStr = val
  9905. })
  9906. }
  9907. .width('100%')
  9908. .margin({ top: 10, bottom: 10 })
  9909. .justifyContent(FlexAlign.Start)
  9910. Row() {
  9911. Text('注释:')
  9912. .fontSize(14)
  9913. .fontColor($r('app.color.text_color'))
  9914. .margin({ left: 22 })
  9915. TextInput({ text: item.COMMENT })
  9916. .height(40)
  9917. .maxLines(1)
  9918. .fontSize(14)
  9919. .layoutWeight(1)
  9920. .fontColor($r('app.color.text_color'))
  9921. .margin({ right: 20, left: 10 })
  9922. .onChange((val: string) => {
  9923. this.commentStr = val
  9924. })
  9925. }
  9926. .width('100%')
  9927. .margin({ top: 10, bottom: 10 })
  9928. .justifyContent(FlexAlign.Start)
  9929. Row() {
  9930. Button('保存')
  9931. .fontColor(Color.White)
  9932. .layoutWeight(1)
  9933. .height(50)
  9934. .width(100)
  9935. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9936. .backgroundColor(this.themeColor)
  9937. .stateEffect(true)
  9938. .margin({ right: 20, bottom: 20 })
  9939. .onClick(async () => {
  9940. this.doEdit(item)
  9941. })
  9942. Button('取消')
  9943. .fontColor(Color.White)
  9944. .layoutWeight(1)
  9945. .height(50)
  9946. .width(100)
  9947. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9948. .backgroundColor(this.themeColor)
  9949. .stateEffect(true)
  9950. .margin({ left: 20, bottom: 20 })
  9951. .onClick(async () => {
  9952. if(this.isGridMusic){
  9953. this.longItemFilePath =''
  9954. }else{
  9955. this.isShowEdit = false
  9956. }
  9957. this.setEditStrEmpty()
  9958. if(this.isShowPlay){
  9959. this.isShowEdit = false
  9960. }
  9961. })
  9962. }
  9963. .margin({
  9964. left: 38,
  9965. right: 38,
  9966. top: 10,
  9967. bottom: 10
  9968. })
  9969. .width(250)
  9970. .height(60)
  9971. }
  9972. }
  9973. .margin({ bottom: 20 })
  9974. }
  9975. setEditStrEmpty(){
  9976. this.imagePathStr = ''
  9977. this.lyricConStr = ''
  9978. this.artistStr = ''
  9979. this.titleStr = ''
  9980. this.ablumStr = ''
  9981. this.genreStr = ''
  9982. this.yearStr = ''
  9983. this.trackStr = ''
  9984. this.albumArtistStr = ''
  9985. this.composerStr = ''
  9986. this.lyricistStr = ''
  9987. this.commentStr = ''
  9988. this.discStr = ''
  9989. }
  9990. initEditFields(item?: VideoItem) {
  9991. if (!item) {
  9992. this.setEditStrEmpty()
  9993. return
  9994. }
  9995. this.imagePathStr = ''
  9996. this.titleStr = item.name ?? ''
  9997. this.artistStr = item.artist ?? ''
  9998. this.ablumStr = item.album ?? ''
  9999. this.genreStr = item.genre ?? ''
  10000. this.yearStr = item.year ?? ''
  10001. this.trackStr = item.track ?? ''
  10002. this.albumArtistStr = item.ALBUMARTIST ?? ''
  10003. this.composerStr = item.COMPOSER ?? ''
  10004. this.lyricistStr = item.LYRICIST ?? ''
  10005. this.commentStr = item.COMMENT ?? ''
  10006. this.discStr = item.disc ?? ''
  10007. this.lyricConStr = item.lyricContent ?? ''
  10008. }
  10009. private syncEditedFields(target?: VideoItem) {
  10010. if (!target) {
  10011. return
  10012. }
  10013. target.name = this.titleStr
  10014. target.artist = this.artistStr
  10015. target.album = this.ablumStr
  10016. target.lyricContent = this.lyricConStr
  10017. target.year = this.yearStr
  10018. target.genre = this.genreStr
  10019. target.track = this.trackStr
  10020. target.ALBUMARTIST = this.albumArtistStr
  10021. target.COMPOSER = this.composerStr
  10022. target.LYRICIST = this.lyricistStr
  10023. target.COMMENT = this.commentStr
  10024. target.disc = this.discStr
  10025. }
  10026. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  10027. apply?: (next: Array<VideoItem>) => void) {
  10028. if (!list || ArrayUtil.isEmpty(list)) {
  10029. return
  10030. }
  10031. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  10032. if (index < 0) {
  10033. return
  10034. }
  10035. const nextList = [...list]
  10036. this.syncEditedFields(nextList[index])
  10037. apply?.(nextList)
  10038. }
  10039. private syncListsAfterEdit(filePath: string) {
  10040. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  10041. this.videoLocalList = next
  10042. this.dataSource.pushArrayData(next)
  10043. })
  10044. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  10045. this.songList = next
  10046. this.sonDataSource.pushArrayData(next)
  10047. })
  10048. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  10049. this.favList = next
  10050. })
  10051. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  10052. this.historyList = next
  10053. })
  10054. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  10055. this.currentSongList = next
  10056. })
  10057. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  10058. this.mediaKuList = next
  10059. })
  10060. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  10061. this.filteredList = next
  10062. })
  10063. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  10064. this.artistList = next
  10065. })
  10066. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  10067. this.albumList = next
  10068. })
  10069. this.listRefreshKey++
  10070. }
  10071. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  10072. if (!mainListUpdated && !playlistUpdated) {
  10073. return;
  10074. }
  10075. this.listRefreshKey++;
  10076. if (mainListUpdated) {
  10077. this.dataSource.notifyDataReload();
  10078. }
  10079. if (playlistUpdated) {
  10080. this.sonDataSource.notifyDataReload();
  10081. }
  10082. }
  10083. @Builder
  10084. detailSheet(item:VideoItem) {
  10085. Scroll() {
  10086. Column() {
  10087. this.songDetail(item)
  10088. }
  10089. }
  10090. .width('100%')
  10091. .height('100%')
  10092. }
  10093. @Builder
  10094. songDetail(currentItem:VideoItem) {
  10095. Column() {
  10096. if (currentItem) {
  10097. Row() {
  10098. Stack() {
  10099. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  10100. currentItem.pixelMapPath)
  10101. .fillColor(this.themeColor)
  10102. .height(80)
  10103. .width(80)
  10104. .borderRadius(10)
  10105. .opacity(this.opacityItem)// 绑定透明度
  10106. .margin({ left: 22 })
  10107. }
  10108. Column() {
  10109. Column() {
  10110. Text(currentItem.name)
  10111. .fontSize(16)
  10112. .maxLines(1)
  10113. .animation({
  10114. duration: 555,
  10115. curve: 'Linear',
  10116. })
  10117. .fontColor($r('app.color.text_color'))
  10118. .margin({ left: 15 })
  10119. }
  10120. .height('100%')
  10121. .width('100%')
  10122. .justifyContent(FlexAlign.Center)
  10123. .alignItems(HorizontalAlign.Start)
  10124. }
  10125. .height('100%')
  10126. }
  10127. .width('100%')
  10128. .height(90)
  10129. .justifyContent(FlexAlign.SpaceBetween)
  10130. Row() {
  10131. Text('艺术家:')
  10132. .fontSize(14)
  10133. .fontColor($r('app.color.text_color'))
  10134. .margin({ left: 22 })
  10135. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  10136. .fontSize(14)
  10137. .fontColor($r('app.color.text_color'))
  10138. .margin({ left: 10 })
  10139. .layoutWeight(1)
  10140. }
  10141. .width('100%')
  10142. .margin({ top: 10, bottom: 10 })
  10143. .justifyContent(FlexAlign.Start)
  10144. Row() {
  10145. Text('专辑名:')
  10146. .fontSize(14)
  10147. .fontColor($r('app.color.text_color'))
  10148. .margin({ left: 22 })
  10149. Text(currentItem?.album ?currentItem.album : '未知专辑')
  10150. .fontSize(14)
  10151. .margin({ left: 10 })
  10152. .fontColor($r('app.color.text_color'))
  10153. .layoutWeight(1)
  10154. }
  10155. .width('100%')
  10156. .margin({ top: 10, bottom: 10 })
  10157. .justifyContent(FlexAlign.Start)
  10158. Row() {
  10159. Text('时长:')
  10160. .fontSize(14)
  10161. .fontColor($r('app.color.text_color'))
  10162. .margin({ left: 22 })
  10163. Text(StrUtil.isEmpty(currentItem.duration)?
  10164. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  10165. .fontSize(14)
  10166. .margin({ left: 10 })
  10167. .fontColor($r('app.color.text_color'))
  10168. .layoutWeight(1)
  10169. }
  10170. .width('100%')
  10171. .margin({ top: 10, bottom: 10 })
  10172. .justifyContent(FlexAlign.Start)
  10173. Row() {
  10174. Text('采样率:')
  10175. .fontSize(14)
  10176. .fontColor($r('app.color.text_color'))
  10177. .margin({ left: 22 })
  10178. Text(Utility.convertToKHz(currentItem.sampleRate))
  10179. .fontSize(14)
  10180. .margin({ left: 10 })
  10181. .fontColor($r('app.color.text_color'))
  10182. .layoutWeight(1)
  10183. }
  10184. .width('100%')
  10185. .margin({ top: 10, bottom: 10 })
  10186. .justifyContent(FlexAlign.Start)
  10187. Row() {
  10188. Text('比特率:')
  10189. .fontSize(14)
  10190. .fontColor($r('app.color.text_color'))
  10191. .margin({ left: 22 })
  10192. Text(currentItem.bit_rate)
  10193. .fontSize(14)
  10194. .margin({ left: 10 })
  10195. .fontColor($r('app.color.text_color'))
  10196. .layoutWeight(1)
  10197. }
  10198. .width('100%')
  10199. .margin({ top: 10, bottom: 10 })
  10200. .justifyContent(FlexAlign.Start)
  10201. Row() {
  10202. Text('位深:')
  10203. .fontSize(14)
  10204. .fontColor($r('app.color.text_color'))
  10205. .margin({ left: 22 })
  10206. Text(`${currentItem.bits_per_raw_sample} bits`)
  10207. .fontSize(14)
  10208. .margin({ left: 10 })
  10209. .fontColor($r('app.color.text_color'))
  10210. .layoutWeight(1)
  10211. }
  10212. .width('100%')
  10213. .margin({ top: 10, bottom: 10 })
  10214. .justifyContent(FlexAlign.Start)
  10215. Row() {
  10216. Text('声道:')
  10217. .fontSize(14)
  10218. .fontColor($r('app.color.text_color'))
  10219. .margin({ left: 22 })
  10220. Text(`${currentItem.channels}`)
  10221. .fontSize(14)
  10222. .margin({ left: 10 })
  10223. .fontColor($r('app.color.text_color'))
  10224. .layoutWeight(1)
  10225. }
  10226. .width('100%')
  10227. .margin({ top: 10, bottom: 10 })
  10228. .justifyContent(FlexAlign.Start)
  10229. Row() {
  10230. Text('声道布局:')
  10231. .fontSize(14)
  10232. .fontColor($r('app.color.text_color'))
  10233. .margin({ left: 22 })
  10234. Text(`${currentItem.channel_layout}`)
  10235. .fontSize(14)
  10236. .margin({ left: 10 })
  10237. .fontColor($r('app.color.text_color'))
  10238. .layoutWeight(1)
  10239. }
  10240. .width('100%')
  10241. .margin({ top: 10, bottom: 10 })
  10242. .justifyContent(FlexAlign.Start)
  10243. Row() {
  10244. Text('起始播放点:')
  10245. .fontSize(14)
  10246. .fontColor($r('app.color.text_color'))
  10247. .margin({ left: 22 })
  10248. Text(`${currentItem.start_time}`)
  10249. .fontSize(14)
  10250. .margin({ left: 10 })
  10251. .fontColor($r('app.color.text_color'))
  10252. .layoutWeight(1)
  10253. }
  10254. .width('100%')
  10255. .margin({ top: 10, bottom: 10 })
  10256. .justifyContent(FlexAlign.Start)
  10257. Row() {
  10258. Text('风格:')
  10259. .fontSize(14)
  10260. .fontColor($r('app.color.text_color'))
  10261. .margin({ left: 22 })
  10262. Text(currentItem.genre)
  10263. .fontSize(14)
  10264. .margin({ left: 10 })
  10265. .fontColor($r('app.color.text_color'))
  10266. .layoutWeight(1)
  10267. }
  10268. .width('100%')
  10269. .margin({ top: 10, bottom: 10 })
  10270. .justifyContent(FlexAlign.Start)
  10271. Row() {
  10272. Text('发行时间:')
  10273. .fontSize(14)
  10274. .fontColor($r('app.color.text_color'))
  10275. .margin({ left: 22 })
  10276. Text(currentItem.year)
  10277. .fontSize(14)
  10278. .margin({ left: 10 })
  10279. .fontColor($r('app.color.text_color'))
  10280. .layoutWeight(1)
  10281. }
  10282. .width('100%')
  10283. .margin({ top: 10, bottom: 10 })
  10284. .justifyContent(FlexAlign.Start)
  10285. Row() {
  10286. Text('质量评分:')
  10287. .fontSize(14)
  10288. .fontColor($r('app.color.text_color'))
  10289. .margin({ left: 22 })
  10290. Text(currentItem.probe_score+"")
  10291. .fontSize(14)
  10292. .margin({ left: 10 })
  10293. .fontColor($r('app.color.text_color'))
  10294. .layoutWeight(1)
  10295. }
  10296. .width('100%')
  10297. .margin({ top: 10, bottom: 10 })
  10298. .justifyContent(FlexAlign.Start)
  10299. Row() {
  10300. Text('音轨号:')
  10301. .fontSize(14)
  10302. .fontColor($r('app.color.text_color'))
  10303. .margin({ left: 22 })
  10304. Text(currentItem.track)
  10305. .fontSize(14)
  10306. .margin({ left: 10 })
  10307. .fontColor($r('app.color.text_color'))
  10308. .layoutWeight(1)
  10309. }
  10310. .width('100%')
  10311. .margin({ top: 10, bottom: 10 })
  10312. .justifyContent(FlexAlign.Start)
  10313. Row() {
  10314. Text('碟号:')
  10315. .fontSize(14)
  10316. .fontColor($r('app.color.text_color'))
  10317. .margin({ left: 22 })
  10318. Text(currentItem.disc)
  10319. .fontSize(14)
  10320. .margin({ left: 10 })
  10321. .fontColor($r('app.color.text_color'))
  10322. .layoutWeight(1)
  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. Text(currentItem.ALBUMARTIST)
  10333. .fontSize(14)
  10334. .margin({ left: 10 })
  10335. .fontColor($r('app.color.text_color'))
  10336. .layoutWeight(1)
  10337. }
  10338. .width('100%')
  10339. .margin({ top: 10, bottom: 10 })
  10340. .justifyContent(FlexAlign.Start)
  10341. Row() {
  10342. Text('作曲家:')
  10343. .fontSize(14)
  10344. .fontColor($r('app.color.text_color'))
  10345. .margin({ left: 22 })
  10346. Text(currentItem.COMPOSER)
  10347. .fontSize(14)
  10348. .margin({ left: 10 })
  10349. .fontColor($r('app.color.text_color'))
  10350. .layoutWeight(1)
  10351. }
  10352. .width('100%')
  10353. .margin({ top: 10, bottom: 10 })
  10354. .justifyContent(FlexAlign.Start)
  10355. Row() {
  10356. Text('作词家:')
  10357. .fontSize(14)
  10358. .fontColor($r('app.color.text_color'))
  10359. .margin({ left: 22 })
  10360. Text(currentItem.LYRICIST)
  10361. .fontSize(14)
  10362. .margin({ left: 10 })
  10363. .fontColor($r('app.color.text_color'))
  10364. .layoutWeight(1)
  10365. }
  10366. .width('100%')
  10367. .margin({ top: 10, bottom: 10 })
  10368. .justifyContent(FlexAlign.Start)
  10369. Row() {
  10370. Text('注释:')
  10371. .fontSize(14)
  10372. .fontColor($r('app.color.text_color'))
  10373. .margin({ left: 22 })
  10374. Text(currentItem.COMMENT)
  10375. .fontSize(14)
  10376. .margin({ left: 10 })
  10377. .fontColor($r('app.color.text_color'))
  10378. .layoutWeight(1)
  10379. }
  10380. .width('100%')
  10381. .margin({ top: 10, bottom: 10 })
  10382. .justifyContent(FlexAlign.Start)
  10383. Row() {
  10384. Text('格式:')
  10385. .fontSize(14)
  10386. .fontColor($r('app.color.text_color'))
  10387. .margin({ left: 22 })
  10388. Text(Utility.formatMimeType(currentItem.mimeType))
  10389. .fontSize(14)
  10390. .margin({ left: 10 })
  10391. .fontColor($r('app.color.text_color'))
  10392. .layoutWeight(1)
  10393. }
  10394. .width('100%')
  10395. .margin({ top: 10, bottom: 10 })
  10396. .justifyContent(FlexAlign.Start)
  10397. Row() {
  10398. Text('播放次数:')
  10399. .fontSize(14)
  10400. .fontColor($r('app.color.text_color'))
  10401. .margin({ left: 22 })
  10402. Text(currentItem.playCount?.toString())
  10403. .fontSize(14)
  10404. .margin({ left: 10 })
  10405. .fontColor($r('app.color.text_color'))
  10406. .layoutWeight(1)
  10407. }
  10408. .width('100%')
  10409. .margin({ top: 10, bottom: 10 })
  10410. .justifyContent(FlexAlign.Start)
  10411. Row() {
  10412. Text('流数量:')
  10413. .fontSize(14)
  10414. .fontColor($r('app.color.text_color'))
  10415. .margin({ left: 22 })
  10416. Text(currentItem.nb_streams?.toString())
  10417. .fontSize(14)
  10418. .margin({ left: 10 })
  10419. .fontColor($r('app.color.text_color'))
  10420. .layoutWeight(1)
  10421. }
  10422. .width('100%')
  10423. .margin({ top: 10, bottom: 10 })
  10424. .justifyContent(FlexAlign.Start)
  10425. Row() {
  10426. Text('文件大小:')
  10427. .fontSize(14)
  10428. .fontColor($r('app.color.text_color'))
  10429. .margin({ left: 22 })
  10430. Text(currentItem.size)
  10431. .fontSize(14)
  10432. .margin({ left: 10 })
  10433. .fontColor($r('app.color.text_color'))
  10434. .layoutWeight(1)
  10435. }
  10436. .width('100%')
  10437. .margin({ top: 10, bottom: 10 })
  10438. .justifyContent(FlexAlign.Start)
  10439. Row() {
  10440. Text('文件名:')
  10441. .fontSize(14)
  10442. .fontColor($r('app.color.text_color'))
  10443. .margin({ left: 22 })
  10444. Text(currentItem.fileName)
  10445. .fontSize(14)
  10446. .margin({ left: 10 })
  10447. .fontColor($r('app.color.text_color'))
  10448. .layoutWeight(1)
  10449. }
  10450. .width('100%')
  10451. .margin({ top: 10, bottom: 10 })
  10452. .justifyContent(FlexAlign.Start)
  10453. Row() {
  10454. Text('修改时间:')
  10455. .fontSize(14)
  10456. .fontColor($r('app.color.text_color'))
  10457. .margin({ left: 22 })
  10458. Text(currentItem.cTime)
  10459. .fontSize(14)
  10460. .margin({ left: 10 })
  10461. .fontColor($r('app.color.text_color'))
  10462. .layoutWeight(1)
  10463. }
  10464. .width('100%')
  10465. .margin({ top: 10, bottom: 10 })
  10466. .justifyContent(FlexAlign.Start)
  10467. Row() {
  10468. Text('存放目录:')
  10469. .fontSize(14)
  10470. .fontColor($r('app.color.text_color'))
  10471. .margin({ left: 22 })
  10472. Text(currentItem.filePath)
  10473. .fontSize(12)
  10474. .margin({ left: 10 })
  10475. .fontColor($r('app.color.text_color'))
  10476. .layoutWeight(1)
  10477. }
  10478. .margin({ top: 10, bottom: 10 })
  10479. .width('100%')
  10480. .justifyContent(FlexAlign.Start)
  10481. Row() {
  10482. Text('内嵌歌词:')
  10483. .fontSize(14)
  10484. .fontColor($r('app.color.text_color'))
  10485. .margin({ left: 22 })
  10486. Text(currentItem.lyricContent)
  10487. .fontSize(12)
  10488. .copyOption(CopyOptions.InApp)
  10489. .margin({ left: 10 })
  10490. .fontColor($r('app.color.text_color'))
  10491. .layoutWeight(1)
  10492. }
  10493. .margin({ top: 10, bottom: 10 })
  10494. .width('100%')
  10495. .justifyContent(FlexAlign.Start)
  10496. }
  10497. }
  10498. .margin({ bottom: 20 })
  10499. }
  10500. //定时关闭布局
  10501. @Builder
  10502. TimeCloseSheet() {
  10503. Scroll() {
  10504. Column() {
  10505. this.TimeClose()
  10506. }
  10507. }
  10508. .width('100%')
  10509. .height('100%')
  10510. }
  10511. //倒计时关闭音乐,退出App功能实现。
  10512. @State selectedMinutes: number = 0 // 0表示未开启
  10513. @State remainingSeconds: number = 0
  10514. // 预设时间选项
  10515. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  10516. private formatTime(seconds: number): string {
  10517. const mins = Math.floor(seconds / 60)
  10518. const secs = seconds % 60
  10519. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  10520. }
  10521. // 开始倒计时
  10522. private handleTimeSelect(minutes: number) {
  10523. if (minutes === this.selectedMinutes) {
  10524. this.stopCountdown();
  10525. this.selectedMinutes = 0;
  10526. return;
  10527. }
  10528. this.selectedMinutes = minutes;
  10529. this.remainingSeconds = minutes * 60;
  10530. this.startCountdown(); // 新增调用
  10531. }
  10532. @Builder
  10533. TimeClose() {
  10534. Column() {
  10535. // 倒计时显示区域
  10536. Text(this.selectedMinutes > 0 ?
  10537. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  10538. "定时关闭未开启")
  10539. .fontSize(17)
  10540. .fontColor($r('app.color.text_color'))
  10541. .margin({ top: 2, bottom: 8 });
  10542. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10543. ForEach(this.presetTimes, (minutes: number, index: number) => {
  10544. // 单行时间选项容器
  10545. Row() {
  10546. // 文字描述区域
  10547. Text(this.getDisplayText(minutes))
  10548. .fontSize(15)
  10549. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  10550. $r('app.color.text_color'))// 选中态颜色变化
  10551. .textAlign(TextAlign.Start)
  10552. .layoutWeight(1); // 占据剩余空间
  10553. // 复选框样式的选择器
  10554. Row() {
  10555. if (minutes === this.selectedMinutes) {
  10556. // 选中状态 - 带勾号的圆形复选框
  10557. Row() {
  10558. // 使用系统内置的勾号图标
  10559. Image($r('sys.media.ohos_ic_public_ok'))
  10560. .width(14)
  10561. .height(14)
  10562. .fillColor(Color.White)
  10563. }
  10564. .width(24)
  10565. .height(24)
  10566. .borderRadius(12)
  10567. .backgroundColor(this.themeColor)
  10568. .justifyContent(FlexAlign.Center)
  10569. .alignItems(VerticalAlign.Center)
  10570. } else {
  10571. // 未选中状态的圆形边框
  10572. Row()
  10573. .width(24)
  10574. .height(24)
  10575. .borderRadius(12)
  10576. .border({
  10577. width: 2,
  10578. color: $r('app.color.text_color'),
  10579. style: BorderStyle.Solid
  10580. })
  10581. .backgroundColor(Color.Transparent)
  10582. }
  10583. }
  10584. .width(24)
  10585. .height(24)
  10586. .margin({ left: 20 })
  10587. .justifyContent(FlexAlign.Center)
  10588. .alignItems(VerticalAlign.Center)
  10589. }
  10590. .width('100%')
  10591. .padding({
  10592. top: 18,
  10593. bottom: 18,
  10594. left: 18,
  10595. right: 18
  10596. })
  10597. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  10598. $r('app.color.bottom_control_background')) // 选中背景高亮
  10599. .borderRadius(12)
  10600. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10601. .margin({ bottom: 18 })
  10602. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  10603. });
  10604. }
  10605. .width('100%')
  10606. .padding(16)
  10607. }
  10608. }
  10609. // 获取显示文本
  10610. private getDisplayText(minutes: number): string {
  10611. if (minutes === -1) {
  10612. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  10613. }
  10614. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  10615. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  10616. }
  10617. // 处理选择事件
  10618. private handleSelect(minutes: number): void {
  10619. if (minutes === -1) { // 自定义
  10620. // 弹出自定义时间对话框
  10621. DialogHelper.showTextInputDialog({
  10622. title: '自定义时间',
  10623. maskColor: Color.Transparent,
  10624. inputType: InputType.Number,
  10625. text: '',
  10626. onChange: (text) => {
  10627. console.error("onChange: " + text);
  10628. },
  10629. onAction: (action, dialogId, content) => {
  10630. if (action == DialogAction.TWO) {
  10631. const customMinutes = Number(content);
  10632. if (customMinutes > 0) {
  10633. this.handleTimeSelect(customMinutes); // 设置自定义时间
  10634. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  10635. }
  10636. }
  10637. }
  10638. });
  10639. } else {
  10640. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  10641. }
  10642. }
  10643. // 添加定时器引用
  10644. private timerId: number = -1;
  10645. // 启动/重置倒计时
  10646. private startCountdown() {
  10647. // 清除旧定时器
  10648. if (this.timerId !== -1) {
  10649. clearInterval(this.timerId);
  10650. }
  10651. // 创建新定时器
  10652. if (this.selectedMinutes > 0) {
  10653. this.timerId = setInterval(() => {
  10654. if (this.remainingSeconds === 15) {
  10655. this.showConfirmationDialog();
  10656. }
  10657. if (this.remainingSeconds > 0) {
  10658. this.remainingSeconds -= 1;
  10659. } else {
  10660. this.stopCountdown();
  10661. this.handleTimeout();
  10662. }
  10663. }, 1000);
  10664. }
  10665. }
  10666. // 15倒计时后再次提示显示确认是否关闭App对话框
  10667. private showConfirmationDialog() {
  10668. DialogHelper.showAlertDialog({
  10669. backgroundColor: $r('app.color.btn_green'),
  10670. title: '确认关闭',
  10671. maskColor: Color.Transparent,
  10672. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  10673. borderStyle: BorderStyle.Dashed,
  10674. primaryButton: '暂不关闭',
  10675. secondaryButton: '确定',
  10676. onAction: (action) => {
  10677. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  10678. this.stopCountdown();
  10679. this.selectedMinutes = 0
  10680. } else if (action == DialogAction.TWO) {
  10681. }
  10682. }
  10683. })
  10684. }
  10685. // 停止倒计时
  10686. private stopCountdown() {
  10687. if (this.timerId !== -1) {
  10688. clearInterval(this.timerId);
  10689. this.timerId = -1;
  10690. }
  10691. }
  10692. // 超时处理
  10693. private handleTimeout() {
  10694. // 执行播放器关闭逻辑
  10695. this.selectedMinutes = 0;
  10696. ToastUtil.showToast(" 定时关闭已完成");
  10697. this.stop(); // 假设存在的播放器实例
  10698. //退出APP
  10699. const mContext = getContext(this) as common.UIAbilityContext
  10700. mContext.terminateSelf();
  10701. AvSessionController.getInstance(true).unregisterSessionListener()
  10702. }
  10703. //倒计时关闭音乐,退出App功能实现结束。
  10704. //播放列表的拖动List 重新排序
  10705. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  10706. //左滑操作 移动文件 重命名 删除等操作
  10707. @Builder
  10708. sonButton(item: VideoItem, index: number, filePath: string) {
  10709. Row() {
  10710. //加入下一首播放
  10711. Button() {
  10712. Image($r('app.media.next_to_play'))
  10713. .fillColor(Color.White)
  10714. .width(20)
  10715. }
  10716. .width(40)
  10717. .height(40)
  10718. .type(ButtonType.Circle)
  10719. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10720. .backgroundColor(this.themeColor)
  10721. .margin(5)
  10722. .onClick(() => {
  10723. this.addToNextPlay(item);
  10724. })
  10725. Button() {
  10726. Image($r('app.media.close'))
  10727. .fillColor(Color.White)
  10728. .width(20)
  10729. }
  10730. .width(40)
  10731. .height(40)
  10732. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10733. .type(ButtonType.Circle)
  10734. .backgroundColor(this.themeColor)
  10735. .margin(5)
  10736. .onClick(() => {
  10737. this.songList.splice(Number(index), 1)
  10738. this.sonDataSource.pushArrayData(this.songList)
  10739. })
  10740. Button() {
  10741. Image($r('app.media.share2'))
  10742. .fillColor(Color.White)
  10743. .width(20)
  10744. }
  10745. .width(40)
  10746. .height(40)
  10747. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10748. .type(ButtonType.Circle)
  10749. .backgroundColor(this.themeColor)
  10750. .margin(5)
  10751. .onClick(() => {
  10752. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10753. })
  10754. }
  10755. }
  10756. itemMoveSon(index: number, newIndex: number): void {
  10757. if (newIndex < 0 || newIndex >= this.songList.length) {
  10758. return;
  10759. }
  10760. let tmp = this.songList.splice(index, 1);
  10761. this.songList.splice(newIndex, 0, tmp[0]);
  10762. this.sonDataSource.pushArrayData(this.songList)
  10763. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  10764. if(this.modeType==4&&this.playlistTable){
  10765. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  10766. }
  10767. }
  10768. @Builder
  10769. PlayList() {
  10770. List({ scroller: this.playListScroller }) {
  10771. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  10772. ListItem() {
  10773. this.MusicItemSon(item, index)
  10774. }
  10775. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  10776. .animation({
  10777. duration: 666,
  10778. curve: 'ease-in-out' // 可选动画曲线
  10779. })
  10780. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  10781. // TransitionEffect.scale({ x: 0, y: 0 })))
  10782. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  10783. //拖动List关键代码开始
  10784. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  10785. .zIndex(this.dragItem === index ? 1 : 0)
  10786. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  10787. .gesture(
  10788. GestureGroup(GestureMode.Sequence,
  10789. LongPressGesture({ repeat: true })
  10790. .onAction((event?: GestureEvent) => {
  10791. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  10792. this.scaleItem = index
  10793. })
  10794. })
  10795. .onActionEnd(() => {
  10796. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  10797. this.scaleItem = -1
  10798. })
  10799. }),
  10800. PanGesture({ fingers: 1, direction: null, distance: 0 })
  10801. .onActionStart(() => {
  10802. this.dragItem = index // 记录当前拖动项索引
  10803. this.dragRefOffset = 0 // 重置偏移基准
  10804. })
  10805. .onActionUpdate((event: GestureEvent) => {
  10806. this.offsetY = event.offsetY - this.dragRefOffset;
  10807. this.neighborItem = -1;
  10808. let indexA = this.songList.indexOf(item);
  10809. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  10810. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  10811. let value: number = 0;
  10812. if (this.offsetY < 0) {
  10813. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  10814. this.neighborItem = indexA - 1;
  10815. this.neighborScale = 1 - value / 20;
  10816. } else if (this.offsetY > 0) {
  10817. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  10818. this.neighborItem = indexA + 1;
  10819. this.neighborScale = 1 - value / 20;
  10820. }
  10821. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  10822. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10823. this.offsetY -= this.ITEM_INTV;
  10824. this.dragRefOffset += this.ITEM_INTV;
  10825. this.itemMoveSon(indexA, indexA + 1);
  10826. });
  10827. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  10828. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10829. this.offsetY += this.ITEM_INTV;
  10830. this.dragRefOffset -= this.ITEM_INTV;
  10831. this.itemMoveSon(indexA, indexA - 1);
  10832. });
  10833. }
  10834. })
  10835. .onActionEnd((event: GestureEvent) => {
  10836. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10837. this.dragItem = -1
  10838. this.neighborItem = -1
  10839. })
  10840. animateTo({
  10841. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  10842. }, () => {
  10843. this.scaleItem = -1
  10844. })
  10845. })
  10846. )
  10847. .onCancel(() => {
  10848. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10849. this.dragItem = -1
  10850. this.neighborItem = -1
  10851. })
  10852. animateTo({
  10853. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  10854. }, () => {
  10855. this.scaleItem = -1
  10856. })
  10857. })
  10858. ) //拖动List关键代码结束
  10859. .onClick(() => {
  10860. this.doPlay(item, index, true)
  10861. })
  10862. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  10863. }
  10864. .width('100%')
  10865. .height('100%')
  10866. .onReachEnd(() => {
  10867. if(this.modeType === 4 )
  10868. return;
  10869. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  10870. const isStreamingSong = this.currentSong && (
  10871. isNavidromeType(this.currentSong.type) ||
  10872. isJellyfinType(this.currentSong.type) ||
  10873. isEmbyType(this.currentSong.type) ||
  10874. isAudioStationType(this.currentSong.type) ||
  10875. isPlexType(this.currentSong.type)
  10876. );
  10877. if (isStreamingSong && hasMoreData()) {
  10878. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  10879. void this.loadMoreNavidromeSongs();
  10880. } else {
  10881. void this.tryLoadNextPageForPlayback();
  10882. }
  10883. })
  10884. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10885. // .animation({ duration: 500, curve: Curve.Ease }))
  10886. .cachedCount(10)
  10887. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  10888. .gesture(PinchGesture({ fingers: 2 })
  10889. .onActionEnd((event: GestureEvent) => {
  10890. this.setSonListTwoFingers()
  10891. })
  10892. .onActionUpdate(e => {
  10893. this.scaleValue = this.pinchValue * e.scale
  10894. })
  10895. .onActionStart(e => {
  10896. }))
  10897. .padding({
  10898. bottom: 0
  10899. })
  10900. }
  10901. setSonListTwoFingers() {
  10902. this.pinchValue = this.scaleValue;
  10903. Logger.info('this.pinchValue = ' + this.pinchValue);
  10904. if (this.pinchValue >= 1) {
  10905. this.sonTwoFingerType++
  10906. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  10907. if (this.sonTwoFingerType > 3) {
  10908. this.sonTwoFingerType = 1
  10909. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  10910. }
  10911. } else {
  10912. this.sonTwoFingerType--
  10913. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  10914. if (this.sonTwoFingerType < 1) {
  10915. this.sonTwoFingerType = 1
  10916. }
  10917. }
  10918. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  10919. this.pinchValue = 1;
  10920. this.scaleValue = 1;
  10921. }
  10922. @State sonTwoFingerType:number = 3
  10923. @Builder
  10924. private MusicItemSon(item: VideoItem, index?: number) {
  10925. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10926. Row() {
  10927. Stack() {
  10928. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  10929. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  10930. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  10931. .alt($r('app.media.alt'))
  10932. .fillColor(this.themeColor)
  10933. .borderRadius(this.isCoverRectangle?11:'100%')
  10934. .clip(true)
  10935. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  10936. .draggable(false)// 禁止长按手势拖动
  10937. .autoResize(true) // 重采样,可减少内存占用
  10938. .margin({ left: 20 })
  10939. }
  10940. .width('15%')
  10941. Column() {
  10942. Column() {
  10943. Text(this.isShowFileName?item.fileName :item.name)
  10944. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  10945. .fontColor(this.curIndex === index ? this.themeColor :
  10946. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  10947. .maxLines(1)
  10948. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  10949. Row() {
  10950. Column(){
  10951. Text(item.md5Str?.includes('Lossless')?
  10952. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  10953. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  10954. .padding({ top: 3,right:6,left:6,bottom:3 })
  10955. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  10956. $r('app.color.text_color'))
  10957. .fontWeight(500)
  10958. .borderRadius(12)
  10959. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  10960. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  10961. .backgroundColor('#FFC107')
  10962. }
  10963. .padding({ top: 8 })
  10964. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  10965. item.artist + ' ' + item?.duration)
  10966. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  10967. .padding({ top: 8 })
  10968. .maxLines(1)
  10969. .fontColor(this.curIndex === index ? this.themeColor :
  10970. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  10971. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  10972. Blank()
  10973. Text(item.size)
  10974. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  10975. .padding({ top: 8 })
  10976. .maxLines(1)
  10977. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  10978. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  10979. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  10980. .margin({ left: 10 })
  10981. }
  10982. }
  10983. .height('100%')
  10984. .width('100%')
  10985. .justifyContent(FlexAlign.Center)
  10986. .alignItems(HorizontalAlign.Start)
  10987. }
  10988. .height('100%')
  10989. .width('65%')
  10990. Column() {
  10991. PlayingIndicator({
  10992. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  10993. indicatorSize: 18
  10994. })
  10995. }
  10996. .width('20%')
  10997. }
  10998. }
  10999. .backgroundColor(Color.Transparent)
  11000. .width('100%')
  11001. .reuseId('son_item')
  11002. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  11003. .shadow(this.scaleItem === index ? {
  11004. radius: 70,
  11005. color: '#15000000',
  11006. offsetX: 0,
  11007. offsetY: 0
  11008. } :
  11009. {
  11010. radius: 0,
  11011. color: '#15000000',
  11012. offsetX: 0,
  11013. offsetY: 0
  11014. })
  11015. .animation({ curve: Curve.Sharp, duration: 300 })
  11016. }
  11017. @Builder
  11018. MusicPlayBuilder() {
  11019. Column() {
  11020. this.IjkMusicPlayerView()
  11021. }
  11022. .transition(TransitionEffect.asymmetric(
  11023. TransitionEffect.opacity(1),
  11024. TransitionEffect.OPACITY
  11025. ))
  11026. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  11027. new hdsEffect.HdsEffectBuilder()
  11028. .shaderEffect({
  11029. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  11030. animation: {
  11031. duration: 10000,
  11032. iterations: -1,
  11033. autoPlay: true,
  11034. onFinish: ()=> {
  11035. console.info('Succeeded in finishing');
  11036. }
  11037. },
  11038. controller: this.bgController,
  11039. })
  11040. .buildEffect():null)
  11041. .height('100%')
  11042. .width('100%')
  11043. .onDisAppear(() => {
  11044. this.translateY = 0;
  11045. this.playDragUiOpacity = 1
  11046. })
  11047. .translate({ y: this.translateY })
  11048. .gesture(
  11049. PanGesture(this.panOption)
  11050. .onActionUpdate((event?: GestureEvent) => {
  11051. if (event) {
  11052. // 判断滑动方向
  11053. const offsetY = event.offsetY ?? 0;
  11054. const isSwipeUp = offsetY < 0;
  11055. if (isSwipeUp) {
  11056. // 向上滑动:不应用位移动画,保持 translateY = 0
  11057. this.translateY = 0;
  11058. this.scaleValueImage = 1
  11059. this.scaleValueText = 1
  11060. this.playDragUiOpacity = 1
  11061. } else {
  11062. if(this.isGeKongPlayNext){
  11063. return
  11064. }
  11065. // 向下滑动:应用位移动画
  11066. this.translateY = offsetY;
  11067. // 向下滑动时的缩放效果
  11068. this.getUIContext().animateTo({
  11069. duration: 500,
  11070. curve: Curve.Sharp
  11071. }, () => {
  11072. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - this.translateY / 880));
  11073. console.info('onecold scaleValueImage:', this.scaleValueImage)
  11074. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  11075. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  11076. })
  11077. }
  11078. }
  11079. })
  11080. .onActionEnd((event?: GestureEvent) => {
  11081. // 判断滑动方向
  11082. const offsetY = event?.offsetY ?? 0;
  11083. const isSwipeUp = offsetY < 0;
  11084. const minDistance = 300; // 最小滑动距离
  11085. const minVelocity = 500; // 最小滑动速度
  11086. const velocity = event?.velocityY ?? 0;
  11087. if (isSwipeUp) {
  11088. // 向上滑动:切换下一首
  11089. const shouldSwitch = this.isPlayPageSwipeNext &&
  11090. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  11091. if (shouldSwitch) {
  11092. // 直接切换下一首,无需动画(因为界面没有移动)
  11093. this.playNext().catch(() => {
  11094. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  11095. });
  11096. }
  11097. } else {
  11098. //这里加个变量,是否开启隔空手势播放下一首
  11099. if(this.isGeKongPlayNext){
  11100. this.playNext()
  11101. return
  11102. }
  11103. // 向下滑动:关闭播放页
  11104. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  11105. if (shouldClose) {
  11106. // 添加关闭动画
  11107. this.getUIContext().animateTo({
  11108. duration: 600,
  11109. curve: Curve.Friction
  11110. }, () => {
  11111. this.isShowPlay = false;
  11112. this.scaleValueImage = 1
  11113. this.scaleValueText = 1
  11114. this.playDragUiOpacity = 1
  11115. this.translateY = 0;
  11116. })
  11117. } else {
  11118. // 回弹动画
  11119. this.getUIContext().animateTo({
  11120. duration: 600,
  11121. curve: Curve.Friction
  11122. }, () => {
  11123. this.scaleValueImage = 1
  11124. this.scaleValueText = 1
  11125. this.playDragUiOpacity = 1
  11126. this.translateY = 0;
  11127. })
  11128. }
  11129. }
  11130. })
  11131. )
  11132. }
  11133. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  11134. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  11135. HeightBreakpoint.HEIGHT_LG;
  11136. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  11137. @State topBarHeight: number = 50
  11138. @State barOpacity: number = 1
  11139. @State barBottomOpacity: number = 1
  11140. private hideDone: boolean = false;
  11141. @State currentYOffset: number = 0;
  11142. @State bottomBarHeight: number = 68;
  11143. private isHiding: boolean = false;
  11144. //是否是Pura X外屏,或者小屏幕
  11145. isPuraWP() {
  11146. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  11147. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  11148. }
  11149. //是否是Pura X外屏,或者小屏幕,手机横屏
  11150. /**
  11151. * 是否是Pura X外屏,或者小屏幕,手机横屏
  11152. * @returns
  11153. */
  11154. isCoverOpacity() {
  11155. if (this.isPuraWP()) {
  11156. return true
  11157. }
  11158. if (this.isPhoneLan()) {
  11159. return true
  11160. }
  11161. if (deviceInfo.marketName.includes('Pura X')
  11162. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  11163. return true
  11164. }
  11165. return false
  11166. }
  11167. //是不是手机横屏
  11168. isPhoneLan() {
  11169. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  11170. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  11171. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  11172. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  11173. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  11174. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  11175. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  11176. if (this.isHiCarKuanBianPing()) {
  11177. return true
  11178. }
  11179. if (this.isHiCar()) {
  11180. return false
  11181. }
  11182. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11183. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  11184. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  11185. return true
  11186. }
  11187. return false
  11188. }
  11189. //是不是1920x720的hicar的屏幕分辨率
  11190. isHiCarKuanBianPing(){
  11191. // if(!this.isHiCar()){
  11192. // return false
  11193. // }
  11194. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11195. { ratio: 1920 / 720, name: "1920x720" },
  11196. ];
  11197. const currentRatio: number = this.windowWidth / this.windowHeight;
  11198. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11199. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  11200. for (const hiCarRatio of hiCarAspectRatios) {
  11201. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  11202. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11203. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11204. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11205. //宽扁平的尺寸设置列表展示
  11206. this.twoFingerType ==3
  11207. this.isGridMusic = false
  11208. return true;
  11209. }
  11210. }
  11211. return false;
  11212. }
  11213. //是不是hicar的屏幕分辨率
  11214. isHiCarSmall() {
  11215. if(!this.isHiCar()){
  11216. return false
  11217. }
  11218. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  11219. {
  11220. this.columns = 6
  11221. return false
  11222. }
  11223. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11224. { ratio: 800 / 480, name: "800x480" },
  11225. { ratio: 1280 / 720, name: "1280x720" },
  11226. { ratio: 1920 / 1080, name: "1920x1080" },
  11227. ];
  11228. const currentRatio: number = this.windowWidth / this.windowHeight;
  11229. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11230. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  11231. for (const hiCarRatio of hiCarAspectRatios) {
  11232. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  11233. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11234. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  11235. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11236. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11237. //宽扁平的尺寸设置列表展示
  11238. return true;
  11239. }
  11240. }
  11241. return false;
  11242. }
  11243. isHiCar(): boolean {
  11244. return this.curDisplayIsHiCar;
  11245. }
  11246. //是不是正常的手机竖屏
  11247. isPhonePortrait() {
  11248. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  11249. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  11250. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  11251. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11252. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  11253. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  11254. return true
  11255. }
  11256. return false
  11257. }
  11258. @State showSpeedDialog: boolean = false
  11259. @State longPressSpeed: number = 3 //长按默认倍数
  11260. @Builder
  11261. SpeedDialog() {
  11262. Stack() {
  11263. Column() {
  11264. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11265. .fontColor(Color.White)
  11266. .visibility(Visibility.Hidden)
  11267. }
  11268. .backgroundColor(Color.Black)
  11269. .borderRadius(20)
  11270. .padding({
  11271. top: 10,
  11272. right: 20,
  11273. left: 15,
  11274. bottom: 20
  11275. })
  11276. .opacity(0.6)
  11277. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11278. .fontColor(Color.White)
  11279. }
  11280. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  11281. .zIndex(5)
  11282. .margin({ top: 80 })
  11283. }
  11284. @Builder
  11285. IjkMusicPlayerView() {
  11286. Stack() {
  11287. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  11288. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  11289. HdsVisualComponent()
  11290. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  11291. console.info('Succeeded in finishing');
  11292. })
  11293. .width('100%')
  11294. .height('100%')
  11295. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  11296. }
  11297. Column() {
  11298. Column() {
  11299. //播放标题
  11300. Column() {
  11301. this.PlayTitle()
  11302. }
  11303. .opacity(this.playDragUiOpacity)
  11304. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 30 })
  11305. .width('100%')
  11306. .margin({ top: 0 })
  11307. .height(PlayConstants.HEIGHT)
  11308. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  11309. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  11310. if (this.showSpeedDialog) {
  11311. this.SpeedDialog()
  11312. }
  11313. Stack() {
  11314. //手势拖动快进
  11315. Column()
  11316. .width(CommonConstants.FULL_PERCENT)
  11317. .height('100%')
  11318. .gesture(
  11319. GestureGroup(GestureMode.Parallel,
  11320. // 长按屏幕倍数播放
  11321. LongPressGesture({ repeat: true })
  11322. .onAction(() => {
  11323. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11324. this.showSpeedDialog = true;
  11325. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  11326. }
  11327. })
  11328. .onActionEnd(() => {
  11329. this.showSpeedDialog = false;
  11330. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11331. }),
  11332. )
  11333. )
  11334. }
  11335. .height('65%')
  11336. Swiper() {
  11337. this.CoverInfo()
  11338. this.PlayerLyrics()
  11339. }
  11340. .onChange((index: number) => {
  11341. this.currentSwiperIndex = index
  11342. if (index === 1) {
  11343. this.syncLyricPositionNow()
  11344. }
  11345. })
  11346. .indicator(false)
  11347. .displayCount(this.getPlayerSwiperDisplayCount())
  11348. .clip(false)
  11349. .loop(false)
  11350. .autoPlay(false)
  11351. // .interval(8000)
  11352. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  11353. .height('100%')
  11354. .hitTestBehavior(HitTestMode.Transparent)
  11355. Image($r('app.media.icon_replay'))
  11356. .objectFit(ImageFit.Auto)
  11357. .width('120px')
  11358. .height('120px')
  11359. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  11360. .border({ width: 0 })
  11361. .visibility(Visibility.None)
  11362. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  11363. .onClick(() => {
  11364. console.info('onecold startPlayOrResumePlay 6744')
  11365. this.startPlayOrResumePlay();
  11366. })
  11367. }
  11368. .width(CommonConstants.FULL_PERCENT)
  11369. .height(CommonConstants.FULL_PERCENT)
  11370. .justifyContent(FlexAlign.End)
  11371. }
  11372. .justifyContent(FlexAlign.End)
  11373. .margin({ bottom: 5 })
  11374. }
  11375. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  11376. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  11377. .animation({
  11378. duration: 666,
  11379. curve: 'ease-in-out' // 可选动画曲线
  11380. })
  11381. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  11382. ? BlurStyle.NONE :
  11383. BlurStyle.BACKGROUND_ULTRA_THICK)
  11384. .hitTestBehavior(HitTestMode.Transparent)
  11385. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  11386. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  11387. .onClick(() => {
  11388. if(this.isHiCar())
  11389. return
  11390. if(this.is_auto_hide_progress){
  11391. this.is_auto_hide_progress = false
  11392. }
  11393. this.startAutoHide()
  11394. })
  11395. }
  11396. @Consume progressValue: number ;
  11397. @State currentTime: string = "00:00";
  11398. @State totalTime: string = "00:00";
  11399. @State loadingVisible: Visibility = Visibility.None;
  11400. @State replayVisible: Visibility = Visibility.None;
  11401. @State slideEnable: boolean = false;
  11402. @State aspRatio: number = 0.5;
  11403. @State mContext: object | undefined = undefined;
  11404. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  11405. @State mFirst: boolean = true;
  11406. @State mDestroyPage: boolean = false;
  11407. @State playSpeed: number = 1;
  11408. @State oldSeconds: number = 0;
  11409. @State isSeekTo: boolean = false;
  11410. @State isCurrentTime: boolean = false;
  11411. @State videoWidth: string = '100%';
  11412. @State videoHeight: string = '100%';
  11413. @State initAspectRatio: number = 1;
  11414. @State videoAspectRatio: number = this.initAspectRatio;
  11415. @State videoUrl: string = '';
  11416. private last: number = 0;
  11417. @State videoParentAspectRatio: number = this.initAspectRatio;
  11418. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  11419. @Consume CONTROL_PlayStatus: number ;
  11420. @State PROGRESS_MAX_VALUE: number = 100;
  11421. @State updateProgressTimer: number = 0;
  11422. private readonly progressUpdateIntervalMs: number = 120;
  11423. private readonly lyricUpdateMinDeltaMs: number = 24;
  11424. private lastLyricRenderPosition: number = Number.NaN;
  11425. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  11426. @State name: string = '';
  11427. // @State loop: boolean = false;
  11428. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  11429. @State multiple: string = '1.0X';
  11430. xcomponentController: XComponentController = new XComponentController()
  11431. private panOptionBright: PanGestureOptions =
  11432. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  11433. private panOptionVolume: PanGestureOptions =
  11434. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  11435. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  11436. //手势的音量控制和亮度控制
  11437. private positionX: number = PlayConstants.POSITION_X;
  11438. private positionY: number = PlayConstants.POSITION_Y;
  11439. private windowClass: window.Window = globalThis.windowClass
  11440. @State volume: number = 0.8;
  11441. @State volumeBoostPercent: number = 0
  11442. @State volumeSmall: boolean = false
  11443. @State autoParseMusicName: boolean = true
  11444. @State isShowFileName: boolean = false
  11445. @State isLongNameRoLL: boolean = true//长歌名滚动
  11446. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  11447. private readonly volumeBoostMaxPercent: number = 500;
  11448. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  11449. @State bright: number = PlayConstants.BRIGHT;
  11450. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  11451. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  11452. @State screenWidth: number = 0
  11453. @State screenHeight: number = 0
  11454. @State statusBarHeight: number = 0
  11455. @State isYesFull: boolean = false
  11456. private seekValue: number = 0
  11457. @State isVideoLock: boolean = false; // Whether the video playback is locked
  11458. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  11459. private playbackUrlRequestSerial: number = 0;
  11460. eventHub = getContext().eventHub;
  11461. private isAppForeground: boolean = true;
  11462. private lastBufferingLogTs: number = 0;
  11463. private readonly bufferingLogIntervalMs: number = 5000;
  11464. //投播组件
  11465. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  11466. // 新的投播控制器(封装了官方示例的逻辑)
  11467. private castControllerWrapper: CastController | undefined = undefined;
  11468. // 保留原始的 avCastController 引用(用于兼容旧代码)
  11469. private castController: avSession.AVCastController | undefined = undefined;
  11470. @State isCastPlaying: boolean = false;
  11471. @State currentTime2: number = 0;
  11472. @State currentStringTime: string = '00:00';
  11473. @State duration: number = 0;
  11474. @State isReady: boolean = false;
  11475. @State durationTime: number = 0;
  11476. @State durationStringTime: string = '00:00';
  11477. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  11478. // @State isPlaying: boolean = false;
  11479. private castSeek: boolean = false;
  11480. private castItem: avSession.AVQueueItem | undefined = undefined;
  11481. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  11482. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  11483. @State rotateAngle2: number = -9
  11484. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  11485. @Consume cover: string | undefined ;
  11486. @State artist: string | undefined = ''
  11487. // 1.初始化controller
  11488. private lyricController: LyricController = new LyricController()
  11489. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  11490. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  11491. private parser = new LyricParser()
  11492. @State randomShakenX: number = 0
  11493. @State randomShakenY: number = 0
  11494. @State lyricTextSize: number = 24
  11495. @State lyricContent: string = ''
  11496. @State isDebug: boolean = false
  11497. @State isHightLightCenter: boolean = true
  11498. private syncWordByWordLyricMode(): void {
  11499. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11500. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11501. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11502. }
  11503. private syncLyricLightTextMode(): void {
  11504. this.lyricController.setLightText(this.isLightText)
  11505. this.lyricControllerXF.setLightText(this.isLightText)
  11506. this.lyricControllerSingle.setLightText(this.isLightText)
  11507. }
  11508. /**
  11509. * 初始化歌词加载与展示逻辑
  11510. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  11511. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  11512. * @param isApi2 是否使用API2获取歌词(可选)
  11513. *
  11514. * 主要流程:
  11515. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  11516. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  11517. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  11518. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  11519. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  11520. * 6. 解析失败或读取失败时,清空歌词显示。
  11521. *
  11522. * 注意事项:
  11523. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  11524. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  11525. * - 歌词内容解析后通过lyricController驱动UI渲染。
  11526. */
  11527. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  11528. if (StrUtil.isEmpty(lyricPath)) {
  11529. return
  11530. }
  11531. this.syncWordByWordLyricMode()
  11532. this.syncLyricLightTextMode()
  11533. this.initPipLyricSetting()
  11534. this.lyricControllerSingle
  11535. .setTextSize(15)
  11536. .setCacheSize(4)
  11537. .setTextColor("#FFFFFF")
  11538. .setHighlightColor(this.currentHighLightLyricColor)
  11539. .setHighlightScale(1.2)
  11540. .setEmptyHint("")
  11541. .setLineSpace(1)
  11542. .setAlignMode('center')
  11543. .setAnimationDuration(500)
  11544. .setSingleLine(true)
  11545. this.lyricContent = ''
  11546. this.lyricController
  11547. .setTextSize(this.currentLyricSize)
  11548. .setCacheSize(4)
  11549. .setTextColor("#DDDDDD")
  11550. .setHighlightColor("#FFFFFF")
  11551. .setEmptyHint("")
  11552. .setAnimationDuration(1000)
  11553. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  11554. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  11555. this.setBlurDegree(this.blurDegree, false)
  11556. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  11557. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  11558. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  11559. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  11560. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  11561. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  11562. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  11563. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  11564. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  11565. this.lyricController.setTextWeight(this.lyricTextWeight)
  11566. this.showSingleLyric = false
  11567. // 加载已保存的歌词时间偏移
  11568. this.loadLyricTimeOffset()
  11569. this.lyricController.setLyric(null)
  11570. this.lyricControllerSingle.setLyric(null)
  11571. console.log("onecold lyricPath =" + lyricPath)
  11572. // 1. 检查内嵌歌词
  11573. let neiqianLrc = ''
  11574. let lyContent = this.currentSong?.lyricContent
  11575. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  11576. neiqianLrc = lyContent
  11577. }
  11578. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  11579. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  11580. // Navidrome JSON歌词转换
  11581. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  11582. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  11583. if (convertedLyric) {
  11584. neiqianLrc = convertedLyric;
  11585. console.log("onecold Navidrome歌词转换成功");
  11586. }
  11587. }
  11588. this.setLyricToControllers(neiqianLrc);
  11589. return
  11590. }
  11591. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  11592. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  11593. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  11594. song: this.currentSong,
  11595. playbackUrl: this.videoUrl,
  11596. manager: RemoteDriveManager.getInstance(),
  11597. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  11598. });
  11599. if (StrUtil.isNotEmpty(remoteLyric)) {
  11600. this.currentSong.lyricContent = remoteLyric;
  11601. this.setLyricToControllers(remoteLyric);
  11602. void this.persistRemoteMetadataToDb(this.currentSong);
  11603. return;
  11604. }
  11605. }
  11606. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  11607. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  11608. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  11609. || isPlexType(this.currentSong.type))) {
  11610. const manager = RemoteDriveManager.getInstance();
  11611. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  11612. // 将currentSong转换为SongData接口
  11613. const songData: SongData = {
  11614. webdav_account_id: this.currentSong.webdav_account_id,
  11615. artist: this.currentSong.artist,
  11616. name: this.currentSong.name,
  11617. webdav_id: this.currentSong.webdav_id,
  11618. lyricIndex: this.currentSong.lyricIndex,
  11619. type: this.currentSong.type
  11620. };
  11621. let serverLyric = '';
  11622. if (!serverLyric && isNavidromeType(songData.type)) {
  11623. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  11624. }
  11625. if (!serverLyric && isJellyfinType(songData.type)) {
  11626. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  11627. }
  11628. if (!serverLyric && isEmbyType(songData.type)) {
  11629. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  11630. }
  11631. if (!serverLyric && isAudioStationType(songData.type)) {
  11632. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  11633. }
  11634. if (!serverLyric && isPlexType(songData.type)) {
  11635. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  11636. }
  11637. if (serverLyric) {
  11638. this.setLyricToControllers(serverLyric, lyricPath);
  11639. return;
  11640. }
  11641. }
  11642. // 4. 尝试在线歌词API
  11643. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  11644. && !Utility.isVideoByExtension(this.videoUrl))) {
  11645. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  11646. return;
  11647. }
  11648. // 5. 从本地文件读取歌词
  11649. await this.loadLyricFromFile(lyricPath, isLocal || false);
  11650. }
  11651. /**
  11652. * 从本地文件加载歌词
  11653. */
  11654. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  11655. try {
  11656. let realLyricPath = lyricPath;
  11657. // 读取文件内容
  11658. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  11659. const stat = await fileIo.stat(file.fd);
  11660. const arrayBuffer = new ArrayBuffer(stat.size);
  11661. fs.read(file.fd, arrayBuffer)
  11662. .then((readLen: number) => {
  11663. console.info("read file data succeed");
  11664. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  11665. if (buf.length === 0) {
  11666. throw new Error("Buffer is empty after reading the file");
  11667. }
  11668. try {
  11669. // 检测文件编码
  11670. let detectedEncoding = this.detect(arrayBuffer);
  11671. console.info("onecoldT Detected encoding: " + detectedEncoding);
  11672. // 使用检测到的编码解码,解决中文乱码问题
  11673. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  11674. console.info("onecoldT Detected textDecoder: " + textDecoder);
  11675. let fileContent = textDecoder.decode(buf);
  11676. console.info(`onecoldT The content of file1: ${fileContent}`);
  11677. console.info(`onecold The content of file2: ${fileContent}`);
  11678. this.lyricContent = fileContent;
  11679. if(isLocal){
  11680. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  11681. this.lyricConStr = fileContent;
  11682. }
  11683. this.setLyricToControllers(fileContent);
  11684. console.info(`The content of file: ${fileContent}`);
  11685. } catch (chardetError) {
  11686. console.error("chardet.detect failed with error: " + chardetError.message);
  11687. this.clearLyricControllers();
  11688. }
  11689. })
  11690. .catch((err: BusinessError) => {
  11691. this.clearLyricControllers();
  11692. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  11693. })
  11694. .catch((err: Error) => {
  11695. this.clearLyricControllers();
  11696. console.error("read file 2 data failed with error message: " + err.message);
  11697. })
  11698. .finally(() => {
  11699. fs.closeSync(file);
  11700. });
  11701. } catch (error) {
  11702. this.clearLyricControllers();
  11703. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  11704. }
  11705. }
  11706. detect(data: ArrayBuffer): string {
  11707. //创建检测对象
  11708. let detector: UniversalDetector = new UniversalDetector();
  11709. // 限制检测数据大小,避免内存溢出
  11710. // 通常只需要检测文件前16KB就足够判断编码格式
  11711. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  11712. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  11713. // 传入检测数据并实时判断编码格式
  11714. detector.handleData(data, 0, detectSize);
  11715. // 标记检测数据 读取结束
  11716. detector.dataEnd();
  11717. // 获取检测结果
  11718. let detected: string = detector.getDetectedCharset();
  11719. // 释放资源
  11720. detector.reset();
  11721. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  11722. return detected;
  11723. }
  11724. /**
  11725. * 设置歌词到所有控制器
  11726. * @param lyricText 歌词文本
  11727. * @param savePath 可选,如果提供则保存到本地文件
  11728. */
  11729. private setLyricToControllers(lyricText: string, savePath?: string): void {
  11730. if (StrUtil.isEmpty(lyricText)) {
  11731. this.clearLyricControllers();
  11732. return;
  11733. }
  11734. this.lyricContent = lyricText;
  11735. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  11736. const lyric: Lyric = this.parser.parse(lines);
  11737. this.lyricController.setLyric(lyric);
  11738. this.lyricControllerXF.setLyric(lyric);
  11739. this.lyricControllerSingle.setLyric(lyric);
  11740. this.showSingleLyric = true;
  11741. // 如果提供了保存路径,保存歌词到本地
  11742. if (savePath) {
  11743. this.saveDataToFile(lyricText, savePath);
  11744. }
  11745. }
  11746. /**
  11747. * 清空所有歌词控制器
  11748. */
  11749. private clearLyricControllers(): void {
  11750. this.lyricController.setLyric(null);
  11751. this.lyricControllerXF.setLyric(null);
  11752. this.lyricControllerSingle.setLyric(null);
  11753. }
  11754. private extractLyricCopyLines(lyricText: string): string[] {
  11755. if (StrUtil.isEmpty(lyricText)) {
  11756. return [];
  11757. }
  11758. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  11759. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  11760. const lines = source.split('\n');
  11761. const result: string[] = [];
  11762. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  11763. for (let i = 0; i < lines.length; i++) {
  11764. const line = lines[i].trim();
  11765. if (!line || metaTagPattern.test(line)) {
  11766. continue;
  11767. }
  11768. const pureLine = line
  11769. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  11770. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  11771. .trim();
  11772. if (pureLine.length > 0) {
  11773. result.push(pureLine);
  11774. }
  11775. }
  11776. return result;
  11777. }
  11778. private openLyricCopySheet(): void {
  11779. const lines = this.extractLyricCopyLines(this.lyricContent);
  11780. if (ArrayUtil.isEmpty(lines)) {
  11781. ToastUtil.showToast('暂无可复制歌词');
  11782. return;
  11783. }
  11784. this.lyricCopyLines = lines;
  11785. this.lyricSelectedIndexes = [];
  11786. this.isShowLyricCopySheet = true;
  11787. }
  11788. private toggleLyricLineSelection(index: number): void {
  11789. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  11790. if (selectedIndex >= 0) {
  11791. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  11792. nextSelectedIndexes.splice(selectedIndex, 1);
  11793. this.lyricSelectedIndexes = nextSelectedIndexes;
  11794. return;
  11795. }
  11796. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  11797. }
  11798. private toggleLyricSelectAll(): void {
  11799. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  11800. this.lyricSelectedIndexes = [];
  11801. return;
  11802. }
  11803. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  11804. }
  11805. private copySelectedLyricLines(): void {
  11806. const selectedLines = this.getSelectedLyricLines();
  11807. if (ArrayUtil.isEmpty(selectedLines)) {
  11808. ToastUtil.showToast('暂无可复制歌词');
  11809. return;
  11810. }
  11811. Utility.copyText(selectedLines.join('\n'));
  11812. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  11813. }
  11814. private getSelectedLyricLines(): string[] {
  11815. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  11816. return [];
  11817. }
  11818. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  11819. const selectedLines: string[] = [];
  11820. for (let i = 0; i < selectedIndexes.length; i++) {
  11821. const index = selectedIndexes[i];
  11822. if (index >= 0 && index < this.lyricCopyLines.length) {
  11823. selectedLines.push(this.lyricCopyLines[index]);
  11824. }
  11825. }
  11826. return selectedLines;
  11827. }
  11828. private shareSelectedLyricLines(): void {
  11829. const selectedLines = this.getSelectedLyricLines();
  11830. if (ArrayUtil.isEmpty(selectedLines)) {
  11831. ToastUtil.showToast('暂无可分享歌词');
  11832. return;
  11833. }
  11834. const shareTitle = `${this.currentSong?.name ?? '歌词'}歌词`;
  11835. Utility.doShareText(selectedLines.join('\n'), this.context, shareTitle, '分享歌词');
  11836. }
  11837. /**
  11838. * 从在线API获取歌词
  11839. */
  11840. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  11841. if (!this.currentSong) {
  11842. this.clearLyricControllers();
  11843. if (isOnLineAndToast) {
  11844. ToastUtil.showShort('未获取到歌词!');
  11845. }
  11846. return;
  11847. }
  11848. let artist = this.currentSong.artist || '';
  11849. if (isApi2 === undefined) {
  11850. isApi2 = false;
  11851. }
  11852. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  11853. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11854. this.setLyricToControllers(res, lyricPath);
  11855. } else {
  11856. this.clearLyricControllers();
  11857. if (isOnLineAndToast) {
  11858. ToastUtil.showShort('未获取到歌词!');
  11859. }
  11860. }
  11861. });
  11862. }
  11863. //初始化悬浮歌词的自定义设置
  11864. initPipLyricSetting() {
  11865. this.lyricControllerXF
  11866. .setTextSize(this.currentLyricSize)
  11867. .setCacheSize(4)
  11868. .setTextColor("#DDDDDD")
  11869. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  11870. .setEmptyHint("")
  11871. .setAnimationDuration(1000)
  11872. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  11873. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  11874. this.setBlurDegree(this.blurDegreePip, true)
  11875. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  11876. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  11877. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  11878. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  11879. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  11880. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  11881. this.lyricControllerXF.setHightLightCenter(true)
  11882. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  11883. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  11884. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  11885. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  11886. if (this.pipBgIndex === 0) {
  11887. if (this.cover) {
  11888. this.pipBg = this.cover
  11889. } else {
  11890. this.pipBg = this.imageColor
  11891. }
  11892. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  11893. }
  11894. }
  11895. //根据item返回歌词内容
  11896. async getLyricContent(item: VideoItem): Promise<string> {
  11897. let neiqianLrc = ''
  11898. let lyContent = item?.lyricContent
  11899. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  11900. neiqianLrc = lyContent
  11901. return neiqianLrc
  11902. }
  11903. try {
  11904. //取数据库里面的歌词lyContent
  11905. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  11906. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  11907. console.log("onecold Lyrics:", lyricContent);
  11908. neiqianLrc = lyricContent
  11909. return neiqianLrc
  11910. }
  11911. } catch (error) {
  11912. console.error("Error fetching lyrics:", error);
  11913. }
  11914. try {
  11915. let filePath = item.filePath;
  11916. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  11917. let realLyricPath = lyricPath;
  11918. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  11919. const stat = await fileIo.stat(file.fd);
  11920. const arrayBuffer = new ArrayBuffer(stat.size);
  11921. const readLen = await fs.read(file.fd, arrayBuffer);
  11922. console.info("read file data succeed");
  11923. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  11924. if (buf.length === 0) {
  11925. throw new Error("Buffer is empty after reading the file");
  11926. }
  11927. // let detectedEncoding = chardet.detect(buf);
  11928. let detectedEncoding = this.detect(arrayBuffer)
  11929. console.info("Detected encoding: " + detectedEncoding);
  11930. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  11931. let fileContent = textDecoder.decode(buf);
  11932. console.info(`onecold The content of file1: ${fileContent}`);
  11933. fs.closeSync(file);
  11934. return fileContent;
  11935. } catch (error) {
  11936. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  11937. return '';
  11938. }
  11939. }
  11940. async saveDataToFile(content: string, filePath: string) {
  11941. if (StrUtil.isEmpty(filePath)) {
  11942. return
  11943. }
  11944. try {
  11945. let lyricContent = ''
  11946. lyricContent = content
  11947. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  11948. // 清空文件内容
  11949. await fileIo.truncate(file.fd, 0);
  11950. await fileIo.write(file.fd, lyricContent);
  11951. await fileIo.close(file);
  11952. console.log('onecold lyric file Data saved successfully.');
  11953. } catch (error) {
  11954. console.error('onecold lyric file Failed to save data:', error);
  11955. }
  11956. }
  11957. // 定义开始旋转的方法
  11958. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  11959. @State timer: number = 0
  11960. @State rotateAngle: number = 0
  11961. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  11962. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  11963. // 页面可见性变化回调
  11964. onPageVisibilityChange() {
  11965. // 当页面可见性改变时,重新启动/停止旋转动画
  11966. this.animationRoFun()
  11967. }
  11968. //封面旋转动画
  11969. animationRoFun() {
  11970. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  11971. // 启动旋转动画
  11972. if (!this.isRotationRunning) {
  11973. this.isRotationRunning = true
  11974. this.startContinuousRotation()
  11975. }
  11976. this.startRotation()
  11977. } else {
  11978. // 停止旋转动画
  11979. this.isRotationRunning = false
  11980. clearInterval(this.timer)
  11981. this.stopRotation()
  11982. }
  11983. }
  11984. // 使用持续的动画进行旋转,避免频繁状态更新
  11985. private startContinuousRotation() {
  11986. clearInterval(this.timer)
  11987. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  11988. // 不使用 % 360 取模,让角度持续累加,避免反转
  11989. this.timer = setInterval(() => {
  11990. if (this.isRotationRunning) {
  11991. this.rotateAngle = this.rotateAngle + 36
  11992. }
  11993. }, 1000)
  11994. }
  11995. // 定义开始旋转的方法
  11996. startRotation() {
  11997. if (this.isPlaying) {
  11998. animateTo({
  11999. duration: 777,
  12000. iterations: 1,
  12001. curve: Curve.Linear
  12002. }, () => {
  12003. this.rotateAngle2 = -9
  12004. })
  12005. }
  12006. }
  12007. // 回调,暂停和播放按钮回调,下一首和上一首
  12008. playChange() {
  12009. // if(this.isCoverRectangle){
  12010. // return
  12011. // }
  12012. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12013. this.setIsPlaying(true)
  12014. this.animationState = AnimationStatus.Running
  12015. } else {
  12016. this.setIsPlaying(false)
  12017. this.animationState = AnimationStatus.Paused
  12018. }
  12019. AppStorage.setOrCreate('animationState', this.animationState);
  12020. }
  12021. // 定义停止旋转的方法
  12022. stopRotation() {
  12023. if (this.isCoverRectangle) {
  12024. this.rotateAngle = 0
  12025. } else {
  12026. //唱针以左上角为点选择逆时针40度
  12027. animateTo({
  12028. duration: 1000,
  12029. curve: Curve.Linear,
  12030. iterations: 1,
  12031. }, () => {
  12032. this.rotateAngle2 = -45;
  12033. });
  12034. }
  12035. }
  12036. @Builder
  12037. private LyricsTopItem() {
  12038. Row() {
  12039. Stack({ alignContent: Alignment.Center }) {
  12040. Image( StrUtil.isNotEmpty(this.cover)?
  12041. this.cover:$r('app.media.alt'))
  12042. .height(58)
  12043. .width(58)
  12044. .clip(true)
  12045. .sourceSize({width:38, height:38})
  12046. .alt($r('app.media.alt'))
  12047. .borderRadius(8)
  12048. .clickEffect({ level: ClickEffectLevel.HEAVY })
  12049. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  12050. .shadow({
  12051. radius: 22,
  12052. type: ShadowType.BLUR,
  12053. color: 'on_primary'
  12054. })
  12055. }
  12056. .width(62)
  12057. .height('100%')
  12058. Column() {
  12059. Column() {
  12060. Text(this.name)
  12061. .fontSize(16)
  12062. .maxLines(1)
  12063. .fontWeight(FontWeight.Bolder)
  12064. .fontColor(Color.White)
  12065. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12066. .margin({ left: 10 })
  12067. Row() {
  12068. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  12069. .fontSize(13)
  12070. .fontWeight(FontWeight.Bolder)
  12071. .padding({ top: 8 })
  12072. .fontColor(Color.White)
  12073. .margin({ left: 10 })
  12074. Blank()
  12075. }
  12076. }
  12077. .height('100%')
  12078. .width('100%')
  12079. .justifyContent(FlexAlign.Center)
  12080. .alignItems(HorizontalAlign.Start)
  12081. }
  12082. .height('100%')
  12083. .layoutWeight(1)
  12084. .margin({ right: 8 })
  12085. Column() {
  12086. PointLightDefaultButton({
  12087. isSysBol:false,
  12088. pointColor:Color.White,
  12089. imageResource:$r('app.media.lyric'),
  12090. isPx: false,
  12091. builderHeight: 23,
  12092. builderWidth: 23,
  12093. })
  12094. .onClick(() => {
  12095. this.isLyricSetting = !this.isLyricSetting;
  12096. })
  12097. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  12098. height: '99%',
  12099. dragBar: true,
  12100. preferType: SheetType.CENTER,
  12101. showClose: true,
  12102. blurStyle: BlurStyle.Thin,
  12103. backgroundColor: Color.Transparent,
  12104. title: { title: $r('app.string.lyric_setting') }
  12105. })
  12106. }
  12107. .width(44)
  12108. .height('100%')
  12109. .justifyContent(FlexAlign.Center)
  12110. .alignItems(HorizontalAlign.End)
  12111. }
  12112. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  12113. .padding({ left: 28, right: 28 })
  12114. .height(58)
  12115. .alignItems(VerticalAlign.Center)
  12116. }
  12117. //歌词显示
  12118. @Builder
  12119. PlayerLyrics() {
  12120. Column() {
  12121. Column() {
  12122. this.LyricsTopItem()
  12123. }
  12124. .height(this.isPuraWP() ? 15 : 58)
  12125. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  12126. Visibility.None : Visibility.Visible)
  12127. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  12128. .width("100%")
  12129. Column() {
  12130. LyricView2({
  12131. controller: this.lyricController,
  12132. enableSeek: true,
  12133. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12134. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12135. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12136. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  12137. if (!this.isPlaying) {
  12138. console.info('onecold startPlayOrResumePlay 7527')
  12139. this.startPlayOrResumePlay()
  12140. }
  12141. else {
  12142. this.isSeekTo = true;
  12143. this.mDestroyPage = false;
  12144. // 只有播放网盘歌曲时才显示转圈圈
  12145. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12146. this.showLoadIng();
  12147. }
  12148. this.seekTo(position + "");
  12149. }
  12150. return true
  12151. }
  12152. })
  12153. .width("100%")
  12154. .layoutWeight(1)
  12155. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  12156. .gesture(LongPressGesture()
  12157. .onAction(() => {
  12158. this.openLyricCopySheet();
  12159. }))
  12160. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  12161. height: '99%',
  12162. dragBar: true,
  12163. showClose: true,
  12164. preferType: SheetType.CENTER,
  12165. blurStyle: BlurStyle.Thin,
  12166. title: { title: '歌词' }
  12167. })
  12168. if (this.isPhoneLan()) {
  12169. Column() {
  12170. if (this.isShowSpectrum) {
  12171. this.InlineSpectrumView()
  12172. }
  12173. this.playProgressView()
  12174. }
  12175. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  12176. }
  12177. }
  12178. .position({
  12179. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  12180. (this.isPuraWP() ? 58 : 99)
  12181. })
  12182. .justifyContent(FlexAlign.Center)
  12183. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  12184. }
  12185. }
  12186. @Builder
  12187. LyricCopySheetBuilder() {
  12188. LyricCopySheet({
  12189. lyricCopyLines: this.lyricCopyLines,
  12190. lyricSelectedIndexes: this.lyricSelectedIndexes,
  12191. isDarkMode: this.isDarkMode,
  12192. themeColor: this.themeColor,
  12193. bottomSafeHeight: this.bottomSafeHeight,
  12194. onToggleLyricLine: (index: number) => {
  12195. this.toggleLyricLineSelection(index);
  12196. },
  12197. onToggleSelectAll: () => {
  12198. this.toggleLyricSelectAll();
  12199. },
  12200. onCopySelectedLines: () => {
  12201. this.copySelectedLyricLines();
  12202. },
  12203. onShareSelectedLines: () => {
  12204. this.shareSelectedLyricLines();
  12205. }
  12206. })
  12207. }
  12208. @Builder
  12209. SingleLyricView() {
  12210. Column() {
  12211. Column() {
  12212. LyricView2({
  12213. controller: this.lyricControllerSingle,
  12214. enableSeek: false,
  12215. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12216. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12217. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12218. })
  12219. .gesture(LongPressGesture()
  12220. .onAction(() => {
  12221. this.openLyricCopySheet();
  12222. }))
  12223. }
  12224. .height(82)
  12225. .margin({ bottom: 20 })
  12226. }
  12227. .opacity(this.playDragUiOpacity)
  12228. }
  12229. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  12230. @Builder
  12231. BottomControl() {
  12232. Column() {
  12233. if (this.isShowSpectrum) {
  12234. this.InlineSpectrumView()
  12235. }
  12236. this.TopPlayProgressView()
  12237. //播放 暂停,下一首,上一首
  12238. this.playCenterView()
  12239. if(!this.curDisplayIsHiCar){
  12240. //播放进度条
  12241. this.BottomView()
  12242. }
  12243. }
  12244. .justifyContent(FlexAlign.Center)
  12245. .alignItems(HorizontalAlign.Center)
  12246. .opacity(this.playDragUiOpacity)
  12247. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  12248. }
  12249. @Builder
  12250. playMenuBuilder(){
  12251. Image($r('app.media.menu'))
  12252. .width(24)
  12253. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12254. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  12255. height: '99%',
  12256. preferType:SheetType.CENTER,
  12257. dragBar: true,
  12258. showClose: true,
  12259. blurStyle: BlurStyle.Thin,
  12260. title: { title: $r('app.string.more') },
  12261. backgroundColor: Color.Transparent,
  12262. })
  12263. }
  12264. //播放控制上一首 下一首 暂停和播放
  12265. @Builder
  12266. playCenterView(){
  12267. Row() {
  12268. PointLightButton({
  12269. builder: () => {
  12270. this.playMenuBuilder()
  12271. },
  12272. isPx: false,
  12273. builderHeight: 26,
  12274. builderWidth: 26,
  12275. })
  12276. .onClick(async () =>{
  12277. this.isShowMoreView = !this.isShowMoreView;
  12278. })
  12279. PointLightButton({
  12280. builder: () => {
  12281. this.playPreviousBuilder()
  12282. },
  12283. isPx: false,
  12284. builderHeight: 26,
  12285. builderWidth: 26,
  12286. })
  12287. .onClick(async () =>{
  12288. await this.playPrevious()
  12289. })
  12290. PointLightButton({
  12291. builder: () => {
  12292. this.PlayOrPauseButton()
  12293. },
  12294. isPx: false,
  12295. builderHeight: this.isPhoneLan()?38:41,
  12296. builderWidth: this.isPhoneLan()?38:41,
  12297. })
  12298. .onClick(() =>{
  12299. this.playOrPause()
  12300. })
  12301. PointLightButton({
  12302. builder: () => {
  12303. this.playNextBuilder()
  12304. },
  12305. isPx: false,
  12306. builderHeight: 26,
  12307. builderWidth: 26,
  12308. })
  12309. .onClick(async () =>{
  12310. await this.playNext()
  12311. })
  12312. this.playModeButton()
  12313. }
  12314. .width('95%')
  12315. .margin({ bottom:this.isCoverOpacity()?0:15 })
  12316. .justifyContent(FlexAlign.SpaceEvenly)
  12317. }
  12318. @Builder
  12319. playPreviousBuilder(){
  12320. Image($r('app.media.ic_previous'))
  12321. .width(32)
  12322. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12323. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12324. }
  12325. @Builder
  12326. playNextBuilder(){
  12327. Image($r('app.media.ic_next'))
  12328. .width(32)
  12329. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12330. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12331. }
  12332. @Builder
  12333. PlayOrPauseButton(){
  12334. Stack() {
  12335. Column() {
  12336. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  12337. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  12338. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  12339. .width(this.isPhoneLan()?38:40)
  12340. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12341. .fillColor(Color.White)
  12342. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12343. }
  12344. // 加载进度圈
  12345. if (this.isPlayerLoading) {
  12346. Progress({value:0,total:100,type:ProgressType.Ring })
  12347. .width(this.isPhoneLan()?40:43)
  12348. .height(this.isPhoneLan()?40:43)
  12349. .color(Color.White)
  12350. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  12351. }
  12352. }
  12353. .width(this.isPhoneLan()?38:41)
  12354. .height(this.isPhoneLan()?38:41)
  12355. }
  12356. @Builder
  12357. TopPlayProgressView(){
  12358. Column() {
  12359. Row(){
  12360. Stack(){
  12361. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  12362. .fontColor([Color.White])
  12363. .fontSize(21)
  12364. .effectStrategy(1)
  12365. Text(this.fastForwardSeconds)
  12366. .fontColor(Color.White)
  12367. .fontSize(10)
  12368. .fontWeight(FontWeight.Bold)
  12369. }
  12370. .padding({left:12,bottom:6})
  12371. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12372. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12373. .onClick(()=>{
  12374. this.backForward()
  12375. })
  12376. Slider({
  12377. value: this.progressValue,
  12378. min: 0,
  12379. max: this.PROGRESS_MAX_VALUE,
  12380. step: 1,
  12381. style: SliderStyle.InSet
  12382. })
  12383. .height(20)
  12384. .blockColor('rgba(255,255,255,1)')
  12385. .trackColor('rgba(255,255,255,0.3)')
  12386. .selectedColor(Color.White)
  12387. .trackThickness(4)
  12388. .showSteps(false)
  12389. .showTips(true)
  12390. .layoutWeight(1)
  12391. .enabled(this.slideEnable)
  12392. .onChange((value: number, mode: SliderChangeMode) => {
  12393. if (mode !== 2) {
  12394. return
  12395. }
  12396. if(this.isSeekTo)
  12397. return
  12398. this.isSeekTo = true;
  12399. this.mDestroyPage = false;
  12400. // 只有播放网盘歌曲时才显示转圈圈
  12401. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12402. this.showLoadIng();
  12403. }
  12404. let seekValue = value * (this.getActiveDuration() / 100);
  12405. this.seekTo(seekValue + "", "top-progress-slider");
  12406. })
  12407. Stack(){
  12408. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  12409. .fontColor([Color.White])
  12410. .fontSize(21)
  12411. .effectStrategy(1)
  12412. Text(this.fastForwardSeconds)
  12413. .fontColor(Color.White)
  12414. .fontSize(10)
  12415. .fontWeight(FontWeight.Bold)
  12416. }
  12417. .padding({right:10,bottom:6})
  12418. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12419. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12420. .onClick(()=>{
  12421. this.fastForward()
  12422. })
  12423. }
  12424. .justifyContent(FlexAlign.Center)
  12425. .padding({left:20,right:20})
  12426. .width(this.isLandscape?'88%':'95%')
  12427. Row() {
  12428. Text(this.currentTime)
  12429. .fontSize(10)
  12430. .fontColor(Color.White)
  12431. .margin({left:25})
  12432. Blank()
  12433. Text(this.totalTime)
  12434. .fontSize(10)
  12435. .fontColor(Color.White)
  12436. .margin({right:25})
  12437. }
  12438. .width(this.isLandscape?'85%':'90%')
  12439. .height(10)
  12440. }
  12441. .width('100%')
  12442. .alignItems(HorizontalAlign.Center)
  12443. }
  12444. @Builder
  12445. playModeButton(){
  12446. PointLightButton({
  12447. builder: () => {
  12448. this.playModeBuilder()
  12449. },
  12450. isPx: false,
  12451. builderHeight: 26,
  12452. builderWidth: 26,
  12453. })
  12454. .onClick(async () =>{
  12455. this.setLoopMode()
  12456. })
  12457. }
  12458. @Builder
  12459. playModeBuilder(){
  12460. Column() {
  12461. if (this.playType === 0) {
  12462. Image($r('app.media.loop'))
  12463. .width(24)
  12464. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12465. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12466. } else if (this.playType === 1) {
  12467. Image($r('app.media.single'))
  12468. .width(24)
  12469. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12470. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12471. } else if (this.playType === 2) {
  12472. Image($r('app.media.normal_play'))
  12473. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12474. .width(24)
  12475. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12476. } else if (this.playType === 3) {
  12477. Image($r('app.media.random'))
  12478. .width(24)
  12479. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12480. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12481. } else if (this.playType === 4) {
  12482. Image($r('app.media.noloop'))
  12483. .width(24)
  12484. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12485. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12486. }
  12487. }
  12488. }
  12489. //播放进度条
  12490. @Builder
  12491. BottomView(){
  12492. Row() {
  12493. PointLightDefaultButton({
  12494. isSysBol:true,
  12495. pointColor:Color.White,
  12496. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12497. isPx: false,
  12498. builderHeight: 22,
  12499. builderWidth: 22,
  12500. })
  12501. .onClick(async () =>{
  12502. if (this.isLandscape) {
  12503. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12504. } else {
  12505. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12506. }
  12507. })
  12508. if(this.currentSong){
  12509. PointLightDefaultButton({
  12510. isSysBol:true,
  12511. pointColor:Color.White,
  12512. imageResource:$r('sys.symbol.rename'),
  12513. isPx: false,
  12514. builderHeight: 22,
  12515. builderWidth: 22,
  12516. })
  12517. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  12518. height: '99%',
  12519. dragBar: true,
  12520. showClose: true,
  12521. preferType: SheetType.BOTTOM,
  12522. title: { title: '编辑标签' }
  12523. })
  12524. .onClick(async () => {
  12525. this.initEditFields(this.currentSong)
  12526. this.tempLyricContent = this.lyricContent
  12527. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  12528. this.lyricConStr = this.tempLyricContent
  12529. }
  12530. this.isShowEdit = !this.isShowEdit;
  12531. })
  12532. }
  12533. PointLightDefaultButton({
  12534. isSysBol:true,
  12535. pointColor:Color.White,
  12536. imageResource:$r('sys.symbol.slider_vertical_3'),
  12537. isPx: false,
  12538. builderHeight: 22,
  12539. builderWidth: 22,
  12540. })
  12541. .onClick(async () => {
  12542. this.isEqualizerSheet = !this.isEqualizerSheet;
  12543. })
  12544. PointLightDefaultButton({
  12545. isSysBol:true,
  12546. pointColor:Color.White,
  12547. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  12548. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  12549. isPx: false,
  12550. builderHeight: 22,
  12551. builderWidth: 22,
  12552. })
  12553. .onClick(async () => {
  12554. if(this.currentSong){
  12555. this.doFav(this.currentSong)
  12556. }
  12557. })
  12558. this.playListBuilder()
  12559. }
  12560. .width(this.isLandscape?'88%':'95%')
  12561. .justifyContent(FlexAlign.SpaceAround)
  12562. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  12563. .height(30)
  12564. .animation({
  12565. duration: 666,
  12566. curve: 'ease-in-out' // 可选动画曲线
  12567. })
  12568. }
  12569. @Builder
  12570. fullButton(){
  12571. Column() {
  12572. Image($r('app.media.full_4'))
  12573. .width(25)
  12574. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12575. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12576. }
  12577. }
  12578. @Builder
  12579. playListBuilder(){
  12580. PointLightDefaultButton({
  12581. isSysBol:true,
  12582. pointColor:Color.White,
  12583. imageResource:$r('sys.symbol.music_note_list'),
  12584. isPx: false,
  12585. builderHeight: 26,
  12586. builderWidth: 26,
  12587. })
  12588. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  12589. height: '95%',
  12590. dragBar: true,
  12591. showClose: true,
  12592. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12593. blurStyle: BlurStyle.Thin,
  12594. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  12595. title: {
  12596. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12597. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12598. + `(${this.getPlayListDisplayCount()}首)`
  12599. }
  12600. })
  12601. .onClick(() => {
  12602. this.isShowSheetView = !this.isShowSheetView;
  12603. if(this.isPlayListBgGrass){
  12604. this.isFrontWhite = true
  12605. }else{
  12606. this.isFrontWhite = false
  12607. }
  12608. this.scrollIndex()
  12609. // 只有在播放本地音乐时才自动加载完整列表
  12610. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  12611. void this.hydrateFullMediaPlayListIfNeeded();
  12612. }
  12613. })
  12614. }
  12615. //旧版本播放进度条(现在是手机横屏的播放条)
  12616. @Builder
  12617. playProgressView() {
  12618. Row() {
  12619. Column(){
  12620. PointLightDefaultButton({
  12621. isSysBol:true,
  12622. pointColor:Color.White,
  12623. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12624. isPx: false,
  12625. builderHeight: 26,
  12626. builderWidth: 26,
  12627. })
  12628. .onClick(async () =>{
  12629. if (this.isLandscape) {
  12630. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12631. } else {
  12632. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12633. }
  12634. })
  12635. }
  12636. .margin({ right: 10,bottom:6})
  12637. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12638. .animation({
  12639. duration: 666,
  12640. curve: 'ease-in-out' // 可选动画曲线
  12641. })
  12642. Text(this.currentTime)
  12643. .fontSize($r('app.float.slider_font_size'))
  12644. .fontColor(Color.White)
  12645. .margin(3)
  12646. Slider({
  12647. value: this.progressValue,
  12648. min: 0,
  12649. max: this.PROGRESS_MAX_VALUE,
  12650. step: 1,
  12651. style: SliderStyle.InSet
  12652. })
  12653. .width('600px')
  12654. .blockColor('rgba(255,255,255,1)')
  12655. .trackColor('rgba(255,255,255,0.3)')
  12656. .selectedColor(Color.White)
  12657. .trackThickness(5)
  12658. .layoutWeight(1)
  12659. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  12660. .showSteps(false)
  12661. .showTips(true)
  12662. .enabled(this.slideEnable)
  12663. .onChange((value: number, mode: SliderChangeMode) => {
  12664. if (mode !== 2) {
  12665. return
  12666. }
  12667. this.isSeekTo = true;
  12668. this.mDestroyPage = false;
  12669. // 只有播放网盘歌曲时才显示转圈圈
  12670. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  12671. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12672. this.showLoadIng();
  12673. }
  12674. let seekValue = value * (this.getActiveDuration() / 100);
  12675. this.seekTo(seekValue + "", "landscape-progress-slider");
  12676. })
  12677. Text(this.totalTime)
  12678. .fontSize($r('app.float.slider_font_size'))
  12679. .fontColor(Color.White)
  12680. .margin(3)
  12681. //播放列表
  12682. Column(){
  12683. this.playListBuilder()
  12684. }
  12685. .margin({ left: 10,bottom:6})
  12686. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12687. .animation({
  12688. duration: 666,
  12689. curve: 'ease-in-out' // 可选动画曲线
  12690. })
  12691. }
  12692. //x5的竖屏模式需要99%
  12693. .width(this.isPhonePortrait() ? '93.4%'
  12694. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  12695. .height(this.isPhoneLan() ? 25 : 33)
  12696. .alignItems(VerticalAlign.Bottom)
  12697. .animation({
  12698. duration: 666,
  12699. curve: 'ease-in-out' // 可选动画曲线
  12700. })
  12701. }
  12702. isBigScreen() {
  12703. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  12704. return true
  12705. }
  12706. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  12707. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  12708. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  12709. return false
  12710. } else {
  12711. return true
  12712. }
  12713. return false
  12714. }
  12715. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  12716. // 添加控制缩放的状态变量
  12717. @State scaleValueImage: number = 1
  12718. @State scaleValueText: number = 1
  12719. @State playDragUiOpacity: number = 1
  12720. @Builder
  12721. private CoverScaleGuideOverlay() {
  12722. Stack() {
  12723. Column({ space: 10 }) {
  12724. SymbolGlyph($r('sys.symbol.arrow_up_left_and_arrow_down_right'))
  12725. .fontSize(34)
  12726. .fontColor([Color.White])
  12727. Text('双指缩放封面')
  12728. .fontSize(16)
  12729. .fontWeight(FontWeight.Bold)
  12730. .fontColor(Color.White)
  12731. Text('在封面区域双指捏合,可调整封面大小')
  12732. .fontSize(12)
  12733. .fontColor(Color.White)
  12734. .opacity(0.88)
  12735. .textAlign(TextAlign.Center)
  12736. }
  12737. .padding({ left: 18, right: 18, top: 16, bottom: 16 })
  12738. .backgroundColor('#A6000000')
  12739. .borderRadius(18)
  12740. .width(this.isPhoneLan() ? 230 : 240)
  12741. }
  12742. .width('100%')
  12743. .height(this.isPhoneLan() ? 260 : 360)
  12744. .align(Alignment.Center)
  12745. .zIndex(10)
  12746. .visibility(this.isShowCoverScaleGuide ? Visibility.Visible : Visibility.None)
  12747. .onClick(() => {
  12748. this.dismissCoverScaleGuide()
  12749. })
  12750. }
  12751. @Builder
  12752. CoverInfo() {
  12753. Column() {
  12754. Stack() {
  12755. Column() {
  12756. //方形封面布局
  12757. if (this.isCoverRectangle) {
  12758. this.RectangleCoverView()
  12759. } else {
  12760. //圆形封面布局
  12761. this.CicleCoverView()
  12762. }
  12763. this.musicNameInfo(false)
  12764. if (this.isPhoneLan()) {
  12765. Text(this.name+"--"+this.artist)
  12766. .fontSize(18)
  12767. .fontWeight(FontWeight.Bold)
  12768. .margin({ top: 13 })
  12769. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12770. .maxLines(1)
  12771. .width('99%')
  12772. .textAlign(TextAlign.Center)
  12773. .fontColor(Color.White)
  12774. }
  12775. }
  12776. .width('100%')
  12777. Column({ space: 8 }) {
  12778. Text(this.name)
  12779. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  12780. .fontWeight(FontWeight.Bold)
  12781. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  12782. .maxLines(1)
  12783. .width('85%')
  12784. .textAlign(TextAlign.Center)
  12785. .fontColor(Color.White)
  12786. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  12787. Text(this.artist)
  12788. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  12789. .fontColor(Color.White)
  12790. .fontWeight(FontWeight.Bold)
  12791. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  12792. }
  12793. .justifyContent(FlexAlign.Start)
  12794. .zIndex(1)
  12795. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  12796. this.CoverScaleGuideOverlay()
  12797. }
  12798. .margin({
  12799. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  12800. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  12801. top: this.isCoverOpacity() ? 0 : 20
  12802. })
  12803. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  12804. this.SingleLyricView()
  12805. }
  12806. if (this.isPhoneLan()) {
  12807. Column() {
  12808. this.playCenterView()
  12809. }
  12810. .position({ left: 28, bottom: 35 })
  12811. } else {
  12812. this.BottomControl()
  12813. }
  12814. }
  12815. .width(CommonConstants.FULL_PERCENT)
  12816. .clip(true)
  12817. }
  12818. //方形封面布局
  12819. @Builder
  12820. RectangleCoverView(){
  12821. Stack({alignContent:Alignment.Center}){
  12822. Image( StrUtil.isNotEmpty(this.cover)?
  12823. this.cover:$r('app.media.alt'))
  12824. .height(this.getRectangleCoverHeight())
  12825. .width(this.getRectangleCoverWidth())
  12826. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  12827. .alt($r('app.media.alt'))
  12828. .margin({ right: 8, left: 8, top: 5 })
  12829. .aspectRatio(1)
  12830. .geometryTransition('cover') // 绑定标识符
  12831. .opacity(this.opacityValueImage)
  12832. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  12833. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  12834. {
  12835. preview: MenuPreviewMode.IMAGE,
  12836. previewAnimationOptions: { scale: [0.8, 1.0] },
  12837. })
  12838. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  12839. {
  12840. preview: MenuPreviewMode.IMAGE,
  12841. previewAnimationOptions: { scale: [0.8, 1.0] },
  12842. })
  12843. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  12844. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  12845. .clip(true)
  12846. .rotate({
  12847. x: 0,
  12848. y: 0,
  12849. z: 1,
  12850. angle: this.rotateAngle
  12851. })
  12852. .animation({
  12853. duration: 1000, // 与 setInterval 同步
  12854. curve: Curve.Linear,
  12855. iterations: 1
  12856. })
  12857. .shadow({
  12858. radius: 22,
  12859. type: ShadowType.BLUR,
  12860. color: 'on_primary'
  12861. })
  12862. .onClick(() => {
  12863. this.isMusicBGCover = !this.isMusicBGCover
  12864. })
  12865. .gesture(PinchGesture({ fingers: 2 })
  12866. .onActionUpdate((event: GestureEvent) => {
  12867. this.updateRectangleCoverScaleByPinch(event.scale)
  12868. })
  12869. .onActionEnd(() => {
  12870. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12871. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  12872. }))
  12873. }
  12874. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  12875. // 设置左下角为缩放中心点
  12876. centerX: '0%',
  12877. centerY: '50%' })
  12878. }
  12879. private getRectangleCoverWidth(): string | number {
  12880. if (this.isHiCar() || this.isCoverOpacity()) {
  12881. return 'auto'
  12882. }
  12883. const baseWidth = this.isBigScreen() ? 72 : this.isCoverTopBig ? 100 : 88
  12884. return `${Math.min(100, Math.max(48, baseWidth * this.rectangleCoverScale))}%`
  12885. }
  12886. private getRectangleCoverHeight(): string | number {
  12887. if (this.isHiCar()) {
  12888. return px2vp(this.windowHeight) * 0.4 * this.rectangleCoverScale
  12889. }
  12890. if (this.isCoverOpacity()) {
  12891. return px2vp(this.windowHeight) * 0.54 * this.rectangleCoverScale
  12892. }
  12893. return 'auto'
  12894. }
  12895. private updateCoverScaleByPinch(scale: number): void {
  12896. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * scale))
  12897. }
  12898. private updateRectangleCoverScaleByPinch(scale: number): void {
  12899. const dampedScale = 1 + (scale - 1) * 0.45
  12900. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * dampedScale))
  12901. }
  12902. private persistCoverScaleAfterPinch(): void {
  12903. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12904. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  12905. }
  12906. @Builder
  12907. CicleCoverView() {
  12908. //圆形封面布局
  12909. Stack({alignContent:Alignment.Center}) {
  12910. Image($r('app.media.ic_music_disc'))
  12911. .width(245)
  12912. .height(245)
  12913. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  12914. .aspectRatio(1)
  12915. .opacity(this.isCoverOpacity() ? 0 : 1)
  12916. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  12917. .borderRadius('100%')
  12918. .align(Alignment.Center)
  12919. .clip(true)
  12920. .rotate({
  12921. angle: this.rotateAngle,
  12922. centerX: "50%",
  12923. centerY: "50%",
  12924. })
  12925. .animation({
  12926. duration: 1000, // 改为 1000ms 与 setInterval 同步
  12927. curve: Curve.Linear,
  12928. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  12929. })
  12930. .shadow({
  12931. radius: 22,
  12932. type: ShadowType.BLUR,
  12933. color: 'on_primary'
  12934. })
  12935. Image( StrUtil.isNotEmpty(this.cover)?
  12936. this.cover:$r('app.media.alt'))
  12937. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  12938. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  12939. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  12940. .alt($r('app.media.alt'))
  12941. .margin({ right: 20, left: 20,
  12942. top:this.isCoverRectangle||this.isLandscape?0:50})
  12943. .aspectRatio(1)
  12944. .opacity(this.opacityValueImage)
  12945. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  12946. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  12947. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  12948. .align(Alignment.Center)//
  12949. .clip(true)
  12950. .shadow({
  12951. radius: 22,
  12952. type: ShadowType.BLUR,
  12953. color: 'on_primary'
  12954. })
  12955. .rotate({
  12956. x: 0,
  12957. y: 0,
  12958. z: 1,
  12959. angle: this.rotateAngle
  12960. })
  12961. .animation({
  12962. duration: 1000, // 与 setInterval 同步
  12963. curve: Curve.Linear,
  12964. iterations: 1
  12965. })
  12966. .onClick(() => {
  12967. this.isMusicBGCover = !this.isMusicBGCover
  12968. })
  12969. // 唱针以左上角为点选择逆时针40度
  12970. Image($r('app.media.ic_music_cover_hand'))
  12971. .height(130)
  12972. .margin({ bottom: 200, top: 0 })
  12973. // .position({ x: this.windowWidth/2, y: 0 })
  12974. .align(Alignment.Top)
  12975. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  12976. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  12977. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  12978. }
  12979. .scale({ x: this.scaleValueImage * this.rectangleCoverScale, y: this.scaleValueImage * this.rectangleCoverScale,
  12980. centerX: '50%',
  12981. centerY: '50%' })
  12982. .priorityGesture(PinchGesture({ fingers: 2 })
  12983. .onActionStart(() => {
  12984. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12985. })
  12986. .onActionUpdate((event: GestureEvent) => {
  12987. this.updateCoverScaleByPinch(event.scale)
  12988. })
  12989. .onActionEnd(() => {
  12990. this.persistCoverScaleAfterPinch()
  12991. }))
  12992. }
  12993. @Builder
  12994. MenuImageBuilder(cover: string|undefined) {
  12995. Menu(){
  12996. MenuItem({
  12997. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  12998. content: '查看封面'
  12999. })
  13000. .onClick(async() => {
  13001. if (StrUtil.isEmpty(cover)) {
  13002. ToastUtil.showToast('当前没有可用封面')
  13003. return;
  13004. }
  13005. this.getUIContext().getRouter().pushUrl({
  13006. url: 'pages/WallpaperPreviewPage',
  13007. params: {
  13008. imageUri: cover
  13009. }
  13010. })
  13011. })
  13012. MenuItem({
  13013. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  13014. content: '更换封面'
  13015. })
  13016. .onClick(async() => {
  13017. await this.replaceCurrentSongCoverByAlbum();
  13018. })
  13019. }
  13020. }
  13021. @Builder
  13022. private musicNameInfo(isHidden: boolean) {
  13023. Row(){
  13024. Column({ space: 8 }) {
  13025. Text(this.name)
  13026. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  13027. .fontWeight(FontWeight.Bold)
  13028. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13029. .maxLines(1)
  13030. .width('99%')
  13031. .textAlign(TextAlign.Start)
  13032. .fontColor(Color.White)
  13033. Text(this.artist + ' ' + this.currentSong?.album)
  13034. .fontSize(this.isCoverOpacity() ? 12 : 15)
  13035. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13036. .fontColor(Color.White)
  13037. .textAlign(TextAlign.Start)
  13038. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  13039. .width('99%')
  13040. .maxLines(1)
  13041. }
  13042. .zIndex(1)
  13043. .layoutWeight(1)
  13044. .margin({ left: 15 })
  13045. Blank()
  13046. Row(){
  13047. PointLightDefaultButton({
  13048. isSysBol:true,
  13049. pointColor:Color.White,
  13050. imageResource:this.showSimple?
  13051. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  13052. isPx: false,
  13053. builderHeight: 26,
  13054. builderWidth: 26,
  13055. })
  13056. .onClick(async () => {
  13057. this.showSimple = !this.showSimple
  13058. PreferencesUtil.put('showSimple', this.showSimple)
  13059. })
  13060. }
  13061. .margin({ left: 8,right:8 })
  13062. }
  13063. .width(this.isLandscape?'83%':'90%')
  13064. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  13065. .opacity(this.playDragUiOpacity)
  13066. .margin({ top:this.isCoverRectangle?10: 0 })
  13067. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  13068. }
  13069. @Builder
  13070. private PlayTitle() {
  13071. Row() {
  13072. Row() {
  13073. Image($r('app.media.ic_back_down'))
  13074. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  13075. .hitTestBehavior(HitTestMode.Transparent)
  13076. }
  13077. .width('100%')
  13078. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13079. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  13080. .onClick(() => {
  13081. this.setShowPlayFalse()
  13082. })
  13083. Column() {
  13084. AVCastPicker({
  13085. normalColor: Color.White,
  13086. onStateChange: this.onStateVastChange
  13087. })
  13088. .width(24)
  13089. .height(24)
  13090. }
  13091. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  13092. }
  13093. .width(PlayConstants.ROW_WIDTH)
  13094. }
  13095. @Builder
  13096. lyricSettingSheet(isPip: boolean) {
  13097. Scroll() {
  13098. this.lyricSetting(isPip)
  13099. }
  13100. .width('100%')
  13101. .height('100%')
  13102. }
  13103. @Builder
  13104. lyricSetting(isPip: boolean) {
  13105. Column() {
  13106. // 时间调节模块
  13107. if (!isPip) {
  13108. this.BuildTimeControls()
  13109. }
  13110. // 字号控制模块
  13111. this.BuildFontControls(isPip)
  13112. }
  13113. }
  13114. // 歌词时间偏移状态
  13115. @State timeOffset: number = 0.0
  13116. @State currentLyricColor: string = '#FFFFFF'
  13117. @State currentLyricColorPip: string = '#FFFFFF'
  13118. @State currentHighLightLyricColor: string = '#FF4081'
  13119. @State currentHighLightLyricColorPip: string = '#FF4081'
  13120. // 歌词字号状态
  13121. @State currentLyricSize: number = 20
  13122. @State currentLyricSizePip: number = 20
  13123. // 高亮歌词放大倍数
  13124. @State currentHightLyricSize: number = 1.2
  13125. @State currentHightLyricSizePip: number = 1.2
  13126. @State currentLyricLineSpace: number = 10
  13127. @State currentLyricLineSpacePip: number = 10
  13128. @State currentLyricAlignMode: number = 1
  13129. @State currentLyricAlignModePip: number = 1
  13130. @State blurDegree: number = 2
  13131. @State blurDegreePip: number = 2
  13132. @State isShowSelectColor: boolean = false
  13133. @State isShowHLSelectColor: boolean = false
  13134. @State isShowPipBgSelectColor: boolean = false
  13135. @State pipLyWidth: number = 330
  13136. @State pipLyHeight: number = 120
  13137. // 构建颜色选择器
  13138. @Builder
  13139. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  13140. Row({ space: 10 }) {
  13141. HSBColorPicker({
  13142. color: '#FFFFFF',
  13143. radius: 8,
  13144. layout: HSBColorPickerLayout.COLUMN,
  13145. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  13146. '#fa7105'],
  13147. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  13148. this.changeLyricColor(value, isPip, isBGPip)
  13149. })
  13150. .height(250)
  13151. .layoutWeight(1)
  13152. .padding(25)
  13153. }
  13154. .width('66%')
  13155. }
  13156. @State isOpenPip: boolean = false
  13157. @State pipBgIndex: number = 0
  13158. // 构建字号控制器
  13159. @Builder
  13160. BuildFontControls(isPip: boolean) {
  13161. Column() {
  13162. if (isPip) {
  13163. Column() {
  13164. Row() {
  13165. Text('悬浮歌词')
  13166. .margin({ left: 18 })
  13167. .fontSize(15)
  13168. .fontColor(Color.White)
  13169. .fontWeight(480)
  13170. .layoutWeight(1)
  13171. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  13172. .selectedColor(this.themeColor)
  13173. .switchPointColor(Color.White)
  13174. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13175. .margin({ right: 18 })
  13176. .onChange((checked: boolean) => {
  13177. this.isOpenPip = checked;
  13178. if (this.isOpenPip) {
  13179. this.startPip()
  13180. } else {
  13181. this.stopPip()
  13182. }
  13183. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  13184. })
  13185. .width(50)
  13186. .height(30);
  13187. }
  13188. .height(55)
  13189. }
  13190. .backgroundColor(Color.Transparent)
  13191. .borderRadius(15)
  13192. .margin({
  13193. left: 30,
  13194. right: 30,
  13195. top: 0,
  13196. bottom: 20
  13197. })
  13198. .padding(0)
  13199. .border({
  13200. color: Color.White,
  13201. width: 1.8
  13202. })
  13203. }else{
  13204. Row() {
  13205. Row() {
  13206. Text(`迷你歌词:`)
  13207. .fontSize(14)
  13208. .fontColor(Color.White)
  13209. .width(88)
  13210. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  13211. .selectedColor(this.themeColor)
  13212. .switchPointColor(Color.White)
  13213. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13214. .onChange((checked: boolean) => {
  13215. this.isShowSingleLineLyric = checked;
  13216. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  13217. })
  13218. .width(50)
  13219. .height(30)
  13220. .alignSelf(ItemAlign.Start)
  13221. .margin({ left: 12 })
  13222. Blank()
  13223. }
  13224. .layoutWeight(1)
  13225. Row() {
  13226. Text(`逐字歌词:`)
  13227. .fontSize(14)
  13228. .fontColor(Color.White)
  13229. .width(88)
  13230. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  13231. .selectedColor(this.themeColor)
  13232. .switchPointColor(Color.White)
  13233. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13234. .onChange((checked: boolean) => {
  13235. this.isEnableWordByWordLyric = checked;
  13236. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  13237. this.syncWordByWordLyricMode()
  13238. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13239. })
  13240. .width(50)
  13241. .height(30)
  13242. .alignSelf(ItemAlign.Start)
  13243. .margin({ left: 12 })
  13244. Blank()
  13245. }
  13246. .layoutWeight(1)
  13247. }
  13248. .width('100%')
  13249. .margin({
  13250. left: 20,
  13251. right: 15,
  13252. top: 10,
  13253. bottom: 10
  13254. })
  13255. }
  13256. if (!isPip) {
  13257. Row() {
  13258. Row() {
  13259. Text(`歌词发光:`)
  13260. .fontSize(14)
  13261. .fontColor(Color.White)
  13262. .width(88)
  13263. Toggle({ type: ToggleType.Switch, isOn: this.isLightText })
  13264. .selectedColor(this.themeColor)
  13265. .switchPointColor(Color.White)
  13266. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13267. .onChange((checked: boolean) => {
  13268. this.isLightText = checked;
  13269. PreferencesUtil.putSync(SettingPage.IS_LIGHT_TEXT, this.isLightText)
  13270. this.syncLyricLightTextMode()
  13271. })
  13272. .width(50)
  13273. .height(30)
  13274. .alignSelf(ItemAlign.Start)
  13275. .margin({ left: 12 })
  13276. Blank()
  13277. }
  13278. .layoutWeight(1)
  13279. Row() {
  13280. Text(`高亮居中:`)
  13281. .fontSize(14)
  13282. .fontColor(Color.White)
  13283. .width(88)
  13284. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  13285. .selectedColor(this.themeColor)
  13286. .switchPointColor(Color.White)
  13287. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13288. .onChange((checked: boolean) => {
  13289. this.isHightLightCenter = checked;
  13290. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  13291. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  13292. })
  13293. .width(50)
  13294. .height(30)
  13295. .alignSelf(ItemAlign.Start)
  13296. .margin({ left: 12 })
  13297. Blank()
  13298. }
  13299. .layoutWeight(1)
  13300. }
  13301. .width('100%')
  13302. .margin({
  13303. left: 20,
  13304. right: 15,
  13305. top: 10,
  13306. bottom: 10
  13307. })
  13308. }
  13309. Row() {
  13310. Text(`歌词居中:`)
  13311. .fontSize(14)
  13312. .fontColor(Color.White)
  13313. Row() {
  13314. ForEach(['居中', '居左'], (size: string, index: number) => {
  13315. Button(size)
  13316. .width(60)
  13317. .height(28)
  13318. .fontSize(12)
  13319. .fontColor('#FFFFFF')
  13320. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  13321. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  13322. .border({
  13323. color: (!isPip && this.currentLyricAlignMode === index) ||
  13324. (isPip && this.currentLyricAlignModePip === index) ?
  13325. '#007DFF' : '#DDDDDD',
  13326. width: 1.8
  13327. })
  13328. .onClick(() => {
  13329. this.setLyricAlignMode(index, isPip)
  13330. })
  13331. .margin({ left: 10, right: 8 })
  13332. })
  13333. }
  13334. .layoutWeight(1)
  13335. Blank()
  13336. }
  13337. .width('100%')
  13338. .margin({
  13339. top: 10,
  13340. bottom: 10,
  13341. right: 15,
  13342. left: 20
  13343. })
  13344. if (isPip) {
  13345. Row() {
  13346. Text(`悬浮背景:`)
  13347. .fontSize(14)
  13348. .fontColor(Color.White)
  13349. Select([
  13350. { value: CommonConstants.PIP_LYRIC_BG[0] },
  13351. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  13352. .font({ size: 13, weight: FontWeight.Medium })
  13353. .fontColor(Color.White)
  13354. .margin({ left: 10 })
  13355. .selected(this.pipBgIndex)
  13356. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  13357. .onSelect(async (_index: number, text?: string | undefined) => {
  13358. this.pipBgIndex = _index
  13359. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  13360. if (this.pipBgIndex === 0) {
  13361. if (this.cover) {
  13362. this.pipBg = this.cover
  13363. } else {
  13364. this.pipBg = this.imageColor
  13365. }
  13366. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13367. } else {
  13368. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  13369. }
  13370. })
  13371. Column() {
  13372. }
  13373. .backgroundColor(this.pipBg)
  13374. .margin({ left: 10, right: 10 })
  13375. .borderRadius(20)
  13376. .height(28)
  13377. .width(28)
  13378. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13379. Row() {
  13380. SymbolGlyph($r('sys.symbol.paintbrush'))
  13381. .fontColor([Color.White])
  13382. .effectStrategy(1)
  13383. Text(`选择颜色`)
  13384. .fontSize(13)
  13385. .margin({ left: 10 })
  13386. .fontColor(Color.White)
  13387. }
  13388. }
  13389. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  13390. .backgroundColor(Color.Transparent)
  13391. .border({
  13392. color: '#FFFFFF',
  13393. radius: 20,
  13394. width: 1.8
  13395. })
  13396. .height(36)
  13397. .width(110)
  13398. .onClick(() => {
  13399. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  13400. })
  13401. .bindPopup(this.isShowPipBgSelectColor, {
  13402. builder: this.SelectColor(false, isPip, true),
  13403. placement: Placement.Top,
  13404. mask: { color: '#33000000' },
  13405. enableArrow: false, //是否显示箭头
  13406. showInSubWindow: false,
  13407. onStateChange: (e) => {
  13408. if (!e.isVisible) {
  13409. this.isShowPipBgSelectColor = false
  13410. }
  13411. }
  13412. })
  13413. }
  13414. .width('100%')
  13415. .margin({ bottom: 5, right: 15, left: 20 })
  13416. }
  13417. Row() {
  13418. Text(`歌词颜色:`)
  13419. .fontSize(14)
  13420. .fontColor(Color.White)
  13421. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13422. .fontSize(15)
  13423. .fontColor(Color.White)
  13424. .margin({ left: 6, right: 6 })
  13425. Column() {
  13426. }
  13427. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13428. .margin({ right: 12 })
  13429. .borderRadius(20)
  13430. .height(28)
  13431. .width(28)
  13432. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13433. Row() {
  13434. SymbolGlyph($r('sys.symbol.paintbrush'))
  13435. .fontColor([Color.White])
  13436. .effectStrategy(1)
  13437. Text(`选择颜色`)
  13438. .fontSize(13)
  13439. .margin({ left: 10 })
  13440. .fontColor(Color.White)
  13441. }
  13442. }
  13443. .backgroundColor(Color.Transparent)
  13444. .border({
  13445. color: '#FFFFFF',
  13446. radius: 20,
  13447. width: 1.8
  13448. })
  13449. .height(36)
  13450. .width(110)
  13451. .onClick(() => {
  13452. this.isShowSelectColor = !this.isShowSelectColor
  13453. })
  13454. .bindPopup(this.isShowSelectColor, {
  13455. builder: this.SelectColor(false, isPip),
  13456. placement: Placement.Top,
  13457. mask: { color: '#33000000' },
  13458. enableArrow: false, //是否显示箭头
  13459. showInSubWindow: false,
  13460. onStateChange: (e) => {
  13461. if (!e.isVisible) {
  13462. this.isShowSelectColor = false
  13463. }
  13464. }
  13465. })
  13466. }
  13467. .width('100%')
  13468. .margin({
  13469. top: 10,
  13470. bottom: 10,
  13471. right: 15,
  13472. left: 20
  13473. })
  13474. Row() {
  13475. Text(`高亮颜色:`)
  13476. .fontSize(14)
  13477. .fontColor(Color.White)
  13478. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13479. .fontSize(15)
  13480. .fontColor(Color.White)
  13481. .margin({ left: 6, right: 6 })
  13482. Column() {
  13483. }
  13484. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13485. .margin({ right: 12 })
  13486. .borderRadius(20)
  13487. .height(28)
  13488. .width(28)
  13489. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13490. Row() {
  13491. SymbolGlyph($r('sys.symbol.paintbrush'))
  13492. .fontColor([Color.White])
  13493. .effectStrategy(1)
  13494. Text(`选择颜色`)
  13495. .fontSize(13)
  13496. .margin({ left: 10 })
  13497. .fontColor(Color.White)
  13498. }
  13499. }
  13500. .backgroundColor(Color.Transparent)
  13501. .border({
  13502. color: '#FFFFFF',
  13503. radius: 20,
  13504. width: 1.8
  13505. })
  13506. .height(36)
  13507. .width(110)
  13508. .onClick(() => {
  13509. this.isShowHLSelectColor = !this.isShowHLSelectColor
  13510. })
  13511. .bindPopup(this.isShowHLSelectColor, {
  13512. builder: this.SelectColor(true, isPip),
  13513. placement: Placement.Top,
  13514. mask: { color: '#33000000' },
  13515. enableArrow: false, //是否显示箭头
  13516. showInSubWindow: false,
  13517. onStateChange: (e) => {
  13518. if (!e.isVisible) {
  13519. this.isShowHLSelectColor = false
  13520. }
  13521. }
  13522. })
  13523. }
  13524. .width('100%')
  13525. .margin({
  13526. top: 10,
  13527. bottom: 10,
  13528. right: 15,
  13529. left: 20
  13530. })
  13531. if (isPip) {
  13532. Row() {
  13533. Text(`显示宽度:`)
  13534. .fontSize(14)
  13535. .fontColor(Color.White)
  13536. Slider({
  13537. value: this.pipLyWidth,
  13538. min: 10,
  13539. max: 800,
  13540. step: 1,
  13541. style: SliderStyle.OutSet
  13542. })
  13543. .blockColor(this.themeColor)
  13544. .trackColor($r('app.color.speed_text_color'))
  13545. .selectedColor(Color.White)
  13546. .trackThickness(6)
  13547. .onChange((value: number) => {
  13548. this.pipLyWidth = value
  13549. if (this.pipController) {
  13550. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13551. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  13552. }
  13553. })
  13554. .layoutWeight(1)
  13555. }
  13556. .justifyContent(FlexAlign.Start)
  13557. .margin({
  13558. left: 20,
  13559. right: 15,
  13560. top: 5,
  13561. bottom: 5
  13562. })
  13563. Row() {
  13564. Text(`显示高度:`)
  13565. .fontSize(14)
  13566. .fontColor(Color.White)
  13567. Slider({
  13568. value: this.pipLyHeight,
  13569. min: 10,
  13570. max: 1000,
  13571. step: 1,
  13572. style: SliderStyle.OutSet
  13573. })
  13574. .blockColor(this.themeColor)
  13575. .trackColor($r('app.color.speed_text_color'))
  13576. .selectedColor(Color.White)
  13577. .trackThickness(6)
  13578. .onChange((value: number) => {
  13579. this.pipLyHeight = value
  13580. if (this.pipController) {
  13581. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13582. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  13583. }
  13584. })
  13585. .layoutWeight(1)
  13586. }
  13587. .justifyContent(FlexAlign.Start)
  13588. .margin({
  13589. left: 20,
  13590. right: 15,
  13591. top: 5,
  13592. bottom: 5
  13593. })
  13594. }
  13595. Row() {
  13596. Text(`歌词字号:`)
  13597. .fontSize(14)
  13598. .fontColor(Color.White)
  13599. Slider({
  13600. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  13601. min: 12,
  13602. max: 30,
  13603. step: 0.1,
  13604. style: SliderStyle.OutSet
  13605. })
  13606. .blockColor(this.themeColor)
  13607. .trackColor($r('app.color.speed_text_color'))
  13608. .selectedColor(Color.White)
  13609. .trackThickness(6)
  13610. .onChange((value: number) => {
  13611. this.setLyricTextSize(value, isPip)
  13612. })
  13613. .layoutWeight(1)
  13614. .margin({ right: 3 })
  13615. Text(this.getLyricSizeDisplayValue(isPip))
  13616. .fontSize(13)
  13617. .fontColor(Color.White)
  13618. .textAlign(TextAlign.Start)
  13619. }
  13620. .width('100%')
  13621. .margin({
  13622. left: 20,
  13623. right: 15,
  13624. top: 5,
  13625. bottom: 5
  13626. })
  13627. Row() {
  13628. Text(`高亮倍数:`)
  13629. .fontSize(14)
  13630. .fontColor(Color.White)
  13631. Slider({
  13632. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  13633. min: 1,
  13634. max: 2,
  13635. step: 0.1,
  13636. style: SliderStyle.OutSet
  13637. })
  13638. .blockColor(this.themeColor)
  13639. .trackColor($r('app.color.speed_text_color'))
  13640. .selectedColor(Color.White)
  13641. .trackThickness(6)
  13642. .onChange((value: number) => {
  13643. this.setHighLyricTextSize(value, isPip)
  13644. })
  13645. .layoutWeight(1)
  13646. .margin({ right: 3 })
  13647. Text(this.getHighLyricSizeDisplayValue(isPip))
  13648. .fontSize(13)
  13649. .fontColor(Color.White)
  13650. .textAlign(TextAlign.Start)
  13651. }
  13652. .width('100%')
  13653. .margin({
  13654. left: 20,
  13655. right: 15,
  13656. top: 5,
  13657. bottom: 5
  13658. })
  13659. Row() {
  13660. Text(`歌词间隙:`)
  13661. .fontSize(14)
  13662. .fontColor(Color.White)
  13663. Slider({
  13664. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  13665. min: 0,
  13666. max: 100,
  13667. step: 1,
  13668. style: SliderStyle.OutSet
  13669. })
  13670. .blockColor(this.themeColor)
  13671. .trackColor($r('app.color.speed_text_color'))
  13672. .selectedColor(Color.White)
  13673. .trackThickness(6)
  13674. .onChange((value: number) => {
  13675. this.setLyricLineSpace(value, isPip)
  13676. })
  13677. .layoutWeight(1)
  13678. .margin({ right: 3 })
  13679. Text(this.getLyricLineSpaceDisplayValue(isPip))
  13680. .fontSize(13)
  13681. .fontColor(Color.White)
  13682. .textAlign(TextAlign.Start)
  13683. }
  13684. .width('100%')
  13685. .margin({
  13686. left: 20,
  13687. right: 15,
  13688. top: 5,
  13689. bottom: 5
  13690. })
  13691. //取值间隔为100,默认为400,取值越大,字体越粗
  13692. Row() {
  13693. Text(`歌词字重:`)
  13694. .fontSize(14)
  13695. .fontColor(Color.White)
  13696. Slider({
  13697. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  13698. min: 100,
  13699. max: 900,
  13700. step: 100,
  13701. style: SliderStyle.OutSet
  13702. })
  13703. .blockColor(this.themeColor)
  13704. .trackColor($r('app.color.speed_text_color'))
  13705. .selectedColor(Color.White)
  13706. .trackThickness(6)
  13707. .onChange((value: number) => {
  13708. if (isPip) {
  13709. this.lyricTextWeightPip = value
  13710. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  13711. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  13712. } else {
  13713. this.lyricTextWeight = value
  13714. this.lyricController.setTextWeight(this.lyricTextWeight)
  13715. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  13716. }
  13717. })
  13718. .layoutWeight(1)
  13719. .margin({ right: 3 })
  13720. Text(this.getLyricTextWeightDisplayValue(isPip))
  13721. .fontSize(13)
  13722. .fontColor(Color.White)
  13723. .textAlign(TextAlign.Start)
  13724. }
  13725. .width('100%')
  13726. .margin({
  13727. left: 20,
  13728. right: 15,
  13729. top: 5,
  13730. bottom: 5
  13731. })
  13732. Row() {
  13733. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  13734. this.pushLyricButton($r('app.media.share2'), 2, '分享歌词')
  13735. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  13736. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  13737. }
  13738. .justifyContent(FlexAlign.Center)
  13739. .margin({ top: 3, bottom: 10 })
  13740. }
  13741. .width('88%')
  13742. }
  13743. private getLyricSizeDisplayValue(isPip: boolean): string {
  13744. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  13745. return lyricSize.toFixed(1);
  13746. }
  13747. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  13748. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  13749. return highLyricSize.toFixed(1);
  13750. }
  13751. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  13752. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  13753. return Math.round(lyricLineSpace).toString();
  13754. }
  13755. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  13756. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  13757. return Math.round(lyricTextWeightValue).toString();
  13758. }
  13759. private setBlurDegree(index: number, isPip: boolean) {
  13760. if (isPip) {
  13761. this.blurDegreePip = index
  13762. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  13763. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  13764. } else {
  13765. this.blurDegree = index
  13766. this.lyricController.setBlurDegree(this.blurDegree)
  13767. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  13768. }
  13769. }
  13770. private setLyricAlignMode(index: number, isPip: boolean) {
  13771. if (isPip) {
  13772. this.currentLyricAlignModePip = index
  13773. if (this.currentLyricAlignModePip === 1) {
  13774. this.lyricControllerXF.setAlignMode("left")
  13775. } else {
  13776. this.lyricControllerXF.setAlignMode("center")
  13777. }
  13778. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  13779. } else {
  13780. this.currentLyricAlignMode = index
  13781. if (this.currentLyricAlignMode === 1) {
  13782. this.lyricController.setAlignMode("left")
  13783. } else {
  13784. this.lyricController.setAlignMode("center")
  13785. }
  13786. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  13787. }
  13788. }
  13789. private setLyricTextSize(index: number, isPip: boolean) {
  13790. if (isPip) {
  13791. this.currentLyricSizePip = index
  13792. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  13793. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  13794. } else {
  13795. this.currentLyricSize = index
  13796. this.lyricController.setTextSize(this.currentLyricSize)
  13797. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  13798. }
  13799. }
  13800. private setHighLyricTextSize(scale: number, isPip: boolean) {
  13801. if (isPip) {
  13802. this.currentHightLyricSizePip = scale
  13803. this.lyricControllerXF
  13804. .setHighlightScale(this.currentHightLyricSizePip)
  13805. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  13806. } else {
  13807. this.currentHightLyricSize = scale
  13808. this.lyricController
  13809. .setHighlightScale(this.currentHightLyricSize)
  13810. PreferencesUtil.putSync('HighLyricTextSize', scale)
  13811. }
  13812. }
  13813. private setLyricLineSpace(index: number, isPip: boolean) {
  13814. if (isPip) {
  13815. this.currentLyricLineSpacePip = index
  13816. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  13817. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  13818. } else {
  13819. this.currentLyricLineSpace = index
  13820. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  13821. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  13822. }
  13823. }
  13824. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  13825. LogUtil.info('onecold isBG = ' + isBG)
  13826. if (isBG) { //如果是设置悬浮背景
  13827. this.pipBg = color
  13828. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  13829. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13830. return
  13831. }
  13832. if (isPip) {
  13833. this.currentLyricColorPip = color
  13834. this.lyricControllerXF
  13835. .setTextColor(this.currentLyricColorPip)
  13836. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  13837. } else {
  13838. this.currentLyricColor = color
  13839. this.lyricController
  13840. .setTextColor(this.currentLyricColor)
  13841. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  13842. }
  13843. }
  13844. private changeLyricHightLightColor(color: string, isPip: boolean) {
  13845. if (isPip) {
  13846. this.currentHighLightLyricColorPip = color
  13847. this.lyricControllerXF
  13848. .setHighlightColor(this.currentHighLightLyricColorPip)
  13849. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  13850. } else {
  13851. this.currentHighLightLyricColor = color
  13852. this.lyricController
  13853. .setHighlightColor(this.currentHighLightLyricColor)
  13854. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  13855. }
  13856. }
  13857. // 构建时间控制器
  13858. @Builder
  13859. BuildTimeControls() {
  13860. Column() {
  13861. // 时间显示
  13862. Text(this.getTimeText())
  13863. .fontSize(18)
  13864. .fontColor(Color.White)
  13865. .margin({ bottom: 10 })
  13866. Row() {
  13867. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  13868. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  13869. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  13870. }
  13871. .justifyContent(FlexAlign.Center)
  13872. }
  13873. .margin({ top: 12, bottom: 8 })
  13874. }
  13875. // 精度按钮组件
  13876. @Builder
  13877. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  13878. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13879. Column() {
  13880. Image(icon)
  13881. .width(28)
  13882. .margin({ bottom: 5 })
  13883. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  13884. Text(label)
  13885. .fontSize(12)
  13886. .fontColor('#FFFFFF')
  13887. }
  13888. }
  13889. .backgroundColor(Color.Transparent)
  13890. .enabled(!this.isButtonDisabled(step))
  13891. .onClick(() => this.handlePrecisionAdjust(step))
  13892. .padding(5)
  13893. .width(66)
  13894. .height(66)
  13895. .margin({ left: 18, right: 18 })
  13896. .border({
  13897. color: '#FFFFFF',
  13898. width: 1.8
  13899. })
  13900. }
  13901. private handlePrecisionAdjust(step: number) {
  13902. if (step === 0) {
  13903. this.timeOffset = 0
  13904. this.saveLyricTimeOffset()
  13905. return
  13906. }
  13907. // 精度处理:保留1位小数
  13908. const newOffset = Number((this.timeOffset + step).toFixed(5))
  13909. // 边界保护(±15.0秒)
  13910. if (newOffset < -30.0 || newOffset > 30.0) {
  13911. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  13912. return
  13913. }
  13914. // 状态更新
  13915. this.timeOffset = newOffset
  13916. // 保存歌词时间偏移
  13917. this.saveLyricTimeOffset()
  13918. }
  13919. // 按钮禁用逻辑
  13920. private isButtonDisabled(step: number): boolean {
  13921. const futureOffset = this.timeOffset + step
  13922. return (futureOffset < -30.0) || (futureOffset > 30.0)
  13923. }
  13924. // 时间显示文本升级
  13925. private getTimeText(): string {
  13926. const absValue = Math.abs(this.timeOffset)
  13927. return this.timeOffset === 0
  13928. ? '歌词时间已重置'
  13929. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  13930. }
  13931. /**
  13932. * 获取当前歌曲的唯一标识key
  13933. * 使用歌曲的filePath作为唯一标识
  13934. */
  13935. private getLyricOffsetKey(): string {
  13936. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  13937. // 使用MD5对filePath进行加密,作为存储key
  13938. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  13939. }
  13940. return ''
  13941. }
  13942. /**
  13943. * 保存当前歌曲的歌词时间偏移
  13944. */
  13945. private saveLyricTimeOffset(): void {
  13946. try {
  13947. const key = this.getLyricOffsetKey()
  13948. if (StrUtil.isEmpty(key)) {
  13949. console.warn('heanup saveLyricTimeOffset: key is empty')
  13950. return
  13951. }
  13952. PreferencesUtil.putSync(key, this.timeOffset)
  13953. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  13954. } catch (e) {
  13955. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  13956. }
  13957. }
  13958. /**
  13959. * 加载当前歌曲的歌词时间偏移
  13960. */
  13961. private loadLyricTimeOffset(): void {
  13962. try {
  13963. const key = this.getLyricOffsetKey()
  13964. if (StrUtil.isEmpty(key)) {
  13965. console.warn('heanup loadLyricTimeOffset: key is empty')
  13966. return
  13967. }
  13968. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  13969. if (savedOffset !== 0) {
  13970. this.timeOffset = savedOffset
  13971. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  13972. }else{
  13973. this.timeOffset = 0
  13974. }
  13975. } catch (e) {
  13976. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  13977. }
  13978. }
  13979. // 导入 本地歌词 搜索歌词
  13980. @Builder
  13981. pushLyricButton(icon: Resource, step: number, label: string) {
  13982. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13983. Row() {
  13984. Image(icon)
  13985. .width(14)
  13986. .margin({ left: 13 })
  13987. Text(label)
  13988. .fontSize(12)
  13989. .margin({ left: 6 })
  13990. .fontColor('#FFFFFF')
  13991. }
  13992. }
  13993. .onClick(() => {
  13994. switch (step) {
  13995. case 0:
  13996. this.callFilePickerSelectFileForLyric()
  13997. break;
  13998. case 1:
  13999. //判断有没有设置api
  14000. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  14001. this.isLyricSetting = false
  14002. this.showTipsDialog()
  14003. return
  14004. }
  14005. if (StrUtil.isNotEmpty(this.videoUrl)) {
  14006. ToastUtil.showToast('正在获取')
  14007. this.isLyricSetting = false
  14008. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  14009. this.initLyric(lyricPath, true);
  14010. }
  14011. break;
  14012. case 2:
  14013. this.isLyricSetting = false
  14014. this.openLyricCopySheet()
  14015. break;
  14016. }
  14017. })
  14018. .padding(5)
  14019. .layoutWeight(1)
  14020. .backgroundColor(Color.Transparent)
  14021. .height(40)
  14022. .margin({ left: 4, right: 4 })
  14023. .border({
  14024. color: '#FFFFFF',
  14025. radius: 20,
  14026. width: 1.8
  14027. })
  14028. }
  14029. showVipDialog() {
  14030. DialogHelper.showCustomContentDialog({
  14031. dialogId: 'vip',
  14032. title: "友情提示",
  14033. autoCancel: false, //点击遮障层时,不关闭弹窗
  14034. backCancel: true, //点击返回键,不关闭弹窗
  14035. contentBuilder: () => {
  14036. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  14037. },
  14038. buttons: [],
  14039. })
  14040. }
  14041. //去赞助的自定义内容
  14042. @Builder
  14043. customVipBuilder(content: string) {
  14044. Column() {
  14045. Text(content)
  14046. .fontColor(Color.Gray)
  14047. .fontSize(16)
  14048. .alignSelf(ItemAlign.Start)
  14049. .margin({ bottom: 15 })
  14050. .fontSize(16)
  14051. Row() {
  14052. Button('取消')
  14053. .fontColor(Color.White)
  14054. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14055. .height(50)
  14056. .layoutWeight(1)
  14057. .stateEffect(true)
  14058. .margin({ right: 6 })
  14059. .onClick(() => {
  14060. DialogHelper.closeDialog('vip'); //关闭弹框
  14061. })
  14062. Button('开通')
  14063. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14064. .layoutWeight(1)
  14065. .height(50)
  14066. .backgroundColor(this.themeColor)
  14067. .stateEffect(true)
  14068. .margin({ left: 6 })
  14069. .onClick(() => {
  14070. DialogHelper.closeDialog('vip'); //关闭弹框
  14071. this.isShowPlay = false
  14072. this.mType = 1 //跳转到用户中心
  14073. // router.pushUrl({
  14074. // url: 'pages/VipPage'
  14075. // }, router.RouterMode.Single);
  14076. })
  14077. }
  14078. }
  14079. .width("100%")
  14080. .padding(10)
  14081. }
  14082. showTipsDialog() {
  14083. DialogHelper.showCustomContentDialog({
  14084. dialogId: 'tips',
  14085. title: "友情提示",
  14086. autoCancel: false, //点击遮障层时,不关闭弹窗
  14087. backCancel: true, //点击返回键,不关闭弹窗
  14088. contentBuilder: () => {
  14089. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  14090. },
  14091. buttons: [],
  14092. })
  14093. }
  14094. @Builder
  14095. customTipsBuilder(content: string) {
  14096. Column() {
  14097. Text(content)
  14098. .fontColor(Color.Gray)
  14099. .fontSize(16)
  14100. .alignSelf(ItemAlign.Start)
  14101. .margin({ bottom: 15 })
  14102. .fontSize(16)
  14103. Row() {
  14104. Button('取消')
  14105. .fontColor(Color.White)
  14106. .backgroundColor(this.themeColor)
  14107. .height(50)
  14108. .layoutWeight(1)
  14109. .stateEffect(true)
  14110. .margin({ right: 6 })
  14111. .onClick(() => {
  14112. DialogHelper.closeDialog('tips'); //关闭弹框
  14113. })
  14114. Button('跳转')
  14115. .fontColor(Color.White)//
  14116. .layoutWeight(1)
  14117. .height(50)
  14118. .backgroundColor(this.themeColor)
  14119. .stateEffect(true)
  14120. .margin({ left: 6 })
  14121. .onClick(() => {
  14122. DialogHelper.closeDialog('tips'); //关闭弹框
  14123. this.isShowEdit = false
  14124. this.longItemFilePath = ''
  14125. // if(this.isGridMusic&&!this.isShowPlay){
  14126. // this.longItemFilePath== ''
  14127. // }else{
  14128. // this.isShowEdit = false
  14129. // }
  14130. this.isShowMoreView = false;
  14131. this.isShowPlay = false
  14132. this.mType = 4
  14133. // router.pushUrl({
  14134. // url: 'pages/SettingPage'
  14135. // }, router.RouterMode.Single);
  14136. })
  14137. }
  14138. }
  14139. .width("100%")
  14140. .padding(10)
  14141. }
  14142. @Builder
  14143. PlayMoreSheet() {
  14144. Column() {
  14145. this.MoreList()
  14146. }
  14147. .width('100%')
  14148. .height('100%')
  14149. }
  14150. @Builder
  14151. MoreList() {
  14152. Scroll() {
  14153. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  14154. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  14155. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14156. Row() {
  14157. if (more.id === 3&&this.currentSong) {
  14158. Image(more.image)
  14159. .width(24)
  14160. .height(24)
  14161. .margin({ left: 10, right: 10 })
  14162. Text(more.title)
  14163. .fontSize(16)
  14164. .fontColor(Color.White)
  14165. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  14166. height: '99%',
  14167. dragBar: true,
  14168. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14169. showClose: true,
  14170. blurStyle: BlurStyle.Thin,
  14171. backgroundColor: Color.Transparent,
  14172. title: { title: '歌曲信息' }
  14173. })
  14174. } else if (more.id === 15 && this.currentSong) { //编辑标签
  14175. Image(more.image)
  14176. .width(24)
  14177. .height(24)
  14178. .margin({ left: 10, right: 10 })
  14179. Text(more.title)
  14180. .fontSize(16)
  14181. .fontColor(Color.White)
  14182. } else if (more.id === 5) { //定时关闭
  14183. Image(more.image)
  14184. .width(24)
  14185. .height(24)
  14186. .margin({ left: 10, right: 10 })
  14187. Text(more.title)
  14188. .fontSize(16)
  14189. .fontColor(Color.White)
  14190. .onClick(() => {
  14191. this.doMore(more.id)
  14192. })
  14193. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  14194. height: this.isCoverOpacity() ? '95%' : '95%',
  14195. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14196. dragBar: true,
  14197. showClose: true,
  14198. title: { title: $r('app.string.time_close') }
  14199. })
  14200. } else if (more.id === 2) { //歌词设置
  14201. Image(more.image)
  14202. .width(24)
  14203. .height(24)
  14204. .margin({ left: 10, right: 10 })
  14205. Text(more.title)
  14206. .fontSize(16)
  14207. .fontColor(Color.White)
  14208. } else if (more.id === 16) { //悬浮歌词设置
  14209. Image(more.image)
  14210. .width(24)
  14211. .height(24)
  14212. .margin({ left: 10, right: 10 })
  14213. Text(more.title)
  14214. .fontSize(16)
  14215. .fontColor(Color.White)
  14216. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  14217. height: '99%',
  14218. dragBar: true,
  14219. preferType: SheetType.CENTER,
  14220. showClose: true,
  14221. blurStyle: BlurStyle.Thin,
  14222. backgroundColor: Color.Transparent,
  14223. title: { title: '悬浮歌词' }
  14224. })
  14225. } else if (more.id === 11) {
  14226. Image(more.image)
  14227. .width(24)
  14228. .height(24)
  14229. .margin({ left: 10, right: 10 })
  14230. Text(more.title)
  14231. .fontSize(16)
  14232. .fontColor(Color.White)
  14233. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  14234. height: this.isCoverOpacity() ? '95%' : '60%',
  14235. dragBar: true,
  14236. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14237. showClose: true,
  14238. blurStyle: BlurStyle.Thin,
  14239. backgroundColor: Color.Transparent,
  14240. title: { title: '跳过头尾' }
  14241. })
  14242. } else if (more.id === 12) { //投播
  14243. AVCastPicker({
  14244. customPicker: (): void => this.TPImageBuilder(more),
  14245. onStateChange: (state) => {
  14246. if (state == AVCastPickerState.STATE_APPEARING) {
  14247. console.log(' The picker starts showing.');
  14248. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14249. console.log(' The picker finishes presenting.');
  14250. }
  14251. },
  14252. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  14253. sessionType: 'video'
  14254. })
  14255. .id('AVCastPicker')
  14256. } else {
  14257. if(more.id >= 22){
  14258. SymbolGlyph(more.image)
  14259. .fontSize(24)
  14260. .fontColor([Color.White])
  14261. .alignSelf(ItemAlign.Center)
  14262. .margin({ left: 10, right: 10,bottom:5})
  14263. // .padding({bottom:4})
  14264. .onClick(() => {
  14265. this.doMore(more.id)
  14266. })
  14267. }else{
  14268. Image(more.image)
  14269. .width(24)
  14270. .height(24)
  14271. .fillColor(Color.White)
  14272. .margin({ left: 10, right: 10 })
  14273. .onClick(() => {
  14274. this.doMore(more.id)
  14275. })
  14276. }
  14277. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  14278. .fontSize(16)
  14279. .margin({top:more.id >= 22?3:0})
  14280. .fontColor(Color.White)
  14281. .onClick(() => {
  14282. this.doMore(more.id)
  14283. })
  14284. Select([//倍速
  14285. { value: '0.25x' },
  14286. { value: '0.5x' },
  14287. { value: '0.75x' },
  14288. { value: '1x' },
  14289. { value: '1.25x' },
  14290. { value: '1.5x' },
  14291. { value: '1.75x' },
  14292. { value: '2x' },
  14293. { value: '3x' }])
  14294. .font({ size: 16, weight: FontWeight.Medium })
  14295. .fontColor($r('sys.color.white'))
  14296. .margin({ left: 25 })
  14297. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  14298. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  14299. .value(Utility.optimizedFormat(this.playSpeed))
  14300. .onSelect(async (_index: number, text?: string | undefined) => {
  14301. let speed = parseFloat(text?.replace('x', '') || '1');
  14302. if (!CommonConstants.video_speed_list.includes(speed)) {
  14303. speed = 1;
  14304. }
  14305. this.playSpeed = speed
  14306. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14307. })
  14308. Slider({
  14309. value: this.volume,
  14310. min: 0,
  14311. max: 1,
  14312. step: 0.1,
  14313. style: SliderStyle.OutSet
  14314. })
  14315. .margin({ left: 18, right: 8 })
  14316. .blockColor(this.themeColor)
  14317. .trackColor($r('app.color.speed_text_color'))
  14318. .selectedColor(Color.White)
  14319. .trackThickness(9)
  14320. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14321. .onChange((value: number) => {
  14322. this.volume = value;
  14323. this.applyCurrentVolume();
  14324. PreferencesUtil.putSync('DefalutVolume',this.volume)
  14325. })
  14326. .layoutWeight(1)
  14327. Slider({
  14328. value: this.volumeBoostPercent,
  14329. min: 0,
  14330. max: this.volumeBoostMaxPercent,
  14331. step: 1,
  14332. style: SliderStyle.OutSet
  14333. })
  14334. .margin({ left: 18, right: 8 })
  14335. .blockColor(this.themeColor)
  14336. .trackColor($r('app.color.speed_text_color'))
  14337. .selectedColor(Color.White)
  14338. .trackThickness(9)
  14339. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14340. .onChange((value: number) => {
  14341. this.volumeBoostPercent = Math.round(value);
  14342. this.applyCurrentVolume();
  14343. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  14344. })
  14345. .layoutWeight(1)
  14346. Text(`${Math.round(this.volumeBoostPercent)}%`)
  14347. .fontSize(13)
  14348. .fontColor(Color.White)
  14349. .margin({ left: 8, right: 8 })
  14350. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14351. Text(`${Math.round(this.volume*100)}%`)
  14352. .fontSize(13)
  14353. .fontColor(Color.White)
  14354. .margin({ left: 8, right: 8 })
  14355. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14356. Blank()
  14357. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  14358. .selectedColor(this.themeColor)
  14359. .switchPointColor(Color.White)
  14360. .margin({ right: 15 })
  14361. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14362. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  14363. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14364. if (more.id == 6) {
  14365. this.isMusicMemoryPlay = checked;
  14366. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  14367. if (this.isMusicMemoryPlay) {
  14368. ToastUtil.showToast('记忆播放已开启')
  14369. } else {
  14370. ToastUtil.showToast('记忆播放已关闭')
  14371. }
  14372. }
  14373. })
  14374. .width(48)
  14375. .height(24);
  14376. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  14377. .selectedColor(this.themeColor)
  14378. .switchPointColor(Color.White)
  14379. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14380. .margin({ right: 15 })
  14381. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  14382. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14383. if (more.id == 7) {
  14384. this.isMusicBGCover = checked;
  14385. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  14386. if (this.isMusicBGCover) {
  14387. ToastUtil.showToast('播放背景随音乐封面已开启')
  14388. } else {
  14389. ToastUtil.showToast('播放背景随音乐封面已关闭')
  14390. }
  14391. }
  14392. })
  14393. .width(48)
  14394. .height(24);
  14395. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  14396. .selectedColor(this.themeColor)
  14397. .switchPointColor(Color.White)
  14398. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14399. .margin({ right: 15 })
  14400. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  14401. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14402. if (more.id == 8) {
  14403. this.isSavePlayMode = checked;
  14404. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  14405. if (this.isSavePlayMode) {
  14406. ToastUtil.showToast('保存播放模式已开启')
  14407. } else {
  14408. ToastUtil.showToast('保存播放模式已关闭')
  14409. }
  14410. }
  14411. })
  14412. .width(48)
  14413. .height(24);
  14414. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  14415. .selectedColor(this.themeColor)
  14416. .switchPointColor(Color.White)
  14417. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14418. .margin({ right: 15 })
  14419. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  14420. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14421. if (more.id == 13) {
  14422. this.isCoverRectangle = checked;
  14423. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  14424. if (this.isCoverRectangle) {
  14425. ToastUtil.showToast('封面方形已开启,双指缩放封面可以调整封面大小')
  14426. this.animationRoFun()
  14427. } else {
  14428. ToastUtil.showToast('封面圆形已开启,双指缩放封面可以调整封面大小')
  14429. this.animationRoFun()
  14430. }
  14431. }
  14432. })
  14433. .width(48)
  14434. .height(24);
  14435. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  14436. .selectedColor(this.themeColor)
  14437. .switchPointColor(Color.White)
  14438. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14439. .margin({ right: 15 })
  14440. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  14441. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14442. if (more.id == 25) {
  14443. this.isShowSpectrum = checked;
  14444. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  14445. }
  14446. })
  14447. .width(48)
  14448. .height(24);
  14449. // 频谱特效类型选择器
  14450. Select([
  14451. { value: '柱状' },
  14452. { value: '波形' },
  14453. { value: '水波纹' },
  14454. { value: '圆形' },
  14455. { value: '粒子' },
  14456. { value: '脉冲' },
  14457. { value: '镜像柱' },
  14458. { value: '影子柱' },
  14459. { value: '轨道线' },
  14460. { value: '点阵' },
  14461. { value: '星爆' },
  14462. { value: '心电图' },
  14463. { value: '特效' }
  14464. ])
  14465. .font({ size: 14, weight: FontWeight.Medium })
  14466. .fontColor(Color.White)
  14467. .margin({ left: 25 })
  14468. .margin({top:more.id >= 22?3:0})
  14469. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  14470. .selected(this.spectrumModeIndex)
  14471. .value(['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'][this.spectrumModeIndex])
  14472. .onSelect((index: number, _text?: string) => {
  14473. this.spectrumModeIndex = index;
  14474. // 使用同步方法保存,确保立即生效
  14475. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  14476. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  14477. const modeNames = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  14478. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  14479. });
  14480. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  14481. .selectedColor(this.themeColor)
  14482. .switchPointColor(Color.White)
  14483. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14484. .margin({ right: 15 })
  14485. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  14486. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14487. if (more.id == 22) {
  14488. this.showSimple = checked;
  14489. PreferencesUtil.put('showSimple', this.showSimple)
  14490. }
  14491. })
  14492. .width(48)
  14493. .height(24);
  14494. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  14495. .selectedColor(this.themeColor)
  14496. .switchPointColor(Color.White)
  14497. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14498. .margin({ right: 15 })
  14499. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  14500. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14501. if (more.id == 23) {
  14502. this.enablePointLight = checked;
  14503. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  14504. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  14505. }
  14506. })
  14507. .width(48)
  14508. .height(24);
  14509. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  14510. .selectedColor(this.themeColor)
  14511. .switchPointColor(Color.White)
  14512. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14513. .margin({ right: 15 })
  14514. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  14515. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14516. if (more.id == 27) {
  14517. this.isGeKongPlayNext = checked;
  14518. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  14519. }
  14520. })
  14521. .width(48)
  14522. .height(24);
  14523. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  14524. .selectedColor(this.themeColor)
  14525. .switchPointColor(Color.White)
  14526. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14527. .margin({ right: 15 })
  14528. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  14529. .onChange((checked: boolean) => { // 是否开启背景流光效果
  14530. if (more.id == 21) {
  14531. this.isShowBgLiuGUANG = checked;
  14532. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  14533. }
  14534. })
  14535. .width(48)
  14536. .height(24);
  14537. }
  14538. }
  14539. .width('100%')
  14540. .height(45)
  14541. .padding(15)
  14542. .backgroundColor(Color.Transparent)
  14543. .borderRadius(12)
  14544. .margin({ bottom: 6 })
  14545. }
  14546. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  14547. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  14548. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  14549. .backgroundColor(Color.Transparent)
  14550. .onClick(() => {
  14551. this.doMore(more.id)
  14552. })
  14553. });
  14554. }
  14555. .width('100%')
  14556. .padding(16)
  14557. }.margin({ bottom: 18 })
  14558. }
  14559. @Builder
  14560. TPImageBuilder(more: MoreItem): void {
  14561. Row() {
  14562. Image($r('app.media.tuoping'))
  14563. .width(22)
  14564. .height(22)
  14565. .margin({ left: 10, right: 10 })
  14566. Text(more.title)
  14567. .fontSize(16)
  14568. .fontColor(Color.White)
  14569. }
  14570. .width('100%')
  14571. .layoutWeight(1)
  14572. .alignItems(VerticalAlign.Center)
  14573. .justifyContent(FlexAlign.Start)
  14574. }
  14575. private moreItems: MoreItem[] = [
  14576. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  14577. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  14578. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  14579. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  14580. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  14581. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  14582. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  14583. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  14584. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  14585. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  14586. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  14587. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  14588. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  14589. { id: 4, image: $r('app.media.share2'), title: '分享' },
  14590. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  14591. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  14592. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  14593. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  14594. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  14595. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  14596. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  14597. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  14598. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  14599. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  14600. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  14601. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  14602. ];
  14603. @State isShowBgLiuGUANG: boolean = false;
  14604. @State isShowMoreView: boolean = false;
  14605. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  14606. @State isShowTimeCloseMore: boolean = false
  14607. @State isShowDetailMore: boolean = false
  14608. @State isMusicBGCover: boolean = true
  14609. @State isSavePlayMode: boolean = true
  14610. @State isLyricSetting: boolean = false
  14611. @State isJumpSetting: boolean = false
  14612. @State isShowEdit: boolean = false
  14613. @State showPipLyric: boolean = false
  14614. @State isShowSpectrum: boolean = false//是否显示频谱
  14615. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  14616. private getSafeBoostPercent(): number {
  14617. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  14618. if (rawBoostPercent <= 150) {
  14619. return rawBoostPercent;
  14620. }
  14621. if (rawBoostPercent <= 300) {
  14622. return 150 + (rawBoostPercent - 150) * 0.45;
  14623. }
  14624. return 217.5 + (rawBoostPercent - 300) * 0.15;
  14625. }
  14626. private getVolumeBoostFactor(): number {
  14627. return 1 + this.getSafeBoostPercent() / 100;
  14628. }
  14629. private getCurrentOutputVolume(): number {
  14630. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  14631. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  14632. const maxOutputVolume = this.getVolumeBoostFactor();
  14633. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  14634. }
  14635. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  14636. if (!this.mIjkMediaPlayer) {
  14637. return;
  14638. }
  14639. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  14640. this.mIjkMediaPlayer.setVolume('1', '1');
  14641. return;
  14642. }
  14643. const outputVolume = this.getCurrentOutputVolume();
  14644. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  14645. }
  14646. async setRingTone() {
  14647. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  14648. return
  14649. }
  14650. // 确定后的逻辑
  14651. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  14652. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  14653. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  14654. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  14655. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  14656. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  14657. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  14658. , this.videoUrl, this.name).then(res => {
  14659. LogUtil.info('onecold setFlag :' + res);
  14660. });
  14661. }
  14662. doMore(moreId: number) {
  14663. switch (moreId) {
  14664. case 30: //歌词
  14665. this.isLyricSetting = !this.isLyricSetting;
  14666. this.isShowMoreView = false
  14667. break;
  14668. case 3: //详情
  14669. this.isShowDetailMore = !this.isShowDetailMore;
  14670. break;
  14671. case 4: //分享
  14672. if (this.currentSong !== undefined) {
  14673. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  14674. }
  14675. this.isShowMoreView = false
  14676. break;
  14677. case 5: //定时关闭
  14678. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  14679. break;
  14680. case 10: //设为铃声
  14681. this.setRingTone()
  14682. this.isShowMoreView = false
  14683. break;
  14684. case 11: //跳过头尾
  14685. this.isJumpSetting = !this.isJumpSetting;
  14686. break;
  14687. case 13: //倍速
  14688. break;
  14689. case 14: //搜索封面
  14690. if (this.currentSong !== undefined) {
  14691. this.doSearchCover(this.currentSong)
  14692. }
  14693. this.isShowMoreView = false
  14694. break;
  14695. case 15: //编辑标签
  14696. this.initEditFields(this.currentSong)
  14697. this.tempLyricContent = this.lyricContent
  14698. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  14699. this.lyricConStr = this.tempLyricContent
  14700. }
  14701. this.isShowEdit = !this.isShowEdit;
  14702. break;
  14703. case 16: //悬浮歌词
  14704. this.showPipLyric = !this.showPipLyric;
  14705. break;
  14706. case 17: //横屏模式
  14707. if (this.isLandscape) {
  14708. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  14709. } else {
  14710. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  14711. }
  14712. this.isShowMoreView = false
  14713. break;
  14714. case 20://AB循环
  14715. this.isABSheet = !this.isABSheet
  14716. break;
  14717. case 24://均衡器
  14718. this.isEqualizerSheet = !this.isEqualizerSheet
  14719. break;
  14720. }
  14721. }
  14722. //AB循环
  14723. @State isOpenAB:boolean = false
  14724. @State jumpATime:number = 0
  14725. @State jumpBTime:number = 0
  14726. @State isABSheet:boolean = false
  14727. @State isEqualizerSheet: boolean = false
  14728. @State eqApplying: boolean = false
  14729. @State eqAppliedAt: number = 0
  14730. @State eqCurrentPresetName: string = '正常'
  14731. @State eqCurrentEnabled: boolean = false
  14732. @Builder
  14733. ABLoopSheet() {
  14734. ABLoopComptent({
  14735. jumpATime:this.jumpATime,
  14736. jumpBTime:this.jumpBTime,
  14737. onClickAItem: async ()=>{
  14738. if(this.mIjkMediaPlayer){
  14739. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  14740. }
  14741. },
  14742. onClickBItem: async ()=>{
  14743. if(this.mIjkMediaPlayer){
  14744. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  14745. if(this.jumpBTime<=this.jumpATime){
  14746. ToastUtil.showToast('设置B点时间不能小于A点时间')
  14747. this.jumpBTime = 0
  14748. }
  14749. }
  14750. },
  14751. onCancleButtonClick: async ()=>{
  14752. this.isOpenAB = false
  14753. this.isABSheet = false
  14754. },
  14755. onStartButtonClick: async ()=>{
  14756. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  14757. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  14758. return
  14759. }
  14760. this.isABSheet = false
  14761. this.startABLoop()
  14762. },
  14763. })
  14764. }
  14765. private syncEqualizerUi(): void {
  14766. const equalizerManager = EqualizerManager.getInstance();
  14767. this.eqCurrentEnabled = equalizerManager.enabled;
  14768. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  14769. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  14770. this.eqAppliedAt = 0;
  14771. }
  14772. }
  14773. private markEqualizerApplied(): void {
  14774. const equalizerManager = EqualizerManager.getInstance();
  14775. this.eqCurrentEnabled = equalizerManager.enabled;
  14776. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  14777. this.eqAppliedAt = Date.now();
  14778. this.eqApplying = false;
  14779. }
  14780. private applyEqualizerToCurrentPlayback(): void {
  14781. if (this.eqApplying) {
  14782. return;
  14783. }
  14784. if (this.castControllerWrapper && this.isCastPlaying) {
  14785. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  14786. return;
  14787. }
  14788. if (!this.currentSong || !this.mIjkMediaPlayer) {
  14789. ToastUtil.showToast('暂无可应用的播放');
  14790. return;
  14791. }
  14792. this.eqApplying = true;
  14793. try {
  14794. const equalizerManager = EqualizerManager.getInstance();
  14795. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14796. this.markEqualizerApplied();
  14797. ToastUtil.showToast('均衡器已实时生效');
  14798. } catch (error) {
  14799. this.eqApplying = false;
  14800. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  14801. }
  14802. }
  14803. @Builder
  14804. private EqualizerApplyStatusBar(): void {
  14805. Row() {
  14806. Column() {
  14807. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  14808. .fontSize(12)
  14809. .fontColor($r('app.color.text_color'))
  14810. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  14811. .fontSize(10)
  14812. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  14813. }
  14814. .alignItems(HorizontalAlign.Start)
  14815. Blank()
  14816. Button('重新应用')
  14817. .fontSize(12)
  14818. .fontColor(Color.White)
  14819. .backgroundColor('#666666')
  14820. .height(28)
  14821. .padding({ left: 14, right: 14 })
  14822. .borderRadius(14)
  14823. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  14824. .onClick(() => {
  14825. this.applyEqualizerToCurrentPlayback();
  14826. })
  14827. }
  14828. .width('100%')
  14829. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  14830. .backgroundColor($r('app.color.settings_background_main'))
  14831. .borderRadius(12)
  14832. }
  14833. @Builder
  14834. EqualizerSheet() {
  14835. Column() {
  14836. Column() {
  14837. EqualizerViewWithCallback({
  14838. onEqualizerChanged: () => {
  14839. this.syncEqualizerUi();
  14840. if (this.mIjkMediaPlayer) {
  14841. const equalizerManager = EqualizerManager.getInstance();
  14842. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14843. this.markEqualizerApplied();
  14844. }
  14845. }
  14846. })
  14847. }
  14848. .margin({ top: 8 })
  14849. Column() {
  14850. this.EqualizerApplyStatusBar()
  14851. }
  14852. .margin({ top: 8 })
  14853. }
  14854. .padding({ left: 12, right: 12, bottom: 20 })
  14855. .width('100%')
  14856. }
  14857. //开始AB循环
  14858. startABLoop(){
  14859. if(this.mIjkMediaPlayer){
  14860. this.seekTo(this.jumpATime+'')
  14861. this.isOpenAB = true
  14862. }
  14863. }
  14864. /**
  14865. * 切换横竖屏
  14866. *
  14867. */
  14868. setOrientation(orientation: number) {
  14869. this.windowClass.setPreferredOrientation(orientation).then(() => {
  14870. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  14871. }).catch((err: BusinessError) => {
  14872. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  14873. });
  14874. }
  14875. /**
  14876. * 画中画功能(悬浮歌词功能)
  14877. *
  14878. */
  14879. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  14880. pipController?: PiPWindow.PiPController;
  14881. navigationId: string = '';
  14882. @State curState: string = '';
  14883. @State curError: ResourceStr = '';
  14884. @State pipBg: string = '#E8E8E8'
  14885. @State buttonAction: string = '';
  14886. //开启画中画功能
  14887. async startPip() {
  14888. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  14889. if (!this.pipController) {
  14890. await this.createPipController();
  14891. }
  14892. if (!this.pipController) {
  14893. Logger.info(`[${TAG}] pipController create error`);
  14894. return;
  14895. }
  14896. await this.pipController.startPiP();
  14897. }
  14898. async stopPip() {
  14899. if (!this.pipController) {
  14900. Logger.info(`[${TAG}] pipController is not exist`);
  14901. return;
  14902. }
  14903. this.isOpenPip = false
  14904. await this.pipController.stopPiP();
  14905. }
  14906. async createPipController() {
  14907. this.pipController = await PiPWindow.create({
  14908. context: getContext(this),
  14909. componentController: this.xcomponentController,
  14910. navigationId: this.navigationId,
  14911. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  14912. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  14913. customUIController: this.nodeController,
  14914. });
  14915. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  14916. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  14917. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  14918. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  14919. this.onStateChange(state, reason);
  14920. });
  14921. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  14922. this.onActionEvent(event, status);
  14923. });
  14924. }
  14925. destroyPipController() {
  14926. if (!this.pipController) {
  14927. return;
  14928. }
  14929. this.pipController.off('stateChange');
  14930. this.pipController.off('controlPanelActionEvent');
  14931. this.pipController = undefined;
  14932. }
  14933. onStateChange(state: PiPWindow.PiPState, reason: string) {
  14934. switch (state) {
  14935. case PiPWindow.PiPState.ABOUT_TO_START:
  14936. this.curState = 'ABOUT_TO_START';
  14937. this.curError = $r('app.string.current_error_hint');
  14938. break;
  14939. case PiPWindow.PiPState.STARTED:
  14940. this.curState = 'STARTED';
  14941. this.curError = $r('app.string.current_error_hint');
  14942. break;
  14943. case PiPWindow.PiPState.ABOUT_TO_STOP:
  14944. this.curState = 'ABOUT_TO_STOP';
  14945. this.curError = $r('app.string.current_error_hint');
  14946. break;
  14947. case PiPWindow.PiPState.STOPPED:
  14948. this.curState = 'STOPPED';
  14949. this.curError = $r('app.string.current_error_hint');
  14950. this.stopPip()
  14951. this.destroyPipController()
  14952. break;
  14953. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  14954. this.curState = 'ABOUT_TO_RESTORE';
  14955. this.curError = $r('app.string.current_error_hint');
  14956. break;
  14957. case PiPWindow.PiPState.ERROR:
  14958. this.curState = 'ERROR';
  14959. this.curError = reason;
  14960. break;
  14961. default:
  14962. break;
  14963. }
  14964. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  14965. }
  14966. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  14967. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  14968. switch (event) {
  14969. case 'playbackStateChanged':
  14970. if (status === 0) {
  14971. this.pause();
  14972. } else {
  14973. console.info('onecold startPlayOrResumePlay 9869')
  14974. this.startPlayOrResumePlay();
  14975. }
  14976. break;
  14977. case 'nextVideo':
  14978. // 切换到下一个视频
  14979. this.playNext().catch(() => {
  14980. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  14981. });
  14982. break;
  14983. case 'previousVideo':
  14984. // 切换到上一个视频
  14985. this.playPrevious().catch(() => {
  14986. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  14987. });
  14988. break;
  14989. case 'previousVideo':
  14990. // 切换到上一个视频
  14991. this.playPrevious().catch(() => {
  14992. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  14993. });
  14994. break;
  14995. default:
  14996. }
  14997. this.buttonAction = event + `-status:${status}`;
  14998. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  14999. }
  15000. /**
  15001. * 画中画功能(悬浮歌词功能)结束
  15002. *
  15003. */
  15004. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  15005. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  15006. this.isShowMoreView = false;
  15007. this.showTipsDialog();
  15008. return ''; // Return empty string when no API is configured
  15009. }
  15010. if (!item) {
  15011. return ''; // Return empty string if item is undefined
  15012. }
  15013. const titleS = title||item?.name || '';
  15014. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  15015. return this.searchCover(item, titleS, artistS, true); // Await is not needed here as we return the promise directly
  15016. }
  15017. /**
  15018. *api搜索封面
  15019. *item,根据title和artist
  15020. */
  15021. searchCover(item: VideoItem, title: string, artist: string, markAsCustomCover: boolean = false): Promise<string> {
  15022. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  15023. LogUtil.debug("onecold res =" + res);
  15024. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  15025. if (item.filePath == this.currentSong?.filePath) {
  15026. if (this.currentSong) {
  15027. mergeCoverWithPriority(this.currentSong, res, markAsCustomCover ? 1 : 0);
  15028. this.cover = this.currentSong.pixelMapPath || res;
  15029. }
  15030. }
  15031. if (isRemoteCloudType(item.type)) {
  15032. mergeCoverWithPriority(item, res, markAsCustomCover ? 1 : 0);
  15033. this.syncRemoteManagerSong(item);
  15034. try {
  15035. await this.persistRemoteMetadataToDb(item);
  15036. this.emitRemoteMetadataUpdated(item);
  15037. } catch (error) {
  15038. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  15039. }
  15040. } else {
  15041. // Update pixel map path but always return res regardless of success
  15042. if (markAsCustomCover) {
  15043. item.isCustomCover = 1;
  15044. this.table.updateCustomCoverPath(item.filePath, res, (success: boolean, error?: string) => {
  15045. if (success) {
  15046. this.doUpdateData();
  15047. console.log("onecold 更新音乐封面成功,数据库已同步");
  15048. } else {
  15049. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15050. }
  15051. });
  15052. } else {
  15053. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  15054. if (success) {
  15055. this.doUpdateData();
  15056. console.log("onecold 更新音乐封面成功,数据库已同步");
  15057. } else {
  15058. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15059. }
  15060. });
  15061. }
  15062. }
  15063. LogUtil.debug("onecold this.cover =" + this.cover);
  15064. }
  15065. return res; // Always return res regardless of updatePixelMapPath result
  15066. });
  15067. }
  15068. @State jumpTopTime: number = 0
  15069. @State jumpEndTime: number = 0
  15070. @State isOpenJump: boolean = false
  15071. @Builder
  15072. JumpTopEndSheet() {
  15073. Scroll() {
  15074. Column() {
  15075. Column() {
  15076. Text('仅对本播放列表有效')
  15077. .fontSize(16)
  15078. .fontColor($r('app.color.text_color'))
  15079. // 跳过头尾
  15080. Column() {
  15081. Row() {
  15082. Text('跳过片头:')
  15083. .fontSize(16)
  15084. .fontColor($r('app.color.text_color'))
  15085. Text(this.jumpTopTime + 's')
  15086. .fontSize(16)
  15087. .fontColor($r('app.color.text_color'))
  15088. }
  15089. .margin({ bottom: 5 })
  15090. Row() {
  15091. Slider({
  15092. value: this.jumpTopTime,
  15093. min: 0,
  15094. max: 120,
  15095. step: 1,
  15096. style: SliderStyle.OutSet
  15097. })
  15098. .blockColor(this.themeColor)
  15099. .trackColor($r('app.color.speed_text_color'))
  15100. .selectedColor(Color.White)
  15101. .trackThickness(8)
  15102. .onChange((value: number) => {
  15103. this.jumpTopTime = value;
  15104. })
  15105. .width('85%')
  15106. }
  15107. .alignItems(VerticalAlign.Top)
  15108. }
  15109. .margin({ top: 10, bottom: 10 })
  15110. // 跳过头尾
  15111. Column() {
  15112. Row() {
  15113. Text('跳过片尾:')
  15114. .fontSize(16)
  15115. .fontColor($r('app.color.text_color'))
  15116. Text(this.jumpEndTime + 's')
  15117. .fontSize(16)
  15118. .fontColor($r('app.color.text_color'))
  15119. }
  15120. .margin({ bottom: 5 })
  15121. Row() {
  15122. Slider({
  15123. value: this.jumpEndTime,
  15124. min: 0,
  15125. max: 120,
  15126. step: 1,
  15127. style: SliderStyle.OutSet
  15128. })
  15129. .blockColor(this.themeColor)
  15130. .trackColor($r('app.color.speed_text_color'))
  15131. .selectedColor(Color.White)
  15132. .trackThickness(8)
  15133. .onChange((value: number) => {
  15134. this.jumpEndTime = value;
  15135. })
  15136. .width('85%')
  15137. }
  15138. .alignItems(VerticalAlign.Top)
  15139. }
  15140. .margin({ top: 10, bottom: 10 })
  15141. Row() {
  15142. Button('保存设置')
  15143. .fontColor(Color.White)
  15144. .layoutWeight(1)
  15145. .height(40)
  15146. .width(80)
  15147. .backgroundColor(this.themeColor)
  15148. .stateEffect(true)
  15149. .margin({ left: 0, bottom: 20 })
  15150. .onClick(async () => {
  15151. if (!Utility.isNoble()) {
  15152. this.isJumpSetting = false
  15153. this.isShowMoreView = false
  15154. this.showVipDialog()
  15155. return
  15156. }
  15157. if (this.currentSong === undefined) {
  15158. return
  15159. }
  15160. if (this.modeType === 0) {
  15161. let parentPath = FileUtil.getParentPath(this.videoUrl)
  15162. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  15163. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  15164. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  15165. } else if (this.modeType === 1) { //媒体库
  15166. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  15167. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  15168. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  15169. } else if (this.modeType === 2) { //艺术家
  15170. if (this.currentSong?.artist) {
  15171. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  15172. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  15173. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  15174. }
  15175. } else if (this.modeType === 3) { //专辑
  15176. if (this.currentSong?.album) {
  15177. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  15178. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  15179. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  15180. }
  15181. }
  15182. ToastUtil.showShort("保存成功")
  15183. this.isJumpSetting = false
  15184. })
  15185. }
  15186. .margin({
  15187. left: 38,
  15188. right: 38,
  15189. top: 10,
  15190. bottom: 10
  15191. })
  15192. .width(120)
  15193. .height(50)
  15194. }
  15195. }
  15196. }
  15197. .width('100%')
  15198. .height('100%')
  15199. }
  15200. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  15201. private onStateVastChange(state: AVCastPickerState) {
  15202. if (state == AVCastPickerState.STATE_APPEARING) {
  15203. console.log('The picker starts showing.');
  15204. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  15205. console.log('The picker finishes presenting.');
  15206. }
  15207. }
  15208. private showSelectLyric() {
  15209. DialogHelper.showActionSheetDialog({
  15210. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  15211. // sheets: ["本地歌词", "搜索歌词"],
  15212. sheets: [
  15213. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  15214. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  15215. ],
  15216. maskColor: Color.Transparent,
  15217. backgroundColor: $r('app.color.bg_card'),
  15218. transition: AnimationHelper.transitionInDown(666),
  15219. onAction: (index) => {
  15220. switch (index) {
  15221. case 0:
  15222. this.callFilePickerSelectFileForLyric()
  15223. break;
  15224. case 1:
  15225. if (StrUtil.isNotEmpty(this.videoUrl)) {
  15226. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15227. this.initLyric(lyricPath);
  15228. }
  15229. break;
  15230. }
  15231. }
  15232. })
  15233. }
  15234. // 拉起picker选择文件管理器
  15235. async callFilePickerSelectFileForLyric(): Promise<void> {
  15236. try {
  15237. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  15238. DocumentSelectOptions.maxSelectNumber = 1
  15239. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  15240. let documentPicker = new picker.DocumentViewPicker();
  15241. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  15242. Logger.info(TAG,
  15243. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  15244. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  15245. this.saveVideoDatasLyric(DocumentSelectResult)
  15246. }
  15247. }).catch((err: BusinessError) => {
  15248. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  15249. });
  15250. } catch (err) {
  15251. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  15252. }
  15253. }
  15254. async saveVideoDatasLyric(uris: string[]) {
  15255. if (ArrayUtil.isEmpty(uris)) {
  15256. return
  15257. }
  15258. let newUris: string[] = [];
  15259. for (let i = 0; i < uris.length; i++) {
  15260. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  15261. Logger.info(TAG, 'filePath uri: ' + filePath);
  15262. newUris.push(filePath)
  15263. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  15264. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  15265. fileIo.copyFileSync(file.fd, file2.fd)
  15266. fileIo.closeSync(file);
  15267. fileIo.closeSync(file2);
  15268. this.initLyric(filePath,false,false,true)
  15269. }
  15270. }
  15271. private initDelayPlay(context: object) {
  15272. this.mContext = context;
  15273. }
  15274. startPipLyric() {
  15275. if (this.pipController) {
  15276. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15277. PiPWindow.PiPControlStatus.PLAY);
  15278. }
  15279. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  15280. if (this.isOpenPip) {
  15281. this.startPip()
  15282. } else {
  15283. this.stopPip()
  15284. }
  15285. }
  15286. //startOffset 从cue分轨时间开始播
  15287. private startPlayOrResumePlay(startOffset?:number) {
  15288. let finalStartOffset = startOffset
  15289. if ((finalStartOffset === undefined || finalStartOffset === null) && this.currentSong && isCueSplitItem(this.currentSong)) {
  15290. finalStartOffset = 0
  15291. }
  15292. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  15293. //针对dsf文件高采样率,统一转wav播放
  15294. // const sampleRate = this.currentSong?.sampleRate||0
  15295. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  15296. // console.info('onecold 采样率 ='+sampleRate)
  15297. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  15298. // console.info('onecold newDsfPath ='+newDsfPath)
  15299. // if(!FileUtil.accessSync(newDsfPath)){
  15300. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  15301. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  15302. // this.videoUrl = newDsfPath
  15303. // this.startPlay(startOffset)
  15304. // }).catch((e:object)=>{
  15305. // console.info("task1 catch e: " + e);
  15306. // })
  15307. // }else{
  15308. // this.videoUrl = newDsfPath
  15309. // this.startPlay(startOffset)
  15310. // }
  15311. //
  15312. // }else{
  15313. // this.startPlay(startOffset)
  15314. // }
  15315. this.startPlay(finalStartOffset)
  15316. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  15317. // 排除用户拖动进度条的情况
  15318. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  15319. void this.preloadNextSongInternal();
  15320. }
  15321. }
  15322. startPlay(startOffset?:number) {
  15323. this.startPipLyric()
  15324. this.mDestroyPage = false;
  15325. this.animationState = AnimationStatus.Running
  15326. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  15327. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  15328. this.stopProgressTask();
  15329. this.startProgressTask();
  15330. this.clearInitialSeekGuardTimer();
  15331. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  15332. this.remoteRestoreSeekToken++;
  15333. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  15334. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  15335. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  15336. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  15337. this.videoUrl.includes('://');
  15338. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  15339. // 网盘歌曲起播阶段统一显示加载圈,prepared/首帧后再收起
  15340. this.isPlayerLoading = !!isRemoteStreamSong;
  15341. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15342. Logger.info(
  15343. TAG,
  15344. `[remote-play] startPlay type=${this.currentSong.type}, memory=${this.pendingMemorySeekPosition}, ` +
  15345. `waitInitial=${this.waitInitialSeekBeforeStart}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15346. );
  15347. }
  15348. this.play(this.videoUrl.toString(),startOffset);
  15349. }
  15350. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  15351. this.mIjkMediaPlayer.start();
  15352. this.setProgress()
  15353. this.CONTROL_PlayStatus = PlayStatus.PLAY
  15354. }
  15355. this.setIsPlaying(true)
  15356. this.updateSessionPlayState(true)
  15357. this.watchStatus();
  15358. this.updateLastPlayTimeStr(this.videoUrl)
  15359. }
  15360. updateLastPlayTimeStr(filePath: string) {
  15361. const activeSong = this.currentSong;
  15362. let targetFilePath = this.currentSong?.filePath || filePath;
  15363. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15364. const remoteStoragePath = this.resolveRemoteStoragePath(activeSong);
  15365. if (remoteStoragePath) {
  15366. targetFilePath = remoteStoragePath;
  15367. }
  15368. Logger.info(`heanup 检测到网络音频播放,改为更新远程歌曲最近播放: ${targetFilePath}`)
  15369. }
  15370. if (!targetFilePath) {
  15371. Logger.warn(TAG, `更新最近播放时间失败,目标路径为空: ${filePath}`);
  15372. return;
  15373. }
  15374. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  15375. const applyHistoryUpdate = (): void => {
  15376. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (success: boolean, error?: string) => {
  15377. if (success) {
  15378. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15379. this.currentSong.lastPlayedStr = lastPlayTime
  15380. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15381. }
  15382. this.getHistoryList(false)
  15383. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  15384. return;
  15385. }
  15386. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15387. Logger.warn(TAG, `远程歌曲最近播放更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  15388. this.persistRemoteMetadataToDb(activeSong)
  15389. .then(() => {
  15390. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (retrySuccess: boolean,
  15391. retryError?: string) => {
  15392. if (retrySuccess) {
  15393. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15394. this.currentSong.lastPlayedStr = lastPlayTime
  15395. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15396. }
  15397. this.getHistoryList(false)
  15398. Logger.info(TAG, `远程歌曲最近播放补入库后更新成功: ${targetFilePath}`);
  15399. } else {
  15400. Logger.error(TAG,
  15401. `远程歌曲最近播放补入库后仍更新失败: ${targetFilePath}, error=${retryError}`);
  15402. }
  15403. });
  15404. })
  15405. .catch((persistError: Error) => {
  15406. Logger.error(TAG,
  15407. `远程歌曲最近播放补入库失败: ${targetFilePath}, error=${persistError.message}`);
  15408. });
  15409. return;
  15410. }
  15411. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  15412. });
  15413. };
  15414. applyHistoryUpdate();
  15415. }
  15416. private completionNum(num: number): string | number {
  15417. if (num < 10) {
  15418. return '0' + num;
  15419. } else {
  15420. return num;
  15421. }
  15422. }
  15423. private parseDurationToMs(duration?: string): number {
  15424. if (!duration) {
  15425. return 0;
  15426. }
  15427. const parts = duration.split(':').map((item) => Number(item));
  15428. if (parts.some((item) => Number.isNaN(item))) {
  15429. return 0;
  15430. }
  15431. if (parts.length === 2) {
  15432. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  15433. }
  15434. if (parts.length === 3) {
  15435. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  15436. }
  15437. return 0;
  15438. }
  15439. private sanitizePlaybackUrl(url?: string): string {
  15440. if (!url) {
  15441. return '';
  15442. }
  15443. let sanitized = url.replace(/(access_token=)[^&]+/ig, '$1***');
  15444. sanitized = sanitized.replace(/(refresh_token=)[^&]+/ig, '$1***');
  15445. sanitized = sanitized.replace(/(Authorization=)[^&]+/ig, '$1***');
  15446. if (sanitized.length > 220) {
  15447. return `${sanitized.substring(0, 220)}...`;
  15448. }
  15449. return sanitized;
  15450. }
  15451. private async dispatchPlaylistPlayRequest(playlistData: PlaylistPlayRequest): Promise<void> {
  15452. clearPendingPlaylistPlay();
  15453. if (playlistData.playType !== undefined) {
  15454. this.applyRequestedPlayType(playlistData.playType);
  15455. }
  15456. await this.handlePlaylistPlayRequest(
  15457. playlistData.playlistId,
  15458. playlistData.playlistName,
  15459. playlistData.songFilePaths,
  15460. playlistData.startIndex,
  15461. playlistData.isJump ?? false,
  15462. playlistData.songCount
  15463. );
  15464. }
  15465. private async resolvePlaybackUrlForCurrentSong(source: string): Promise<string | null> {
  15466. const song = this.currentSong;
  15467. if (!song) {
  15468. Logger.warn(TAG, `[play-url] skip source=${source}, currentSong is null`);
  15469. return null;
  15470. }
  15471. const expectedFilePath = song.filePath || '';
  15472. const requestSerial = ++this.playbackUrlRequestSerial;
  15473. Logger.info(
  15474. TAG,
  15475. `[play-url] begin serial=${requestSerial}, source=${source}, song=${song.name}, path=${expectedFilePath}`
  15476. );
  15477. const resolvedUrl = await setVideoUrlForSong(song, {
  15478. context: this.context,
  15479. autoParseMusicName: this.autoParseMusicName
  15480. });
  15481. const currentFilePath = this.currentSong?.filePath || '';
  15482. if (requestSerial !== this.playbackUrlRequestSerial || currentFilePath !== expectedFilePath) {
  15483. Logger.warn(
  15484. TAG,
  15485. `[play-url] stale serial=${requestSerial}, source=${source}, expected=${expectedFilePath}, ` +
  15486. `current=${currentFilePath}, drop=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15487. );
  15488. return null;
  15489. }
  15490. Logger.info(
  15491. TAG,
  15492. `[play-url] apply serial=${requestSerial}, source=${source}, song=${song.name}, ` +
  15493. `url=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15494. );
  15495. return resolvedUrl;
  15496. }
  15497. private beginSeekTrace(source: string, requestMs: number): void {
  15498. this.lastSeekSource = source;
  15499. this.lastSeekRequestMs = requestMs;
  15500. this.seekTraceUntilTs = Date.now() + this.seekTraceLogWindowMs;
  15501. this.lastSeekTraceLogTs = 0;
  15502. }
  15503. private isSeekTraceActive(): boolean {
  15504. return this.seekTraceUntilTs > 0 && Date.now() <= this.seekTraceUntilTs;
  15505. }
  15506. private logSeekTrace(stage: string, position?: number, playerDuration?: number, force: boolean = false): void {
  15507. if (!force && !this.isSeekTraceActive()) {
  15508. return;
  15509. }
  15510. const now = Date.now();
  15511. if (!force && now - this.lastSeekTraceLogTs < this.seekTraceLogIntervalMs) {
  15512. return;
  15513. }
  15514. this.lastSeekTraceLogTs = now;
  15515. const currentPosition = typeof position === 'number' ? position : this.mIjkMediaPlayer.getCurrentPosition();
  15516. const resolvedPlayerDuration = typeof playerDuration === 'number' ? playerDuration : this.mIjkMediaPlayer.getDuration();
  15517. Logger.info(
  15518. TAG,
  15519. `[seek-trace] stage=${stage}, source=${this.lastSeekSource || 'unknown'}, req=${this.lastSeekRequestMs}, ` +
  15520. `current=${currentPosition}, playerDuration=${resolvedPlayerDuration}, uiDuration=${this.duration}, ` +
  15521. `activeDuration=${this.getActiveDuration()}, isPlaying=${this.mIjkMediaPlayer.isPlaying()}, ` +
  15522. `isSeekTo=${this.isSeekTo}, waitInitial=${this.waitInitialSeekBeforeStart}, ` +
  15523. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15524. );
  15525. }
  15526. private stringForTime(timeMs: number): string {
  15527. let totalSeconds: number | string = (timeMs / 1000);
  15528. let newSeconds: number | string = totalSeconds % 60;
  15529. let minutes: number | string = (totalSeconds / 60) % 60;
  15530. let hours: number | string = totalSeconds / 3600;
  15531. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  15532. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  15533. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  15534. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  15535. if (this.isCurrentTime) {
  15536. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  15537. this.oldSeconds = newSeconds
  15538. } else {
  15539. newSeconds = this.oldSeconds
  15540. }
  15541. }
  15542. newSeconds = this.completionNum(newSeconds);
  15543. if (hours > 0) {
  15544. return hours + ":" + minutes + ":" + newSeconds;
  15545. } else {
  15546. return minutes + ":" + newSeconds;
  15547. }
  15548. }
  15549. private getPlayerSwiperDisplayCount(): number {
  15550. return new BreakpointType<number>({
  15551. sm: 1,
  15552. md: 2,
  15553. lg: 2,
  15554. xl: 2,
  15555. xxl: 2
  15556. }).getValue(this.currentBreakpoint) ?? 1
  15557. }
  15558. private shouldUpdateMainLyricPanel(): boolean {
  15559. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  15560. }
  15561. private getActivePlaybackPositionMs(): number {
  15562. if (this.castControllerWrapper && this.isCastPlaying) {
  15563. return this.currentTime2 * 1000
  15564. }
  15565. return this.mIjkMediaPlayer.getCurrentPosition()
  15566. }
  15567. private syncLyricPositionNow(): void {
  15568. const position = this.getActivePlaybackPositionMs()
  15569. if (position < 0) {
  15570. return
  15571. }
  15572. this.updateLyricPosition(position + this.timeOffset * 1000)
  15573. }
  15574. private updateLyricPosition(lyricPosition: number): void {
  15575. if (!this.isAppForeground || !this.isPageVisible) {
  15576. return;
  15577. }
  15578. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  15579. const shouldUpdatePipLyric = this.showPipLyric
  15580. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  15581. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  15582. return
  15583. }
  15584. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  15585. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  15586. return;
  15587. }
  15588. this.lastLyricRenderPosition = lyricPosition;
  15589. if (shouldUpdateMainLyric) {
  15590. this.lyricController.updatePosition(lyricPosition);
  15591. }
  15592. if (shouldUpdatePipLyric) {
  15593. this.lyricControllerXF.updatePosition(lyricPosition);
  15594. }
  15595. if (shouldUpdateSingleLineLyric) {
  15596. this.lyricControllerSingle.updatePosition(lyricPosition);
  15597. }
  15598. }
  15599. private setProgress() {
  15600. if (this.castControllerWrapper && this.isCastPlaying) {
  15601. return;
  15602. }
  15603. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  15604. const rawPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15605. const rawDuration = this.mIjkMediaPlayer.getDuration();
  15606. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  15607. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  15608. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  15609. const cueTrackDuration = cueTrackItem ? getCueTrackDuration(cueTrackItem) : 0;
  15610. let position = rawPosition;
  15611. let duration = rawDuration;
  15612. if (cueTrackItem) {
  15613. position = Math.max(0, rawPosition - cueTrackStartOffset);
  15614. if (cueTrackDuration > 0) {
  15615. duration = cueTrackDuration;
  15616. } else if (cueTrackEndOffset > cueTrackStartOffset) {
  15617. duration = cueTrackEndOffset - cueTrackStartOffset;
  15618. } else if (rawDuration > cueTrackStartOffset) {
  15619. duration = rawDuration - cueTrackStartOffset;
  15620. }
  15621. if (duration > 0 && position > duration) {
  15622. position = duration;
  15623. }
  15624. }
  15625. if (duration <= 0 && this.duration > 0) {
  15626. duration = this.duration;
  15627. }
  15628. let pos = 0;
  15629. if (duration > 0) {
  15630. this.slideEnable = true;
  15631. let curPercent = position / duration;
  15632. pos = curPercent * 100;
  15633. if (shouldRefreshUi) {
  15634. if (pos > this.PROGRESS_MAX_VALUE) {
  15635. this.progressValue = this.PROGRESS_MAX_VALUE
  15636. } else {
  15637. this.progressValue = pos;
  15638. }
  15639. }
  15640. }
  15641. this.logSeekTrace('progress-tick', position, duration);
  15642. // LogUtils.getInstance()
  15643. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  15644. if (shouldRefreshUi) {
  15645. this.totalTime = this.stringForTime(duration);
  15646. }
  15647. if (position > duration) {
  15648. position = duration;
  15649. }
  15650. if (shouldRefreshUi) {
  15651. const lyricPosition = (cueTrackItem ? rawPosition : position) + this.timeOffset * 1000;
  15652. this.isCurrentTime = true;
  15653. this.updateLyricPosition(lyricPosition);
  15654. // 蓝牙歌词更新逻辑
  15655. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  15656. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  15657. // 仅在歌词行变化时更新,避免频繁调用
  15658. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  15659. this.lastBluetoothLyricLine = currentLyricLine;
  15660. this.avSessionController.updateBluetoothLyric(
  15661. currentLyricLine,
  15662. this.currentSong.name || '',
  15663. this.currentSong.artist || '',
  15664. this.bluetoothLyricMode
  15665. );
  15666. }
  15667. }
  15668. this.currentTime = this.stringForTime(position);
  15669. this.isCurrentTime = false
  15670. }
  15671. if (this.mIjkMediaPlayer.isPlaying()) {
  15672. const isCueTrackCompleted = cueTrackItem &&
  15673. cueTrackEndOffset > cueTrackStartOffset &&
  15674. rawPosition >= cueTrackEndOffset;
  15675. //如果是开启AB循环
  15676. if(this.isOpenAB){
  15677. if(position >=this.jumpBTime){
  15678. this.seekTo(this.jumpATime+'')
  15679. return
  15680. }
  15681. }
  15682. // 判断是否播放到结束时间
  15683. if ((this.isOpenJump && duration > this.jumpEndTime * 1000 &&
  15684. position >= duration - this.jumpEndTime * 1000) || isCueTrackCompleted) {
  15685. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  15686. this.CONTROL_PlayStatus = PlayStatus.INIT
  15687. this.startPlayOrResumePlay();
  15688. }else if (this.playType == 2) { //2:正常播放,单片播完
  15689. this.showRePlay();
  15690. this.currentTime = this.stringForTime(duration);
  15691. this.progressValue = this.PROGRESS_MAX_VALUE;
  15692. this.slideEnable = false;
  15693. this.stop();
  15694. // ToastUtil.showToast('开始重新播放')
  15695. }else if (this.playType == 4) { //4:连续播放不循环
  15696. // 检查是否是最后一首
  15697. if (this.curIndex >= this.songList.length - 1) {
  15698. // 已经是最后一首,停止播放
  15699. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  15700. ToastUtil.showToast('已经是最后一首了');
  15701. this.showRePlay();
  15702. this.currentTime = this.stringForTime(duration);
  15703. this.progressValue = this.PROGRESS_MAX_VALUE;
  15704. this.slideEnable = false;
  15705. this.stop();
  15706. } else {
  15707. // 不是最后一首,继续播放下一首
  15708. this.playNext().catch(() => {
  15709. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  15710. });
  15711. }
  15712. }else{
  15713. this.playNext().catch(() => {
  15714. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  15715. });
  15716. }
  15717. }
  15718. }
  15719. }
  15720. private startProgressTask() {
  15721. let that = this;
  15722. if (this.updateProgressTimer) {
  15723. clearInterval(this.updateProgressTimer);
  15724. this.updateProgressTimer = 0;
  15725. }
  15726. this.updateProgressTimer = setInterval(() => {
  15727. //LogUtils.getInstance().LOGI("startProgressTask");
  15728. if (!that.mDestroyPage) {
  15729. that.setProgress();
  15730. }
  15731. }, this.progressUpdateIntervalMs);
  15732. }
  15733. private stopProgressTask() {
  15734. LogUtils.getInstance().LOGI("stopProgressTask");
  15735. clearInterval(this.updateProgressTimer);
  15736. this.updateProgressTimer = 0;
  15737. }
  15738. private showLoadIng() {
  15739. this.isPlayerLoading = true;
  15740. this.loadingVisible = Visibility.Visible;
  15741. this.replayVisible = Visibility.None;
  15742. }
  15743. private hideLoadIng() {
  15744. this.isPlayerLoading = false;
  15745. this.loadingVisible = Visibility.None;
  15746. this.replayVisible = Visibility.None;
  15747. }
  15748. private showRePlay() {
  15749. this.isPlayerLoading = false;
  15750. this.loadingVisible = Visibility.None;
  15751. this.replayVisible = Visibility.Visible;
  15752. }
  15753. private beginRemoteSongSwitchLoading(song?: VideoItem): boolean {
  15754. const shouldShow = !!song && isRemoteCloudType(song.type);
  15755. if (shouldShow) {
  15756. this.showLoadIng();
  15757. }
  15758. return shouldShow;
  15759. }
  15760. private clearInitialSeekGuardTimer(): void {
  15761. if (this.initialSeekGuardTimer) {
  15762. clearTimeout(this.initialSeekGuardTimer);
  15763. this.initialSeekGuardTimer = 0;
  15764. }
  15765. }
  15766. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  15767. try {
  15768. if (!this.mIjkMediaPlayer.isPlaying()) {
  15769. this.mIjkMediaPlayer.start();
  15770. }
  15771. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15772. this.setIsPlaying(true);
  15773. this.updateSessionPlayState(true);
  15774. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  15775. } catch (error) {
  15776. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  15777. }
  15778. }
  15779. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  15780. this.clearInitialSeekGuardTimer();
  15781. const wasWaiting = this.waitInitialSeekBeforeStart;
  15782. this.waitInitialSeekBeforeStart = false;
  15783. this.pendingMemorySeekPosition = 0;
  15784. this.isPlayerLoading = false;
  15785. this.hideLoadIng();
  15786. if (wasWaiting) {
  15787. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  15788. }
  15789. if (shouldStart) {
  15790. this.ensurePlayerStartedAfterInitialSeek(reason);
  15791. }
  15792. }
  15793. private startInitialSeekGuardTimer(scene: string): void {
  15794. this.clearInitialSeekGuardTimer();
  15795. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  15796. return;
  15797. }
  15798. const token = this.remoteRestoreSeekToken;
  15799. this.initialSeekGuardTimer = setTimeout(() => {
  15800. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  15801. return;
  15802. }
  15803. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  15804. this.finishInitialSeekWait('seek-timeout', true);
  15805. }, this.initialSeekGuardTimeoutMs);
  15806. }
  15807. private async play(url: string,startOffset?:number) {
  15808. this.lyricController.setLyric(null)
  15809. this.lyricControllerSingle.setLyric(null)
  15810. this.lastLyricRenderPosition = Number.NaN;
  15811. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  15812. console.info('onecold this.url 1= '+url)
  15813. if(!url.toLowerCase().startsWith('http')){
  15814. let hasPermission = await PermissionUtil.activatePermission(url)
  15815. console.info('onecold this.hasPermission 1= '+hasPermission)
  15816. if(!url.includes(this.packName)){
  15817. const file = fs.openSync(url)
  15818. this.videoUrl = file.path
  15819. url= this.videoUrl
  15820. }
  15821. console.info('onecold this.hasPermission 1= '+hasPermission)
  15822. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  15823. }
  15824. let that = this;
  15825. const isBaiduStreamingPlaybackUrl = this.isBaiduStreamingUrl(url);
  15826. if (this.waitInitialSeekBeforeStart) {
  15827. that.showLoadIng();
  15828. } else {
  15829. that.hideLoadIng();
  15830. }
  15831. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  15832. this.isOpenAB = false
  15833. //设置XComponent回调的context
  15834. if (!!this.mContext) {
  15835. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  15836. }
  15837. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  15838. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  15839. try {
  15840. this.mIjkMediaPlayer.reset();
  15841. Logger.info(TAG, 'IjkPlayer reset 成功');
  15842. } catch (error) {
  15843. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  15844. }
  15845. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15846. //设置debug模式(用于EQ日志采集)
  15847. this.mIjkMediaPlayer.setDebug(true);
  15848. //初始化配置
  15849. this.mIjkMediaPlayer.native_setup();
  15850. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  15851. this.applyCurrentVolume(true);
  15852. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  15853. const headers = new Map<string, string>();
  15854. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  15855. headers.set("Accept", "*/*");
  15856. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  15857. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  15858. //如果封面为空,则搜索封面
  15859. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  15860. }
  15861. // 仅对确实需要额外认证头的远程类型补充请求头。
  15862. // Navidrome/Plex/AudioStation/DaoLiYu 等类型的播放链接已自带认证参数,这里不要再误走 WebDAV 认证分支。
  15863. if (this.currentSong
  15864. && (isWebDavType(this.currentSong.type) || isJellyfinType(this.currentSong.type) || isEmbyType(this.currentSong.type))) {
  15865. Logger.info(`heanup 远程歌曲认证头构建 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  15866. if (this.currentSong.webdav_account_id) {
  15867. try {
  15868. const webdavManager = RemoteDriveManager.getInstance();
  15869. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  15870. if (webDavHeaders && webDavHeaders.size > 0) {
  15871. webDavHeaders.forEach((value, key) => headers.set(key, value));
  15872. Logger.info(`heanup 成功通过webdav_account_id获取并合并远程认证头`);
  15873. } else {
  15874. Logger.warn(`heanup 通过webdav_account_id未获取到额外认证头`);
  15875. }
  15876. } catch (error) {
  15877. const err = error as Error;
  15878. Logger.error(`heanup 获取远程认证头时出错: ${err.message}`);
  15879. }
  15880. } else {
  15881. Logger.error(`heanup 远程歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法构建认证头`);
  15882. }
  15883. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  15884. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  15885. }
  15886. // 统一设置带认证的请求头
  15887. // 百度类型也需要特殊请求头
  15888. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  15889. try {
  15890. const webdavManager = RemoteDriveManager.getInstance();
  15891. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  15892. baiduHeaders.forEach((value, key) => headers.set(key, value));
  15893. const headerSnapshot: Record<string, string> = {};
  15894. headers.forEach((value, key) => headerSnapshot[key] = value);
  15895. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  15896. } catch (error) {
  15897. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  15898. }
  15899. }
  15900. //设置视频源(先准备好认证头,再设置数据源)
  15901. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  15902. this.mIjkMediaPlayer.setDataSource(url);
  15903. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  15904. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  15905. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  15906. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  15907. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  15908. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  15909. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  15910. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  15911. // 缓冲和播放优化设置
  15912. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  15913. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  15914. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  15915. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  15916. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  15917. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  15918. // 网络相关设置
  15919. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  15920. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  15921. // 重连设置
  15922. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  15923. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  15924. } else if ((this.currentSong && isBaiduType(this.currentSong.type)) || isBaiduStreamingPlaybackUrl) {
  15925. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  15926. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  15927. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  15928. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  15929. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  15930. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  15931. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  15932. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  15933. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  15934. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  15935. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  15936. }
  15937. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  15938. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  15939. // }
  15940. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  15941. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  15942. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  15943. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  15944. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  15945. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  15946. //停止预读的最小帧数
  15947. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  15948. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  15949. // 设置其他缓冲相关选项
  15950. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  15951. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  15952. //启动预加载
  15953. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  15954. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  15955. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  15956. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  15957. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  15958. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  15959. // 因此需要播放器丢包,才不会累积延时
  15960. // 这个和第三个参数packet-buffering无关。
  15961. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  15962. // 无限制收流
  15963. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  15964. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  15965. // 屏幕常亮
  15966. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  15967. // 开启hls起播优化 默认是关闭的
  15968. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  15969. // 设置超时
  15970. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  15971. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  15972. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  15973. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  15974. // 变速播放
  15975. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  15976. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  15977. let Speed = this.mIjkMediaPlayer.getSpeed()
  15978. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  15979. //是否开启循环播放
  15980. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  15981. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  15982. (width: number, height: number, sar_num: number, sar_den: number) => {
  15983. if (height === 0) {
  15984. return;
  15985. }
  15986. const va = width / height;
  15987. const vpa = that.videoParentAspectRatio;
  15988. if (vpa > va) {
  15989. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  15990. } else {
  15991. that.videoWidth = '100%';
  15992. }
  15993. if (width && height) {
  15994. that.videoAspectRatio = width / height;
  15995. }
  15996. LogUtils.getInstance()
  15997. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  15998. if (!that.waitInitialSeekBeforeStart) {
  15999. that.hideLoadIng();
  16000. }
  16001. }
  16002. );
  16003. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  16004. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  16005. async () => {
  16006. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  16007. Logger.info(
  16008. TAG,
  16009. `[seek] prepared enter, waitInitial=${this.waitInitialSeekBeforeStart}, pendingMemory=${this.pendingMemorySeekPosition}, ` +
  16010. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16011. );
  16012. if (!this.waitInitialSeekBeforeStart) {
  16013. // 无记忆seek时,prepared后可直接隐藏加载
  16014. this.isPlayerLoading = false;
  16015. }
  16016. try {
  16017. //保存碰一碰分享的当前的歌曲
  16018. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  16019. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  16020. await this.initLyric(lyricPath);
  16021. const applyDuration = (durationMs: number): void => {
  16022. const cueTrackDuration = this.currentSong && isCueSplitItem(this.currentSong)
  16023. ? getCueTrackDuration(this.currentSong)
  16024. : 0;
  16025. const effectiveDuration = cueTrackDuration > 0 ? cueTrackDuration : durationMs;
  16026. if (effectiveDuration <= 0) {
  16027. return;
  16028. }
  16029. this.duration = effectiveDuration;
  16030. this.durationTime = Math.floor(effectiveDuration / 1000);
  16031. this.durationStringTime = secondToTime(this.durationTime);
  16032. this.totalTime = this.stringForTime(effectiveDuration);
  16033. if (this.currentSong) {
  16034. this.currentSong.duration = this.totalTime;
  16035. try {
  16036. this.avSessionController.setAVMetadataMusic(this.currentSong, effectiveDuration, this.lyricContent);
  16037. } catch (metaError) {
  16038. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  16039. }
  16040. }
  16041. };
  16042. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  16043. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  16044. return 0;
  16045. }
  16046. const httpRequest = http.createHttp();
  16047. try {
  16048. const response = await httpRequest.request(url, {
  16049. method: http.RequestMethod.GET,
  16050. connectTimeout: 8000,
  16051. readTimeout: 8000,
  16052. expectDataType: http.HttpDataType.STRING,
  16053. header: {
  16054. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  16055. 'Host': 'pan.baidu.com',
  16056. 'Referer': 'https://pan.baidu.com/disk/home',
  16057. 'Accept-Encoding': 'identity'
  16058. }
  16059. });
  16060. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  16061. return 0;
  16062. }
  16063. const text = response.result;
  16064. if (text.indexOf('#EXTM3U') < 0) {
  16065. return 0;
  16066. }
  16067. const lines = text.split('\n');
  16068. let totalSeconds = 0;
  16069. for (let i = 0; i < lines.length; i++) {
  16070. const line = lines[i].trim();
  16071. if (line.startsWith('#EXTINF:')) {
  16072. const colonIndex = line.indexOf(':');
  16073. if (colonIndex < 0) {
  16074. continue;
  16075. }
  16076. const content = line.substring(colonIndex + 1);
  16077. const commaIndex = content.indexOf(',');
  16078. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  16079. const seconds = Number(numberPart);
  16080. if (!Number.isNaN(seconds) && seconds > 0) {
  16081. totalSeconds += seconds;
  16082. }
  16083. }
  16084. }
  16085. if (totalSeconds > 0) {
  16086. return Math.floor(totalSeconds * 1000);
  16087. }
  16088. return 0;
  16089. } catch (fetchError) {
  16090. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  16091. return 0;
  16092. } finally {
  16093. httpRequest.destroy();
  16094. }
  16095. };
  16096. const fetchDurationFallback = async (): Promise<void> => {
  16097. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16098. if (durationMs > 0) {
  16099. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  16100. applyDuration(durationMs);
  16101. return;
  16102. }
  16103. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  16104. };
  16105. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  16106. Logger.info(
  16107. TAG,
  16108. `[seek] prepared duration snapshot, playerDuration=${preparedDuration}, metaDuration=${this.currentSong?.duration ?? ''}, ` +
  16109. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16110. );
  16111. if (preparedDuration > 0) {
  16112. applyDuration(preparedDuration);
  16113. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  16114. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16115. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  16116. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  16117. applyDuration(durationMs);
  16118. }
  16119. }
  16120. } else {
  16121. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  16122. if (metaDurationMs > 0) {
  16123. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  16124. applyDuration(metaDurationMs);
  16125. } else {
  16126. fetchDurationFallback();
  16127. }
  16128. }
  16129. setTimeout(() => {
  16130. this.avSessionController.initAvSession(false);
  16131. if (this.duration > 0) {
  16132. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  16133. }
  16134. this.setAvSessionListener();
  16135. this.updateSessionPlayState(true)
  16136. this.setCurrentPlayMode()
  16137. const cueTrackStartOffset = this.currentSong && isCueSplitItem(this.currentSong)
  16138. ? getCueTrackStartOffset(this.currentSong)
  16139. : 0;
  16140. if ((startOffset && startOffset > 0) || cueTrackStartOffset > 0) {//cue分轨播放
  16141. const cueSeekValue = cueTrackStartOffset > 0 && (!startOffset || startOffset <= 0) ? 0 : startOffset;
  16142. this.seekTo((cueSeekValue || 0) + "");
  16143. this.saveLastPlayList()
  16144. return
  16145. }
  16146. }, 500)
  16147. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16148. let timeoutPlay = 0
  16149. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16150. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  16151. timeoutPlay = 400
  16152. }
  16153. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  16154. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  16155. timeoutPlay = Math.max(timeoutPlay,
  16156. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  16157. }
  16158. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  16159. if (this.modeType === 0) { //文件夹
  16160. let parentPath = FileUtil.getParentPath(this.videoUrl)
  16161. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  16162. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  16163. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  16164. } else if (this.modeType === 1) { //媒体库
  16165. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  16166. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  16167. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  16168. } else if (this.modeType === 2) { //艺术家
  16169. if (this.currentSong?.artist) {
  16170. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  16171. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  16172. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  16173. }
  16174. } else if (this.modeType === 3) { //专辑
  16175. if (this.currentSong?.album) {
  16176. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  16177. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  16178. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  16179. }
  16180. }
  16181. const playerDuration = this.mIjkMediaPlayer.getDuration()
  16182. if (playerDuration > 0 && (!this.currentSong || !isCueSplitItem(this.currentSong))) {
  16183. this.duration = playerDuration
  16184. }
  16185. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  16186. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  16187. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  16188. let targetSeekPosition = memoryPosition;
  16189. if (this.isOpenJump) {
  16190. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  16191. }
  16192. this.pendingMemorySeekPosition = targetSeekPosition;
  16193. this.startInitialSeekGuardTimer('prepared-memory-seek');
  16194. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  16195. setTimeout(() => {
  16196. if (!this.waitInitialSeekBeforeStart) {
  16197. return;
  16198. }
  16199. this.restorePlaybackPosition();
  16200. }, timeoutPlay);
  16201. this.isFirstStartPlay = false
  16202. this.saveLastPlayList()
  16203. return
  16204. }
  16205. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  16206. if (this.mIjkMediaPlayer != null) {
  16207. let jumpTopTimeMs = this.jumpTopTime*1000;
  16208. if (jumpTopTimeMs <= this.duration) {
  16209. // 调用 seekTo 方法,跳到指定时间
  16210. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16211. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16212. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  16213. }
  16214. }, timeoutPlay)
  16215. } else {
  16216. // 提示用户无法跳过
  16217. ToastUtil.showToast('跳过时间超过视频时长');
  16218. }
  16219. }
  16220. } else {
  16221. this.jumpTopTime = 0
  16222. this.jumpEndTime = 0
  16223. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  16224. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  16225. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  16226. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  16227. //记忆播放(每一首都会记忆播放)
  16228. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16229. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16230. if (this.pendingMemorySeekPosition > 0 ||
  16231. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  16232. this.restorePlaybackPosition() //读取播放记忆功能
  16233. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  16234. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  16235. this.restorePlaybackPosition() //读取播放记忆功能
  16236. }
  16237. this.isFirstStartPlay = false
  16238. }, timeoutPlay)
  16239. } else {
  16240. this.isFirstStartPlay = false
  16241. }
  16242. }
  16243. this.saveLastPlayList()
  16244. } catch (error) {
  16245. let err: BusinessError = error as BusinessError;
  16246. console.error('onecold failed with err: ' + JSON.stringify(err));
  16247. if (this.waitInitialSeekBeforeStart) {
  16248. this.finishInitialSeekWait('prepared-exception', true);
  16249. }
  16250. }
  16251. }
  16252. );
  16253. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  16254. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  16255. (text: string) => {
  16256. }
  16257. );
  16258. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  16259. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  16260. () => {
  16261. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  16262. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  16263. // 异步调用playNext
  16264. this.playNext().catch(() => {
  16265. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16266. });
  16267. } else if (this.playType == 1) { //1:单片重复播放
  16268. this.CONTROL_PlayStatus = PlayStatus.INIT
  16269. that.startPlayOrResumePlay();
  16270. } else if (this.playType == 2) { //2:正常播放,单曲播完
  16271. that.showRePlay();
  16272. that.currentTime = that.stringForTime(that.getActiveDuration());
  16273. that.progressValue = this.PROGRESS_MAX_VALUE;
  16274. that.slideEnable = false;
  16275. that.stop();
  16276. // ToastUtil.showToast('开始重新播放')
  16277. } else if (this.playType == 3) { //3:随机播放
  16278. // 异步调用randomPlay
  16279. this.randomPlay().catch(() => {
  16280. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  16281. });
  16282. } else if (this.playType == 4) { //4:连续播放不循环
  16283. // 异步调用playNext
  16284. this.playNext().catch(() => {
  16285. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16286. });
  16287. }
  16288. }
  16289. );
  16290. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  16291. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  16292. (percent: number) => {
  16293. if (this.isDebug) {
  16294. const now = Date.now();
  16295. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  16296. this.lastBufferingLogTs = now;
  16297. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  16298. }
  16299. }
  16300. }
  16301. );
  16302. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  16303. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  16304. () => {
  16305. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  16306. that.logSeekTrace('seek-complete', undefined, undefined, true);
  16307. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  16308. setTimeout(() => {
  16309. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  16310. that.isSeekTo = false;
  16311. if (waitingInitialSeek) {
  16312. that.finishInitialSeekWait('seek-complete', true);
  16313. } else {
  16314. that.hideLoadIng();
  16315. }
  16316. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  16317. }
  16318. );
  16319. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  16320. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  16321. (what: number, extra: number) => {
  16322. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  16323. if (that.isSeekTraceActive()) {
  16324. Logger.info(
  16325. TAG,
  16326. `[seek] onInfo what=${what}, extra=${extra}, source=${that.lastSeekSource || 'unknown'}, ` +
  16327. `req=${that.lastSeekRequestMs}, url=${that.sanitizePlaybackUrl(that.videoUrl)}`
  16328. );
  16329. that.logSeekTrace(`info-${what}`, undefined, undefined, true);
  16330. }
  16331. if (!that.waitInitialSeekBeforeStart) {
  16332. that.hideLoadIng();
  16333. }
  16334. }
  16335. );
  16336. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  16337. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  16338. (what: number, extra: number) => {
  16339. this.finishInitialSeekWait('player-error', false);
  16340. this.stopProgressTask();
  16341. this.logSeekTrace(`error-${what}-${extra}`, undefined, undefined, true);
  16342. Logger.error(
  16343. TAG,
  16344. `[seek] onError what=${what}, extra=${extra}, url=${this.sanitizePlaybackUrl(this.videoUrl)}, ` +
  16345. `song=${JSON.stringify(this.currentSong)}`
  16346. );
  16347. // 检查是否为WebDAV播放错误
  16348. let isWebDavError = false;
  16349. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  16350. try {
  16351. const globalContext = GlobalContext.getContext();
  16352. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  16353. if (webDavAuthInfo) {
  16354. isWebDavError = true;
  16355. }
  16356. } catch (error) {
  16357. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  16358. }
  16359. }
  16360. if (isWebDavError) {
  16361. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  16362. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  16363. // this.currentWebDavAuthInfo = null;
  16364. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  16365. // 根据错误代码提供更具体的错误信息
  16366. let errorMessage = "WebDAV播放失败";
  16367. if (what === -1) { // 网络错误
  16368. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  16369. } else if (what === -1004) { // HTTP 404
  16370. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  16371. } else if (what === -1001) { // 超时
  16372. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  16373. } else if (what === -1003) { // 无法解析主机
  16374. errorMessage = "无法连接到WebDAV服务器";
  16375. }
  16376. ToastUtil.showToast(errorMessage);
  16377. } else {
  16378. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16379. !this.videoUrl.startsWith('http') &&
  16380. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  16381. !FileUtil.accessSync(this.videoUrl)) {
  16382. console.info('heanup 播放.文件不存在');
  16383. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  16384. }
  16385. }
  16386. that.hideLoadIng();
  16387. }
  16388. );
  16389. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  16390. this.mIjkMediaPlayer.setMessageListener();
  16391. // 应用均衡器设置
  16392. try {
  16393. const equalizerManager = EqualizerManager.getInstance();
  16394. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  16395. Logger.info(TAG, 'heanup 均衡器设置已应用');
  16396. this.markEqualizerApplied();
  16397. } catch (eqError) {
  16398. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  16399. this.eqApplying = false;
  16400. }
  16401. this.mIjkMediaPlayer.prepareAsync();
  16402. this.mIjkMediaPlayer.start();
  16403. }
  16404. //保存最后播放的那首歌和已经对应的播放列表
  16405. saveLastPlayList() {
  16406. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  16407. PreferencesUtil.putSync('LastMusicList', this.songList)
  16408. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  16409. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  16410. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  16411. }
  16412. // 清空播放记录
  16413. clearVideoHistory() {
  16414. this.table.clearPlayHistory((success: boolean, error?: string) => {
  16415. if (success) {
  16416. this.historyList = [];
  16417. this.updateListData(this.historyList)
  16418. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  16419. ToastUtil.showToast('清空播放记录成功')
  16420. } else {
  16421. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  16422. }
  16423. });
  16424. }
  16425. public async setAvSessionListener() {
  16426. if (!this.avSessionController) {
  16427. return;
  16428. }
  16429. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  16430. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  16431. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  16432. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  16433. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  16434. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  16435. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  16436. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  16437. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  16438. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  16439. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  16440. }
  16441. setLoopMode() {
  16442. let itype = this.playType + 1
  16443. if (itype >= 5) {
  16444. this.playType = 0
  16445. ToastUtil.showToast('连续循环播放')
  16446. } else if (itype === 1) {
  16447. this.playType = 1
  16448. ToastUtil.showToast('单曲循环')
  16449. } else if (itype === 2) {
  16450. this.playType = 2
  16451. ToastUtil.showToast('单曲播完')
  16452. } else if (itype === 3) {
  16453. this.playType = 3
  16454. ToastUtil.showToast('随机播放')
  16455. } else if (itype === 4) {
  16456. this.playType = 4
  16457. ToastUtil.showToast('连续播放不循环')
  16458. } else if (itype === 0) {
  16459. this.playType = 0
  16460. ToastUtil.showToast('连续循环播放')
  16461. }
  16462. PreferencesUtil.putSync('musicPlayType', this.playType)
  16463. this.setCurrentPlayMode()
  16464. }
  16465. private sessionSetLoopModeCallback = (mode: number) => {
  16466. if (this.mIjkMediaPlayer != null) {
  16467. ToastUtil.showToast('当前播放模式:' + mode)
  16468. Logger.info('onecold 当前播放模式= ' + mode)
  16469. let hmPlayMode = mode + 1
  16470. if (hmPlayMode >= 4) {
  16471. hmPlayMode = 0
  16472. }
  16473. if (hmPlayMode === 1) {
  16474. this.playType = 1
  16475. ToastUtil.showToast('单曲循环')
  16476. } else if (hmPlayMode === 0) {
  16477. this.playType = 2
  16478. ToastUtil.showToast('单曲播完')
  16479. } else if (hmPlayMode === 3) {
  16480. this.playType = 3
  16481. ToastUtil.showToast('随机播放')
  16482. } else if (hmPlayMode === 2) {
  16483. this.playType = 0
  16484. ToastUtil.showToast('连续循环播放')
  16485. } else if (hmPlayMode === 4) {
  16486. this.playType = 4
  16487. ToastUtil.showToast('连续播放不循环')
  16488. }
  16489. PreferencesUtil.putSync('musicPlayType', this.playType)
  16490. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  16491. let playBackState: avSession.AVPlaybackState = {
  16492. loopMode: hmPlayMode,
  16493. };
  16494. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  16495. console.info(`set setLoopMode AVPlaybackState successfully`);
  16496. }).catch((err: BusinessError) => {
  16497. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16498. });
  16499. }
  16500. }
  16501. setCurrentPlayMode() {
  16502. if (!this.avSessionController) {
  16503. return;
  16504. }
  16505. let mLoopMode = 0
  16506. switch (this.playType) {
  16507. case 0:
  16508. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  16509. break;
  16510. case 1:
  16511. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  16512. break;
  16513. case 2:
  16514. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  16515. break;
  16516. case 3:
  16517. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  16518. break;
  16519. case 4:
  16520. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  16521. break;
  16522. }
  16523. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  16524. let playBState: avSession.AVPlaybackState = {
  16525. loopMode: mLoopMode,
  16526. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  16527. };
  16528. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  16529. console.info(`set setLoopMode AVPlaybackState successfully`);
  16530. }).catch((err: BusinessError) => {
  16531. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16532. });
  16533. }
  16534. private applyRequestedPlayType(playType: number): void {
  16535. if (playType < 0 || playType > 4 || this.playType === playType) {
  16536. return
  16537. }
  16538. this.playType = playType
  16539. PreferencesUtil.putSync('musicPlayType', this.playType)
  16540. this.setCurrentPlayMode()
  16541. }
  16542. private sessionToggleFavoriteCallback = (assetId: string) => {
  16543. if (this.mIjkMediaPlayer != null && this.currentSong) {
  16544. console.info(`on toggleFavorite `);
  16545. // 应用收到收藏命令,进行收藏处理。
  16546. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  16547. this.doFav(this.currentSong)
  16548. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  16549. let playbackState: avSession.AVPlaybackState = {
  16550. isFavorite: !this.isFac,
  16551. };
  16552. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  16553. console.info(`SetAVPlaybackState successfully`);
  16554. }).catch((err: BusinessError) => {
  16555. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  16556. });
  16557. }
  16558. }
  16559. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  16560. device: avSession.OutputDeviceInfo) => {
  16561. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  16562. // 将 connectState 转换为可读的字符串
  16563. let stateName = 'UNKNOWN';
  16564. switch (connectState) {
  16565. case avSession.ConnectionState.STATE_CONNECTED:
  16566. stateName = 'CONNECTED(1)';
  16567. break;
  16568. case avSession.ConnectionState.STATE_DISCONNECTED:
  16569. stateName = 'DISCONNECTED(2)';
  16570. break;
  16571. case avSession.ConnectionState.STATE_CONNECTING:
  16572. stateName = 'CONNECTING(3)';
  16573. break;
  16574. default:
  16575. stateName = `OTHER(${connectState})`;
  16576. }
  16577. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  16578. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16579. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  16580. await this.startCasting();
  16581. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16582. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  16583. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  16584. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  16585. if (device) {
  16586. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  16587. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  16588. this.endCasting();
  16589. }
  16590. }
  16591. };
  16592. private async startCasting() {
  16593. try {
  16594. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  16595. // 获取原始的 AVCastController
  16596. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  16597. if (!avCastCtrl) {
  16598. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  16599. return;
  16600. }
  16601. this.castController = avCastCtrl;
  16602. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  16603. // 创建新的 CastController 封装器
  16604. this.castControllerWrapper = new CastController(avCastCtrl);
  16605. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  16606. // 设置回调函数
  16607. let callbacks: CastControllerCallbacks = {
  16608. onPlayNext: () => {
  16609. Logger.info('heanup CastController', '收到 playNext 回调');
  16610. this.playNext();
  16611. },
  16612. onPlayPrevious: () => {
  16613. Logger.info('heanup CastController', '收到 playPrevious 回调');
  16614. this.playPrevious();
  16615. },
  16616. onPositionChanged: (position: number) => {
  16617. this.positionChange(position);
  16618. },
  16619. onDurationChanged: (duration: number) => {
  16620. this.playDurationChange(duration);
  16621. }
  16622. };
  16623. this.castControllerWrapper.setCallbacks(callbacks);
  16624. Logger.info('heanup startCasting', '✅ 设置回调成功');
  16625. // 暂停本地播放
  16626. this.pause();
  16627. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  16628. // 初始化投播会话
  16629. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  16630. await this.castControllerWrapper.initAVCast(
  16631. this.songList,
  16632. this.curIndex,
  16633. this.mIjkMediaPlayer.getCurrentPosition(),
  16634. this.videoUrl,
  16635. this.getActiveDuration()
  16636. );
  16637. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  16638. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  16639. refToIsCasting?.set(true);
  16640. this.castSeek = true;
  16641. // 从 CastController 获取投播状态
  16642. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  16643. if (this.isCastPlaying) {
  16644. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16645. this.setIsPlaying(true);
  16646. this.updateSessionPlayState(true);
  16647. }
  16648. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  16649. } catch (error) {
  16650. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  16651. }
  16652. }
  16653. async changeCasting() {
  16654. Logger.info('heanup changeCasting', '切换投播');
  16655. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  16656. this.initQueueItem();
  16657. await this.prepare();
  16658. this.setPlaybackStateChangeListener();
  16659. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  16660. this.castSeek = true;
  16661. }
  16662. public endCasting() {
  16663. Logger.info('heanup endCasting', 'endCasting被调用');
  16664. this.avSessionController.getAvSession()?.stopCasting();
  16665. this.stopCast();
  16666. // 关闭文件描述符
  16667. if (this.castFile) {
  16668. try {
  16669. fs.closeSync(this.castFile);
  16670. this.castFile = undefined;
  16671. Logger.info('heanup endCasting', '关闭投播文件描述符');
  16672. } catch (error) {
  16673. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  16674. }
  16675. }
  16676. this.isCastPlaying = false;
  16677. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  16678. refToIsCasting?.set(false);
  16679. this.pause();
  16680. this.setIsPlaying(false);
  16681. // if (this.curIndex === this.curSource.index) {
  16682. // this.play
  16683. // this.seek(this.currentTime * 1000);
  16684. // this.setIsPlaying(true);
  16685. // } else {
  16686. // this.pauseVideo();
  16687. // this.setIsPlaying(false);
  16688. // }
  16689. }
  16690. public setIsPlaying(isPlayer: boolean) {
  16691. this.isPlaying = isPlayer;
  16692. // 发送播放状态变化事件给歌单详情页面
  16693. try {
  16694. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  16695. const currentFilePath = this.currentSong?.filePath || ''
  16696. const eventData: emitter.EventData = {
  16697. data: {
  16698. isPlaying: this.isPlaying,
  16699. curIndex: this.curIndex,
  16700. currentFilePath: currentFilePath
  16701. }
  16702. };
  16703. emitter.emit(eventPlaybackStatus, eventData)
  16704. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  16705. } catch (error) {
  16706. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  16707. }
  16708. }
  16709. private setPlaybackStateChangeListener(): void {
  16710. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  16711. // 我们需要通过其他方式来判断播放状态
  16712. // 1. 监听位置变化
  16713. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  16714. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  16715. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  16716. this.positionChange(playbackState.position.elapsedTime);
  16717. }
  16718. });
  16719. // 2. 监听时长变化
  16720. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  16721. const duration = playbackState?.extras?.duration;
  16722. if (typeof duration === 'number') {
  16723. this.playDurationChange(duration);
  16724. }
  16725. });
  16726. // 3. 监听所有状态变化(用于调试和状态判断)
  16727. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  16728. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  16729. // 检查是否有 state 字段(某些设备可能返回)
  16730. if (playbackState.state !== undefined) {
  16731. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  16732. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  16733. this.isCastPlaying = true;
  16734. }
  16735. }
  16736. });
  16737. // 4. 监听播放完成事件
  16738. this.castController?.on('endOfStream', this.playNextCallback);
  16739. this.castController?.on('playNext', this.playNextCallback);
  16740. this.castController?.on('playPrevious', this.playPreviousCallback);
  16741. // 5. 监听错误事件
  16742. this.castController?.on('error', (error: BusinessError) => {
  16743. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  16744. this.isCastPlaying = false;
  16745. });
  16746. }
  16747. private updateSessionPlayState(isPlay: boolean): void {
  16748. // if(!this.isBgPlayOpen)
  16749. // return
  16750. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  16751. : this.mIjkMediaPlayer.getCurrentPosition();
  16752. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  16753. this.setAVSessionPlayState({
  16754. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  16755. position: {
  16756. elapsedTime: elapsedTime,
  16757. updateTime: new Date().getTime()
  16758. }
  16759. });
  16760. }
  16761. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  16762. this.avSessionController.setAvSessionPlayState(playbackState)
  16763. }
  16764. private positionChange(position: number) {
  16765. this.currentTime2 = position / 1000;
  16766. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  16767. if (this.castControllerWrapper && this.isCastPlaying) {
  16768. this.updateCastProgress(position);
  16769. if (this.isSeekTo) {
  16770. this.isSeekTo = false;
  16771. }
  16772. }
  16773. }
  16774. private playDurationChange(duration: number) {
  16775. this.duration = duration;
  16776. this.durationTime = Math.floor(this.duration / 1000);
  16777. this.durationStringTime = secondToTime((this.durationTime));
  16778. if (this.castControllerWrapper && this.isCastPlaying) {
  16779. this.totalTime = this.stringForTime(this.duration);
  16780. }
  16781. }
  16782. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  16783. private reloadCasting = async () => {
  16784. Logger.info('heanup reloadCasting', '重新加载投播');
  16785. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  16786. this.initQueueItem();
  16787. await this.prepare();
  16788. };
  16789. public playNextCallback = (): void => {
  16790. this.playNext().catch(() => {
  16791. Logger.error('heanup playNextCallback', `播放下一首失败`);
  16792. });
  16793. };
  16794. public playPreviousCallback = (): void => {
  16795. this.playPrevious().catch(() => {
  16796. Logger.error('heanup playNextCallback', `播放上一首失败`);
  16797. });
  16798. };
  16799. async prepare() {
  16800. try {
  16801. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  16802. await this.castController?.prepare(this.castItem);
  16803. Logger.info('heanup prepare', '投播prepare成功');
  16804. await this.castController?.start(this.castItem);
  16805. Logger.info('heanup prepare', '投播start成功');
  16806. // 投播启动成功,设置为投播状态
  16807. this.isCastPlaying = true;
  16808. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  16809. } catch (error) {
  16810. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  16811. this.isCastPlaying = false;
  16812. }
  16813. }
  16814. public initQueueItem() {
  16815. let item = this.songList[this.curIndex];
  16816. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  16817. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  16818. let isStreaming = this.isUrl(this.videoUrl);
  16819. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  16820. // 关闭之前的文件描述符
  16821. if (this.castFile) {
  16822. try {
  16823. fs.closeSync(this.castFile);
  16824. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  16825. } catch (error) {
  16826. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  16827. }
  16828. }
  16829. let description: avSession.AVMediaDescription = {
  16830. assetId: 'AUDIO-' + item.filePath,
  16831. title: item.name,
  16832. artist: item.artist || '',
  16833. // 该字段大写,音频'AUDIO',视频'VIDEO'
  16834. mediaType: 'AUDIO',
  16835. mediaSize: item.videoSize,
  16836. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  16837. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  16838. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  16839. duration: this.duration,
  16840. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  16841. appName: this.appName,
  16842. lyricContent: item.lyricContent,
  16843. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  16844. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  16845. };
  16846. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  16847. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  16848. if (isStreaming) {
  16849. // 流媒体地址使用 mediaUri
  16850. description.mediaUri = this.videoUrl;
  16851. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  16852. } else {
  16853. // 本地文件使用 fdSrc
  16854. const localPath = this.videoUrl || item.filePath;
  16855. let uri = fileUri.getUriFromPath(localPath);
  16856. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  16857. let fdSrc: media.AVFileDescriptor = {
  16858. fd: this.castFile.fd
  16859. };
  16860. description.fdSrc = fdSrc;
  16861. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  16862. }
  16863. this.castItem = {
  16864. itemId: this.curIndex,
  16865. description: description
  16866. };
  16867. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  16868. title: description.title,
  16869. mediaType: description.mediaType,
  16870. hasMediaUri: !!description.mediaUri,
  16871. hasFdSrc: !!description.fdSrc,
  16872. duration: description.duration
  16873. })}`);
  16874. }
  16875. // 判断是否是 URL 或流媒体地址
  16876. private isUrl(str: string): boolean {
  16877. if (!str) {
  16878. return false;
  16879. }
  16880. // 检查常见的流媒体协议
  16881. if (str.startsWith('http://') || str.startsWith('https://') ||
  16882. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  16883. str.startsWith('rtp://') || str.startsWith('mms://')) {
  16884. return true;
  16885. }
  16886. // 扩展的URL正则表达式,支持多种协议
  16887. const urlPattern = new RegExp(
  16888. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  16889. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  16890. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  16891. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  16892. 'localhost)' + // 或localhost
  16893. '(\\:\\d+)?' + // 端口号(可选)
  16894. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  16895. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  16896. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  16897. 'i' // 不区分大小写
  16898. );
  16899. return urlPattern.test(str);
  16900. }
  16901. async stopCast() {
  16902. try {
  16903. // 使用 CastController 释放资源
  16904. if (this.castControllerWrapper) {
  16905. await this.castControllerWrapper.releaseAVCast();
  16906. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  16907. }
  16908. // 清空引用
  16909. this.castControllerWrapper = undefined;
  16910. this.castController = undefined;
  16911. this.castItem = undefined;
  16912. this.castFile = undefined;
  16913. } catch (error) {
  16914. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  16915. }
  16916. }
  16917. private sessionPlayCallback = (): void => {
  16918. this.playOrPause()
  16919. };
  16920. private sessionPauseCallback = (): void => {
  16921. this.pause()
  16922. };
  16923. private async playOrPause() {
  16924. if (!this.debounce()) {
  16925. return;
  16926. }
  16927. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  16928. await this.pause();
  16929. } else {
  16930. // 如果是投播模式,使用 CastController 的 play 方法
  16931. if (this.castControllerWrapper && this.isCastPlaying) {
  16932. try {
  16933. Logger.info('heanup playOrPause', '投播模式播放');
  16934. await this.castControllerWrapper.setPlaying();
  16935. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16936. this.setIsPlaying(true);
  16937. this.updateSessionPlayState(true);
  16938. Logger.info('heanup playOrPause', '投播播放成功');
  16939. this.playChange();
  16940. } catch (error) {
  16941. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  16942. }
  16943. } else {
  16944. console.info('onecold startPlayOrResumePlay 11064')
  16945. this.startPlayOrResumePlay();
  16946. this.playChange()
  16947. }
  16948. }
  16949. }
  16950. private sessionPlayNextCallback = (): void => {
  16951. this.playNext().catch(() => {
  16952. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  16953. });
  16954. };
  16955. private sessionPlayPreviousCallback = (): void => {
  16956. this.playPrevious().catch(() => {
  16957. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  16958. });
  16959. };
  16960. private sessionStopCallback = (): void => {
  16961. this.stop()
  16962. };
  16963. private sessionFastForwardCallback = async (time?: number) => {
  16964. if (!time) {
  16965. return;
  16966. }
  16967. let curPosition: number;
  16968. if (this.castController && this.isCastPlaying) {
  16969. // 投播模式,使用UI显示的时间
  16970. curPosition = this.currentTime2 * 1000;
  16971. } else if (this.mIjkMediaPlayer != null) {
  16972. // 本地播放器模式
  16973. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16974. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16975. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  16976. }
  16977. } else {
  16978. return;
  16979. }
  16980. let seeTime = curPosition + time * 1000;
  16981. // 限制 seekValue 在合法范围内
  16982. if (seeTime < 0) {
  16983. seeTime = 0;
  16984. } else if (seeTime > this.duration) {
  16985. seeTime = this.duration;
  16986. }
  16987. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  16988. this.setSeekToActionProgress(seeTime);
  16989. await this.seekTo(seeTime + "");
  16990. };
  16991. private getActiveDuration(): number {
  16992. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16993. const cueDuration = getCueTrackDuration(this.currentSong);
  16994. if (cueDuration > 0) {
  16995. return cueDuration;
  16996. }
  16997. }
  16998. let duration = this.mIjkMediaPlayer.getDuration();
  16999. if (this.castControllerWrapper && this.isCastPlaying) {
  17000. return this.duration > 0 ? this.duration : duration;
  17001. }
  17002. if (duration <= 0 && this.duration > 0) {
  17003. duration = this.duration;
  17004. }
  17005. return duration;
  17006. }
  17007. private isBaiduStreamingUrl(url: string): boolean {
  17008. if (StrUtil.isEmpty(url)) {
  17009. return false;
  17010. }
  17011. const lowerUrl = url.toLowerCase();
  17012. return lowerUrl.includes('pan.baidu.com/rest/2.0/xpan/file') && lowerUrl.includes('method=streaming');
  17013. }
  17014. @Builder
  17015. InlineSpectrumView() {
  17016. SpectrumView({
  17017. isVisible: this.currentSwiperIndex === 0,
  17018. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  17019. })
  17020. .width( '83%')
  17021. .height(this.isCoverOpacity() ? 80 : 100)
  17022. .margin({bottom: 3 })
  17023. .clip(true)
  17024. .zIndex(-2)
  17025. .onClick(()=>{
  17026. this.cycleSpectrumMode();
  17027. })
  17028. }
  17029. private cycleSpectrumMode(): void {
  17030. const modeNames: string[] = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  17031. if (modeNames.length <= 0) {
  17032. return;
  17033. }
  17034. const nextIndex: number = (this.spectrumModeIndex + 1) % modeNames.length;
  17035. this.spectrumModeIndex = nextIndex;
  17036. PreferencesUtil.putSync('spectrumModeIndex', nextIndex);
  17037. AppStorage.setOrCreate<number>('spectrumMode', nextIndex);
  17038. Logger.info('heanup-LocalMusic', `频谱特效已顺序切换为: ${modeNames[nextIndex]}`);
  17039. }
  17040. private getSongDurationMs(song?: VideoItem): number {
  17041. if (!song || !song.duration) {
  17042. return 0;
  17043. }
  17044. const raw = song.duration.trim();
  17045. if (!raw) {
  17046. return 0;
  17047. }
  17048. const parts = raw.split(':').map((part) => Number(part));
  17049. if (parts.some((part) => Number.isNaN(part))) {
  17050. return 0;
  17051. }
  17052. let seconds = 0;
  17053. if (parts.length === 3) {
  17054. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  17055. } else if (parts.length === 2) {
  17056. seconds = parts[0] * 60 + parts[1];
  17057. } else if (parts.length === 1) {
  17058. seconds = parts[0];
  17059. }
  17060. return seconds > 0 ? seconds * 1000 : 0;
  17061. }
  17062. private updateCastProgress(position: number): void {
  17063. const duration = this.getActiveDuration();
  17064. if (duration <= 0) {
  17065. return;
  17066. }
  17067. this.slideEnable = true;
  17068. let pos = (position / duration) * 100;
  17069. if (pos > this.PROGRESS_MAX_VALUE) {
  17070. this.progressValue = this.PROGRESS_MAX_VALUE;
  17071. } else if (pos < 0) {
  17072. this.progressValue = 0;
  17073. } else {
  17074. this.progressValue = pos;
  17075. }
  17076. this.totalTime = this.stringForTime(duration);
  17077. if (position > duration) {
  17078. position = duration;
  17079. }
  17080. this.isCurrentTime = true;
  17081. this.currentTime = this.stringForTime(position);
  17082. this.isCurrentTime = false;
  17083. const lyricPosition = position + this.timeOffset * 1000;
  17084. this.updateLyricPosition(lyricPosition);
  17085. }
  17086. /**
  17087. * Gesture method onActionUpdate.
  17088. *
  17089. * @param event Gesture event.手势拖动设置快进和后退
  17090. */
  17091. private setSeekToActionProgress(position: number) {
  17092. // 投播模式使用this.duration,本地模式使用播放器获取
  17093. let duration = this.getActiveDuration();
  17094. let pos = 0;
  17095. if (duration > 0) {
  17096. this.slideEnable = true;
  17097. let curPercent = position / duration;
  17098. pos = curPercent * 100;
  17099. if (pos > this.PROGRESS_MAX_VALUE) {
  17100. this.progressValue = this.PROGRESS_MAX_VALUE
  17101. } else {
  17102. this.progressValue = pos;
  17103. }
  17104. }
  17105. // LogUtils.getInstance()
  17106. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  17107. this.totalTime = this.stringForTime(duration);
  17108. if (position > duration) {
  17109. position = duration;
  17110. }
  17111. this.isCurrentTime = true;
  17112. this.currentTime = this.stringForTime(position);
  17113. this.isCurrentTime = false
  17114. }
  17115. private sessionRewindCallback = async (time?: number) => {
  17116. if (!time) {
  17117. return;
  17118. }
  17119. let curPosition: number;
  17120. if (this.castController && this.isCastPlaying) {
  17121. // 投播模式,使用UI显示的时间
  17122. curPosition = this.currentTime2 * 1000;
  17123. } else if (this.mIjkMediaPlayer != null) {
  17124. // 本地播放器模式
  17125. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17126. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17127. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17128. }
  17129. } else {
  17130. return;
  17131. }
  17132. let seeTime = curPosition - time * 1000;
  17133. // 限制 seekValue 在合法范围内
  17134. if (seeTime < 0) {
  17135. seeTime = 0;
  17136. } else if (seeTime > this.duration) {
  17137. seeTime = this.duration;
  17138. }
  17139. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  17140. this.setSeekToActionProgress(seeTime);
  17141. await this.seekTo(seeTime + "");
  17142. };
  17143. private sessionSeekCallback = async (seekTime: number) => {
  17144. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  17145. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  17146. await this.seekTo(seekTime + "");
  17147. };
  17148. private async getFileSize(filePath: string): Promise<number> {
  17149. try {
  17150. const stat = await fs.stat(filePath);
  17151. return stat.size;
  17152. } catch (err) {
  17153. console.error('Failed to get file size: ' + err.message);
  17154. return 0;
  17155. }
  17156. }
  17157. private async pause() {
  17158. // 如果是投播模式,使用 CastController 的 pause 方法
  17159. if (this.castControllerWrapper && this.isCastPlaying) {
  17160. try {
  17161. Logger.info('heanup pause', '投播模式暂停');
  17162. await this.castControllerWrapper.setPause();
  17163. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17164. this.setIsPlaying(false);
  17165. this.updateSessionPlayState(false);
  17166. Logger.info('heanup pause', '投播暂停成功');
  17167. } catch (error) {
  17168. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  17169. }
  17170. } else if (this.mIjkMediaPlayer.isPlaying()) {
  17171. // 本地播放器模式
  17172. this.savePlaybackPosition();
  17173. this.mIjkMediaPlayer.pause();
  17174. this.setProgress();
  17175. this.mDestroyPage = true;
  17176. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17177. this.updateSessionPlayState(false)
  17178. this.playChange()
  17179. if (this.pipController) {
  17180. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  17181. PiPWindow.PiPControlStatus.PAUSE);
  17182. }
  17183. }
  17184. }
  17185. private stop() {
  17186. this.clearInitialSeekGuardTimer();
  17187. this.waitInitialSeekBeforeStart = false;
  17188. this.pendingMemorySeekPosition = 0;
  17189. this.isPlayerLoading = false;
  17190. this.savePlaybackPosition();
  17191. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17192. this.mIjkMediaPlayer.stop();
  17193. this.mIjkMediaPlayer.release();
  17194. this.stopProgressTask();
  17195. this.updateSessionPlayState(false)
  17196. this.playChange()
  17197. this.watchStatus();
  17198. }
  17199. //保持记忆播放功能
  17200. private savePlaybackPosition() {
  17201. if (this.mIjkMediaPlayer != null) {
  17202. let position = this.mIjkMediaPlayer.getCurrentPosition();
  17203. // ToastUtil.showToast('保存记忆播放 = ' + position)
  17204. let duration = this.mIjkMediaPlayer.getDuration();
  17205. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17206. position = Math.max(0, position - getCueTrackStartOffset(this.currentSong));
  17207. const cueDuration = getCueTrackDuration(this.currentSong);
  17208. if (cueDuration > 0) {
  17209. duration = cueDuration;
  17210. }
  17211. }
  17212. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  17213. // 如果播放位置接近视频末尾,则保存 position 为 0
  17214. const playbackPosition = (duration - position < threshold) ? 0 : position;
  17215. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  17216. PreferencesUtil.putSync(memoryKey, playbackPosition);
  17217. }
  17218. }
  17219. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  17220. if (song && isRemoteCloudType(song.type)) {
  17221. const accountId = song.webdav_account_id || 'unknown';
  17222. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  17223. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  17224. }
  17225. if (song && isCueSplitItem(song)) {
  17226. return `memory_play_local_cue:${song.filePath}`;
  17227. }
  17228. return playbackUrl || '';
  17229. }
  17230. private getPlaybackMemoryKey(): string {
  17231. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  17232. }
  17233. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  17234. if (token !== this.remoteRestoreSeekToken) {
  17235. return;
  17236. }
  17237. if (!this.mIjkMediaPlayer || position <= 0) {
  17238. if (this.waitInitialSeekBeforeStart) {
  17239. this.finishInitialSeekWait('invalid-memory-position', true);
  17240. }
  17241. return;
  17242. }
  17243. const duration = this.getActiveDuration();
  17244. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  17245. let safePosition = position;
  17246. if (duration > 0) {
  17247. safePosition = Math.max(0, Math.min(position, duration - 500));
  17248. } else {
  17249. safePosition = Math.max(0, position);
  17250. }
  17251. if (safePosition <= 0) {
  17252. if (this.waitInitialSeekBeforeStart) {
  17253. this.finishInitialSeekWait('memory-position-too-small', true);
  17254. }
  17255. return;
  17256. }
  17257. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  17258. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  17259. }
  17260. this.seekTo(safePosition + "", retryCount === 0 ? 'remote-memory-restore' : 'remote-memory-retry');
  17261. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  17262. return;
  17263. }
  17264. setTimeout(() => {
  17265. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  17266. return;
  17267. }
  17268. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  17269. if (Math.abs(latestPos - safePosition) <= 1500) {
  17270. return;
  17271. }
  17272. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  17273. }, this.remoteMemorySeekRetryIntervalMs);
  17274. }
  17275. //获取记忆播放功能
  17276. private restorePlaybackPosition() {
  17277. const position: number = this.pendingMemorySeekPosition > 0 ?
  17278. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  17279. if (!this.mIjkMediaPlayer || position <= 0) {
  17280. if (this.waitInitialSeekBeforeStart) {
  17281. this.finishInitialSeekWait('no-memory-position', true);
  17282. }
  17283. return;
  17284. }
  17285. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17286. if (isRemoteSong && this.videoUrl.includes('://')) {
  17287. const token = this.remoteRestoreSeekToken;
  17288. this.restoreRemotePlaybackPositionSafely(position, token);
  17289. return;
  17290. }
  17291. const duration = this.getActiveDuration();
  17292. let safePosition = position;
  17293. if (duration > 0) {
  17294. safePosition = Math.max(0, Math.min(position, duration - 500));
  17295. } else {
  17296. safePosition = Math.max(0, position);
  17297. }
  17298. if (safePosition <= 0) {
  17299. if (this.waitInitialSeekBeforeStart) {
  17300. this.finishInitialSeekWait('memory-position-too-small', true);
  17301. }
  17302. return;
  17303. }
  17304. this.seekTo(safePosition + "", isRemoteSong ? 'remote-memory-restore' : 'memory-restore');
  17305. }
  17306. private async seekTo(value: string, source: string = 'internal') {
  17307. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  17308. // ToastUtil.showToast('wma格式不支持拖动快进。')
  17309. // return
  17310. // }
  17311. // 如果是投播模式,使用 CastController 的 seek 方法
  17312. if (this.castControllerWrapper && this.isCastPlaying) {
  17313. try {
  17314. let seekPos = Number.parseInt(value);
  17315. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17316. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17317. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17318. const duration = this.getActiveDuration();
  17319. if (duration > 0) {
  17320. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17321. }
  17322. if (cueTrackItem) {
  17323. seekPos += cueTrackStartOffset;
  17324. if (cueTrackEndOffset > cueTrackStartOffset) {
  17325. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17326. }
  17327. }
  17328. this.beginSeekTrace(source, seekPos);
  17329. this.isSeekTo = true;
  17330. Logger.info(
  17331. TAG,
  17332. `[seek] cast dispatch, source=${source}, target=${seekPos}, duration=${duration}, ` +
  17333. `uiDuration=${this.duration}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17334. );
  17335. // 检查是否接近末尾
  17336. if (this.duration > 0 && seekPos >= this.duration - 500) {
  17337. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  17338. }
  17339. await this.castControllerWrapper.seek(seekPos);
  17340. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  17341. } catch (error) {
  17342. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  17343. }
  17344. } else {
  17345. // 本地播放器模式
  17346. let seekPos = Number.parseInt(value);
  17347. if (Number.isNaN(seekPos)) {
  17348. return;
  17349. }
  17350. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17351. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17352. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17353. const duration = this.getActiveDuration();
  17354. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17355. if (duration > 0) {
  17356. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17357. } else if (seekPos < 0) {
  17358. seekPos = 0;
  17359. }
  17360. if (cueTrackItem) {
  17361. seekPos += cueTrackStartOffset;
  17362. if (cueTrackEndOffset > cueTrackStartOffset) {
  17363. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17364. }
  17365. }
  17366. if (isRemoteSong && duration <= 0 && seekPos > 0) {
  17367. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${seekPos}ms`);
  17368. return;
  17369. }
  17370. if (isRemoteSong && duration <= 0) {
  17371. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  17372. }
  17373. if (source !== 'internal') {
  17374. this.beginSeekTrace(source, seekPos);
  17375. }
  17376. this.isSeekTo = true
  17377. try {
  17378. if (isRemoteSong || source !== 'internal' || this.isSeekTraceActive()) {
  17379. Logger.info(
  17380. TAG,
  17381. `[seek] player dispatch, source=${source}, target=${seekPos}, activeDuration=${duration}, ` +
  17382. `playerDuration=${this.mIjkMediaPlayer.getDuration()}, current=${this.mIjkMediaPlayer.getCurrentPosition()}, ` +
  17383. `isPlaying=${this.mIjkMediaPlayer.isPlaying()}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17384. );
  17385. }
  17386. this.mIjkMediaPlayer.seekTo(seekPos + "");
  17387. this.logSeekTrace('seek-dispatched', this.mIjkMediaPlayer.getCurrentPosition(), this.mIjkMediaPlayer.getDuration(), true);
  17388. this.setProgress()
  17389. } catch (error) {
  17390. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  17391. this.logSeekTrace('seek-dispatch-error', undefined, undefined, true);
  17392. } finally {
  17393. this.isSeekTo = false
  17394. }
  17395. }
  17396. }
  17397. // 添加到下一首播放
  17398. private addToNextPlay(song: VideoItem) {
  17399. if (!this.debounce()) {
  17400. return;
  17401. }
  17402. if (this.currentSong) {
  17403. if (this.currentSong === song) {
  17404. ToastUtil.showToast('当前已经在播放这首歌了!')
  17405. return
  17406. }
  17407. }
  17408. // 如果未开始播放或队列为空
  17409. if (this.curIndex === -1 || this.songList.length === 0) {
  17410. this.songList = [song];
  17411. this.curIndex = 0;
  17412. this.doPlay(song)
  17413. return;
  17414. }
  17415. // 插入到当前索引+1的位置
  17416. const insertPos = this.curIndex + 1;
  17417. this.songList.splice(insertPos, 0, song);
  17418. this.songList = [...this.songList]; // 触发状态更新
  17419. this.sonDataSource.pushArrayData(this.songList)
  17420. ToastUtil.showToast('已添加至下一首播放')
  17421. }
  17422. //后退10s,可再设置设置默认几秒
  17423. async backForward() {
  17424. // 如果是投播模式,从currentTime2获取当前位置
  17425. let pos: number;
  17426. if (this.castController && this.isCastPlaying) {
  17427. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17428. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  17429. } else if (this.mIjkMediaPlayer) {
  17430. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17431. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17432. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17433. }
  17434. } else {
  17435. return;
  17436. }
  17437. let value = pos - Number(this.fastForwardSeconds) * 1000;
  17438. if (value < 0) {
  17439. value = 0;
  17440. }
  17441. await this.seekTo(value + "");
  17442. }
  17443. //快进10s,可再设置设置默认几秒
  17444. async fastForward() {
  17445. // 如果是投播模式,从currentTime2获取当前位置
  17446. let pos: number;
  17447. if (this.castController && this.isCastPlaying) {
  17448. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17449. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  17450. } else if (this.mIjkMediaPlayer) {
  17451. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17452. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17453. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17454. }
  17455. } else {
  17456. return;
  17457. }
  17458. let value = pos + Number(this.fastForwardSeconds) * 1000;
  17459. // 限制不超过总时长
  17460. if (this.duration > 0 && value > this.duration) {
  17461. value = this.duration;
  17462. }
  17463. await this.seekTo(value + "");
  17464. }
  17465. //下一个
  17466. private async playNext() {
  17467. this.lyricController.setLyric(null)
  17468. this.lyricControllerXF.setLyric(null)
  17469. this.lyricControllerSingle.setLyric(null)
  17470. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  17471. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  17472. if (!this.debounce()) {
  17473. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  17474. return;
  17475. }
  17476. Logger.info('heanup playNext', `playType=${this.playType}`);
  17477. if (this.playType == 3) { //3:随机播放
  17478. Logger.info('heanup playNext', '随机播放模式');
  17479. await this.randomPlay()
  17480. return;
  17481. }
  17482. if (ArrayUtil.isNotEmpty(this.songList)) {
  17483. if (this.curIndex >= this.songList.length - 1) {
  17484. // playType=0 或 3: 尝试加载更多或循环
  17485. // playType=4: 不循环,检查是否是最后一首
  17486. if (this.playType == 4) {
  17487. // 连续播放不循环模式:到达最后一首时停止播放
  17488. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  17489. ToastUtil.showToast('已经是最后一首了');
  17490. this.showRePlay();
  17491. this.currentTime = this.stringForTime(this.getActiveDuration());
  17492. this.progressValue = this.PROGRESS_MAX_VALUE;
  17493. this.slideEnable = false;
  17494. this.stop();
  17495. return;
  17496. }
  17497. await this.tryLoadNextPageForPlayback();
  17498. }
  17499. if (this.curIndex >= this.songList.length - 1) {
  17500. // playType=4 不应该执行到这里,因为上面已经return了
  17501. this.curIndex = 0;
  17502. } else {
  17503. this.curIndex++;
  17504. }
  17505. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17506. this.currentSong = this.songList[this.curIndex];
  17507. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17508. const nextLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17509. const nextUrl = await this.resolvePlaybackUrlForCurrentSong('playNext');
  17510. if (!nextUrl) {
  17511. if (nextLoading) {
  17512. this.hideLoadIng();
  17513. }
  17514. return;
  17515. }
  17516. this.videoUrl = nextUrl;
  17517. this.artist = this.songList[this.curIndex].artist
  17518. this.name = this.songList[this.curIndex].name
  17519. //this.cover = this.songList[this.curIndex].pixelMapPath
  17520. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  17521. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  17522. // 如果是投播模式,使用 CastController 播放下一首
  17523. if (this.castControllerWrapper) {
  17524. console.info('heanup playNext', '使用 CastController 播放下一首');
  17525. try {
  17526. const nextDuration = this.getSongDurationMs(this.currentSong);
  17527. if (nextDuration > 0) {
  17528. this.duration = nextDuration;
  17529. this.durationTime = Math.floor(nextDuration / 1000);
  17530. this.durationStringTime = secondToTime(this.durationTime);
  17531. this.totalTime = this.stringForTime(nextDuration);
  17532. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  17533. }
  17534. this.updateCastProgress(0);
  17535. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  17536. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17537. if (nextLoading) {
  17538. this.hideLoadIng();
  17539. }
  17540. console.info('heanup playNext', 'CastController 播放下一首成功');
  17541. return;
  17542. } catch (error) {
  17543. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  17544. // 如果投播失败,回退到本地播放
  17545. this.isCastPlaying = false;
  17546. }
  17547. }
  17548. // 本地播放器模式,需要先stop
  17549. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17550. this.stop();
  17551. if (nextLoading) {
  17552. this.showLoadIng();
  17553. }
  17554. this.changeImageAnimation()
  17555. }
  17556. }
  17557. changeImageAnimation() {
  17558. if(this.openSkipSongAnimate){
  17559. // 第一步:淡出动画
  17560. this.getUIContext()?.animateTo({
  17561. duration: 500,
  17562. curve: Curve.EaseOut,
  17563. }, () => {
  17564. this.opacityValueImage = 0.1;
  17565. if(this.isCoverRectangle){
  17566. this.scaleValueImage = 0.88
  17567. }
  17568. });
  17569. // 第二步:切换图片后淡入
  17570. setTimeout(() => {
  17571. this.cover = this.songList[this.curIndex].pixelMapPath
  17572. this.getUIContext()?.animateTo({
  17573. duration: 500,
  17574. curve: Curve.EaseIn,
  17575. }, () => {
  17576. this.opacityValueImage = 1;
  17577. this.scaleValueImage = 1 // 图标恢复到原始大小
  17578. this.startPlayOrResumePlay()
  17579. });
  17580. }, 500);
  17581. }else{
  17582. this.cover = this.songList[this.curIndex].pixelMapPath
  17583. this.startPlayOrResumePlay()
  17584. }
  17585. }
  17586. // 内部方法:提前缓存下一首
  17587. private async preloadNextSongInternal(): Promise<void> {
  17588. // 随机模式下传递已播放索引集合
  17589. if (this.playType === 3) {
  17590. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17591. this.songList,
  17592. this.curIndex,
  17593. this.playType,
  17594. this.playedIndices
  17595. );
  17596. } else {
  17597. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17598. this.songList,
  17599. this.curIndex,
  17600. this.playType
  17601. );
  17602. }
  17603. }
  17604. // 存储已播放的歌曲索引
  17605. private playedIndices: Set<number> = new Set();
  17606. // 存储已播放的本地歌曲路径(随机播放去重用)
  17607. private playedLocalFilePaths: Set<string> = new Set();
  17608. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  17609. private randomPlayHistory: VideoItem[] = [];
  17610. //随机播放
  17611. private async randomPlay() {
  17612. // if (!this.debounce()) {
  17613. // return;
  17614. // }
  17615. // 网盘模式: 渐进式扩展播放库的随机播放
  17616. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  17617. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  17618. if (isCloudSong) {
  17619. // 阈值常量
  17620. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  17621. const LOAD_MORE_PAGES = 3; // 每次加载页数
  17622. // 获取网盘播放列表
  17623. const navidromeList = getNavidromeVideoItems();
  17624. const webdavList = getWebdavVideoItems();
  17625. const isNavidrome = navidromeList.length > 0;
  17626. const remoteList = isNavidrome ? navidromeList : webdavList;
  17627. if (remoteList.length > 0) {
  17628. // 将当前歌加入历史栈
  17629. if (this.currentSong) {
  17630. this.randomPlayHistory.unshift(this.currentSong);
  17631. if (this.randomPlayHistory.length > 50) {
  17632. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  17633. }
  17634. // 标记当前歌曲为已播放
  17635. markAsPlayed(this.currentSong.filePath);
  17636. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  17637. }
  17638. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  17639. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  17640. const totalCount = remoteList.length;
  17641. const playedCount = isNavidrome ? getPlayedCount() : 0;
  17642. Logger.info(TAG, `randomPlay(网盘模式): 总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  17643. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  17644. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  17645. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  17646. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  17647. if (loadSuccess) {
  17648. // 重新获取未播放数量
  17649. unplayedCount = getUnplayedCount();
  17650. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  17651. }
  17652. }
  17653. // 从未播放歌曲中随机选择
  17654. let candidates: VideoItem[];
  17655. if (isNavidrome) {
  17656. candidates = getUnplayedSongs();
  17657. // 如果全部播放完,重置已播放记录
  17658. if (candidates.length === 0) {
  17659. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  17660. clearPlayedHistory();
  17661. // 排除当前歌曲
  17662. const currentFilePath = this.currentSong?.filePath;
  17663. candidates = currentFilePath
  17664. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  17665. : getNavidromeVideoItems();
  17666. }
  17667. } else {
  17668. // WebDAV模式:简单排除当前歌曲
  17669. const currentFilePath = this.currentSong?.filePath;
  17670. candidates = currentFilePath
  17671. ? remoteList.filter(v => v.filePath !== currentFilePath)
  17672. : remoteList;
  17673. }
  17674. if (candidates.length > 0) {
  17675. const randomIndex = Math.floor(Math.random() * candidates.length);
  17676. const randomSong = candidates[randomIndex];
  17677. // 标记为已播放
  17678. if (isNavidrome) {
  17679. markAsPlayed(randomSong.filePath);
  17680. }
  17681. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  17682. // 将选中的歌曲加入播放列表(如果不存在)
  17683. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  17684. if (nextIndex < 0) {
  17685. this.songList = [...this.songList, randomSong];
  17686. this.sonDataSource.pushArrayData(this.songList);
  17687. nextIndex = this.songList.length - 1;
  17688. }
  17689. this.curIndex = nextIndex;
  17690. this.playedIndices.add(this.curIndex);
  17691. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17692. this.stop();
  17693. this.currentSong = randomSong;
  17694. const randomRemoteListLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17695. const randomRemoteListUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-list');
  17696. if (!randomRemoteListUrl) {
  17697. if (randomRemoteListLoading) {
  17698. this.hideLoadIng();
  17699. }
  17700. return;
  17701. }
  17702. this.videoUrl = randomRemoteListUrl;
  17703. this.name = this.currentSong.name;
  17704. this.artist = this.currentSong.artist;
  17705. this.changeImageAnimation();
  17706. return;
  17707. }
  17708. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  17709. }
  17710. }
  17711. if (this.currentSong) {
  17712. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  17713. this.randomPlayHistory.unshift(this.currentSong);
  17714. // 限制历史栈大小,避免无限增长
  17715. if (this.randomPlayHistory.length > 50) {
  17716. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  17717. }
  17718. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  17719. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  17720. const currentFilePath = this.currentSong.filePath;
  17721. if (isCurrentRemote) {
  17722. const remoteOptions: RandomSongQueryOptions = {
  17723. type: this.currentSong.type,
  17724. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  17725. };
  17726. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  17727. if (randomRemoteSong) {
  17728. // 验证并修正webdav_account_id
  17729. if (randomRemoteSong.webdav_account_id) {
  17730. const manager = RemoteDriveManager.getInstance();
  17731. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  17732. if (!account) {
  17733. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  17734. // 获取所有账号,查找相同类型的账号
  17735. const allAccounts = manager.getAllWebDavAccounts();
  17736. let foundAccount: WebDavAccount | null = null;
  17737. for (let i = 0; i < allAccounts.length; i++) {
  17738. if (allAccounts[i].webType === randomRemoteSong.type) {
  17739. foundAccount = allAccounts[i];
  17740. break;
  17741. }
  17742. }
  17743. if (foundAccount && foundAccount.id) {
  17744. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  17745. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  17746. // 更新数据库记录
  17747. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  17748. } else {
  17749. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  17750. return;
  17751. }
  17752. }
  17753. }
  17754. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  17755. if (nextIndex < 0) {
  17756. this.songList = [...this.songList, randomRemoteSong];
  17757. this.sonDataSource.pushArrayData(this.songList);
  17758. nextIndex = this.songList.length - 1;
  17759. }
  17760. this.curIndex = nextIndex;
  17761. this.playedIndices.add(this.curIndex);
  17762. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17763. this.stop();
  17764. this.currentSong = randomRemoteSong;
  17765. const randomRemoteDbLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17766. const randomRemoteUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-db');
  17767. if (!randomRemoteUrl) {
  17768. if (randomRemoteDbLoading) {
  17769. this.hideLoadIng();
  17770. }
  17771. return;
  17772. }
  17773. this.videoUrl = randomRemoteUrl;
  17774. this.name = this.currentSong.name;
  17775. this.artist = this.currentSong.artist;
  17776. this.changeImageAnimation();
  17777. return;
  17778. }
  17779. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  17780. } else {
  17781. if (currentFilePath) {
  17782. this.playedLocalFilePaths.add(currentFilePath);
  17783. }
  17784. // 根据modeType构建不同的查询选项
  17785. const localOptions: RandomSongQueryOptions = {
  17786. type: CommonConstants.TYPE_LOCAL,
  17787. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  17788. };
  17789. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  17790. // modeType==0: 文件夹模式,添加parentPath过滤
  17791. if (this.modeType === 0 && this.currentPath) {
  17792. localOptions.parentPath = this.currentPath;
  17793. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  17794. }
  17795. // modeType==4: 歌单模式,添加playlistSongFilePaths
  17796. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  17797. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  17798. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  17799. } else if (this.modeType === 4) {
  17800. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  17801. }
  17802. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  17803. if (!randomLocalSong) {
  17804. this.playedLocalFilePaths.clear();
  17805. if (currentFilePath) {
  17806. this.playedLocalFilePaths.add(currentFilePath);
  17807. }
  17808. const fallbackLocalOptions: RandomSongQueryOptions = {
  17809. type: CommonConstants.TYPE_LOCAL,
  17810. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  17811. };
  17812. // fallback时也要保持modeType的过滤条件
  17813. if (this.modeType === 0 && this.currentPath) {
  17814. fallbackLocalOptions.parentPath = this.currentPath;
  17815. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  17816. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  17817. }
  17818. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  17819. }
  17820. if (randomLocalSong !== null) {
  17821. const selectedLocalSong = randomLocalSong;
  17822. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  17823. if (nextIndex < 0) {
  17824. this.songList = [...this.songList, selectedLocalSong];
  17825. this.sonDataSource.pushArrayData(this.songList);
  17826. nextIndex = this.songList.length - 1;
  17827. }
  17828. this.curIndex = nextIndex;
  17829. this.playedIndices.add(this.curIndex);
  17830. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17831. this.stop();
  17832. this.currentSong = selectedLocalSong;
  17833. const randomLocalUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-local-db');
  17834. if (!randomLocalUrl) {
  17835. return;
  17836. }
  17837. this.videoUrl = randomLocalUrl;
  17838. this.name = this.currentSong.name;
  17839. this.artist = this.currentSong.artist;
  17840. this.changeImageAnimation();
  17841. return;
  17842. }
  17843. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  17844. }
  17845. }
  17846. if (ArrayUtil.isNotEmpty(this.songList)) {
  17847. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  17848. this.playedIndices.add(this.curIndex);
  17849. }
  17850. if (this.songList.length > 3) {
  17851. // 优先使用预缓存的随机索引(仅网盘播放时)
  17852. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  17853. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  17854. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  17855. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  17856. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  17857. this.curIndex = this.preloadNextRandomIndex;
  17858. this.playedIndices.add(this.curIndex);
  17859. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  17860. // 立即预缓存下一首,避免下次点击时没有预缓存
  17861. void this.preloadNextSongInternal();
  17862. } else {
  17863. // 如果没有预缓存索引,则正常随机选择
  17864. // 如果所有歌曲都播放过一次,清空已播放索引集合
  17865. if (this.playedIndices.size === this.songList.length) {
  17866. this.playedIndices.clear();
  17867. }
  17868. // 随机选择一个未播放的歌曲索引
  17869. let newIndex: number;
  17870. // 添加超时机制防止无限循环
  17871. let attempt = 0;
  17872. const maxAttempts = 100; // 根据需求调整
  17873. do {
  17874. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  17875. attempt++;
  17876. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  17877. if (attempt >= maxAttempts) {
  17878. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  17879. newIndex = Math.floor(Math.random() * this.songList.length);
  17880. }
  17881. this.curIndex = newIndex;
  17882. this.playedIndices.add(newIndex);
  17883. }
  17884. } else {
  17885. // 当歌曲数量小于或等于3时,直接播放下一首
  17886. if (this.curIndex == this.songList.length - 1) {
  17887. this.curIndex = 0;
  17888. } else {
  17889. this.curIndex++;
  17890. }
  17891. }
  17892. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17893. this.stop();
  17894. this.currentSong = this.songList[this.curIndex];
  17895. const randomFallbackLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17896. const randomFallbackUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-fallback');
  17897. if (!randomFallbackUrl) {
  17898. if (randomFallbackLoading) {
  17899. this.hideLoadIng();
  17900. }
  17901. return;
  17902. }
  17903. this.videoUrl = randomFallbackUrl;
  17904. this.name = this.songList[this.curIndex].name;
  17905. this.artist = this.songList[this.curIndex].artist
  17906. // this.cover = this.songList[this.curIndex].pixelMapPath
  17907. this.changeImageAnimation()
  17908. // 预缓存下一首(包括网盘和本地)
  17909. void this.preloadNextSongInternal();
  17910. }
  17911. }
  17912. private async playIndex(index: number) {
  17913. if (!this.debounce()) {
  17914. return;
  17915. }
  17916. if (ArrayUtil.isNotEmpty(this.songList)) {
  17917. this.curIndex = index;
  17918. this.currentSong = this.songList[index];
  17919. const playIndexLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17920. const playIndexUrl = await this.resolvePlaybackUrlForCurrentSong('playIndex');
  17921. if (!playIndexUrl) {
  17922. if (playIndexLoading) {
  17923. this.hideLoadIng();
  17924. }
  17925. return;
  17926. }
  17927. this.videoUrl = playIndexUrl;
  17928. this.name = this.currentSong.name
  17929. this.artist = this.currentSong.artist
  17930. // 如果是投播模式,需要为投播设备准备当前歌曲
  17931. if (this.castController && this.isCastPlaying) {
  17932. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  17933. this.initQueueItem();
  17934. await this.prepare();
  17935. if (playIndexLoading) {
  17936. this.hideLoadIng();
  17937. }
  17938. this.cover = this.currentSong.pixelMapPath;
  17939. return;
  17940. }
  17941. // 本地播放器模式,需要先stop
  17942. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17943. this.stop();
  17944. if (playIndexLoading) {
  17945. this.showLoadIng();
  17946. }
  17947. this.changeImageAnimation()
  17948. }
  17949. }
  17950. //上一个
  17951. private async playPrevious() {
  17952. if (!this.debounce()) {
  17953. return;
  17954. }
  17955. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  17956. this.randomModePlayFromHistory()
  17957. return;
  17958. }
  17959. if (this.curIndex == 0) {
  17960. this.curIndex = this.songList.length - 1;
  17961. } else {
  17962. this.curIndex--;
  17963. }
  17964. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17965. this.currentSong = this.songList[this.curIndex];
  17966. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17967. // 验证并修正webdav_account_id(针对远程类型歌曲)
  17968. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  17969. const manager = RemoteDriveManager.getInstance();
  17970. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  17971. if (!account) {
  17972. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  17973. // 获取所有账号,查找相同类型的账号
  17974. const allAccounts = manager.getAllWebDavAccounts();
  17975. let foundAccount: WebDavAccount | null = null;
  17976. for (let i = 0; i < allAccounts.length; i++) {
  17977. if (allAccounts[i].webType === this.currentSong.type) {
  17978. foundAccount = allAccounts[i];
  17979. break;
  17980. }
  17981. }
  17982. if (foundAccount && foundAccount.id) {
  17983. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  17984. this.currentSong.webdav_account_id = foundAccount.id.toString();
  17985. // 更新数据库记录
  17986. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  17987. } else {
  17988. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  17989. // 跳过无效账号的歌曲,继续查找上一首
  17990. if (this.curIndex == 0) {
  17991. this.curIndex = this.songList.length - 1;
  17992. } else {
  17993. this.curIndex--;
  17994. }
  17995. this.currentSong = this.songList[this.curIndex];
  17996. }
  17997. }
  17998. }
  17999. const previousLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18000. const previousUrl = await this.resolvePlaybackUrlForCurrentSong('playPrevious');
  18001. if (!previousUrl) {
  18002. if (previousLoading) {
  18003. this.hideLoadIng();
  18004. }
  18005. return;
  18006. }
  18007. this.videoUrl = previousUrl;
  18008. this.name = this.songList[this.curIndex].name
  18009. this.artist = this.songList[this.curIndex].artist
  18010. // 如果是投播模式,使用 CastController 切换上一首
  18011. if (this.castControllerWrapper) {
  18012. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  18013. try {
  18014. const prevDuration = this.getSongDurationMs(this.currentSong);
  18015. if (prevDuration > 0) {
  18016. this.duration = prevDuration;
  18017. this.durationTime = Math.floor(prevDuration / 1000);
  18018. this.durationStringTime = secondToTime(this.durationTime);
  18019. this.totalTime = this.stringForTime(prevDuration);
  18020. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  18021. }
  18022. this.updateCastProgress(0);
  18023. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  18024. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  18025. if (previousLoading) {
  18026. this.hideLoadIng();
  18027. }
  18028. } catch (error) {
  18029. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  18030. this.isCastPlaying = false;
  18031. }
  18032. this.cover = this.songList[this.curIndex].pixelMapPath;
  18033. return;
  18034. }
  18035. // 本地播放器模式,需要先stop
  18036. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18037. this.stop();
  18038. if (previousLoading) {
  18039. this.showLoadIng();
  18040. }
  18041. this.changeImageAnimation()
  18042. }
  18043. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  18044. private async randomModePlayFromHistory() {
  18045. if (this.randomPlayHistory.length >= 1) {
  18046. // 播放历史栈的第一首(刚刚播放过的)
  18047. const prevSong = this.randomPlayHistory[0];
  18048. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  18049. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  18050. this.randomPlayHistory.shift();
  18051. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  18052. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18053. this.stop();
  18054. // 验证并修正webdav_account_id(针对远程类型歌曲)
  18055. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  18056. const manager = RemoteDriveManager.getInstance();
  18057. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  18058. if (!account) {
  18059. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  18060. const allAccounts = manager.getAllWebDavAccounts();
  18061. let foundAccount: WebDavAccount | null = null;
  18062. for (let i = 0; i < allAccounts.length; i++) {
  18063. if (allAccounts[i].webType === prevSong.type) {
  18064. foundAccount = allAccounts[i];
  18065. break;
  18066. }
  18067. }
  18068. if (foundAccount && foundAccount.id) {
  18069. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  18070. prevSong.webdav_account_id = foundAccount.id.toString();
  18071. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  18072. } else {
  18073. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  18074. // 无法播放这首歌,继续尝试下一首历史记录
  18075. if (this.randomPlayHistory.length >= 1) {
  18076. this.randomModePlayFromHistory();
  18077. return;
  18078. } else {
  18079. // 历史记录为空,无法继续
  18080. ToastUtil.showToast('没有更多历史记录');
  18081. return;
  18082. }
  18083. }
  18084. }
  18085. }
  18086. this.currentSong = prevSong;
  18087. const historyLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18088. const historyUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-history');
  18089. if (!historyUrl) {
  18090. if (historyLoading) {
  18091. this.hideLoadIng();
  18092. }
  18093. return;
  18094. }
  18095. this.videoUrl = historyUrl;
  18096. this.cover = this.currentSong.pixelMapPath
  18097. this.artist = this.currentSong.artist
  18098. this.name = this.currentSong.name;
  18099. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  18100. this.startPlayOrResumePlay();
  18101. } else {
  18102. ToastUtil.showToast('随机播放模式暂无历史记录');
  18103. }
  18104. }
  18105. debounce() {
  18106. const delay = 600;
  18107. let cur = new Date().getTime();
  18108. if (cur - this.last > delay) {
  18109. this.last = cur;
  18110. return true;
  18111. }
  18112. return false;
  18113. }
  18114. /**
  18115. * Sets whether the screen is a constant based on the playback status.
  18116. */
  18117. watchStatus() {
  18118. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  18119. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  18120. this.windowClass.setWindowKeepScreenOn(true);
  18121. } else {
  18122. this.windowClass.setWindowKeepScreenOn(false);
  18123. }
  18124. }
  18125. /**
  18126. * Volume gesture method onActionStart.
  18127. *
  18128. * @param event Gesture event.
  18129. */
  18130. private customDialogComponentIdMM: number = 0
  18131. @Builder
  18132. customDialogComponentMM() {
  18133. Column() {
  18134. Row() {
  18135. Blank()
  18136. Text('验证密码')
  18137. .fontSize(22)
  18138. .fontColor($r('app.color.pri_bg'))
  18139. .margin({ top: 18 })
  18140. Blank()
  18141. Image($r('app.media.close'))
  18142. .fillColor(Color.White)
  18143. .margin({ top: 18, right: 18 })
  18144. .width(20)
  18145. .onClick(() => {
  18146. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18147. })
  18148. }
  18149. .width('100%') // 使Row占据整个宽度
  18150. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  18151. Verify({
  18152. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  18153. });
  18154. }.height('60%')
  18155. .backgroundColor($r('app.color.index_background'))
  18156. .justifyContent(FlexAlign.SpaceBetween)
  18157. }
  18158. private handleVerifyCompleted(isSuccess: boolean) {
  18159. if (isSuccess) {
  18160. console.log('验证成功');
  18161. // 在这里处理验证成功后的逻辑
  18162. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18163. this.currentPath = this.lockPath
  18164. this.getSortedFiles(this.currentPath)
  18165. } else {
  18166. // console.log('验证失败');
  18167. ToastUtil.showToast('验证失败')
  18168. }
  18169. }
  18170. private showVerifyDialog() {
  18171. promptAction.openCustomDialog({
  18172. transition: TransitionEffect.asymmetric(
  18173. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  18174. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18175. ,
  18176. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  18177. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18178. ),
  18179. builder: () => {
  18180. this.customDialogComponentMM()
  18181. },
  18182. isModal: true,
  18183. autoCancel: true,
  18184. maskColor: Color.Transparent,
  18185. alignment: DialogAlignment.Bottom,
  18186. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  18187. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  18188. console.log("dialog onWillDismiss")
  18189. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  18190. dismissDialogAction.dismiss()
  18191. }
  18192. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  18193. dismissDialogAction.dismiss()
  18194. }
  18195. }
  18196. }).then((dialogId: number) => {
  18197. this.customDialogComponentIdMM = dialogId
  18198. })
  18199. }
  18200. //左滑操作 移动文件 重命名 删除等操作
  18201. @Builder
  18202. DeleteButton(item: VideoItem, index: number, filePath: string) {
  18203. Row() {
  18204. //加入收藏
  18205. // Button() {
  18206. // Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  18207. // .fillColor(Color.White)
  18208. // .width(20)
  18209. // }
  18210. // .width(40)
  18211. // .height(40)
  18212. // .type(ButtonType.Circle)
  18213. // .backgroundColor(this.themeColor)
  18214. // .margin(5)
  18215. // .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18216. // .onClick(() => {
  18217. // if (item) {
  18218. // this.doFav(item)
  18219. // }
  18220. // })
  18221. //加入下一首播放
  18222. Button() {
  18223. Image($r('app.media.next_to_play'))
  18224. .fillColor(Color.White)
  18225. .width(20)
  18226. }
  18227. .width(40)
  18228. .height(40)
  18229. .type(ButtonType.Circle)
  18230. .backgroundColor(this.themeColor)
  18231. .margin(5)
  18232. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18233. .onClick(() => {
  18234. this.addToNextPlay(item);
  18235. })
  18236. //复制文件
  18237. Button() {
  18238. Image($r('app.media.copy'))
  18239. .fillColor(Color.White)
  18240. .width(20)
  18241. }
  18242. .width(40)
  18243. .height(40)
  18244. .type(ButtonType.Circle)
  18245. .backgroundColor(this.themeColor)
  18246. .margin(5)
  18247. .id(filePath + 'copy')
  18248. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18249. .onClick(() => {
  18250. this.showCopyDialog(false, item, index, filePath + 'copy');
  18251. })
  18252. //移动文件
  18253. Button() {
  18254. Image($r('app.media.cut'))
  18255. .fillColor(Color.White)
  18256. .width(20)
  18257. }
  18258. .width(40)
  18259. .height(40)
  18260. .type(ButtonType.Circle)
  18261. .backgroundColor(this.themeColor)
  18262. .margin(5)
  18263. .id(filePath)
  18264. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18265. .onClick(() => {
  18266. this.showCutDialog(false, item, index, filePath);
  18267. })
  18268. Button() {
  18269. Image($r('app.media.cut_current'))
  18270. .fillColor(Color.White)
  18271. .width(20)
  18272. }
  18273. .width(40)
  18274. .height(40)
  18275. .type(ButtonType.Circle)
  18276. .backgroundColor(this.themeColor)
  18277. .margin(5)
  18278. .id(filePath + 'current')
  18279. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  18280. (this.isHasDir ? Visibility.Visible : Visibility.None))
  18281. .onClick(() => {
  18282. this.showCutDialog(true, item, index, filePath + 'current');
  18283. })
  18284. //重命名
  18285. // Button() {
  18286. // Image($r('app.media.rename2'))
  18287. // .fillColor(Color.White)
  18288. // .width(20)
  18289. // }
  18290. // .width(40)
  18291. // .height(40)
  18292. // .type(ButtonType.Circle)
  18293. // .backgroundColor(this.themeColor)
  18294. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18295. // (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18296. // item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18297. // .margin(5)
  18298. // .onClick(() => {
  18299. // this.showReNameDialog(item, index + '', filePath)
  18300. //
  18301. // })
  18302. Button() {
  18303. Image($r('app.media.delete2'))
  18304. .fillColor(Color.White)
  18305. .width(20)
  18306. }
  18307. .width(40)
  18308. .height(40)
  18309. .type(ButtonType.Circle)
  18310. .backgroundColor(this.themeColor)
  18311. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18312. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18313. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18314. .margin({ left:5,top:5,bottom:5,right:20} )
  18315. .onClick(() => {
  18316. this.selectSingleItemForDelete(item)
  18317. this.showWarnIsDelete()
  18318. // this.showWarnIsDeleteFile(item, index + '', filePath)
  18319. })
  18320. // Button() {
  18321. // Image($r('app.media.share2'))
  18322. // .fillColor(Color.White)
  18323. // .width(20)
  18324. // }
  18325. // .width(40)
  18326. // .height(40)
  18327. // .type(ButtonType.Circle)
  18328. // .backgroundColor(this.themeColor)
  18329. // .margin(5)
  18330. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18331. // .onClick(() => {
  18332. // Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  18333. // })
  18334. }
  18335. }
  18336. /**
  18337. * 穿山甲banner广告
  18338. */
  18339. // private declare bannerAd: CSJNativeExpressAd;
  18340. // @State private status: string = "未加载"
  18341. // @State private isShowAd: boolean = false
  18342. // private declare mAdSlot: AdSlot;
  18343. // private mBiddingAdm = '' //服务端bidding才需要设置
  18344. // private expressLoadAdListener: NativeExpressAdListener = {
  18345. // /**
  18346. // * 加载失败的回调
  18347. // *
  18348. // * @param code
  18349. // * @param message
  18350. // */
  18351. // onError: (code: number, message: string) => {
  18352. // console.error("加载广告失败,code=" + code + ",message=" + message);
  18353. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  18354. // },
  18355. //
  18356. // /**
  18357. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  18358. // *
  18359. // * @param ads 返回的广告列表
  18360. // */
  18361. //
  18362. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  18363. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  18364. // if (ads && ads.length > 0) {
  18365. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  18366. // ad.setExpressInteractionListener({
  18367. // /**
  18368. // *广告的点击回调
  18369. // * @param type 广告的交互类型
  18370. // */
  18371. // onAdClicked: (type: number) => {
  18372. // console.log("BannerExpressAdPage==onAdClicked......");
  18373. // },
  18374. //
  18375. // /**
  18376. // * 广告的展示回调 每个广告仅回调一次
  18377. // * @param type 广告的交互类型
  18378. // */
  18379. // onAdShow: (type: number) => {
  18380. // console.log("BannerExpressAdPage==onAdShow......");
  18381. // },
  18382. //
  18383. // /**
  18384. // * 模板渲染失败
  18385. // */
  18386. // onRenderFail: (code: number, msg: string) => {
  18387. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  18388. // },
  18389. //
  18390. // /**
  18391. // * 模板渲染成功
  18392. // * @param width 返回view的宽 单位 vp
  18393. // * @param height 返回view的高 单位 vp
  18394. // */
  18395. // onRenderSuccess: (width: number, height: number) => {
  18396. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  18397. // this.bannerAd = ad;
  18398. // this.status = "广告加载完成待展示";
  18399. //
  18400. // this.showBannerAd()
  18401. // }
  18402. // })
  18403. // //渲染广告
  18404. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  18405. // this.setDislikeCallback(ad); //设置dislike
  18406. // ad.render(this.getUIContext())
  18407. // this.status = "广告加载中...";
  18408. // });
  18409. // }
  18410. // }
  18411. // }
  18412. //
  18413. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  18414. // ad.setDislikeCallback({
  18415. // /**
  18416. // * dislike show
  18417. // */
  18418. // onShow: () => {
  18419. // console.log("BannerExpressAdPage==dislike......show");
  18420. // },
  18421. //
  18422. // /**
  18423. // * @param position 选择的位置
  18424. // * @param value 选择的内容
  18425. // * @param enforceRemove 是否强制关闭广告
  18426. // */
  18427. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  18428. // this.isShowAd = false;
  18429. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  18430. // ",enforce=" + enforceRemove);
  18431. // },
  18432. //
  18433. // /**
  18434. // * 点击取消
  18435. // */
  18436. // onCancel: () => {
  18437. // console.log("BannerExpressAdPage==dislike......onCancel");
  18438. // }
  18439. //
  18440. // })
  18441. // }
  18442. /**
  18443. * 加载Banner广告
  18444. */
  18445. loadBannerAd(rit: string) {
  18446. // if (Utility.isNoble()) {
  18447. // return
  18448. // }
  18449. // if (!Utility.isPassInstallTime(2)) {
  18450. // return
  18451. // }
  18452. // this.isShowAd = false;
  18453. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  18454. // this.mAdSlot = new AdSlotBuilder()
  18455. // .setCodeId(rit)
  18456. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  18457. // .setAdCount(1)
  18458. // .setBidAdm(this.mBiddingAdm)
  18459. // .build()
  18460. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  18461. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  18462. // this.status = "广告加载中..."
  18463. }
  18464. /**
  18465. * 展示Banner广告
  18466. */
  18467. // showBannerAd() {
  18468. // if (!this.bannerAd) {
  18469. // return
  18470. // }
  18471. // this.isShowAd = true
  18472. // this.status = "已展示"
  18473. // }
  18474. /**
  18475. * 穿山甲广告代码结束
  18476. */
  18477. /**
  18478. * 处理歌单播放请求
  18479. */
  18480. private syncWebdavQueueWithoutRestart(): void {
  18481. try {
  18482. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  18483. return;
  18484. }
  18485. const webdavList = getWebdavVideoItems();
  18486. if (!ArrayUtil.isNotEmpty(webdavList)) {
  18487. return;
  18488. }
  18489. const currentPath = this.currentSong.filePath;
  18490. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  18491. if (targetIndex < 0) {
  18492. const memoryIndex = getWebdavCurrentPlayIndex();
  18493. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  18494. targetIndex = memoryIndex;
  18495. }
  18496. }
  18497. if (targetIndex < 0) {
  18498. targetIndex = 0;
  18499. }
  18500. this.songList = [...webdavList];
  18501. this.currentSongList = [...webdavList];
  18502. this.sonDataSource.pushArrayData(this.songList);
  18503. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  18504. this.curIndex = targetIndex;
  18505. PreferencesUtil.putSync('LastMusicList', this.songList);
  18506. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  18507. } catch (error) {
  18508. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  18509. }
  18510. }
  18511. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  18512. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  18513. try {
  18514. const totalCount = songCount ?? songFilePaths.length;
  18515. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  18516. // 检查是否为WebDAV播放请求
  18517. if (playlistId === 'webdav-playlist') {
  18518. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  18519. // 从全局内存读取videoItems数据
  18520. const videoItems = getWebdavVideoItems();
  18521. const currentPlayIndex = getWebdavCurrentPlayIndex();
  18522. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  18523. if (videoItems && videoItems.length > 0) {
  18524. // 验证webdav_account_id设置情况
  18525. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  18526. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  18527. if(isJump){
  18528. this.setShowPlayTrue()//显示播放页
  18529. }
  18530. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18531. return
  18532. } else {
  18533. return
  18534. }
  18535. }
  18536. if (playlistId === 'navidrome-playlist') {
  18537. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  18538. const videoItems = getNavidromeVideoItems();
  18539. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  18540. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  18541. if (videoItems && videoItems.length > 0) {
  18542. if(isJump){
  18543. this.setShowPlayTrue()//显示播放页
  18544. }
  18545. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  18546. return;
  18547. } else {
  18548. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  18549. return;
  18550. }
  18551. }
  18552. if (playlistId === 'find-album-playlist' || playlistId.indexOf('find-') === 0) {
  18553. Logger.info(`heanup 检测到发现页播放请求,从内存读取videoItems`)
  18554. const videoItems = getFindVideoItems();
  18555. const currentPlayIndex = getFindCurrentPlayIndex();
  18556. Logger.info(`heanup 发现页歌曲列表长度: ${videoItems.length}, 索引: ${currentPlayIndex}`)
  18557. if (videoItems && videoItems.length > 0) {
  18558. if (isJump) {
  18559. this.setShowPlayTrue()
  18560. }
  18561. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18562. return
  18563. } else {
  18564. Logger.warn('heanup 发现页播放请求缺少歌曲数据')
  18565. return
  18566. }
  18567. }
  18568. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  18569. const songMap: Map<number, VideoItem> = new Map()
  18570. let completedQueries = 0
  18571. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  18572. // 遍历所有文件路径,使用索引记录位置
  18573. for (let i = 0; i < songFilePaths.length; i++) {
  18574. const filePath = songFilePaths[i]
  18575. const index = i
  18576. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  18577. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  18578. const queryPromise = this.table.queryVideoByFilePath(filePath)
  18579. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  18580. queryPromise.then((videoItem) => {
  18581. completedQueries++
  18582. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  18583. if (videoItem) {
  18584. // 使用索引作为key保存到Map中,保持原始顺序
  18585. songMap.set(index, videoItem)
  18586. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  18587. } else {
  18588. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  18589. }
  18590. // 检查是否所有歌曲都已加载完成
  18591. if (completedQueries === songFilePaths.length) {
  18592. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  18593. // 按照索引顺序重建歌曲数组
  18594. const songs: VideoItem[] = []
  18595. for (let j = 0; j < songFilePaths.length; j++) {
  18596. const song = songMap.get(j)
  18597. if (song) {
  18598. songs.push(song)
  18599. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  18600. }
  18601. }
  18602. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  18603. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18604. }
  18605. }).catch((error: Error) => {
  18606. completedQueries++
  18607. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  18608. // 即使出错也要检查是否完成所有查询
  18609. if (completedQueries === songFilePaths.length) {
  18610. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  18611. // 按照索引顺序重建歌曲数组
  18612. const songs: VideoItem[] = []
  18613. for (let j = 0; j < songFilePaths.length; j++) {
  18614. const song = songMap.get(j)
  18615. if (song) {
  18616. songs.push(song)
  18617. }
  18618. }
  18619. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18620. }
  18621. })
  18622. }
  18623. } catch (error) {
  18624. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  18625. ToastUtil.showToast('播放失败')
  18626. }
  18627. }
  18628. /**
  18629. * 完成歌单加载并开始播放
  18630. */
  18631. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number) {
  18632. if (songs.length === 0) {
  18633. Logger.error('heanup 没有找到任何可播放的歌曲')
  18634. ToastUtil.showToast('没有找到可播放的歌曲')
  18635. return
  18636. }
  18637. this.songList = songs
  18638. this.currentSongList = songs // 同步更新 currentSongList
  18639. this.sonDataSource.pushArrayData(songs)
  18640. this.sonDataSource.notifyDataReload()
  18641. this.curIndex = startIndex
  18642. // 保存歌单的歌曲路径列表,用于随机播放
  18643. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  18644. const actualTotal = totalCount ?? songs.length;
  18645. // 如果是网盘播放,保存服务端总数到全局存储
  18646. if (totalCount && totalCount > 0 && songs.length > 0) {
  18647. const firstSong = songs[0];
  18648. if (firstSong && (isNavidromeType(firstSong.type) ||
  18649. isJellyfinType(firstSong.type) ||
  18650. isEmbyType(firstSong.type) ||
  18651. isAudioStationType(firstSong.type) ||
  18652. isPlexType(firstSong.type) ||
  18653. isDaoLiYuType(firstSong.type))) {
  18654. setNavidromeTotalCount(totalCount);
  18655. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  18656. }
  18657. }
  18658. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  18659. if (songs[startIndex]) {
  18660. // 确保当前播放的歌曲也更新到存储
  18661. AppStorage.setOrCreate('currentSong', songs[startIndex])
  18662. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  18663. this.doPlay(songs[startIndex], startIndex, true)
  18664. }
  18665. PreferencesUtil.putSync('LastMusicList', this.songList)
  18666. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  18667. }
  18668. }
  18669. //视频气泡窗口的布局
  18670. @Builder
  18671. function customPopupBuilder(dataBu: BubbleBean) {
  18672. List() {
  18673. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  18674. ListItem() {
  18675. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  18676. Row() {
  18677. Column() {
  18678. Image(dataBu.imageRes[index])
  18679. .height(28)
  18680. .fillColor(dataBu.color)
  18681. .alignSelf(ItemAlign.Center)
  18682. }
  18683. .width(32)
  18684. Text(item)
  18685. .padding({
  18686. top: 10,
  18687. bottom: 10,
  18688. right: 10,
  18689. left: 10
  18690. })
  18691. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  18692. .textAlign(TextAlign.Start)
  18693. .width("100%")
  18694. }
  18695. }
  18696. .backgroundColor($r('app.color.settings_background_main'))
  18697. .margin({ top: 6, bottom: 6 })
  18698. }
  18699. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  18700. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  18701. TransitionEffect.scale({ x: 0, y: 0 })))
  18702. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  18703. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  18704. .onClick(() => {
  18705. dataBu.onItemClick?.(index)
  18706. })
  18707. })
  18708. }
  18709. .scrollBar(BarState.Off)
  18710. .width(120)
  18711. .divider({
  18712. strokeWidth: 1,
  18713. color: "#22FFFFFF"
  18714. })
  18715. }
  18716. // Function to calculate a hash for the file list
  18717. function simpleHash(fileList: string[]): string {
  18718. let hash = 0;
  18719. const str = fileList.join(',');
  18720. for (let i = 0; i < str.length; i++) {
  18721. const char = str.charCodeAt(i);
  18722. hash = (hash << 5) - hash + char;
  18723. hash |= 0; // Convert to 32bit integer
  18724. }
  18725. return hash.toString();
  18726. }
  18727. interface MoreItem {
  18728. id: number;
  18729. image: Resource;
  18730. title: string;
  18731. }
  18732. //视频气泡窗口的布局
  18733. @Builder
  18734. function cutPopupBuilder(dataBu: BubbleBean) {
  18735. Column() {
  18736. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  18737. .padding({
  18738. top: 10,
  18739. bottom: 10,
  18740. right: 10,
  18741. left: 10
  18742. })
  18743. .textAlign(TextAlign.Start)
  18744. .width(160)
  18745. .fontWeight(666)
  18746. .fontSize(16)
  18747. List() {
  18748. ForEach(dataBu.data, (item: string, index: number) => {
  18749. ListItem() {
  18750. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  18751. Row() {
  18752. Column() {
  18753. Image($r('app.media.music_group'))
  18754. .height(28)
  18755. .fillColor(dataBu.color)
  18756. .alignSelf(ItemAlign.Center)
  18757. }
  18758. .width(32)
  18759. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  18760. .padding({
  18761. top: 10,
  18762. bottom: 10,
  18763. right: 10,
  18764. left: 10
  18765. })
  18766. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  18767. .fontSize(15)
  18768. }
  18769. }
  18770. .backgroundColor(Color.Transparent)
  18771. .margin({ top: 7, bottom: 7 })
  18772. }
  18773. .onClick(() => {
  18774. dataBu.onItemClick?.(index)
  18775. })
  18776. })
  18777. }
  18778. .scrollBar(BarState.Off)
  18779. .width(150)
  18780. .divider({
  18781. strokeWidth: 1,
  18782. color: "#22FFFFFF"
  18783. })
  18784. }
  18785. .height(300)
  18786. .padding({
  18787. bottom: 30
  18788. })
  18789. }
  18790. @Concurrent
  18791. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  18792. const alphabetSet = new Set<string>()
  18793. for (const item of items) {
  18794. let text = isShowFileName ? (item.fileName || '') :
  18795. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  18796. if (sortType === 0 || sortType == 1) {
  18797. text = item.artist || ''
  18798. } else if (sortType === 2 || sortType == 3) {
  18799. text = item.album || ''
  18800. }
  18801. if (text && text.length > 0) {
  18802. const first = getFirstLetter(text)
  18803. if (!alphabetSet.has(first)) {
  18804. alphabetSet.add(first)
  18805. }
  18806. }
  18807. }
  18808. const sorted = Array.from(alphabetSet).sort((a, b) => {
  18809. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  18810. return a.localeCompare(b)
  18811. }
  18812. return b.localeCompare(a)
  18813. })
  18814. return sorted
  18815. }
  18816. function getFileDirName(filePath: string,rootPath:string): string{
  18817. if(filePath===rootPath){
  18818. return '首页'
  18819. }
  18820. let result = FileUtil.getFileName(filePath)
  18821. if(StrUtil.isEmpty(result))
  18822. return ''
  18823. if(result.startsWith('.'))
  18824. result = result.replace(/\./g, '')
  18825. return result
  18826. }
  18827. //只扫描当前目录下文件(不扫描子文件夹)的方法
  18828. @Concurrent
  18829. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  18830. const table: MediaTable = new MediaTable(context);
  18831. try {
  18832. // 直接获取当前目录下的文件列表
  18833. const files = FileUtil.listFileSync(dirPath);
  18834. await Promise.all(files.map(async (file) => {
  18835. const fPath = `${dirPath}/${file}`;
  18836. // 跳过目录,只处理文件
  18837. if (FileUtil.isDirectory(fPath)) {
  18838. return;
  18839. }
  18840. // 跳过特定格式文件
  18841. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  18842. return;
  18843. }
  18844. // 检查是否为媒体文件
  18845. if (Utility.isMeidaByExtension(fPath)) {
  18846. let mType = CommonConstants.TYPE_LOCAL;
  18847. if (fPath.includes(lockPath)) {
  18848. mType = CommonConstants.TYPE_LOCK;
  18849. }
  18850. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  18851. context, fPath, mType, true
  18852. );
  18853. table.insert(mediaItem, (id: number) => {
  18854. // 插入回调函数
  18855. }, cover_api);
  18856. }
  18857. }));
  18858. } catch (error) {
  18859. console.error(' 扫描当前目录失败:', error);
  18860. }
  18861. }
  18862. //内嵌标签后更新库
  18863. @Concurrent
  18864. async function updateInfoDb(
  18865. context: Context,
  18866. filePath: string,
  18867. titleStr: string,
  18868. artistStr: string,
  18869. albumStr: string,
  18870. lyricConStr: string,
  18871. yearStr: string,
  18872. genreStr: string,
  18873. trackStr: string,
  18874. albumArtistStr: string,
  18875. composerStr: string,
  18876. lyricistStr: string,
  18877. commentStr: string,
  18878. discStr: string,
  18879. ): Promise<boolean> {
  18880. const table: MediaTable = new MediaTable(context);
  18881. await new Promise<void>((resolve, reject) => {
  18882. table.getRdbStore(context, (err:Error) => {
  18883. err ? reject(err) : resolve();
  18884. });
  18885. });
  18886. return await new Promise<boolean>((resolve) => {
  18887. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  18888. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  18889. (success: boolean, error?: string) => {
  18890. if (success) {
  18891. console.log("onecold 编辑信息成功,数据库已同步");
  18892. } else {
  18893. console.error("onecold 编辑信息数据库失败原因: " + error);
  18894. }
  18895. resolve(success);
  18896. });
  18897. });
  18898. }
  18899. @Concurrent
  18900. async function replaceLocalMusicCoverTask(
  18901. context: Context,
  18902. filePath: string,
  18903. sandboxCoverPath: string
  18904. ): Promise<boolean> {
  18905. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  18906. if (!coverResult) {
  18907. return false;
  18908. }
  18909. const table: MediaTable = new MediaTable(context);
  18910. await new Promise<void>((resolve, reject) => {
  18911. table.getRdbStore(context, (err: Error) => {
  18912. err ? reject(err) : resolve();
  18913. });
  18914. });
  18915. return await new Promise<boolean>((resolve) => {
  18916. table.updateCustomCoverPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  18917. (success: boolean, _error?: string) => {
  18918. resolve(success);
  18919. });
  18920. });
  18921. }